@metamask/assets-controllers 83.1.0 → 84.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -2
- package/dist/AccountTrackerController.cjs +20 -21
- package/dist/AccountTrackerController.cjs.map +1 -1
- package/dist/AccountTrackerController.d.cts +4 -3
- package/dist/AccountTrackerController.d.cts.map +1 -1
- package/dist/AccountTrackerController.d.mts +4 -3
- package/dist/AccountTrackerController.d.mts.map +1 -1
- package/dist/AccountTrackerController.mjs +20 -21
- package/dist/AccountTrackerController.mjs.map +1 -1
- package/dist/AssetsContractController.cjs +10 -10
- package/dist/AssetsContractController.cjs.map +1 -1
- package/dist/AssetsContractController.d.cts +3 -3
- package/dist/AssetsContractController.d.cts.map +1 -1
- package/dist/AssetsContractController.d.mts +3 -3
- package/dist/AssetsContractController.d.mts.map +1 -1
- package/dist/AssetsContractController.mjs +10 -10
- package/dist/AssetsContractController.mjs.map +1 -1
- package/dist/CurrencyRateController.cjs +3 -3
- package/dist/CurrencyRateController.cjs.map +1 -1
- package/dist/CurrencyRateController.d.cts +4 -3
- package/dist/CurrencyRateController.d.cts.map +1 -1
- package/dist/CurrencyRateController.d.mts +4 -3
- package/dist/CurrencyRateController.d.mts.map +1 -1
- package/dist/CurrencyRateController.mjs +3 -3
- package/dist/CurrencyRateController.mjs.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.cjs +7 -7
- package/dist/DeFiPositionsController/DeFiPositionsController.cjs.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.d.cts +3 -2
- package/dist/DeFiPositionsController/DeFiPositionsController.d.cts.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.d.mts +3 -2
- package/dist/DeFiPositionsController/DeFiPositionsController.d.mts.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.mjs +7 -7
- package/dist/DeFiPositionsController/DeFiPositionsController.mjs.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.cjs +12 -12
- package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.d.cts +3 -2
- package/dist/MultichainAssetsController/MultichainAssetsController.d.cts.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.d.mts +3 -2
- package/dist/MultichainAssetsController/MultichainAssetsController.d.mts.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.mjs +12 -12
- package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs +13 -13
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts +4 -3
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts.map +1 -1
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts +4 -3
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts.map +1 -1
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs +13 -13
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs +9 -9
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.cts +3 -2
- package/dist/MultichainBalancesController/MultichainBalancesController.d.cts.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.mts +3 -2
- package/dist/MultichainBalancesController/MultichainBalancesController.d.mts.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs +9 -9
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
- package/dist/NftController.cjs +25 -25
- package/dist/NftController.cjs.map +1 -1
- package/dist/NftController.d.cts +3 -3
- package/dist/NftController.d.cts.map +1 -1
- package/dist/NftController.d.mts +3 -3
- package/dist/NftController.d.mts.map +1 -1
- package/dist/NftController.mjs +25 -25
- package/dist/NftController.mjs.map +1 -1
- package/dist/NftDetectionController.cjs +5 -6
- package/dist/NftDetectionController.cjs.map +1 -1
- package/dist/NftDetectionController.d.cts +5 -5
- package/dist/NftDetectionController.d.cts.map +1 -1
- package/dist/NftDetectionController.d.mts +5 -5
- package/dist/NftDetectionController.d.mts.map +1 -1
- package/dist/NftDetectionController.mjs +5 -6
- package/dist/NftDetectionController.mjs.map +1 -1
- package/dist/RatesController/RatesController.cjs +5 -5
- package/dist/RatesController/RatesController.cjs.map +1 -1
- package/dist/RatesController/RatesController.d.cts.map +1 -1
- package/dist/RatesController/RatesController.d.mts.map +1 -1
- package/dist/RatesController/RatesController.mjs +5 -5
- package/dist/RatesController/RatesController.mjs.map +1 -1
- package/dist/RatesController/types.cjs.map +1 -1
- package/dist/RatesController/types.d.cts +3 -2
- package/dist/RatesController/types.d.cts.map +1 -1
- package/dist/RatesController/types.d.mts +3 -2
- package/dist/RatesController/types.d.mts.map +1 -1
- package/dist/RatesController/types.mjs.map +1 -1
- package/dist/TokenBalancesController.cjs +22 -22
- package/dist/TokenBalancesController.cjs.map +1 -1
- package/dist/TokenBalancesController.d.cts +3 -2
- package/dist/TokenBalancesController.d.cts.map +1 -1
- package/dist/TokenBalancesController.d.mts +3 -2
- package/dist/TokenBalancesController.d.mts.map +1 -1
- package/dist/TokenBalancesController.mjs +22 -22
- package/dist/TokenBalancesController.mjs.map +1 -1
- package/dist/TokenDetectionController.cjs +24 -24
- package/dist/TokenDetectionController.cjs.map +1 -1
- package/dist/TokenDetectionController.d.cts +4 -3
- package/dist/TokenDetectionController.d.cts.map +1 -1
- package/dist/TokenDetectionController.d.mts +4 -3
- package/dist/TokenDetectionController.d.mts.map +1 -1
- package/dist/TokenDetectionController.mjs +24 -24
- package/dist/TokenDetectionController.mjs.map +1 -1
- package/dist/TokenListController.cjs +4 -4
- package/dist/TokenListController.cjs.map +1 -1
- package/dist/TokenListController.d.cts +3 -2
- package/dist/TokenListController.d.cts.map +1 -1
- package/dist/TokenListController.d.mts +3 -2
- package/dist/TokenListController.d.mts.map +1 -1
- package/dist/TokenListController.mjs +4 -4
- package/dist/TokenListController.mjs.map +1 -1
- package/dist/TokenRatesController.cjs +6 -6
- package/dist/TokenRatesController.cjs.map +1 -1
- package/dist/TokenRatesController.d.cts +3 -2
- package/dist/TokenRatesController.d.cts.map +1 -1
- package/dist/TokenRatesController.d.mts +3 -2
- package/dist/TokenRatesController.d.mts.map +1 -1
- package/dist/TokenRatesController.mjs +6 -6
- package/dist/TokenRatesController.mjs.map +1 -1
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs +4 -4
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -1
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts +3 -2
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts.map +1 -1
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts +3 -2
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts.map +1 -1
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs +4 -4
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -1
- package/dist/TokensController.cjs +17 -17
- package/dist/TokensController.cjs.map +1 -1
- package/dist/TokensController.d.cts +3 -2
- package/dist/TokensController.d.cts.map +1 -1
- package/dist/TokensController.d.mts +3 -2
- package/dist/TokensController.d.mts.map +1 -1
- package/dist/TokensController.mjs +17 -17
- package/dist/TokensController.mjs.map +1 -1
- package/dist/selectors/token-selectors.d.cts +8 -8
- package/dist/selectors/token-selectors.d.mts +8 -8
- package/package.json +25 -24
|
@@ -79,7 +79,7 @@ export class AssetsContractController {
|
|
|
79
79
|
_AssetsContractController_provider.set(this, void 0);
|
|
80
80
|
_AssetsContractController_ipfsGateway.set(this, void 0);
|
|
81
81
|
_AssetsContractController_chainId.set(this, void 0);
|
|
82
|
-
this.
|
|
82
|
+
this.messenger = messenger;
|
|
83
83
|
__classPrivateFieldSet(this, _AssetsContractController_provider, undefined, "f");
|
|
84
84
|
__classPrivateFieldSet(this, _AssetsContractController_ipfsGateway, IPFS_DEFAULT_GATEWAY_URL, "f");
|
|
85
85
|
__classPrivateFieldSet(this, _AssetsContractController_chainId, initialChainId, "f");
|
|
@@ -421,7 +421,7 @@ export class AssetsContractController {
|
|
|
421
421
|
_AssetsContractController_provider = new WeakMap(), _AssetsContractController_ipfsGateway = new WeakMap(), _AssetsContractController_chainId = new WeakMap(), _AssetsContractController_instances = new WeakSet(), _AssetsContractController_registerActionHandlers = function _AssetsContractController_registerActionHandlers() {
|
|
422
422
|
const methodsExcludedFromMessenger = [
|
|
423
423
|
'constructor',
|
|
424
|
-
'
|
|
424
|
+
'messenger',
|
|
425
425
|
'setProvider',
|
|
426
426
|
'provider',
|
|
427
427
|
'ipfsGateway',
|
|
@@ -430,17 +430,17 @@ _AssetsContractController_provider = new WeakMap(), _AssetsContractController_ip
|
|
|
430
430
|
getKnownPropertyNames(Object.getPrototypeOf(this)).forEach((method) => {
|
|
431
431
|
if (((key) => !methodsExcludedFromMessenger.find((e) => e === key) &&
|
|
432
432
|
typeof this[key] === 'function')(method)) {
|
|
433
|
-
this.
|
|
433
|
+
this.messenger.registerActionHandler(`${name}:${method}`,
|
|
434
434
|
// TODO: Write a generic for-loop implementation that iterates over an input union type in tandem with the input array.
|
|
435
435
|
// @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
|
|
436
436
|
this[method].bind(this));
|
|
437
437
|
}
|
|
438
438
|
});
|
|
439
439
|
}, _AssetsContractController_registerEventSubscriptions = function _AssetsContractController_registerEventSubscriptions() {
|
|
440
|
-
this.
|
|
440
|
+
this.messenger.subscribe(`PreferencesController:stateChange`, ({ ipfsGateway }) => {
|
|
441
441
|
__classPrivateFieldSet(this, _AssetsContractController_ipfsGateway, ipfsGateway, "f");
|
|
442
442
|
});
|
|
443
|
-
this.
|
|
443
|
+
this.messenger.subscribe(`NetworkController:networkDidChange`, ({ selectedNetworkClientId }) => {
|
|
444
444
|
const chainId = __classPrivateFieldGet(this, _AssetsContractController_instances, "m", _AssetsContractController_getCorrectChainId).call(this, selectedNetworkClientId);
|
|
445
445
|
if (__classPrivateFieldGet(this, _AssetsContractController_chainId, "f") !== chainId) {
|
|
446
446
|
__classPrivateFieldSet(this, _AssetsContractController_chainId, chainId, "f");
|
|
@@ -450,8 +450,8 @@ _AssetsContractController_provider = new WeakMap(), _AssetsContractController_ip
|
|
|
450
450
|
});
|
|
451
451
|
}, _AssetsContractController_getCorrectProvider = function _AssetsContractController_getCorrectProvider(networkClientId) {
|
|
452
452
|
const provider = networkClientId
|
|
453
|
-
? this.
|
|
454
|
-
: (this.
|
|
453
|
+
? this.messenger.call(`NetworkController:getNetworkClientById`, networkClientId).provider
|
|
454
|
+
: (this.messenger.call('NetworkController:getSelectedNetworkClient')
|
|
455
455
|
?.provider ?? __classPrivateFieldGet(this, _AssetsContractController_provider, "f"));
|
|
456
456
|
if (provider === undefined) {
|
|
457
457
|
throw new Error(MISSING_PROVIDER_ERROR);
|
|
@@ -459,13 +459,13 @@ _AssetsContractController_provider = new WeakMap(), _AssetsContractController_ip
|
|
|
459
459
|
return new Web3Provider(provider);
|
|
460
460
|
}, _AssetsContractController_getCorrectChainId = function _AssetsContractController_getCorrectChainId(networkClientId) {
|
|
461
461
|
if (networkClientId) {
|
|
462
|
-
const networkClientConfiguration = this.
|
|
462
|
+
const networkClientConfiguration = this.messenger.call('NetworkController:getNetworkConfigurationByNetworkClientId', networkClientId);
|
|
463
463
|
if (networkClientConfiguration) {
|
|
464
464
|
return networkClientConfiguration.chainId;
|
|
465
465
|
}
|
|
466
466
|
}
|
|
467
|
-
const { selectedNetworkClientId } = this.
|
|
468
|
-
const networkClient = this.
|
|
467
|
+
const { selectedNetworkClientId } = this.messenger.call('NetworkController:getState');
|
|
468
|
+
const networkClient = this.messenger.call('NetworkController:getNetworkClientById', selectedNetworkClientId);
|
|
469
469
|
return networkClient.configuration?.chainId ?? __classPrivateFieldGet(this, _AssetsContractController_chainId, "f");
|
|
470
470
|
};
|
|
471
471
|
export default AssetsContractController;
|
|
@@ -1 +1 @@
|
|
|
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,4CAA4C;IAC9C,CAAC,+BAA+B,CAAC,aAAa,CAAC,EAC7C,4CAA4C;IAC9C,CAAC,+BAA+B,CAAC,QAAQ,CAAC,EACxC,4CAA4C;IAC9C,CAAC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AI,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 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"]}
|
|
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;AACxD,OAAO,EAAE,wBAAwB,EAAE,mCAAmC;AAYtE,OAAO,EAAE,qBAAqB,EAAY,wBAAwB;AAElE,OAAO,8BAA6B,wCAAwC;;AAE5E,OAAO,E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C,SAAS,CAAC,IAAI,CACvC,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 { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';\nimport type { Messenger, ActionConstraint } from '@metamask/messenger';\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 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 = Messenger<\n typeof name,\n AssetsContractControllerActions | AllowedActions,\n AssetsContractControllerEvents | AllowedEvents\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 messenger: 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.messenger = 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 'messenger',\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.messenger.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.messenger.subscribe(\n `PreferencesController:stateChange`,\n ({ ipfsGateway }) => {\n this.#ipfsGateway = ipfsGateway;\n },\n );\n\n this.messenger.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.messenger.call(\n `NetworkController:getNetworkClientById`,\n networkClientId,\n ).provider\n : (this.messenger.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.messenger.call(\n 'NetworkController:getNetworkConfigurationByNetworkClientId',\n networkClientId,\n );\n if (networkClientConfiguration) {\n return networkClientConfiguration.chainId;\n }\n }\n const { selectedNetworkClientId } = this.messenger.call(\n 'NetworkController:getState',\n );\n const networkClient = this.messenger.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"]}
|
|
@@ -10,13 +10,13 @@ const metadata = {
|
|
|
10
10
|
currentCurrency: {
|
|
11
11
|
includeInStateLogs: true,
|
|
12
12
|
persist: true,
|
|
13
|
-
|
|
13
|
+
includeInDebugSnapshot: true,
|
|
14
14
|
usedInUi: true,
|
|
15
15
|
},
|
|
16
16
|
currencyRates: {
|
|
17
17
|
includeInStateLogs: true,
|
|
18
18
|
persist: true,
|
|
19
|
-
|
|
19
|
+
includeInDebugSnapshot: true,
|
|
20
20
|
usedInUi: true,
|
|
21
21
|
},
|
|
22
22
|
};
|
|
@@ -41,7 +41,7 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
|
|
|
41
41
|
* @param options - Constructor options.
|
|
42
42
|
* @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
|
|
43
43
|
* @param options.interval - The polling interval, in milliseconds.
|
|
44
|
-
* @param options.messenger - A reference to the
|
|
44
|
+
* @param options.messenger - A reference to the messenger.
|
|
45
45
|
* @param options.state - Initial state to set on this controller.
|
|
46
46
|
* @param options.useExternalServices - Feature Switch for using external services (default: true)
|
|
47
47
|
* @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
|
|
@@ -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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ent":["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: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\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"]}
|
|
1
|
+
{"version":3,"file":"CurrencyRateController.cjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;AAKA,iEAGoC;AAGpC,qEAA+E;AAC/E,6CAAoC;AAEpC,+EAAmG;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAwBtC,MAAM,QAAQ,GAAqC;IACjD,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,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,oDAA+B,GAI1E;IASC;;;;;;;;;;OAUG;IACH,YAAY,EACV,cAAc,GAAG,KAAK,EACtB,QAAQ,GAAG,MAAM,EACjB,mBAAmB,GAAG,GAAG,EAAE,CAAC,IAAI,EAChC,SAAS,EACT,KAAK,EACL,sBAAsB,GAAG,+CAA6B,GAQvD;QACC,KAAK,CAAC;YACJ,IAAI;YACJ,QAAQ;YACR,SAAS;YACT,KAAK,EAAE,EAAE,GAAG,YAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;QAvCY,UAAK,GAAG,IAAI,mBAAK,EAAE,CA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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 ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\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\nexport type CurrencyRateMessenger = Messenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents\n>;\n\nconst metadata: StateMetadata<CurrencyRateState> = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\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 messenger.\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"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
2
|
+
import type { Messenger } from "@metamask/messenger";
|
|
2
3
|
import type { NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
|
|
3
4
|
import { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from "./crypto-compare-service/index.cjs";
|
|
4
5
|
/**
|
|
@@ -23,7 +24,7 @@ export type CurrencyRateControllerEvents = CurrencyRateStateChange;
|
|
|
23
24
|
export type GetCurrencyRateState = ControllerGetStateAction<typeof name, CurrencyRateState>;
|
|
24
25
|
export type CurrencyRateControllerActions = GetCurrencyRateState;
|
|
25
26
|
type AllowedActions = NetworkControllerGetNetworkClientByIdAction;
|
|
26
|
-
type CurrencyRateMessenger =
|
|
27
|
+
export type CurrencyRateMessenger = Messenger<typeof name, CurrencyRateControllerActions | AllowedActions, CurrencyRateControllerEvents>;
|
|
27
28
|
/** The input to start polling for the {@link CurrencyRateController} */
|
|
28
29
|
type CurrencyRatePollingInput = {
|
|
29
30
|
nativeCurrencies: string[];
|
|
@@ -58,7 +59,7 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
|
|
|
58
59
|
* @param options - Constructor options.
|
|
59
60
|
* @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
|
|
60
61
|
* @param options.interval - The polling interval, in milliseconds.
|
|
61
|
-
* @param options.messenger - A reference to the
|
|
62
|
+
* @param options.messenger - A reference to the messenger.
|
|
62
63
|
* @param options.state - Initial state to set on this controller.
|
|
63
64
|
* @param options.useExternalServices - Feature Switch for using external services (default: true)
|
|
64
65
|
* @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CurrencyRateController.d.cts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,
|
|
1
|
+
{"version":3,"file":"CurrencyRateController.d.cts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,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,iB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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"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
2
|
+
import type { Messenger } from "@metamask/messenger";
|
|
2
3
|
import type { NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
|
|
3
4
|
import { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from "./crypto-compare-service/index.mjs";
|
|
4
5
|
/**
|
|
@@ -23,7 +24,7 @@ export type CurrencyRateControllerEvents = CurrencyRateStateChange;
|
|
|
23
24
|
export type GetCurrencyRateState = ControllerGetStateAction<typeof name, CurrencyRateState>;
|
|
24
25
|
export type CurrencyRateControllerActions = GetCurrencyRateState;
|
|
25
26
|
type AllowedActions = NetworkControllerGetNetworkClientByIdAction;
|
|
26
|
-
type CurrencyRateMessenger =
|
|
27
|
+
export type CurrencyRateMessenger = Messenger<typeof name, CurrencyRateControllerActions | AllowedActions, CurrencyRateControllerEvents>;
|
|
27
28
|
/** The input to start polling for the {@link CurrencyRateController} */
|
|
28
29
|
type CurrencyRatePollingInput = {
|
|
29
30
|
nativeCurrencies: string[];
|
|
@@ -58,7 +59,7 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
|
|
|
58
59
|
* @param options - Constructor options.
|
|
59
60
|
* @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
|
|
60
61
|
* @param options.interval - The polling interval, in milliseconds.
|
|
61
|
-
* @param options.messenger - A reference to the
|
|
62
|
+
* @param options.messenger - A reference to the messenger.
|
|
62
63
|
* @param options.state - Initial state to set on this controller.
|
|
63
64
|
* @param options.useExternalServices - Feature Switch for using external services (default: true)
|
|
64
65
|
* @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CurrencyRateController.d.mts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,
|
|
1
|
+
{"version":3,"file":"CurrencyRateController.d.mts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,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,MAAM,MAAM,qBAAqB,GAAG,SAAS,CAC3C,OAAO,IAAI,EACX,6BAA6B,GAAG,cAA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true,
|
|
10
|
-
|
|
10
|
+
includeInDebugSnapshot: true,
|
|
11
11
|
usedInUi: true,
|
|
12
12
|
},
|
|
13
13
|
currencyRates: {
|
|
14
14
|
includeInStateLogs: true,
|
|
15
15
|
persist: true,
|
|
16
|
-
|
|
16
|
+
includeInDebugSnapshot: true,
|
|
17
17
|
usedInUi: true,
|
|
18
18
|
},
|
|
19
19
|
};
|
|
@@ -38,7 +38,7 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
|
|
|
38
38
|
* @param options - Constructor options.
|
|
39
39
|
* @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
|
|
40
40
|
* @param options.interval - The polling interval, in milliseconds.
|
|
41
|
-
* @param options.messenger - A reference to the
|
|
41
|
+
* @param options.messenger - A reference to the messenger.
|
|
42
42
|
* @param options.state - Initial state to set on this controller.
|
|
43
43
|
* @param options.useExternalServices - Feature Switch for using external services (default: true)
|
|
44
44
|
* @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
|
|
@@ -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;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAA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AG;oBACpB,cAAc,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI;oBAC7D,cAAc,EAAE,IAAI,EAAE,CAAC,eAAe,CAAC,WAAW,EAAE,CAAC,IAAI,IAAI;oBAC7D,iBAAiB,EAAE,IAAI,EAAE,GAAG,IAAI,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;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: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\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"]}
|
|
1
|
+
{"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACt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;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 ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\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\nexport type CurrencyRateMessenger = Messenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents\n>;\n\nconst metadata: StateMetadata<CurrencyRateState> = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\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 messenger.\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"]}
|
|
@@ -25,13 +25,13 @@ const controllerMetadata = {
|
|
|
25
25
|
allDeFiPositions: {
|
|
26
26
|
includeInStateLogs: false,
|
|
27
27
|
persist: false,
|
|
28
|
-
|
|
28
|
+
includeInDebugSnapshot: false,
|
|
29
29
|
usedInUi: true,
|
|
30
30
|
},
|
|
31
31
|
allDeFiPositionsCount: {
|
|
32
32
|
includeInStateLogs: false,
|
|
33
33
|
persist: false,
|
|
34
|
-
|
|
34
|
+
includeInDebugSnapshot: false,
|
|
35
35
|
usedInUi: false,
|
|
36
36
|
},
|
|
37
37
|
};
|
|
@@ -68,19 +68,19 @@ class DeFiPositionsController extends (0, polling_controller_1.StaticIntervalPol
|
|
|
68
68
|
this.setIntervalLength(TEN_MINUTES_IN_MS);
|
|
69
69
|
__classPrivateFieldSet(this, _DeFiPositionsController_fetchPositions, (0, fetch_positions_1.buildPositionFetcher)(), "f");
|
|
70
70
|
__classPrivateFieldSet(this, _DeFiPositionsController_isEnabled, isEnabled, "f");
|
|
71
|
-
this.
|
|
71
|
+
this.messenger.subscribe('KeyringController:unlock', () => {
|
|
72
72
|
this.startPolling(null);
|
|
73
73
|
});
|
|
74
|
-
this.
|
|
74
|
+
this.messenger.subscribe('KeyringController:lock', () => {
|
|
75
75
|
this.stopAllPolling();
|
|
76
76
|
});
|
|
77
|
-
this.
|
|
77
|
+
this.messenger.subscribe('TransactionController:transactionConfirmed', async (transactionMeta) => {
|
|
78
78
|
if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this)) {
|
|
79
79
|
return;
|
|
80
80
|
}
|
|
81
81
|
await __classPrivateFieldGet(this, _DeFiPositionsController_instances, "m", _DeFiPositionsController_updateAccountPositions).call(this, transactionMeta.txParams.from);
|
|
82
82
|
});
|
|
83
|
-
this.
|
|
83
|
+
this.messenger.subscribe('AccountsController:accountAdded', async (account) => {
|
|
84
84
|
if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this) || !account.type.startsWith('eip155:')) {
|
|
85
85
|
return;
|
|
86
86
|
}
|
|
@@ -92,7 +92,7 @@ class DeFiPositionsController extends (0, polling_controller_1.StaticIntervalPol
|
|
|
92
92
|
if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this)) {
|
|
93
93
|
return;
|
|
94
94
|
}
|
|
95
|
-
const accounts = this.
|
|
95
|
+
const accounts = this.messenger.call('AccountsController:listAccounts');
|
|
96
96
|
const initialResult = [];
|
|
97
97
|
const results = await (0, assetsUtil_1.reduceInBatchesSerially)({
|
|
98
98
|
initialResult,
|