@metamask-previews/network-controller 22.2.1-preview-03c4c9c3 → 22.2.1-preview-86cafc23
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/CHANGELOG.md +9 -25
- package/dist/NetworkController.cjs +52 -19
- package/dist/NetworkController.cjs.map +1 -1
- package/dist/NetworkController.d.cts +8 -72
- package/dist/NetworkController.d.cts.map +1 -1
- package/dist/NetworkController.d.mts +8 -72
- package/dist/NetworkController.d.mts.map +1 -1
- package/dist/NetworkController.mjs +53 -20
- package/dist/NetworkController.mjs.map +1 -1
- package/dist/create-auto-managed-network-client.cjs +13 -12
- package/dist/create-auto-managed-network-client.cjs.map +1 -1
- package/dist/create-auto-managed-network-client.d.cts +7 -8
- package/dist/create-auto-managed-network-client.d.cts.map +1 -1
- package/dist/create-auto-managed-network-client.d.mts +7 -8
- package/dist/create-auto-managed-network-client.d.mts.map +1 -1
- package/dist/create-auto-managed-network-client.mjs +13 -12
- package/dist/create-auto-managed-network-client.mjs.map +1 -1
- package/dist/create-network-client.cjs +10 -33
- package/dist/create-network-client.cjs.map +1 -1
- package/dist/create-network-client.d.cts +7 -9
- package/dist/create-network-client.d.cts.map +1 -1
- package/dist/create-network-client.d.mts +7 -9
- package/dist/create-network-client.d.mts.map +1 -1
- package/dist/create-network-client.mjs +10 -33
- package/dist/create-network-client.mjs.map +1 -1
- package/dist/index.cjs +1 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -3
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +0 -1
- package/dist/index.mjs.map +1 -1
- package/dist/rpc-service/abstract-rpc-service.cjs.map +1 -1
- package/dist/rpc-service/abstract-rpc-service.d.cts +39 -5
- package/dist/rpc-service/abstract-rpc-service.d.cts.map +1 -1
- package/dist/rpc-service/abstract-rpc-service.d.mts +39 -5
- package/dist/rpc-service/abstract-rpc-service.d.mts.map +1 -1
- package/dist/rpc-service/abstract-rpc-service.mjs.map +1 -1
- package/dist/rpc-service/rpc-service-chain.cjs +23 -10
- package/dist/rpc-service/rpc-service-chain.cjs.map +1 -1
- package/dist/rpc-service/rpc-service-chain.d.cts +35 -10
- package/dist/rpc-service/rpc-service-chain.d.cts.map +1 -1
- package/dist/rpc-service/rpc-service-chain.d.mts +35 -10
- package/dist/rpc-service/rpc-service-chain.d.mts.map +1 -1
- package/dist/rpc-service/rpc-service-chain.mjs +23 -10
- package/dist/rpc-service/rpc-service-chain.mjs.map +1 -1
- package/dist/rpc-service/rpc-service.cjs +31 -34
- package/dist/rpc-service/rpc-service.cjs.map +1 -1
- package/dist/rpc-service/rpc-service.d.cts +23 -56
- package/dist/rpc-service/rpc-service.d.cts.map +1 -1
- package/dist/rpc-service/rpc-service.d.mts +23 -56
- package/dist/rpc-service/rpc-service.d.mts.map +1 -1
- package/dist/rpc-service/rpc-service.mjs +30 -33
- package/dist/rpc-service/rpc-service.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/rpc-service/rpc-service-requestable.cjs +0 -3
- package/dist/rpc-service/rpc-service-requestable.cjs.map +0 -1
- package/dist/rpc-service/rpc-service-requestable.d.cts +0 -47
- package/dist/rpc-service/rpc-service-requestable.d.cts.map +0 -1
- package/dist/rpc-service/rpc-service-requestable.d.mts +0 -47
- package/dist/rpc-service/rpc-service-requestable.d.mts.map +0 -1
- package/dist/rpc-service/rpc-service-requestable.mjs +0 -2
- package/dist/rpc-service/rpc-service-requestable.mjs.map +0 -1
|
@@ -13,22 +13,33 @@ var _RpcServiceChain_instances, _RpcServiceChain_services, _RpcServiceChain_buil
|
|
|
13
13
|
import { RpcService } from "./rpc-service.mjs";
|
|
14
14
|
/**
|
|
15
15
|
* This class constructs a chain of RpcService objects which represent a
|
|
16
|
-
* particular network. The first object in the chain is intended to be the
|
|
17
|
-
*
|
|
18
|
-
* failovers.
|
|
16
|
+
* particular network. The first object in the chain is intended to be the primary
|
|
17
|
+
* way of reaching the network and the remaining objects are used as failovers.
|
|
19
18
|
*/
|
|
20
19
|
export class RpcServiceChain {
|
|
21
20
|
/**
|
|
22
21
|
* Constructs a new RpcServiceChain object.
|
|
23
22
|
*
|
|
24
|
-
* @param
|
|
25
|
-
*
|
|
26
|
-
*
|
|
23
|
+
* @param args - The arguments.
|
|
24
|
+
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
25
|
+
* If your JavaScript environment supports `fetch` natively, you'll probably
|
|
26
|
+
* want to pass that; otherwise you can pass an equivalent (such as `fetch`
|
|
27
|
+
* via `node-fetch`).
|
|
28
|
+
* @param args.btoa - A function that can be used to convert a binary string
|
|
29
|
+
* into base-64. Used to encode authorization credentials.
|
|
30
|
+
* @param args.serviceConfigurations - The options for the RPC services that
|
|
31
|
+
* you want to construct. This class takes a set of configuration objects and
|
|
32
|
+
* not literal `RpcService`s to account for the possibility that we may want
|
|
33
|
+
* to send request headers to official Infura endpoints and not failovers.
|
|
27
34
|
*/
|
|
28
|
-
constructor(
|
|
35
|
+
constructor({ fetch: givenFetch, btoa: givenBtoa, serviceConfigurations, }) {
|
|
29
36
|
_RpcServiceChain_instances.add(this);
|
|
30
37
|
_RpcServiceChain_services.set(this, void 0);
|
|
31
|
-
__classPrivateFieldSet(this, _RpcServiceChain_services, __classPrivateFieldGet(this, _RpcServiceChain_instances, "m", _RpcServiceChain_buildRpcServiceChain).call(this,
|
|
38
|
+
__classPrivateFieldSet(this, _RpcServiceChain_services, __classPrivateFieldGet(this, _RpcServiceChain_instances, "m", _RpcServiceChain_buildRpcServiceChain).call(this, {
|
|
39
|
+
serviceConfigurations,
|
|
40
|
+
fetch: givenFetch,
|
|
41
|
+
btoa: givenBtoa,
|
|
42
|
+
}), "f");
|
|
32
43
|
}
|
|
33
44
|
/**
|
|
34
45
|
* Listens for when any of the RPC services retry a request.
|
|
@@ -77,12 +88,14 @@ export class RpcServiceChain {
|
|
|
77
88
|
return __classPrivateFieldGet(this, _RpcServiceChain_services, "f")[0].request(jsonRpcRequest, fetchOptions);
|
|
78
89
|
}
|
|
79
90
|
}
|
|
80
|
-
_RpcServiceChain_services = new WeakMap(), _RpcServiceChain_instances = new WeakSet(), _RpcServiceChain_buildRpcServiceChain = function _RpcServiceChain_buildRpcServiceChain(
|
|
81
|
-
return [...
|
|
91
|
+
_RpcServiceChain_services = new WeakMap(), _RpcServiceChain_instances = new WeakSet(), _RpcServiceChain_buildRpcServiceChain = function _RpcServiceChain_buildRpcServiceChain({ serviceConfigurations, fetch: givenFetch, btoa: givenBtoa, }) {
|
|
92
|
+
return [...serviceConfigurations]
|
|
82
93
|
.reverse()
|
|
83
94
|
.reduce((workingServices, serviceConfiguration, index) => {
|
|
84
95
|
const failoverService = index > 0 ? workingServices[0] : undefined;
|
|
85
96
|
const service = new RpcService({
|
|
97
|
+
fetch: givenFetch,
|
|
98
|
+
btoa: givenBtoa,
|
|
86
99
|
...serviceConfiguration,
|
|
87
100
|
failoverService,
|
|
88
101
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-service-chain.mjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service-chain.ts"],"names":[],"mappings":";;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"rpc-service-chain.mjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service-chain.ts"],"names":[],"mappings":";;;;;;;;;;;;AAQA,OAAO,EAAE,UAAU,EAAE,0BAAsB;AAkB3C;;;;GAIG;AACH,MAAM,OAAO,eAAe;IAG1B;;;;;;;;;;;;;;OAcG;IACH,YAAY,EACV,KAAK,EAAE,UAAU,EACjB,IAAI,EAAE,SAAS,EACf,qBAAqB,GAKtB;;QAzBQ,4CAAwB;QA0B/B,uBAAA,IAAI,6BAAa,uBAAA,IAAI,yEAAsB,MAA1B,IAAI,EAAuB;YAC1C,qBAAqB;YACrB,KAAK,EAAE,UAAU;YACjB,IAAI,EAAE,SAAS;SAChB,CAAC,MAAA,CAAC;IACL,CAAC;IAED;;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U,EACjB,IAAI,EAAE,SAAS,GAKhB;IACC,OAAO,CAAC,GAAG,qBAAqB,CAAC;SAC9B,OAAO,EAAE;SACT,MAAM,CAAC,CAAC,eAA6B,EAAE,oBAAoB,EAAE,KAAK,EAAE,EAAE;QACrE,MAAM,eAAe,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACnE,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC;YAC7B,KAAK,EAAE,UAAU;YACjB,IAAI,EAAE,SAAS;YACf,GAAG,oBAAoB;YACvB,eAAe;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,CAAC;IACvC,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport type { AbstractRpcService } from './abstract-rpc-service';\nimport { RpcService } from './rpc-service';\nimport type { FetchOptions } from './shared';\n\n/**\n * The subset of options accepted by the RpcServiceChain constructor which\n * represent a single endpoint.\n */\ntype RpcServiceConfiguration = {\n /**\n * The URL of the endpoint.\n */\n endpointUrl: URL | string;\n /**\n * The options to pass to `fetch` when making the request to the endpoint.\n */\n fetchOptions?: FetchOptions;\n};\n\n/**\n * This class constructs a chain of RpcService objects which represent a\n * particular network. The first object in the chain is intended to be the primary\n * way of reaching the network and the remaining objects are used as failovers.\n */\nexport class RpcServiceChain implements AbstractRpcService {\n readonly #services: RpcService[];\n\n /**\n * Constructs a new RpcServiceChain object.\n *\n * @param args - The arguments.\n * @param args.fetch - A function that can be used to make an HTTP request.\n * If your JavaScript environment supports `fetch` natively, you'll probably\n * want to pass that; otherwise you can pass an equivalent (such as `fetch`\n * via `node-fetch`).\n * @param args.btoa - A function that can be used to convert a binary string\n * into base-64. Used to encode authorization credentials.\n * @param args.serviceConfigurations - The options for the RPC services that\n * you want to construct. This class takes a set of configuration objects and\n * not literal `RpcService`s to account for the possibility that we may want\n * to send request headers to official Infura endpoints and not failovers.\n */\n constructor({\n fetch: givenFetch,\n btoa: givenBtoa,\n serviceConfigurations,\n }: {\n fetch: typeof fetch;\n btoa: typeof btoa;\n serviceConfigurations: RpcServiceConfiguration[];\n }) {\n this.#services = this.#buildRpcServiceChain({\n serviceConfigurations,\n fetch: givenFetch,\n btoa: givenBtoa,\n });\n }\n\n /**\n * Listens for when any of the RPC services retry a request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onRetry(listener: Parameters<RpcService['onRetry']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onRetry(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services retry the request too many times\n * in a row.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onBreak} returns.\n */\n onBreak(listener: Parameters<RpcService['onBreak']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onBreak(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services send a slow request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onDegraded(listener: Parameters<RpcService['onDegraded']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onDegraded(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is specifically designed for `eth_getBlockByNumber`, which\n * can return a `result` of `null` despite an expected `Result` being\n * provided.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params> & { method: 'eth_getBlockByNumber' },\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>>;\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is designed for all RPC methods except for\n * `eth_getBlockByNumber`, which are expected to return a `result` of the\n * expected `Result`.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result>>;\n\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions: FetchOptions = {},\n ): Promise<JsonRpcResponse<Result | null>> {\n return this.#services[0].request(jsonRpcRequest, fetchOptions);\n }\n\n /**\n * Constructs the chain of RPC services. The second RPC service is\n * configured as the failover for the first, the third service is\n * configured as the failover for the second, etc.\n *\n * @param args - The arguments.\n * @param args.serviceConfigurations - The options for the RPC services that\n * you want to construct.\n * @param args.fetch - A function that can be used to make an HTTP request.\n * @param args.btoa - A function that can be used to convert a binary string\n * into base-64. Used to encode authorization credentials.\n * @returns The constructed chain of RPC services.\n */\n #buildRpcServiceChain({\n serviceConfigurations,\n fetch: givenFetch,\n btoa: givenBtoa,\n }: {\n serviceConfigurations: RpcServiceConfiguration[];\n fetch: typeof fetch;\n btoa: typeof btoa;\n }): RpcService[] {\n return [...serviceConfigurations]\n .reverse()\n .reduce((workingServices: RpcService[], serviceConfiguration, index) => {\n const failoverService = index > 0 ? workingServices[0] : undefined;\n const service = new RpcService({\n fetch: givenFetch,\n btoa: givenBtoa,\n ...serviceConfiguration,\n failoverService,\n });\n return [service, ...workingServices];\n }, []);\n }\n}\n"]}
|
|
@@ -13,25 +13,13 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
13
13
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
14
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
15
|
};
|
|
16
|
-
var _RpcService_instances, _RpcService_fetch, _RpcService_fetchOptions, _RpcService_failoverService, _RpcService_policy, _RpcService_getDefaultFetchOptions, _RpcService_getCompleteFetchOptions, _RpcService_executePolicy;
|
|
16
|
+
var _RpcService_instances, _RpcService_fetch, _RpcService_endpointUrl, _RpcService_fetchOptions, _RpcService_failoverService, _RpcService_policy, _RpcService_getDefaultFetchOptions, _RpcService_getCompleteFetchOptions, _RpcService_executePolicy;
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
-
exports.RpcService = exports.
|
|
18
|
+
exports.RpcService = exports.CONNECTION_ERRORS = void 0;
|
|
19
19
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
20
20
|
const rpc_errors_1 = require("@metamask/rpc-errors");
|
|
21
21
|
const utils_1 = require("@metamask/utils");
|
|
22
22
|
const deepmerge_1 = __importDefault(require("deepmerge"));
|
|
23
|
-
/**
|
|
24
|
-
* The maximum number of times that a failing service should be re-run before
|
|
25
|
-
* giving up.
|
|
26
|
-
*/
|
|
27
|
-
exports.DEFAULT_MAX_RETRIES = 4;
|
|
28
|
-
/**
|
|
29
|
-
* The maximum number of times that the service is allowed to fail before
|
|
30
|
-
* pausing further retries. This is set to a value such that if given a
|
|
31
|
-
* service that continually fails, the policy needs to be executed 3 times
|
|
32
|
-
* before further retries are paused.
|
|
33
|
-
*/
|
|
34
|
-
exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + exports.DEFAULT_MAX_RETRIES) * 3;
|
|
35
23
|
/**
|
|
36
24
|
* The list of error messages that represent a failure to connect to the network.
|
|
37
25
|
*
|
|
@@ -108,7 +96,7 @@ function isConnectionError(error) {
|
|
|
108
96
|
return (error.constructor.name === constructorName && pattern.test(message));
|
|
109
97
|
}));
|
|
110
98
|
}
|
|
111
|
-
exports.
|
|
99
|
+
exports.default = isConnectionError;
|
|
112
100
|
/**
|
|
113
101
|
* Determines whether the given error message refers to a Nock error.
|
|
114
102
|
*
|
|
@@ -145,14 +133,31 @@ class RpcService {
|
|
|
145
133
|
/**
|
|
146
134
|
* Constructs a new RpcService object.
|
|
147
135
|
*
|
|
148
|
-
* @param
|
|
136
|
+
* @param args - The arguments.
|
|
137
|
+
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
138
|
+
* If your JavaScript environment supports `fetch` natively, you'll probably
|
|
139
|
+
* want to pass that; otherwise you can pass an equivalent (such as `fetch`
|
|
140
|
+
* via `node-fetch`).
|
|
141
|
+
* @param args.btoa - A function that can be used to convert a binary string
|
|
142
|
+
* into base-64. Used to encode authorization credentials.
|
|
143
|
+
* @param args.endpointUrl - The URL of the RPC endpoint.
|
|
144
|
+
* @param args.fetchOptions - A common set of options that will be used to
|
|
145
|
+
* make every request. Can be overridden on the request level (e.g. to add
|
|
146
|
+
* headers).
|
|
147
|
+
* @param args.failoverService - An RPC service that represents a failover
|
|
148
|
+
* endpoint which will be invoked while the circuit for _this_ service is
|
|
149
|
+
* open.
|
|
149
150
|
*/
|
|
150
|
-
constructor(
|
|
151
|
+
constructor({ fetch: givenFetch, btoa: givenBtoa, endpointUrl, fetchOptions = {}, failoverService, }) {
|
|
151
152
|
_RpcService_instances.add(this);
|
|
152
153
|
/**
|
|
153
154
|
* The function used to make an HTTP request.
|
|
154
155
|
*/
|
|
155
156
|
_RpcService_fetch.set(this, void 0);
|
|
157
|
+
/**
|
|
158
|
+
* The URL of the RPC endpoint.
|
|
159
|
+
*/
|
|
160
|
+
_RpcService_endpointUrl.set(this, void 0);
|
|
156
161
|
/**
|
|
157
162
|
* A common set of options that the request options will extend.
|
|
158
163
|
*/
|
|
@@ -166,15 +171,13 @@ class RpcService {
|
|
|
166
171
|
* The policy that wraps the request.
|
|
167
172
|
*/
|
|
168
173
|
_RpcService_policy.set(this, void 0);
|
|
169
|
-
const { btoa: givenBtoa, endpointUrl, failoverService, fetch: givenFetch, fetchOptions = {}, policyOptions = {}, } = options;
|
|
170
174
|
__classPrivateFieldSet(this, _RpcService_fetch, givenFetch, "f");
|
|
171
|
-
this
|
|
172
|
-
__classPrivateFieldSet(this, _RpcService_fetchOptions, __classPrivateFieldGet(this, _RpcService_instances, "m", _RpcService_getDefaultFetchOptions).call(this, this
|
|
175
|
+
__classPrivateFieldSet(this, _RpcService_endpointUrl, getNormalizedEndpointUrl(endpointUrl), "f");
|
|
176
|
+
__classPrivateFieldSet(this, _RpcService_fetchOptions, __classPrivateFieldGet(this, _RpcService_instances, "m", _RpcService_getDefaultFetchOptions).call(this, __classPrivateFieldGet(this, _RpcService_endpointUrl, "f"), fetchOptions, givenBtoa), "f");
|
|
173
177
|
__classPrivateFieldSet(this, _RpcService_failoverService, failoverService, "f");
|
|
174
178
|
const policy = (0, controller_utils_1.createServicePolicy)({
|
|
175
|
-
maxRetries:
|
|
176
|
-
maxConsecutiveFailures:
|
|
177
|
-
...policyOptions,
|
|
179
|
+
maxRetries: 4,
|
|
180
|
+
maxConsecutiveFailures: 15,
|
|
178
181
|
retryFilterPolicy: (0, controller_utils_1.handleWhen)((error) => {
|
|
179
182
|
return (
|
|
180
183
|
// Ignore errors where the request failed to establish
|
|
@@ -198,7 +201,7 @@ class RpcService {
|
|
|
198
201
|
*/
|
|
199
202
|
onRetry(listener) {
|
|
200
203
|
return __classPrivateFieldGet(this, _RpcService_policy, "f").onRetry((data) => {
|
|
201
|
-
listener({ ...data, endpointUrl: this.
|
|
204
|
+
listener({ ...data, endpointUrl: __classPrivateFieldGet(this, _RpcService_endpointUrl, "f").toString() });
|
|
202
205
|
});
|
|
203
206
|
}
|
|
204
207
|
/**
|
|
@@ -211,13 +214,7 @@ class RpcService {
|
|
|
211
214
|
*/
|
|
212
215
|
onBreak(listener) {
|
|
213
216
|
return __classPrivateFieldGet(this, _RpcService_policy, "f").onBreak((data) => {
|
|
214
|
-
listener({
|
|
215
|
-
...data,
|
|
216
|
-
endpointUrl: this.endpointUrl.toString(),
|
|
217
|
-
failoverEndpointUrl: __classPrivateFieldGet(this, _RpcService_failoverService, "f")
|
|
218
|
-
? __classPrivateFieldGet(this, _RpcService_failoverService, "f").endpointUrl.toString()
|
|
219
|
-
: undefined,
|
|
220
|
-
});
|
|
217
|
+
listener({ ...data, endpointUrl: __classPrivateFieldGet(this, _RpcService_endpointUrl, "f").toString() });
|
|
221
218
|
});
|
|
222
219
|
}
|
|
223
220
|
/**
|
|
@@ -230,7 +227,7 @@ class RpcService {
|
|
|
230
227
|
*/
|
|
231
228
|
onDegraded(listener) {
|
|
232
229
|
return __classPrivateFieldGet(this, _RpcService_policy, "f").onDegraded(() => {
|
|
233
|
-
listener({ endpointUrl: this.
|
|
230
|
+
listener({ endpointUrl: __classPrivateFieldGet(this, _RpcService_endpointUrl, "f").toString() });
|
|
234
231
|
});
|
|
235
232
|
}
|
|
236
233
|
async request(jsonRpcRequest, fetchOptions = {}) {
|
|
@@ -248,7 +245,7 @@ class RpcService {
|
|
|
248
245
|
}
|
|
249
246
|
}
|
|
250
247
|
exports.RpcService = RpcService;
|
|
251
|
-
_RpcService_fetch = new WeakMap(), _RpcService_fetchOptions = new WeakMap(), _RpcService_failoverService = new WeakMap(), _RpcService_policy = new WeakMap(), _RpcService_instances = new WeakSet(), _RpcService_getDefaultFetchOptions = function _RpcService_getDefaultFetchOptions(endpointUrl, fetchOptions, givenBtoa) {
|
|
248
|
+
_RpcService_fetch = new WeakMap(), _RpcService_endpointUrl = new WeakMap(), _RpcService_fetchOptions = new WeakMap(), _RpcService_failoverService = new WeakMap(), _RpcService_policy = new WeakMap(), _RpcService_instances = new WeakSet(), _RpcService_getDefaultFetchOptions = function _RpcService_getDefaultFetchOptions(endpointUrl, fetchOptions, givenBtoa) {
|
|
252
249
|
if (endpointUrl.username && endpointUrl.password) {
|
|
253
250
|
const authString = `${endpointUrl.username}:${endpointUrl.password}`;
|
|
254
251
|
const encodedCredentials = givenBtoa(authString);
|
|
@@ -290,7 +287,7 @@ _RpcService_fetch = new WeakMap(), _RpcService_fetchOptions = new WeakMap(), _Rp
|
|
|
290
287
|
*/
|
|
291
288
|
async function _RpcService_executePolicy(jsonRpcRequest, fetchOptions) {
|
|
292
289
|
return await __classPrivateFieldGet(this, _RpcService_policy, "f").execute(async () => {
|
|
293
|
-
const response = await __classPrivateFieldGet(this, _RpcService_fetch, "f").call(this, this
|
|
290
|
+
const response = await __classPrivateFieldGet(this, _RpcService_fetch, "f").call(this, __classPrivateFieldGet(this, _RpcService_endpointUrl, "f"), fetchOptions);
|
|
294
291
|
if (response.status === 405) {
|
|
295
292
|
throw rpc_errors_1.rpcErrors.methodNotFound();
|
|
296
293
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-service.cjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,iEAIoC;AACpC,qDAAiD;AAEjD,2CAKyB;AACzB,0DAAkC;AAyClC;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;;;GAKG;AACU,QAAA,iBAAiB,GAAG;IAC/B,SAAS;IACT;QACE,eAAe,EAAE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AAI,IAA6B,CAAC;QAClC,IAAI;YACF,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SACzB;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,KAAK,YAAY,WAAW,EAAE;gBAChC,MAAM,sBAAS,CAAC,QAAQ,CAAC;oBACvB,OAAO,EAAE,kDAAkD;oBAC3D,IAAI,EAAE,IAAI;iBACX,CAAC,CAAC;aACJ;iBAAM;gBACL,MAAM,KAAK,CAAC;aACb;SACF;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,MAAM,sBAAS,CAAC,QAAQ,CAAC;gBACvB,OAAO,EAAE,yBAAyB,QAAQ,CAAC,MAAM,GAAG;gBACpD,IAAI,EAAE,IAAI;aACX,CAAC,CAAC;SACJ;QAED,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport {\n CircuitState,\n createServicePolicy,\n handleWhen,\n} from '@metamask/controller-utils';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport {\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcResponse,\n} from '@metamask/utils';\nimport deepmerge from 'deepmerge';\n\nimport type { AbstractRpcService } from './abstract-rpc-service';\nimport type { AddToCockatielEventData, FetchOptions } from './shared';\n\n/**\n * Options for the RpcService constructor.\n */\nexport type RpcServiceOptions = {\n /**\n * A function that can be used to convert a binary string into a\n * base64-encoded ASCII string. Used to encode authorization credentials.\n */\n btoa: typeof btoa;\n /**\n * The URL of the RPC endpoint to hit.\n */\n endpointUrl: URL | string;\n /**\n * An RPC service that represents a failover endpoint which will be invoked\n * while the circuit for _this_ service is open.\n */\n failoverService?: AbstractRpcService;\n /**\n * A function that can be used to make an HTTP request. If your JavaScript\n * environment supports `fetch` natively, you'll probably want to pass that;\n * otherwise you can pass an equivalent (such as `fetch` via `node-fetch`).\n */\n fetch: typeof fetch;\n /**\n * A common set of options that will be used to make every request. Can be\n * overridden on the request level (e.g. to add headers).\n */\n fetchOptions?: FetchOptions;\n /**\n * Options to pass to `createServicePolicy`. Note that `retryFilterPolicy` is\n * not accepted, as it is overwritten. See {@link createServicePolicy}.\n */\n policyOptions?: Omit<CreateServicePolicyOptions, 'retryFilterPolicy'>;\n};\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 4;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The list of error messages that represent a failure to connect to the network.\n *\n * This list was derived from Sindre Sorhus's `is-network-error` package:\n * <https://github.com/sindresorhus/is-network-error/blob/7bbfa8be9482ce1427a21fbff60e3ee1650dd091/index.js>\n */\nexport const CONNECTION_ERRORS = [\n // Chrome\n {\n constructorName: 'TypeError',\n pattern: /network error/u,\n },\n // Chrome\n {\n constructorName: 'TypeError',\n pattern: /Failed to fetch/u,\n },\n // Firefox\n {\n constructorName: 'TypeError',\n pattern: /NetworkError when attempting to fetch resource\\./u,\n },\n // Safari 16\n {\n constructorName: 'TypeError',\n pattern: /The Internet connection appears to be offline\\./u,\n },\n // Safari 17+\n {\n constructorName: 'TypeError',\n pattern: /Load failed/u,\n },\n // `cross-fetch`\n {\n constructorName: 'TypeError',\n pattern: /Network request failed/u,\n },\n // `node-fetch`\n {\n constructorName: 'FetchError',\n pattern: /request to (.+) failed/u,\n },\n // Undici (Node.js)\n {\n constructorName: 'TypeError',\n pattern: /fetch failed/u,\n },\n // Undici (Node.js)\n {\n constructorName: 'TypeError',\n pattern: /terminated/u,\n },\n];\n\n/**\n * Determines whether the given error represents a failure to reach the network\n * after request parameters have been validated.\n *\n * This is somewhat difficult to verify because JavaScript engines (and in\n * some cases libraries) produce slightly different error messages for this\n * particular scenario, and we need to account for this.\n *\n * @param error - The error.\n * @returns True if the error indicates that the network cannot be connected to,\n * and false otherwise.\n */\nexport function isConnectionError(error: unknown) {\n if (!(typeof error === 'object' && error !== null && 'message' in error)) {\n return false;\n }\n\n const { message } = error;\n\n return (\n typeof message === 'string' &&\n !isNockError(message) &&\n CONNECTION_ERRORS.some(({ constructorName, pattern }) => {\n return (\n error.constructor.name === constructorName && pattern.test(message)\n );\n })\n );\n}\n\n/**\n * Determines whether the given error message refers to a Nock error.\n *\n * It's important that if we failed to mock a request in a test, the resulting\n * error does not cause the request to be retried so that we can see it right\n * away.\n *\n * @param message - The error message to test.\n * @returns True if the message indicates a missing Nock mock, false otherwise.\n */\nfunction isNockError(message: string) {\n return message.includes('Nock:');\n}\n\n/**\n * Guarantees a URL, even given a string. This is useful for checking components\n * of that URL.\n *\n * @param endpointUrlOrUrlString - Either a URL object or a string that\n * represents the URL of an endpoint.\n * @returns A URL object.\n */\nfunction getNormalizedEndpointUrl(endpointUrlOrUrlString: URL | string): URL {\n return endpointUrlOrUrlString instanceof URL\n ? endpointUrlOrUrlString\n : new URL(endpointUrlOrUrlString);\n}\n\n/**\n * This class is responsible for making a request to an endpoint that implements\n * the JSON-RPC protocol. It is designed to gracefully handle network and server\n * failures, retrying requests using exponential backoff. It also offers a hook\n * which can used to respond to slow requests.\n */\nexport class RpcService implements AbstractRpcService {\n /**\n * The function used to make an HTTP request.\n */\n readonly #fetch: typeof fetch;\n\n /**\n * The URL of the RPC endpoint.\n */\n readonly endpointUrl: URL;\n\n /**\n * A common set of options that the request options will extend.\n */\n readonly #fetchOptions: FetchOptions;\n\n /**\n * An RPC service that represents a failover endpoint which will be invoked\n * while the circuit for _this_ service is open.\n */\n readonly #failoverService: RpcServiceOptions['failoverService'];\n\n /**\n * The policy that wraps the request.\n */\n readonly #policy: ServicePolicy;\n\n /**\n * Constructs a new RpcService object.\n *\n * @param options - The options. See {@link RpcServiceOptions}.\n */\n constructor(options: RpcServiceOptions) {\n const {\n btoa: givenBtoa,\n endpointUrl,\n failoverService,\n fetch: givenFetch,\n fetchOptions = {},\n policyOptions = {},\n } = options;\n\n this.#fetch = givenFetch;\n this.endpointUrl = getNormalizedEndpointUrl(endpointUrl);\n this.#fetchOptions = this.#getDefaultFetchOptions(\n this.endpointUrl,\n fetchOptions,\n givenBtoa,\n );\n this.#failoverService = failoverService;\n\n const policy = createServicePolicy({\n maxRetries: DEFAULT_MAX_RETRIES,\n maxConsecutiveFailures: DEFAULT_MAX_CONSECUTIVE_FAILURES,\n ...policyOptions,\n retryFilterPolicy: handleWhen((error) => {\n return (\n // Ignore errors where the request failed to establish\n isConnectionError(error) ||\n // Ignore server sent HTML error pages or truncated JSON responses\n error.message.includes('not valid JSON') ||\n // Ignore server overload errors\n error.message.includes('Gateway timeout') ||\n (hasProperty(error, 'code') &&\n (error.code === 'ETIMEDOUT' || error.code === 'ECONNRESET'))\n );\n }),\n });\n this.#policy = policy;\n }\n\n /**\n * Listens for when the RPC service retries the request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link ServicePolicy.onRetry} returns.\n * @see {@link createServicePolicy}\n */\n onRetry(\n listener: AddToCockatielEventData<\n Parameters<ServicePolicy['onRetry']>[0],\n { endpointUrl: string }\n >,\n ) {\n return this.#policy.onRetry((data) => {\n listener({ ...data, endpointUrl: this.endpointUrl.toString() });\n });\n }\n\n /**\n * Listens for when the RPC service retries the request too many times in a\n * row.\n *\n * @param listener - The callback to be called when the circuit is broken.\n * @returns What {@link ServicePolicy.onBreak} returns.\n * @see {@link createServicePolicy}\n */\n onBreak(\n listener: AddToCockatielEventData<\n Parameters<ServicePolicy['onBreak']>[0],\n { endpointUrl: string; failoverEndpointUrl?: string }\n >,\n ) {\n return this.#policy.onBreak((data) => {\n listener({\n ...data,\n endpointUrl: this.endpointUrl.toString(),\n failoverEndpointUrl: this.#failoverService\n ? this.#failoverService.endpointUrl.toString()\n : undefined,\n });\n });\n }\n\n /**\n * Listens for when the policy underlying this RPC service detects a slow\n * request.\n *\n * @param listener - The callback to be called when the request is slow.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n * @see {@link createServicePolicy}\n */\n onDegraded(\n listener: AddToCockatielEventData<\n Parameters<ServicePolicy['onDegraded']>[0],\n { endpointUrl: string }\n >,\n ) {\n return this.#policy.onDegraded(() => {\n listener({ endpointUrl: this.endpointUrl.toString() });\n });\n }\n\n /**\n * Makes a request to the RPC endpoint. If the circuit is open because this\n * request has failed too many times, the request is forwarded to a failover\n * service (if provided).\n *\n * This overload is specifically designed for `eth_getBlockByNumber`, which\n * can return a `result` of `null` despite an expected `Result` being\n * provided.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params> & { method: 'eth_getBlockByNumber' },\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>>;\n\n /**\n * Makes a request to the RPC endpoint. If the circuit is open because this\n * request has failed too many times, the request is forwarded to a failover\n * service (if provided).\n *\n * This overload is designed for all RPC methods except for\n * `eth_getBlockByNumber`, which are expected to return a `result` of the\n * expected `Result`.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result>>;\n\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions: FetchOptions = {},\n ): Promise<JsonRpcResponse<Result | null>> {\n const completeFetchOptions = this.#getCompleteFetchOptions(\n jsonRpcRequest,\n fetchOptions,\n );\n\n try {\n return await this.#executePolicy<Params, Result>(\n jsonRpcRequest,\n completeFetchOptions,\n );\n } catch (error) {\n if (\n this.#policy.circuitBreakerPolicy.state === CircuitState.Open &&\n this.#failoverService !== undefined\n ) {\n return await this.#failoverService.request(\n jsonRpcRequest,\n completeFetchOptions,\n );\n }\n throw error;\n }\n }\n\n /**\n * Constructs a default set of options to `fetch`.\n *\n * If a username and password are present in the URL, they are extracted to an\n * Authorization header.\n *\n * @param endpointUrl - The endpoint URL.\n * @param fetchOptions - The options to `fetch`.\n * @param givenBtoa - An implementation of `btoa`.\n * @returns The default fetch options.\n */\n #getDefaultFetchOptions(\n endpointUrl: URL,\n fetchOptions: FetchOptions,\n givenBtoa: (stringToEncode: string) => string,\n ): FetchOptions {\n if (endpointUrl.username && endpointUrl.password) {\n const authString = `${endpointUrl.username}:${endpointUrl.password}`;\n const encodedCredentials = givenBtoa(authString);\n return deepmerge(fetchOptions, {\n headers: { Authorization: `Basic ${encodedCredentials}` },\n });\n }\n\n return fetchOptions;\n }\n\n /**\n * Constructs a final set of options to pass to `fetch`. Note that the method\n * defaults to `post`, and the JSON-RPC request is automatically JSON-encoded.\n *\n * @param jsonRpcRequest - The JSON-RPC request.\n * @param fetchOptions - Custom `fetch` options.\n * @returns The complete set of `fetch` options.\n */\n #getCompleteFetchOptions<Params extends JsonRpcParams>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions: FetchOptions,\n ): FetchOptions {\n const defaultOptions = {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n };\n const mergedOptions = deepmerge(\n defaultOptions,\n deepmerge(this.#fetchOptions, fetchOptions),\n );\n\n const { id, jsonrpc, method, params } = jsonRpcRequest;\n const body = JSON.stringify({\n id,\n jsonrpc,\n method,\n params,\n });\n\n return { ...mergedOptions, body };\n }\n\n /**\n * Makes the request using the Cockatiel policy that this service creates.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - The options for `fetch`; will be combined with the\n * fetch options passed to the constructor\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async #executePolicy<\n Params extends JsonRpcParams,\n Result extends Json,\n Request extends JsonRpcRequest = JsonRpcRequest<Params>,\n >(\n jsonRpcRequest: Request,\n fetchOptions: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>> {\n return await this.#policy.execute(async () => {\n const response = await this.#fetch(this.endpointUrl, fetchOptions);\n\n if (response.status === 405) {\n throw rpcErrors.methodNotFound();\n }\n\n if (response.status === 429) {\n throw rpcErrors.internal({ message: 'Request is being rate limited.' });\n }\n\n if (response.status === 503 || response.status === 504) {\n throw rpcErrors.internal({\n message:\n 'Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.',\n });\n }\n\n const text = await response.text();\n\n if (\n jsonRpcRequest.method === 'eth_getBlockByNumber' &&\n text === 'Not Found'\n ) {\n return {\n id: jsonRpcRequest.id,\n jsonrpc: jsonRpcRequest.jsonrpc,\n result: null,\n };\n }\n\n // Type annotation: We assume that if this response is valid JSON, it's a\n // valid JSON-RPC response.\n let json: JsonRpcResponse<Result>;\n try {\n json = JSON.parse(text);\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw rpcErrors.internal({\n message: 'Could not parse response as it is not valid JSON',\n data: text,\n });\n } else {\n throw error;\n }\n }\n\n if (!response.ok) {\n throw rpcErrors.internal({\n message: `Non-200 status code: '${response.status}'`,\n data: json,\n });\n }\n\n return json;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpc-service.cjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA,iEAIoC;AACpC,qDAAiD;AAEjD,2CAKyB;AACzB,0DAAkC;AAKlC;;;;;GAKG;AACU,QAAA,iBAAiB,GAAG;IAC/B,SAAS;IACT;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,gBAAgB;KAC1B;IACD,SAAS;IACT;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,kBAAkB;KAC5B;IACD,UAAU;IACV;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,mDAAmD;KAC7D;IACD,YAAY;IACZ;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,kDAAkD;KAC5D;IACD,aAAa;IACb;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,cAAc;KACxB;IACD,gBAAgB;IAChB;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,yBAAyB;KACnC;IACD,eAAe;IACf;QACE,eAAe,EAAE,YAAY;QAC7B,OAAO,EAAE,yBAAyB;KACnC;IACD,mBAAmB;IACnB;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,eAAe;KACzB;IACD,mBAAmB;IACnB;QACE,eAAe,EAAE,WAAW;QAC5B,OAAO,EAAE,aAAa;KACvB;CACF,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,SAAwB,iBAAiB,CAAC,KAAc;IACtD,IAAI,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,SAAS,IAAI,KAAK,CAAC,EAAE;QACxE,OAAO,KAAK,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,CAAC;QAEnC,IACE,cAAc,CAAC,MAAM,KAAK,sBAAsB;YAChD,IAAI,KAAK,WAAW,EACpB;YACA,OAAO;gBACL,EAAE,EAAE,cAAc,CAAC,EAAE;gBACrB,OAAO,EAAE,cAAc,CAAC,OAAO;gBAC/B,MAAM,EAAE,IAAI;aACb,CAAC;SACH;QAED,yEAAyE;QACzE,2BAA2B;QAC3B,IAAI,IAA6B,CAAC;QAClC,IAAI;YACF,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SACzB;QAAC,OAAO,KAAK,EAAE;YACd,IAAI,KAAK,YAAY,WAAW,EAAE;gBAChC,MAAM,sBAAS,CAAC,QAAQ,CAAC;oBACvB,OAAO,EAAE,kDAAkD;oBAC3D,IAAI,EAAE,IAAI;iBACX,CAAC,CAAC;aACJ;iBAAM;gBACL,MAAM,KAAK,CAAC;aACb;SACF;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;YAChB,MAAM,sBAAS,CAAC,QAAQ,CAAC;gBACvB,OAAO,EAAE,yBAAyB,QAAQ,CAAC,MAAM,GAAG;gBACpD,IAAI,EAAE,IAAI;aACX,CAAC,CAAC;SACJ;QAED,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ServicePolicy } from '@metamask/controller-utils';\nimport {\n CircuitState,\n createServicePolicy,\n handleWhen,\n} from '@metamask/controller-utils';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport {\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcResponse,\n} from '@metamask/utils';\nimport deepmerge from 'deepmerge';\n\nimport type { AbstractRpcService } from './abstract-rpc-service';\nimport type { AddToCockatielEventData, FetchOptions } from './shared';\n\n/**\n * The list of error messages that represent a failure to connect to the network.\n *\n * This list was derived from Sindre Sorhus's `is-network-error` package:\n * <https://github.com/sindresorhus/is-network-error/blob/7bbfa8be9482ce1427a21fbff60e3ee1650dd091/index.js>\n */\nexport const CONNECTION_ERRORS = [\n // Chrome\n {\n constructorName: 'TypeError',\n pattern: /network error/u,\n },\n // Chrome\n {\n constructorName: 'TypeError',\n pattern: /Failed to fetch/u,\n },\n // Firefox\n {\n constructorName: 'TypeError',\n pattern: /NetworkError when attempting to fetch resource\\./u,\n },\n // Safari 16\n {\n constructorName: 'TypeError',\n pattern: /The Internet connection appears to be offline\\./u,\n },\n // Safari 17+\n {\n constructorName: 'TypeError',\n pattern: /Load failed/u,\n },\n // `cross-fetch`\n {\n constructorName: 'TypeError',\n pattern: /Network request failed/u,\n },\n // `node-fetch`\n {\n constructorName: 'FetchError',\n pattern: /request to (.+) failed/u,\n },\n // Undici (Node.js)\n {\n constructorName: 'TypeError',\n pattern: /fetch failed/u,\n },\n // Undici (Node.js)\n {\n constructorName: 'TypeError',\n pattern: /terminated/u,\n },\n];\n\n/**\n * Determines whether the given error represents a failure to reach the network\n * after request parameters have been validated.\n *\n * This is somewhat difficult to verify because JavaScript engines (and in\n * some cases libraries) produce slightly different error messages for this\n * particular scenario, and we need to account for this.\n *\n * @param error - The error.\n * @returns True if the error indicates that the network cannot be connected to,\n * and false otherwise.\n */\nexport default function isConnectionError(error: unknown) {\n if (!(typeof error === 'object' && error !== null && 'message' in error)) {\n return false;\n }\n\n const { message } = error;\n\n return (\n typeof message === 'string' &&\n !isNockError(message) &&\n CONNECTION_ERRORS.some(({ constructorName, pattern }) => {\n return (\n error.constructor.name === constructorName && pattern.test(message)\n );\n })\n );\n}\n\n/**\n * Determines whether the given error message refers to a Nock error.\n *\n * It's important that if we failed to mock a request in a test, the resulting\n * error does not cause the request to be retried so that we can see it right\n * away.\n *\n * @param message - The error message to test.\n * @returns True if the message indicates a missing Nock mock, false otherwise.\n */\nfunction isNockError(message: string) {\n return message.includes('Nock:');\n}\n\n/**\n * Guarantees a URL, even given a string. This is useful for checking components\n * of that URL.\n *\n * @param endpointUrlOrUrlString - Either a URL object or a string that\n * represents the URL of an endpoint.\n * @returns A URL object.\n */\nfunction getNormalizedEndpointUrl(endpointUrlOrUrlString: URL | string): URL {\n return endpointUrlOrUrlString instanceof URL\n ? endpointUrlOrUrlString\n : new URL(endpointUrlOrUrlString);\n}\n\n/**\n * This class is responsible for making a request to an endpoint that implements\n * the JSON-RPC protocol. It is designed to gracefully handle network and server\n * failures, retrying requests using exponential backoff. It also offers a hook\n * which can used to respond to slow requests.\n */\nexport class RpcService implements AbstractRpcService {\n /**\n * The function used to make an HTTP request.\n */\n readonly #fetch: typeof fetch;\n\n /**\n * The URL of the RPC endpoint.\n */\n readonly #endpointUrl: URL;\n\n /**\n * A common set of options that the request options will extend.\n */\n readonly #fetchOptions: FetchOptions;\n\n /**\n * An RPC service that represents a failover endpoint which will be invoked\n * while the circuit for _this_ service is open.\n */\n readonly #failoverService: AbstractRpcService | undefined;\n\n /**\n * The policy that wraps the request.\n */\n readonly #policy: ServicePolicy;\n\n /**\n * Constructs a new RpcService object.\n *\n * @param args - The arguments.\n * @param args.fetch - A function that can be used to make an HTTP request.\n * If your JavaScript environment supports `fetch` natively, you'll probably\n * want to pass that; otherwise you can pass an equivalent (such as `fetch`\n * via `node-fetch`).\n * @param args.btoa - A function that can be used to convert a binary string\n * into base-64. Used to encode authorization credentials.\n * @param args.endpointUrl - The URL of the RPC endpoint.\n * @param args.fetchOptions - A common set of options that will be used to\n * make every request. Can be overridden on the request level (e.g. to add\n * headers).\n * @param args.failoverService - An RPC service that represents a failover\n * endpoint which will be invoked while the circuit for _this_ service is\n * open.\n */\n constructor({\n fetch: givenFetch,\n btoa: givenBtoa,\n endpointUrl,\n fetchOptions = {},\n failoverService,\n }: {\n fetch: typeof fetch;\n btoa: typeof btoa;\n endpointUrl: URL | string;\n fetchOptions?: FetchOptions;\n failoverService?: AbstractRpcService;\n }) {\n this.#fetch = givenFetch;\n this.#endpointUrl = getNormalizedEndpointUrl(endpointUrl);\n this.#fetchOptions = this.#getDefaultFetchOptions(\n this.#endpointUrl,\n fetchOptions,\n givenBtoa,\n );\n this.#failoverService = failoverService;\n\n const policy = createServicePolicy({\n maxRetries: 4,\n maxConsecutiveFailures: 15,\n retryFilterPolicy: handleWhen((error) => {\n return (\n // Ignore errors where the request failed to establish\n isConnectionError(error) ||\n // Ignore server sent HTML error pages or truncated JSON responses\n error.message.includes('not valid JSON') ||\n // Ignore server overload errors\n error.message.includes('Gateway timeout') ||\n (hasProperty(error, 'code') &&\n (error.code === 'ETIMEDOUT' || error.code === 'ECONNRESET'))\n );\n }),\n });\n this.#policy = policy;\n }\n\n /**\n * Listens for when the RPC service retries the request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link ServicePolicy.onRetry} returns.\n * @see {@link createServicePolicy}\n */\n onRetry(\n listener: AddToCockatielEventData<\n Parameters<ServicePolicy['onRetry']>[0],\n { endpointUrl: string }\n >,\n ) {\n return this.#policy.onRetry((data) => {\n listener({ ...data, endpointUrl: this.#endpointUrl.toString() });\n });\n }\n\n /**\n * Listens for when the RPC service retries the request too many times in a\n * row.\n *\n * @param listener - The callback to be called when the circuit is broken.\n * @returns What {@link ServicePolicy.onBreak} returns.\n * @see {@link createServicePolicy}\n */\n onBreak(\n listener: AddToCockatielEventData<\n Parameters<ServicePolicy['onBreak']>[0],\n { endpointUrl: string }\n >,\n ) {\n return this.#policy.onBreak((data) => {\n listener({ ...data, endpointUrl: this.#endpointUrl.toString() });\n });\n }\n\n /**\n * Listens for when the policy underlying this RPC service detects a slow\n * request.\n *\n * @param listener - The callback to be called when the request is slow.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n * @see {@link createServicePolicy}\n */\n onDegraded(\n listener: AddToCockatielEventData<\n Parameters<ServicePolicy['onDegraded']>[0],\n { endpointUrl: string }\n >,\n ) {\n return this.#policy.onDegraded(() => {\n listener({ endpointUrl: this.#endpointUrl.toString() });\n });\n }\n\n /**\n * Makes a request to the RPC endpoint. If the circuit is open because this\n * request has failed too many times, the request is forwarded to a failover\n * service (if provided).\n *\n * This overload is specifically designed for `eth_getBlockByNumber`, which\n * can return a `result` of `null` despite an expected `Result` being\n * provided.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params> & { method: 'eth_getBlockByNumber' },\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>>;\n\n /**\n * Makes a request to the RPC endpoint. If the circuit is open because this\n * request has failed too many times, the request is forwarded to a failover\n * service (if provided).\n *\n * This overload is designed for all RPC methods except for\n * `eth_getBlockByNumber`, which are expected to return a `result` of the\n * expected `Result`.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result>>;\n\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions: FetchOptions = {},\n ): Promise<JsonRpcResponse<Result | null>> {\n const completeFetchOptions = this.#getCompleteFetchOptions(\n jsonRpcRequest,\n fetchOptions,\n );\n\n try {\n return await this.#executePolicy<Params, Result>(\n jsonRpcRequest,\n completeFetchOptions,\n );\n } catch (error) {\n if (\n this.#policy.circuitBreakerPolicy.state === CircuitState.Open &&\n this.#failoverService !== undefined\n ) {\n return await this.#failoverService.request(\n jsonRpcRequest,\n completeFetchOptions,\n );\n }\n throw error;\n }\n }\n\n /**\n * Constructs a default set of options to `fetch`.\n *\n * If a username and password are present in the URL, they are extracted to an\n * Authorization header.\n *\n * @param endpointUrl - The endpoint URL.\n * @param fetchOptions - The options to `fetch`.\n * @param givenBtoa - An implementation of `btoa`.\n * @returns The default fetch options.\n */\n #getDefaultFetchOptions(\n endpointUrl: URL,\n fetchOptions: FetchOptions,\n givenBtoa: (stringToEncode: string) => string,\n ): FetchOptions {\n if (endpointUrl.username && endpointUrl.password) {\n const authString = `${endpointUrl.username}:${endpointUrl.password}`;\n const encodedCredentials = givenBtoa(authString);\n return deepmerge(fetchOptions, {\n headers: { Authorization: `Basic ${encodedCredentials}` },\n });\n }\n\n return fetchOptions;\n }\n\n /**\n * Constructs a final set of options to pass to `fetch`. Note that the method\n * defaults to `post`, and the JSON-RPC request is automatically JSON-encoded.\n *\n * @param jsonRpcRequest - The JSON-RPC request.\n * @param fetchOptions - Custom `fetch` options.\n * @returns The complete set of `fetch` options.\n */\n #getCompleteFetchOptions<Params extends JsonRpcParams>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions: FetchOptions,\n ): FetchOptions {\n const defaultOptions = {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n };\n const mergedOptions = deepmerge(\n defaultOptions,\n deepmerge(this.#fetchOptions, fetchOptions),\n );\n\n const { id, jsonrpc, method, params } = jsonRpcRequest;\n const body = JSON.stringify({\n id,\n jsonrpc,\n method,\n params,\n });\n\n return { ...mergedOptions, body };\n }\n\n /**\n * Makes the request using the Cockatiel policy that this service creates.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - The options for `fetch`; will be combined with the\n * fetch options passed to the constructor\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async #executePolicy<\n Params extends JsonRpcParams,\n Result extends Json,\n Request extends JsonRpcRequest = JsonRpcRequest<Params>,\n >(\n jsonRpcRequest: Request,\n fetchOptions: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>> {\n return await this.#policy.execute(async () => {\n const response = await this.#fetch(this.#endpointUrl, fetchOptions);\n\n if (response.status === 405) {\n throw rpcErrors.methodNotFound();\n }\n\n if (response.status === 429) {\n throw rpcErrors.internal({ message: 'Request is being rate limited.' });\n }\n\n if (response.status === 503 || response.status === 504) {\n throw rpcErrors.internal({\n message:\n 'Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.',\n });\n }\n\n const text = await response.text();\n\n if (\n jsonRpcRequest.method === 'eth_getBlockByNumber' &&\n text === 'Not Found'\n ) {\n return {\n id: jsonRpcRequest.id,\n jsonrpc: jsonRpcRequest.jsonrpc,\n result: null,\n };\n }\n\n // Type annotation: We assume that if this response is valid JSON, it's a\n // valid JSON-RPC response.\n let json: JsonRpcResponse<Result>;\n try {\n json = JSON.parse(text);\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw rpcErrors.internal({\n message: 'Could not parse response as it is not valid JSON',\n data: text,\n });\n } else {\n throw error;\n }\n }\n\n if (!response.ok) {\n throw rpcErrors.internal({\n message: `Non-200 status code: '${response.status}'`,\n data: json,\n });\n }\n\n return json;\n });\n }\n}\n"]}
|
|
@@ -1,55 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ServicePolicy } from "@metamask/controller-utils";
|
|
2
2
|
import type { JsonRpcRequest } from "@metamask/utils";
|
|
3
3
|
import { type Json, type JsonRpcParams, type JsonRpcResponse } from "@metamask/utils";
|
|
4
4
|
import type { AbstractRpcService } from "./abstract-rpc-service.cjs";
|
|
5
5
|
import type { AddToCockatielEventData, FetchOptions } from "./shared.cjs";
|
|
6
|
-
/**
|
|
7
|
-
* Options for the RpcService constructor.
|
|
8
|
-
*/
|
|
9
|
-
export type RpcServiceOptions = {
|
|
10
|
-
/**
|
|
11
|
-
* A function that can be used to convert a binary string into a
|
|
12
|
-
* base64-encoded ASCII string. Used to encode authorization credentials.
|
|
13
|
-
*/
|
|
14
|
-
btoa: typeof btoa;
|
|
15
|
-
/**
|
|
16
|
-
* The URL of the RPC endpoint to hit.
|
|
17
|
-
*/
|
|
18
|
-
endpointUrl: URL | string;
|
|
19
|
-
/**
|
|
20
|
-
* An RPC service that represents a failover endpoint which will be invoked
|
|
21
|
-
* while the circuit for _this_ service is open.
|
|
22
|
-
*/
|
|
23
|
-
failoverService?: AbstractRpcService;
|
|
24
|
-
/**
|
|
25
|
-
* A function that can be used to make an HTTP request. If your JavaScript
|
|
26
|
-
* environment supports `fetch` natively, you'll probably want to pass that;
|
|
27
|
-
* otherwise you can pass an equivalent (such as `fetch` via `node-fetch`).
|
|
28
|
-
*/
|
|
29
|
-
fetch: typeof fetch;
|
|
30
|
-
/**
|
|
31
|
-
* A common set of options that will be used to make every request. Can be
|
|
32
|
-
* overridden on the request level (e.g. to add headers).
|
|
33
|
-
*/
|
|
34
|
-
fetchOptions?: FetchOptions;
|
|
35
|
-
/**
|
|
36
|
-
* Options to pass to `createServicePolicy`. Note that `retryFilterPolicy` is
|
|
37
|
-
* not accepted, as it is overwritten. See {@link createServicePolicy}.
|
|
38
|
-
*/
|
|
39
|
-
policyOptions?: Omit<CreateServicePolicyOptions, 'retryFilterPolicy'>;
|
|
40
|
-
};
|
|
41
|
-
/**
|
|
42
|
-
* The maximum number of times that a failing service should be re-run before
|
|
43
|
-
* giving up.
|
|
44
|
-
*/
|
|
45
|
-
export declare const DEFAULT_MAX_RETRIES = 4;
|
|
46
|
-
/**
|
|
47
|
-
* The maximum number of times that the service is allowed to fail before
|
|
48
|
-
* pausing further retries. This is set to a value such that if given a
|
|
49
|
-
* service that continually fails, the policy needs to be executed 3 times
|
|
50
|
-
* before further retries are paused.
|
|
51
|
-
*/
|
|
52
|
-
export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
|
|
53
6
|
/**
|
|
54
7
|
* The list of error messages that represent a failure to connect to the network.
|
|
55
8
|
*
|
|
@@ -72,7 +25,7 @@ export declare const CONNECTION_ERRORS: {
|
|
|
72
25
|
* @returns True if the error indicates that the network cannot be connected to,
|
|
73
26
|
* and false otherwise.
|
|
74
27
|
*/
|
|
75
|
-
export
|
|
28
|
+
export default function isConnectionError(error: unknown): boolean;
|
|
76
29
|
/**
|
|
77
30
|
* This class is responsible for making a request to an endpoint that implements
|
|
78
31
|
* the JSON-RPC protocol. It is designed to gracefully handle network and server
|
|
@@ -81,16 +34,31 @@ export declare function isConnectionError(error: unknown): boolean;
|
|
|
81
34
|
*/
|
|
82
35
|
export declare class RpcService implements AbstractRpcService {
|
|
83
36
|
#private;
|
|
84
|
-
/**
|
|
85
|
-
* The URL of the RPC endpoint.
|
|
86
|
-
*/
|
|
87
|
-
readonly endpointUrl: URL;
|
|
88
37
|
/**
|
|
89
38
|
* Constructs a new RpcService object.
|
|
90
39
|
*
|
|
91
|
-
* @param
|
|
40
|
+
* @param args - The arguments.
|
|
41
|
+
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
42
|
+
* If your JavaScript environment supports `fetch` natively, you'll probably
|
|
43
|
+
* want to pass that; otherwise you can pass an equivalent (such as `fetch`
|
|
44
|
+
* via `node-fetch`).
|
|
45
|
+
* @param args.btoa - A function that can be used to convert a binary string
|
|
46
|
+
* into base-64. Used to encode authorization credentials.
|
|
47
|
+
* @param args.endpointUrl - The URL of the RPC endpoint.
|
|
48
|
+
* @param args.fetchOptions - A common set of options that will be used to
|
|
49
|
+
* make every request. Can be overridden on the request level (e.g. to add
|
|
50
|
+
* headers).
|
|
51
|
+
* @param args.failoverService - An RPC service that represents a failover
|
|
52
|
+
* endpoint which will be invoked while the circuit for _this_ service is
|
|
53
|
+
* open.
|
|
92
54
|
*/
|
|
93
|
-
constructor(
|
|
55
|
+
constructor({ fetch: givenFetch, btoa: givenBtoa, endpointUrl, fetchOptions, failoverService, }: {
|
|
56
|
+
fetch: typeof fetch;
|
|
57
|
+
btoa: typeof btoa;
|
|
58
|
+
endpointUrl: URL | string;
|
|
59
|
+
fetchOptions?: FetchOptions;
|
|
60
|
+
failoverService?: AbstractRpcService;
|
|
61
|
+
});
|
|
94
62
|
/**
|
|
95
63
|
* Listens for when the RPC service retries the request.
|
|
96
64
|
*
|
|
@@ -111,7 +79,6 @@ export declare class RpcService implements AbstractRpcService {
|
|
|
111
79
|
*/
|
|
112
80
|
onBreak(listener: AddToCockatielEventData<Parameters<ServicePolicy['onBreak']>[0], {
|
|
113
81
|
endpointUrl: string;
|
|
114
|
-
failoverEndpointUrl?: string;
|
|
115
82
|
}>): import("cockatiel").IDisposable;
|
|
116
83
|
/**
|
|
117
84
|
* Listens for when the policy underlying this RPC service detects a slow
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-service.d.cts","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"rpc-service.d.cts","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAOhE,OAAO,KAAK,EAAE,cAAc,EAAE,wBAAwB;AACtD,OAAO,EAEL,KAAK,IAAI,EACT,KAAK,aAAa,EAClB,KAAK,eAAe,EACrB,wBAAwB;AAGzB,OAAO,KAAK,EAAE,kBAAkB,EAAE,mCAA+B;AACjE,OAAO,KAAK,EAAE,uBAAuB,EAAE,YAAY,EAAE,qBAAiB;AAEtE;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB;;;GA8C7B,CAAC;AAEF;;;;;;;;;;;GAW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,eAAe,CAAC,IAAI,CAAC,CAAC;IAE3D;;;;;;;;;;;;;;;;;;OAkBG;IACG,OAAO,CAAC,MAAM,SAAS,aAAa,EAAE,MAAM,SAAS,IAAI,EAC7D,cAAc,EAAE,cAAc,CAAC,MAAM,CAAC,EACtC,YAAY,CAAC,EAAE,YAAY,GAC1B,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;CA0KpC"}
|
|
@@ -1,55 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ServicePolicy } from "@metamask/controller-utils";
|
|
2
2
|
import type { JsonRpcRequest } from "@metamask/utils";
|
|
3
3
|
import { type Json, type JsonRpcParams, type JsonRpcResponse } from "@metamask/utils";
|
|
4
4
|
import type { AbstractRpcService } from "./abstract-rpc-service.mjs";
|
|
5
5
|
import type { AddToCockatielEventData, FetchOptions } from "./shared.mjs";
|
|
6
|
-
/**
|
|
7
|
-
* Options for the RpcService constructor.
|
|
8
|
-
*/
|
|
9
|
-
export type RpcServiceOptions = {
|
|
10
|
-
/**
|
|
11
|
-
* A function that can be used to convert a binary string into a
|
|
12
|
-
* base64-encoded ASCII string. Used to encode authorization credentials.
|
|
13
|
-
*/
|
|
14
|
-
btoa: typeof btoa;
|
|
15
|
-
/**
|
|
16
|
-
* The URL of the RPC endpoint to hit.
|
|
17
|
-
*/
|
|
18
|
-
endpointUrl: URL | string;
|
|
19
|
-
/**
|
|
20
|
-
* An RPC service that represents a failover endpoint which will be invoked
|
|
21
|
-
* while the circuit for _this_ service is open.
|
|
22
|
-
*/
|
|
23
|
-
failoverService?: AbstractRpcService;
|
|
24
|
-
/**
|
|
25
|
-
* A function that can be used to make an HTTP request. If your JavaScript
|
|
26
|
-
* environment supports `fetch` natively, you'll probably want to pass that;
|
|
27
|
-
* otherwise you can pass an equivalent (such as `fetch` via `node-fetch`).
|
|
28
|
-
*/
|
|
29
|
-
fetch: typeof fetch;
|
|
30
|
-
/**
|
|
31
|
-
* A common set of options that will be used to make every request. Can be
|
|
32
|
-
* overridden on the request level (e.g. to add headers).
|
|
33
|
-
*/
|
|
34
|
-
fetchOptions?: FetchOptions;
|
|
35
|
-
/**
|
|
36
|
-
* Options to pass to `createServicePolicy`. Note that `retryFilterPolicy` is
|
|
37
|
-
* not accepted, as it is overwritten. See {@link createServicePolicy}.
|
|
38
|
-
*/
|
|
39
|
-
policyOptions?: Omit<CreateServicePolicyOptions, 'retryFilterPolicy'>;
|
|
40
|
-
};
|
|
41
|
-
/**
|
|
42
|
-
* The maximum number of times that a failing service should be re-run before
|
|
43
|
-
* giving up.
|
|
44
|
-
*/
|
|
45
|
-
export declare const DEFAULT_MAX_RETRIES = 4;
|
|
46
|
-
/**
|
|
47
|
-
* The maximum number of times that the service is allowed to fail before
|
|
48
|
-
* pausing further retries. This is set to a value such that if given a
|
|
49
|
-
* service that continually fails, the policy needs to be executed 3 times
|
|
50
|
-
* before further retries are paused.
|
|
51
|
-
*/
|
|
52
|
-
export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
|
|
53
6
|
/**
|
|
54
7
|
* The list of error messages that represent a failure to connect to the network.
|
|
55
8
|
*
|
|
@@ -72,7 +25,7 @@ export declare const CONNECTION_ERRORS: {
|
|
|
72
25
|
* @returns True if the error indicates that the network cannot be connected to,
|
|
73
26
|
* and false otherwise.
|
|
74
27
|
*/
|
|
75
|
-
export
|
|
28
|
+
export default function isConnectionError(error: unknown): boolean;
|
|
76
29
|
/**
|
|
77
30
|
* This class is responsible for making a request to an endpoint that implements
|
|
78
31
|
* the JSON-RPC protocol. It is designed to gracefully handle network and server
|
|
@@ -81,16 +34,31 @@ export declare function isConnectionError(error: unknown): boolean;
|
|
|
81
34
|
*/
|
|
82
35
|
export declare class RpcService implements AbstractRpcService {
|
|
83
36
|
#private;
|
|
84
|
-
/**
|
|
85
|
-
* The URL of the RPC endpoint.
|
|
86
|
-
*/
|
|
87
|
-
readonly endpointUrl: URL;
|
|
88
37
|
/**
|
|
89
38
|
* Constructs a new RpcService object.
|
|
90
39
|
*
|
|
91
|
-
* @param
|
|
40
|
+
* @param args - The arguments.
|
|
41
|
+
* @param args.fetch - A function that can be used to make an HTTP request.
|
|
42
|
+
* If your JavaScript environment supports `fetch` natively, you'll probably
|
|
43
|
+
* want to pass that; otherwise you can pass an equivalent (such as `fetch`
|
|
44
|
+
* via `node-fetch`).
|
|
45
|
+
* @param args.btoa - A function that can be used to convert a binary string
|
|
46
|
+
* into base-64. Used to encode authorization credentials.
|
|
47
|
+
* @param args.endpointUrl - The URL of the RPC endpoint.
|
|
48
|
+
* @param args.fetchOptions - A common set of options that will be used to
|
|
49
|
+
* make every request. Can be overridden on the request level (e.g. to add
|
|
50
|
+
* headers).
|
|
51
|
+
* @param args.failoverService - An RPC service that represents a failover
|
|
52
|
+
* endpoint which will be invoked while the circuit for _this_ service is
|
|
53
|
+
* open.
|
|
92
54
|
*/
|
|
93
|
-
constructor(
|
|
55
|
+
constructor({ fetch: givenFetch, btoa: givenBtoa, endpointUrl, fetchOptions, failoverService, }: {
|
|
56
|
+
fetch: typeof fetch;
|
|
57
|
+
btoa: typeof btoa;
|
|
58
|
+
endpointUrl: URL | string;
|
|
59
|
+
fetchOptions?: FetchOptions;
|
|
60
|
+
failoverService?: AbstractRpcService;
|
|
61
|
+
});
|
|
94
62
|
/**
|
|
95
63
|
* Listens for when the RPC service retries the request.
|
|
96
64
|
*
|
|
@@ -111,7 +79,6 @@ export declare class RpcService implements AbstractRpcService {
|
|
|
111
79
|
*/
|
|
112
80
|
onBreak(listener: AddToCockatielEventData<Parameters<ServicePolicy['onBreak']>[0], {
|
|
113
81
|
endpointUrl: string;
|
|
114
|
-
failoverEndpointUrl?: string;
|
|
115
82
|
}>): import("cockatiel").IDisposable;
|
|
116
83
|
/**
|
|
117
84
|
* Listens for when the policy underlying this RPC service detects a slow
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-service.d.mts","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"m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