@metamask-previews/assets-controllers 38.0.0-preview-39802fe2 → 38.0.0-preview-3e4b1340
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/CurrencyRateController.js +2 -2
- package/dist/CurrencyRateController.mjs +1 -1
- package/dist/{chunk-JMZ7KWJS.js → chunk-FJ6O67JX.js} +18 -14
- package/dist/chunk-FJ6O67JX.js.map +1 -0
- package/dist/{chunk-UKXD6WUT.mjs → chunk-YXL5QC2Q.mjs} +18 -14
- package/dist/{chunk-UKXD6WUT.mjs.map → chunk-YXL5QC2Q.mjs.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/CurrencyRateController.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-JMZ7KWJS.js.map +0 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkFJ6O67JXjs = require('./chunk-FJ6O67JX.js');
|
|
5
5
|
require('./chunk-7K6PSEAA.js');
|
|
6
6
|
require('./chunk-GDFLKKDY.js');
|
|
7
7
|
require('./chunk-Z4BLTVTB.js');
|
|
8
8
|
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
exports.CurrencyRateController =
|
|
11
|
+
exports.CurrencyRateController = _chunkFJ6O67JXjs.CurrencyRateController; exports.default = _chunkFJ6O67JXjs.CurrencyRateController_default;
|
|
12
12
|
//# sourceMappingURL=CurrencyRateController.js.map
|
|
@@ -87,6 +87,7 @@ var CurrencyRateController = class extends _pollingcontroller.StaticIntervalPoll
|
|
|
87
87
|
const nativeCurrencyForExchangeRate = Object.values(
|
|
88
88
|
_controllerutils.TESTNET_TICKER_SYMBOLS
|
|
89
89
|
).includes(nativeCurrency) ? _controllerutils.FALL_BACK_VS_CURRENCY : nativeCurrency;
|
|
90
|
+
let shouldUpdateState = true;
|
|
90
91
|
try {
|
|
91
92
|
if (currentCurrency && nativeCurrency && // if either currency is an empty string we can skip the comparison
|
|
92
93
|
// because it will result in an error from the api and ultimately
|
|
@@ -103,23 +104,26 @@ var CurrencyRateController = class extends _pollingcontroller.StaticIntervalPoll
|
|
|
103
104
|
}
|
|
104
105
|
} catch (error) {
|
|
105
106
|
if (!(error instanceof Error && error.message.includes("market does not exist for this coin pair"))) {
|
|
107
|
+
shouldUpdateState = false;
|
|
106
108
|
throw error;
|
|
107
109
|
}
|
|
108
110
|
} finally {
|
|
109
111
|
try {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
112
|
+
if (shouldUpdateState) {
|
|
113
|
+
this.update(() => {
|
|
114
|
+
return {
|
|
115
|
+
currencyRates: {
|
|
116
|
+
...currencyRates,
|
|
117
|
+
[nativeCurrency]: {
|
|
118
|
+
conversionDate,
|
|
119
|
+
conversionRate,
|
|
120
|
+
usdConversionRate
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
currentCurrency
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
}
|
|
123
127
|
} finally {
|
|
124
128
|
releaseLock();
|
|
125
129
|
}
|
|
@@ -154,4 +158,4 @@ var CurrencyRateController_default = CurrencyRateController;
|
|
|
154
158
|
|
|
155
159
|
|
|
156
160
|
exports.CurrencyRateController = CurrencyRateController; exports.CurrencyRateController_default = CurrencyRateController_default;
|
|
157
|
-
//# sourceMappingURL=chunk-
|
|
161
|
+
//# sourceMappingURL=chunk-FJ6O67JX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/CurrencyRateController.ts"],"names":["fetchExchangeRate"],"mappings":";;;;;AAKA;AAAA,EACE;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cAAc,cAAc,MAAM;AAAA,EAClE;AACF;AAEA,IAAO,iCAAQ","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 {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n} 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/**\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<\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 networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n await this.updateExchangeRate(networkClient.configuration.ticker);\n }\n}\n\nexport default CurrencyRateController;\n"]}
|
|
@@ -87,6 +87,7 @@ var CurrencyRateController = class extends StaticIntervalPollingController {
|
|
|
87
87
|
const nativeCurrencyForExchangeRate = Object.values(
|
|
88
88
|
TESTNET_TICKER_SYMBOLS
|
|
89
89
|
).includes(nativeCurrency) ? FALL_BACK_VS_CURRENCY : nativeCurrency;
|
|
90
|
+
let shouldUpdateState = true;
|
|
90
91
|
try {
|
|
91
92
|
if (currentCurrency && nativeCurrency && // if either currency is an empty string we can skip the comparison
|
|
92
93
|
// because it will result in an error from the api and ultimately
|
|
@@ -103,23 +104,26 @@ var CurrencyRateController = class extends StaticIntervalPollingController {
|
|
|
103
104
|
}
|
|
104
105
|
} catch (error) {
|
|
105
106
|
if (!(error instanceof Error && error.message.includes("market does not exist for this coin pair"))) {
|
|
107
|
+
shouldUpdateState = false;
|
|
106
108
|
throw error;
|
|
107
109
|
}
|
|
108
110
|
} finally {
|
|
109
111
|
try {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
112
|
+
if (shouldUpdateState) {
|
|
113
|
+
this.update(() => {
|
|
114
|
+
return {
|
|
115
|
+
currencyRates: {
|
|
116
|
+
...currencyRates,
|
|
117
|
+
[nativeCurrency]: {
|
|
118
|
+
conversionDate,
|
|
119
|
+
conversionRate,
|
|
120
|
+
usdConversionRate
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
currentCurrency
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
}
|
|
123
127
|
} finally {
|
|
124
128
|
releaseLock();
|
|
125
129
|
}
|
|
@@ -154,4 +158,4 @@ export {
|
|
|
154
158
|
CurrencyRateController,
|
|
155
159
|
CurrencyRateController_default
|
|
156
160
|
};
|
|
157
|
-
//# sourceMappingURL=chunk-
|
|
161
|
+
//# sourceMappingURL=chunk-YXL5QC2Q.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/CurrencyRateController.ts"],"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 {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n} 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/**\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<\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 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 throw error;\n }\n } finally {\n try {\n this.update(() => {\n
|
|
1
|
+
{"version":3,"sources":["../src/CurrencyRateController.ts"],"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 {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n} 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/**\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<\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 networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n await this.updateExchangeRate(networkClient.configuration.ticker);\n }\n}\n\nexport default CurrencyRateController;\n"],"mappings":";;;;;AAKA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAKP,SAAS,uCAAuC;AAChD,SAAS,aAAa;AAwBtB,IAAM,OAAO;AA0Bb,IAAM,WAAW;AAAA,EACf,iBAAiB,EAAE,SAAS,MAAM,WAAW,KAAK;AAAA,EAClD,eAAe,EAAE,SAAS,MAAM,WAAW,KAAK;AAClD;AAEA,IAAM,eAAe;AAAA,EACnB,iBAAiB;AAAA,EACjB,eAAe;AAAA,IACb,KAAK;AAAA,MACH,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,IACrB;AAAA,EACF;AACF;AAMO,IAAM,yBAAN,cAAqC,gCAI1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,YAAY;AAAA,IACV,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA,mBAAAA,qBAAoB;AAAA,EACtB,GAMG;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA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AM;AAAA,MACR;AAAA,IACF,UAAE;AACA,UAAI;AACF,YAAI,mBAAmB;AACrB,eAAK,OAAO,MAAM;AAChB,mBAAO;AAAA,cACL,eAAe;AAAA,gBACb,GAAG;AAAA,gBACH,CAAC,cAAc,GAAG;AAAA,kBAChB;AAAA,kBACA;AAAA,kBACA;AAAA,gBACF;AAAA,cACF;AAAA,cACA;AAAA,YACF;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,UAAE;AACA,oBAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOS,UAAU;AACjB,UAAM,QAAQ;AACd,SAAK,eAAe;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,aAAa,iBAAiD;AAClE,UAAM,gBAAgB,KAAK,gBAAgB;AAAA,MACzC;AAAA,MACA;AAAA,IACF;AACA,UAAM,KAAK,mBAAmB,cAAc,cAAc,MAAM;AAAA,EAClE;AACF;AAEA,IAAO,iCAAQ;","names":["fetchExchangeRate"]}
|
package/dist/index.js
CHANGED
|
@@ -27,7 +27,7 @@ require('./chunk-JCR4H6YL.js');
|
|
|
27
27
|
require('./chunk-5QLC2MHV.js');
|
|
28
28
|
|
|
29
29
|
|
|
30
|
-
var
|
|
30
|
+
var _chunkFJ6O67JXjs = require('./chunk-FJ6O67JX.js');
|
|
31
31
|
require('./chunk-7K6PSEAA.js');
|
|
32
32
|
require('./chunk-GDFLKKDY.js');
|
|
33
33
|
|
|
@@ -77,5 +77,5 @@ require('./chunk-Z4BLTVTB.js');
|
|
|
77
77
|
|
|
78
78
|
|
|
79
79
|
|
|
80
|
-
exports.AccountTrackerController = _chunkHVOIBGYNjs.AccountTrackerController; exports.AssetsContractController = _chunkLKVWPNXYjs.AssetsContractController; exports.CodefiTokenPricesServiceV2 = _chunkV6DNVRODjs.CodefiTokenPricesServiceV2; exports.Cryptocurrency = _chunkTIFLP53Rjs.Cryptocurrency; exports.CurrencyRateController =
|
|
80
|
+
exports.AccountTrackerController = _chunkHVOIBGYNjs.AccountTrackerController; exports.AssetsContractController = _chunkLKVWPNXYjs.AssetsContractController; exports.CodefiTokenPricesServiceV2 = _chunkV6DNVRODjs.CodefiTokenPricesServiceV2; exports.Cryptocurrency = _chunkTIFLP53Rjs.Cryptocurrency; exports.CurrencyRateController = _chunkFJ6O67JXjs.CurrencyRateController; exports.NftController = _chunk2TZK6YZAjs.NftController; exports.NftDetectionController = _chunkBBCZM5P4js.NftDetectionController; exports.RatesController = _chunkTIFLP53Rjs.RatesController; exports.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID = _chunkLKVWPNXYjs.SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID; exports.SUPPORTED_CHAIN_IDS = _chunkV6DNVRODjs.SUPPORTED_CHAIN_IDS; exports.TokenBalancesController = _chunkYGGUAMHVjs.TokenBalancesController; exports.TokenDetectionController = _chunk3LPQTUGGjs.TokenDetectionController; exports.TokenListController = _chunkZAR4BIOCjs.TokenListController; exports.TokenRatesController = _chunkK7WZALCYjs.TokenRatesController; exports.TokensController = _chunkNDUMUEE6js.TokensController; exports.fetchTokenContractExchangeRates = _chunkMZI3SDQNjs.fetchTokenContractExchangeRates; exports.formatIconUrlWithProxy = _chunkMZI3SDQNjs.formatIconUrlWithProxy; exports.getDefaultNftControllerState = _chunk2TZK6YZAjs.getDefaultNftControllerState; exports.getDefaultTokenRatesControllerState = _chunkK7WZALCYjs.getDefaultTokenRatesControllerState; exports.getFormattedIpfsUrl = _chunkMZI3SDQNjs.getFormattedIpfsUrl; exports.isTokenDetectionSupportedForNetwork = _chunkMZI3SDQNjs.isTokenDetectionSupportedForNetwork;
|
|
81
81
|
//# sourceMappingURL=index.js.map
|
package/dist/index.mjs
CHANGED