@qevm/providers 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +78 -0
  3. package/lib/_version.d.ts +2 -0
  4. package/lib/_version.d.ts.map +1 -0
  5. package/lib/_version.js +5 -0
  6. package/lib/_version.js.map +1 -0
  7. package/lib/alchemy-provider.d.ts +17 -0
  8. package/lib/alchemy-provider.d.ts.map +1 -0
  9. package/lib/alchemy-provider.js +112 -0
  10. package/lib/alchemy-provider.js.map +1 -0
  11. package/lib/ankr-provider.d.ts +10 -0
  12. package/lib/ankr-provider.d.ts.map +1 -0
  13. package/lib/ankr-provider.js +79 -0
  14. package/lib/ankr-provider.js.map +1 -0
  15. package/lib/base-provider.d.ts +156 -0
  16. package/lib/base-provider.d.ts.map +1 -0
  17. package/lib/base-provider.js +2585 -0
  18. package/lib/base-provider.js.map +1 -0
  19. package/lib/browser-ipc-provider.d.ts +3 -0
  20. package/lib/browser-ipc-provider.d.ts.map +1 -0
  21. package/lib/browser-ipc-provider.js +6 -0
  22. package/lib/browser-ipc-provider.js.map +1 -0
  23. package/lib/browser-net.d.ts +2 -0
  24. package/lib/browser-net.d.ts.map +1 -0
  25. package/lib/browser-net.js +6 -0
  26. package/lib/browser-net.js.map +1 -0
  27. package/lib/browser-ws.d.ts +3 -0
  28. package/lib/browser-ws.d.ts.map +1 -0
  29. package/lib/browser-ws.js +22 -0
  30. package/lib/browser-ws.js.map +1 -0
  31. package/lib/cloudflare-provider.d.ts +8 -0
  32. package/lib/cloudflare-provider.d.ts.map +1 -0
  33. package/lib/cloudflare-provider.js +100 -0
  34. package/lib/cloudflare-provider.js.map +1 -0
  35. package/lib/etherscan-provider.d.ts +18 -0
  36. package/lib/etherscan-provider.d.ts.map +1 -0
  37. package/lib/etherscan-provider.js +528 -0
  38. package/lib/etherscan-provider.js.map +1 -0
  39. package/lib/fallback-provider.d.ts +20 -0
  40. package/lib/fallback-provider.d.ts.map +1 -0
  41. package/lib/fallback-provider.js +699 -0
  42. package/lib/fallback-provider.js.map +1 -0
  43. package/lib/formatter.d.ts +60 -0
  44. package/lib/formatter.d.ts.map +1 -0
  45. package/lib/formatter.js +452 -0
  46. package/lib/formatter.js.map +1 -0
  47. package/lib/index.d.ts +23 -0
  48. package/lib/index.d.ts.map +1 -0
  49. package/lib/index.js +97 -0
  50. package/lib/index.js.map +1 -0
  51. package/lib/infura-provider.d.ts +21 -0
  52. package/lib/infura-provider.d.ts.map +1 -0
  53. package/lib/infura-provider.js +141 -0
  54. package/lib/infura-provider.js.map +1 -0
  55. package/lib/ipc-provider.d.ts +8 -0
  56. package/lib/ipc-provider.d.ts.map +1 -0
  57. package/lib/ipc-provider.js +77 -0
  58. package/lib/ipc-provider.js.map +1 -0
  59. package/lib/json-rpc-batch-provider.d.ts +17 -0
  60. package/lib/json-rpc-batch-provider.d.ts.map +1 -0
  61. package/lib/json-rpc-batch-provider.js +99 -0
  62. package/lib/json-rpc-batch-provider.js.map +1 -0
  63. package/lib/json-rpc-provider.d.ts +54 -0
  64. package/lib/json-rpc-provider.d.ts.map +1 -0
  65. package/lib/json-rpc-provider.js +855 -0
  66. package/lib/json-rpc-provider.js.map +1 -0
  67. package/lib/nodesmith-provider.d.ts +7 -0
  68. package/lib/nodesmith-provider.d.ts.map +1 -0
  69. package/lib/nodesmith-provider.js +64 -0
  70. package/lib/nodesmith-provider.js.map +1 -0
  71. package/lib/pocket-provider.d.ts +12 -0
  72. package/lib/pocket-provider.d.ts.map +1 -0
  73. package/lib/pocket-provider.js +98 -0
  74. package/lib/pocket-provider.js.map +1 -0
  75. package/lib/url-json-rpc-provider.d.ts +18 -0
  76. package/lib/url-json-rpc-provider.d.ts.map +1 -0
  77. package/lib/url-json-rpc-provider.js +153 -0
  78. package/lib/url-json-rpc-provider.js.map +1 -0
  79. package/lib/web3-provider.d.ts +28 -0
  80. package/lib/web3-provider.d.ts.map +1 -0
  81. package/lib/web3-provider.js +155 -0
  82. package/lib/web3-provider.js.map +1 -0
  83. package/lib/websocket-provider.d.ts +48 -0
  84. package/lib/websocket-provider.d.ts.map +1 -0
  85. package/lib/websocket-provider.js +384 -0
  86. package/lib/websocket-provider.js.map +1 -0
  87. package/lib/ws.d.ts +3 -0
  88. package/lib/ws.d.ts.map +1 -0
  89. package/lib/ws.js +9 -0
  90. package/lib/ws.js.map +1 -0
  91. package/package.json +57 -0
  92. package/src.ts/_version.ts +1 -0
  93. package/src.ts/alchemy-provider.ts +101 -0
  94. package/src.ts/ankr-provider.ts +68 -0
  95. package/src.ts/base-provider.ts +2216 -0
  96. package/src.ts/browser-ipc-provider.ts +7 -0
  97. package/src.ts/browser-net.ts +3 -0
  98. package/src.ts/browser-ws.ts +21 -0
  99. package/src.ts/cloudflare-provider.ts +42 -0
  100. package/src.ts/etherscan-provider.ts +454 -0
  101. package/src.ts/fallback-provider.ts +654 -0
  102. package/src.ts/formatter.ts +522 -0
  103. package/src.ts/index.ts +178 -0
  104. package/src.ts/infura-provider.ts +143 -0
  105. package/src.ts/ipc-provider.ts +72 -0
  106. package/src.ts/json-rpc-batch-provider.ts +97 -0
  107. package/src.ts/json-rpc-provider.ts +742 -0
  108. package/src.ts/nodesmith-provider.ts +50 -0
  109. package/src.ts/pocket-provider.ts +93 -0
  110. package/src.ts/url-json-rpc-provider.ts +106 -0
  111. package/src.ts/web3-provider.ts +169 -0
  112. package/src.ts/websocket-provider.ts +350 -0
  113. package/src.ts/ws.ts +3 -0
  114. package/thirdparty.d.ts +10 -0
@@ -0,0 +1,742 @@
1
+ "use strict";
2
+
3
+ // See: https://github.com/ethereum/wiki/wiki/JSON-RPC
4
+
5
+ import { Provider, TransactionRequest, TransactionResponse } from "@qevm/abstract-provider";
6
+ import { Signer, TypedDataDomain, TypedDataField, TypedDataSigner } from "@qevm/abstract-signer";
7
+ import { BigNumber } from "@ethersproject/bignumber";
8
+ import { Bytes, hexlify, hexValue, hexZeroPad, isHexString } from "@qevm/bytes";
9
+ import { _TypedDataEncoder } from "@qevm/hash";
10
+ import { Network, Networkish } from "@ethersproject/networks";
11
+ import { checkProperties, deepCopy, Deferrable, defineReadOnly, getStatic, resolveProperties, shallowCopy } from "@ethersproject/properties";
12
+ import { toUtf8Bytes } from "@ethersproject/strings";
13
+ import { AccessList, accessListify } from "@qevm/transactions";
14
+ import { ConnectionInfo, fetchJson, poll } from "@ethersproject/web";
15
+
16
+ import { Logger } from "@ethersproject/logger";
17
+ import { version } from "./_version";
18
+ const logger = new Logger(version);
19
+
20
+ import { BaseProvider, Event } from "./base-provider";
21
+
22
+
23
+ const errorGas = [ "call", "estimateGas" ];
24
+
25
+ function spelunk(value: any, requireData: boolean): null | { message: string, data: null | string } {
26
+ if (value == null) { return null; }
27
+
28
+ // These *are* the droids we're looking for.
29
+ if (typeof(value.message) === "string" && value.message.match("reverted")) {
30
+ const data = isHexString(value.data) ? value.data: null;
31
+ if (!requireData || data) {
32
+ return { message: value.message, data };
33
+ }
34
+ }
35
+
36
+ // Spelunk further...
37
+ if (typeof(value) === "object") {
38
+ for (const key in value) {
39
+ const result = spelunk(value[key], requireData);
40
+ if (result) { return result; }
41
+ }
42
+ return null;
43
+ }
44
+
45
+ // Might be a JSON string we can further descend...
46
+ if (typeof(value) === "string") {
47
+ try {
48
+ return spelunk(JSON.parse(value), requireData);
49
+ } catch (error) { }
50
+ }
51
+
52
+ return null;
53
+ }
54
+
55
+ function checkError(method: string, error: any, params: any): any {
56
+
57
+ const transaction = params.transaction || params.signedTransaction;
58
+
59
+ // Undo the "convenience" some nodes are attempting to prevent backwards
60
+ // incompatibility; maybe for v6 consider forwarding reverts as errors
61
+ if (method === "call") {
62
+ const result = spelunk(error, true);
63
+ if (result) { return result.data; }
64
+
65
+ // Nothing descriptive..
66
+ logger.throwError("missing revert data in call exception; Transaction reverted without a reason string", Logger.errors.CALL_EXCEPTION, {
67
+ data: "0x", transaction, error
68
+ });
69
+ }
70
+
71
+ if (method === "estimateGas") {
72
+ // Try to find something, with a preference on SERVER_ERROR body
73
+ let result = spelunk(error.body, false);
74
+ if (result == null) { result = spelunk(error, false); }
75
+
76
+ // Found "reverted", this is a CALL_EXCEPTION
77
+ if (result) {
78
+ logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
79
+ reason: result.message, method, transaction, error
80
+ });
81
+ }
82
+ }
83
+
84
+ // @TODO: Should we spelunk for message too?
85
+
86
+ let message = error.message;
87
+ if (error.code === Logger.errors.SERVER_ERROR && error.error && typeof(error.error.message) === "string") {
88
+ message = error.error.message;
89
+ } else if (typeof(error.body) === "string") {
90
+ message = error.body;
91
+ } else if (typeof(error.responseText) === "string") {
92
+ message = error.responseText;
93
+ }
94
+ message = (message || "").toLowerCase();
95
+
96
+ // "insufficient funds for gas * price + value + cost(data)"
97
+ if (message.match(/insufficient funds|base fee exceeds gas limit|InsufficientFunds/i)) {
98
+ logger.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, {
99
+ error, method, transaction
100
+ });
101
+ }
102
+
103
+ // "nonce too low"
104
+ if (message.match(/nonce (is )?too low/i)) {
105
+ logger.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, {
106
+ error, method, transaction
107
+ });
108
+ }
109
+
110
+ // "replacement transaction underpriced"
111
+ if (message.match(/replacement transaction underpriced|transaction gas price.*too low/i)) {
112
+ logger.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, {
113
+ error, method, transaction
114
+ });
115
+ }
116
+
117
+ // "replacement transaction underpriced"
118
+ if (message.match(/only replay-protected/i)) {
119
+ logger.throwError("legacy pre-eip-155 transactions not supported", Logger.errors.UNSUPPORTED_OPERATION, {
120
+ error, method, transaction
121
+ });
122
+ }
123
+
124
+ if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted|revert/)) {
125
+ logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
126
+ error, method, transaction
127
+ });
128
+ }
129
+
130
+ throw error;
131
+ }
132
+
133
+ function timer(timeout: number): Promise<any> {
134
+ return new Promise(function(resolve) {
135
+ setTimeout(resolve, timeout);
136
+ });
137
+ }
138
+
139
+ function getResult(payload: { error?: { code?: number, data?: any, message?: string }, result?: any }): any {
140
+ if (payload.error) {
141
+ // @TODO: not any
142
+ const error: any = new Error(payload.error.message);
143
+ error.code = payload.error.code;
144
+ error.data = payload.error.data;
145
+ throw error;
146
+ }
147
+
148
+ return payload.result;
149
+ }
150
+
151
+ function getLowerCase(value: string): string {
152
+ if (value) { return value.toLowerCase(); }
153
+ return value;
154
+ }
155
+
156
+ const _constructorGuard = {};
157
+
158
+ export class JsonRpcSigner extends Signer implements TypedDataSigner {
159
+ readonly provider: JsonRpcProvider;
160
+ _index: number;
161
+ _address: string;
162
+
163
+ constructor(constructorGuard: any, provider: JsonRpcProvider, addressOrIndex?: string | number) {
164
+ super();
165
+
166
+ if (constructorGuard !== _constructorGuard) {
167
+ throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");
168
+ }
169
+
170
+ defineReadOnly(this, "provider", provider);
171
+
172
+ if (addressOrIndex == null) { addressOrIndex = 0; }
173
+
174
+ if (typeof(addressOrIndex) === "string") {
175
+ defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex));
176
+ defineReadOnly(this, "_index", null);
177
+
178
+ } else if (typeof(addressOrIndex) === "number") {
179
+ defineReadOnly(this, "_index", addressOrIndex);
180
+ defineReadOnly(this, "_address", null);
181
+
182
+ } else {
183
+ logger.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex);
184
+ }
185
+ }
186
+
187
+ connect(provider: Provider): JsonRpcSigner {
188
+ return logger.throwError("cannot alter JSON-RPC Signer connection", Logger.errors.UNSUPPORTED_OPERATION, {
189
+ operation: "connect"
190
+ });
191
+ }
192
+
193
+ connectUnchecked(): JsonRpcSigner {
194
+ return new UncheckedJsonRpcSigner(_constructorGuard, this.provider, this._address || this._index);
195
+ }
196
+
197
+ getAddress(): Promise<string> {
198
+ if (this._address) {
199
+ return Promise.resolve(this._address);
200
+ }
201
+
202
+ return this.provider.send("eth_accounts", []).then((accounts) => {
203
+ if (accounts.length <= this._index) {
204
+ logger.throwError("unknown account #" + this._index, Logger.errors.UNSUPPORTED_OPERATION, {
205
+ operation: "getAddress"
206
+ });
207
+ }
208
+ return this.provider.formatter.address(accounts[this._index])
209
+ });
210
+ }
211
+
212
+ sendUncheckedTransaction(transaction: Deferrable<TransactionRequest>): Promise<string> {
213
+ transaction = shallowCopy(transaction);
214
+
215
+ const fromAddress = this.getAddress().then((address) => {
216
+ if (address) { address = address.toLowerCase(); }
217
+ return address;
218
+ });
219
+
220
+ // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
221
+ // wishes to use this, it is easy to specify explicitly, otherwise
222
+ // we look it up for them.
223
+ if (transaction.gasLimit == null) {
224
+ const estimate = shallowCopy(transaction);
225
+ estimate.from = fromAddress;
226
+ transaction.gasLimit = this.provider.estimateGas(estimate);
227
+ }
228
+
229
+ if (transaction.to != null) {
230
+ transaction.to = Promise.resolve(transaction.to).then(async (to) => {
231
+ if (to == null) { return null; }
232
+ const address = await this.provider.resolveName(to);
233
+ if (address == null) {
234
+ logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to);
235
+ }
236
+ return address;
237
+ });
238
+ }
239
+
240
+ return resolveProperties({
241
+ tx: resolveProperties(transaction),
242
+ sender: fromAddress
243
+ }).then(({ tx, sender }) => {
244
+
245
+ if (tx.from != null) {
246
+ if (tx.from.toLowerCase() !== sender) {
247
+ logger.throwArgumentError("from address mismatch", "transaction", transaction);
248
+ }
249
+ } else {
250
+ tx.from = sender;
251
+ }
252
+
253
+ const hexTx = (<any>this.provider.constructor).hexlifyTransaction(tx, { from: true });
254
+
255
+ return this.provider.send("eth_sendTransaction", [ hexTx ]).then((hash) => {
256
+ return hash;
257
+ }, (error) => {
258
+ if (typeof(error.message) === "string" && error.message.match(/user denied/i)) {
259
+ logger.throwError("user rejected transaction", Logger.errors.ACTION_REJECTED, {
260
+ action: "sendTransaction",
261
+ transaction: tx
262
+ });
263
+ }
264
+
265
+ return checkError("sendTransaction", error, hexTx);
266
+ });
267
+ });
268
+ }
269
+
270
+ signTransaction(transaction: Deferrable<TransactionRequest>): Promise<string> {
271
+ return logger.throwError("signing transactions is unsupported", Logger.errors.UNSUPPORTED_OPERATION, {
272
+ operation: "signTransaction"
273
+ });
274
+ }
275
+
276
+ async sendTransaction(transaction: Deferrable<TransactionRequest>): Promise<TransactionResponse> {
277
+ // This cannot be mined any earlier than any recent block
278
+ const blockNumber = await this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval);
279
+
280
+ // Send the transaction
281
+ const hash = await this.sendUncheckedTransaction(transaction);
282
+
283
+ try {
284
+ // Unfortunately, JSON-RPC only provides and opaque transaction hash
285
+ // for a response, and we need the actual transaction, so we poll
286
+ // for it; it should show up very quickly
287
+ return await poll(async () => {
288
+ const tx = await this.provider.getTransaction(hash);
289
+ if (tx === null) { return undefined; }
290
+ return this.provider._wrapTransaction(tx, hash, blockNumber);
291
+ }, { oncePoll: this.provider });
292
+ } catch (error) {
293
+ (<any>error).transactionHash = hash;
294
+ throw error;
295
+ }
296
+ }
297
+
298
+ async signMessage(message: Bytes | string): Promise<string> {
299
+ const data = ((typeof(message) === "string") ? toUtf8Bytes(message): message);
300
+ const address = await this.getAddress();
301
+ try {
302
+ return await this.provider.send("personal_sign", [ hexlify(data), address.toLowerCase() ]);
303
+ } catch (error) {
304
+ if (typeof(error.message) === "string" && error.message.match(/user denied/i)) {
305
+ logger.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, {
306
+ action: "signMessage",
307
+ from: address,
308
+ messageData: message
309
+ });
310
+ }
311
+ throw error;
312
+ }
313
+ }
314
+
315
+ async _legacySignMessage(message: Bytes | string): Promise<string> {
316
+ const data = ((typeof(message) === "string") ? toUtf8Bytes(message): message);
317
+ const address = await this.getAddress();
318
+
319
+ try {
320
+ // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
321
+ return await this.provider.send("eth_sign", [ address.toLowerCase(), hexlify(data) ]);
322
+ } catch (error) {
323
+ if (typeof(error.message) === "string" && error.message.match(/user denied/i)) {
324
+ logger.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, {
325
+ action: "_legacySignMessage",
326
+ from: address,
327
+ messageData: message
328
+ });
329
+ }
330
+ throw error;
331
+ }
332
+ }
333
+
334
+ async _signTypedData(domain: TypedDataDomain, types: Record<string, Array<TypedDataField>>, value: Record<string, any>): Promise<string> {
335
+ // Populate any ENS names (in-place)
336
+ const populated = await _TypedDataEncoder.resolveNames(domain, types, value, (name: string) => {
337
+ return this.provider.resolveName(name);
338
+ });
339
+
340
+ const address = await this.getAddress();
341
+
342
+ try {
343
+ return await this.provider.send("eth_signTypedData_v4", [
344
+ address.toLowerCase(),
345
+ JSON.stringify(_TypedDataEncoder.getPayload(populated.domain, types, populated.value))
346
+ ]);
347
+ } catch (error) {
348
+ if (typeof(error.message) === "string" && error.message.match(/user denied/i)) {
349
+ logger.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, {
350
+ action: "_signTypedData",
351
+ from: address,
352
+ messageData: { domain: populated.domain, types, value: populated.value }
353
+ });
354
+ }
355
+ throw error;
356
+ }
357
+ }
358
+
359
+ async unlock(password: string): Promise<boolean> {
360
+ const provider = this.provider;
361
+
362
+ const address = await this.getAddress();
363
+
364
+ return provider.send("personal_unlockAccount", [ address.toLowerCase(), password, null ]);
365
+ }
366
+ }
367
+
368
+ class UncheckedJsonRpcSigner extends JsonRpcSigner {
369
+ sendTransaction(transaction: Deferrable<TransactionRequest>): Promise<TransactionResponse> {
370
+ return this.sendUncheckedTransaction(transaction).then((hash) => {
371
+ return <TransactionResponse>{
372
+ hash: hash,
373
+ nonce: null,
374
+ gasLimit: null,
375
+ gasPrice: null,
376
+ data: null,
377
+ value: null,
378
+ chainId: null,
379
+ confirmations: 0,
380
+ from: null,
381
+ wait: (confirmations?: number) => { return this.provider.waitForTransaction(hash, confirmations); }
382
+ };
383
+ });
384
+ }
385
+ }
386
+
387
+ const allowedTransactionKeys: { [ key: string ]: boolean } = {
388
+ chainId: true, data: true, gasLimit: true, gasPrice:true, nonce: true, to: true, value: true,
389
+ type: true, accessList: true,
390
+ maxFeePerGas: true, maxPriorityFeePerGas: true
391
+ }
392
+
393
+ export class JsonRpcProvider extends BaseProvider {
394
+ readonly connection: ConnectionInfo;
395
+
396
+ _pendingFilter: Promise<number>;
397
+ _nextId: number;
398
+
399
+ // During any given event loop, the results for a given call will
400
+ // all be the same, so we can dedup the calls to save requests and
401
+ // bandwidth. @TODO: Try out generalizing this against send?
402
+ _eventLoopCache: Record<string, Promise<any>>;
403
+ get _cache(): Record<string, Promise<any>> {
404
+ if (this._eventLoopCache == null) {
405
+ this._eventLoopCache = { };
406
+ }
407
+ return this._eventLoopCache;
408
+ }
409
+
410
+ constructor(url?: ConnectionInfo | string, network?: Networkish) {
411
+ let networkOrReady: Networkish | Promise<Network> = network;
412
+
413
+ // The network is unknown, query the JSON-RPC for it
414
+ if (networkOrReady == null) {
415
+ networkOrReady = new Promise((resolve, reject) => {
416
+ setTimeout(() => {
417
+ this.detectNetwork().then((network) => {
418
+ resolve(network);
419
+ }, (error) => {
420
+ reject(error);
421
+ });
422
+ }, 0);
423
+ });
424
+ }
425
+
426
+ super(networkOrReady);
427
+
428
+ // Default URL
429
+ if (!url) { url = getStatic<() => string>(this.constructor, "defaultUrl")(); }
430
+
431
+ if (typeof(url) === "string") {
432
+ defineReadOnly(this, "connection",Object.freeze({
433
+ url: url
434
+ }));
435
+ } else {
436
+ defineReadOnly(this, "connection", Object.freeze(shallowCopy(url)));
437
+ }
438
+
439
+ this._nextId = 42;
440
+ }
441
+
442
+ static defaultUrl(): string {
443
+ return "http:/\/localhost:8545";
444
+ }
445
+
446
+ detectNetwork(): Promise<Network> {
447
+ if (!this._cache["detectNetwork"]) {
448
+ this._cache["detectNetwork"] = this._uncachedDetectNetwork();
449
+
450
+ // Clear this cache at the beginning of the next event loop
451
+ setTimeout(() => {
452
+ this._cache["detectNetwork"] = null;
453
+ }, 0);
454
+ }
455
+ return this._cache["detectNetwork"];
456
+ }
457
+
458
+ async _uncachedDetectNetwork(): Promise<Network> {
459
+ await timer(0);
460
+
461
+ let chainId = null;
462
+ try {
463
+ chainId = await this.send("eth_chainId", [ ]);
464
+ } catch (error) {
465
+ try {
466
+ chainId = await this.send("net_version", [ ]);
467
+ } catch (error) { }
468
+ }
469
+
470
+ if (chainId != null) {
471
+ const getNetwork = getStatic<(network: Networkish) => Network>(this.constructor, "getNetwork");
472
+ try {
473
+ return getNetwork(BigNumber.from(chainId).toNumber());
474
+ } catch (error) {
475
+ return logger.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
476
+ chainId: chainId,
477
+ event: "invalidNetwork",
478
+ serverError: error
479
+ });
480
+ }
481
+ }
482
+
483
+ return logger.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
484
+ event: "noNetwork"
485
+ });
486
+ }
487
+
488
+ getSigner(addressOrIndex?: string | number): JsonRpcSigner {
489
+ return new JsonRpcSigner(_constructorGuard, this, addressOrIndex);
490
+ }
491
+
492
+ getUncheckedSigner(addressOrIndex?: string | number): UncheckedJsonRpcSigner {
493
+ return this.getSigner(addressOrIndex).connectUnchecked();
494
+ }
495
+
496
+ listAccounts(): Promise<Array<string>> {
497
+ return this.send("eth_accounts", []).then((accounts: Array<string>) => {
498
+ return accounts.map((a) => this.formatter.address(a));
499
+ });
500
+ }
501
+
502
+ send(method: string, params: Array<any>): Promise<any> {
503
+ const request = {
504
+ method: method,
505
+ params: params,
506
+ id: (this._nextId++),
507
+ jsonrpc: "2.0"
508
+ };
509
+
510
+ this.emit("debug", {
511
+ action: "request",
512
+ request: deepCopy(request),
513
+ provider: this
514
+ });
515
+
516
+ // We can expand this in the future to any call, but for now these
517
+ // are the biggest wins and do not require any serializing parameters.
518
+ const cache = ([ "eth_chainId", "eth_blockNumber" ].indexOf(method) >= 0);
519
+ if (cache && this._cache[method]) {
520
+ return this._cache[method];
521
+ }
522
+
523
+ const result = fetchJson(this.connection, JSON.stringify(request), getResult).then((result) => {
524
+ this.emit("debug", {
525
+ action: "response",
526
+ request: request,
527
+ response: result,
528
+ provider: this
529
+ });
530
+
531
+ return result;
532
+
533
+ }, (error) => {
534
+ this.emit("debug", {
535
+ action: "response",
536
+ error: error,
537
+ request: request,
538
+ provider: this
539
+ });
540
+
541
+ throw error;
542
+ });
543
+
544
+ // Cache the fetch, but clear it on the next event loop
545
+ if (cache) {
546
+ this._cache[method] = result;
547
+ setTimeout(() => {
548
+ this._cache[method] = null;
549
+ }, 0);
550
+ }
551
+
552
+ return result;
553
+ }
554
+
555
+ prepareRequest(method: string, params: any): [ string, Array<any> ] {
556
+ switch (method) {
557
+ case "getBlockNumber":
558
+ return [ "eth_blockNumber", [] ];
559
+
560
+ case "getGasPrice":
561
+ return [ "eth_gasPrice", [] ];
562
+
563
+ case "getBalance":
564
+ return [ "eth_getBalance", [ getLowerCase(params.address), params.blockTag ] ];
565
+
566
+ case "getTransactionCount":
567
+ return [ "eth_getTransactionCount", [ getLowerCase(params.address), params.blockTag ] ];
568
+
569
+ case "getCode":
570
+ return [ "eth_getCode", [ getLowerCase(params.address), params.blockTag ] ];
571
+
572
+ case "getStorageAt":
573
+ return [ "eth_getStorageAt", [ getLowerCase(params.address), hexZeroPad(params.position, 32), params.blockTag ] ];
574
+
575
+ case "sendTransaction":
576
+ return [ "eth_sendRawTransaction", [ params.signedTransaction ] ]
577
+
578
+ case "getBlock":
579
+ if (params.blockTag) {
580
+ return [ "eth_getBlockByNumber", [ params.blockTag, !!params.includeTransactions ] ];
581
+ } else if (params.blockHash) {
582
+ return [ "eth_getBlockByHash", [ params.blockHash, !!params.includeTransactions ] ];
583
+ }
584
+ return null;
585
+
586
+ case "getTransaction":
587
+ return [ "eth_getTransactionByHash", [ params.transactionHash ] ];
588
+
589
+ case "getTransactionReceipt":
590
+ return [ "eth_getTransactionReceipt", [ params.transactionHash ] ];
591
+
592
+ case "call": {
593
+ const hexlifyTransaction = getStatic<(t: TransactionRequest, a?: { [key: string]: boolean }) => { [key: string]: string }>(this.constructor, "hexlifyTransaction");
594
+ return [ "eth_call", [ hexlifyTransaction(params.transaction, { from: true }), params.blockTag ] ];
595
+ }
596
+
597
+ case "estimateGas": {
598
+ const hexlifyTransaction = getStatic<(t: TransactionRequest, a?: { [key: string]: boolean }) => { [key: string]: string }>(this.constructor, "hexlifyTransaction");
599
+ return [ "eth_estimateGas", [ hexlifyTransaction(params.transaction, { from: true }) ] ];
600
+ }
601
+
602
+ case "getLogs":
603
+ if (params.filter && params.filter.address != null) {
604
+ params.filter.address = getLowerCase(params.filter.address);
605
+ }
606
+ return [ "eth_getLogs", [ params.filter ] ];
607
+
608
+ default:
609
+ break;
610
+ }
611
+
612
+ return null;
613
+ }
614
+
615
+ async perform(method: string, params: any): Promise<any> {
616
+ // Legacy networks do not like the type field being passed along (which
617
+ // is fair), so we delete type if it is 0 and a non-EIP-1559 network
618
+ if (method === "call" || method === "estimateGas") {
619
+ const tx = params.transaction;
620
+ if (tx && tx.type != null && BigNumber.from(tx.type).isZero()) {
621
+ // If there are no EIP-1559 properties, it might be non-EIP-1559
622
+ if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {
623
+ const feeData = await this.getFeeData();
624
+ if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
625
+ // Network doesn't know about EIP-1559 (and hence type)
626
+ params = shallowCopy(params);
627
+ params.transaction = shallowCopy(tx);
628
+ delete params.transaction.type;
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ const args = this.prepareRequest(method, params);
635
+
636
+ if (args == null) {
637
+ logger.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
638
+ }
639
+ try {
640
+ return await this.send(args[0], args[1])
641
+ } catch (error) {
642
+ return checkError(method, error, params);
643
+ }
644
+ }
645
+
646
+ _startEvent(event: Event): void {
647
+ if (event.tag === "pending") { this._startPending(); }
648
+ super._startEvent(event);
649
+ }
650
+
651
+ _startPending(): void {
652
+ if (this._pendingFilter != null) { return; }
653
+ const self = this;
654
+
655
+ const pendingFilter: Promise<number> = this.send("eth_newPendingTransactionFilter", []);
656
+ this._pendingFilter = pendingFilter;
657
+
658
+ pendingFilter.then(function(filterId) {
659
+ function poll() {
660
+ self.send("eth_getFilterChanges", [ filterId ]).then(function(hashes: Array<string>) {
661
+ if (self._pendingFilter != pendingFilter) { return null; }
662
+
663
+ let seq = Promise.resolve();
664
+ hashes.forEach(function(hash) {
665
+ // @TODO: This should be garbage collected at some point... How? When?
666
+ self._emitted["t:" + hash.toLowerCase()] = "pending";
667
+ seq = seq.then(function() {
668
+ return self.getTransaction(hash).then(function(tx): any {
669
+ self.emit("pending", tx);
670
+ return null;
671
+ });
672
+ });
673
+ });
674
+
675
+ return seq.then(function() {
676
+ return timer(1000);
677
+ });
678
+ }).then(function(): any {
679
+ if (self._pendingFilter != pendingFilter) {
680
+ self.send("eth_uninstallFilter", [ filterId ]);
681
+ return;
682
+ }
683
+ setTimeout(function() { poll(); }, 0);
684
+
685
+ return null;
686
+ }).catch((error: Error) => { });
687
+ }
688
+ poll();
689
+
690
+ return filterId;
691
+ }).catch((error: Error) => { });
692
+ }
693
+
694
+ _stopEvent(event: Event): void {
695
+ if (event.tag === "pending" && this.listenerCount("pending") === 0) {
696
+ this._pendingFilter = null;
697
+ }
698
+ super._stopEvent(event);
699
+ }
700
+
701
+ // Convert an ethers.js transaction into a JSON-RPC transaction
702
+ // - gasLimit => gas
703
+ // - All values hexlified
704
+ // - All numeric values zero-striped
705
+ // - All addresses are lowercased
706
+ // NOTE: This allows a TransactionRequest, but all values should be resolved
707
+ // before this is called
708
+ // @TODO: This will likely be removed in future versions and prepareRequest
709
+ // will be the preferred method for this.
710
+ static hexlifyTransaction(transaction: TransactionRequest, allowExtra?: { [key: string]: boolean }): { [key: string]: string | AccessList } {
711
+ // Check only allowed properties are given
712
+ const allowed = shallowCopy(allowedTransactionKeys);
713
+ if (allowExtra) {
714
+ for (const key in allowExtra) {
715
+ if (allowExtra[key]) { allowed[key] = true; }
716
+ }
717
+ }
718
+
719
+ checkProperties(transaction, allowed);
720
+
721
+ const result: { [key: string]: string | AccessList } = {};
722
+
723
+ // JSON-RPC now requires numeric values to be "quantity" values
724
+ ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach(function(key) {
725
+ if ((<any>transaction)[key] == null) { return; }
726
+ const value = hexValue(BigNumber.from((<any>transaction)[key]));
727
+ if (key === "gasLimit") { key = "gas"; }
728
+ result[key] = value;
729
+ });
730
+
731
+ ["from", "to", "data"].forEach(function(key) {
732
+ if ((<any>transaction)[key] == null) { return; }
733
+ result[key] = hexlify((<any>transaction)[key]);
734
+ });
735
+
736
+ if ((<any>transaction).accessList) {
737
+ result["accessList"] = accessListify((<any>transaction).accessList);
738
+ }
739
+
740
+ return result;
741
+ }
742
+ }