@metamask/network-controller 24.0.0 → 24.1.0

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.
Files changed (32) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/dist/NetworkController.cjs.map +1 -1
  3. package/dist/NetworkController.d.cts +1 -0
  4. package/dist/NetworkController.d.cts.map +1 -1
  5. package/dist/NetworkController.d.mts +1 -0
  6. package/dist/NetworkController.d.mts.map +1 -1
  7. package/dist/NetworkController.mjs.map +1 -1
  8. package/dist/create-network-client.cjs +9 -1
  9. package/dist/create-network-client.cjs.map +1 -1
  10. package/dist/create-network-client.d.cts.map +1 -1
  11. package/dist/create-network-client.d.mts.map +1 -1
  12. package/dist/create-network-client.mjs +9 -1
  13. package/dist/create-network-client.mjs.map +1 -1
  14. package/dist/rpc-service/rpc-service-chain.cjs.map +1 -1
  15. package/dist/rpc-service/rpc-service-chain.d.cts +10 -10
  16. package/dist/rpc-service/rpc-service-chain.d.mts +10 -10
  17. package/dist/rpc-service/rpc-service-chain.mjs.map +1 -1
  18. package/dist/rpc-service/rpc-service.cjs +68 -22
  19. package/dist/rpc-service/rpc-service.cjs.map +1 -1
  20. package/dist/rpc-service/rpc-service.d.cts +19 -10
  21. package/dist/rpc-service/rpc-service.d.cts.map +1 -1
  22. package/dist/rpc-service/rpc-service.d.mts +19 -10
  23. package/dist/rpc-service/rpc-service.d.mts.map +1 -1
  24. package/dist/rpc-service/rpc-service.mjs +69 -23
  25. package/dist/rpc-service/rpc-service.mjs.map +1 -1
  26. package/dist/rpc-service/shared.cjs.map +1 -1
  27. package/dist/rpc-service/shared.d.cts +1 -3
  28. package/dist/rpc-service/shared.d.cts.map +1 -1
  29. package/dist/rpc-service/shared.d.mts +1 -3
  30. package/dist/rpc-service/shared.d.mts.map +1 -1
  31. package/dist/rpc-service/shared.mjs.map +1 -1
  32. package/package.json +4 -4
@@ -53,10 +53,18 @@ function createNetworkClient({ configuration, getRpcServiceOptions, getBlockTrac
53
53
  error,
54
54
  });
55
55
  });
56
- rpcServiceChain.onDegraded(({ endpointUrl }) => {
56
+ rpcServiceChain.onDegraded(({ endpointUrl, ...rest }) => {
57
+ let error;
58
+ if ('error' in rest) {
59
+ error = rest.error;
60
+ }
61
+ else if ('value' in rest) {
62
+ error = rest.value;
63
+ }
57
64
  messenger.publish('NetworkController:rpcEndpointDegraded', {
58
65
  chainId: configuration.chainId,
59
66
  endpointUrl,
67
+ error,
60
68
  });
61
69
  });
62
70
  rpcServiceChain.onRetry(({ endpointUrl, attempt }) => {
@@ -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;AAE3C,2EAGyC;AACzC,+DAKmC;AAMnC,2EAAkE;AAMlE,uCAA4C;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,GAWrB;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,eAAe,IAAI,EAAE,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC;IACzB,MAAM,eAAe,GAAG,IAAI,mCAAe,CACzC,qBAAqB,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QAC1C,GAAG,oBAAoB,CAAC,WAAW,CAAC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QAC1C,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO,IAAA,iCAAe,EAAC;QACrB,GAAG,eAAe;QAClB,uBAAuB,CAAC,OAAO,CAAC;QAChC,IAAA,yDAA+B,EAAC,EAAE,YAAY,EAAE,CAAC;QACjD,IAAA,oDAA0B,EAAC,EAAE,YAAY,EAAE,CAAC;QAC5C,IAAA,uDAA6B,GAAE;QAC/B,IAAA,+DAAqC,EAAC,EAAE,YAAY,EAAE,CAAC;QACvD,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,oCAAoC;IAC3C,OAAO,IAAA,uCAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;QAClD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE;YACpC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;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 type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport {\n providerFromEngine,\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';\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 * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\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}): 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 })),\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 }) => {\n messenger.publish('NetworkController:rpcEndpointDegraded', {\n chainId: configuration.chainId,\n endpointUrl,\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 = providerFromEngine(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: SafeEventEmitterProvider;\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: SafeEventEmitterProvider;\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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":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5C,IAAA,uDAA6B,GAAE;QAC/B,IAAA,+DAAqC,EAAC,EAAE,YAAY,EAAE,CAAC;QACvD,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,oCAAoC;IAC3C,OAAO,IAAA,uCAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;QAClD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE;YACpC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;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 type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport {\n providerFromEngine,\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';\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 * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\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}): 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 })),\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 = providerFromEngine(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: SafeEventEmitterProvider;\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: SafeEventEmitterProvider;\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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.d.cts","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,0BAA0B,EAAE,oCAAoC;AA0B9E,OAAO,KAAK,EAAE,0BAA0B,EAAE,gCAA4B;AACtE,OAAO,KAAK,EAAE,i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C;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,GACrB,EAAE;IACD,aAAa,EAAE,0BAA0B,CAAC;IAC1C,oBAAoB,EAAE,CACpB,cAAc,EAAE,MAAM,KACnB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,GAAG,aAAa,CAAC,CAAC;IAChE,sBAAsB,EAAE,CACtB,cAAc,EAAE,MAAM,KACnB,IAAI,CAAC,0BAA0B,EAAE,UAAU,CAAC,CAAC;IAClD,SAAS,EAAE,0BAA0B,CAAC;IACtC,oBAAoB,EAAE,OAAO,CAAC;CAC/B,GAAG,aAAa,CAgGhB"}
@@ -1 +1 @@
1
- {"version":3,"file":"create-network-client.d.mts","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,0BAA0B,EAAE,oCAAoC;AA0B9E,OAAO,KAAK,EAAE,0BAA0B,EAAE,gCAA4B;AACtE,OAAO,KAAK,EAAE,iBAAiB,EAAE,sCAAkC;AAEnE,OAAO,KAAK,EACV,YAAY,EACZ,0BAA0B,EAC1B,QAAQ,EACT,oBAAgB;AAKjB;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,aAAa,EAAE,0BAA0B,CAAC;IAC1C,QAAQ,EAAE,QAAQ,CAAC;IACnB,YAAY,EAAE,YAAY,CAAC;IAC3B,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,GACrB,EAAE;IACD,aAAa,EAAE,0BAA0B,CAAC;IAC1C,oBAAoB,EAAE,CACpB,cAAc,EAAE,MAAM,KACnB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,GAAG,aAAa,CAAC,CAAC;IAChE,sBAAsB,EAAE,CACtB,cAAc,EAAE,MAAM,KACnB,IAAI,CAAC,0BAA0B,EAAE,UAAU,CAAC,CAAC;IAClD,SAAS,EAAE,0BAA0B,CAAC;IACtC,oBAAoB,EAAE,OAAO,CAAC;CAC/B,GAAG,aAAa,CAwFhB"}
1
+ {"version":3,"file":"create-network-client.d.mts","sourceRoot":"","sources":["../src/create-network-client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,0BAA0B,EAAE,oCAAoC;AA0B9E,OAAO,KAAK,EAAE,0BAA0B,EAAE,gCAA4B;AACtE,OAAO,KAAK,EAAE,iBAAiB,EAAE,sCAAkC;AAEnE,OAAO,KAAK,EACV,YAAY,EACZ,0BAA0B,EAC1B,QAAQ,EACT,oBAAgB;AAKjB;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,aAAa,EAAE,0BAA0B,CAAC;IAC1C,QAAQ,EAAE,QAAQ,CAAC;IACnB,YAAY,EAAE,YAAY,CAAC;IAC3B,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,GACrB,EAAE;IACD,aAAa,EAAE,0BAA0B,CAAC;IAC1C,oBAAoB,EAAE,CACpB,cAAc,EAAE,MAAM,KACnB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,GAAG,aAAa,CAAC,CAAC;IAChE,sBAAsB,EAAE,CACtB,cAAc,EAAE,MAAM,KACnB,IAAI,CAAC,0BAA0B,EAAE,UAAU,CAAC,CAAC;IAClD,SAAS,EAAE,0BAA0B,CAAC;IACtC,oBAAoB,EAAE,OAAO,CAAC;CAC/B,GAAG,aAAa,CAgGhB"}
@@ -50,10 +50,18 @@ export function createNetworkClient({ configuration, getRpcServiceOptions, getBl
50
50
  error,
51
51
  });
52
52
  });
53
- rpcServiceChain.onDegraded(({ endpointUrl }) => {
53
+ rpcServiceChain.onDegraded(({ endpointUrl, ...rest }) => {
54
+ let error;
55
+ if ('error' in rest) {
56
+ error = rest.error;
57
+ }
58
+ else if ('value' in rest) {
59
+ error = rest.value;
60
+ }
54
61
  messenger.publish('NetworkController:rpcEndpointDegraded', {
55
62
  chainId: configuration.chainId,
56
63
  endpointUrl,
64
+ error,
57
65
  });
58
66
  });
59
67
  rpcServiceChain.onRetry(({ endpointUrl, attempt }) => {
@@ -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;AAE3C,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACvB,wCAAwC;AACzC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,eAAe,EAChB,kCAAkC;AAMnC,OAAO,EAAE,eAAe,EAAE,4CAAwC;AAMlE,OAAO,EAAE,iBAAiB,EAAE,oBAAgB;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,GAWrB;IACC,MAAM,kBAAkB,GACtB,aAAa,CAAC,IAAI,KAAK,iBAAiB,CAAC,MAAM;QAC7C,CAAC,CAAC,WAAW,aAAa,CAAC,OAAO,iBAAiB,aAAa,CAAC,eAAe,EAAE;QAClF,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC;IAC3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C;IAChB,CAAC,CAAC;AACJ,CAAC,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS,6BAA6B,CAAC,EACrC,YAAY,EACZ,OAAO,EACP,gBAAgB,GAKjB;IACC,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO;QACzC,CAAC,CAAC,CAAC,oCAAoC,EAAE,CAAC;QAC1C,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO,eAAe,CAAC;QACrB,GAAG,eAAe;QAClB,uBAAuB,CAAC,OAAO,CAAC;QAChC,+BAA+B,CAAC,EAAE,YAAY,EAAE,CAAC;QACjD,0BAA0B,CAAC,EAAE,YAAY,EAAE,CAAC;QAC5C,6BAA6B,EAAE;QAC/B,qCAAqC,CAAC,EAAE,YAAY,EAAE,CAAC;QACvD,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,oCAAoC;IAC3C,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;QAClD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE;YACpC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;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 type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport {\n providerFromEngine,\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';\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 * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\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}): 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 })),\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 }) => {\n messenger.publish('NetworkController:rpcEndpointDegraded', {\n chainId: configuration.chainId,\n endpointUrl,\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 = providerFromEngine(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: SafeEventEmitterProvider;\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: SafeEventEmitterProvider;\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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;AAE3C,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACvB,wCAAwC;AACzC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,eAAe,EAChB,kCAAkC;AAMnC,OAAO,EAAE,eAAe,EAAE,4CAAwC;AAMlE,OAAO,EAAE,iBAAiB,EAAE,oBAAgB;AAE5C,MAAM,MAAM,GAAG,IAAI,CAAC;AAapB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,aAAa,EACb,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,oBAAoB,GAWrB;IACC,MAAM,kBAAkB,GACtB,aAAa,CAAC,IAAI,KAAK,iBAAiB,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,eAAe,IAAI,EAAE,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC;IACzB,MAAM,eAAe,GAAG,IAAI,eAAe,CACzC,qB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E,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC,CAAC;AAEF;;;;;;;;GAQG;AACH,SAAS,6BAA6B,CAAC,EACrC,YAAY,EACZ,OAAO,EACP,gBAAgB,GAKjB;IACC,MAAM,eAAe,GAAG,OAAO,CAAC,GAAG,CAAC,OAAO;QACzC,CAAC,CAAC,CAAC,oCAAoC,EAAE,CAAC;QAC1C,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO,eAAe,CAAC;QACrB,GAAG,eAAe;QAClB,uBAAuB,CAAC,OAAO,CAAC;QAChC,+BAA+B,CAAC,EAAE,YAAY,EAAE,CAAC;QACjD,0BAA0B,CAAC,EAAE,YAAY,EAAE,CAAC;QAC5C,6BAA6B,EAAE;QAC/B,qCAAqC,CAAC,EAAE,YAAY,EAAE,CAAC;QACvD,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,oCAAoC;IAC3C,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;QAClD,IAAI,GAAG,CAAC,MAAM,KAAK,iBAAiB,EAAE;YACpC,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;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 type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport {\n providerFromEngine,\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';\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 * @returns The network client.\n */\nexport function createNetworkClient({\n configuration,\n getRpcServiceOptions,\n getBlockTrackerOptions,\n messenger,\n isRpcFailoverEnabled,\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}): 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 })),\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 = providerFromEngine(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: SafeEventEmitterProvider;\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: SafeEventEmitterProvider;\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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-chain.cjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service-chain.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA,mDAA2C;AAK3C;;;;;GAKG;AACH,MAAa,eAAe;IAG1B;;;;;;OAMG;IACH,YACE,wBAAsE;;QAV/D,4CAAwB;QAY/B,uBAAA,IAAI,6BAAa,uBAAA,IAAI,yEAAsB,MAA1B,IAAI,EAAuB,wBAAwB,CAAC,MAAA,CAAC;IACxE,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,QAA8C;QACpD,MAAM,WAAW,GAAG,uBAAA,IAAI,iCAAU,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CACjD,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAC1B,CAAC;QAEF,OAAO;YACL,OAAO;gBACL,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAED;;;;;;OAMG;IACH,OAAO,CAAC,QAA8C;QACpD,MAAM,WAAW,GAAG,uBAAA,IAAI,iCAAU,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CACjD,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAC1B,CAAC;QAEF,OAAO;YACL,OAAO;gBACL,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,UAAU,CAAC,QAAiD;QAC1D,MAAM,WAAW,GAAG,uBAAA,IAAI,iCAAU,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CACjD,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAC7B,CAAC;QAEF,OAAO;YACL,OAAO;gBACL,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAgDD,KAAK,CAAC,OAAO,CACX,cAAsC,EACtC,eAA6B,EAAE;QAE/B,OAAO,uBAAA,IAAI,iCAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjE,CAAC;CA0BF;AApJD,0CAoJC;8KAbG,wBAAsE;IAEtE,OAAO,CAAC,GAAG,wBAAwB,CAAC;SACjC,OAAO,EAAE;SACT,MAAM,CAAC,CAAC,eAA6B,EAAE,oBAAoB,EAAE,KAAK,EAAE,EAAE;QACrE,MAAM,eAAe,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACnE,MAAM,OAAO,GAAG,IAAI,wBAAU,CAAC;YAC7B,GAAG,oBAAoB;YACvB,eAAe;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,CAAC;IACvC,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport { RpcService } from './rpc-service';\nimport type { RpcServiceOptions } from './rpc-service';\nimport type { RpcServiceRequestable } from './rpc-service-requestable';\nimport type { FetchOptions } from './shared';\n\n/**\n * This class constructs a chain of RpcService objects which represent a\n * particular network. The first object in the chain is intended to be the\n * primary way of reaching the network and the remaining objects are used as\n * failovers.\n */\nexport class RpcServiceChain implements RpcServiceRequestable {\n readonly #services: RpcService[];\n\n /**\n * Constructs a new RpcServiceChain object.\n *\n * @param rpcServiceConfigurations - The options for the RPC services\n * that you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n */\n constructor(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ) {\n this.#services = this.#buildRpcServiceChain(rpcServiceConfigurations);\n }\n\n /**\n * Listens for when any of the RPC services retry a request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onRetry(listener: Parameters<RpcService['onRetry']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onRetry(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services retry the request too many times\n * in a row.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onBreak} returns.\n */\n onBreak(listener: Parameters<RpcService['onBreak']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onBreak(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services send a slow request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onDegraded(listener: Parameters<RpcService['onDegraded']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onDegraded(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is specifically designed for `eth_getBlockByNumber`, which\n * can return a `result` of `null` despite an expected `Result` being\n * provided.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params> & { method: 'eth_getBlockByNumber' },\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>>;\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is designed for all RPC methods except for\n * `eth_getBlockByNumber`, which are expected to return a `result` of the\n * expected `Result`.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result>>;\n\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions: FetchOptions = {},\n ): Promise<JsonRpcResponse<Result | null>> {\n return this.#services[0].request(jsonRpcRequest, fetchOptions);\n }\n\n /**\n * Constructs the chain of RPC services. The second RPC service is\n * configured as the failover for the first, the third service is\n * configured as the failover for the second, etc.\n *\n * @param rpcServiceConfigurations - The options for the RPC services that\n * you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n * @returns The constructed chain of RPC services.\n */\n #buildRpcServiceChain(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ): RpcService[] {\n return [...rpcServiceConfigurations]\n .reverse()\n .reduce((workingServices: RpcService[], serviceConfiguration, index) => {\n const failoverService = index > 0 ? workingServices[0] : undefined;\n const service = new RpcService({\n ...serviceConfiguration,\n failoverService,\n });\n return [service, ...workingServices];\n }, []);\n }\n}\n"]}
1
+ {"version":3,"file":"rpc-service-chain.cjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service-chain.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA,mDAA2C;AAK3C;;;;;GAKG;AACH,MAAa,eAAe;IAG1B;;;;;;OAMG;IACH,YACE,wBAAsE;;QAV/D,4CAAwB;QAY/B,uBAAA,IAAI,6BAAa,uBAAA,IAAI,yEAAsB,MAA1B,IAAI,EAAuB,wBAAwB,CAAC,MAAA,CAAC;IACxE,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,QAA8C;QACpD,MAAM,WAAW,GAAG,uBAAA,IAAI,iCAAU,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CACjD,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAC1B,CAAC;QAEF,OAAO;YACL,OAAO;gBACL,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAED;;;;;;OAMG;IACH,OAAO,CAAC,QAA8C;QACpD,MAAM,WAAW,GAAG,uBAAA,IAAI,iCAAU,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CACjD,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAC1B,CAAC;QAEF,OAAO;YACL,OAAO;gBACL,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,UAAU,CAAC,QAAiD;QAC1D,MAAM,WAAW,GAAG,uBAAA,IAAI,iCAAU,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CACjD,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAC7B,CAAC;QAEF,OAAO;YACL,OAAO;gBACL,WAAW,CAAC,OAAO,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAgDD,KAAK,CAAC,OAAO,CACX,cAAsC,EACtC,eAA6B,EAAE;QAE/B,OAAO,uBAAA,IAAI,iCAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjE,CAAC;CA0BF;AApJD,0CAoJC;8KAbG,wBAAsE;IAEtE,OAAO,CAAC,GAAG,wBAAwB,CAAC;SACjC,OAAO,EAAE;SACT,MAAM,CAAC,CAAC,eAA6B,EAAE,oBAAoB,EAAE,KAAK,EAAE,EAAE;QACrE,MAAM,eAAe,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACnE,MAAM,OAAO,GAAG,IAAI,wBAAU,CAAC;YAC7B,GAAG,oBAAoB;YACvB,eAAe;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,CAAC;IACvC,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport { RpcService } from './rpc-service';\nimport type { RpcServiceOptions } from './rpc-service';\nimport type { RpcServiceRequestable } from './rpc-service-requestable';\nimport type { FetchOptions } from './shared';\n\n/**\n * This class constructs a chain of RpcService objects which represent a\n * particular network. The first object in the chain is intended to be the\n * primary way of reaching the network and the remaining objects are used as\n * failovers.\n */\nexport class RpcServiceChain implements RpcServiceRequestable {\n readonly #services: RpcService[];\n\n /**\n * Constructs a new RpcServiceChain object.\n *\n * @param rpcServiceConfigurations - The options for the RPC services\n * that you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n */\n constructor(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ) {\n this.#services = this.#buildRpcServiceChain(rpcServiceConfigurations);\n }\n\n /**\n * Listens for when any of the RPC services retry a request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onRetry(listener: Parameters<RpcService['onRetry']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onRetry(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services retry the request too many times\n * in a row.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onBreak} returns.\n */\n onBreak(listener: Parameters<RpcService['onBreak']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onBreak(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services send a slow request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onDegraded(listener: Parameters<RpcService['onDegraded']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onDegraded(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is specifically designed for `eth_getBlockByNumber`, which\n * can return a `result` of `null` despite an expected `Result` being\n * provided.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A 401 error if the response status is 401.\n * @throws A \"rate limiting\" error if the response HTTP status is 429.\n * @throws A \"resource unavailable\" error if the response status is 402, 404, or any 5xx.\n * @throws A generic HTTP client error (-32100) for any other 4xx status codes.\n * @throws A \"parse\" error 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 first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is designed for all RPC methods except for\n * `eth_getBlockByNumber`, which are expected to return a `result` of the\n * expected `Result`.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A 401 error if the response status is 401.\n * @throws A \"rate limiting\" error if the response HTTP status is 429.\n * @throws A \"resource unavailable\" error if the response status is 402, 404, or any 5xx.\n * @throws A generic HTTP client error (-32100) for any other 4xx status codes.\n * @throws A \"parse\" error 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 return this.#services[0].request(jsonRpcRequest, fetchOptions);\n }\n\n /**\n * Constructs the chain of RPC services. The second RPC service is\n * configured as the failover for the first, the third service is\n * configured as the failover for the second, etc.\n *\n * @param rpcServiceConfigurations - The options for the RPC services that\n * you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n * @returns The constructed chain of RPC services.\n */\n #buildRpcServiceChain(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ): RpcService[] {\n return [...rpcServiceConfigurations]\n .reverse()\n .reduce((workingServices: RpcService[], serviceConfiguration, index) => {\n const failoverService = index > 0 ? workingServices[0] : undefined;\n const service = new RpcService({\n ...serviceConfiguration,\n failoverService,\n });\n return [service, ...workingServices];\n }, []);\n }\n}\n"]}
@@ -59,11 +59,11 @@ export declare class RpcServiceChain implements RpcServiceRequestable {
59
59
  * @param fetchOptions - An options bag for {@link fetch} which further
60
60
  * specifies the request.
61
61
  * @returns The decoded JSON-RPC response from the endpoint.
62
- * @throws A "method not found" error if the response status is 405.
63
- * @throws A rate limiting error if the response HTTP status is 429.
64
- * @throws A timeout error if the response HTTP status is 503 or 504.
65
- * @throws A generic error if the response HTTP status is not 2xx but also not
66
- * 405, 429, 503, or 504.
62
+ * @throws A 401 error if the response status is 401.
63
+ * @throws A "rate limiting" error if the response HTTP status is 429.
64
+ * @throws A "resource unavailable" error if the response status is 402, 404, or any 5xx.
65
+ * @throws A generic HTTP client error (-32100) for any other 4xx status codes.
66
+ * @throws A "parse" error if the response is not valid JSON.
67
67
  */
68
68
  request<Params extends JsonRpcParams, Result extends Json>(jsonRpcRequest: JsonRpcRequest<Params> & {
69
69
  method: 'eth_getBlockByNumber';
@@ -80,11 +80,11 @@ export declare class RpcServiceChain implements RpcServiceRequestable {
80
80
  * @param fetchOptions - An options bag for {@link fetch} which further
81
81
  * specifies the request.
82
82
  * @returns The decoded JSON-RPC response from the endpoint.
83
- * @throws A "method not found" error if the response status is 405.
84
- * @throws A rate limiting error if the response HTTP status is 429.
85
- * @throws A timeout error if the response HTTP status is 503 or 504.
86
- * @throws A generic error if the response HTTP status is not 2xx but also not
87
- * 405, 429, 503, or 504.
83
+ * @throws A 401 error if the response status is 401.
84
+ * @throws A "rate limiting" error if the response HTTP status is 429.
85
+ * @throws A "resource unavailable" error if the response status is 402, 404, or any 5xx.
86
+ * @throws A generic HTTP client error (-32100) for any other 4xx status codes.
87
+ * @throws A "parse" error if the response is not valid JSON.
88
88
  */
89
89
  request<Params extends JsonRpcParams, Result extends Json>(jsonRpcRequest: JsonRpcRequest<Params>, fetchOptions?: FetchOptions): Promise<JsonRpcResponse<Result>>;
90
90
  }
@@ -59,11 +59,11 @@ export declare class RpcServiceChain implements RpcServiceRequestable {
59
59
  * @param fetchOptions - An options bag for {@link fetch} which further
60
60
  * specifies the request.
61
61
  * @returns The decoded JSON-RPC response from the endpoint.
62
- * @throws A "method not found" error if the response status is 405.
63
- * @throws A rate limiting error if the response HTTP status is 429.
64
- * @throws A timeout error if the response HTTP status is 503 or 504.
65
- * @throws A generic error if the response HTTP status is not 2xx but also not
66
- * 405, 429, 503, or 504.
62
+ * @throws A 401 error if the response status is 401.
63
+ * @throws A "rate limiting" error if the response HTTP status is 429.
64
+ * @throws A "resource unavailable" error if the response status is 402, 404, or any 5xx.
65
+ * @throws A generic HTTP client error (-32100) for any other 4xx status codes.
66
+ * @throws A "parse" error if the response is not valid JSON.
67
67
  */
68
68
  request<Params extends JsonRpcParams, Result extends Json>(jsonRpcRequest: JsonRpcRequest<Params> & {
69
69
  method: 'eth_getBlockByNumber';
@@ -80,11 +80,11 @@ export declare class RpcServiceChain implements RpcServiceRequestable {
80
80
  * @param fetchOptions - An options bag for {@link fetch} which further
81
81
  * specifies the request.
82
82
  * @returns The decoded JSON-RPC response from the endpoint.
83
- * @throws A "method not found" error if the response status is 405.
84
- * @throws A rate limiting error if the response HTTP status is 429.
85
- * @throws A timeout error if the response HTTP status is 503 or 504.
86
- * @throws A generic error if the response HTTP status is not 2xx but also not
87
- * 405, 429, 503, or 504.
83
+ * @throws A 401 error if the response status is 401.
84
+ * @throws A "rate limiting" error if the response HTTP status is 429.
85
+ * @throws A "resource unavailable" error if the response status is 402, 404, or any 5xx.
86
+ * @throws A generic HTTP client error (-32100) for any other 4xx status codes.
87
+ * @throws A "parse" error if the response is not valid JSON.
88
88
  */
89
89
  request<Params extends JsonRpcParams, Result extends Json>(jsonRpcRequest: JsonRpcRequest<Params>, fetchOptions?: FetchOptions): Promise<JsonRpcResponse<Result>>;
90
90
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rpc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CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAgDD,KAAK,CAAC,OAAO,CACX,cAAsC,EACtC,eAA6B,EAAE;QAE/B,OAAO,uBAAA,IAAI,iCAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjE,CAAC;CA0BF;8KAbG,wBAAsE;IAEtE,OAAO,CAAC,GAAG,wBAAwB,CAAC;SACjC,OAAO,EAAE;SACT,MAAM,CAAC,CAAC,eAA6B,EAAE,oBAAoB,EAAE,KAAK,EAAE,EAAE;QACrE,MAAM,eAAe,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACnE,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC;YAC7B,GAAG,oBAAoB;YACvB,eAAe;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,CAAC;IACvC,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport { RpcService } from './rpc-service';\nimport type { RpcServiceOptions } from './rpc-service';\nimport type { RpcServiceRequestable } from './rpc-service-requestable';\nimport type { FetchOptions } from './shared';\n\n/**\n * This class constructs a chain of RpcService objects which represent a\n * particular network. The first object in the chain is intended to be the\n * primary way of reaching the network and the remaining objects are used as\n * failovers.\n */\nexport class RpcServiceChain implements RpcServiceRequestable {\n readonly #services: RpcService[];\n\n /**\n * Constructs a new RpcServiceChain object.\n *\n * @param rpcServiceConfigurations - The options for the RPC services\n * that you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n */\n constructor(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ) {\n this.#services = this.#buildRpcServiceChain(rpcServiceConfigurations);\n }\n\n /**\n * Listens for when any of the RPC services retry a request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onRetry(listener: Parameters<RpcService['onRetry']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onRetry(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services retry the request too many times\n * in a row.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onBreak} returns.\n */\n onBreak(listener: Parameters<RpcService['onBreak']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onBreak(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services send a slow request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onDegraded(listener: Parameters<RpcService['onDegraded']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onDegraded(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is specifically designed for `eth_getBlockByNumber`, which\n * can return a `result` of `null` despite an expected `Result` being\n * provided.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params> & { method: 'eth_getBlockByNumber' },\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result> | JsonRpcResponse<null>>;\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is designed for all RPC methods except for\n * `eth_getBlockByNumber`, which are expected to return a `result` of the\n * expected `Result`.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A \"method not found\" error if the response status is 405.\n * @throws A rate limiting error if the response HTTP status is 429.\n * @throws A timeout error if the response HTTP status is 503 or 504.\n * @throws A generic error if the response HTTP status is not 2xx but also not\n * 405, 429, 503, or 504.\n */\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions?: FetchOptions,\n ): Promise<JsonRpcResponse<Result>>;\n\n async request<Params extends JsonRpcParams, Result extends Json>(\n jsonRpcRequest: JsonRpcRequest<Params>,\n fetchOptions: FetchOptions = {},\n ): Promise<JsonRpcResponse<Result | null>> {\n return this.#services[0].request(jsonRpcRequest, fetchOptions);\n }\n\n /**\n * Constructs the chain of RPC services. The second RPC service is\n * configured as the failover for the first, the third service is\n * configured as the failover for the second, etc.\n *\n * @param rpcServiceConfigurations - The options for the RPC services that\n * you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n * @returns The constructed chain of RPC services.\n */\n #buildRpcServiceChain(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ): RpcService[] {\n return [...rpcServiceConfigurations]\n .reverse()\n .reduce((workingServices: RpcService[], serviceConfiguration, index) => {\n const failoverService = index > 0 ? workingServices[0] : undefined;\n const service = new RpcService({\n ...serviceConfiguration,\n failoverService,\n });\n return [service, ...workingServices];\n }, []);\n }\n}\n"]}
1
+ {"version":3,"file":"rpc-service-chain.mjs","sourceRoot":"","sources":["../../src/rpc-service/rpc-service-chain.ts"],"names":[],"mappings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CAAC;YAC5D,CAAC;SACF,CAAC;IACJ,CAAC;IAgDD,KAAK,CAAC,OAAO,CACX,cAAsC,EACtC,eAA6B,EAAE;QAE/B,OAAO,uBAAA,IAAI,iCAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjE,CAAC;CA0BF;8KAbG,wBAAsE;IAEtE,OAAO,CAAC,GAAG,wBAAwB,CAAC;SACjC,OAAO,EAAE;SACT,MAAM,CAAC,CAAC,eAA6B,EAAE,oBAAoB,EAAE,KAAK,EAAE,EAAE;QACrE,MAAM,eAAe,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACnE,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC;YAC7B,GAAG,oBAAoB;YACvB,eAAe;SAChB,CAAC,CAAC;QACH,OAAO,CAAC,OAAO,EAAE,GAAG,eAAe,CAAC,CAAC;IACvC,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC","sourcesContent":["import type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n JsonRpcResponse,\n} from '@metamask/utils';\n\nimport { RpcService } from './rpc-service';\nimport type { RpcServiceOptions } from './rpc-service';\nimport type { RpcServiceRequestable } from './rpc-service-requestable';\nimport type { FetchOptions } from './shared';\n\n/**\n * This class constructs a chain of RpcService objects which represent a\n * particular network. The first object in the chain is intended to be the\n * primary way of reaching the network and the remaining objects are used as\n * failovers.\n */\nexport class RpcServiceChain implements RpcServiceRequestable {\n readonly #services: RpcService[];\n\n /**\n * Constructs a new RpcServiceChain object.\n *\n * @param rpcServiceConfigurations - The options for the RPC services\n * that you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n */\n constructor(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ) {\n this.#services = this.#buildRpcServiceChain(rpcServiceConfigurations);\n }\n\n /**\n * Listens for when any of the RPC services retry a request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onRetry(listener: Parameters<RpcService['onRetry']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onRetry(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services retry the request too many times\n * in a row.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onBreak} returns.\n */\n onBreak(listener: Parameters<RpcService['onBreak']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onBreak(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Listens for when any of the RPC services send a slow request.\n *\n * @param listener - The callback to be called when the retry occurs.\n * @returns What {@link RpcService.onRetry} returns.\n */\n onDegraded(listener: Parameters<RpcService['onDegraded']>[0]) {\n const disposables = this.#services.map((service) =>\n service.onDegraded(listener),\n );\n\n return {\n dispose() {\n disposables.forEach((disposable) => disposable.dispose());\n },\n };\n }\n\n /**\n * Makes a request to the first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is specifically designed for `eth_getBlockByNumber`, which\n * can return a `result` of `null` despite an expected `Result` being\n * provided.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A 401 error if the response status is 401.\n * @throws A \"rate limiting\" error if the response HTTP status is 429.\n * @throws A \"resource unavailable\" error if the response status is 402, 404, or any 5xx.\n * @throws A generic HTTP client error (-32100) for any other 4xx status codes.\n * @throws A \"parse\" error 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 first RPC service in the chain. If this service is\n * down, then the request is forwarded to the next service in the chain, etc.\n *\n * This overload is designed for all RPC methods except for\n * `eth_getBlockByNumber`, which are expected to return a `result` of the\n * expected `Result`.\n *\n * @param jsonRpcRequest - The JSON-RPC request to send to the endpoint.\n * @param fetchOptions - An options bag for {@link fetch} which further\n * specifies the request.\n * @returns The decoded JSON-RPC response from the endpoint.\n * @throws A 401 error if the response status is 401.\n * @throws A \"rate limiting\" error if the response HTTP status is 429.\n * @throws A \"resource unavailable\" error if the response status is 402, 404, or any 5xx.\n * @throws A generic HTTP client error (-32100) for any other 4xx status codes.\n * @throws A \"parse\" error 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 return this.#services[0].request(jsonRpcRequest, fetchOptions);\n }\n\n /**\n * Constructs the chain of RPC services. The second RPC service is\n * configured as the failover for the first, the third service is\n * configured as the failover for the second, etc.\n *\n * @param rpcServiceConfigurations - The options for the RPC services that\n * you want to construct. Each object in this array is the same as\n * {@link RpcServiceOptions}.\n * @returns The constructed chain of RPC services.\n */\n #buildRpcServiceChain(\n rpcServiceConfigurations: Omit<RpcServiceOptions, 'failoverService'>[],\n ): RpcService[] {\n return [...rpcServiceConfigurations]\n .reverse()\n .reduce((workingServices: RpcService[], serviceConfiguration, index) => {\n const failoverService = index > 0 ? workingServices[0] : undefined;\n const service = new RpcService({\n ...serviceConfiguration,\n failoverService,\n });\n return [service, ...workingServices];\n }, []);\n }\n}\n"]}
@@ -15,7 +15,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
15
15
  };
16
16
  var _RpcService_instances, _RpcService_fetch, _RpcService_fetchOptions, _RpcService_failoverService, _RpcService_policy, _RpcService_getDefaultFetchOptions, _RpcService_getCompleteFetchOptions, _RpcService_processRequest;
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.RpcService = exports.isConnectionError = exports.CONNECTION_ERRORS = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_MAX_RETRIES = void 0;
18
+ exports.RpcService = exports.isConnectionError = exports.CUSTOM_RPC_ERRORS = exports.CONNECTION_ERRORS = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_MAX_RETRIES = void 0;
19
19
  const controller_utils_1 = require("@metamask/controller-utils");
20
20
  const rpc_errors_1 = require("@metamask/rpc-errors");
21
21
  const utils_1 = require("@metamask/utils");
@@ -85,6 +85,15 @@ exports.CONNECTION_ERRORS = [
85
85
  pattern: /terminated/u,
86
86
  },
87
87
  ];
88
+ /**
89
+ * Custom JSON-RPC error codes for specific cases.
90
+ *
91
+ * These should be moved to `@metamask/rpc-errors` eventually.
92
+ */
93
+ exports.CUSTOM_RPC_ERRORS = {
94
+ unauthorized: -32006,
95
+ httpClientError: -32080,
96
+ };
88
97
  /**
89
98
  * Determines whether the given error represents a failure to reach the network
90
99
  * after request parameters have been validated.
@@ -122,6 +131,19 @@ exports.isConnectionError = isConnectionError;
122
131
  function isNockError(message) {
123
132
  return message.includes('Nock:');
124
133
  }
134
+ /**
135
+ * Determine whether the given error message indicates a failure to parse JSON.
136
+ *
137
+ * This is different in tests vs. implementation code because it may manifest as
138
+ * a FetchError or a SyntaxError.
139
+ *
140
+ * @param error - The error object to test.
141
+ * @returns True if the error indicates a JSON parse error, false otherwise.
142
+ */
143
+ function isJsonParseError(error) {
144
+ return (error instanceof SyntaxError ||
145
+ /invalid json/iu.test((0, utils_1.getErrorMessage)(error)));
146
+ }
125
147
  /**
126
148
  * Guarantees a URL, even given a string. This is useful for checking components
127
149
  * of that URL.
@@ -135,6 +157,18 @@ function getNormalizedEndpointUrl(endpointUrlOrUrlString) {
135
157
  ? endpointUrlOrUrlString
136
158
  : new URL(endpointUrlOrUrlString);
137
159
  }
160
+ /**
161
+ * Strips username and password from a URL.
162
+ *
163
+ * @param url - The URL to strip credentials from.
164
+ * @returns A new URL object with credentials removed.
165
+ */
166
+ function stripCredentialsFromUrl(url) {
167
+ const strippedUrl = new URL(url.toString());
168
+ strippedUrl.username = '';
169
+ strippedUrl.password = '';
170
+ return strippedUrl;
171
+ }
138
172
  /**
139
173
  * This class is responsible for making a request to an endpoint that implements
140
174
  * the JSON-RPC protocol. It is designed to gracefully handle network and server
@@ -168,8 +202,9 @@ class RpcService {
168
202
  _RpcService_policy.set(this, void 0);
169
203
  const { btoa: givenBtoa, endpointUrl, failoverService, fetch: givenFetch, fetchOptions = {}, policyOptions = {}, } = options;
170
204
  __classPrivateFieldSet(this, _RpcService_fetch, givenFetch, "f");
171
- this.endpointUrl = getNormalizedEndpointUrl(endpointUrl);
172
- __classPrivateFieldSet(this, _RpcService_fetchOptions, __classPrivateFieldGet(this, _RpcService_instances, "m", _RpcService_getDefaultFetchOptions).call(this, this.endpointUrl, fetchOptions, givenBtoa), "f");
205
+ const normalizedUrl = getNormalizedEndpointUrl(endpointUrl);
206
+ __classPrivateFieldSet(this, _RpcService_fetchOptions, __classPrivateFieldGet(this, _RpcService_instances, "m", _RpcService_getDefaultFetchOptions).call(this, normalizedUrl, fetchOptions, givenBtoa), "f");
207
+ this.endpointUrl = stripCredentialsFromUrl(normalizedUrl);
173
208
  __classPrivateFieldSet(this, _RpcService_failoverService, failoverService, "f");
174
209
  const policy = (0, controller_utils_1.createServicePolicy)({
175
210
  maxRetries: exports.DEFAULT_MAX_RETRIES,
@@ -180,10 +215,12 @@ class RpcService {
180
215
  // Ignore errors where the request failed to establish
181
216
  isConnectionError(error) ||
182
217
  // Ignore server sent HTML error pages or truncated JSON responses
183
- error.message.includes('not valid JSON') ||
218
+ isJsonParseError(error) ||
184
219
  // Ignore server overload errors
185
220
  ('httpStatus' in error &&
186
- (error.httpStatus === 503 || error.httpStatus === 504)) ||
221
+ (error.httpStatus === 502 ||
222
+ error.httpStatus === 503 ||
223
+ error.httpStatus === 504)) ||
187
224
  ((0, utils_1.hasProperty)(error, 'code') &&
188
225
  (error.code === 'ETIMEDOUT' || error.code === 'ECONNRESET')));
189
226
  }),
@@ -230,8 +267,8 @@ class RpcService {
230
267
  * @see {@link createServicePolicy}
231
268
  */
232
269
  onDegraded(listener) {
233
- return __classPrivateFieldGet(this, _RpcService_policy, "f").onDegraded(() => {
234
- listener({ endpointUrl: this.endpointUrl.toString() });
270
+ return __classPrivateFieldGet(this, _RpcService_policy, "f").onDegraded((data) => {
271
+ listener({ ...(data ?? {}), endpointUrl: this.endpointUrl.toString() });
235
272
  });
236
273
  }
237
274
  async request(jsonRpcRequest, fetchOptions = {}) {
@@ -282,11 +319,11 @@ _RpcService_fetch = new WeakMap(), _RpcService_fetchOptions = new WeakMap(), _Rp
282
319
  * @param fetchOptions - The options for `fetch`; will be combined with the
283
320
  * fetch options passed to the constructor
284
321
  * @returns The decoded JSON-RPC response from the endpoint.
285
- * @throws A "method not found" error if the response status is 405.
286
- * @throws A rate limiting error if the response HTTP status is 429.
287
- * @throws A timeout error if the response HTTP status is 503 or 504.
288
- * @throws A generic error if the response HTTP status is not 2xx but also not
289
- * 405, 429, 503, or 504.
322
+ * @throws An "authorized" JSON-RPC error (code -32006) if the response HTTP status is 401.
323
+ * @throws A "rate limiting" JSON-RPC error (code -32005) if the response HTTP status is 429.
324
+ * @throws A "resource unavailable" JSON-RPC error (code -32002) if the response HTTP status is 402, 404, or any 5xx.
325
+ * @throws A generic HTTP client JSON-RPC error (code -32050) for any other 4xx HTTP status codes.
326
+ * @throws A "parse" JSON-RPC error (code -32700) if the response is not valid JSON.
290
327
  */
291
328
  async function _RpcService_processRequest(fetchOptions) {
292
329
  let response;
@@ -302,26 +339,35 @@ async function _RpcService_processRequest(fetchOptions) {
302
339
  catch (error) {
303
340
  if (error instanceof controller_utils_1.HttpError) {
304
341
  const status = error.httpStatus;
305
- if (status === 405) {
306
- throw rpc_errors_1.rpcErrors.methodNotFound();
342
+ if (status === 401) {
343
+ throw new rpc_errors_1.JsonRpcError(exports.CUSTOM_RPC_ERRORS.unauthorized, 'Unauthorized.', {
344
+ httpStatus: status,
345
+ });
307
346
  }
308
347
  if (status === 429) {
309
348
  throw rpc_errors_1.rpcErrors.limitExceeded({
310
349
  message: 'Request is being rate limited.',
350
+ data: {
351
+ httpStatus: status,
352
+ },
311
353
  });
312
354
  }
313
- if (status === 503 || status === 504) {
314
- throw rpc_errors_1.rpcErrors.internal({
315
- message: 'Gateway timeout. The request took too long to process. This can happen when querying logs over too wide a block range.',
355
+ if (status >= 500 || status === 402 || status === 404) {
356
+ throw rpc_errors_1.rpcErrors.resourceUnavailable({
357
+ message: 'RPC endpoint not found or unavailable.',
358
+ data: {
359
+ httpStatus: status,
360
+ },
316
361
  });
317
362
  }
318
- throw rpc_errors_1.rpcErrors.internal({
319
- message: `Non-200 status code: '${status}'`,
363
+ // Handle all other 4xx errors as generic HTTP client errors
364
+ throw new rpc_errors_1.JsonRpcError(exports.CUSTOM_RPC_ERRORS.httpClientError, 'RPC endpoint returned HTTP client error.', {
365
+ httpStatus: status,
320
366
  });
321
367
  }
322
- else if (error instanceof SyntaxError) {
323
- throw rpc_errors_1.rpcErrors.internal({
324
- message: 'Could not parse response as it is not valid JSON',
368
+ else if (isJsonParseError(error)) {
369
+ throw rpc_errors_1.rpcErrors.parse({
370
+ message: 'RPC endpoint did not return JSON.',
325
371
  });
326
372
  }
327
373
  throw error;