@metamask-previews/assets-controllers 11.0.1-preview.d32a7cc
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 +235 -0
- package/LICENSE +20 -0
- package/README.md +30 -0
- package/dist/AccountTrackerController.d.ts +106 -0
- package/dist/AccountTrackerController.d.ts.map +1 -0
- package/dist/AccountTrackerController.js +163 -0
- package/dist/AccountTrackerController.js.map +1 -0
- package/dist/AssetsContractController.d.ts +188 -0
- package/dist/AssetsContractController.d.ts.map +1 -0
- package/dist/AssetsContractController.js +330 -0
- package/dist/AssetsContractController.js.map +1 -0
- package/dist/CurrencyRateController.d.ts +101 -0
- package/dist/CurrencyRateController.d.ts.map +1 -0
- package/dist/CurrencyRateController.js +219 -0
- package/dist/CurrencyRateController.js.map +1 -0
- package/dist/NftController.d.ts +464 -0
- package/dist/NftController.d.ts.map +1 -0
- package/dist/NftController.js +924 -0
- package/dist/NftController.js.map +1 -0
- package/dist/NftDetectionController.d.ts +182 -0
- package/dist/NftDetectionController.d.ts.map +1 -0
- package/dist/NftDetectionController.js +188 -0
- package/dist/NftDetectionController.js.map +1 -0
- package/dist/Standards/ERC20Standard.d.ts +50 -0
- package/dist/Standards/ERC20Standard.d.ts.map +1 -0
- package/dist/Standards/ERC20Standard.js +144 -0
- package/dist/Standards/ERC20Standard.js.map +1 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts +79 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +148 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts +89 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +182 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -0
- package/dist/Standards/standards-types.d.ts +15 -0
- package/dist/Standards/standards-types.d.ts.map +1 -0
- package/dist/Standards/standards-types.js +3 -0
- package/dist/Standards/standards-types.js.map +1 -0
- package/dist/TokenBalancesController.d.ts +71 -0
- package/dist/TokenBalancesController.d.ts.map +1 -0
- package/dist/TokenBalancesController.js +94 -0
- package/dist/TokenBalancesController.js.map +1 -0
- package/dist/TokenDetectionController.d.ts +87 -0
- package/dist/TokenDetectionController.d.ts.map +1 -0
- package/dist/TokenDetectionController.js +189 -0
- package/dist/TokenDetectionController.js.map +1 -0
- package/dist/TokenListController.d.ts +117 -0
- package/dist/TokenListController.d.ts.map +1 -0
- package/dist/TokenListController.js +248 -0
- package/dist/TokenListController.js.map +1 -0
- package/dist/TokenRatesController.d.ts +172 -0
- package/dist/TokenRatesController.d.ts.map +1 -0
- package/dist/TokenRatesController.js +327 -0
- package/dist/TokenRatesController.js.map +1 -0
- package/dist/TokensController.d.ts +250 -0
- package/dist/TokensController.d.ts.map +1 -0
- package/dist/TokensController.js +550 -0
- package/dist/TokensController.js.map +1 -0
- package/dist/assetsUtil.d.ts +109 -0
- package/dist/assetsUtil.d.ts.map +1 -0
- package/dist/assetsUtil.js +227 -0
- package/dist/assetsUtil.js.map +1 -0
- package/dist/constants.d.ts +6 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +10 -0
- package/dist/constants.js.map +1 -0
- package/dist/crypto-compare.d.ts +13 -0
- package/dist/crypto-compare.d.ts.map +1 -0
- package/dist/crypto-compare.js +67 -0
- package/dist/crypto-compare.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/token-service.d.ts +31 -0
- package/dist/token-service.d.ts.map +1 -0
- package/dist/token-service.js +134 -0
- package/dist/token-service.js.map +1 -0
- package/package.json +82 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CurrencyRateController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AAU,CAAC,CAAgC;IAEnD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC;IAE/B,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC;IAEnC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC;IAOhC;;;;;;;;;OASG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,SAAS,EACT,KAAK,EACL,iBAA4C,GAC7C,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,iBAAiB,CAAC,EAAE,OAAO,wBAAwB,CAAC;KACrD;IAaD;;OAEG;IACG,KAAK;IAMX;;OAEG;IACH,IAAI;IAMJ;;;;OAIG;IACM,OAAO;IAKhB;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAOhD;;;;OAIG;IACG,iBAAiB,CAAC,MAAM,EAAE,MAAM;IAOtC,OAAO,CAAC,WAAW;IAMnB;;OAEG;YACW,YAAY;IAW1B;;;;OAIG;IACG,kBAAkB,IAAI,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;CA+E9D;AAED,eAAe,sBAAsB,CAAC"}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
12
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
13
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
14
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
15
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
16
|
+
};
|
|
17
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
18
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
19
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
20
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
21
|
+
};
|
|
22
|
+
var _CurrencyRateController_enabled;
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.CurrencyRateController = void 0;
|
|
25
|
+
const base_controller_1 = require("@metamask/base-controller");
|
|
26
|
+
const controller_utils_1 = require("@metamask/controller-utils");
|
|
27
|
+
const async_mutex_1 = require("async-mutex");
|
|
28
|
+
const crypto_compare_1 = require("./crypto-compare");
|
|
29
|
+
const name = 'CurrencyRateController';
|
|
30
|
+
const metadata = {
|
|
31
|
+
conversionDate: { persist: true, anonymous: true },
|
|
32
|
+
conversionRate: { persist: true, anonymous: true },
|
|
33
|
+
currentCurrency: { persist: true, anonymous: true },
|
|
34
|
+
nativeCurrency: { persist: true, anonymous: true },
|
|
35
|
+
pendingCurrentCurrency: { persist: false, anonymous: true },
|
|
36
|
+
pendingNativeCurrency: { persist: false, anonymous: true },
|
|
37
|
+
usdConversionRate: { persist: true, anonymous: true },
|
|
38
|
+
};
|
|
39
|
+
const defaultState = {
|
|
40
|
+
conversionDate: 0,
|
|
41
|
+
conversionRate: 0,
|
|
42
|
+
currentCurrency: 'usd',
|
|
43
|
+
nativeCurrency: 'ETH',
|
|
44
|
+
pendingCurrentCurrency: null,
|
|
45
|
+
pendingNativeCurrency: null,
|
|
46
|
+
usdConversionRate: null,
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Controller that passively polls on a set interval for an exchange rate from the current network
|
|
50
|
+
* asset to the user's preferred currency.
|
|
51
|
+
*/
|
|
52
|
+
class CurrencyRateController extends base_controller_1.BaseControllerV2 {
|
|
53
|
+
/**
|
|
54
|
+
* Creates a CurrencyRateController instance.
|
|
55
|
+
*
|
|
56
|
+
* @param options - Constructor options.
|
|
57
|
+
* @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
|
|
58
|
+
* @param options.interval - The polling interval, in milliseconds.
|
|
59
|
+
* @param options.messenger - A reference to the messaging system.
|
|
60
|
+
* @param options.state - Initial state to set on this controller.
|
|
61
|
+
* @param options.fetchExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
|
|
62
|
+
*/
|
|
63
|
+
constructor({ includeUsdRate = false, interval = 180000, messenger, state, fetchExchangeRate = crypto_compare_1.fetchExchangeRate, }) {
|
|
64
|
+
super({
|
|
65
|
+
name,
|
|
66
|
+
metadata,
|
|
67
|
+
messenger,
|
|
68
|
+
state: Object.assign(Object.assign({}, defaultState), state),
|
|
69
|
+
});
|
|
70
|
+
this.mutex = new async_mutex_1.Mutex();
|
|
71
|
+
/**
|
|
72
|
+
* A boolean that controls whether or not network requests can be made by the controller
|
|
73
|
+
*/
|
|
74
|
+
_CurrencyRateController_enabled.set(this, void 0);
|
|
75
|
+
this.includeUsdRate = includeUsdRate;
|
|
76
|
+
this.intervalDelay = interval;
|
|
77
|
+
this.fetchExchangeRate = fetchExchangeRate;
|
|
78
|
+
__classPrivateFieldSet(this, _CurrencyRateController_enabled, false, "f");
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Start polling for the currency rate.
|
|
82
|
+
*/
|
|
83
|
+
start() {
|
|
84
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
85
|
+
__classPrivateFieldSet(this, _CurrencyRateController_enabled, true, "f");
|
|
86
|
+
yield this.startPolling();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Stop polling for the currency rate.
|
|
91
|
+
*/
|
|
92
|
+
stop() {
|
|
93
|
+
__classPrivateFieldSet(this, _CurrencyRateController_enabled, false, "f");
|
|
94
|
+
this.stopPolling();
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Prepare to discard this controller.
|
|
98
|
+
*
|
|
99
|
+
* This stops any active polling.
|
|
100
|
+
*/
|
|
101
|
+
destroy() {
|
|
102
|
+
super.destroy();
|
|
103
|
+
this.stopPolling();
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Sets a currency to track.
|
|
107
|
+
*
|
|
108
|
+
* @param currentCurrency - ISO 4217 currency code.
|
|
109
|
+
*/
|
|
110
|
+
setCurrentCurrency(currentCurrency) {
|
|
111
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
112
|
+
this.update((state) => {
|
|
113
|
+
state.pendingCurrentCurrency = currentCurrency;
|
|
114
|
+
});
|
|
115
|
+
yield this.updateExchangeRate();
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Sets a new native currency.
|
|
120
|
+
*
|
|
121
|
+
* @param symbol - Symbol for the base asset.
|
|
122
|
+
*/
|
|
123
|
+
setNativeCurrency(symbol) {
|
|
124
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
125
|
+
this.update((state) => {
|
|
126
|
+
state.pendingNativeCurrency = symbol;
|
|
127
|
+
});
|
|
128
|
+
yield this.updateExchangeRate();
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
stopPolling() {
|
|
132
|
+
if (this.intervalId) {
|
|
133
|
+
clearInterval(this.intervalId);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Starts a new polling interval.
|
|
138
|
+
*/
|
|
139
|
+
startPolling() {
|
|
140
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
141
|
+
this.stopPolling();
|
|
142
|
+
// TODO: Expose polling currency rate update errors
|
|
143
|
+
yield (0, controller_utils_1.safelyExecute)(() => __awaiter(this, void 0, void 0, function* () { return yield this.updateExchangeRate(); }));
|
|
144
|
+
this.intervalId = setInterval(() => __awaiter(this, void 0, void 0, function* () {
|
|
145
|
+
yield (0, controller_utils_1.safelyExecute)(() => __awaiter(this, void 0, void 0, function* () { return yield this.updateExchangeRate(); }));
|
|
146
|
+
}), this.intervalDelay);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Updates exchange rate for the current currency.
|
|
151
|
+
*
|
|
152
|
+
* @returns The controller state.
|
|
153
|
+
*/
|
|
154
|
+
updateExchangeRate() {
|
|
155
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
156
|
+
if (!__classPrivateFieldGet(this, _CurrencyRateController_enabled, "f")) {
|
|
157
|
+
console.info('[CurrencyRateController] Not updating exchange rate since network requests have been disabled');
|
|
158
|
+
return this.state;
|
|
159
|
+
}
|
|
160
|
+
const releaseLock = yield this.mutex.acquire();
|
|
161
|
+
const { currentCurrency: stateCurrentCurrency, nativeCurrency: stateNativeCurrency, pendingCurrentCurrency, pendingNativeCurrency, } = this.state;
|
|
162
|
+
let conversionDate = null;
|
|
163
|
+
let conversionRate = null;
|
|
164
|
+
let usdConversionRate = null;
|
|
165
|
+
const currentCurrency = pendingCurrentCurrency !== null && pendingCurrentCurrency !== void 0 ? pendingCurrentCurrency : stateCurrentCurrency;
|
|
166
|
+
const nativeCurrency = pendingNativeCurrency !== null && pendingNativeCurrency !== void 0 ? pendingNativeCurrency : stateNativeCurrency;
|
|
167
|
+
// For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.
|
|
168
|
+
const nativeCurrencyForExchangeRate = Object.values(controller_utils_1.TESTNET_TICKER_SYMBOLS).includes(nativeCurrency)
|
|
169
|
+
? controller_utils_1.FALL_BACK_VS_CURRENCY // ETH
|
|
170
|
+
: nativeCurrency;
|
|
171
|
+
try {
|
|
172
|
+
if (currentCurrency &&
|
|
173
|
+
nativeCurrency &&
|
|
174
|
+
// if either currency is an empty string we can skip the comparison
|
|
175
|
+
// because it will result in an error from the api and ultimately
|
|
176
|
+
// a null conversionRate either way.
|
|
177
|
+
currentCurrency !== '' &&
|
|
178
|
+
nativeCurrency !== '') {
|
|
179
|
+
const fetchExchangeRateResponse = yield this.fetchExchangeRate(currentCurrency, nativeCurrencyForExchangeRate, this.includeUsdRate);
|
|
180
|
+
conversionRate = fetchExchangeRateResponse.conversionRate;
|
|
181
|
+
usdConversionRate = fetchExchangeRateResponse.usdConversionRate;
|
|
182
|
+
conversionDate = Date.now() / 1000;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (!(error instanceof Error &&
|
|
187
|
+
error.message.includes('market does not exist for this coin pair'))) {
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
try {
|
|
193
|
+
this.update(() => {
|
|
194
|
+
return {
|
|
195
|
+
conversionDate,
|
|
196
|
+
conversionRate,
|
|
197
|
+
// we currently allow and handle an empty string as a valid nativeCurrency
|
|
198
|
+
// in cases where a user has not entered a native ticker symbol for a custom network
|
|
199
|
+
// currentCurrency is not from user input but this protects us from unexpected changes.
|
|
200
|
+
nativeCurrency,
|
|
201
|
+
currentCurrency,
|
|
202
|
+
pendingCurrentCurrency: null,
|
|
203
|
+
pendingNativeCurrency: null,
|
|
204
|
+
usdConversionRate,
|
|
205
|
+
};
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
finally {
|
|
209
|
+
releaseLock();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return this.state;
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
exports.CurrencyRateController = CurrencyRateController;
|
|
217
|
+
_CurrencyRateController_enabled = new WeakMap();
|
|
218
|
+
exports.default = CurrencyRateController;
|
|
219
|
+
//# sourceMappingURL=CurrencyRateController.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CurrencyRateController.js","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AACA,+DAA6D;AAC7D,iEAIoC;AACpC,6CAAoC;AAGpC,qDAAiF;AAsBjF,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAoBtC,MAAM,QAAQ,GAAG;IACf,cAAc,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IAClD,cAAc,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IAClD,eAAe,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IACnD,cAAc,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;IAClD,sBAAsB,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE;IAC3D,qBAAqB,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE;IAC1D,iBAAiB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE;CACtD,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,cAAc,EAAE,CAAC;IACjB,cAAc,EAAE,CAAC;IACjB,eAAe,EAAE,KAAK;IACtB,cAAc,EAAE,KAAK;IACrB,sBAAsB,EAAE,IAAI;IAC5B,qBAAqB,EAAE,IAAI;IAC3B,iBAAiB,EAAE,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;YACD,OAAO,IAAI,CAAC,KAAK,CAAC;QACpB,CAAC;KAAA;CACF;AAnND,wDAmNC;;AAED,kBAAe,sBAAsB,CAAC","sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseControllerV2 } from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n safelyExecute,\n} from '@metamask/controller-utils';\nimport { Mutex } from 'async-mutex';\nimport type { Patch } from 'immer';\n\nimport { fetchExchangeRate as defaultFetchExchangeRate } from './crypto-compare';\n\n/**\n * @type CurrencyRateState\n * @property conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property nativeCurrency - Symbol for the base asset used for conversion\n * @property pendingCurrentCurrency - The currency being switched to\n * @property pendingNativeCurrency - The base asset currency being switched to\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n conversionDate: number | null;\n conversionRate: number | null;\n currentCurrency: string;\n nativeCurrency: string;\n pendingCurrentCurrency: string | null;\n pendingNativeCurrency: string | null;\n usdConversionRate: number | null;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = {\n type: `${typeof name}:stateChange`;\n payload: [CurrencyRateState, Patch[]];\n};\n\nexport type GetCurrencyRateState = {\n type: `${typeof name}:getState`;\n handler: () => CurrencyRateState;\n};\n\ntype CurrencyRateMessenger = RestrictedControllerMessenger<\n typeof name,\n GetCurrencyRateState,\n CurrencyRateStateChange,\n never,\n never\n>;\n\nconst metadata = {\n conversionDate: { persist: true, anonymous: true },\n conversionRate: { persist: true, anonymous: true },\n currentCurrency: { persist: true, anonymous: true },\n nativeCurrency: { persist: true, anonymous: true },\n pendingCurrentCurrency: { persist: false, anonymous: true },\n pendingNativeCurrency: { persist: false, anonymous: true },\n usdConversionRate: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n conversionDate: 0,\n conversionRate: 0,\n currentCurrency: 'usd',\n nativeCurrency: 'ETH',\n pendingCurrentCurrency: null,\n pendingNativeCurrency: null,\n usdConversionRate: null,\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 BaseControllerV2<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private readonly intervalDelay;\n\n private readonly fetchExchangeRate;\n\n private readonly includeUsdRate;\n\n /**\n * A boolean that controls whether or not network requests can be made by the controller\n */\n #enabled;\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.intervalDelay = interval;\n this.fetchExchangeRate = fetchExchangeRate;\n this.#enabled = false;\n }\n\n /**\n * Start polling for the currency rate.\n */\n async start() {\n this.#enabled = true;\n\n await this.startPolling();\n }\n\n /**\n * Stop polling for the currency rate.\n */\n stop() {\n this.#enabled = false;\n\n this.stopPolling();\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.stopPolling();\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n this.update((state) => {\n state.pendingCurrentCurrency = currentCurrency;\n });\n await this.updateExchangeRate();\n }\n\n /**\n * Sets a new native currency.\n *\n * @param symbol - Symbol for the base asset.\n */\n async setNativeCurrency(symbol: string) {\n this.update((state) => {\n state.pendingNativeCurrency = symbol;\n });\n await this.updateExchangeRate();\n }\n\n private stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n */\n private async startPolling(): Promise<void> {\n this.stopPolling();\n // TODO: Expose polling currency rate update errors\n\n await safelyExecute(async () => await this.updateExchangeRate());\n\n this.intervalId = setInterval(async () => {\n await safelyExecute(async () => await this.updateExchangeRate());\n }, this.intervalDelay);\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @returns The controller state.\n */\n async updateExchangeRate(): Promise<CurrencyRateState | void> {\n if (!this.#enabled) {\n console.info(\n '[CurrencyRateController] Not updating exchange rate since network requests have been disabled',\n );\n return this.state;\n }\n const releaseLock = await this.mutex.acquire();\n const {\n currentCurrency: stateCurrentCurrency,\n nativeCurrency: stateNativeCurrency,\n pendingCurrentCurrency,\n pendingNativeCurrency,\n } = this.state;\n\n let conversionDate: number | null = null;\n let conversionRate: number | null = null;\n let usdConversionRate: number | null = null;\n const currentCurrency = pendingCurrentCurrency ?? stateCurrentCurrency;\n const nativeCurrency = pendingNativeCurrency ?? stateNativeCurrency;\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\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 return {\n conversionDate,\n conversionRate,\n // we currently allow and handle an empty string as a valid nativeCurrency\n // in cases where a user has not entered a native ticker symbol for a custom network\n // currentCurrency is not from user input but this protects us from unexpected changes.\n nativeCurrency,\n currentCurrency,\n pendingCurrentCurrency: null,\n pendingNativeCurrency: null,\n usdConversionRate,\n };\n });\n } finally {\n releaseLock();\n }\n }\n return this.state;\n }\n}\n\nexport default CurrencyRateController;\n"]}
|