1 | import { deepCopy } from "@ethersproject/properties";
|
2 | import { fetchJson } from "@ethersproject/web";
|
3 | import { JsonRpcProvider } from "./json-rpc-provider";
|
4 |
|
5 | export class JsonRpcBatchProvider extends JsonRpcProvider {
|
6 | send(method, params) {
|
7 | const request = {
|
8 | method: method,
|
9 | params: params,
|
10 | id: (this._nextId++),
|
11 | jsonrpc: "2.0"
|
12 | };
|
13 | if (this._pendingBatch == null) {
|
14 | this._pendingBatch = [];
|
15 | }
|
16 | const inflightRequest = { request, resolve: null, reject: null };
|
17 | const promise = new Promise((resolve, reject) => {
|
18 | inflightRequest.resolve = resolve;
|
19 | inflightRequest.reject = reject;
|
20 | });
|
21 | this._pendingBatch.push(inflightRequest);
|
22 | if (!this._pendingBatchAggregator) {
|
23 |
|
24 | this._pendingBatchAggregator = setTimeout(() => {
|
25 |
|
26 |
|
27 | const batch = this._pendingBatch;
|
28 | this._pendingBatch = null;
|
29 | this._pendingBatchAggregator = null;
|
30 |
|
31 | const request = batch.map((inflight) => inflight.request);
|
32 | this.emit("debug", {
|
33 | action: "requestBatch",
|
34 | request: deepCopy(request),
|
35 | provider: this
|
36 | });
|
37 | return fetchJson(this.connection, JSON.stringify(request)).then((result) => {
|
38 | this.emit("debug", {
|
39 | action: "response",
|
40 | request: request,
|
41 | response: result,
|
42 | provider: this
|
43 | });
|
44 |
|
45 |
|
46 | batch.forEach((inflightRequest, index) => {
|
47 | const payload = result[index];
|
48 | if (payload.error) {
|
49 | const error = new Error(payload.error.message);
|
50 | error.code = payload.error.code;
|
51 | error.data = payload.error.data;
|
52 | inflightRequest.reject(error);
|
53 | }
|
54 | else {
|
55 | inflightRequest.resolve(payload.result);
|
56 | }
|
57 | });
|
58 | }, (error) => {
|
59 | this.emit("debug", {
|
60 | action: "response",
|
61 | error: error,
|
62 | request: request,
|
63 | provider: this
|
64 | });
|
65 | batch.forEach((inflightRequest) => {
|
66 | inflightRequest.reject(error);
|
67 | });
|
68 | });
|
69 | }, 10);
|
70 | }
|
71 | return promise;
|
72 | }
|
73 | }
|
74 |
|
\ | No newline at end of file |