UNPKG

3.13 kBJavaScriptView Raw
1import { deepCopy } from "@ethersproject/properties";
2import { fetchJson } from "@ethersproject/web";
3import { JsonRpcProvider } from "./json-rpc-provider";
4// Experimental
5export 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 // Schedule batch for next event loop + short duration
24 this._pendingBatchAggregator = setTimeout(() => {
25 // Get teh current batch and clear it, so new requests
26 // go into the next batch
27 const batch = this._pendingBatch;
28 this._pendingBatch = null;
29 this._pendingBatchAggregator = null;
30 // Get the request as an array of requests
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 // For each result, feed it to the correct Promise, depending
45 // on whether it was a success or error
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//# sourceMappingURL=json-rpc-batch-provider.js.map
\No newline at end of file