-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
abstract-provider.ts
1761 lines (1480 loc) · 59.2 KB
/
abstract-provider.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The available providers should suffice for most developers purposes,
* but the [[AbstractProvider]] class has many features which enable
* sub-classing it for specific purposes.
*
* @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider]
*/
// @TODO
// Event coalescence
// When we register an event with an async value (e.g. address is a Signer
// or ENS name), we need to add it immeidately for the Event API, but also
// need time to resolve the address. Upon resolving the address, we need to
// migrate the listener to the static event. We also need to maintain a map
// of Signer/ENS name to address so we can sync respond to listenerCount.
import { getAddress, resolveAddress } from "../address/index.js";
import { ZeroAddress } from "../constants/index.js";
import { Contract } from "../contract/index.js";
import { namehash } from "../hash/index.js";
import { Transaction } from "../transaction/index.js";
import {
concat, dataLength, dataSlice, hexlify, isHexString,
getBigInt, getBytes, getNumber,
isCallException, isError, makeError, assert, assertArgument,
FetchRequest,
toBeArray, toQuantity,
defineProperties, EventPayload, resolveProperties,
toUtf8String
} from "../utils/index.js";
import { EnsResolver } from "./ens-resolver.js";
import {
formatBlock, formatLog, formatTransactionReceipt, formatTransactionResponse
} from "./format.js";
import { Network } from "./network.js";
import { copyRequest, Block, FeeData, Log, TransactionReceipt, TransactionResponse } from "./provider.js";
import {
PollingBlockSubscriber, PollingBlockTagSubscriber, PollingEventSubscriber,
PollingOrphanSubscriber, PollingTransactionSubscriber
} from "./subscriber-polling.js";
import type { Addressable, AddressLike } from "../address/index.js";
import type { BigNumberish, BytesLike } from "../utils/index.js";
import type { FetchResponse, Listener } from "../utils/index.js";
import type { Networkish } from "./network.js";
import type { FetchUrlFeeDataNetworkPlugin } from "./plugins-network.js";
//import type { MaxPriorityFeePlugin } from "./plugins-network.js";
import type {
BlockParams, LogParams, TransactionReceiptParams,
TransactionResponseParams
} from "./formatting.js";
import type {
BlockTag, EventFilter, Filter, FilterByBlockHash, OrphanFilter,
PreparedTransactionRequest, Provider, ProviderEvent,
TransactionRequest
} from "./provider.js";
type Timer = ReturnType<typeof setTimeout>;
// Constants
const BN_2 = BigInt(2);
const MAX_CCIP_REDIRECTS = 10;
function isPromise<T = any>(value: any): value is Promise<T> {
return (value && typeof(value.then) === "function");
}
function getTag(prefix: string, value: any): string {
return prefix + ":" + JSON.stringify(value, (k, v) => {
if (v == null) { return "null"; }
if (typeof(v) === "bigint") { return `bigint:${ v.toString() }`}
if (typeof(v) === "string") { return v.toLowerCase(); }
// Sort object keys
if (typeof(v) === "object" && !Array.isArray(v)) {
const keys = Object.keys(v);
keys.sort();
return keys.reduce((accum, key) => {
accum[key] = v[key];
return accum;
}, <any>{ });
}
return v;
});
}
/**
* The types of additional event values that can be emitted for the
* ``"debug"`` event.
*/
export type DebugEventAbstractProvider = {
action: "sendCcipReadFetchRequest",
request: FetchRequest
index: number
urls: Array<string>
} | {
action: "receiveCcipReadFetchResult",
request: FetchRequest,
result: any
} | {
action: "receiveCcipReadFetchError",
request: FetchRequest,
result: any
} | {
action: "sendCcipReadCall",
transaction: { to: string, data: string }
} | {
action: "receiveCcipReadCallResult",
transaction: { to: string, data: string }
result: string
} | {
action: "receiveCcipReadCallError",
transaction: { to: string, data: string }
error: Error
};
/**
* The value passed to the [[AbstractProvider-_getSubscriber]] method.
*
* Only developers sub-classing [[AbstractProvider[[ will care about this,
* if they are modifying a low-level feature of how subscriptions operate.
*/
export type Subscription = {
type: "block" | "close" | "debug" | "error" | "finalized" | "network" | "pending" | "safe",
tag: string
} | {
type: "transaction",
tag: string,
hash: string
} | {
type: "event",
tag: string,
filter: EventFilter
} | {
type: "orphan",
tag: string,
filter: OrphanFilter
};
/**
* A **Subscriber** manages a subscription.
*
* Only developers sub-classing [[AbstractProvider[[ will care about this,
* if they are modifying a low-level feature of how subscriptions operate.
*/
export interface Subscriber {
/**
* Called initially when a subscriber is added the first time.
*/
start(): void;
/**
* Called when there are no more subscribers to the event.
*/
stop(): void;
/**
* Called when the subscription should pause.
*
* If %%dropWhilePaused%%, events that occur while paused should not
* be emitted [[resume]].
*/
pause(dropWhilePaused?: boolean): void;
/**
* Resume a paused subscriber.
*/
resume(): void;
/**
* The frequency (in ms) to poll for events, if polling is used by
* the subscriber.
*
* For non-polling subscribers, this must return ``undefined``.
*/
pollingInterval?: number;
}
/**
* An **UnmanagedSubscriber** is useful for events which do not require
* any additional management, such as ``"debug"`` which only requires
* emit in synchronous event loop triggered calls.
*/
export class UnmanagedSubscriber implements Subscriber {
/**
* The name fof the event.
*/
name!: string;
/**
* Create a new UnmanagedSubscriber with %%name%%.
*/
constructor(name: string) { defineProperties<UnmanagedSubscriber>(this, { name }); }
start(): void { }
stop(): void { }
pause(dropWhilePaused?: boolean): void { }
resume(): void { }
}
type Sub = {
tag: string;
nameMap: Map<string, string>
addressableMap: WeakMap<Addressable, string>;
listeners: Array<{ listener: Listener, once: boolean }>;
// @TODO: get rid of this, as it is (and has to be)
// tracked in subscriber
started: boolean;
subscriber: Subscriber;
};
function copy<T = any>(value: T): T {
return JSON.parse(JSON.stringify(value));
}
function concisify(items: Array<string>): Array<string> {
items = Array.from((new Set(items)).values())
items.sort();
return items;
}
async function getSubscription(_event: ProviderEvent, provider: AbstractProvider): Promise<Subscription> {
if (_event == null) { throw new Error("invalid event"); }
// Normalize topic array info an EventFilter
if (Array.isArray(_event)) { _event = { topics: _event }; }
if (typeof(_event) === "string") {
switch (_event) {
case "block":
case "debug":
case "error":
case "finalized":
case "network":
case "pending":
case "safe": {
return { type: _event, tag: _event };
}
}
}
if (isHexString(_event, 32)) {
const hash = _event.toLowerCase();
return { type: "transaction", tag: getTag("tx", { hash }), hash };
}
if ((<any>_event).orphan) {
const event = <OrphanFilter>_event;
// @TODO: Should lowercase and whatnot things here instead of copy...
return { type: "orphan", tag: getTag("orphan", event), filter: copy(event) };
}
if (((<any>_event).address || (<any>_event).topics)) {
const event = <EventFilter>_event;
const filter: any = {
topics: ((event.topics || []).map((t) => {
if (t == null) { return null; }
if (Array.isArray(t)) {
return concisify(t.map((t) => t.toLowerCase()));
}
return t.toLowerCase();
}))
};
if (event.address) {
const addresses: Array<string> = [ ];
const promises: Array<Promise<void>> = [ ];
const addAddress = (addr: AddressLike) => {
if (isHexString(addr)) {
addresses.push(addr);
} else {
promises.push((async () => {
addresses.push(await resolveAddress(addr, provider));
})());
}
}
if (Array.isArray(event.address)) {
event.address.forEach(addAddress);
} else {
addAddress(event.address);
}
if (promises.length) { await Promise.all(promises); }
filter.address = concisify(addresses.map((a) => a.toLowerCase()));
}
return { filter, tag: getTag("event", filter), type: "event" };
}
assertArgument(false, "unknown ProviderEvent", "event", _event);
}
function getTime(): number { return (new Date()).getTime(); }
/**
* An **AbstractPlugin** is used to provide additional internal services
* to an [[AbstractProvider]] without adding backwards-incompatible changes
* to method signatures or other internal and complex logic.
*/
export interface AbstractProviderPlugin {
/**
* The reverse domain notation of the plugin.
*/
readonly name: string;
/**
* Creates a new instance of the plugin, connected to %%provider%%.
*/
connect(provider: AbstractProvider): AbstractProviderPlugin;
}
/**
* A normalized filter used for [[PerformActionRequest]] objects.
*/
export type PerformActionFilter = {
address?: string | Array<string>;
topics?: Array<null | string | Array<string>>;
fromBlock?: BlockTag;
toBlock?: BlockTag;
} | {
address?: string | Array<string>;
topics?: Array<null | string | Array<string>>;
blockHash?: string;
};
/**
* A normalized transactions used for [[PerformActionRequest]] objects.
*/
export interface PerformActionTransaction extends PreparedTransactionRequest {
/**
* The ``to`` address of the transaction.
*/
to?: string;
/**
* The sender of the transaction.
*/
from?: string;
}
/**
* The [[AbstractProvider]] methods will normalize all values and pass this
* type to [[AbstractProvider-_perform]].
*/
export type PerformActionRequest = {
method: "broadcastTransaction",
signedTransaction: string
} | {
method: "call",
transaction: PerformActionTransaction, blockTag: BlockTag
} | {
method: "chainId"
} | {
method: "estimateGas",
transaction: PerformActionTransaction
} | {
method: "getBalance",
address: string, blockTag: BlockTag
} | {
method: "getBlock",
blockTag: BlockTag, includeTransactions: boolean
} | {
method: "getBlock",
blockHash: string, includeTransactions: boolean
} | {
method: "getBlockNumber"
} | {
method: "getCode",
address: string, blockTag: BlockTag
} | {
method: "getGasPrice"
} | {
method: "getLogs",
filter: PerformActionFilter
} | {
method: "getPriorityFee"
} | {
method: "getStorage",
address: string, position: bigint, blockTag: BlockTag
} | {
method: "getTransaction",
hash: string
} | {
method: "getTransactionCount",
address: string, blockTag: BlockTag
} | {
method: "getTransactionReceipt",
hash: string
} | {
method: "getTransactionResult",
hash: string
};
type _PerformAccountRequest = {
method: "getBalance" | "getTransactionCount" | "getCode"
} | {
method: "getStorage", position: bigint
}
/**
* Options for configuring some internal aspects of an [[AbstractProvider]].
*
* **``cacheTimeout``** - how long to cache a low-level ``_perform``
* for, based on input parameters. This reduces the number of calls
* to getChainId and getBlockNumber, but may break test chains which
* can perform operations (internally) synchronously. Use ``-1`` to
* disable, ``0`` will only buffer within the same event loop and
* any other value is in ms. (default: ``250``)
*/
export type AbstractProviderOptions = {
cacheTimeout?: number;
pollingInterval?: number;
};
const defaultOptions = {
cacheTimeout: 250,
pollingInterval: 4000
};
type CcipArgs = {
sender: string;
urls: Array<string>;
calldata: string;
selector: string;
extraData: string;
errorArgs: Array<any>
};
/**
* An **AbstractProvider** provides a base class for other sub-classes to
* implement the [[Provider]] API by normalizing input arguments and
* formatting output results as well as tracking events for consistent
* behaviour on an eventually-consistent network.
*/
export class AbstractProvider implements Provider {
#subs: Map<string, Sub>;
#plugins: Map<string, AbstractProviderPlugin>;
// null=unpaused, true=paused+dropWhilePaused, false=paused
#pausedState: null | boolean;
#destroyed: boolean;
#networkPromise: null | Promise<Network>;
readonly #anyNetwork: boolean;
#performCache: Map<string, Promise<any>>;
// The most recent block number if running an event or -1 if no "block" event
#lastBlockNumber: number;
#nextTimer: number;
#timers: Map<number, { timer: null | Timer, func: () => void, time: number }>;
#disableCcipRead: boolean;
#options: Required<AbstractProviderOptions>;
/**
* Create a new **AbstractProvider** connected to %%network%%, or
* use the various network detection capabilities to discover the
* [[Network]] if necessary.
*/
constructor(_network?: "any" | Networkish, options?: AbstractProviderOptions) {
this.#options = Object.assign({ }, defaultOptions, options || { });
if (_network === "any") {
this.#anyNetwork = true;
this.#networkPromise = null;
} else if (_network) {
const network = Network.from(_network);
this.#anyNetwork = false;
this.#networkPromise = Promise.resolve(network);
setTimeout(() => { this.emit("network", network, null); }, 0);
} else {
this.#anyNetwork = false;
this.#networkPromise = null;
}
this.#lastBlockNumber = -1;
this.#performCache = new Map();
this.#subs = new Map();
this.#plugins = new Map();
this.#pausedState = null;
this.#destroyed = false;
this.#nextTimer = 1;
this.#timers = new Map();
this.#disableCcipRead = false;
}
get pollingInterval(): number { return this.#options.pollingInterval; }
/**
* Returns ``this``, to allow an **AbstractProvider** to implement
* the [[ContractRunner]] interface.
*/
get provider(): this { return this; }
/**
* Returns all the registered plug-ins.
*/
get plugins(): Array<AbstractProviderPlugin> {
return Array.from(this.#plugins.values());
}
/**
* Attach a new plug-in.
*/
attachPlugin(plugin: AbstractProviderPlugin): this {
if (this.#plugins.get(plugin.name)) {
throw new Error(`cannot replace existing plugin: ${ plugin.name } `);
}
this.#plugins.set(plugin.name, plugin.connect(this));
return this;
}
/**
* Get a plugin by name.
*/
getPlugin<T extends AbstractProviderPlugin = AbstractProviderPlugin>(name: string): null | T {
return <T>(this.#plugins.get(name)) || null;
}
/**
* Prevent any CCIP-read operation, regardless of whether requested
* in a [[call]] using ``enableCcipRead``.
*/
get disableCcipRead(): boolean { return this.#disableCcipRead; }
set disableCcipRead(value: boolean) { this.#disableCcipRead = !!value; }
// Shares multiple identical requests made during the same 250ms
async #perform<T = any>(req: PerformActionRequest): Promise<T> {
const timeout = this.#options.cacheTimeout;
// Caching disabled
if (timeout < 0) { return await this._perform(req); }
// Create a tag
const tag = getTag(req.method, req);
let perform = this.#performCache.get(tag);
if (!perform) {
perform = this._perform(req);
this.#performCache.set(tag, perform);
setTimeout(() => {
if (this.#performCache.get(tag) === perform) {
this.#performCache.delete(tag);
}
}, timeout);
}
return await perform;
}
/**
* Resolves to the data for executing the CCIP-read operations.
*/
async ccipReadFetch(tx: PerformActionTransaction, calldata: string, urls: Array<string>): Promise<null | string> {
if (this.disableCcipRead || urls.length === 0 || tx.to == null) { return null; }
const sender = tx.to.toLowerCase();
const data = calldata.toLowerCase();
const errorMessages: Array<string> = [ ];
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
// URL expansion
const href = url.replace("{sender}", sender).replace("{data}", data);
// If no {data} is present, use POST; otherwise GET
//const json: string | null = (url.indexOf("{data}") >= 0) ? null: JSON.stringify({ data, sender });
//const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => {
// value.status = response.statusCode;
// return value;
//});
const request = new FetchRequest(href);
if (url.indexOf("{data}") === -1) {
request.body = { data, sender };
}
this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls });
let errorMessage = "unknown error";
// Fetch the resource...
let resp: FetchResponse;
try {
resp = await request.send();
} catch (error: any) {
// ...low-level fetch error (missing host, bad SSL, etc.),
// so try next URL
errorMessages.push(error.message);
this.emit("debug", { action: "receiveCcipReadFetchError", request, result: { error } });
continue;
}
try {
const result = resp.bodyJson;
if (result.data) {
this.emit("debug", { action: "receiveCcipReadFetchResult", request, result });
return result.data;
}
if (result.message) { errorMessage = result.message; }
this.emit("debug", { action: "receiveCcipReadFetchError", request, result });
} catch (error) { }
// 4xx indicates the result is not present; stop
assert(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${ errorMessage }`,
"OFFCHAIN_FAULT", { reason: "404_MISSING_RESOURCE", transaction: tx, info: { url, errorMessage } });
// 5xx indicates server issue; try the next url
errorMessages.push(errorMessage);
}
assert(false, `error encountered during CCIP fetch: ${ errorMessages.map((m) => JSON.stringify(m)).join(", ") }`, "OFFCHAIN_FAULT", {
reason: "500_SERVER_ERROR",
transaction: tx, info: { urls, errorMessages }
});
}
/**
* Provides the opportunity for a sub-class to wrap a block before
* returning it, to add additional properties or an alternate
* sub-class of [[Block]].
*/
_wrapBlock(value: BlockParams, network: Network): Block {
return new Block(formatBlock(value), this);
}
/**
* Provides the opportunity for a sub-class to wrap a log before
* returning it, to add additional properties or an alternate
* sub-class of [[Log]].
*/
_wrapLog(value: LogParams, network: Network): Log {
return new Log(formatLog(value), this);
}
/**
* Provides the opportunity for a sub-class to wrap a transaction
* receipt before returning it, to add additional properties or an
* alternate sub-class of [[TransactionReceipt]].
*/
_wrapTransactionReceipt(value: TransactionReceiptParams, network: Network): TransactionReceipt {
return new TransactionReceipt(formatTransactionReceipt(value), this);
}
/**
* Provides the opportunity for a sub-class to wrap a transaction
* response before returning it, to add additional properties or an
* alternate sub-class of [[TransactionResponse]].
*/
_wrapTransactionResponse(tx: TransactionResponseParams, network: Network): TransactionResponse {
return new TransactionResponse(formatTransactionResponse(tx), this);
}
/**
* Resolves to the Network, forcing a network detection using whatever
* technique the sub-class requires.
*
* Sub-classes **must** override this.
*/
_detectNetwork(): Promise<Network> {
assert(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", {
operation: "_detectNetwork"
});
}
/**
* Sub-classes should use this to perform all built-in operations. All
* methods sanitizes and normalizes the values passed into this.
*
* Sub-classes **must** override this.
*/
async _perform<T = any>(req: PerformActionRequest): Promise<T> {
assert(false, `unsupported method: ${ req.method }`, "UNSUPPORTED_OPERATION", {
operation: req.method,
info: req
});
}
// State
async getBlockNumber(): Promise<number> {
const blockNumber = getNumber(await this.#perform({ method: "getBlockNumber" }), "%response");
if (this.#lastBlockNumber >= 0) { this.#lastBlockNumber = blockNumber; }
return blockNumber;
}
/**
* Returns or resolves to the address for %%address%%, resolving ENS
* names and [[Addressable]] objects and returning if already an
* address.
*/
_getAddress(address: AddressLike): string | Promise<string> {
return resolveAddress(address, this);
}
/**
* Returns or resolves to a valid block tag for %%blockTag%%, resolving
* negative values and returning if already a valid block tag.
*/
_getBlockTag(blockTag?: BlockTag): string | Promise<string> {
if (blockTag == null) { return "latest"; }
switch (blockTag) {
case "earliest":
return "0x0";
case "finalized":
case "latest":
case "pending":
case "safe":
return blockTag;
}
if (isHexString(blockTag)) {
if (isHexString(blockTag, 32)) { return blockTag; }
return toQuantity(blockTag);
}
if (typeof(blockTag) === "bigint") {
blockTag = getNumber(blockTag, "blockTag");
}
if (typeof(blockTag) === "number") {
if (blockTag >= 0) { return toQuantity(blockTag); }
if (this.#lastBlockNumber >= 0) { return toQuantity(this.#lastBlockNumber + blockTag); }
return this.getBlockNumber().then((b) => toQuantity(b + <number>blockTag));
}
assertArgument(false, "invalid blockTag", "blockTag", blockTag);
}
/**
* Returns or resolves to a filter for %%filter%%, resolving any ENS
* names or [[Addressable]] object and returning if already a valid
* filter.
*/
_getFilter(filter: Filter | FilterByBlockHash): PerformActionFilter | Promise<PerformActionFilter> {
// Create a canonical representation of the topics
const topics = (filter.topics || [ ]).map((t) => {
if (t == null) { return null; }
if (Array.isArray(t)) {
return concisify(t.map((t) => t.toLowerCase()));
}
return t.toLowerCase();
});
const blockHash = ("blockHash" in filter) ? filter.blockHash: undefined;
const resolve = (_address: Array<string>, fromBlock?: string, toBlock?: string) => {
let address: undefined | string | Array<string> = undefined;
switch (_address.length) {
case 0: break;
case 1:
address = _address[0];
break;
default:
_address.sort();
address = _address;
}
if (blockHash) {
if (fromBlock != null || toBlock != null) {
throw new Error("invalid filter");
}
}
const filter = <any>{ };
if (address) { filter.address = address; }
if (topics.length) { filter.topics = topics; }
if (fromBlock) { filter.fromBlock = fromBlock; }
if (toBlock) { filter.toBlock = toBlock; }
if (blockHash) { filter.blockHash = blockHash; }
return filter;
};
// Addresses could be async (ENS names or Addressables)
let address: Array<string | Promise<string>> = [ ];
if (filter.address) {
if (Array.isArray(filter.address)) {
for (const addr of filter.address) { address.push(this._getAddress(addr)); }
} else {
address.push(this._getAddress(filter.address));
}
}
let fromBlock: undefined | string | Promise<string> = undefined;
if ("fromBlock" in filter) { fromBlock = this._getBlockTag(filter.fromBlock); }
let toBlock: undefined | string | Promise<string> = undefined;
if ("toBlock" in filter) { toBlock = this._getBlockTag(filter.toBlock); }
if (address.filter((a) => (typeof(a) !== "string")).length ||
(fromBlock != null && typeof(fromBlock) !== "string") ||
(toBlock != null && typeof(toBlock) !== "string")) {
return Promise.all([ Promise.all(address), fromBlock, toBlock ]).then((result) => {
return resolve(result[0], result[1], result[2]);
});
}
return resolve(<Array<string>>address, fromBlock, toBlock);
}
/**
* Returns or resolves to a transaction for %%request%%, resolving
* any ENS names or [[Addressable]] and returning if already a valid
* transaction.
*/
_getTransactionRequest(_request: TransactionRequest): PerformActionTransaction | Promise<PerformActionTransaction> {
const request = <PerformActionTransaction>copyRequest(_request);
const promises: Array<Promise<void>> = [ ];
[ "to", "from" ].forEach((key) => {
if ((<any>request)[key] == null) { return; }
const addr = resolveAddress((<any>request)[key], this);
if (isPromise(addr)) {
promises.push((async function() { (<any>request)[key] = await addr; })());
} else {
(<any>request)[key] = addr;
}
});
if (request.blockTag != null) {
const blockTag = this._getBlockTag(request.blockTag);
if (isPromise(blockTag)) {
promises.push((async function() { request.blockTag = await blockTag; })());
} else {
request.blockTag = blockTag;
}
}
if (promises.length) {
return (async function() {
await Promise.all(promises);
return request;
})();
}
return request;
}
async getNetwork(): Promise<Network> {
// No explicit network was set and this is our first time
if (this.#networkPromise == null) {
// Detect the current network (shared with all calls)
const detectNetwork = (async () => {
try {
const network = await this._detectNetwork();
this.emit("network", network, null);
return network;
} catch (error) {
if (this.#networkPromise === detectNetwork!) {
this.#networkPromise = null;
}
throw error;
}
})();
this.#networkPromise = detectNetwork;
return (await detectNetwork).clone();
}
const networkPromise = this.#networkPromise;
const [ expected, actual ] = await Promise.all([
networkPromise, // Possibly an explicit Network
this._detectNetwork() // The actual connected network
]);
if (expected.chainId !== actual.chainId) {
if (this.#anyNetwork) {
// The "any" network can change, so notify listeners
this.emit("network", actual, expected);
// Update the network if something else hasn't already changed it
if (this.#networkPromise === networkPromise) {
this.#networkPromise = Promise.resolve(actual);
}
} else {
// Otherwise, we do not allow changes to the underlying network
assert(false, `network changed: ${ expected.chainId } => ${ actual.chainId } `, "NETWORK_ERROR", {
event: "changed"
});
}
}
return expected.clone();
}
async getFeeData(): Promise<FeeData> {
const network = await this.getNetwork();
const getFeeDataFunc = async () => {
const { _block, gasPrice, priorityFee } = await resolveProperties({
_block: this.#getBlock("latest", false),
gasPrice: ((async () => {
try {
const value = await this.#perform({ method: "getGasPrice" });
return getBigInt(value, "%response");
} catch (error) { }
return null
})()),
priorityFee: ((async () => {
try {
const value = await this.#perform({ method: "getPriorityFee" });
return getBigInt(value, "%response");
} catch (error) { }
return null;
})())
});
let maxFeePerGas: null | bigint = null;
let maxPriorityFeePerGas: null | bigint = null;
// These are the recommended EIP-1559 heuristics for fee data
const block = this._wrapBlock(_block, network);
if (block && block.baseFeePerGas) {
maxPriorityFeePerGas = (priorityFee != null) ? priorityFee: BigInt("1000000000");
maxFeePerGas = (block.baseFeePerGas * BN_2) + maxPriorityFeePerGas;
}
return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas);
};
// Check for a FeeDataNetWorkPlugin
const plugin = <FetchUrlFeeDataNetworkPlugin>network.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");
if (plugin) {
const req = new FetchRequest(plugin.url);
const feeData = await plugin.processFunc(getFeeDataFunc, this, req);
return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas);
}
return await getFeeDataFunc();
}
async estimateGas(_tx: TransactionRequest): Promise<bigint> {
let tx = this._getTransactionRequest(_tx);
if (isPromise(tx)) { tx = await tx; }
return getBigInt(await this.#perform({
method: "estimateGas", transaction: tx
}), "%response");
}
async #call(tx: PerformActionTransaction, blockTag: string, attempt: number): Promise<string> {
assert (attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
reason: "TOO_MANY_REDIRECTS",
transaction: Object.assign({ }, tx, { blockTag, enableCcipRead: true })
});
// This came in as a PerformActionTransaction, so to/from are safe; we can cast
const transaction = <PerformActionTransaction>copyRequest(tx);
try {
return hexlify(await this._perform({ method: "call", transaction, blockTag }));
} catch (error: any) {
// CCIP Read OffchainLookup
if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") {
const data = error.data;
const txSender = await resolveAddress(transaction.to, this);
// Parse the CCIP Read Arguments
let ccipArgs: CcipArgs;
try {
ccipArgs = parseOffchainLookup(dataSlice(error.data, 4));
} catch (error: any) {
assert(false, error.message, "OFFCHAIN_FAULT", {
reason: "BAD_DATA", transaction, info: { data } });