@metamask/assets-controllers 40.0.0 → 41.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 +14 -1
- package/dist/AccountTrackerController.d.cts +4 -4
- package/dist/AccountTrackerController.d.mts +4 -4
- package/dist/CurrencyRateController.cjs +40 -58
- package/dist/CurrencyRateController.cjs.map +1 -1
- package/dist/CurrencyRateController.d.cts +15 -15
- package/dist/CurrencyRateController.d.cts.map +1 -1
- package/dist/CurrencyRateController.d.mts +15 -15
- package/dist/CurrencyRateController.d.mts.map +1 -1
- package/dist/CurrencyRateController.mjs +41 -59
- package/dist/CurrencyRateController.mjs.map +1 -1
- package/dist/RatesController/RatesController.cjs +1 -1
- package/dist/RatesController/RatesController.cjs.map +1 -1
- package/dist/RatesController/RatesController.mjs +1 -1
- package/dist/RatesController/RatesController.mjs.map +1 -1
- package/dist/RatesController/types.cjs.map +1 -1
- package/dist/RatesController/types.d.cts +6 -7
- package/dist/RatesController/types.d.cts.map +1 -1
- package/dist/RatesController/types.d.mts +6 -7
- package/dist/RatesController/types.d.mts.map +1 -1
- package/dist/RatesController/types.mjs.map +1 -1
- package/dist/TokenDetectionController.cjs +53 -14
- package/dist/TokenDetectionController.cjs.map +1 -1
- package/dist/TokenDetectionController.d.cts +4 -4
- package/dist/TokenDetectionController.d.cts.map +1 -1
- package/dist/TokenDetectionController.d.mts +4 -4
- package/dist/TokenDetectionController.d.mts.map +1 -1
- package/dist/TokenDetectionController.mjs +54 -14
- package/dist/TokenDetectionController.mjs.map +1 -1
- package/dist/TokenListController.cjs.map +1 -1
- package/dist/TokenListController.d.cts +5 -5
- package/dist/TokenListController.d.cts.map +1 -1
- package/dist/TokenListController.d.mts +5 -5
- package/dist/TokenListController.d.mts.map +1 -1
- package/dist/TokenListController.mjs.map +1 -1
- package/dist/TokenRatesController.d.cts +4 -4
- package/dist/TokenRatesController.d.mts +4 -4
- package/dist/crypto-compare-service/crypto-compare.cjs +8 -6
- package/dist/crypto-compare-service/crypto-compare.cjs.map +1 -1
- package/dist/crypto-compare-service/crypto-compare.d.cts +1 -1
- package/dist/crypto-compare-service/crypto-compare.d.cts.map +1 -1
- package/dist/crypto-compare-service/crypto-compare.d.mts +1 -1
- package/dist/crypto-compare-service/crypto-compare.d.mts.map +1 -1
- package/dist/crypto-compare-service/crypto-compare.mjs +8 -6
- package/dist/crypto-compare-service/crypto-compare.mjs.map +1 -1
- package/package.json +9 -9
|
@@ -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,iBAAiB,IAAI,wBAAwB,EAAE,2CAAiC;AAsBzF,MAAM,IAAI,GAAG,wBAAwB,CAAC;AA0BtC,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACnD,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CAClD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAAG,EAAE;YACH,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;YACjB,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAOF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,+BAA+B,EAI1E;IAOC;;;;;;;;;OASG;IACH,YAAY,EACV,cAAc,GAAG,KAAK,EACtB,QAAQ,GAAG,MAAM,EACjB,SAAS,EACT,KAAK,EACL,iBAAiB,GAAG,wBAAwB,GAO7C;QACC,KAAK,CAAC;YACJ,IAA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;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,cAAc,GACW;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC;IAChD,CAAC;CACF;AAED,eAAe,sBAAsB,CAAC","sourcesContent":["import type {\n RestrictedControllerMessenger,\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 { fetchExchangeRate as defaultFetchExchangeRate } 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 = RestrictedControllerMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrency: 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 fetchExchangeRate;\n\n private readonly includeUsdRate;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n messenger,\n state,\n fetchExchangeRate = defaultFetchExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n fetchExchangeRate?: typeof defaultFetchExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.setIntervalLength(interval);\n this.fetchExchangeRate = fetchExchangeRate;\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-misused-promises\n nativeCurrencies.forEach(this.updateExchangeRate.bind(this));\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pair.\n *\n * @param nativeCurrency - The ticker symbol for the chain.\n */\n async updateExchangeRate(nativeCurrency: string): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n const { currentCurrency, currencyRates } = this.state;\n\n let conversionDate: number | null = null;\n let conversionRate: number | null = null;\n let usdConversionRate: number | null = null;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n const nativeCurrencyForExchangeRate = Object.values(\n TESTNET_TICKER_SYMBOLS,\n ).includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY // ETH\n : nativeCurrency;\n\n let shouldUpdateState = true;\n try {\n if (\n currentCurrency &&\n nativeCurrency &&\n // if either currency is an empty string we can skip the comparison\n // because it will result in an error from the api and ultimately\n // a null conversionRate either way.\n currentCurrency !== '' &&\n nativeCurrency !== ''\n ) {\n const fetchExchangeRateResponse = await this.fetchExchangeRate(\n currentCurrency,\n nativeCurrencyForExchangeRate,\n this.includeUsdRate,\n );\n conversionRate = fetchExchangeRateResponse.conversionRate;\n usdConversionRate = fetchExchangeRateResponse.usdConversionRate;\n conversionDate = Date.now() / 1000;\n }\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n error.message.includes('market does not exist for this coin pair')\n )\n ) {\n // Don't update state on transient / unexpected errors\n shouldUpdateState = false;\n throw error;\n }\n } finally {\n try {\n if (shouldUpdateState) {\n this.update(() => {\n return {\n currencyRates: {\n ...currencyRates,\n [nativeCurrency]: {\n conversionDate,\n conversionRate,\n usdConversionRate,\n },\n },\n currentCurrency,\n };\n });\n }\n } finally {\n releaseLock();\n }\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.nativeCurrency - The native currency symbol to poll prices for.\n */\n async _executePoll({\n nativeCurrency,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrency);\n }\n}\n\nexport default CurrencyRateController;\n"]}
|
|
1
|
+
{"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,mCAAmC;AAEpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AA0BtC,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACnD,aAAa,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CAClD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAAG,EAAE;YACH,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;YACjB,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAOF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,+BAA+B,EAI1E;IAOC;;;;;;;;;OASG;IACH,YAAY,EACV,cAAc,GAAG,KAAK,EACtB,QAAQ,GAAG,MAAM,EACjB,SAAS,EACT,KAAK,EACL,sBAAsB,GAAG,6BAA6B,GAOvD;QACC,KAAK,CAAC;YACJ,IAAI;YACJ,QAAQ;YACR,SAAS;YACT,KAAK,EAAE,EAAE,GAAG,YAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;QAlCY,UAAK,GAAG,IAAI,KAAK,EAAE,CAAC;QAmCnC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC;QAC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D,CAAC;CACF;AAED,eAAe,sBAAsB,CAAC","sourcesContent":["import type {\n RestrictedControllerMessenger,\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 = RestrictedControllerMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(nativeCurrencies: string[]): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RatesController.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c,EAAE,IAAI,CAAC,GAAG,EAAE;gBAC1B,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC;gBACpC,GAAG,CAAC,uBAAA,IAAI,uCAAgB,IAAI,EAAE,iBAAiB,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;aAC/D,CAAC;SACH;QAED,IAAI,CAAC,MAAM,CACT,CAAC,KAAkC,EAAwB,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: '0',\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, string>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RatesController.cjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAA2D;AAC3D,6CAAoC;AAGpC,gFAA+F;AAQlF,QAAA,IAAI,GAAG,iBAAiB,CAAC;AAEtC,IAAY,cAEX;AAFD,WAAY,cAAc;IACxB,6BAAW,CAAA;AACb,CAAC,EAFW,cAAc,8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B,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, number>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RatesController.mjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AAQ/F,MAAM,CAAC,MAAM,IAAI,GAAG,iBAAiB,CAAC;AAEtC,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACxB,6BAAW,CAAA;AACb,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB;AAED,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,QAAQ,GAAG;IACf,YAAY,EAAE,EAAE,O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","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: '0',\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, string>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RatesController.mjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AAQ/F,MAAM,CAAC,MAAM,IAAI,GAAG,iBAAiB,CAAC;AAEtC,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACxB,6BAAW,CAAA;AACb,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB;AAED,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,QAAQ,GAAG;IACf,YAAY,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IAChD,KAAK,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACzC,gBAAgB,EAAE,EAAE,OAAO,EA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A,IAAI,8BAAO,CAAC,OAAO,EAAE,CAAC;IAChD,IAAI;QACF,OAAO,QAAQ,EAAE,CAAC;KACnB;YAAS;QACR,WAAW,EAAE,CAAC;KACf;AACH,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,gEAAa,MAAjB,IAAI,CAAe,CAAC;AAC5B,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,6DAAU,MAAd,IAAI,EAAW,KAAK,IAAI,EAAE;QAC9B,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QACtD,MAAM,QAAQ,GAGV,MAAM,uBAAA,IAAI,+CAAwB,MAA5B,IAAI,EACZ,YAAY,EACZ,gBAAgB,EAChB,uBAAA,IAAI,uCAAgB,CACrB,CAAC;QAEF,MAAM,YAAY,GAAoB,EAAE,CAAC;QACzC,KAAK,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC/D,YAAY,CAAC,cAAc,CAAC,GAAG;gBAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;gBAC1B,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC;gBACpC,GAAG,CAAC,uBAAA,IAAI,uCAAgB,IAAI,EAAE,iBAAiB,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;aAC/D,CAAC;SACH;QAED,IAAI,CAAC,MAAM,CACT,CAAC,KAAkC,EAAwB,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, number>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a
|
|
1
|
+
{"version":3,"file":"types.cjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a number that maps a cryptocurrency code (e.g., \"BTC\") to its\n * conversion rate.\n * The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the\n * conversion rate to USD is not available.\n * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.\n */\nexport type Rate = {\n conversionRate: number;\n conversionDate: number;\n usdConversionRate?: number;\n};\n\n/**\n * Represents the conversion rates for multiple cryptocurrencies.\n * Each key is a string representing the cryptocurrency symbol (e.g., \"BTC\", \"SOL\"),\n * and its value is a `Rate` object containing conversion rates from that cryptocurrency\n * to a fiat currencies and an optional USD rate.\n */\nexport type ConversionRates = Record<string, Rate>;\n\n/**\n * Represents the state structure for the RatesController.\n */\nexport type RatesControllerState = {\n /**\n * The fiat currency in which conversion rates are expressed\n * (i.e., the \"to\" currency).\n */\n fiatCurrency: string;\n /**\n * The conversion rates for multiple cryptocurrencies.\n */\n rates: ConversionRates;\n /**\n * A list of supported cryptocurrency symbols.\n * (i.e., the \"from\" currencies).\n */\n cryptocurrencies: Cryptocurrency[];\n};\n\n/**\n * Type definition for RatesController state change events.\n */\nexport type RatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Type definition for the RatesController polling started event.\n */\nexport type RatesControllerPollingStartedEvent = {\n type: `${typeof ratesControllerName}:pollingStarted`;\n payload: [];\n};\n\n/**\n * Type definition for the RatesController polling stopped event.\n */\nexport type RatesControllerPollingStoppedEvent = {\n type: `${typeof ratesControllerName}:pollingStopped`;\n payload: [];\n};\n\n/**\n * Defines the events that the RatesController can emit.\n */\nexport type RatesControllerEvents =\n | RatesControllerStateChangeEvent\n | RatesControllerPollingStartedEvent\n | RatesControllerPollingStoppedEvent;\n\nexport type RatesControllerGetStateAction = ControllerGetStateAction<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Defines the actions that can be performed to get the state of the RatesController.\n */\nexport type RatesControllerActions = RatesControllerGetStateAction;\n\n/**\n * Defines the actions that the RatesController can perform.\n */\nexport type RatesControllerMessenger = RestrictedControllerMessenger<\n typeof ratesControllerName,\n RatesControllerActions,\n RatesControllerEvents,\n never,\n never\n>;\n\n/**\n * The options required to initialize a RatesController.\n */\nexport type RatesControllerOptions = {\n /**\n * Whether to include USD rates in the conversion rates.\n */\n includeUsdRate: boolean;\n /**\n * The polling interval in milliseconds.\n */\n interval?: number;\n /**\n * The messenger instance for communication.\n */\n messenger: RatesControllerMessenger;\n /**\n * The initial state of the controller.\n */\n state?: Partial<RatesControllerState>;\n /**\n * The function to fetch exchange rates.\n */\n fetchMultiExchangeRate?: typeof defaultFetchExchangeRate;\n};\n"]}
|
|
@@ -3,17 +3,16 @@ import type { fetchMultiExchangeRate as defaultFetchExchangeRate } from "../cryp
|
|
|
3
3
|
import type { name as ratesControllerName, Cryptocurrency } from "./RatesController.cjs";
|
|
4
4
|
/**
|
|
5
5
|
* Represents the conversion rates from one currency to others, including the conversion date.
|
|
6
|
-
* The `conversionRate` field is a
|
|
7
|
-
* conversion rate.
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* conversion rate to USD is not available. We also use string for the same reason as stated before.
|
|
6
|
+
* The `conversionRate` field is a number that maps a cryptocurrency code (e.g., "BTC") to its
|
|
7
|
+
* conversion rate.
|
|
8
|
+
* The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the
|
|
9
|
+
* conversion rate to USD is not available.
|
|
11
10
|
* The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.
|
|
12
11
|
*/
|
|
13
12
|
export type Rate = {
|
|
14
|
-
conversionRate:
|
|
13
|
+
conversionRate: number;
|
|
15
14
|
conversionDate: number;
|
|
16
|
-
usdConversionRate?:
|
|
15
|
+
usdConversionRate?: number;
|
|
17
16
|
};
|
|
18
17
|
/**
|
|
19
18
|
* Represents the conversion rates for multiple cryptocurrencies.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,sBAAsB,IAAI,wBAA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MAAM,qBAAqB,GAC7B,+BAA+B,GAC/B,kCAAkC,GAClC,kCAAkC,CAAC;AAEvC,MAAM,MAAM,6BAA6B,GAAG,wBAAwB,CAClE,OAAO,mBAAmB,EAC1B,oBAAoB,CACrB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AAEnE;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,6BAA6B,CAClE,OAAO,mBAAmB,EAC1B,sBAAsB,EACtB,qBAAqB,EACrB,KAAK,EACL,KAAK,CACN,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC;;OAEG;IACH,cAAc,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,EAAE,wBAAwB,CAAC;IACpC;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACtC;;OAEG;IACH,sBAAsB,CAAC,EAAE,OAAO,wBAAwB,CAAC;CAC1D,CAAC"}
|
|
@@ -3,17 +3,16 @@ import type { fetchMultiExchangeRate as defaultFetchExchangeRate } from "../cryp
|
|
|
3
3
|
import type { name as ratesControllerName, Cryptocurrency } from "./RatesController.mjs";
|
|
4
4
|
/**
|
|
5
5
|
* Represents the conversion rates from one currency to others, including the conversion date.
|
|
6
|
-
* The `conversionRate` field is a
|
|
7
|
-
* conversion rate.
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* conversion rate to USD is not available. We also use string for the same reason as stated before.
|
|
6
|
+
* The `conversionRate` field is a number that maps a cryptocurrency code (e.g., "BTC") to its
|
|
7
|
+
* conversion rate.
|
|
8
|
+
* The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the
|
|
9
|
+
* conversion rate to USD is not available.
|
|
11
10
|
* The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.
|
|
12
11
|
*/
|
|
13
12
|
export type Rate = {
|
|
14
|
-
conversionRate:
|
|
13
|
+
conversionRate: number;
|
|
15
14
|
conversionDate: number;
|
|
16
|
-
usdConversionRate?:
|
|
15
|
+
usdConversionRate?: number;
|
|
17
16
|
};
|
|
18
17
|
/**
|
|
19
18
|
* Represents the conversion rates for multiple cryptocurrencies.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AACpG,OAAO,KAAK,EACV,IAAI,IAAI,mBAAmB,EAC3B,cAAc,EACf,8BAA0B;AAE3B
|
|
1
|
+
{"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,6BAA6B,EAC7B,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AACpG,OAAO,KAAK,EACV,IAAI,IAAI,mBAAmB,EAC3B,cAAc,EACf,8BAA0B;AAE3B;;;;;;;GAOG;AACH,MAAM,MAAM,IAAI,GAAG;IACjB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEnD;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IACjC;;;OAGG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,KAAK,EAAE,eAAe,CAAC;IACvB;;;OAGG;IACH,gBAAgB,EAAE,cAAc,EAAE,CAAC;CACpC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GAAG,0BAA0B,CACtE,OAAO,mBAAmB,EAC1B,oBAAoB,CACrB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,GAAG,OAAO,mBAAmB,iBAAiB,CAAC;IACrD,OAAO,EAAE,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,GAAG,OAAO,mBAAmB,iBAAiB,CAAC;IACrD,OAAO,EAAE,EAAE,CAAC;CACb,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAC7B,+BAA+B,GAC/B,kCAAkC,GAClC,kCAAkC,CAAC;AAEvC,MAAM,MAAM,6BAA6B,GAAG,wBAAwB,CAClE,OAAO,mBAAmB,EAC1B,oBAAoB,CACrB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG,6BAA6B,CAAC;AAEnE;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,6BAA6B,CAClE,OAAO,mBAAmB,EAC1B,sBAAsB,EACtB,qBAAqB,EACrB,KAAK,EACL,KAAK,CACN,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC;;OAEG;IACH,cAAc,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,SAAS,EAAE,wBAAwB,CAAC;IACpC;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACtC;;OAEG;IACH,sBAAsB,CAAC,EAAE,OAAO,wBAAwB,CAAC;CAC1D,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a
|
|
1
|
+
{"version":3,"file":"types.mjs","sourceRoot":"","sources":["../../src/RatesController/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\n\nimport type { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n name as ratesControllerName,\n Cryptocurrency,\n} from './RatesController';\n\n/**\n * Represents the conversion rates from one currency to others, including the conversion date.\n * The `conversionRate` field is a number that maps a cryptocurrency code (e.g., \"BTC\") to its\n * conversion rate.\n * The `usdConversionRate` provides the conversion rate to USD as a number, or `null` if the\n * conversion rate to USD is not available.\n * The `conversionDate` is a Unix timestamp (number) indicating when the conversion rate was last updated.\n */\nexport type Rate = {\n conversionRate: number;\n conversionDate: number;\n usdConversionRate?: number;\n};\n\n/**\n * Represents the conversion rates for multiple cryptocurrencies.\n * Each key is a string representing the cryptocurrency symbol (e.g., \"BTC\", \"SOL\"),\n * and its value is a `Rate` object containing conversion rates from that cryptocurrency\n * to a fiat currencies and an optional USD rate.\n */\nexport type ConversionRates = Record<string, Rate>;\n\n/**\n * Represents the state structure for the RatesController.\n */\nexport type RatesControllerState = {\n /**\n * The fiat currency in which conversion rates are expressed\n * (i.e., the \"to\" currency).\n */\n fiatCurrency: string;\n /**\n * The conversion rates for multiple cryptocurrencies.\n */\n rates: ConversionRates;\n /**\n * A list of supported cryptocurrency symbols.\n * (i.e., the \"from\" currencies).\n */\n cryptocurrencies: Cryptocurrency[];\n};\n\n/**\n * Type definition for RatesController state change events.\n */\nexport type RatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Type definition for the RatesController polling started event.\n */\nexport type RatesControllerPollingStartedEvent = {\n type: `${typeof ratesControllerName}:pollingStarted`;\n payload: [];\n};\n\n/**\n * Type definition for the RatesController polling stopped event.\n */\nexport type RatesControllerPollingStoppedEvent = {\n type: `${typeof ratesControllerName}:pollingStopped`;\n payload: [];\n};\n\n/**\n * Defines the events that the RatesController can emit.\n */\nexport type RatesControllerEvents =\n | RatesControllerStateChangeEvent\n | RatesControllerPollingStartedEvent\n | RatesControllerPollingStoppedEvent;\n\nexport type RatesControllerGetStateAction = ControllerGetStateAction<\n typeof ratesControllerName,\n RatesControllerState\n>;\n\n/**\n * Defines the actions that can be performed to get the state of the RatesController.\n */\nexport type RatesControllerActions = RatesControllerGetStateAction;\n\n/**\n * Defines the actions that the RatesController can perform.\n */\nexport type RatesControllerMessenger = RestrictedControllerMessenger<\n typeof ratesControllerName,\n RatesControllerActions,\n RatesControllerEvents,\n never,\n never\n>;\n\n/**\n * The options required to initialize a RatesController.\n */\nexport type RatesControllerOptions = {\n /**\n * Whether to include USD rates in the conversion rates.\n */\n includeUsdRate: boolean;\n /**\n * The polling interval in milliseconds.\n */\n interval?: number;\n /**\n * The messenger instance for communication.\n */\n messenger: RatesControllerMessenger;\n /**\n * The initial state of the controller.\n */\n state?: Partial<RatesControllerState>;\n /**\n * The function to fetch exchange rates.\n */\n fetchMultiExchangeRate?: typeof defaultFetchExchangeRate;\n};\n"]}
|
|
@@ -13,13 +13,14 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
13
13
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
14
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
15
|
};
|
|
16
|
-
var _TokenDetectionController_instances, _TokenDetectionController_intervalId, _TokenDetectionController_selectedAccountId, _TokenDetectionController_networkClientId,
|
|
16
|
+
var _TokenDetectionController_instances, _TokenDetectionController_intervalId, _TokenDetectionController_selectedAccountId, _TokenDetectionController_networkClientId, _TokenDetectionController_tokensChainsCache, _TokenDetectionController_disabled, _TokenDetectionController_isUnlocked, _TokenDetectionController_isDetectionEnabledFromPreferences, _TokenDetectionController_isDetectionEnabledForNetwork, _TokenDetectionController_getBalancesInSingleCall, _TokenDetectionController_trackMetaMetricsEvent, _TokenDetectionController_accountsAPI, _TokenDetectionController_registerEventListeners, _TokenDetectionController_stopPolling, _TokenDetectionController_startPolling, _TokenDetectionController_compareTokensChainsCache, _TokenDetectionController_getCorrectChainIdAndNetworkClientId, _TokenDetectionController_restartTokenDetection, _TokenDetectionController_getSlicesOfTokensToDetect, _TokenDetectionController_getConvertedStaticMainnetTokenList, _TokenDetectionController_addDetectedTokensViaAPI, _TokenDetectionController_addDetectedTokens, _TokenDetectionController_getSelectedAccount, _TokenDetectionController_getSelectedAddress;
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.TokenDetectionController = exports.controllerName = exports.STATIC_MAINNET_TOKEN_LIST = void 0;
|
|
19
19
|
const contract_metadata_1 = __importDefault(require("@metamask/contract-metadata"));
|
|
20
20
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
21
21
|
const polling_controller_1 = require("@metamask/polling-controller");
|
|
22
22
|
const utils_1 = require("@metamask/utils");
|
|
23
|
+
const lodash_1 = require("lodash");
|
|
23
24
|
const assetsUtil_1 = require("./assetsUtil.cjs");
|
|
24
25
|
const multi_chain_accounts_service_1 = require("./multi-chain-accounts-service/index.cjs");
|
|
25
26
|
const DEFAULT_INTERVAL = 180000;
|
|
@@ -35,6 +36,19 @@ exports.STATIC_MAINNET_TOKEN_LIST = Object.entries(contract_metadata_1.default).
|
|
|
35
36
|
},
|
|
36
37
|
};
|
|
37
38
|
}, {});
|
|
39
|
+
/**
|
|
40
|
+
* Function that takes a TokensChainsCache object and maps chainId with TokenListMap.
|
|
41
|
+
* @param tokensChainsCache - TokensChainsCache input object
|
|
42
|
+
* @returns returns the map of chainId with TokenListMap
|
|
43
|
+
*/
|
|
44
|
+
function mapChainIdWithTokenListMap(tokensChainsCache) {
|
|
45
|
+
return (0, lodash_1.mapValues)(tokensChainsCache, (value) => {
|
|
46
|
+
if ((0, lodash_1.isObject)(value) && 'data' in value) {
|
|
47
|
+
return (0, lodash_1.get)(value, ['data']);
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
38
52
|
exports.controllerName = 'TokenDetectionController';
|
|
39
53
|
/**
|
|
40
54
|
* Controller that passively polls on a set interval for Tokens auto detection
|
|
@@ -69,7 +83,7 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
|
|
|
69
83
|
_TokenDetectionController_intervalId.set(this, void 0);
|
|
70
84
|
_TokenDetectionController_selectedAccountId.set(this, void 0);
|
|
71
85
|
_TokenDetectionController_networkClientId.set(this, void 0);
|
|
72
|
-
|
|
86
|
+
_TokenDetectionController_tokensChainsCache.set(this, {});
|
|
73
87
|
_TokenDetectionController_disabled.set(this, void 0);
|
|
74
88
|
_TokenDetectionController_isUnlocked.set(this, void 0);
|
|
75
89
|
_TokenDetectionController_isDetectionEnabledFromPreferences.set(this, void 0);
|
|
@@ -113,6 +127,8 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
|
|
|
113
127
|
__classPrivateFieldSet(this, _TokenDetectionController_selectedAccountId, __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getSelectedAccount).call(this).id, "f");
|
|
114
128
|
const { chainId, networkClientId } = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getCorrectChainIdAndNetworkClientId).call(this);
|
|
115
129
|
__classPrivateFieldSet(this, _TokenDetectionController_networkClientId, networkClientId, "f");
|
|
130
|
+
const { tokensChainsCache } = this.messagingSystem.call('TokenListController:getState');
|
|
131
|
+
__classPrivateFieldSet(this, _TokenDetectionController_tokensChainsCache, tokensChainsCache, "f");
|
|
116
132
|
const { useTokenDetection: defaultUseTokenDetection } = this.messagingSystem.call('PreferencesController:getState');
|
|
117
133
|
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, defaultUseTokenDetection, "f");
|
|
118
134
|
__classPrivateFieldSet(this, _TokenDetectionController_isDetectionEnabledForNetwork, (0, assetsUtil_1.isTokenDetectionSupportedForNetwork)(chainId), "f");
|
|
@@ -191,9 +207,9 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
|
|
|
191
207
|
const isTokenDetectionInactiveInMainnet = !__classPrivateFieldGet(this, _TokenDetectionController_isDetectionEnabledFromPreferences, "f") &&
|
|
192
208
|
chainIdAgainstWhichToDetect === controller_utils_1.ChainId.mainnet;
|
|
193
209
|
const { tokensChainsCache } = this.messagingSystem.call('TokenListController:getState');
|
|
194
|
-
__classPrivateFieldSet(this,
|
|
195
|
-
?
|
|
196
|
-
: tokensChainsCache
|
|
210
|
+
__classPrivateFieldSet(this, _TokenDetectionController_tokensChainsCache, isTokenDetectionInactiveInMainnet
|
|
211
|
+
? __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getConvertedStaticMainnetTokenList).call(this)
|
|
212
|
+
: tokensChainsCache ?? {}, "f");
|
|
197
213
|
const tokenCandidateSlices = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_getSlicesOfTokensToDetect).call(this, {
|
|
198
214
|
chainId: chainIdAgainstWhichToDetect,
|
|
199
215
|
selectedAddress: addressAgainstWhichToDetect,
|
|
@@ -218,7 +234,7 @@ class TokenDetectionController extends (0, polling_controller_1.StaticIntervalPo
|
|
|
218
234
|
}
|
|
219
235
|
}
|
|
220
236
|
exports.TokenDetectionController = TokenDetectionController;
|
|
221
|
-
_TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_selectedAccountId = new WeakMap(), _TokenDetectionController_networkClientId = new WeakMap(),
|
|
237
|
+
_TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_selectedAccountId = new WeakMap(), _TokenDetectionController_networkClientId = new WeakMap(), _TokenDetectionController_tokensChainsCache = new WeakMap(), _TokenDetectionController_disabled = new WeakMap(), _TokenDetectionController_isUnlocked = new WeakMap(), _TokenDetectionController_isDetectionEnabledFromPreferences = new WeakMap(), _TokenDetectionController_isDetectionEnabledForNetwork = new WeakMap(), _TokenDetectionController_getBalancesInSingleCall = new WeakMap(), _TokenDetectionController_trackMetaMetricsEvent = new WeakMap(), _TokenDetectionController_accountsAPI = new WeakMap(), _TokenDetectionController_instances = new WeakSet(), _TokenDetectionController_registerEventListeners = function _TokenDetectionController_registerEventListeners() {
|
|
222
238
|
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
223
239
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
224
240
|
this.messagingSystem.subscribe('KeyringController:unlock', async () => {
|
|
@@ -232,9 +248,9 @@ _TokenDetectionController_intervalId = new WeakMap(), _TokenDetectionController_
|
|
|
232
248
|
this.messagingSystem.subscribe('TokenListController:stateChange',
|
|
233
249
|
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
234
250
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
235
|
-
async ({
|
|
236
|
-
const
|
|
237
|
-
if (
|
|
251
|
+
async ({ tokensChainsCache }) => {
|
|
252
|
+
const isEqualValues = __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_compareTokensChainsCache).call(this, tokensChainsCache, __classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f"));
|
|
253
|
+
if (!isEqualValues) {
|
|
238
254
|
await __classPrivateFieldGet(this, _TokenDetectionController_instances, "m", _TokenDetectionController_restartTokenDetection).call(this);
|
|
239
255
|
}
|
|
240
256
|
});
|
|
@@ -296,6 +312,11 @@ async function _TokenDetectionController_startPolling() {
|
|
|
296
312
|
__classPrivateFieldSet(this, _TokenDetectionController_intervalId, setInterval(async () => {
|
|
297
313
|
await this.detectTokens();
|
|
298
314
|
}, this.getIntervalLength()), "f");
|
|
315
|
+
}, _TokenDetectionController_compareTokensChainsCache = function _TokenDetectionController_compareTokensChainsCache(tokensChainsCache, previousTokensChainsCache) {
|
|
316
|
+
const cleanPreviousTokensChainsCache = mapChainIdWithTokenListMap(previousTokensChainsCache);
|
|
317
|
+
const cleanTokensChainsCache = mapChainIdWithTokenListMap(tokensChainsCache);
|
|
318
|
+
const isEqualValues = (0, lodash_1.isEqual)(cleanTokensChainsCache, cleanPreviousTokensChainsCache);
|
|
319
|
+
return isEqualValues;
|
|
299
320
|
}, _TokenDetectionController_getCorrectChainIdAndNetworkClientId = function _TokenDetectionController_getCorrectChainIdAndNetworkClientId(networkClientId) {
|
|
300
321
|
if (networkClientId) {
|
|
301
322
|
const networkConfiguration = this.messagingSystem.call('NetworkController:getNetworkConfigurationByNetworkClientId', networkClientId);
|
|
@@ -335,7 +356,7 @@ async function _TokenDetectionController_restartTokenDetection({ selectedAddress
|
|
|
335
356
|
allIgnoredTokens,
|
|
336
357
|
].map((tokens) => (tokens[chainId]?.[selectedAddress] ?? []).map((value) => typeof value === 'string' ? value : value.address));
|
|
337
358
|
const tokensToDetect = [];
|
|
338
|
-
for (const tokenAddress of Object.keys(__classPrivateFieldGet(this,
|
|
359
|
+
for (const tokenAddress of Object.keys(__classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")?.[chainId]?.data || {})) {
|
|
339
360
|
if ([
|
|
340
361
|
tokensAddresses,
|
|
341
362
|
detectedTokensAddresses,
|
|
@@ -349,6 +370,24 @@ async function _TokenDetectionController_restartTokenDetection({ selectedAddress
|
|
|
349
370
|
slicesOfTokensToDetect.push(tokensToDetect.slice(i, i + size));
|
|
350
371
|
}
|
|
351
372
|
return slicesOfTokensToDetect;
|
|
373
|
+
}, _TokenDetectionController_getConvertedStaticMainnetTokenList = function _TokenDetectionController_getConvertedStaticMainnetTokenList() {
|
|
374
|
+
const data = Object.entries(exports.STATIC_MAINNET_TOKEN_LIST).reduce((acc, [key, value]) => ({
|
|
375
|
+
...acc,
|
|
376
|
+
[key]: {
|
|
377
|
+
name: value.name,
|
|
378
|
+
symbol: value.symbol,
|
|
379
|
+
decimals: value.decimals,
|
|
380
|
+
address: value.address,
|
|
381
|
+
aggregators: [],
|
|
382
|
+
iconUrl: value?.iconUrl,
|
|
383
|
+
},
|
|
384
|
+
}), {});
|
|
385
|
+
return {
|
|
386
|
+
'0x1': {
|
|
387
|
+
data,
|
|
388
|
+
timestamp: 0,
|
|
389
|
+
},
|
|
390
|
+
};
|
|
352
391
|
}, _TokenDetectionController_addDetectedTokensViaAPI =
|
|
353
392
|
/**
|
|
354
393
|
* This adds detected tokens from the Accounts API, avoiding the multi-call RPC calls for balances
|
|
@@ -378,12 +417,12 @@ async function _TokenDetectionController_addDetectedTokensViaAPI({ selectedAddre
|
|
|
378
417
|
if (!tokenCandidateSet.has(token.address)) {
|
|
379
418
|
return;
|
|
380
419
|
}
|
|
381
|
-
// We need specific data from
|
|
420
|
+
// We need specific data from tokensChainsCache to correctly create a token
|
|
382
421
|
// So even if we have a token that was detected correctly by the API, if its missing data we cannot safely add it.
|
|
383
|
-
if (!__classPrivateFieldGet(this,
|
|
422
|
+
if (!__classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")[chainId].data[token.address]) {
|
|
384
423
|
return;
|
|
385
424
|
}
|
|
386
|
-
const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this,
|
|
425
|
+
const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")[chainId].data[token.address];
|
|
387
426
|
eventTokensDetails.push(`${symbol} - ${tokenAddress}`);
|
|
388
427
|
tokensWithBalance.push({
|
|
389
428
|
address: tokenAddress,
|
|
@@ -422,7 +461,7 @@ async function _TokenDetectionController_addDetectedTokensViaAPI({ selectedAddre
|
|
|
422
461
|
const tokensWithBalance = [];
|
|
423
462
|
const eventTokensDetails = [];
|
|
424
463
|
for (const nonZeroTokenAddress of Object.keys(balances)) {
|
|
425
|
-
const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this,
|
|
464
|
+
const { decimals, symbol, aggregators, iconUrl, name } = __classPrivateFieldGet(this, _TokenDetectionController_tokensChainsCache, "f")[chainId].data[nonZeroTokenAddress];
|
|
426
465
|
eventTokensDetails.push(`${symbol} - ${nonZeroTokenAddress}`);
|
|
427
466
|
tokensWithBalance.push({
|
|
428
467
|
address: nonZeroTokenAddress,
|