@metamask/assets-controllers 72.0.0 → 73.0.1

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 (66) hide show
  1. package/CHANGELOG.md +41 -1
  2. package/dist/AccountTrackerController.cjs +50 -34
  3. package/dist/AccountTrackerController.cjs.map +1 -1
  4. package/dist/AccountTrackerController.d.cts +9 -6
  5. package/dist/AccountTrackerController.d.cts.map +1 -1
  6. package/dist/AccountTrackerController.d.mts +9 -6
  7. package/dist/AccountTrackerController.d.mts.map +1 -1
  8. package/dist/AccountTrackerController.mjs +52 -35
  9. package/dist/AccountTrackerController.mjs.map +1 -1
  10. package/dist/AssetsContractController.cjs +39 -16
  11. package/dist/AssetsContractController.cjs.map +1 -1
  12. package/dist/AssetsContractController.d.cts +7 -5
  13. package/dist/AssetsContractController.d.cts.map +1 -1
  14. package/dist/AssetsContractController.d.mts +7 -5
  15. package/dist/AssetsContractController.d.mts.map +1 -1
  16. package/dist/AssetsContractController.mjs +39 -16
  17. package/dist/AssetsContractController.mjs.map +1 -1
  18. package/dist/CurrencyRateController.cjs +6 -1
  19. package/dist/CurrencyRateController.cjs.map +1 -1
  20. package/dist/CurrencyRateController.d.cts +4 -1
  21. package/dist/CurrencyRateController.d.cts.map +1 -1
  22. package/dist/CurrencyRateController.d.mts +4 -1
  23. package/dist/CurrencyRateController.d.mts.map +1 -1
  24. package/dist/CurrencyRateController.mjs +6 -1
  25. package/dist/CurrencyRateController.mjs.map +1 -1
  26. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs +37 -13
  27. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
  28. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts.map +1 -1
  29. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts.map +1 -1
  30. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs +37 -13
  31. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
  32. package/dist/TokenBalancesController.cjs +15 -1
  33. package/dist/TokenBalancesController.cjs.map +1 -1
  34. package/dist/TokenBalancesController.d.cts.map +1 -1
  35. package/dist/TokenBalancesController.d.mts.map +1 -1
  36. package/dist/TokenBalancesController.mjs +15 -1
  37. package/dist/TokenBalancesController.mjs.map +1 -1
  38. package/dist/TokenDetectionController.cjs +16 -12
  39. package/dist/TokenDetectionController.cjs.map +1 -1
  40. package/dist/TokenDetectionController.d.cts +8 -4
  41. package/dist/TokenDetectionController.d.cts.map +1 -1
  42. package/dist/TokenDetectionController.d.mts +8 -4
  43. package/dist/TokenDetectionController.d.mts.map +1 -1
  44. package/dist/TokenDetectionController.mjs +16 -12
  45. package/dist/TokenDetectionController.mjs.map +1 -1
  46. package/dist/TokensController.cjs +1 -0
  47. package/dist/TokensController.cjs.map +1 -1
  48. package/dist/TokensController.d.cts +5 -1
  49. package/dist/TokensController.d.cts.map +1 -1
  50. package/dist/TokensController.d.mts +5 -1
  51. package/dist/TokensController.d.mts.map +1 -1
  52. package/dist/TokensController.mjs +1 -0
  53. package/dist/TokensController.mjs.map +1 -1
  54. package/dist/index.cjs.map +1 -1
  55. package/dist/index.d.cts +1 -1
  56. package/dist/index.d.cts.map +1 -1
  57. package/dist/index.d.mts +1 -1
  58. package/dist/index.d.mts.map +1 -1
  59. package/dist/index.mjs.map +1 -1
  60. package/dist/multicall.cjs.map +1 -1
  61. package/dist/multicall.d.cts +1 -2
  62. package/dist/multicall.d.cts.map +1 -1
  63. package/dist/multicall.d.mts +1 -2
  64. package/dist/multicall.d.mts.map +1 -1
  65. package/dist/multicall.mjs.map +1 -1
  66. package/package.json +9 -9
@@ -16,8 +16,6 @@ function $importDefault(module) {
16
16
  }
17
17
  return module;
18
18
  }
19
- // import { BigNumber } from '@ethersproject/bignumber';
20
- import { BigNumber } from "@ethersproject/bignumber";
21
19
  import { Contract } from "@ethersproject/contracts";
22
20
  import { Web3Provider } from "@ethersproject/providers";
23
21
  import { IPFS_DEFAULT_GATEWAY_URL } from "@metamask/controller-utils";
@@ -25,6 +23,7 @@ import { getKnownPropertyNames } from "@metamask/utils";
25
23
  import $abiSingleCallBalancesContract from "single-call-balance-checker-abi";
26
24
  const abiSingleCallBalancesContract = $importDefault($abiSingleCallBalancesContract);
27
25
  import { SupportedStakedBalanceNetworks, SupportedTokenDetectionNetworks } from "./assetsUtil.mjs";
26
+ import { multicallOrFallback } from "./multicall.mjs";
28
27
  import { ERC20Standard } from "./Standards/ERC20Standard.mjs";
29
28
  import { ERC1155Standard } from "./Standards/NftStandards/ERC1155/ERC1155Standard.mjs";
30
29
  import { ERC721Standard } from "./Standards/NftStandards/ERC721/ERC721Standard.mjs";
@@ -341,27 +340,29 @@ export class AssetsContractController {
341
340
  return nonZeroBalances;
342
341
  }
343
342
  /**
344
- * Get the staked ethereum balance for an address in a single call.
343
+ * Get the staked ethereum balance for multiple addresses in a single call.
345
344
  *
346
- * @param address - The address to check staked ethereum balance for.
345
+ * @param addresses - The addresses to check staked ethereum balance for.
347
346
  * @param networkClientId - Network Client ID to fetch the provider with.
348
347
  * @returns The hex staked ethereum balance for address.
349
348
  */
350
- async getStakedBalanceForChain(address, networkClientId) {
349
+ async getStakedBalanceForChain(addresses, networkClientId) {
351
350
  const chainId = __classPrivateFieldGet(this, _AssetsContractController_instances, "m", _AssetsContractController_getCorrectChainId).call(this, networkClientId);
352
351
  const provider = __classPrivateFieldGet(this, _AssetsContractController_instances, "m", _AssetsContractController_getCorrectProvider).call(this, networkClientId);
353
- // balance defaults to zero
354
- let balance = BigNumber.from(0);
352
+ const balances = addresses.reduce((accumulator, address) => {
353
+ accumulator[address] = '0x00';
354
+ return accumulator;
355
+ }, {});
355
356
  // Only fetch staked balance on supported networks
356
357
  if (![
357
358
  SupportedStakedBalanceNetworks.mainnet,
358
359
  SupportedStakedBalanceNetworks.hoodi,
359
360
  ].includes(chainId)) {
360
- return undefined;
361
+ return {};
361
362
  }
362
363
  // Only fetch staked balance if contract address exists
363
364
  if (!((id) => id in STAKING_CONTRACT_ADDRESS_BY_CHAINID)(chainId)) {
364
- return undefined;
365
+ return {};
365
366
  }
366
367
  const contractAddress = STAKING_CONTRACT_ADDRESS_BY_CHAINID[chainId];
367
368
  const abi = [
@@ -381,18 +382,40 @@ export class AssetsContractController {
381
382
  },
382
383
  ];
383
384
  try {
384
- const contract = new Contract(contractAddress, abi, provider);
385
- const userShares = await contract.getShares(address);
386
- // convert shares to assets only if address shares > 0 else return default balance
387
- if (!userShares.lte(0)) {
388
- balance = await contract.convertToAssets(userShares.toString());
389
- }
385
+ const calls = addresses.map((address) => ({
386
+ contract: new Contract(contractAddress, abi, provider),
387
+ functionSignature: 'getShares(address)',
388
+ arguments: [address],
389
+ }));
390
+ const userShares = await multicallOrFallback(calls, chainId, provider);
391
+ const nonZeroCalls = userShares
392
+ .map((shares, index) => {
393
+ if (shares.success && shares.value.gt(0)) {
394
+ return {
395
+ address: addresses[index],
396
+ call: {
397
+ contract: new Contract(contractAddress, abi, provider),
398
+ functionSignature: 'convertToAssets(uint256)',
399
+ arguments: [shares.value.toString()],
400
+ },
401
+ };
402
+ }
403
+ return null;
404
+ })
405
+ .filter(Boolean);
406
+ const nonZeroBalances = await multicallOrFallback(nonZeroCalls.map((call) => call.call), chainId, provider);
407
+ nonZeroBalances.forEach((balance, index) => {
408
+ if (balance.success && balance.value) {
409
+ const { address } = nonZeroCalls[index];
410
+ balances[address] = balance.value.toHexString();
411
+ }
412
+ });
390
413
  }
391
414
  catch (error) {
392
415
  // if we get an error, log and return the default value
393
416
  console.error(error);
394
417
  }
395
- return balance.toHexString();
418
+ return balances;
396
419
  }
397
420
  }
398
421
  _AssetsContractController_provider = new WeakMap(), _AssetsContractController_ipfsGateway = new WeakMap(), _AssetsContractController_chainId = new WeakMap(), _AssetsContractController_instances = new WeakSet(), _AssetsContractController_registerActionHandlers = function _AssetsContractController_registerActionHandlers() {
@@ -1 +1 @@
1
- {"version":3,"file":"Asset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C,sBAAsB,CAAC,CAAC;KACzC;IAED,OAAO,IAAI,YAAY,CAAC,QAAQ,CAAC,CAAC;AACpC,CAAC,qGAQkB,eAAiC;IAClD,IAAI,eAAe,EAAE;QACnB,MAAM,0BAA0B,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC1D,4DAA4D,EAC5D,eAAe,CAChB,CAAC;QACF,IAAI,0BAA0B,EAAE;YAC9B,OAAO,0BAA0B,CAAC,OAAO,CAAC;SAC3C;KACF;IACD,MAAM,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC3D,4BAA4B,CAC7B,CAAC;IACF,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,wCAAwC,EACxC,uBAAuB,CACxB,CAAC;IACF,OAAO,aAAa,CAAC,aAAa,EAAE,OAAO,IAAI,uBAAA,IAAI,yCAAS,CAAC;AAC/D,CAAC;AA0ZH,eAAe,wBAAwB,CAAC","sourcesContent":["// import { BigNumber } from '@ethersproject/bignumber';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type {\n ActionConstraint,\n RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetNetworkConfigurationByNetworkClientId,\n NetworkControllerGetSelectedNetworkClientAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkDidChangeEvent,\n Provider,\n} from '@metamask/network-controller';\nimport type { PreferencesControllerStateChangeEvent } from '@metamask/preferences-controller';\nimport { getKnownPropertyNames, type Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport abiSingleCallBalancesContract from 'single-call-balance-checker-abi';\n\nimport {\n SupportedStakedBalanceNetworks,\n SupportedTokenDetectionNetworks,\n} from './assetsUtil';\nimport { ERC20Standard } from './Standards/ERC20Standard';\nimport { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';\nimport { ERC721Standard } from './Standards/NftStandards/ERC721/ERC721Standard';\n\n/**\n * Check if token detection is enabled for certain networks\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID = {\n [SupportedTokenDetectionNetworks.mainnet]:\n '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',\n [SupportedTokenDetectionNetworks.bsc]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.polygon]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.avax]:\n '0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',\n [SupportedTokenDetectionNetworks.aurora]:\n '0x1286415D333855237f89Df27D388127181448538',\n [SupportedTokenDetectionNetworks.linea_goerli]:\n '0x10dAd7Ca3921471f616db788D9300DC97Db01783',\n [SupportedTokenDetectionNetworks.linea_mainnet]:\n '0xF62e6a41561b3650a69Bb03199C735e3E3328c0D',\n [SupportedTokenDetectionNetworks.arbitrum]:\n '0x151E24A486D7258dd7C33Fb67E4bB01919B7B32c',\n [SupportedTokenDetectionNetworks.optimism]:\n '0xB1c568e9C3E6bdaf755A60c7418C269eb11524FC',\n [SupportedTokenDetectionNetworks.base]:\n '0x6AA75276052D96696134252587894ef5FFA520af',\n [SupportedTokenDetectionNetworks.zksync]:\n '0x458fEd3144680a5b8bcfaa0F9594aa19B4Ea2D34',\n [SupportedTokenDetectionNetworks.cronos]:\n '0x768ca200f0fc702ac9ea502498c18f5eff176378',\n [SupportedTokenDetectionNetworks.celo]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.gnosis]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.fantom]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.polygon_zkevm]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonbeam]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonriver]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n} as const satisfies Record<Hex, string>;\n\nexport const STAKING_CONTRACT_ADDRESS_BY_CHAINID = {\n [SupportedStakedBalanceNetworks.mainnet]:\n '0x4fef9d741011476750a243ac70b9789a63dd47df',\n [SupportedStakedBalanceNetworks.hoodi]:\n '0xe96ac18cfe5a7af8fe1fe7bc37ff110d88bc67ff',\n} as const satisfies Record<Hex, string>;\n\nexport const MISSING_PROVIDER_ERROR =\n 'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';\n\n/**\n * @type BalanceMap\n *\n * Key value object containing the balance for each tokenAddress\n * @property [tokenAddress] - Address of the token\n */\nexport type BalanceMap = {\n [tokenAddress: string]: BN;\n};\n\n/**\n * The name of the {@link AssetsContractController}\n */\nconst name = 'AssetsContractController';\n\n/**\n * A utility type that derives the public method names of a given messenger consumer class,\n * and uses it to generate the class's internal messenger action types.\n * @template Controller - A messenger consumer class.\n */\n// TODO: Figure out generic constraint and move to base-controller\ntype ControllerActionsMap<Controller> = {\n [ClassMethod in keyof Controller as Controller[ClassMethod] extends ActionConstraint['handler']\n ? ClassMethod\n : never]: {\n type: `${typeof name}:${ClassMethod & string}`;\n handler: Controller[ClassMethod];\n };\n};\n\ntype AssetsContractControllerActionsMap =\n ControllerActionsMap<AssetsContractController>;\n\n/**\n * The union of all public class method names of {@link AssetsContractController}.\n */\ntype AssetsContractControllerMethodName =\n keyof AssetsContractControllerActionsMap;\n\n/**\n * The union of all internal messenger actions available to the {@link AssetsContractControllerMessenger}.\n */\nexport type AssetsContractControllerActions =\n AssetsContractControllerActionsMap[AssetsContractControllerMethodName];\n\nexport type AssetsContractControllerGetERC20StandardAction =\n AssetsContractControllerActionsMap['getERC20Standard'];\n\nexport type AssetsContractControllerGetERC721StandardAction =\n AssetsContractControllerActionsMap['getERC721Standard'];\n\nexport type AssetsContractControllerGetERC1155StandardAction =\n AssetsContractControllerActionsMap['getERC1155Standard'];\n\nexport type AssetsContractControllerGetERC20BalanceOfAction =\n AssetsContractControllerActionsMap['getERC20BalanceOf'];\n\nexport type AssetsContractControllerGetERC20TokenDecimalsAction =\n AssetsContractControllerActionsMap['getERC20TokenDecimals'];\n\nexport type AssetsContractControllerGetERC20TokenNameAction =\n AssetsContractControllerActionsMap['getERC20TokenName'];\n\nexport type AssetsContractControllerGetERC721NftTokenIdAction =\n AssetsContractControllerActionsMap['getERC721NftTokenId'];\n\nexport type AssetsContractControllerGetERC721TokenURIAction =\n AssetsContractControllerActionsMap['getERC721TokenURI'];\n\nexport type AssetsContractControllerGetERC721AssetNameAction =\n AssetsContractControllerActionsMap['getERC721AssetName'];\n\nexport type AssetsContractControllerGetERC721AssetSymbolAction =\n AssetsContractControllerActionsMap['getERC721AssetSymbol'];\n\nexport type AssetsContractControllerGetERC721OwnerOfAction =\n AssetsContractControllerActionsMap['getERC721OwnerOf'];\n\nexport type AssetsContractControllerGetERC1155TokenURIAction =\n AssetsContractControllerActionsMap['getERC1155TokenURI'];\n\nexport type AssetsContractControllerGetERC1155BalanceOfAction =\n AssetsContractControllerActionsMap['getERC1155BalanceOf'];\n\nexport type AssetsContractControllerTransferSingleERC1155Action =\n AssetsContractControllerActionsMap['transferSingleERC1155'];\n\nexport type AssetsContractControllerGetTokenStandardAndDetailsAction =\n AssetsContractControllerActionsMap['getTokenStandardAndDetails'];\n\nexport type AssetsContractControllerGetBalancesInSingleCallAction =\n AssetsContractControllerActionsMap['getBalancesInSingleCall'];\n\n/**\n * The union of all internal messenger events available to the {@link AssetsContractControllerMessenger}.\n */\nexport type AssetsContractControllerEvents = never;\n\n/**\n * The union of all external messenger actions that must be allowed by the {@link AssetsContractControllerMessenger}.\n */\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId\n | NetworkControllerGetSelectedNetworkClientAction\n | NetworkControllerGetStateAction;\n\n/**\n * The union of all external messenger event that must be allowed by the {@link AssetsContractControllerMessenger}.\n */\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerNetworkDidChangeEvent;\n\n/**\n * The messenger of the {@link AssetsContractController}.\n */\nexport type AssetsContractControllerMessenger = RestrictedMessenger<\n typeof name,\n AssetsContractControllerActions | AllowedActions,\n AssetsContractControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport type StakedBalance = string | undefined;\n\n/**\n * Controller that interacts with contracts on mainnet through web3\n */\nexport class AssetsContractController {\n readonly name: typeof name = name;\n\n protected messagingSystem: AssetsContractControllerMessenger;\n\n #provider: Provider | undefined;\n\n #ipfsGateway: string;\n\n #chainId: Hex;\n\n /**\n * Creates a AssetsContractController instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The messenger.\n * @param options.chainId - The chain ID of the current network.\n */\n constructor({\n messenger,\n chainId: initialChainId,\n }: {\n messenger: AssetsContractControllerMessenger;\n chainId: Hex;\n }) {\n this.messagingSystem = messenger;\n this.#provider = undefined;\n this.#ipfsGateway = IPFS_DEFAULT_GATEWAY_URL;\n this.#chainId = initialChainId;\n\n this.#registerActionHandlers();\n this.#registerEventSubscriptions();\n }\n\n // TODO: Expand into base-controller utility function that batch registers action handlers.\n #registerActionHandlers() {\n const methodsExcludedFromMessenger = [\n 'constructor',\n 'messagingSystem',\n 'setProvider',\n 'provider',\n 'ipfsGateway',\n 'chainId',\n ];\n\n getKnownPropertyNames<keyof this>(Object.getPrototypeOf(this)).forEach(\n (method) => {\n if (\n ((key: keyof this): key is AssetsContractControllerMethodName =>\n !methodsExcludedFromMessenger.find((e) => e === key) &&\n typeof this[key] === 'function')(method)\n ) {\n this.messagingSystem.registerActionHandler(\n `${name}:${method}`,\n // TODO: Write a generic for-loop implementation that iterates over an input union type in tandem with the input array.\n // @ts-expect-error Both assigned argument and assignee parameter are using the entire union type for `method` instead of the type for the current element\n this[method].bind(this),\n );\n }\n },\n );\n }\n\n #registerEventSubscriptions() {\n this.messagingSystem.subscribe(\n `PreferencesController:stateChange`,\n ({ ipfsGateway }) => {\n this.#ipfsGateway = ipfsGateway;\n },\n );\n\n this.messagingSystem.subscribe(\n `NetworkController:networkDidChange`,\n ({ selectedNetworkClientId }) => {\n const chainId = this.#getCorrectChainId(selectedNetworkClientId);\n\n if (this.#chainId !== chainId) {\n this.#chainId = chainId;\n // @ts-expect-error TODO: remove this annotation once the `Eip1193Provider` class is released\n this.#provider = this.#getCorrectProvider();\n }\n },\n );\n }\n\n /**\n * Sets a new provider.\n *\n * @param provider - Provider used to create a new underlying Web3 instance\n */\n setProvider(provider: Provider | undefined) {\n this.#provider = provider;\n }\n\n get ipfsGateway() {\n return this.#ipfsGateway;\n }\n\n get chainId() {\n return this.#chainId;\n }\n\n /**\n * Get the relevant provider instance.\n *\n * @param networkClientId - Network Client ID.\n * @returns Web3Provider instance.\n */\n #getCorrectProvider(networkClientId?: NetworkClientId): Web3Provider {\n const provider = networkClientId\n ? this.messagingSystem.call(\n `NetworkController:getNetworkClientById`,\n networkClientId,\n ).provider\n : (this.messagingSystem.call('NetworkController:getSelectedNetworkClient')\n ?.provider ?? this.#provider);\n\n if (provider === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n\n return new Web3Provider(provider);\n }\n\n /**\n * Get the relevant chain ID.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns Hex chain ID.\n */\n #getCorrectChainId(networkClientId?: NetworkClientId): Hex {\n if (networkClientId) {\n const networkClientConfiguration = this.messagingSystem.call(\n 'NetworkController:getNetworkConfigurationByNetworkClientId',\n networkClientId,\n );\n if (networkClientConfiguration) {\n return networkClientConfiguration.chainId;\n }\n }\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return networkClient.configuration?.chainId ?? this.#chainId;\n }\n\n /**\n * Get a ERC20Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC20Standard instance.\n */\n getERC20Standard(networkClientId?: NetworkClientId): ERC20Standard {\n const provider = this.#getCorrectProvider(networkClientId);\n return new ERC20Standard(provider);\n }\n\n /**\n * Get a ERC721Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC721Standard instance.\n */\n getERC721Standard(networkClientId?: NetworkClientId): ERC721Standard {\n const provider = this.#getCorrectProvider(networkClientId);\n return new ERC721Standard(provider);\n }\n\n /**\n * Get a ERC1155Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC1155Standard instance.\n */\n getERC1155Standard(networkClientId?: NetworkClientId): ERC1155Standard {\n const provider = this.#getCorrectProvider(networkClientId);\n return new ERC1155Standard(provider);\n }\n\n /**\n * Get balance or count for current account on specific asset contract.\n *\n * @param address - Asset ERC20 contract address.\n * @param selectedAddress - Current account public address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getERC20BalanceOf(\n address: string,\n selectedAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getBalanceOf(address, selectedAddress);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenDecimals(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenDecimals(address);\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenName(address);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param address - ERC721 asset contract address.\n * @param selectedAddress - Current account public address.\n * @param index - An NFT counter less than `balanceOf(selectedAddress)`.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.\n */\n async getERC721NftTokenId(\n address: string,\n selectedAddress: string,\n index: number,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getNftTokenId(address, selectedAddress, index);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param tokenAddress - ERC721 asset contract address.\n * @param userAddress - Current account public address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.\n */\n async getTokenStandardAndDetails(\n tokenAddress: string,\n userAddress?: string,\n tokenId?: string,\n networkClientId?: NetworkClientId,\n ): Promise<{\n standard: string;\n tokenURI?: string | undefined;\n symbol?: string | undefined;\n name?: string | undefined;\n decimals?: string | undefined;\n balance?: BN | undefined;\n }> {\n // Asserts provider is available\n this.#getCorrectProvider(networkClientId);\n\n // ERC721\n try {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return {\n ...(await erc721Standard.getDetails(\n tokenAddress,\n this.#ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC1155\n try {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return {\n ...(await erc1155Standard.getDetails(\n tokenAddress,\n this.#ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC20\n try {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return {\n ...(await erc20Standard.getDetails(tokenAddress, userAddress)),\n };\n } catch {\n // Ignore\n }\n\n throw new Error('Unable to determine contract standard');\n }\n\n /**\n * Query for tokenURI for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC721TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'name'.\n */\n async getERC721AssetName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetName(address);\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'symbol'.\n */\n async getERC721AssetSymbol(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetSymbol(address);\n }\n\n /**\n * Query for owner for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the owner address.\n */\n async getERC721OwnerOf(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getOwnerOf(address, tokenId);\n }\n\n /**\n * Query for tokenURI for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @param tokenId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC1155TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for balance of a given ERC 1155 token.\n *\n * @param userAddress - Wallet public address.\n * @param nftAddress - ERC1155 asset contract address.\n * @param nftId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getERC1155BalanceOf(\n userAddress: string,\n nftAddress: string,\n nftId: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getBalanceOf(nftAddress, userAddress, nftId);\n }\n\n /**\n * Transfer single ERC1155 token.\n *\n * @param nftAddress - ERC1155 token address.\n * @param senderAddress - ERC1155 token sender.\n * @param recipientAddress - ERC1155 token recipient.\n * @param nftId - ERC1155 token id.\n * @param qty - Quantity of tokens to be sent.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'transferSingle' ERC1155 token.\n */\n async transferSingleERC1155(\n nftAddress: string,\n senderAddress: string,\n recipientAddress: string,\n nftId: string,\n qty: string,\n networkClientId?: NetworkClientId,\n ): Promise<void> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.transferSingle(\n nftAddress,\n senderAddress,\n recipientAddress,\n nftId,\n qty,\n );\n }\n\n /**\n * Get the token balance for a list of token addresses in a single call. Only non-zero balances\n * are returned.\n *\n * @param selectedAddress - The address to check token balances for.\n * @param tokensToDetect - The token addresses to detect balances for.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns The list of non-zero token balances.\n */\n async getBalancesInSingleCall(\n selectedAddress: string,\n tokensToDetect: string[],\n networkClientId?: NetworkClientId,\n ) {\n const chainId = this.#getCorrectChainId(networkClientId);\n const provider = this.#getCorrectProvider(networkClientId);\n if (\n !((id): id is keyof typeof SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID =>\n id in SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)(chainId)\n ) {\n // Only fetch balance if contract address exists\n return {};\n }\n const contractAddress = SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[chainId];\n\n const contract = new Contract(\n contractAddress,\n abiSingleCallBalancesContract,\n provider,\n );\n const result = await contract.balances([selectedAddress], tokensToDetect);\n const nonZeroBalances: BalanceMap = {};\n /* istanbul ignore else */\n if (result.length > 0) {\n tokensToDetect.forEach((tokenAddress, index) => {\n const balance: BN = result[index];\n /* istanbul ignore else */\n if (String(balance) !== '0') {\n nonZeroBalances[tokenAddress] = balance;\n }\n });\n }\n return nonZeroBalances;\n }\n\n /**\n * Get the staked ethereum balance for an address in a single call.\n *\n * @param address - The address to check staked ethereum balance for.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns The hex staked ethereum balance for address.\n */\n async getStakedBalanceForChain(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<StakedBalance> {\n const chainId = this.#getCorrectChainId(networkClientId);\n const provider = this.#getCorrectProvider(networkClientId);\n\n // balance defaults to zero\n let balance: BigNumber = BigNumber.from(0);\n\n // Only fetch staked balance on supported networks\n if (\n ![\n SupportedStakedBalanceNetworks.mainnet,\n SupportedStakedBalanceNetworks.hoodi,\n ].includes(chainId as SupportedStakedBalanceNetworks)\n ) {\n return undefined as StakedBalance;\n }\n // Only fetch staked balance if contract address exists\n if (\n !((id): id is keyof typeof STAKING_CONTRACT_ADDRESS_BY_CHAINID =>\n id in STAKING_CONTRACT_ADDRESS_BY_CHAINID)(chainId)\n ) {\n return undefined as StakedBalance;\n }\n\n const contractAddress = STAKING_CONTRACT_ADDRESS_BY_CHAINID[chainId];\n const abi = [\n {\n inputs: [{ internalType: 'address', name: 'account', type: 'address' }],\n name: 'getShares',\n outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'uint256', name: 'shares', type: 'uint256' }],\n name: 'convertToAssets',\n outputs: [{ internalType: 'uint256', name: 'assets', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n ];\n\n try {\n const contract = new Contract(contractAddress, abi, provider);\n const userShares = await contract.getShares(address);\n\n // convert shares to assets only if address shares > 0 else return default balance\n if (!userShares.lte(0)) {\n balance = await contract.convertToAssets(userShares.toString());\n }\n } catch (error) {\n // if we get an error, log and return the default value\n console.error(error);\n }\n\n return balance.toHexString();\n }\n}\n\nexport default AssetsContractController;\n"]}
1
+ {"version":3,"file":"AssetsContractController.mjs","sourceRoot":"","sources":["../src/AssetsContractController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAEA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAE,iCAAiC;AAKxD,OAAO,EAAE,wBAAwB,EAAE,mCAAmC;AAWtE,OAAO,EAAE,qBAAqB,EAAY,wBAAwB;AAElE,OAAO,8BAA6B,wCAAwC;;AAE5E,OAAO,EACL,8BAA8B,EAC9B,+BAA+B,EAChC,yBAAqB;AAEtB,OAAO,EAAE,mBAAmB,EAAE,wBAAoB;AAClD,OAAO,EAAE,aAAa,EAAE,sCAAkC;AAC1D,OAAO,EAAE,eAAe,EAAE,6DAAyD;AACnF,OAAO,EAAE,cAAc,EAAE,2DAAuD;AAEhF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,uCAAuC,GAAG;IACrD,CAAC,+BAA+B,CAAC,OAAO,CAAC,EACvC,4CAA4C;IAC9C,CAAC,+BAA+B,CAAC,GAAG,CAAC,EACnC,4CAA4C;IAC9C,CAAC,+BAA+B,CAAC,OAAO,CAAC,EACvC,4CAA4C;IAC9C,CAAC,+BAA+B,CAAC,IAAI,CAAC,EACpC,4CAA4C;IAC9C,CAAC,+BAA+B,CAAC,MAAM,CAAC,EACtC,4CAA4C;IAC9C,CAAC,+BAA+B,CAAC,YAAY,CAAC,EAC5C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wC,EACxC,eAAe,CAChB,CAAC,QAAQ;QACZ,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,4CAA4C,CAAC;YACtE,EAAE,QAAQ,IAAI,uBAAA,IAAI,0CAAU,CAAC,CAAC;IAEpC,IAAI,QAAQ,KAAK,SAAS,EAAE;QAC1B,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;KACzC;IAED,OAAO,IAAI,YAAY,CAAC,QAAQ,CAAC,CAAC;AACpC,CAAC,qGAQkB,eAAiC;IAClD,IAAI,eAAe,EAAE;QACnB,MAAM,0BAA0B,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC1D,4DAA4D,EAC5D,eAAe,CAChB,CAAC;QACF,IAAI,0BAA0B,EAAE;YAC9B,OAAO,0BAA0B,CAAC,OAAO,CAAC;SAC3C;KACF;IACD,MAAM,EAAE,uBAAuB,EAAE,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC3D,4BAA4B,CAC7B,CAAC;IACF,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,wCAAwC,EACxC,uBAAuB,CACxB,CAAC;IACF,OAAO,aAAa,CAAC,aAAa,EAAE,OAAO,IAAI,uBAAA,IAAI,yCAAS,CAAC;AAC/D,CAAC;AA2bH,eAAe,wBAAwB,CAAC","sourcesContent":["// import { BigNumber } from '@ethersproject/bignumber';\nimport type { BigNumber } from '@ethersproject/bignumber';\nimport { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type {\n ActionConstraint,\n RestrictedMessenger,\n} from '@metamask/base-controller';\nimport { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetNetworkConfigurationByNetworkClientId,\n NetworkControllerGetSelectedNetworkClientAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkDidChangeEvent,\n Provider,\n} from '@metamask/network-controller';\nimport type { PreferencesControllerStateChangeEvent } from '@metamask/preferences-controller';\nimport { getKnownPropertyNames, type Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport abiSingleCallBalancesContract from 'single-call-balance-checker-abi';\n\nimport {\n SupportedStakedBalanceNetworks,\n SupportedTokenDetectionNetworks,\n} from './assetsUtil';\nimport type { Call } from './multicall';\nimport { multicallOrFallback } from './multicall';\nimport { ERC20Standard } from './Standards/ERC20Standard';\nimport { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';\nimport { ERC721Standard } from './Standards/NftStandards/ERC721/ERC721Standard';\n\n/**\n * Check if token detection is enabled for certain networks\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID = {\n [SupportedTokenDetectionNetworks.mainnet]:\n '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',\n [SupportedTokenDetectionNetworks.bsc]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.polygon]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.avax]:\n '0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',\n [SupportedTokenDetectionNetworks.aurora]:\n '0x1286415D333855237f89Df27D388127181448538',\n [SupportedTokenDetectionNetworks.linea_goerli]:\n '0x10dAd7Ca3921471f616db788D9300DC97Db01783',\n [SupportedTokenDetectionNetworks.linea_mainnet]:\n '0xF62e6a41561b3650a69Bb03199C735e3E3328c0D',\n [SupportedTokenDetectionNetworks.arbitrum]:\n '0x151E24A486D7258dd7C33Fb67E4bB01919B7B32c',\n [SupportedTokenDetectionNetworks.optimism]:\n '0xB1c568e9C3E6bdaf755A60c7418C269eb11524FC',\n [SupportedTokenDetectionNetworks.base]:\n '0x6AA75276052D96696134252587894ef5FFA520af',\n [SupportedTokenDetectionNetworks.zksync]:\n '0x458fEd3144680a5b8bcfaa0F9594aa19B4Ea2D34',\n [SupportedTokenDetectionNetworks.cronos]:\n '0x768ca200f0fc702ac9ea502498c18f5eff176378',\n [SupportedTokenDetectionNetworks.celo]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.gnosis]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.fantom]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.polygon_zkevm]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonbeam]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonriver]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n} as const satisfies Record<Hex, string>;\n\nexport const STAKING_CONTRACT_ADDRESS_BY_CHAINID = {\n [SupportedStakedBalanceNetworks.mainnet]:\n '0x4fef9d741011476750a243ac70b9789a63dd47df',\n [SupportedStakedBalanceNetworks.hoodi]:\n '0xe96ac18cfe5a7af8fe1fe7bc37ff110d88bc67ff',\n} as const satisfies Record<Hex, string>;\n\nexport const MISSING_PROVIDER_ERROR =\n 'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';\n\n/**\n * BalanceMap\n *\n * Key value object containing the balance for each tokenAddress\n *\n * [tokenAddress] - Address of the token\n */\nexport type BalanceMap = {\n [tokenAddress: string]: BN;\n};\n\n/**\n * The name of the {@link AssetsContractController}\n */\nconst name = 'AssetsContractController';\n\n/**\n * A utility type that derives the public method names of a given messenger consumer class,\n * and uses it to generate the class's internal messenger action types.\n *\n * @template Controller - A messenger consumer class.\n */\n// TODO: Figure out generic constraint and move to base-controller\ntype ControllerActionsMap<Controller> = {\n [ClassMethod in keyof Controller as Controller[ClassMethod] extends ActionConstraint['handler']\n ? ClassMethod\n : never]: {\n type: `${typeof name}:${ClassMethod & string}`;\n handler: Controller[ClassMethod];\n };\n};\n\ntype AssetsContractControllerActionsMap =\n ControllerActionsMap<AssetsContractController>;\n\n/**\n * The union of all public class method names of {@link AssetsContractController}.\n */\ntype AssetsContractControllerMethodName =\n keyof AssetsContractControllerActionsMap;\n\n/**\n * The union of all internal messenger actions available to the {@link AssetsContractControllerMessenger}.\n */\nexport type AssetsContractControllerActions =\n AssetsContractControllerActionsMap[AssetsContractControllerMethodName];\n\nexport type AssetsContractControllerGetERC20StandardAction =\n AssetsContractControllerActionsMap['getERC20Standard'];\n\nexport type AssetsContractControllerGetERC721StandardAction =\n AssetsContractControllerActionsMap['getERC721Standard'];\n\nexport type AssetsContractControllerGetERC1155StandardAction =\n AssetsContractControllerActionsMap['getERC1155Standard'];\n\nexport type AssetsContractControllerGetERC20BalanceOfAction =\n AssetsContractControllerActionsMap['getERC20BalanceOf'];\n\nexport type AssetsContractControllerGetERC20TokenDecimalsAction =\n AssetsContractControllerActionsMap['getERC20TokenDecimals'];\n\nexport type AssetsContractControllerGetERC20TokenNameAction =\n AssetsContractControllerActionsMap['getERC20TokenName'];\n\nexport type AssetsContractControllerGetERC721NftTokenIdAction =\n AssetsContractControllerActionsMap['getERC721NftTokenId'];\n\nexport type AssetsContractControllerGetERC721TokenURIAction =\n AssetsContractControllerActionsMap['getERC721TokenURI'];\n\nexport type AssetsContractControllerGetERC721AssetNameAction =\n AssetsContractControllerActionsMap['getERC721AssetName'];\n\nexport type AssetsContractControllerGetERC721AssetSymbolAction =\n AssetsContractControllerActionsMap['getERC721AssetSymbol'];\n\nexport type AssetsContractControllerGetERC721OwnerOfAction =\n AssetsContractControllerActionsMap['getERC721OwnerOf'];\n\nexport type AssetsContractControllerGetERC1155TokenURIAction =\n AssetsContractControllerActionsMap['getERC1155TokenURI'];\n\nexport type AssetsContractControllerGetERC1155BalanceOfAction =\n AssetsContractControllerActionsMap['getERC1155BalanceOf'];\n\nexport type AssetsContractControllerTransferSingleERC1155Action =\n AssetsContractControllerActionsMap['transferSingleERC1155'];\n\nexport type AssetsContractControllerGetTokenStandardAndDetailsAction =\n AssetsContractControllerActionsMap['getTokenStandardAndDetails'];\n\nexport type AssetsContractControllerGetBalancesInSingleCallAction =\n AssetsContractControllerActionsMap['getBalancesInSingleCall'];\n\n/**\n * The union of all internal messenger events available to the {@link AssetsContractControllerMessenger}.\n */\nexport type AssetsContractControllerEvents = never;\n\n/**\n * The union of all external messenger actions that must be allowed by the {@link AssetsContractControllerMessenger}.\n */\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId\n | NetworkControllerGetSelectedNetworkClientAction\n | NetworkControllerGetStateAction;\n\n/**\n * The union of all external messenger event that must be allowed by the {@link AssetsContractControllerMessenger}.\n */\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerNetworkDidChangeEvent;\n\n/**\n * The messenger of the {@link AssetsContractController}.\n */\nexport type AssetsContractControllerMessenger = RestrictedMessenger<\n typeof name,\n AssetsContractControllerActions | AllowedActions,\n AssetsContractControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport type StakedBalance = string | undefined;\n\n/**\n * Controller that interacts with contracts on mainnet through web3\n */\nexport class AssetsContractController {\n readonly name: typeof name = name;\n\n protected messagingSystem: AssetsContractControllerMessenger;\n\n #provider: Provider | undefined;\n\n #ipfsGateway: string;\n\n #chainId: Hex;\n\n /**\n * Creates a AssetsContractController instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The messenger.\n * @param options.chainId - The chain ID of the current network.\n */\n constructor({\n messenger,\n chainId: initialChainId,\n }: {\n messenger: AssetsContractControllerMessenger;\n chainId: Hex;\n }) {\n this.messagingSystem = messenger;\n this.#provider = undefined;\n this.#ipfsGateway = IPFS_DEFAULT_GATEWAY_URL;\n this.#chainId = initialChainId;\n\n this.#registerActionHandlers();\n this.#registerEventSubscriptions();\n }\n\n // TODO: Expand into base-controller utility function that batch registers action handlers.\n #registerActionHandlers() {\n const methodsExcludedFromMessenger = [\n 'constructor',\n 'messagingSystem',\n 'setProvider',\n 'provider',\n 'ipfsGateway',\n 'chainId',\n ];\n\n getKnownPropertyNames<keyof this>(Object.getPrototypeOf(this)).forEach(\n (method) => {\n if (\n ((key: keyof this): key is AssetsContractControllerMethodName =>\n !methodsExcludedFromMessenger.find((e) => e === key) &&\n typeof this[key] === 'function')(method)\n ) {\n this.messagingSystem.registerActionHandler(\n `${name}:${method}`,\n // TODO: Write a generic for-loop implementation that iterates over an input union type in tandem with the input array.\n // @ts-expect-error Both assigned argument and assignee parameter are using the entire union type for `method` instead of the type for the current element\n this[method].bind(this),\n );\n }\n },\n );\n }\n\n #registerEventSubscriptions() {\n this.messagingSystem.subscribe(\n `PreferencesController:stateChange`,\n ({ ipfsGateway }) => {\n this.#ipfsGateway = ipfsGateway;\n },\n );\n\n this.messagingSystem.subscribe(\n `NetworkController:networkDidChange`,\n ({ selectedNetworkClientId }) => {\n const chainId = this.#getCorrectChainId(selectedNetworkClientId);\n\n if (this.#chainId !== chainId) {\n this.#chainId = chainId;\n // @ts-expect-error TODO: remove this annotation once the `Eip1193Provider` class is released\n this.#provider = this.#getCorrectProvider();\n }\n },\n );\n }\n\n /**\n * Sets a new provider.\n *\n * @param provider - Provider used to create a new underlying Web3 instance\n */\n setProvider(provider: Provider | undefined) {\n this.#provider = provider;\n }\n\n get ipfsGateway() {\n return this.#ipfsGateway;\n }\n\n get chainId() {\n return this.#chainId;\n }\n\n /**\n * Get the relevant provider instance.\n *\n * @param networkClientId - Network Client ID.\n * @returns Web3Provider instance.\n */\n #getCorrectProvider(networkClientId?: NetworkClientId): Web3Provider {\n const provider = networkClientId\n ? this.messagingSystem.call(\n `NetworkController:getNetworkClientById`,\n networkClientId,\n ).provider\n : (this.messagingSystem.call('NetworkController:getSelectedNetworkClient')\n ?.provider ?? this.#provider);\n\n if (provider === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n\n return new Web3Provider(provider);\n }\n\n /**\n * Get the relevant chain ID.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns Hex chain ID.\n */\n #getCorrectChainId(networkClientId?: NetworkClientId): Hex {\n if (networkClientId) {\n const networkClientConfiguration = this.messagingSystem.call(\n 'NetworkController:getNetworkConfigurationByNetworkClientId',\n networkClientId,\n );\n if (networkClientConfiguration) {\n return networkClientConfiguration.chainId;\n }\n }\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return networkClient.configuration?.chainId ?? this.#chainId;\n }\n\n /**\n * Get a ERC20Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC20Standard instance.\n */\n getERC20Standard(networkClientId?: NetworkClientId): ERC20Standard {\n const provider = this.#getCorrectProvider(networkClientId);\n return new ERC20Standard(provider);\n }\n\n /**\n * Get a ERC721Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC721Standard instance.\n */\n getERC721Standard(networkClientId?: NetworkClientId): ERC721Standard {\n const provider = this.#getCorrectProvider(networkClientId);\n return new ERC721Standard(provider);\n }\n\n /**\n * Get a ERC1155Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC1155Standard instance.\n */\n getERC1155Standard(networkClientId?: NetworkClientId): ERC1155Standard {\n const provider = this.#getCorrectProvider(networkClientId);\n return new ERC1155Standard(provider);\n }\n\n /**\n * Get balance or count for current account on specific asset contract.\n *\n * @param address - Asset ERC20 contract address.\n * @param selectedAddress - Current account public address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getERC20BalanceOf(\n address: string,\n selectedAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getBalanceOf(address, selectedAddress);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenDecimals(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenDecimals(address);\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenName(address);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param address - ERC721 asset contract address.\n * @param selectedAddress - Current account public address.\n * @param index - An NFT counter less than `balanceOf(selectedAddress)`.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.\n */\n async getERC721NftTokenId(\n address: string,\n selectedAddress: string,\n index: number,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getNftTokenId(address, selectedAddress, index);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param tokenAddress - ERC721 asset contract address.\n * @param userAddress - Current account public address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.\n */\n async getTokenStandardAndDetails(\n tokenAddress: string,\n userAddress?: string,\n tokenId?: string,\n networkClientId?: NetworkClientId,\n ): Promise<{\n standard: string;\n tokenURI?: string | undefined;\n symbol?: string | undefined;\n name?: string | undefined;\n decimals?: string | undefined;\n balance?: BN | undefined;\n }> {\n // Asserts provider is available\n this.#getCorrectProvider(networkClientId);\n\n // ERC721\n try {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return {\n ...(await erc721Standard.getDetails(\n tokenAddress,\n this.#ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC1155\n try {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return {\n ...(await erc1155Standard.getDetails(\n tokenAddress,\n this.#ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC20\n try {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return {\n ...(await erc20Standard.getDetails(tokenAddress, userAddress)),\n };\n } catch {\n // Ignore\n }\n\n throw new Error('Unable to determine contract standard');\n }\n\n /**\n * Query for tokenURI for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC721TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'name'.\n */\n async getERC721AssetName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetName(address);\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'symbol'.\n */\n async getERC721AssetSymbol(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetSymbol(address);\n }\n\n /**\n * Query for owner for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the owner address.\n */\n async getERC721OwnerOf(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getOwnerOf(address, tokenId);\n }\n\n /**\n * Query for tokenURI for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @param tokenId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC1155TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for balance of a given ERC 1155 token.\n *\n * @param userAddress - Wallet public address.\n * @param nftAddress - ERC1155 asset contract address.\n * @param nftId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getERC1155BalanceOf(\n userAddress: string,\n nftAddress: string,\n nftId: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getBalanceOf(nftAddress, userAddress, nftId);\n }\n\n /**\n * Transfer single ERC1155 token.\n *\n * @param nftAddress - ERC1155 token address.\n * @param senderAddress - ERC1155 token sender.\n * @param recipientAddress - ERC1155 token recipient.\n * @param nftId - ERC1155 token id.\n * @param qty - Quantity of tokens to be sent.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'transferSingle' ERC1155 token.\n */\n async transferSingleERC1155(\n nftAddress: string,\n senderAddress: string,\n recipientAddress: string,\n nftId: string,\n qty: string,\n networkClientId?: NetworkClientId,\n ): Promise<void> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.transferSingle(\n nftAddress,\n senderAddress,\n recipientAddress,\n nftId,\n qty,\n );\n }\n\n /**\n * Get the token balance for a list of token addresses in a single call. Only non-zero balances\n * are returned.\n *\n * @param selectedAddress - The address to check token balances for.\n * @param tokensToDetect - The token addresses to detect balances for.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns The list of non-zero token balances.\n */\n async getBalancesInSingleCall(\n selectedAddress: string,\n tokensToDetect: string[],\n networkClientId?: NetworkClientId,\n ) {\n const chainId = this.#getCorrectChainId(networkClientId);\n const provider = this.#getCorrectProvider(networkClientId);\n if (\n !((id): id is keyof typeof SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID =>\n id in SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)(chainId)\n ) {\n // Only fetch balance if contract address exists\n return {};\n }\n const contractAddress = SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[chainId];\n\n const contract = new Contract(\n contractAddress,\n abiSingleCallBalancesContract,\n provider,\n );\n const result = await contract.balances([selectedAddress], tokensToDetect);\n const nonZeroBalances: BalanceMap = {};\n /* istanbul ignore else */\n if (result.length > 0) {\n tokensToDetect.forEach((tokenAddress, index) => {\n const balance: BN = result[index];\n /* istanbul ignore else */\n if (String(balance) !== '0') {\n nonZeroBalances[tokenAddress] = balance;\n }\n });\n }\n return nonZeroBalances;\n }\n\n /**\n * Get the staked ethereum balance for multiple addresses in a single call.\n *\n * @param addresses - The addresses to check staked ethereum balance for.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns The hex staked ethereum balance for address.\n */\n async getStakedBalanceForChain(\n addresses: string[],\n networkClientId?: NetworkClientId,\n ): Promise<Record<string, StakedBalance>> {\n const chainId = this.#getCorrectChainId(networkClientId);\n const provider = this.#getCorrectProvider(networkClientId);\n\n const balances = addresses.reduce<Record<string, StakedBalance>>(\n (accumulator, address) => {\n accumulator[address] = '0x00';\n return accumulator;\n },\n {},\n );\n\n // Only fetch staked balance on supported networks\n if (\n ![\n SupportedStakedBalanceNetworks.mainnet,\n SupportedStakedBalanceNetworks.hoodi,\n ].includes(chainId as SupportedStakedBalanceNetworks)\n ) {\n return {};\n }\n // Only fetch staked balance if contract address exists\n if (\n !((id): id is keyof typeof STAKING_CONTRACT_ADDRESS_BY_CHAINID =>\n id in STAKING_CONTRACT_ADDRESS_BY_CHAINID)(chainId)\n ) {\n return {};\n }\n\n const contractAddress = STAKING_CONTRACT_ADDRESS_BY_CHAINID[chainId];\n const abi = [\n {\n inputs: [{ internalType: 'address', name: 'account', type: 'address' }],\n name: 'getShares',\n outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [{ internalType: 'uint256', name: 'shares', type: 'uint256' }],\n name: 'convertToAssets',\n outputs: [{ internalType: 'uint256', name: 'assets', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n ];\n\n try {\n const calls = addresses.map((address) => ({\n contract: new Contract(contractAddress, abi, provider),\n functionSignature: 'getShares(address)',\n arguments: [address],\n }));\n\n const userShares = await multicallOrFallback(calls, chainId, provider);\n\n const nonZeroCalls = userShares\n .map((shares, index) => {\n if (shares.success && (shares.value as BigNumber).gt(0)) {\n return {\n address: addresses[index],\n call: {\n contract: new Contract(contractAddress, abi, provider),\n functionSignature: 'convertToAssets(uint256)',\n arguments: [(shares.value as BigNumber).toString()],\n },\n };\n }\n return null;\n })\n .filter(Boolean) as { call: Call; address: string }[];\n\n const nonZeroBalances = await multicallOrFallback(\n nonZeroCalls.map((call) => call.call),\n chainId,\n provider,\n );\n nonZeroBalances.forEach((balance, index) => {\n if (balance.success && balance.value) {\n const { address } = nonZeroCalls[index];\n balances[address] = (balance.value as BigNumber).toHexString();\n }\n });\n } catch (error) {\n // if we get an error, log and return the default value\n console.error(error);\n }\n\n return balances;\n }\n}\n\nexport default AssetsContractController;\n"]}
@@ -33,9 +33,10 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
33
33
  * @param options.interval - The polling interval, in milliseconds.
34
34
  * @param options.messenger - A reference to the messaging system.
35
35
  * @param options.state - Initial state to set on this controller.
36
+ * @param options.useExternalServices - Feature Switch for using external services (default: true)
36
37
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
37
38
  */
38
- constructor({ includeUsdRate = false, interval = 180000, messenger, state, fetchMultiExchangeRate = crypto_compare_service_1.fetchMultiExchangeRate, }) {
39
+ constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = crypto_compare_service_1.fetchMultiExchangeRate, }) {
39
40
  super({
40
41
  name,
41
42
  metadata,
@@ -44,6 +45,7 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
44
45
  });
45
46
  this.mutex = new async_mutex_1.Mutex();
46
47
  this.includeUsdRate = includeUsdRate;
48
+ this.useExternalServices = useExternalServices;
47
49
  this.setIntervalLength(interval);
48
50
  this.fetchMultiExchangeRate = fetchMultiExchangeRate;
49
51
  }
@@ -76,6 +78,9 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
76
78
  * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.
77
79
  */
78
80
  async updateExchangeRate(nativeCurrencies) {
81
+ if (!this.useExternalServices()) {
82
+ return;
83
+ }
79
84
  const releaseLock = await this.mutex.acquire();
80
85
  try {
81
86
  const { currentCurrency } = this.state;
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.cjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;AAKA,iEAGoC;AAEpC,qEAA+E;AAC/E,6CAAoC;AAEpC,+EAAmG;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AA0BtC,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACnD,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CAClD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAA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,CAAC;gBACF,OAAO,GAAG,CAAC;YACb,CAAC,EACD,EAAwC,CACzC,CAAC;YAEF,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,CAAC,aAAa,GAAG;oBACpB,GAAG,KAAK,CAAC,aAAa;oBACtB,GAAG,KAAK;iBACT,CAAC;YACJ,CAAC,CAAC,CAAC;SACJ;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,MAAM,KAAK,CAAC;SACb;gBAAS;YACR,WAAW,EAAE,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACM,OAAO;QACd,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,gBAAgB,GACS;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAClD,CAAC;CACF;AAvJD,wDAuJC;AAED,kBAAe,sBAAsB,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype CurrencyRateMessenger = RestrictedMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\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 this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
1
+ {"version":3,"file":"CurrencyRateController.cjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;AAKA,iEAGoC;AAEpC,qEAA+E;AAC/E,6CAAoC;AAEpC,+EAAmG;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AA0BtC,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACnD,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CAClD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAAG,EAAE;YACH,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;YACjB,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAOF;;;GAGG;AACH,MAAa,sBAAuB,SAAQ,IAAA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IAAI;iBACrC,CAAC;gBACF,OAAO,GAAG,CAAC;YACb,CAAC,EACD,EAAwC,CACzC,CAAC;YAEF,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,CAAC,aAAa,GAAG;oBACpB,GAAG,KAAK,CAAC,aAAa;oBACtB,GAAG,KAAK;iBACT,CAAC;YACJ,CAAC,CAAC,CAAC;SACJ;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,MAAM,KAAK,CAAC;SACb;gBAAS;YACR,WAAW,EAAE,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACM,OAAO;QACd,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,gBAAgB,GACS;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAClD,CAAC;CACF;AAjKD,wDAiKC;AAED,kBAAe,sBAAsB,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype CurrencyRateMessenger = RestrictedMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.useExternalServices - Feature Switch for using external services (default: true)\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\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 this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
@@ -51,6 +51,7 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
51
51
  private readonly mutex;
52
52
  private readonly fetchMultiExchangeRate;
53
53
  private readonly includeUsdRate;
54
+ private readonly useExternalServices;
54
55
  /**
55
56
  * Creates a CurrencyRateController instance.
56
57
  *
@@ -59,13 +60,15 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
59
60
  * @param options.interval - The polling interval, in milliseconds.
60
61
  * @param options.messenger - A reference to the messaging system.
61
62
  * @param options.state - Initial state to set on this controller.
63
+ * @param options.useExternalServices - Feature Switch for using external services (default: true)
62
64
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
63
65
  */
64
- constructor({ includeUsdRate, interval, messenger, state, fetchMultiExchangeRate, }: {
66
+ constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, }: {
65
67
  includeUsdRate?: boolean;
66
68
  interval?: number;
67
69
  messenger: CurrencyRateMessenger;
68
70
  state?: Partial<CurrencyRateState>;
71
+ useExternalServices?: () => boolean;
69
72
  fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;
70
73
  });
71
74
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.d.cts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,2CAA2C,EAAE,qCAAqC;AAIhG,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAEnG;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CACnB,MAAM,EACN;QACE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;KAClC,CACF,CAAC;CACH,CAAC;AAEF,QAAA,MAAM,IAAI,2BAA2B,CAAC;AAEtC,MAAM,MAAM,uBAAuB,GAAG,0BAA0B,CAC9D,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG,uBAAuB,CAAC;AAEnE,MAAM,MAAM,oBAAoB,GAAG,wBAAwB,CACzD,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,oBAAoB,CAAC;AAEjE,KAAK,cAAc,GAAG,2CAA2C,CAAC;AAElE,KAAK,qBAAqB,GAAG,mBAAmB,CAC9C,OAAO,IAAI,EACX,6BAA6B,GAAG,cAAc,EAC9C,4BAA4B,EAC5B,cAAc,CAAC,MAAM,CAAC,EACtB,KAAK,CACN,CAAC;AAkBF,wEAAwE;AACxE,KAAK,wBAAwB,GAAG;IAC9B,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B,CAAC;;;;;;;;;;;;;;;;AAEF;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,4BAC1C,OAAO,IAAI,EACX,iBAAiB,EACjB,qBAAqB,CACtB;IACC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAe;IAErC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAC;IAExC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC;IAEhC;;;;;;;;;OASG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,SAAS,EACT,KAAK,EACL,sBAAsD,GACvD,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;KAC/D;IAYD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAkBhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IAuDhB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
1
+ {"version":3,"file":"CurrencyRateController.d.cts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EAC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AC,cAAc,CAAC;IAEhC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAgB;IAEpD;;;;;;;;;;OAUG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,mBAAgC,EAChC,SAAS,EACT,KAAK,EACL,sBAAsD,GACvD,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC;QACpC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;KAC/D;IAaD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAkBhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IA2DhB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
@@ -51,6 +51,7 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
51
51
  private readonly mutex;
52
52
  private readonly fetchMultiExchangeRate;
53
53
  private readonly includeUsdRate;
54
+ private readonly useExternalServices;
54
55
  /**
55
56
  * Creates a CurrencyRateController instance.
56
57
  *
@@ -59,13 +60,15 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
59
60
  * @param options.interval - The polling interval, in milliseconds.
60
61
  * @param options.messenger - A reference to the messaging system.
61
62
  * @param options.state - Initial state to set on this controller.
63
+ * @param options.useExternalServices - Feature Switch for using external services (default: true)
62
64
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
63
65
  */
64
- constructor({ includeUsdRate, interval, messenger, state, fetchMultiExchangeRate, }: {
66
+ constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, }: {
65
67
  includeUsdRate?: boolean;
66
68
  interval?: number;
67
69
  messenger: CurrencyRateMessenger;
68
70
  state?: Partial<CurrencyRateState>;
71
+ useExternalServices?: () => boolean;
69
72
  fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;
70
73
  });
71
74
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.d.mts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,2CAA2C,EAAE,qCAAqC;AAIhG,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAEnG;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CACnB,MAAM,EACN;QACE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;KAClC,CACF,CAAC;CACH,CAAC;AAEF,QAAA,MAAM,IAAI,2BAA2B,CAAC;AAEtC,MAAM,MAAM,uBAAuB,GAAG,0BAA0B,CAC9D,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG,uBAAuB,CAAC;AAEnE,MAAM,MAAM,oBAAoB,GAAG,wBAAwB,CACzD,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,oBAAoB,CAAC;AAEjE,KAAK,cAAc,GAAG,2CAA2C,CAAC;AAElE,KAAK,qBAAqB,GAAG,mBAAmB,CAC9C,OAAO,IAAI,EACX,6BAA6B,GAAG,cAAc,EAC9C,4BAA4B,EAC5B,cAAc,CAAC,MAAM,CAAC,EACtB,KAAK,CACN,CAAC;AAkBF,wEAAwE;AACxE,KAAK,wBAAwB,GAAG;IAC9B,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B,CAAC;;;;;;;;;;;;;;;;AAEF;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,4BAC1C,OAAO,IAAI,EACX,iBAAiB,EACjB,qBAAqB,CACtB;IACC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAe;IAErC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAC;IAExC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC;IAEhC;;;;;;;;;OASG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,SAAS,EACT,KAAK,EACL,sBAAsD,GACvD,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;KAC/D;IAYD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAkBhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IAuDhB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
1
+ {"version":3,"file":"CurrencyRateController.d.mts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCA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OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAgB;IAEpD;;;;;;;;;;OAUG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,mBAAgC,EAChC,SAAS,EACT,KAAK,EACL,sBAAsD,GACvD,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC;QACpC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;KAC/D;IAaD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAkBhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IA2DhB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
@@ -30,9 +30,10 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
30
30
  * @param options.interval - The polling interval, in milliseconds.
31
31
  * @param options.messenger - A reference to the messaging system.
32
32
  * @param options.state - Initial state to set on this controller.
33
+ * @param options.useExternalServices - Feature Switch for using external services (default: true)
33
34
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
34
35
  */
35
- constructor({ includeUsdRate = false, interval = 180000, messenger, state, fetchMultiExchangeRate = defaultFetchMultiExchangeRate, }) {
36
+ constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = defaultFetchMultiExchangeRate, }) {
36
37
  super({
37
38
  name,
38
39
  metadata,
@@ -41,6 +42,7 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
41
42
  });
42
43
  this.mutex = new Mutex();
43
44
  this.includeUsdRate = includeUsdRate;
45
+ this.useExternalServices = useExternalServices;
44
46
  this.setIntervalLength(interval);
45
47
  this.fetchMultiExchangeRate = fetchMultiExchangeRate;
46
48
  }
@@ -73,6 +75,9 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
73
75
  * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.
74
76
  */
75
77
  async updateExchangeRate(nativeCurrencies) {
78
+ if (!this.useExternalServices()) {
79
+ return;
80
+ }
76
81
  const releaseLock = await this.mutex.acquire();
77
82
  try {
78
83
  const { currentCurrency } = this.state;
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,mCAAmC;AAEpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AA0BtC,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACnD,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CAClD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAAG,EAAE;YACH,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;YACjB,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAOF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,+BAA+B,EAI1E;IAOC;;;;;;;;;OASG;IACH,YAAY,EACV,cAAc,GAAG,KAAK,EACtB,QAA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,CAAC;SACJ;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,MAAM,KAAK,CAAC;SACb;gBAAS;YACR,WAAW,EAAE,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACM,OAAO;QACd,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,gBAAgB,GACS;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAClD,CAAC;CACF;AAED,eAAe,sBAAsB,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype CurrencyRateMessenger = RestrictedMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\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 this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
1
+ {"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,mCAAmC;AAEpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AA0BtC,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACnD,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CAClD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAAG,EAAE;YACH,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;YACjB,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAOF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,+BAA+B,EAI1E;IASC;;;;;;;;;;OAUG;IACH,YAAY,EACV,cAAc,GAAG,KAAK,EACtB,QAAQ,GAAG,MAAM,EACjB,mBAAmB,GAAG,G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EAAE,EAAE;gBACpB,KAAK,CAAC,aAAa,GAAG;oBACpB,GAAG,KAAK,CAAC,aAAa;oBACtB,GAAG,KAAK;iBACT,CAAC;YACJ,CAAC,CAAC,CAAC;SACJ;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,MAAM,KAAK,CAAC;SACb;gBAAS;YACR,WAAW,EAAE,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACM,OAAO;QACd,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,gBAAgB,GACS;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAClD,CAAC;CACF;AAED,eAAe,sBAAsB,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype CurrencyRateMessenger = RestrictedMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.useExternalServices - Feature Switch for using external services (default: true)\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\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 this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
@@ -155,12 +155,17 @@ class MultichainAssetsRatesController extends (0, polling_controller_1.StaticInt
155
155
  const selectedAccount = account ??
156
156
  this.messagingSystem.call('AccountsController:getSelectedMultichainAccount');
157
157
  try {
158
- const historicalPricesResponse = await __classPrivateFieldGet(this, _MultichainAssetsRatesController_instances, "m", _MultichainAssetsRatesController_handleSnapRequest).call(this, {
158
+ const historicalPricesResponse = await this.messagingSystem.call('SnapController:handleRequest', {
159
159
  snapId: selectedAccount?.metadata.snap?.id,
160
+ origin: 'metamask',
160
161
  handler: snaps_utils_1.HandlerType.OnAssetHistoricalPrice,
161
- params: {
162
- from: asset,
163
- to: currentCaipCurrency,
162
+ request: {
163
+ jsonrpc: '2.0',
164
+ method: snaps_utils_1.HandlerType.OnAssetHistoricalPrice,
165
+ params: {
166
+ from: asset,
167
+ to: currentCaipCurrency,
168
+ },
164
169
  },
165
170
  });
166
171
  // skip state update if no historical prices are returned
@@ -202,6 +207,10 @@ _MultichainAssetsRatesController_mutex = new WeakMap(), _MultichainAssetsRatesCo
202
207
  handler: snaps_utils_1.HandlerType.OnAssetsConversion,
203
208
  params: conversions,
204
209
  }));
210
+ // If the snap request failed, return empty rates
211
+ if (!accountRatesResponse) {
212
+ return {};
213
+ }
205
214
  // Prepare assets param for onAssetsMarketData
206
215
  const currentCurrencyCaip = constant_1.MAP_CAIP_CURRENCIES[__classPrivateFieldGet(this, _MultichainAssetsRatesController_currentCurrency, "f")] ?? constant_1.MAP_CAIP_CURRENCIES.usd;
207
216
  const assetsParam = {
@@ -263,6 +272,9 @@ async function _MultichainAssetsRatesController_updateAssetsRatesForNewAssets(ac
263
272
  })),
264
273
  };
265
274
  }, _MultichainAssetsRatesController_flattenRates = function _MultichainAssetsRatesController_flattenRates(assetsConversionResponse) {
275
+ if (!assetsConversionResponse?.conversionRates) {
276
+ return {};
277
+ }
266
278
  const { conversionRates } = assetsConversionResponse;
267
279
  return Object.fromEntries(Object.entries(conversionRates).map(([asset, nestedObj]) => {
268
280
  // e.g., nestedObj might look like: { "swift:0/iso4217:EUR": { rate, conversionTime } }
@@ -302,16 +314,28 @@ async function _MultichainAssetsRatesController_updateAssetsRatesForNewAssets(ac
302
314
  * @returns A promise that resolves with the account rates.
303
315
  */
304
316
  async function _MultichainAssetsRatesController_handleSnapRequest({ snapId, handler, params, }) {
305
- return this.messagingSystem.call('SnapController:handleRequest', {
306
- snapId,
307
- origin: 'metamask',
308
- handler,
309
- request: {
310
- jsonrpc: '2.0',
311
- method: handler,
317
+ try {
318
+ return (await this.messagingSystem.call('SnapController:handleRequest', {
319
+ snapId,
320
+ origin: 'metamask',
321
+ handler,
322
+ request: {
323
+ jsonrpc: '2.0',
324
+ method: handler,
325
+ params,
326
+ },
327
+ }));
328
+ }
329
+ catch (error) {
330
+ console.error(`Snap request failed for ${handler}:`, {
331
+ snapId,
332
+ handler,
333
+ message: error.message,
312
334
  params,
313
- },
314
- });
335
+ });
336
+ // Ignore
337
+ return undefined;
338
+ }
315
339
  }, _MultichainAssetsRatesController_mergeMarketDataIntoConversionRates = function _MultichainAssetsRatesController_mergeMarketDataIntoConversionRates(accountRatesResponse, marketDataResponse) {
316
340
  // Early return if no market data to merge
317
341
  if (!marketDataResponse?.marketData) {