@metamask-previews/network-controller 25.0.0-preview-ee982ebe → 25.0.0-preview-1a8571ae
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/dist/NetworkController.cjs.map +1 -1
- package/dist/NetworkController.mjs.map +1 -1
- package/dist/create-auto-managed-network-client.cjs.map +1 -1
- package/dist/create-auto-managed-network-client.mjs.map +1 -1
- package/dist/create-network-client.cjs.map +1 -1
- package/dist/create-network-client.mjs.map +1 -1
- package/dist/rpc-service/rpc-service.cjs.map +1 -1
- package/dist/rpc-service/rpc-service.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-auto-managed-network-client.cjs","sourceRoot":"","sources":["../src/create-auto-managed-network-client.ts"],"names":[],"mappings":";;;AAIA,uEAA8D;AAS9D;;;;GAIG;AACH,MAAM,wBAAwB,GAAG,YAAY,CAAC;AA+B9C;;;;GAIG;AACH,MAAM,oBAAoB,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,SAAgB,8BAA8B,CAE5C,EACA,0BAA0B,EAC1B,oBAAoB,EACpB,sBAAsB,GAAG,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EACnC,SAAS,EACT,oBAAoB,EAAE,yBAAyB,EAC/C,MAAM,GAYP;IACC,IAAI,oBAAoB,GAAG,yBAAyB,CAAC;IACrD,IAAI,aAAwC,CAAC;IAE7C,MAAM,0BAA0B,GAAG,GAAkB,EAAE;QACrD,aAAa,KAAb,aAAa,GAAK,IAAA,2CAAmB,EAAC;YACpC,aAAa,EAAE,0BAA0B;YACzC,oBAAoB;YACpB,sBAAsB;YACtB,SAAS;YACT,oBAAoB;YACpB,MAAM;SACP,CAAC,EAAC;QAEH,IAAI,aAAa,KAAK,SAAS,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,wFAAwF,CACzF,CA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MAAM,kBAAkB,GAAG,GAAG,EAAE;QAC9B,oBAAoB,GAAG,KAAK,CAAC;QAC7B,OAAO,EAAE,CAAC;QACV,aAAa,GAAG,SAAS,CAAC;IAC5B,CAAC,CAAC;IAEF,OAAO;QACL,aAAa,EAAE,0BAA0B;QACzC,QAAQ,EAAE,aAAa;QACvB,YAAY,EAAE,iBAAiB;QAC/B,OAAO;QACP,iBAAiB;QACjB,kBAAkB;KACnB,CAAC;AACJ,CAAC;AA9JD,wEA8JC","sourcesContent":["import type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkClient } from './create-network-client';\nimport { createNetworkClient } from './create-network-client';\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\n\n/**\n * The name of the method on both the provider and block tracker proxy which can\n * be used to get the underlying provider or block tracker from the network\n * client, when it is initialized.\n */\nconst REFLECTIVE_PROPERTY_NAME = '__target__';\n\n/**\n * Represents a proxy object which wraps a target object. As a proxy, it allows\n * for accessing and setting all of the properties that the target object\n * supports, but also supports an extra propertyName (`__target__`) to access\n * the target itself.\n *\n * @template Type - The type of the target object. It is assumed that this type\n * will be constant even when the target is swapped.\n */\nexport type ProxyWithAccessibleTarget<TargetType> = TargetType & {\n [REFLECTIVE_PROPERTY_NAME]: TargetType;\n};\n\n/**\n * An object that provides the same interface as a network client but where the\n * network client is not initialized until either the provider or block tracker\n * is first accessed.\n */\nexport type AutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n> = {\n configuration: Configuration;\n provider: ProxyWithAccessibleTarget<Provider>;\n blockTracker: ProxyWithAccessibleTarget<BlockTracker>;\n destroy: () => void;\n enableRpcFailover: () => void;\n disableRpcFailover: () => void;\n};\n\n/**\n * By default, the provider and block provider proxies will point to nothing.\n * This is impossible when using the Proxy API, as the target object has to be\n * something, so this object represents that \"something\".\n */\nconst UNINITIALIZED_TARGET = { __UNINITIALIZED__: true };\n\n/**\n * This function creates two proxies, one that wraps a provider and another that\n * wraps a block tracker. These proxies are unique in that both will be \"empty\"\n * at first; that is, neither will point to a functional provider or block\n * tracker. Instead, as soon as a method or event is accessed on either object\n * that requires a network request to function, a network client is created on\n * the fly and the method or event in question is then forwarded to whichever\n * part of the network client is serving as the receiver. The network client is\n * then cached for subsequent usages.\n *\n * @param args - The arguments.\n * @param args.networkClientConfiguration - The configuration object that will be\n * used to instantiate the network client when it is needed.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable.\n * @param args.logger - A `loglevel` logger.\n * @returns The auto-managed network client.\n */\nexport function createAutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n>({\n networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions = () => ({}),\n messenger,\n isRpcFailoverEnabled: givenIsRpcFailoverEnabled,\n logger,\n}: {\n networkClientConfiguration: Configuration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions?: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): AutoManagedNetworkClient<Configuration> {\n let isRpcFailoverEnabled = givenIsRpcFailoverEnabled;\n let networkClient: NetworkClient | undefined;\n\n const ensureNetworkClientCreated = (): NetworkClient => {\n networkClient ??= createNetworkClient({\n configuration: networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n });\n\n if (networkClient === undefined) {\n throw new Error(\n \"It looks like `createNetworkClient` didn't return anything. Perhaps it's being mocked?\",\n );\n }\n\n return networkClient;\n };\n\n const providerProxy = new Proxy(UNINITIALIZED_TARGET, {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.provider;\n }\n\n const { provider } = ensureNetworkClientCreated();\n\n if (propertyName in provider) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = provider[propertyName as keyof typeof provider];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be compatible\n // with the signature of the method being called, as technically\n // it can be anything.\n return value.apply(this === receiver ? provider : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { provider } = ensureNetworkClientCreated();\n return propertyName in provider;\n },\n });\n\n const blockTrackerProxy: ProxyWithAccessibleTarget<BlockTracker> = new Proxy(\n UNINITIALIZED_TARGET,\n {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.blockTracker;\n }\n\n const { blockTracker } = ensureNetworkClientCreated();\n\n if (propertyName in blockTracker) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = blockTracker[propertyName as keyof typeof blockTracker];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be\n // compatible with the signature of the method being called, as\n // technically it can be anything.\n return value.apply(this === receiver ? blockTracker : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { blockTracker } = ensureNetworkClientCreated();\n return propertyName in blockTracker;\n },\n },\n );\n\n const destroy = () => {\n networkClient?.destroy();\n };\n\n const enableRpcFailover = () => {\n isRpcFailoverEnabled = true;\n destroy();\n networkClient = undefined;\n };\n\n const disableRpcFailover = () => {\n isRpcFailoverEnabled = false;\n destroy();\n networkClient = undefined;\n };\n\n return {\n configuration: networkClientConfiguration,\n provider: providerProxy,\n blockTracker: blockTrackerProxy,\n destroy,\n enableRpcFailover,\n disableRpcFailover,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create-auto-managed-network-client.cjs","sourceRoot":"","sources":["../src/create-auto-managed-network-client.ts"],"names":[],"mappings":";;;AAIA,uEAA8D;AAS9D;;;;GAIG;AACH,MAAM,wBAAwB,GAAG,YAAY,CAAC;AA+B9C;;;;GAIG;AACH,MAAM,oBAAoB,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,SAAgB,8BAA8B,CAE5C,EACA,0BAA0B,EAC1B,oBAAoB,EACpB,sBAAsB,GAAG,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EACnC,SAAS,EACT,oBAAoB,EAAE,yBAAyB,EAC/C,MAAM,GAYP;IACC,IAAI,oBAAoB,GAAG,yBAA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,KAAK,wBAAwB,EAAE,CAAC;gBAC9C,OAAO,IAAI,CAAC;YACd,CAAC;YACD,MAAM,EAAE,YAAY,EAAE,GAAG,0BAA0B,EAAE,CAAC;YACtD,OAAO,YAAY,IAAI,YAAY,CAAC;QACtC,CAAC;KACF,CACF,CAAC;IAEF,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,aAAa,EAAE,OAAO,EAAE,CAAC;IAC3B,CAAC,CAAC;IAEF,MAAM,iBAAiB,GAAG,GAAG,EAAE;QAC7B,oBAAoB,GAAG,IAAI,CAAC;QAC5B,OAAO,EAAE,CAAC;QACV,aAAa,GAAG,SAAS,CAAC;IAC5B,CAAC,CAAC;IAEF,MAAM,kBAAkB,GAAG,GAAG,EAAE;QAC9B,oBAAoB,GAAG,KAAK,CAAC;QAC7B,OAAO,EAAE,CAAC;QACV,aAAa,GAAG,SAAS,CAAC;IAC5B,CAAC,CAAC;IAEF,OAAO;QACL,aAAa,EAAE,0BAA0B;QACzC,QAAQ,EAAE,aAAa;QACvB,YAAY,EAAE,iBAAiB;QAC/B,OAAO;QACP,iBAAiB;QACjB,kBAAkB;KACnB,CAAC;AACJ,CAAC;AA9JD,wEA8JC","sourcesContent":["import type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkClient } from './create-network-client';\nimport { createNetworkClient } from './create-network-client';\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\n\n/**\n * The name of the method on both the provider and block tracker proxy which can\n * be used to get the underlying provider or block tracker from the network\n * client, when it is initialized.\n */\nconst REFLECTIVE_PROPERTY_NAME = '__target__';\n\n/**\n * Represents a proxy object which wraps a target object. As a proxy, it allows\n * for accessing and setting all of the properties that the target object\n * supports, but also supports an extra propertyName (`__target__`) to access\n * the target itself.\n *\n * @template Type - The type of the target object. It is assumed that this type\n * will be constant even when the target is swapped.\n */\nexport type ProxyWithAccessibleTarget<TargetType> = TargetType & {\n [REFLECTIVE_PROPERTY_NAME]: TargetType;\n};\n\n/**\n * An object that provides the same interface as a network client but where the\n * network client is not initialized until either the provider or block tracker\n * is first accessed.\n */\nexport type AutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n> = {\n configuration: Configuration;\n provider: ProxyWithAccessibleTarget<Provider>;\n blockTracker: ProxyWithAccessibleTarget<BlockTracker>;\n destroy: () => void;\n enableRpcFailover: () => void;\n disableRpcFailover: () => void;\n};\n\n/**\n * By default, the provider and block provider proxies will point to nothing.\n * This is impossible when using the Proxy API, as the target object has to be\n * something, so this object represents that \"something\".\n */\nconst UNINITIALIZED_TARGET = { __UNINITIALIZED__: true };\n\n/**\n * This function creates two proxies, one that wraps a provider and another that\n * wraps a block tracker. These proxies are unique in that both will be \"empty\"\n * at first; that is, neither will point to a functional provider or block\n * tracker. Instead, as soon as a method or event is accessed on either object\n * that requires a network request to function, a network client is created on\n * the fly and the method or event in question is then forwarded to whichever\n * part of the network client is serving as the receiver. The network client is\n * then cached for subsequent usages.\n *\n * @param args - The arguments.\n * @param args.networkClientConfiguration - The configuration object that will be\n * used to instantiate the network client when it is needed.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable.\n * @param args.logger - A `loglevel` logger.\n * @returns The auto-managed network client.\n */\nexport function createAutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n>({\n networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions = () => ({}),\n messenger,\n isRpcFailoverEnabled: givenIsRpcFailoverEnabled,\n logger,\n}: {\n networkClientConfiguration: Configuration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions?: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): AutoManagedNetworkClient<Configuration> {\n let isRpcFailoverEnabled = givenIsRpcFailoverEnabled;\n let networkClient: NetworkClient | undefined;\n\n const ensureNetworkClientCreated = (): NetworkClient => {\n networkClient ??= createNetworkClient({\n configuration: networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n });\n\n if (networkClient === undefined) {\n throw new Error(\n \"It looks like `createNetworkClient` didn't return anything. Perhaps it's being mocked?\",\n );\n }\n\n return networkClient;\n };\n\n const providerProxy = new Proxy(UNINITIALIZED_TARGET, {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.provider;\n }\n\n const { provider } = ensureNetworkClientCreated();\n\n if (propertyName in provider) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = provider[propertyName as keyof typeof provider];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be compatible\n // with the signature of the method being called, as technically\n // it can be anything.\n return value.apply(this === receiver ? provider : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { provider } = ensureNetworkClientCreated();\n return propertyName in provider;\n },\n });\n\n const blockTrackerProxy: ProxyWithAccessibleTarget<BlockTracker> = new Proxy(\n UNINITIALIZED_TARGET,\n {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.blockTracker;\n }\n\n const { blockTracker } = ensureNetworkClientCreated();\n\n if (propertyName in blockTracker) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = blockTracker[propertyName as keyof typeof blockTracker];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be\n // compatible with the signature of the method being called, as\n // technically it can be anything.\n return value.apply(this === receiver ? blockTracker : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { blockTracker } = ensureNetworkClientCreated();\n return propertyName in blockTracker;\n },\n },\n );\n\n const destroy = () => {\n networkClient?.destroy();\n };\n\n const enableRpcFailover = () => {\n isRpcFailoverEnabled = true;\n destroy();\n networkClient = undefined;\n };\n\n const disableRpcFailover = () => {\n isRpcFailoverEnabled = false;\n destroy();\n networkClient = undefined;\n };\n\n return {\n configuration: networkClientConfiguration,\n provider: providerProxy,\n blockTracker: blockTrackerProxy,\n destroy,\n enableRpcFailover,\n disableRpcFailover,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-auto-managed-network-client.mjs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OAAO,UAAyB,GAAG,IAAW;wBAC5C,wDAAwD;wBACxD,+DAA+D;wBAC/D,kCAAkC;wBAClC,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;oBACpE,CAAC,CAAC;iBACH;gBACD,OAAO,KAAK,CAAC;aACd;YAED,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,gCAAgC;QAChC,8DAA8D;QAC9D,GAAG,CAAC,OAAY,EAAE,YAAyB;YACzC,IAAI,YAAY,KAAK,wBAAwB,EAAE;gBAC7C,OAAO,IAAI,CAAC;aACb;YACD,MAAM,EAAE,YAAY,EAAE,GAAG,0BAA0B,EAAE,CAAC;YACtD,OAAO,YAAY,IAAI,YAAY,CAAC;QACtC,CAAC;KACF,CACF,CAAC;IAEF,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,aAAa,EAAE,OAAO,EAAE,CAAC;IAC3B,CAAC,CAAC;IAEF,MAAM,iBAAiB,GAAG,GAAG,EAAE;QAC7B,oBAAoB,GAAG,IAAI,CAAC;QAC5B,OAAO,EAAE,CAAC;QACV,aAAa,GAAG,SAAS,CAAC;IAC5B,CAAC,CAAC;IAEF,MAAM,kBAAkB,GAAG,GAAG,EAAE;QAC9B,oBAAoB,GAAG,KAAK,CAAC;QAC7B,OAAO,EAAE,CAAC;QACV,aAAa,GAAG,SAAS,CAAC;IAC5B,CAAC,CAAC;IAEF,OAAO;QACL,aAAa,EAAE,0BAA0B;QACzC,QAAQ,EAAE,aAAa;QACvB,YAAY,EAAE,iBAAiB;QAC/B,OAAO;QACP,iBAAiB;QACjB,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkClient } from './create-network-client';\nimport { createNetworkClient } from './create-network-client';\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\n\n/**\n * The name of the method on both the provider and block tracker proxy which can\n * be used to get the underlying provider or block tracker from the network\n * client, when it is initialized.\n */\nconst REFLECTIVE_PROPERTY_NAME = '__target__';\n\n/**\n * Represents a proxy object which wraps a target object. As a proxy, it allows\n * for accessing and setting all of the properties that the target object\n * supports, but also supports an extra propertyName (`__target__`) to access\n * the target itself.\n *\n * @template Type - The type of the target object. It is assumed that this type\n * will be constant even when the target is swapped.\n */\nexport type ProxyWithAccessibleTarget<TargetType> = TargetType & {\n [REFLECTIVE_PROPERTY_NAME]: TargetType;\n};\n\n/**\n * An object that provides the same interface as a network client but where the\n * network client is not initialized until either the provider or block tracker\n * is first accessed.\n */\nexport type AutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n> = {\n configuration: Configuration;\n provider: ProxyWithAccessibleTarget<Provider>;\n blockTracker: ProxyWithAccessibleTarget<BlockTracker>;\n destroy: () => void;\n enableRpcFailover: () => void;\n disableRpcFailover: () => void;\n};\n\n/**\n * By default, the provider and block provider proxies will point to nothing.\n * This is impossible when using the Proxy API, as the target object has to be\n * something, so this object represents that \"something\".\n */\nconst UNINITIALIZED_TARGET = { __UNINITIALIZED__: true };\n\n/**\n * This function creates two proxies, one that wraps a provider and another that\n * wraps a block tracker. These proxies are unique in that both will be \"empty\"\n * at first; that is, neither will point to a functional provider or block\n * tracker. Instead, as soon as a method or event is accessed on either object\n * that requires a network request to function, a network client is created on\n * the fly and the method or event in question is then forwarded to whichever\n * part of the network client is serving as the receiver. The network client is\n * then cached for subsequent usages.\n *\n * @param args - The arguments.\n * @param args.networkClientConfiguration - The configuration object that will be\n * used to instantiate the network client when it is needed.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable.\n * @param args.logger - A `loglevel` logger.\n * @returns The auto-managed network client.\n */\nexport function createAutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n>({\n networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions = () => ({}),\n messenger,\n isRpcFailoverEnabled: givenIsRpcFailoverEnabled,\n logger,\n}: {\n networkClientConfiguration: Configuration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions?: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): AutoManagedNetworkClient<Configuration> {\n let isRpcFailoverEnabled = givenIsRpcFailoverEnabled;\n let networkClient: NetworkClient | undefined;\n\n const ensureNetworkClientCreated = (): NetworkClient => {\n networkClient ??= createNetworkClient({\n configuration: networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n });\n\n if (networkClient === undefined) {\n throw new Error(\n \"It looks like `createNetworkClient` didn't return anything. Perhaps it's being mocked?\",\n );\n }\n\n return networkClient;\n };\n\n const providerProxy = new Proxy(UNINITIALIZED_TARGET, {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.provider;\n }\n\n const { provider } = ensureNetworkClientCreated();\n\n if (propertyName in provider) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = provider[propertyName as keyof typeof provider];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be compatible\n // with the signature of the method being called, as technically\n // it can be anything.\n return value.apply(this === receiver ? provider : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { provider } = ensureNetworkClientCreated();\n return propertyName in provider;\n },\n });\n\n const blockTrackerProxy: ProxyWithAccessibleTarget<BlockTracker> = new Proxy(\n UNINITIALIZED_TARGET,\n {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.blockTracker;\n }\n\n const { blockTracker } = ensureNetworkClientCreated();\n\n if (propertyName in blockTracker) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = blockTracker[propertyName as keyof typeof blockTracker];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be\n // compatible with the signature of the method being called, as\n // technically it can be anything.\n return value.apply(this === receiver ? blockTracker : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { blockTracker } = ensureNetworkClientCreated();\n return propertyName in blockTracker;\n },\n },\n );\n\n const destroy = () => {\n networkClient?.destroy();\n };\n\n const enableRpcFailover = () => {\n isRpcFailoverEnabled = true;\n destroy();\n networkClient = undefined;\n };\n\n const disableRpcFailover = () => {\n isRpcFailoverEnabled = false;\n destroy();\n networkClient = undefined;\n };\n\n return {\n configuration: networkClientConfiguration,\n provider: providerProxy,\n blockTracker: blockTrackerProxy,\n destroy,\n enableRpcFailover,\n disableRpcFailover,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create-auto-managed-network-client.mjs","sourceRoot":"","sources":["../src/create-auto-managed-network-client.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAE,oCAAgC;AAS9D;;;;GAIG;AACH,MAAM,wBAAwB,GAAG,YAAY,CAAC;AA+B9C;;;;GAIG;AACH,MAAM,oBAAoB,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,8BAA8B,CAE5C,EACA,0BAA0B,EAC1B,oBAAoB,EACpB,sBAAsB,GAAG,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EACnC,SAAS,EACT,oBAAoB,EAAE,yBAAyB,EAC/C,MAAM,GAYP;IACC,IAAI,oBAAoB,GAAG,yBAAyB,CAAC;IACrD,IAAI,aAAwC,CAAC;IAE7C,MAAM,0BAA0B,GAAG,GAAkB,EAAE;QACrD,aAAa,KAAb,aAAa,GAAK,mBAAmB,CAAC;YACpC,aAAa,EAAE,0BAA0B;YACzC,oBAAoB;YACpB,sBAAsB;YACtB,SAAS;YACT,oBAAoB;YACpB,MAAM;SACP,CAAC,EAAC;QAEH,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CACb,wFAAwF,CACzF,CAAC;QACJ,CAAC;QAED,OAAO,aAAa,CAAC;IACvB,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,oBAAoB,EAA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BAAkB,GAAG,GAAG,EAAE;QAC9B,oBAAoB,GAAG,KAAK,CAAC;QAC7B,OAAO,EAAE,CAAC;QACV,aAAa,GAAG,SAAS,CAAC;IAC5B,CAAC,CAAC;IAEF,OAAO;QACL,aAAa,EAAE,0BAA0B;QACzC,QAAQ,EAAE,aAAa;QACvB,YAAY,EAAE,iBAAiB;QAC/B,OAAO;QACP,iBAAiB;QACjB,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkClient } from './create-network-client';\nimport { createNetworkClient } from './create-network-client';\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\n\n/**\n * The name of the method on both the provider and block tracker proxy which can\n * be used to get the underlying provider or block tracker from the network\n * client, when it is initialized.\n */\nconst REFLECTIVE_PROPERTY_NAME = '__target__';\n\n/**\n * Represents a proxy object which wraps a target object. As a proxy, it allows\n * for accessing and setting all of the properties that the target object\n * supports, but also supports an extra propertyName (`__target__`) to access\n * the target itself.\n *\n * @template Type - The type of the target object. It is assumed that this type\n * will be constant even when the target is swapped.\n */\nexport type ProxyWithAccessibleTarget<TargetType> = TargetType & {\n [REFLECTIVE_PROPERTY_NAME]: TargetType;\n};\n\n/**\n * An object that provides the same interface as a network client but where the\n * network client is not initialized until either the provider or block tracker\n * is first accessed.\n */\nexport type AutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n> = {\n configuration: Configuration;\n provider: ProxyWithAccessibleTarget<Provider>;\n blockTracker: ProxyWithAccessibleTarget<BlockTracker>;\n destroy: () => void;\n enableRpcFailover: () => void;\n disableRpcFailover: () => void;\n};\n\n/**\n * By default, the provider and block provider proxies will point to nothing.\n * This is impossible when using the Proxy API, as the target object has to be\n * something, so this object represents that \"something\".\n */\nconst UNINITIALIZED_TARGET = { __UNINITIALIZED__: true };\n\n/**\n * This function creates two proxies, one that wraps a provider and another that\n * wraps a block tracker. These proxies are unique in that both will be \"empty\"\n * at first; that is, neither will point to a functional provider or block\n * tracker. Instead, as soon as a method or event is accessed on either object\n * that requires a network request to function, a network client is created on\n * the fly and the method or event in question is then forwarded to whichever\n * part of the network client is serving as the receiver. The network client is\n * then cached for subsequent usages.\n *\n * @param args - The arguments.\n * @param args.networkClientConfiguration - The configuration object that will be\n * used to instantiate the network client when it is needed.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable.\n * @param args.logger - A `loglevel` logger.\n * @returns The auto-managed network client.\n */\nexport function createAutoManagedNetworkClient<\n Configuration extends NetworkClientConfiguration,\n>({\n networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions = () => ({}),\n messenger,\n isRpcFailoverEnabled: givenIsRpcFailoverEnabled,\n logger,\n}: {\n networkClientConfiguration: Configuration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions?: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): AutoManagedNetworkClient<Configuration> {\n let isRpcFailoverEnabled = givenIsRpcFailoverEnabled;\n let networkClient: NetworkClient | undefined;\n\n const ensureNetworkClientCreated = (): NetworkClient => {\n networkClient ??= createNetworkClient({\n configuration: networkClientConfiguration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n });\n\n if (networkClient === undefined) {\n throw new Error(\n \"It looks like `createNetworkClient` didn't return anything. Perhaps it's being mocked?\",\n );\n }\n\n return networkClient;\n };\n\n const providerProxy = new Proxy(UNINITIALIZED_TARGET, {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.provider;\n }\n\n const { provider } = ensureNetworkClientCreated();\n\n if (propertyName in provider) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = provider[propertyName as keyof typeof provider];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be compatible\n // with the signature of the method being called, as technically\n // it can be anything.\n return value.apply(this === receiver ? provider : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { provider } = ensureNetworkClientCreated();\n return propertyName in provider;\n },\n });\n\n const blockTrackerProxy: ProxyWithAccessibleTarget<BlockTracker> = new Proxy(\n UNINITIALIZED_TARGET,\n {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(_target: any, propertyName: PropertyKey, receiver: unknown) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return networkClient?.blockTracker;\n }\n\n const { blockTracker } = ensureNetworkClientCreated();\n\n if (propertyName in blockTracker) {\n // Typecast: We know that `[propertyName]` is a propertyName on\n // `provider`.\n const value = blockTracker[propertyName as keyof typeof blockTracker];\n if (typeof value === 'function') {\n // Ensure that the method on the provider is called with `this` as\n // the target, *not* the proxy (which happens by default) —\n // this allows private properties to be accessed\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function (this: unknown, ...args: any[]) {\n // @ts-expect-error We don't care that `this` may not be\n // compatible with the signature of the method being called, as\n // technically it can be anything.\n return value.apply(this === receiver ? blockTracker : this, args);\n };\n }\n return value;\n }\n\n return undefined;\n },\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n has(_target: any, propertyName: PropertyKey) {\n if (propertyName === REFLECTIVE_PROPERTY_NAME) {\n return true;\n }\n const { blockTracker } = ensureNetworkClientCreated();\n return propertyName in blockTracker;\n },\n },\n );\n\n const destroy = () => {\n networkClient?.destroy();\n };\n\n const enableRpcFailover = () => {\n isRpcFailoverEnabled = true;\n destroy();\n networkClient = undefined;\n };\n\n const disableRpcFailover = () => {\n isRpcFailoverEnabled = false;\n destroy();\n networkClient = undefined;\n };\n\n return {\n configuration: networkClientConfiguration,\n provider: providerProxy,\n blockTracker: blockTrackerProxy,\n destroy,\n enableRpcFailover,\n disableRpcFailover,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-network-client.cjs","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AAErD,mEAAkE;AAClE,uEAAuE;AACvE,+EAQ2C;AAC3C,2EAGyC;AACzC,+DAKmC;AAOnC,2EAAkE;AAMlE,uCAA4C;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAgB,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,EACpB,MAAM,GAYP;IACC,MAAM,kBAAkB,GACtB,aAAa,CAAC,IAAI,KAAK,yBAAiB,CAAC,MAAM;QAC7C,CAAC,CAAC,WAAW,aAAa,CAAC,OAA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AAC;SACjE;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { InfuraNetworkType } from '@metamask/controller-utils';\nimport { ChainId } from '@metamask/controller-utils';\nimport type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createInfuraMiddleware } from '@metamask/eth-json-rpc-infura';\nimport {\n createBlockCacheMiddleware,\n createBlockRefMiddleware,\n createBlockRefRewriteMiddleware,\n createBlockTrackerInspectorMiddleware,\n createInflightCacheMiddleware,\n createFetchMiddleware,\n createRetryOnEmptyMiddleware,\n} from '@metamask/eth-json-rpc-middleware';\nimport {\n InternalProvider,\n providerFromMiddleware,\n} from '@metamask/eth-json-rpc-provider';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n JsonRpcEngine,\n mergeMiddleware,\n} from '@metamask/json-rpc-engine';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport type { Hex, Json, JsonRpcParams } from '@metamask/utils';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport { RpcServiceChain } from './rpc-service/rpc-service-chain';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\nimport { NetworkClientType } from './types';\n\nconst SECOND = 1000;\n\n/**\n * The pair of provider / block tracker that can be used to interface with the\n * network and respond to new activity.\n */\nexport type NetworkClient = {\n configuration: NetworkClientConfiguration;\n provider: Provider;\n blockTracker: BlockTracker;\n destroy: () => void;\n};\n\n/**\n * Create a JSON RPC network client for a specific network.\n *\n * @param args - The arguments.\n * @param args.configuration - The network configuration.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable. This effectively\n * causes the `failoverRpcUrls` property of the network client configuration\n * to be honored or ignored.\n * @param args.logger - A `loglevel` logger.\n * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n}: {\n configuration: NetworkClientConfiguration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): NetworkClient {\n const primaryEndpointUrl =\n configuration.type === NetworkClientType.Infura\n ? `https://${configuration.network}.infura.io/v3/${configuration.infuraProjectId}`\n : configuration.rpcUrl;\n const availableEndpointUrls = isRpcFailoverEnabled\n ? [primaryEndpointUrl, ...(configuration.failoverRpcUrls ?? [])]\n : [primaryEndpointUrl];\n const rpcServiceChain = new RpcServiceChain(\n availableEndpointUrls.map((endpointUrl) => ({\n ...getRpcServiceOptions(endpointUrl),\n endpointUrl,\n logger,\n })),\n );\n rpcServiceChain.onBreak(({ endpointUrl, failoverEndpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointUnavailable', {\n chainId: configuration.chainId,\n endpointUrl,\n failoverEndpointUrl,\n error,\n });\n });\n rpcServiceChain.onDegraded(({ endpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointDegraded', {\n chainId: configuration.chainId,\n endpointUrl,\n error,\n });\n });\n rpcServiceChain.onRetry(({ endpointUrl, attempt }) => {\n messenger.publish('NetworkController:rpcEndpointRequestRetried', {\n endpointUrl,\n attempt,\n });\n });\n\n const rpcApiMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraMiddleware({\n rpcService: rpcServiceChain,\n options: {\n source: 'metamask',\n },\n })\n : createFetchMiddleware({ rpcService: rpcServiceChain });\n\n const rpcProvider = providerFromMiddleware(rpcApiMiddleware);\n\n const blockTracker = createBlockTracker({\n networkClientType: configuration.type,\n endpointUrl: primaryEndpointUrl,\n getOptions: getBlockTrackerOptions,\n provider: rpcProvider,\n });\n\n const networkMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraNetworkMiddleware({\n blockTracker,\n network: configuration.network,\n rpcProvider,\n rpcApiMiddleware,\n })\n : createCustomNetworkMiddleware({\n blockTracker,\n chainId: configuration.chainId,\n rpcApiMiddleware,\n });\n\n const engine = new JsonRpcEngine();\n\n engine.push(networkMiddleware);\n\n const provider: Provider = new InternalProvider({ engine });\n\n const destroy = () => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n blockTracker.destroy();\n };\n\n return { configuration, provider, blockTracker, destroy };\n}\n\n/**\n * Create the block tracker for the network.\n *\n * @param args - The arguments.\n * @param args.networkClientType - The type of the network client (\"infura\" or\n * \"custom\").\n * @param args.endpointUrl - The URL of the endpoint.\n * @param args.getOptions - Factory for the block tracker options.\n * @param args.provider - The EIP-1193 provider for the network's JSON-RPC\n * middleware stack.\n * @returns The created block tracker.\n */\nfunction createBlockTracker({\n networkClientType,\n endpointUrl,\n getOptions,\n provider,\n}: {\n networkClientType: NetworkClientType;\n endpointUrl: string;\n getOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n provider: InternalProvider;\n}) {\n const testOptions =\n process.env.IN_TEST && networkClientType === NetworkClientType.Custom\n ? { pollingInterval: SECOND }\n : {};\n\n return new PollingBlockTracker({\n ...testOptions,\n ...getOptions(endpointUrl),\n provider,\n });\n}\n\n/**\n * Create middleware for infura.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.network - The Infura network to use.\n * @param args.rpcProvider - The RPC provider to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createInfuraNetworkMiddleware({\n blockTracker,\n network,\n rpcProvider,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n network: InfuraNetworkType;\n rpcProvider: InternalProvider;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}) {\n return mergeMiddleware([\n createNetworkAndChainIdMiddleware({ network }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockRefMiddleware({ blockTracker, provider: rpcProvider }),\n createRetryOnEmptyMiddleware({ blockTracker, provider: rpcProvider }),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * Creates static method middleware.\n *\n * @param args - The Arguments.\n * @param args.network - The Infura network to use.\n * @returns The middleware that implements the eth_chainId method.\n */\nfunction createNetworkAndChainIdMiddleware({\n network,\n}: {\n network: InfuraNetworkType;\n}) {\n return createScaffoldMiddleware({\n eth_chainId: ChainId[network],\n });\n}\n\nconst createChainIdMiddleware = (\n chainId: Hex,\n): JsonRpcMiddleware<JsonRpcParams, Json> => {\n return (req, res, next, end) => {\n if (req.method === 'eth_chainId') {\n res.result = chainId;\n return end();\n }\n return next();\n };\n};\n\n/**\n * Creates custom middleware.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.chainId - The chain id to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createCustomNetworkMiddleware({\n blockTracker,\n chainId,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n chainId: Hex;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n const testMiddlewares = process.env.IN_TEST\n ? [createEstimateGasDelayTestMiddleware()]\n : [];\n\n return mergeMiddleware([\n ...testMiddlewares,\n createChainIdMiddleware(chainId),\n createBlockRefRewriteMiddleware({ blockTracker }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * For use in tests only.\n * Adds a delay to `eth_estimateGas` calls.\n *\n * @returns The middleware for delaying gas estimation calls by 2 seconds when in test.\n */\nfunction createEstimateGasDelayTestMiddleware() {\n return createAsyncMiddleware(async (req, _, next) => {\n if (req.method === 'eth_estimateGas') {\n await new Promise((resolve) => setTimeout(resolve, SECOND * 2));\n }\n return next();\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create-network-client.cjs","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":";;;AACA,iEAAqD;AAErD,mEAAkE;AAClE,uEAAuE;AACvE,+EAQ2C;AAC3C,2EAGyC;AACzC,+DAKmC;AAOnC,2EAAkE;AAMlE,uCAA4C;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAgB,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,EACpB,MAAM,GAYP;IACC,MAAM,kBAAkB,GACtB,aAAa,CAAC,IAAI,KAAK,yBAAiB,CAAC,MAAM;QAC7C,CAAC,CAAC,WAAW,aAAa,CAAC,OAAO,iBAAiB,aAAa,CAAC,eAAe,EAAE;QAClF,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC;IAC3B,MAAM,qBAAqB,GAAG,oBAAoB;QAChD,CAAC,CAAC,CAAC,kBAAkB,EAAE,GAAG,CAAC,aAAa,CAAC,eAA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/controller-utils';\nimport { ChainId } from '@metamask/controller-utils';\nimport type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createInfuraMiddleware } from '@metamask/eth-json-rpc-infura';\nimport {\n createBlockCacheMiddleware,\n createBlockRefMiddleware,\n createBlockRefRewriteMiddleware,\n createBlockTrackerInspectorMiddleware,\n createInflightCacheMiddleware,\n createFetchMiddleware,\n createRetryOnEmptyMiddleware,\n} from '@metamask/eth-json-rpc-middleware';\nimport {\n InternalProvider,\n providerFromMiddleware,\n} from '@metamask/eth-json-rpc-provider';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n JsonRpcEngine,\n mergeMiddleware,\n} from '@metamask/json-rpc-engine';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport type { Hex, Json, JsonRpcParams } from '@metamask/utils';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport { RpcServiceChain } from './rpc-service/rpc-service-chain';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\nimport { NetworkClientType } from './types';\n\nconst SECOND = 1000;\n\n/**\n * The pair of provider / block tracker that can be used to interface with the\n * network and respond to new activity.\n */\nexport type NetworkClient = {\n configuration: NetworkClientConfiguration;\n provider: Provider;\n blockTracker: BlockTracker;\n destroy: () => void;\n};\n\n/**\n * Create a JSON RPC network client for a specific network.\n *\n * @param args - The arguments.\n * @param args.configuration - The network configuration.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable. This effectively\n * causes the `failoverRpcUrls` property of the network client configuration\n * to be honored or ignored.\n * @param args.logger - A `loglevel` logger.\n * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n}: {\n configuration: NetworkClientConfiguration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): NetworkClient {\n const primaryEndpointUrl =\n configuration.type === NetworkClientType.Infura\n ? `https://${configuration.network}.infura.io/v3/${configuration.infuraProjectId}`\n : configuration.rpcUrl;\n const availableEndpointUrls = isRpcFailoverEnabled\n ? [primaryEndpointUrl, ...(configuration.failoverRpcUrls ?? [])]\n : [primaryEndpointUrl];\n const rpcServiceChain = new RpcServiceChain(\n availableEndpointUrls.map((endpointUrl) => ({\n ...getRpcServiceOptions(endpointUrl),\n endpointUrl,\n logger,\n })),\n );\n rpcServiceChain.onBreak(({ endpointUrl, failoverEndpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointUnavailable', {\n chainId: configuration.chainId,\n endpointUrl,\n failoverEndpointUrl,\n error,\n });\n });\n rpcServiceChain.onDegraded(({ endpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointDegraded', {\n chainId: configuration.chainId,\n endpointUrl,\n error,\n });\n });\n rpcServiceChain.onRetry(({ endpointUrl, attempt }) => {\n messenger.publish('NetworkController:rpcEndpointRequestRetried', {\n endpointUrl,\n attempt,\n });\n });\n\n const rpcApiMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraMiddleware({\n rpcService: rpcServiceChain,\n options: {\n source: 'metamask',\n },\n })\n : createFetchMiddleware({ rpcService: rpcServiceChain });\n\n const rpcProvider = providerFromMiddleware(rpcApiMiddleware);\n\n const blockTracker = createBlockTracker({\n networkClientType: configuration.type,\n endpointUrl: primaryEndpointUrl,\n getOptions: getBlockTrackerOptions,\n provider: rpcProvider,\n });\n\n const networkMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraNetworkMiddleware({\n blockTracker,\n network: configuration.network,\n rpcProvider,\n rpcApiMiddleware,\n })\n : createCustomNetworkMiddleware({\n blockTracker,\n chainId: configuration.chainId,\n rpcApiMiddleware,\n });\n\n const engine = new JsonRpcEngine();\n\n engine.push(networkMiddleware);\n\n const provider: Provider = new InternalProvider({ engine });\n\n const destroy = () => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n blockTracker.destroy();\n };\n\n return { configuration, provider, blockTracker, destroy };\n}\n\n/**\n * Create the block tracker for the network.\n *\n * @param args - The arguments.\n * @param args.networkClientType - The type of the network client (\"infura\" or\n * \"custom\").\n * @param args.endpointUrl - The URL of the endpoint.\n * @param args.getOptions - Factory for the block tracker options.\n * @param args.provider - The EIP-1193 provider for the network's JSON-RPC\n * middleware stack.\n * @returns The created block tracker.\n */\nfunction createBlockTracker({\n networkClientType,\n endpointUrl,\n getOptions,\n provider,\n}: {\n networkClientType: NetworkClientType;\n endpointUrl: string;\n getOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n provider: InternalProvider;\n}) {\n const testOptions =\n process.env.IN_TEST && networkClientType === NetworkClientType.Custom\n ? { pollingInterval: SECOND }\n : {};\n\n return new PollingBlockTracker({\n ...testOptions,\n ...getOptions(endpointUrl),\n provider,\n });\n}\n\n/**\n * Create middleware for infura.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.network - The Infura network to use.\n * @param args.rpcProvider - The RPC provider to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createInfuraNetworkMiddleware({\n blockTracker,\n network,\n rpcProvider,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n network: InfuraNetworkType;\n rpcProvider: InternalProvider;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}) {\n return mergeMiddleware([\n createNetworkAndChainIdMiddleware({ network }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockRefMiddleware({ blockTracker, provider: rpcProvider }),\n createRetryOnEmptyMiddleware({ blockTracker, provider: rpcProvider }),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * Creates static method middleware.\n *\n * @param args - The Arguments.\n * @param args.network - The Infura network to use.\n * @returns The middleware that implements the eth_chainId method.\n */\nfunction createNetworkAndChainIdMiddleware({\n network,\n}: {\n network: InfuraNetworkType;\n}) {\n return createScaffoldMiddleware({\n eth_chainId: ChainId[network],\n });\n}\n\nconst createChainIdMiddleware = (\n chainId: Hex,\n): JsonRpcMiddleware<JsonRpcParams, Json> => {\n return (req, res, next, end) => {\n if (req.method === 'eth_chainId') {\n res.result = chainId;\n return end();\n }\n return next();\n };\n};\n\n/**\n * Creates custom middleware.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.chainId - The chain id to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createCustomNetworkMiddleware({\n blockTracker,\n chainId,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n chainId: Hex;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n const testMiddlewares = process.env.IN_TEST\n ? [createEstimateGasDelayTestMiddleware()]\n : [];\n\n return mergeMiddleware([\n ...testMiddlewares,\n createChainIdMiddleware(chainId),\n createBlockRefRewriteMiddleware({ blockTracker }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * For use in tests only.\n * Adds a delay to `eth_estimateGas` calls.\n *\n * @returns The middleware for delaying gas estimation calls by 2 seconds when in test.\n */\nfunction createEstimateGasDelayTestMiddleware() {\n return createAsyncMiddleware(async (req, _, next) => {\n if (req.method === 'eth_estimateGas') {\n await new Promise((resolve) => setTimeout(resolve, SECOND * 2));\n }\n return next();\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-network-client.mjs","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,mCAAmC;AAErD,OAAO,EAAE,mBAAmB,EAAE,oCAAoC;AAClE,OAAO,EAAE,sBAAsB,EAAE,sCAAsC;AACvE,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,+BAA+B,EAC/B,qCAAqC,EACrC,6BAA6B,EAC7B,qBAAqB,EACrB,4BAA4B,EAC7B,0CAA0C;AAC3C,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACvB,wCAAwC;AACzC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,eAAe,EAChB,kCAAkC;AAOnC,OAAO,EAAE,eAAe,EAAE,4CAAwC;AAMlE,OAAO,EAAE,iBAAiB,EAAE,oBAAgB;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,EACpB,MAAM,GAYP;IACC,MAAM,kBAAkB,GACtB,aA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AAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { InfuraNetworkType } from '@metamask/controller-utils';\nimport { ChainId } from '@metamask/controller-utils';\nimport type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createInfuraMiddleware } from '@metamask/eth-json-rpc-infura';\nimport {\n createBlockCacheMiddleware,\n createBlockRefMiddleware,\n createBlockRefRewriteMiddleware,\n createBlockTrackerInspectorMiddleware,\n createInflightCacheMiddleware,\n createFetchMiddleware,\n createRetryOnEmptyMiddleware,\n} from '@metamask/eth-json-rpc-middleware';\nimport {\n InternalProvider,\n providerFromMiddleware,\n} from '@metamask/eth-json-rpc-provider';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n JsonRpcEngine,\n mergeMiddleware,\n} from '@metamask/json-rpc-engine';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport type { Hex, Json, JsonRpcParams } from '@metamask/utils';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport { RpcServiceChain } from './rpc-service/rpc-service-chain';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\nimport { NetworkClientType } from './types';\n\nconst SECOND = 1000;\n\n/**\n * The pair of provider / block tracker that can be used to interface with the\n * network and respond to new activity.\n */\nexport type NetworkClient = {\n configuration: NetworkClientConfiguration;\n provider: Provider;\n blockTracker: BlockTracker;\n destroy: () => void;\n};\n\n/**\n * Create a JSON RPC network client for a specific network.\n *\n * @param args - The arguments.\n * @param args.configuration - The network configuration.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable. This effectively\n * causes the `failoverRpcUrls` property of the network client configuration\n * to be honored or ignored.\n * @param args.logger - A `loglevel` logger.\n * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n}: {\n configuration: NetworkClientConfiguration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): NetworkClient {\n const primaryEndpointUrl =\n configuration.type === NetworkClientType.Infura\n ? `https://${configuration.network}.infura.io/v3/${configuration.infuraProjectId}`\n : configuration.rpcUrl;\n const availableEndpointUrls = isRpcFailoverEnabled\n ? [primaryEndpointUrl, ...(configuration.failoverRpcUrls ?? [])]\n : [primaryEndpointUrl];\n const rpcServiceChain = new RpcServiceChain(\n availableEndpointUrls.map((endpointUrl) => ({\n ...getRpcServiceOptions(endpointUrl),\n endpointUrl,\n logger,\n })),\n );\n rpcServiceChain.onBreak(({ endpointUrl, failoverEndpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointUnavailable', {\n chainId: configuration.chainId,\n endpointUrl,\n failoverEndpointUrl,\n error,\n });\n });\n rpcServiceChain.onDegraded(({ endpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointDegraded', {\n chainId: configuration.chainId,\n endpointUrl,\n error,\n });\n });\n rpcServiceChain.onRetry(({ endpointUrl, attempt }) => {\n messenger.publish('NetworkController:rpcEndpointRequestRetried', {\n endpointUrl,\n attempt,\n });\n });\n\n const rpcApiMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraMiddleware({\n rpcService: rpcServiceChain,\n options: {\n source: 'metamask',\n },\n })\n : createFetchMiddleware({ rpcService: rpcServiceChain });\n\n const rpcProvider = providerFromMiddleware(rpcApiMiddleware);\n\n const blockTracker = createBlockTracker({\n networkClientType: configuration.type,\n endpointUrl: primaryEndpointUrl,\n getOptions: getBlockTrackerOptions,\n provider: rpcProvider,\n });\n\n const networkMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraNetworkMiddleware({\n blockTracker,\n network: configuration.network,\n rpcProvider,\n rpcApiMiddleware,\n })\n : createCustomNetworkMiddleware({\n blockTracker,\n chainId: configuration.chainId,\n rpcApiMiddleware,\n });\n\n const engine = new JsonRpcEngine();\n\n engine.push(networkMiddleware);\n\n const provider: Provider = new InternalProvider({ engine });\n\n const destroy = () => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n blockTracker.destroy();\n };\n\n return { configuration, provider, blockTracker, destroy };\n}\n\n/**\n * Create the block tracker for the network.\n *\n * @param args - The arguments.\n * @param args.networkClientType - The type of the network client (\"infura\" or\n * \"custom\").\n * @param args.endpointUrl - The URL of the endpoint.\n * @param args.getOptions - Factory for the block tracker options.\n * @param args.provider - The EIP-1193 provider for the network's JSON-RPC\n * middleware stack.\n * @returns The created block tracker.\n */\nfunction createBlockTracker({\n networkClientType,\n endpointUrl,\n getOptions,\n provider,\n}: {\n networkClientType: NetworkClientType;\n endpointUrl: string;\n getOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n provider: InternalProvider;\n}) {\n const testOptions =\n process.env.IN_TEST && networkClientType === NetworkClientType.Custom\n ? { pollingInterval: SECOND }\n : {};\n\n return new PollingBlockTracker({\n ...testOptions,\n ...getOptions(endpointUrl),\n provider,\n });\n}\n\n/**\n * Create middleware for infura.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.network - The Infura network to use.\n * @param args.rpcProvider - The RPC provider to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createInfuraNetworkMiddleware({\n blockTracker,\n network,\n rpcProvider,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n network: InfuraNetworkType;\n rpcProvider: InternalProvider;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}) {\n return mergeMiddleware([\n createNetworkAndChainIdMiddleware({ network }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockRefMiddleware({ blockTracker, provider: rpcProvider }),\n createRetryOnEmptyMiddleware({ blockTracker, provider: rpcProvider }),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * Creates static method middleware.\n *\n * @param args - The Arguments.\n * @param args.network - The Infura network to use.\n * @returns The middleware that implements the eth_chainId method.\n */\nfunction createNetworkAndChainIdMiddleware({\n network,\n}: {\n network: InfuraNetworkType;\n}) {\n return createScaffoldMiddleware({\n eth_chainId: ChainId[network],\n });\n}\n\nconst createChainIdMiddleware = (\n chainId: Hex,\n): JsonRpcMiddleware<JsonRpcParams, Json> => {\n return (req, res, next, end) => {\n if (req.method === 'eth_chainId') {\n res.result = chainId;\n return end();\n }\n return next();\n };\n};\n\n/**\n * Creates custom middleware.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.chainId - The chain id to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createCustomNetworkMiddleware({\n blockTracker,\n chainId,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n chainId: Hex;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n const testMiddlewares = process.env.IN_TEST\n ? [createEstimateGasDelayTestMiddleware()]\n : [];\n\n return mergeMiddleware([\n ...testMiddlewares,\n createChainIdMiddleware(chainId),\n createBlockRefRewriteMiddleware({ blockTracker }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * For use in tests only.\n * Adds a delay to `eth_estimateGas` calls.\n *\n * @returns The middleware for delaying gas estimation calls by 2 seconds when in test.\n */\nfunction createEstimateGasDelayTestMiddleware() {\n return createAsyncMiddleware(async (req, _, next) => {\n if (req.method === 'eth_estimateGas') {\n await new Promise((resolve) => setTimeout(resolve, SECOND * 2));\n }\n return next();\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create-network-client.mjs","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,mCAAmC;AAErD,OAAO,EAAE,mBAAmB,EAAE,oCAAoC;AAClE,OAAO,EAAE,sBAAsB,EAAE,sCAAsC;AACvE,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,+BAA+B,EAC/B,qCAAqC,EACrC,6BAA6B,EAC7B,qBAAqB,EACrB,4BAA4B,EAC7B,0CAA0C;AAC3C,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACvB,wCAAwC;AACzC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,eAAe,EAChB,kCAAkC;AAOnC,OAAO,EAAE,eAAe,EAAE,4CAAwC;AAMlE,OAAO,EAAE,iBAAiB,EAAE,oBAAgB;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBA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C,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;QAClE,CAAC;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { InfuraNetworkType } from '@metamask/controller-utils';\nimport { ChainId } from '@metamask/controller-utils';\nimport type { PollingBlockTrackerOptions } from '@metamask/eth-block-tracker';\nimport { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createInfuraMiddleware } from '@metamask/eth-json-rpc-infura';\nimport {\n createBlockCacheMiddleware,\n createBlockRefMiddleware,\n createBlockRefRewriteMiddleware,\n createBlockTrackerInspectorMiddleware,\n createInflightCacheMiddleware,\n createFetchMiddleware,\n createRetryOnEmptyMiddleware,\n} from '@metamask/eth-json-rpc-middleware';\nimport {\n InternalProvider,\n providerFromMiddleware,\n} from '@metamask/eth-json-rpc-provider';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n JsonRpcEngine,\n mergeMiddleware,\n} from '@metamask/json-rpc-engine';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport type { Hex, Json, JsonRpcParams } from '@metamask/utils';\nimport type { Logger } from 'loglevel';\n\nimport type { NetworkControllerMessenger } from './NetworkController';\nimport type { RpcServiceOptions } from './rpc-service/rpc-service';\nimport { RpcServiceChain } from './rpc-service/rpc-service-chain';\nimport type {\n BlockTracker,\n NetworkClientConfiguration,\n Provider,\n} from './types';\nimport { NetworkClientType } from './types';\n\nconst SECOND = 1000;\n\n/**\n * The pair of provider / block tracker that can be used to interface with the\n * network and respond to new activity.\n */\nexport type NetworkClient = {\n configuration: NetworkClientConfiguration;\n provider: Provider;\n blockTracker: BlockTracker;\n destroy: () => void;\n};\n\n/**\n * Create a JSON RPC network client for a specific network.\n *\n * @param args - The arguments.\n * @param args.configuration - The network configuration.\n * @param args.getRpcServiceOptions - Factory for constructing RPC service\n * options. See {@link NetworkControllerOptions.getRpcServiceOptions}.\n * @param args.getBlockTrackerOptions - Factory for constructing block tracker\n * options. See {@link NetworkControllerOptions.getBlockTrackerOptions}.\n * @param args.messenger - The network controller messenger.\n * @param args.isRpcFailoverEnabled - Whether or not requests sent to the\n * primary RPC endpoint for this network should be automatically diverted to\n * provided failover endpoints if the primary is unavailable. This effectively\n * causes the `failoverRpcUrls` property of the network client configuration\n * to be honored or ignored.\n * @param args.logger - A `loglevel` logger.\n * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\n logger,\n}: {\n configuration: NetworkClientConfiguration;\n getRpcServiceOptions: (\n rpcEndpointUrl: string,\n ) => Omit<RpcServiceOptions, 'failoverService' | 'endpointUrl'>;\n getBlockTrackerOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n messenger: NetworkControllerMessenger;\n isRpcFailoverEnabled: boolean;\n logger?: Logger;\n}): NetworkClient {\n const primaryEndpointUrl =\n configuration.type === NetworkClientType.Infura\n ? `https://${configuration.network}.infura.io/v3/${configuration.infuraProjectId}`\n : configuration.rpcUrl;\n const availableEndpointUrls = isRpcFailoverEnabled\n ? [primaryEndpointUrl, ...(configuration.failoverRpcUrls ?? [])]\n : [primaryEndpointUrl];\n const rpcServiceChain = new RpcServiceChain(\n availableEndpointUrls.map((endpointUrl) => ({\n ...getRpcServiceOptions(endpointUrl),\n endpointUrl,\n logger,\n })),\n );\n rpcServiceChain.onBreak(({ endpointUrl, failoverEndpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointUnavailable', {\n chainId: configuration.chainId,\n endpointUrl,\n failoverEndpointUrl,\n error,\n });\n });\n rpcServiceChain.onDegraded(({ endpointUrl, ...rest }) => {\n let error: unknown;\n if ('error' in rest) {\n error = rest.error;\n } else if ('value' in rest) {\n error = rest.value;\n }\n\n messenger.publish('NetworkController:rpcEndpointDegraded', {\n chainId: configuration.chainId,\n endpointUrl,\n error,\n });\n });\n rpcServiceChain.onRetry(({ endpointUrl, attempt }) => {\n messenger.publish('NetworkController:rpcEndpointRequestRetried', {\n endpointUrl,\n attempt,\n });\n });\n\n const rpcApiMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraMiddleware({\n rpcService: rpcServiceChain,\n options: {\n source: 'metamask',\n },\n })\n : createFetchMiddleware({ rpcService: rpcServiceChain });\n\n const rpcProvider = providerFromMiddleware(rpcApiMiddleware);\n\n const blockTracker = createBlockTracker({\n networkClientType: configuration.type,\n endpointUrl: primaryEndpointUrl,\n getOptions: getBlockTrackerOptions,\n provider: rpcProvider,\n });\n\n const networkMiddleware =\n configuration.type === NetworkClientType.Infura\n ? createInfuraNetworkMiddleware({\n blockTracker,\n network: configuration.network,\n rpcProvider,\n rpcApiMiddleware,\n })\n : createCustomNetworkMiddleware({\n blockTracker,\n chainId: configuration.chainId,\n rpcApiMiddleware,\n });\n\n const engine = new JsonRpcEngine();\n\n engine.push(networkMiddleware);\n\n const provider: Provider = new InternalProvider({ engine });\n\n const destroy = () => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n blockTracker.destroy();\n };\n\n return { configuration, provider, blockTracker, destroy };\n}\n\n/**\n * Create the block tracker for the network.\n *\n * @param args - The arguments.\n * @param args.networkClientType - The type of the network client (\"infura\" or\n * \"custom\").\n * @param args.endpointUrl - The URL of the endpoint.\n * @param args.getOptions - Factory for the block tracker options.\n * @param args.provider - The EIP-1193 provider for the network's JSON-RPC\n * middleware stack.\n * @returns The created block tracker.\n */\nfunction createBlockTracker({\n networkClientType,\n endpointUrl,\n getOptions,\n provider,\n}: {\n networkClientType: NetworkClientType;\n endpointUrl: string;\n getOptions: (\n rpcEndpointUrl: string,\n ) => Omit<PollingBlockTrackerOptions, 'provider'>;\n provider: InternalProvider;\n}) {\n const testOptions =\n process.env.IN_TEST && networkClientType === NetworkClientType.Custom\n ? { pollingInterval: SECOND }\n : {};\n\n return new PollingBlockTracker({\n ...testOptions,\n ...getOptions(endpointUrl),\n provider,\n });\n}\n\n/**\n * Create middleware for infura.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.network - The Infura network to use.\n * @param args.rpcProvider - The RPC provider to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createInfuraNetworkMiddleware({\n blockTracker,\n network,\n rpcProvider,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n network: InfuraNetworkType;\n rpcProvider: InternalProvider;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}) {\n return mergeMiddleware([\n createNetworkAndChainIdMiddleware({ network }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockRefMiddleware({ blockTracker, provider: rpcProvider }),\n createRetryOnEmptyMiddleware({ blockTracker, provider: rpcProvider }),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * Creates static method middleware.\n *\n * @param args - The Arguments.\n * @param args.network - The Infura network to use.\n * @returns The middleware that implements the eth_chainId method.\n */\nfunction createNetworkAndChainIdMiddleware({\n network,\n}: {\n network: InfuraNetworkType;\n}) {\n return createScaffoldMiddleware({\n eth_chainId: ChainId[network],\n });\n}\n\nconst createChainIdMiddleware = (\n chainId: Hex,\n): JsonRpcMiddleware<JsonRpcParams, Json> => {\n return (req, res, next, end) => {\n if (req.method === 'eth_chainId') {\n res.result = chainId;\n return end();\n }\n return next();\n };\n};\n\n/**\n * Creates custom middleware.\n *\n * @param args - The arguments.\n * @param args.blockTracker - The block tracker to use.\n * @param args.chainId - The chain id to use.\n * @param args.rpcApiMiddleware - Additional middleware.\n * @returns The collection of middleware that makes up the Infura client.\n */\nfunction createCustomNetworkMiddleware({\n blockTracker,\n chainId,\n rpcApiMiddleware,\n}: {\n blockTracker: PollingBlockTracker;\n chainId: Hex;\n rpcApiMiddleware: JsonRpcMiddleware<JsonRpcParams, Json>;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n const testMiddlewares = process.env.IN_TEST\n ? [createEstimateGasDelayTestMiddleware()]\n : [];\n\n return mergeMiddleware([\n ...testMiddlewares,\n createChainIdMiddleware(chainId),\n createBlockRefRewriteMiddleware({ blockTracker }),\n createBlockCacheMiddleware({ blockTracker }),\n createInflightCacheMiddleware(),\n createBlockTrackerInspectorMiddleware({ blockTracker }),\n rpcApiMiddleware,\n ]);\n}\n\n/**\n * For use in tests only.\n * Adds a delay to `eth_estimateGas` calls.\n *\n * @returns The middleware for delaying gas estimation calls by 2 seconds when in test.\n */\nfunction createEstimateGasDelayTestMiddleware() {\n return createAsyncMiddleware(async (req, _, next) => {\n if (req.method === 'eth_estimateGas') {\n await new Promise((resolve) => setTimeout(resolve, SECOND * 2));\n }\n return next();\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-service.cjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,iEAMoC;AACpC,qDAA+D;AAE/D,2CAOyB;AACzB,0DAAkC;AA8ClC;;;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,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,EA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,EAAE,CAAC;YACjD,MAAM,qCAAqC,GAAG,IAAI,CAAC,YAAY,CAC7D,SAAS,EACT,EAAE,qBAAqB,EAAE,CAAC,EAAE,CAC7B,CAAC,MAAM,CACN,CAAC,4BAA4B,IAAI,uBAAA,IAAI,0BAAQ,CAAC,oBAAoB,CAAC;gBACjE,gBAAQ,CAAC,MAAM,CAClB,CAAC;YACF,MAAM,sBAAS,CAAC,mBAAmB,CAAC;gBAClC,OAAO,EAAE,sDAAsD,qCAAqC,oDAAoD;aACzJ,CAAC,CAAC;SACJ;QACD,MAAM,KAAK,CAAC;KACb;AACH,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport {\n BrokenCircuitError,\n CircuitState,\n HttpError,\n createServicePolicy,\n handleWhen,\n} from '@metamask/controller-utils';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport {\n Duration,\n getErrorMessage,\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcResponse,\n} from '@metamask/utils';\nimport deepmerge from 'deepmerge';\nimport type { Logger } from 'loglevel';\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 * A `loglevel` logger.\n */\n logger?: Pick<Logger, 'warn'>;\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 * Custom JSON-RPC error codes for specific cases.\n *\n * These should be moved to `@metamask/rpc-errors` eventually.\n */\nexport const CUSTOM_RPC_ERRORS = {\n unauthorized: -32006,\n httpClientError: -32080,\n} as const;\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 * Determine whether the given error message indicates a failure to parse JSON.\n *\n * This is different in tests vs. implementation code because it may manifest as\n * a FetchError or a SyntaxError.\n *\n * @param error - The error object to test.\n * @returns True if the error indicates a JSON parse error, false otherwise.\n */\nfunction isJsonParseError(error: unknown) {\n return (\n error instanceof SyntaxError ||\n /invalid json/iu.test(getErrorMessage(error))\n );\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 * Strips username and password from a URL.\n *\n * @param url - The URL to strip credentials from.\n * @returns A new URL object with credentials removed.\n */\nfunction stripCredentialsFromUrl(url: URL): URL {\n const strippedUrl = new URL(url.toString());\n strippedUrl.username = '';\n strippedUrl.password = '';\n return strippedUrl;\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 * A `loglevel` logger.\n */\n readonly #logger: RpcServiceOptions['logger'];\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 logger,\n fetchOptions = {},\n policyOptions = {},\n } = options;\n\n this.#fetch = givenFetch;\n const normalizedUrl = getNormalizedEndpointUrl(endpointUrl);\n this.#fetchOptions = this.#getDefaultFetchOptions(\n normalizedUrl,\n fetchOptions,\n givenBtoa,\n );\n this.endpointUrl = stripCredentialsFromUrl(normalizedUrl);\n this.#failoverService = failoverService;\n this.#logger = logger;\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 isJsonParseError(error) ||\n // Ignore server overload errors\n ('httpStatus' in error &&\n (error.httpStatus === 502 ||\n error.httpStatus === 503 ||\n error.httpStatus === 504)) ||\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((data) => {\n listener({ ...(data ?? {}), 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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.#processRequest<Result>(completeFetchOptions);\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 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\n */\n async #processRequest<Result extends Json>(\n fetchOptions: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>> {\n let response: Response | undefined;\n try {\n return await this.#policy.execute(async () => {\n response = await this.#fetch(this.endpointUrl, fetchOptions);\n if (!response.ok) {\n throw new HttpError(response.status);\n }\n return await response.json();\n });\n } catch (error) {\n if (error instanceof HttpError) {\n const status = error.httpStatus;\n if (status === 401) {\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.unauthorized,\n 'Unauthorized.',\n {\n httpStatus: status,\n },\n );\n }\n if (status === 429) {\n throw rpcErrors.limitExceeded({\n message: 'Request is being rate limited.',\n data: {\n httpStatus: status,\n },\n });\n }\n if (status >= 500 || status === 402 || status === 404) {\n throw rpcErrors.resourceUnavailable({\n message: 'RPC endpoint not found or unavailable.',\n data: {\n httpStatus: status,\n },\n });\n }\n\n // Handle all other 4xx errors as generic HTTP client errors\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.httpClientError,\n 'RPC endpoint returned HTTP client error.',\n {\n httpStatus: status,\n },\n );\n } else if (isJsonParseError(error)) {\n throw rpcErrors.parse({\n message: 'RPC endpoint did not return JSON.',\n });\n } else if (error instanceof BrokenCircuitError) {\n this.#logger?.warn(error);\n const remainingCircuitOpenDuration =\n this.#policy.getRemainingCircuitOpenDuration();\n const formattedRemainingCircuitOpenDuration = Intl.NumberFormat(\n undefined,\n { maximumFractionDigits: 2 },\n ).format(\n (remainingCircuitOpenDuration ?? this.#policy.circuitBreakDuration) /\n Duration.Minute,\n );\n throw rpcErrors.resourceUnavailable({\n message: `RPC endpoint returned too many errors, retrying in ${formattedRemainingCircuitOpenDuration} minutes. Consider using a different RPC endpoint.`,\n });\n }\n throw error;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpc-service.cjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,iEAMoC;AACpC,qDAA+D;AAE/D,2CAOyB;AACzB,0DAAkC;AA8ClC;;;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,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;;;;GAIG;AACU,QAAA,iBAAiB,GAAG;IAC/B,YAAY,EAAE,CAAC,KAAK;IACpB,eAAe,EAAE,CAAC,K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icePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport {\n BrokenCircuitError,\n CircuitState,\n HttpError,\n createServicePolicy,\n handleWhen,\n} from '@metamask/controller-utils';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport {\n Duration,\n getErrorMessage,\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcResponse,\n} from '@metamask/utils';\nimport deepmerge from 'deepmerge';\nimport type { Logger } from 'loglevel';\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 * A `loglevel` logger.\n */\n logger?: Pick<Logger, 'warn'>;\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 * Custom JSON-RPC error codes for specific cases.\n *\n * These should be moved to `@metamask/rpc-errors` eventually.\n */\nexport const CUSTOM_RPC_ERRORS = {\n unauthorized: -32006,\n httpClientError: -32080,\n} as const;\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 * Determine whether the given error message indicates a failure to parse JSON.\n *\n * This is different in tests vs. implementation code because it may manifest as\n * a FetchError or a SyntaxError.\n *\n * @param error - The error object to test.\n * @returns True if the error indicates a JSON parse error, false otherwise.\n */\nfunction isJsonParseError(error: unknown) {\n return (\n error instanceof SyntaxError ||\n /invalid json/iu.test(getErrorMessage(error))\n );\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 * Strips username and password from a URL.\n *\n * @param url - The URL to strip credentials from.\n * @returns A new URL object with credentials removed.\n */\nfunction stripCredentialsFromUrl(url: URL): URL {\n const strippedUrl = new URL(url.toString());\n strippedUrl.username = '';\n strippedUrl.password = '';\n return strippedUrl;\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 * A `loglevel` logger.\n */\n readonly #logger: RpcServiceOptions['logger'];\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 logger,\n fetchOptions = {},\n policyOptions = {},\n } = options;\n\n this.#fetch = givenFetch;\n const normalizedUrl = getNormalizedEndpointUrl(endpointUrl);\n this.#fetchOptions = this.#getDefaultFetchOptions(\n normalizedUrl,\n fetchOptions,\n givenBtoa,\n );\n this.endpointUrl = stripCredentialsFromUrl(normalizedUrl);\n this.#failoverService = failoverService;\n this.#logger = logger;\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 isJsonParseError(error) ||\n // Ignore server overload errors\n ('httpStatus' in error &&\n (error.httpStatus === 502 ||\n error.httpStatus === 503 ||\n error.httpStatus === 504)) ||\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((data) => {\n listener({ ...(data ?? {}), 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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.#processRequest<Result>(completeFetchOptions);\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 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\n */\n async #processRequest<Result extends Json>(\n fetchOptions: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>> {\n let response: Response | undefined;\n try {\n return await this.#policy.execute(async () => {\n response = await this.#fetch(this.endpointUrl, fetchOptions);\n if (!response.ok) {\n throw new HttpError(response.status);\n }\n return await response.json();\n });\n } catch (error) {\n if (error instanceof HttpError) {\n const status = error.httpStatus;\n if (status === 401) {\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.unauthorized,\n 'Unauthorized.',\n {\n httpStatus: status,\n },\n );\n }\n if (status === 429) {\n throw rpcErrors.limitExceeded({\n message: 'Request is being rate limited.',\n data: {\n httpStatus: status,\n },\n });\n }\n if (status >= 500 || status === 402 || status === 404) {\n throw rpcErrors.resourceUnavailable({\n message: 'RPC endpoint not found or unavailable.',\n data: {\n httpStatus: status,\n },\n });\n }\n\n // Handle all other 4xx errors as generic HTTP client errors\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.httpClientError,\n 'RPC endpoint returned HTTP client error.',\n {\n httpStatus: status,\n },\n );\n } else if (isJsonParseError(error)) {\n throw rpcErrors.parse({\n message: 'RPC endpoint did not return JSON.',\n });\n } else if (error instanceof BrokenCircuitError) {\n this.#logger?.warn(error);\n const remainingCircuitOpenDuration =\n this.#policy.getRemainingCircuitOpenDuration();\n const formattedRemainingCircuitOpenDuration = Intl.NumberFormat(\n undefined,\n { maximumFractionDigits: 2 },\n ).format(\n (remainingCircuitOpenDuration ?? this.#policy.circuitBreakDuration) /\n Duration.Minute,\n );\n throw rpcErrors.resourceUnavailable({\n message: `RPC endpoint returned too many errors, retrying in ${formattedRemainingCircuitOpenDuration} minutes. Consider using a different RPC endpoint.`,\n });\n }\n throw error;\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-service.mjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,SAAS,EACT,mBAAmB,EACnB,UAAU,EACX,mCAAmC;AACpC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,6BAA6B;AAE/D,OAAO,EACL,QAAQ,EACR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A4D;YAC5D,MAAM,IAAI,YAAY,CACpB,iBAAiB,CAAC,eAAe,EACjC,0CAA0C,EAC1C;gBACE,UAAU,EAAE,MAAM;aACnB,CACF,CAAC;SACH;aAAM,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE;YAClC,MAAM,SAAS,CAAC,KAAK,CAAC;gBACpB,OAAO,EAAE,mCAAmC;aAC7C,CAAC,CAAC;SACJ;aAAM,IAAI,KAAK,YAAY,kBAAkB,EAAE;YAC9C,uBAAA,IAAI,0BAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;YAC1B,MAAM,4BAA4B,GAChC,uBAAA,IAAI,0BAAQ,CAAC,+BAA+B,EAAE,CAAC;YACjD,MAAM,qCAAqC,GAAG,IAAI,CAAC,YAAY,CAC7D,SAAS,EACT,EAAE,qBAAqB,EAAE,CAAC,EAAE,CAC7B,CAAC,MAAM,CACN,CAAC,4BAA4B,IAAI,uBAAA,IAAI,0BAAQ,CAAC,oBAAoB,CAAC;gBACjE,QAAQ,CAAC,MAAM,CAClB,CAAC;YACF,MAAM,SAAS,CAAC,mBAAmB,CAAC;gBAClC,OAAO,EAAE,sDAAsD,qCAAqC,oDAAoD;aACzJ,CAAC,CAAC;SACJ;QACD,MAAM,KAAK,CAAC;KACb;AACH,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport {\n BrokenCircuitError,\n CircuitState,\n HttpError,\n createServicePolicy,\n handleWhen,\n} from '@metamask/controller-utils';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport {\n Duration,\n getErrorMessage,\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcResponse,\n} from '@metamask/utils';\nimport deepmerge from 'deepmerge';\nimport type { Logger } from 'loglevel';\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 * A `loglevel` logger.\n */\n logger?: Pick<Logger, 'warn'>;\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 * Custom JSON-RPC error codes for specific cases.\n *\n * These should be moved to `@metamask/rpc-errors` eventually.\n */\nexport const CUSTOM_RPC_ERRORS = {\n unauthorized: -32006,\n httpClientError: -32080,\n} as const;\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 * Determine whether the given error message indicates a failure to parse JSON.\n *\n * This is different in tests vs. implementation code because it may manifest as\n * a FetchError or a SyntaxError.\n *\n * @param error - The error object to test.\n * @returns True if the error indicates a JSON parse error, false otherwise.\n */\nfunction isJsonParseError(error: unknown) {\n return (\n error instanceof SyntaxError ||\n /invalid json/iu.test(getErrorMessage(error))\n );\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 * Strips username and password from a URL.\n *\n * @param url - The URL to strip credentials from.\n * @returns A new URL object with credentials removed.\n */\nfunction stripCredentialsFromUrl(url: URL): URL {\n const strippedUrl = new URL(url.toString());\n strippedUrl.username = '';\n strippedUrl.password = '';\n return strippedUrl;\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 * A `loglevel` logger.\n */\n readonly #logger: RpcServiceOptions['logger'];\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 logger,\n fetchOptions = {},\n policyOptions = {},\n } = options;\n\n this.#fetch = givenFetch;\n const normalizedUrl = getNormalizedEndpointUrl(endpointUrl);\n this.#fetchOptions = this.#getDefaultFetchOptions(\n normalizedUrl,\n fetchOptions,\n givenBtoa,\n );\n this.endpointUrl = stripCredentialsFromUrl(normalizedUrl);\n this.#failoverService = failoverService;\n this.#logger = logger;\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 isJsonParseError(error) ||\n // Ignore server overload errors\n ('httpStatus' in error &&\n (error.httpStatus === 502 ||\n error.httpStatus === 503 ||\n error.httpStatus === 504)) ||\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((data) => {\n listener({ ...(data ?? {}), 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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.#processRequest<Result>(completeFetchOptions);\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 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\n */\n async #processRequest<Result extends Json>(\n fetchOptions: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>> {\n let response: Response | undefined;\n try {\n return await this.#policy.execute(async () => {\n response = await this.#fetch(this.endpointUrl, fetchOptions);\n if (!response.ok) {\n throw new HttpError(response.status);\n }\n return await response.json();\n });\n } catch (error) {\n if (error instanceof HttpError) {\n const status = error.httpStatus;\n if (status === 401) {\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.unauthorized,\n 'Unauthorized.',\n {\n httpStatus: status,\n },\n );\n }\n if (status === 429) {\n throw rpcErrors.limitExceeded({\n message: 'Request is being rate limited.',\n data: {\n httpStatus: status,\n },\n });\n }\n if (status >= 500 || status === 402 || status === 404) {\n throw rpcErrors.resourceUnavailable({\n message: 'RPC endpoint not found or unavailable.',\n data: {\n httpStatus: status,\n },\n });\n }\n\n // Handle all other 4xx errors as generic HTTP client errors\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.httpClientError,\n 'RPC endpoint returned HTTP client error.',\n {\n httpStatus: status,\n },\n );\n } else if (isJsonParseError(error)) {\n throw rpcErrors.parse({\n message: 'RPC endpoint did not return JSON.',\n });\n } else if (error instanceof BrokenCircuitError) {\n this.#logger?.warn(error);\n const remainingCircuitOpenDuration =\n this.#policy.getRemainingCircuitOpenDuration();\n const formattedRemainingCircuitOpenDuration = Intl.NumberFormat(\n undefined,\n { maximumFractionDigits: 2 },\n ).format(\n (remainingCircuitOpenDuration ?? this.#policy.circuitBreakDuration) /\n Duration.Minute,\n );\n throw rpcErrors.resourceUnavailable({\n message: `RPC endpoint returned too many errors, retrying in ${formattedRemainingCircuitOpenDuration} minutes. Consider using a different RPC endpoint.`,\n });\n }\n throw error;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpc-service.mjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,SAAS,EACT,mBAAmB,EACnB,UAAU,EACX,mCAAmC;AACpC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,6BAA6B;AAE/D,OAAO,EACL,QAAQ,EACR,eAAe,EACf,WAAW,EAIZ,wBAAwB;AACzB,OAAO,UAAS,kBAAkB;;AA8ClC;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;;;GAKG;AACH,MAAM,CAAC,MAAM,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;K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BAAkB,EAAE,CAAC;YAC/C,uBAAA,IAAI,0BAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;YAC1B,MAAM,4BAA4B,GAChC,uBAAA,IAAI,0BAAQ,CAAC,+BAA+B,EAAE,CAAC;YACjD,MAAM,qCAAqC,GAAG,IAAI,CAAC,YAAY,CAC7D,SAAS,EACT,EAAE,qBAAqB,EAAE,CAAC,EAAE,CAC7B,CAAC,MAAM,CACN,CAAC,4BAA4B,IAAI,uBAAA,IAAI,0BAAQ,CAAC,oBAAoB,CAAC;gBACjE,QAAQ,CAAC,MAAM,CAClB,CAAC;YACF,MAAM,SAAS,CAAC,mBAAmB,CAAC;gBAClC,OAAO,EAAE,sDAAsD,qCAAqC,oDAAoD;aACzJ,CAAC,CAAC;QACL,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport {\n BrokenCircuitError,\n CircuitState,\n HttpError,\n createServicePolicy,\n handleWhen,\n} from '@metamask/controller-utils';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport {\n Duration,\n getErrorMessage,\n hasProperty,\n type Json,\n type JsonRpcParams,\n type JsonRpcResponse,\n} from '@metamask/utils';\nimport deepmerge from 'deepmerge';\nimport type { Logger } from 'loglevel';\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 * A `loglevel` logger.\n */\n logger?: Pick<Logger, 'warn'>;\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 * Custom JSON-RPC error codes for specific cases.\n *\n * These should be moved to `@metamask/rpc-errors` eventually.\n */\nexport const CUSTOM_RPC_ERRORS = {\n unauthorized: -32006,\n httpClientError: -32080,\n} as const;\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 * Determine whether the given error message indicates a failure to parse JSON.\n *\n * This is different in tests vs. implementation code because it may manifest as\n * a FetchError or a SyntaxError.\n *\n * @param error - The error object to test.\n * @returns True if the error indicates a JSON parse error, false otherwise.\n */\nfunction isJsonParseError(error: unknown) {\n return (\n error instanceof SyntaxError ||\n /invalid json/iu.test(getErrorMessage(error))\n );\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 * Strips username and password from a URL.\n *\n * @param url - The URL to strip credentials from.\n * @returns A new URL object with credentials removed.\n */\nfunction stripCredentialsFromUrl(url: URL): URL {\n const strippedUrl = new URL(url.toString());\n strippedUrl.username = '';\n strippedUrl.password = '';\n return strippedUrl;\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 * A `loglevel` logger.\n */\n readonly #logger: RpcServiceOptions['logger'];\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 logger,\n fetchOptions = {},\n policyOptions = {},\n } = options;\n\n this.#fetch = givenFetch;\n const normalizedUrl = getNormalizedEndpointUrl(endpointUrl);\n this.#fetchOptions = this.#getDefaultFetchOptions(\n normalizedUrl,\n fetchOptions,\n givenBtoa,\n );\n this.endpointUrl = stripCredentialsFromUrl(normalizedUrl);\n this.#failoverService = failoverService;\n this.#logger = logger;\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 isJsonParseError(error) ||\n // Ignore server overload errors\n ('httpStatus' in error &&\n (error.httpStatus === 502 ||\n error.httpStatus === 503 ||\n error.httpStatus === 504)) ||\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((data) => {\n listener({ ...(data ?? {}), 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\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.#processRequest<Result>(completeFetchOptions);\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 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 An \"authorized\" JSON-RPC error (code -32006) if the response HTTP status is 401.\n * @throws A \"rate limiting\" JSON-RPC error (code -32005) if the response HTTP status is 429.\n * @throws A \"resource unavailable\" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.\n * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.\n * @throws A \"parse\" JSON-RPC error (code -32700) if the response is not valid JSON.\n */\n async #processRequest<Result extends Json>(\n fetchOptions: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>> {\n let response: Response | undefined;\n try {\n return await this.#policy.execute(async () => {\n response = await this.#fetch(this.endpointUrl, fetchOptions);\n if (!response.ok) {\n throw new HttpError(response.status);\n }\n return await response.json();\n });\n } catch (error) {\n if (error instanceof HttpError) {\n const status = error.httpStatus;\n if (status === 401) {\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.unauthorized,\n 'Unauthorized.',\n {\n httpStatus: status,\n },\n );\n }\n if (status === 429) {\n throw rpcErrors.limitExceeded({\n message: 'Request is being rate limited.',\n data: {\n httpStatus: status,\n },\n });\n }\n if (status >= 500 || status === 402 || status === 404) {\n throw rpcErrors.resourceUnavailable({\n message: 'RPC endpoint not found or unavailable.',\n data: {\n httpStatus: status,\n },\n });\n }\n\n // Handle all other 4xx errors as generic HTTP client errors\n throw new JsonRpcError(\n CUSTOM_RPC_ERRORS.httpClientError,\n 'RPC endpoint returned HTTP client error.',\n {\n httpStatus: status,\n },\n );\n } else if (isJsonParseError(error)) {\n throw rpcErrors.parse({\n message: 'RPC endpoint did not return JSON.',\n });\n } else if (error instanceof BrokenCircuitError) {\n this.#logger?.warn(error);\n const remainingCircuitOpenDuration =\n this.#policy.getRemainingCircuitOpenDuration();\n const formattedRemainingCircuitOpenDuration = Intl.NumberFormat(\n undefined,\n { maximumFractionDigits: 2 },\n ).format(\n (remainingCircuitOpenDuration ?? this.#policy.circuitBreakDuration) /\n Duration.Minute,\n );\n throw rpcErrors.resourceUnavailable({\n message: `RPC endpoint returned too many errors, retrying in ${formattedRemainingCircuitOpenDuration} minutes. Consider using a different RPC endpoint.`,\n });\n }\n throw error;\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/network-controller",
|
|
3
|
-
"version": "25.0.0-preview-
|
|
3
|
+
"version": "25.0.0-preview-1a8571ae",
|
|
4
4
|
"description": "Provides an interface to the currently selected network via a MetaMask-compatible provider object",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -87,7 +87,7 @@
|
|
|
87
87
|
"ts-jest": "^27.1.4",
|
|
88
88
|
"typedoc": "^0.24.8",
|
|
89
89
|
"typedoc-plugin-missing-exports": "^2.0.0",
|
|
90
|
-
"typescript": "~5.
|
|
90
|
+
"typescript": "~5.3.3"
|
|
91
91
|
},
|
|
92
92
|
"peerDependencies": {
|
|
93
93
|
"@metamask/error-reporting-service": "^3.0.0"
|