@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.
- package/LICENSE.md +21 -0
- package/README.md +78 -0
- package/lib/_version.d.ts +2 -0
- package/lib/_version.d.ts.map +1 -0
- package/lib/_version.js +5 -0
- package/lib/_version.js.map +1 -0
- package/lib/alchemy-provider.d.ts +17 -0
- package/lib/alchemy-provider.d.ts.map +1 -0
- package/lib/alchemy-provider.js +112 -0
- package/lib/alchemy-provider.js.map +1 -0
- package/lib/ankr-provider.d.ts +10 -0
- package/lib/ankr-provider.d.ts.map +1 -0
- package/lib/ankr-provider.js +79 -0
- package/lib/ankr-provider.js.map +1 -0
- package/lib/base-provider.d.ts +156 -0
- package/lib/base-provider.d.ts.map +1 -0
- package/lib/base-provider.js +2585 -0
- package/lib/base-provider.js.map +1 -0
- package/lib/browser-ipc-provider.d.ts +3 -0
- package/lib/browser-ipc-provider.d.ts.map +1 -0
- package/lib/browser-ipc-provider.js +6 -0
- package/lib/browser-ipc-provider.js.map +1 -0
- package/lib/browser-net.d.ts +2 -0
- package/lib/browser-net.d.ts.map +1 -0
- package/lib/browser-net.js +6 -0
- package/lib/browser-net.js.map +1 -0
- package/lib/browser-ws.d.ts +3 -0
- package/lib/browser-ws.d.ts.map +1 -0
- package/lib/browser-ws.js +22 -0
- package/lib/browser-ws.js.map +1 -0
- package/lib/cloudflare-provider.d.ts +8 -0
- package/lib/cloudflare-provider.d.ts.map +1 -0
- package/lib/cloudflare-provider.js +100 -0
- package/lib/cloudflare-provider.js.map +1 -0
- package/lib/etherscan-provider.d.ts +18 -0
- package/lib/etherscan-provider.d.ts.map +1 -0
- package/lib/etherscan-provider.js +528 -0
- package/lib/etherscan-provider.js.map +1 -0
- package/lib/fallback-provider.d.ts +20 -0
- package/lib/fallback-provider.d.ts.map +1 -0
- package/lib/fallback-provider.js +699 -0
- package/lib/fallback-provider.js.map +1 -0
- package/lib/formatter.d.ts +60 -0
- package/lib/formatter.d.ts.map +1 -0
- package/lib/formatter.js +452 -0
- package/lib/formatter.js.map +1 -0
- package/lib/index.d.ts +23 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +97 -0
- package/lib/index.js.map +1 -0
- package/lib/infura-provider.d.ts +21 -0
- package/lib/infura-provider.d.ts.map +1 -0
- package/lib/infura-provider.js +141 -0
- package/lib/infura-provider.js.map +1 -0
- package/lib/ipc-provider.d.ts +8 -0
- package/lib/ipc-provider.d.ts.map +1 -0
- package/lib/ipc-provider.js +77 -0
- package/lib/ipc-provider.js.map +1 -0
- package/lib/json-rpc-batch-provider.d.ts +17 -0
- package/lib/json-rpc-batch-provider.d.ts.map +1 -0
- package/lib/json-rpc-batch-provider.js +99 -0
- package/lib/json-rpc-batch-provider.js.map +1 -0
- package/lib/json-rpc-provider.d.ts +54 -0
- package/lib/json-rpc-provider.d.ts.map +1 -0
- package/lib/json-rpc-provider.js +855 -0
- package/lib/json-rpc-provider.js.map +1 -0
- package/lib/nodesmith-provider.d.ts +7 -0
- package/lib/nodesmith-provider.d.ts.map +1 -0
- package/lib/nodesmith-provider.js +64 -0
- package/lib/nodesmith-provider.js.map +1 -0
- package/lib/pocket-provider.d.ts +12 -0
- package/lib/pocket-provider.d.ts.map +1 -0
- package/lib/pocket-provider.js +98 -0
- package/lib/pocket-provider.js.map +1 -0
- package/lib/url-json-rpc-provider.d.ts +18 -0
- package/lib/url-json-rpc-provider.d.ts.map +1 -0
- package/lib/url-json-rpc-provider.js +153 -0
- package/lib/url-json-rpc-provider.js.map +1 -0
- package/lib/web3-provider.d.ts +28 -0
- package/lib/web3-provider.d.ts.map +1 -0
- package/lib/web3-provider.js +155 -0
- package/lib/web3-provider.js.map +1 -0
- package/lib/websocket-provider.d.ts +48 -0
- package/lib/websocket-provider.d.ts.map +1 -0
- package/lib/websocket-provider.js +384 -0
- package/lib/websocket-provider.js.map +1 -0
- package/lib/ws.d.ts +3 -0
- package/lib/ws.d.ts.map +1 -0
- package/lib/ws.js +9 -0
- package/lib/ws.js.map +1 -0
- package/package.json +57 -0
- package/src.ts/_version.ts +1 -0
- package/src.ts/alchemy-provider.ts +101 -0
- package/src.ts/ankr-provider.ts +68 -0
- package/src.ts/base-provider.ts +2216 -0
- package/src.ts/browser-ipc-provider.ts +7 -0
- package/src.ts/browser-net.ts +3 -0
- package/src.ts/browser-ws.ts +21 -0
- package/src.ts/cloudflare-provider.ts +42 -0
- package/src.ts/etherscan-provider.ts +454 -0
- package/src.ts/fallback-provider.ts +654 -0
- package/src.ts/formatter.ts +522 -0
- package/src.ts/index.ts +178 -0
- package/src.ts/infura-provider.ts +143 -0
- package/src.ts/ipc-provider.ts +72 -0
- package/src.ts/json-rpc-batch-provider.ts +97 -0
- package/src.ts/json-rpc-provider.ts +742 -0
- package/src.ts/nodesmith-provider.ts +50 -0
- package/src.ts/pocket-provider.ts +93 -0
- package/src.ts/url-json-rpc-provider.ts +106 -0
- package/src.ts/web3-provider.ts +169 -0
- package/src.ts/websocket-provider.ts +350 -0
- package/src.ts/ws.ts +3 -0
- package/thirdparty.d.ts +10 -0
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
import { Block, BlockWithTransactions, Provider } from "@qevm/abstract-provider";
|
|
4
|
+
import { BigNumber } from "@ethersproject/bignumber";
|
|
5
|
+
import { isHexString } from "@qevm/bytes";
|
|
6
|
+
import { Network } from "@ethersproject/networks";
|
|
7
|
+
import { deepCopy, defineReadOnly, shallowCopy } from "@ethersproject/properties";
|
|
8
|
+
import { shuffled } from "@ethersproject/random";
|
|
9
|
+
import { poll } from "@ethersproject/web";
|
|
10
|
+
|
|
11
|
+
import { BaseProvider } from "./base-provider";
|
|
12
|
+
import { isCommunityResource } from "./formatter";
|
|
13
|
+
|
|
14
|
+
import { Logger } from "@ethersproject/logger";
|
|
15
|
+
import { version } from "./_version";
|
|
16
|
+
const logger = new Logger(version);
|
|
17
|
+
|
|
18
|
+
function now() { return (new Date()).getTime(); }
|
|
19
|
+
|
|
20
|
+
// Returns to network as long as all agree, or null if any is null.
|
|
21
|
+
// Throws an error if any two networks do not match.
|
|
22
|
+
function checkNetworks(networks: Array<Network>): Network {
|
|
23
|
+
let result = null;
|
|
24
|
+
|
|
25
|
+
for (let i = 0; i < networks.length; i++) {
|
|
26
|
+
const network = networks[i];
|
|
27
|
+
|
|
28
|
+
// Null! We do not know our network; bail.
|
|
29
|
+
if (network == null) { return null; }
|
|
30
|
+
|
|
31
|
+
if (result) {
|
|
32
|
+
// Make sure the network matches the previous networks
|
|
33
|
+
if (!(result.name === network.name && result.chainId === network.chainId &&
|
|
34
|
+
((result.ensAddress === network.ensAddress) || (result.ensAddress == null && network.ensAddress == null)))) {
|
|
35
|
+
|
|
36
|
+
logger.throwArgumentError("provider mismatch", "networks", networks);
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
result = network;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return result;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function median(values: Array<number>, maxDelta?: number): number {
|
|
47
|
+
values = values.slice().sort();
|
|
48
|
+
const middle = Math.floor(values.length / 2);
|
|
49
|
+
|
|
50
|
+
// Odd length; take the middle
|
|
51
|
+
if (values.length % 2) {
|
|
52
|
+
return values[middle];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Even length; take the average of the two middle
|
|
56
|
+
const a = values[middle - 1], b = values[middle];
|
|
57
|
+
|
|
58
|
+
if (maxDelta != null && Math.abs(a - b) > maxDelta) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return (a + b) / 2;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function serialize(value: any): string {
|
|
66
|
+
if (value === null) {
|
|
67
|
+
return "null";
|
|
68
|
+
} else if (typeof(value) === "number" || typeof(value) === "boolean") {
|
|
69
|
+
return JSON.stringify(value);
|
|
70
|
+
} else if (typeof(value) === "string") {
|
|
71
|
+
return value;
|
|
72
|
+
} else if (BigNumber.isBigNumber(value)) {
|
|
73
|
+
return value.toString();
|
|
74
|
+
} else if (Array.isArray(value)) {
|
|
75
|
+
return JSON.stringify(value.map((i) => serialize(i)));
|
|
76
|
+
} else if (typeof(value) === "object") {
|
|
77
|
+
const keys = Object.keys(value);
|
|
78
|
+
keys.sort();
|
|
79
|
+
return "{" + keys.map((key) => {
|
|
80
|
+
let v = value[key];
|
|
81
|
+
if (typeof(v) === "function") {
|
|
82
|
+
v = "[function]";
|
|
83
|
+
} else {
|
|
84
|
+
v = serialize(v);
|
|
85
|
+
}
|
|
86
|
+
return JSON.stringify(key) + ":" + v;
|
|
87
|
+
}).join(",") + "}";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
throw new Error("unknown value type: " + typeof(value));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Next request ID to use for emitting debug info
|
|
94
|
+
let nextRid = 1;
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
export interface FallbackProviderConfig {
|
|
98
|
+
// The Provider
|
|
99
|
+
provider: Provider;
|
|
100
|
+
|
|
101
|
+
// The priority to favour this Provider; lower values are used first (higher priority)
|
|
102
|
+
priority?: number;
|
|
103
|
+
|
|
104
|
+
// Timeout before also triggering the next provider; this does not stop
|
|
105
|
+
// this provider and if its result comes back before a quorum is reached
|
|
106
|
+
// it will be incorporated into the vote
|
|
107
|
+
// - lower values will cause more network traffic but may result in a
|
|
108
|
+
// faster result.
|
|
109
|
+
stallTimeout?: number;
|
|
110
|
+
|
|
111
|
+
// How much this provider contributes to the quorum; sometimes a specific
|
|
112
|
+
// provider may be more reliable or trustworthy than others, but usually
|
|
113
|
+
// this should be left as the default
|
|
114
|
+
weight?: number;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
// A Staller is used to provide a delay to give a Provider a chance to response
|
|
118
|
+
// before asking the next Provider to try.
|
|
119
|
+
type Staller = {
|
|
120
|
+
wait: (func: () => void) => Promise<void>
|
|
121
|
+
getPromise: () => Promise<void>,
|
|
122
|
+
cancel: () => void
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
function stall(duration: number): Staller {
|
|
126
|
+
let cancel: () => void = null;
|
|
127
|
+
|
|
128
|
+
let timer: NodeJS.Timer = null;
|
|
129
|
+
let promise = <Promise<void>>(new Promise((resolve) => {
|
|
130
|
+
cancel = function() {
|
|
131
|
+
if (timer) {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
timer = null;
|
|
134
|
+
}
|
|
135
|
+
resolve();
|
|
136
|
+
}
|
|
137
|
+
timer = setTimeout(cancel, duration);
|
|
138
|
+
}));
|
|
139
|
+
|
|
140
|
+
const wait = (func: () => void) => {
|
|
141
|
+
promise = promise.then(func);
|
|
142
|
+
return promise;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function getPromise(): Promise<void> {
|
|
146
|
+
return promise;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return { cancel, getPromise, wait };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const ForwardErrors = [
|
|
153
|
+
Logger.errors.CALL_EXCEPTION,
|
|
154
|
+
Logger.errors.INSUFFICIENT_FUNDS,
|
|
155
|
+
Logger.errors.NONCE_EXPIRED,
|
|
156
|
+
Logger.errors.REPLACEMENT_UNDERPRICED,
|
|
157
|
+
Logger.errors.UNPREDICTABLE_GAS_LIMIT
|
|
158
|
+
];
|
|
159
|
+
|
|
160
|
+
const ForwardProperties = [
|
|
161
|
+
"address",
|
|
162
|
+
"args",
|
|
163
|
+
"errorArgs",
|
|
164
|
+
"errorSignature",
|
|
165
|
+
"method",
|
|
166
|
+
"transaction",
|
|
167
|
+
];
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
// @TODO: Make this an object with staller and cancel built-in
|
|
171
|
+
interface RunningConfig extends FallbackProviderConfig {
|
|
172
|
+
start?: number;
|
|
173
|
+
done?: boolean;
|
|
174
|
+
cancelled?: boolean;
|
|
175
|
+
runner?: Promise<any>;
|
|
176
|
+
staller?: Staller;
|
|
177
|
+
result?: any;
|
|
178
|
+
error?: Error;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
function exposeDebugConfig(config: RunningConfig, now?: number): any {
|
|
182
|
+
const result: any = {
|
|
183
|
+
weight: config.weight
|
|
184
|
+
};
|
|
185
|
+
Object.defineProperty(result, "provider", { get: () => config.provider });
|
|
186
|
+
if (config.start) { result.start = config.start; }
|
|
187
|
+
if (now) { result.duration = (now - config.start); }
|
|
188
|
+
if (config.done) {
|
|
189
|
+
if (config.error) {
|
|
190
|
+
result.error = config.error;
|
|
191
|
+
} else {
|
|
192
|
+
result.result = config.result || null;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function normalizedTally(normalize: (value: any) => string, quorum: number): (configs: Array<RunningConfig>) => any {
|
|
199
|
+
return function(configs: Array<RunningConfig>): any {
|
|
200
|
+
|
|
201
|
+
// Count the votes for each result
|
|
202
|
+
const tally: { [ key: string]: { count: number, result: any } } = { };
|
|
203
|
+
configs.forEach((c) => {
|
|
204
|
+
const value = normalize(c.result);
|
|
205
|
+
if (!tally[value]) { tally[value] = { count: 0, result: c.result }; }
|
|
206
|
+
tally[value].count++;
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Check for a quorum on any given result
|
|
210
|
+
const keys = Object.keys(tally);
|
|
211
|
+
for (let i = 0; i < keys.length; i++) {
|
|
212
|
+
const check = tally[keys[i]];
|
|
213
|
+
if (check.count >= quorum) {
|
|
214
|
+
return check.result;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// No quroum
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function getProcessFunc(provider: FallbackProvider, method: string, params: { [ key: string ]: any }): (configs: Array<RunningConfig>) => any {
|
|
223
|
+
|
|
224
|
+
let normalize = serialize;
|
|
225
|
+
|
|
226
|
+
switch (method) {
|
|
227
|
+
case "getBlockNumber":
|
|
228
|
+
// Return the median value, unless there is (median + 1) is also
|
|
229
|
+
// present, in which case that is probably true and the median
|
|
230
|
+
// is going to be stale soon. In the event of a malicious node,
|
|
231
|
+
// the lie will be true soon enough.
|
|
232
|
+
return function(configs: Array<RunningConfig>): number {
|
|
233
|
+
const values = configs.map((c) => c.result);
|
|
234
|
+
|
|
235
|
+
// Get the median block number
|
|
236
|
+
let blockNumber = median(configs.map((c) => c.result), 2);
|
|
237
|
+
if (blockNumber == null) { return undefined; }
|
|
238
|
+
|
|
239
|
+
blockNumber = Math.ceil(blockNumber);
|
|
240
|
+
|
|
241
|
+
// If the next block height is present, its prolly safe to use
|
|
242
|
+
if (values.indexOf(blockNumber + 1) >= 0) { blockNumber++; }
|
|
243
|
+
|
|
244
|
+
// Don't ever roll back the blockNumber
|
|
245
|
+
if (blockNumber >= provider._highestBlockNumber) {
|
|
246
|
+
provider._highestBlockNumber = blockNumber;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return provider._highestBlockNumber;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
case "getGasPrice":
|
|
253
|
+
// Return the middle (round index up) value, similar to median
|
|
254
|
+
// but do not average even entries and choose the higher.
|
|
255
|
+
// Malicious actors must compromise 50% of the nodes to lie.
|
|
256
|
+
return function(configs: Array<RunningConfig>): BigNumber {
|
|
257
|
+
const values = configs.map((c) => c.result);
|
|
258
|
+
values.sort();
|
|
259
|
+
return values[Math.floor(values.length / 2)];
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
case "getEtherPrice":
|
|
263
|
+
// Returns the median price. Malicious actors must compromise at
|
|
264
|
+
// least 50% of the nodes to lie (in a meaningful way).
|
|
265
|
+
return function(configs: Array<RunningConfig>): number {
|
|
266
|
+
return median(configs.map((c) => c.result));
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// No additional normalizing required; serialize is enough
|
|
270
|
+
case "getBalance":
|
|
271
|
+
case "getTransactionCount":
|
|
272
|
+
case "getCode":
|
|
273
|
+
case "getStorageAt":
|
|
274
|
+
case "call":
|
|
275
|
+
case "estimateGas":
|
|
276
|
+
case "getLogs":
|
|
277
|
+
break;
|
|
278
|
+
|
|
279
|
+
// We drop the confirmations from transactions as it is approximate
|
|
280
|
+
case "getTransaction":
|
|
281
|
+
case "getTransactionReceipt":
|
|
282
|
+
normalize = function(tx: any): string {
|
|
283
|
+
if (tx == null) { return null; }
|
|
284
|
+
|
|
285
|
+
tx = shallowCopy(tx);
|
|
286
|
+
tx.confirmations = -1;
|
|
287
|
+
return serialize(tx);
|
|
288
|
+
}
|
|
289
|
+
break;
|
|
290
|
+
|
|
291
|
+
// We drop the confirmations from transactions as it is approximate
|
|
292
|
+
case "getBlock":
|
|
293
|
+
// We drop the confirmations from transactions as it is approximate
|
|
294
|
+
if (params.includeTransactions) {
|
|
295
|
+
normalize = function(block: BlockWithTransactions): string {
|
|
296
|
+
if (block == null) { return null; }
|
|
297
|
+
|
|
298
|
+
block = shallowCopy(block);
|
|
299
|
+
block.transactions = block.transactions.map((tx) => {
|
|
300
|
+
tx = shallowCopy(tx);
|
|
301
|
+
tx.confirmations = -1;
|
|
302
|
+
return tx;
|
|
303
|
+
});
|
|
304
|
+
return serialize(block);
|
|
305
|
+
};
|
|
306
|
+
} else {
|
|
307
|
+
normalize = function(block: Block): string {
|
|
308
|
+
if (block == null) { return null; }
|
|
309
|
+
return serialize(block);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
break;
|
|
313
|
+
|
|
314
|
+
default:
|
|
315
|
+
throw new Error("unknown method: " + method);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Return the result if and only if the expected quorum is
|
|
319
|
+
// satisfied and agreed upon for the final result.
|
|
320
|
+
return normalizedTally(normalize, provider.quorum);
|
|
321
|
+
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// If we are doing a blockTag query, we need to make sure the backend is
|
|
325
|
+
// caught up to the FallbackProvider, before sending a request to it.
|
|
326
|
+
async function waitForSync(config: RunningConfig, blockNumber: number): Promise<BaseProvider> {
|
|
327
|
+
const provider = <BaseProvider>(config.provider);
|
|
328
|
+
|
|
329
|
+
if ((provider.blockNumber != null && provider.blockNumber >= blockNumber) || blockNumber === -1) {
|
|
330
|
+
return provider;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return poll(() => {
|
|
334
|
+
return new Promise((resolve, reject) => {
|
|
335
|
+
setTimeout(function() {
|
|
336
|
+
|
|
337
|
+
// We are synced
|
|
338
|
+
if (provider.blockNumber >= blockNumber) { return resolve(provider); }
|
|
339
|
+
|
|
340
|
+
// We're done; just quit
|
|
341
|
+
if (config.cancelled) { return resolve(null); }
|
|
342
|
+
|
|
343
|
+
// Try again, next block
|
|
344
|
+
return resolve(undefined);
|
|
345
|
+
}, 0);
|
|
346
|
+
});
|
|
347
|
+
}, { oncePoll: provider });
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function getRunner(config: RunningConfig, currentBlockNumber: number, method: string, params: { [ key: string]: any }): Promise<any> {
|
|
351
|
+
let provider = config.provider;
|
|
352
|
+
|
|
353
|
+
switch (method) {
|
|
354
|
+
case "getBlockNumber":
|
|
355
|
+
case "getGasPrice":
|
|
356
|
+
return provider[method]();
|
|
357
|
+
case "getEtherPrice":
|
|
358
|
+
if ((<any>provider).getEtherPrice) {
|
|
359
|
+
return (<any>provider).getEtherPrice();
|
|
360
|
+
}
|
|
361
|
+
break;
|
|
362
|
+
case "getBalance":
|
|
363
|
+
case "getTransactionCount":
|
|
364
|
+
case "getCode":
|
|
365
|
+
if (params.blockTag && isHexString(params.blockTag)) {
|
|
366
|
+
provider = await waitForSync(config, currentBlockNumber)
|
|
367
|
+
}
|
|
368
|
+
return provider[method](params.address, params.blockTag || "latest");
|
|
369
|
+
case "getStorageAt":
|
|
370
|
+
if (params.blockTag && isHexString(params.blockTag)) {
|
|
371
|
+
provider = await waitForSync(config, currentBlockNumber)
|
|
372
|
+
}
|
|
373
|
+
return provider.getStorageAt(params.address, params.position, params.blockTag || "latest");
|
|
374
|
+
case "getBlock":
|
|
375
|
+
if (params.blockTag && isHexString(params.blockTag)) {
|
|
376
|
+
provider = await waitForSync(config, currentBlockNumber)
|
|
377
|
+
}
|
|
378
|
+
return provider[(params.includeTransactions ? "getBlockWithTransactions": "getBlock")](params.blockTag || params.blockHash);
|
|
379
|
+
case "call":
|
|
380
|
+
case "estimateGas":
|
|
381
|
+
if (params.blockTag && isHexString(params.blockTag)) {
|
|
382
|
+
provider = await waitForSync(config, currentBlockNumber)
|
|
383
|
+
}
|
|
384
|
+
if (method === "call" && params.blockTag) {
|
|
385
|
+
return provider[method](params.transaction, params.blockTag);
|
|
386
|
+
}
|
|
387
|
+
return provider[method](params.transaction);
|
|
388
|
+
case "getTransaction":
|
|
389
|
+
case "getTransactionReceipt":
|
|
390
|
+
return provider[method](params.transactionHash);
|
|
391
|
+
case "getLogs": {
|
|
392
|
+
let filter = params.filter;
|
|
393
|
+
if ((filter.fromBlock && isHexString(filter.fromBlock)) || (filter.toBlock && isHexString(filter.toBlock))) {
|
|
394
|
+
provider = await waitForSync(config, currentBlockNumber)
|
|
395
|
+
}
|
|
396
|
+
return provider.getLogs(filter);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return logger.throwError("unknown method error", Logger.errors.UNKNOWN_ERROR, {
|
|
401
|
+
method: method,
|
|
402
|
+
params: params
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export class FallbackProvider extends BaseProvider {
|
|
407
|
+
readonly providerConfigs: ReadonlyArray<FallbackProviderConfig>;
|
|
408
|
+
readonly quorum: number;
|
|
409
|
+
|
|
410
|
+
// Due to the highly asyncronous nature of the blockchain, we need
|
|
411
|
+
// to make sure we never unroll the blockNumber due to our random
|
|
412
|
+
// sample of backends
|
|
413
|
+
_highestBlockNumber: number;
|
|
414
|
+
|
|
415
|
+
constructor(providers: Array<Provider | FallbackProviderConfig>, quorum?: number) {
|
|
416
|
+
if (providers.length === 0) {
|
|
417
|
+
logger.throwArgumentError("missing providers", "providers", providers);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const providerConfigs: Array<FallbackProviderConfig> = providers.map((configOrProvider, index) => {
|
|
421
|
+
if (Provider.isProvider(configOrProvider)) {
|
|
422
|
+
const stallTimeout = isCommunityResource(configOrProvider) ? 2000: 750;
|
|
423
|
+
const priority = 1;
|
|
424
|
+
return Object.freeze({ provider: configOrProvider, weight: 1, stallTimeout, priority });
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const config: FallbackProviderConfig = shallowCopy(configOrProvider);
|
|
428
|
+
|
|
429
|
+
if (config.priority == null) { config.priority = 1; }
|
|
430
|
+
if (config.stallTimeout == null) {
|
|
431
|
+
config.stallTimeout = isCommunityResource(configOrProvider) ? 2000: 750;
|
|
432
|
+
}
|
|
433
|
+
if (config.weight == null) { config.weight = 1; }
|
|
434
|
+
|
|
435
|
+
const weight = config.weight;
|
|
436
|
+
if (weight % 1 || weight > 512 || weight < 1) {
|
|
437
|
+
logger.throwArgumentError("invalid weight; must be integer in [1, 512]", `providers[${ index }].weight`, weight);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
return Object.freeze(config);
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
const total = providerConfigs.reduce((accum, c) => (accum + c.weight), 0);
|
|
444
|
+
|
|
445
|
+
if (quorum == null) {
|
|
446
|
+
quorum = total / 2;
|
|
447
|
+
} else if (quorum > total) {
|
|
448
|
+
logger.throwArgumentError("quorum will always fail; larger than total weight", "quorum", quorum);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// Are all providers' networks are known
|
|
452
|
+
let networkOrReady: Network | Promise<Network> = checkNetworks(providerConfigs.map((c) => (<any>(c.provider)).network));
|
|
453
|
+
|
|
454
|
+
// Not all networks are known; we must stall
|
|
455
|
+
if (networkOrReady == null) {
|
|
456
|
+
networkOrReady = new Promise((resolve, reject) => {
|
|
457
|
+
setTimeout(() => {
|
|
458
|
+
this.detectNetwork().then(resolve, reject);
|
|
459
|
+
}, 0);
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
super(networkOrReady);
|
|
464
|
+
|
|
465
|
+
// Preserve a copy, so we do not get mutated
|
|
466
|
+
defineReadOnly(this, "providerConfigs", Object.freeze(providerConfigs));
|
|
467
|
+
defineReadOnly(this, "quorum", quorum);
|
|
468
|
+
|
|
469
|
+
this._highestBlockNumber = -1;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async detectNetwork(): Promise<Network> {
|
|
473
|
+
const networks = await Promise.all(this.providerConfigs.map((c) => c.provider.getNetwork()));
|
|
474
|
+
return checkNetworks(networks);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async perform(method: string, params: { [name: string]: any }): Promise<any> {
|
|
478
|
+
// Sending transactions is special; always broadcast it to all backends
|
|
479
|
+
if (method === "sendTransaction") {
|
|
480
|
+
const results: Array<string | Error> = await Promise.all(this.providerConfigs.map((c) => {
|
|
481
|
+
return c.provider.sendTransaction(params.signedTransaction).then((result) => {
|
|
482
|
+
return result.hash;
|
|
483
|
+
}, (error) => {
|
|
484
|
+
return error;
|
|
485
|
+
});
|
|
486
|
+
}));
|
|
487
|
+
|
|
488
|
+
// Any success is good enough (other errors are likely "already seen" errors
|
|
489
|
+
for (let i = 0; i < results.length; i++) {
|
|
490
|
+
const result = results[i];
|
|
491
|
+
if (typeof(result) === "string") { return result; }
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// They were all an error; pick the first error
|
|
495
|
+
throw results[0];
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// We need to make sure we are in sync with our backends, so we need
|
|
499
|
+
// to know this before we can make a lot of calls
|
|
500
|
+
if (this._highestBlockNumber === -1 && method !== "getBlockNumber") {
|
|
501
|
+
await this.getBlockNumber();
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const processFunc = getProcessFunc(this, method, params);
|
|
505
|
+
|
|
506
|
+
// Shuffle the providers and then sort them by their priority; we
|
|
507
|
+
// shallowCopy them since we will store the result in them too
|
|
508
|
+
const configs: Array<RunningConfig> = shuffled(this.providerConfigs.map(shallowCopy));
|
|
509
|
+
configs.sort((a, b) => (a.priority - b.priority));
|
|
510
|
+
|
|
511
|
+
const currentBlockNumber = this._highestBlockNumber;
|
|
512
|
+
|
|
513
|
+
let i = 0;
|
|
514
|
+
let first = true;
|
|
515
|
+
while (true) {
|
|
516
|
+
const t0 = now();
|
|
517
|
+
|
|
518
|
+
// Compute the inflight weight (exclude anything past)
|
|
519
|
+
let inflightWeight = configs.filter((c) => (c.runner && ((t0 - c.start) < c.stallTimeout)))
|
|
520
|
+
.reduce((accum, c) => (accum + c.weight), 0);
|
|
521
|
+
|
|
522
|
+
// Start running enough to meet quorum
|
|
523
|
+
while (inflightWeight < this.quorum && i < configs.length) {
|
|
524
|
+
const config = configs[i++];
|
|
525
|
+
|
|
526
|
+
const rid = nextRid++;
|
|
527
|
+
|
|
528
|
+
config.start = now();
|
|
529
|
+
config.staller = stall(config.stallTimeout);
|
|
530
|
+
config.staller.wait(() => { config.staller = null; });
|
|
531
|
+
|
|
532
|
+
config.runner = getRunner(config, currentBlockNumber, method, params).then((result) => {
|
|
533
|
+
config.done = true;
|
|
534
|
+
config.result = result;
|
|
535
|
+
|
|
536
|
+
if (this.listenerCount("debug")) {
|
|
537
|
+
this.emit("debug", {
|
|
538
|
+
action: "request",
|
|
539
|
+
rid: rid,
|
|
540
|
+
backend: exposeDebugConfig(config, now()),
|
|
541
|
+
request: { method: method, params: deepCopy(params) },
|
|
542
|
+
provider: this
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
}, (error) => {
|
|
547
|
+
config.done = true;
|
|
548
|
+
config.error = error;
|
|
549
|
+
|
|
550
|
+
if (this.listenerCount("debug")) {
|
|
551
|
+
this.emit("debug", {
|
|
552
|
+
action: "request",
|
|
553
|
+
rid: rid,
|
|
554
|
+
backend: exposeDebugConfig(config, now()),
|
|
555
|
+
request: { method: method, params: deepCopy(params) },
|
|
556
|
+
provider: this
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
if (this.listenerCount("debug")) {
|
|
562
|
+
this.emit("debug", {
|
|
563
|
+
action: "request",
|
|
564
|
+
rid: rid,
|
|
565
|
+
backend: exposeDebugConfig(config, null),
|
|
566
|
+
request: { method: method, params: deepCopy(params) },
|
|
567
|
+
provider: this
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
inflightWeight += config.weight;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// Wait for anything meaningful to finish or stall out
|
|
575
|
+
const waiting: Array<Promise<any>> = [ ];
|
|
576
|
+
configs.forEach((c) => {
|
|
577
|
+
if (c.done || !c.runner) { return; }
|
|
578
|
+
waiting.push(c.runner);
|
|
579
|
+
if (c.staller) { waiting.push(c.staller.getPromise()); }
|
|
580
|
+
});
|
|
581
|
+
|
|
582
|
+
if (waiting.length) { await Promise.race(waiting); }
|
|
583
|
+
|
|
584
|
+
// Check the quorum and process the results; the process function
|
|
585
|
+
// may additionally decide the quorum is not met
|
|
586
|
+
const results = configs.filter((c) => (c.done && c.error == null));
|
|
587
|
+
if (results.length >= this.quorum) {
|
|
588
|
+
const result = processFunc(results);
|
|
589
|
+
if (result !== undefined) {
|
|
590
|
+
// Shut down any stallers
|
|
591
|
+
configs.forEach(c => {
|
|
592
|
+
if (c.staller) { c.staller.cancel(); }
|
|
593
|
+
c.cancelled = true;
|
|
594
|
+
});
|
|
595
|
+
return result;
|
|
596
|
+
}
|
|
597
|
+
if (!first) { await stall(100).getPromise(); }
|
|
598
|
+
first = false;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// No result, check for errors that should be forwarded
|
|
602
|
+
const errors = configs.reduce((accum, c) => {
|
|
603
|
+
if (!c.done || c.error == null) { return accum; }
|
|
604
|
+
|
|
605
|
+
const code = (<any>(c.error)).code;
|
|
606
|
+
if (ForwardErrors.indexOf(code) >= 0) {
|
|
607
|
+
if (!accum[code]) { accum[code] = { error: c.error, weight: 0 }; }
|
|
608
|
+
accum[code].weight += c.weight;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
return accum;
|
|
612
|
+
}, <{ [ code: string ]: { error: Error, weight: number } }>({ }));
|
|
613
|
+
|
|
614
|
+
Object.keys(errors).forEach((errorCode: string) => {
|
|
615
|
+
const tally = errors[errorCode];
|
|
616
|
+
if (tally.weight < this.quorum) { return; }
|
|
617
|
+
|
|
618
|
+
// Shut down any stallers
|
|
619
|
+
configs.forEach(c => {
|
|
620
|
+
if (c.staller) { c.staller.cancel(); }
|
|
621
|
+
c.cancelled = true;
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
const e = <any>(tally.error);
|
|
625
|
+
|
|
626
|
+
const props: { [ name: string ]: any } = { };
|
|
627
|
+
ForwardProperties.forEach((name) => {
|
|
628
|
+
if (e[name] == null) { return; }
|
|
629
|
+
props[name] = e[name];
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
logger.throwError(e.reason || e.message, <any>errorCode, props);
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
// All configs have run to completion; we will never get more data
|
|
636
|
+
if (configs.filter((c) => !c.done).length === 0) { break; }
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// Shut down any stallers; shouldn't be any
|
|
640
|
+
configs.forEach(c => {
|
|
641
|
+
if (c.staller) { c.staller.cancel(); }
|
|
642
|
+
c.cancelled = true;
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
return logger.throwError("failed to meet quorum", Logger.errors.SERVER_ERROR, {
|
|
646
|
+
method: method,
|
|
647
|
+
params: params,
|
|
648
|
+
//results: configs.map((c) => c.result),
|
|
649
|
+
//errors: configs.map((c) => c.error),
|
|
650
|
+
results: configs.map((c) => exposeDebugConfig(c)),
|
|
651
|
+
provider: this
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
}
|