@metamask-previews/assets-controllers 16.0.0-preview.72e94e9 → 16.0.0-preview.e3b05ea
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.d.ts +39 -17
- package/dist/CurrencyRateController.d.ts.map +1 -1
- package/dist/CurrencyRateController.js +110 -41
- package/dist/CurrencyRateController.js.map +1 -1
- package/dist/NftController.d.ts +1 -1
- package/dist/NftController.js +1 -1
- package/dist/NftController.js.map +1 -1
- package/dist/NftDetectionController.d.ts +16 -5
- package/dist/NftDetectionController.d.ts.map +1 -1
- package/dist/NftDetectionController.js +26 -5
- package/dist/NftDetectionController.js.map +1 -1
- package/dist/TokenBalancesController.js +4 -4
- package/dist/TokenBalancesController.js.map +1 -1
- package/dist/TokenDetectionController.d.ts +19 -5
- package/dist/TokenDetectionController.d.ts.map +1 -1
- package/dist/TokenDetectionController.js +27 -7
- package/dist/TokenDetectionController.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,22 +1,24 @@
|
|
|
1
1
|
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
2
|
-
import
|
|
3
|
-
import { PollingController } from '@metamask/polling-controller';
|
|
2
|
+
import { BaseControllerV2 } from '@metamask/base-controller';
|
|
4
3
|
import type { Patch } from 'immer';
|
|
5
4
|
import { fetchExchangeRate as defaultFetchExchangeRate } from './crypto-compare';
|
|
6
5
|
/**
|
|
7
6
|
* @type CurrencyRateState
|
|
8
|
-
* @property
|
|
9
|
-
* @property
|
|
10
|
-
* @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency
|
|
7
|
+
* @property conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
|
|
8
|
+
* @property conversionRate - Conversion rate from current base asset to the current currency
|
|
11
9
|
* @property currentCurrency - Currently-active ISO 4217 currency code
|
|
10
|
+
* @property nativeCurrency - Symbol for the base asset used for conversion
|
|
11
|
+
* @property pendingCurrentCurrency - The currency being switched to
|
|
12
|
+
* @property pendingNativeCurrency - The base asset currency being switched to
|
|
12
13
|
* @property usdConversionRate - Conversion rate from usd to the current currency
|
|
13
14
|
*/
|
|
14
15
|
export declare type CurrencyRateState = {
|
|
16
|
+
conversionDate: number | null;
|
|
17
|
+
conversionRate: number | null;
|
|
15
18
|
currentCurrency: string;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}>;
|
|
19
|
+
nativeCurrency: string;
|
|
20
|
+
pendingCurrentCurrency: string | null;
|
|
21
|
+
pendingNativeCurrency: string | null;
|
|
20
22
|
usdConversionRate: number | null;
|
|
21
23
|
};
|
|
22
24
|
declare const name = "CurrencyRateController";
|
|
@@ -28,14 +30,16 @@ export declare type GetCurrencyRateState = {
|
|
|
28
30
|
type: `${typeof name}:getState`;
|
|
29
31
|
handler: () => CurrencyRateState;
|
|
30
32
|
};
|
|
31
|
-
declare type
|
|
32
|
-
declare type CurrencyRateMessenger = RestrictedControllerMessenger<typeof name, GetCurrencyRateState | AllowedActions, CurrencyRateStateChange, AllowedActions['type'], never>;
|
|
33
|
+
declare type CurrencyRateMessenger = RestrictedControllerMessenger<typeof name, GetCurrencyRateState, CurrencyRateStateChange, never, never>;
|
|
33
34
|
/**
|
|
34
35
|
* Controller that passively polls on a set interval for an exchange rate from the current network
|
|
35
36
|
* asset to the user's preferred currency.
|
|
36
37
|
*/
|
|
37
|
-
export declare class CurrencyRateController extends
|
|
38
|
+
export declare class CurrencyRateController extends BaseControllerV2<typeof name, CurrencyRateState, CurrencyRateMessenger> {
|
|
39
|
+
#private;
|
|
38
40
|
private readonly mutex;
|
|
41
|
+
private intervalId?;
|
|
42
|
+
private readonly intervalDelay;
|
|
39
43
|
private readonly fetchExchangeRate;
|
|
40
44
|
private readonly includeUsdRate;
|
|
41
45
|
/**
|
|
@@ -55,6 +59,20 @@ export declare class CurrencyRateController extends PollingController<typeof nam
|
|
|
55
59
|
state?: Partial<CurrencyRateState>;
|
|
56
60
|
fetchExchangeRate?: typeof defaultFetchExchangeRate;
|
|
57
61
|
});
|
|
62
|
+
/**
|
|
63
|
+
* Start polling for the currency rate.
|
|
64
|
+
*/
|
|
65
|
+
start(): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* Stop polling for the currency rate.
|
|
68
|
+
*/
|
|
69
|
+
stop(): void;
|
|
70
|
+
/**
|
|
71
|
+
* Prepare to discard this controller.
|
|
72
|
+
*
|
|
73
|
+
* This stops any active polling.
|
|
74
|
+
*/
|
|
75
|
+
destroy(): void;
|
|
58
76
|
/**
|
|
59
77
|
* Sets a currency to track.
|
|
60
78
|
*
|
|
@@ -62,18 +80,22 @@ export declare class CurrencyRateController extends PollingController<typeof nam
|
|
|
62
80
|
*/
|
|
63
81
|
setCurrentCurrency(currentCurrency: string): Promise<void>;
|
|
64
82
|
/**
|
|
65
|
-
*
|
|
83
|
+
* Sets a new native currency.
|
|
66
84
|
*
|
|
67
|
-
* @param
|
|
85
|
+
* @param symbol - Symbol for the base asset.
|
|
86
|
+
*/
|
|
87
|
+
setNativeCurrency(symbol: string): Promise<void>;
|
|
88
|
+
private stopPolling;
|
|
89
|
+
/**
|
|
90
|
+
* Starts a new polling interval.
|
|
68
91
|
*/
|
|
69
|
-
|
|
92
|
+
private startPolling;
|
|
70
93
|
/**
|
|
71
94
|
* Updates exchange rate for the current currency.
|
|
72
95
|
*
|
|
73
|
-
* @param networkClientId - The network client ID used to get a ticker value.
|
|
74
96
|
* @returns The controller state.
|
|
75
97
|
*/
|
|
76
|
-
|
|
98
|
+
updateExchangeRate(): Promise<CurrencyRateState | void>;
|
|
77
99
|
}
|
|
78
100
|
export default CurrencyRateController;
|
|
79
101
|
//# sourceMappingURL=CurrencyRateController.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CurrencyRateController.d.ts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;
|
|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AAK,CAAe;IAErC,OAAO,CAAC,UAAU,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"}
|
|
@@ -8,33 +8,48 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
9
|
});
|
|
10
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;
|
|
11
23
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
24
|
exports.CurrencyRateController = void 0;
|
|
25
|
+
const base_controller_1 = require("@metamask/base-controller");
|
|
13
26
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
14
|
-
const polling_controller_1 = require("@metamask/polling-controller");
|
|
15
27
|
const async_mutex_1 = require("async-mutex");
|
|
16
28
|
const crypto_compare_1 = require("./crypto-compare");
|
|
17
29
|
const name = 'CurrencyRateController';
|
|
18
30
|
const metadata = {
|
|
31
|
+
conversionDate: { persist: true, anonymous: true },
|
|
32
|
+
conversionRate: { persist: true, anonymous: true },
|
|
19
33
|
currentCurrency: { persist: true, anonymous: true },
|
|
20
|
-
|
|
34
|
+
nativeCurrency: { persist: true, anonymous: true },
|
|
35
|
+
pendingCurrentCurrency: { persist: false, anonymous: true },
|
|
36
|
+
pendingNativeCurrency: { persist: false, anonymous: true },
|
|
21
37
|
usdConversionRate: { persist: true, anonymous: true },
|
|
22
38
|
};
|
|
23
39
|
const defaultState = {
|
|
40
|
+
conversionDate: 0,
|
|
41
|
+
conversionRate: 0,
|
|
24
42
|
currentCurrency: 'usd',
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
conversionRate: 0,
|
|
29
|
-
},
|
|
30
|
-
},
|
|
43
|
+
nativeCurrency: 'ETH',
|
|
44
|
+
pendingCurrentCurrency: null,
|
|
45
|
+
pendingNativeCurrency: null,
|
|
31
46
|
usdConversionRate: null,
|
|
32
47
|
};
|
|
33
48
|
/**
|
|
34
49
|
* Controller that passively polls on a set interval for an exchange rate from the current network
|
|
35
50
|
* asset to the user's preferred currency.
|
|
36
51
|
*/
|
|
37
|
-
class CurrencyRateController extends
|
|
52
|
+
class CurrencyRateController extends base_controller_1.BaseControllerV2 {
|
|
38
53
|
/**
|
|
39
54
|
* Creates a CurrencyRateController instance.
|
|
40
55
|
*
|
|
@@ -53,9 +68,39 @@ class CurrencyRateController extends polling_controller_1.PollingController {
|
|
|
53
68
|
state: Object.assign(Object.assign({}, defaultState), state),
|
|
54
69
|
});
|
|
55
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);
|
|
56
75
|
this.includeUsdRate = includeUsdRate;
|
|
57
|
-
this.
|
|
76
|
+
this.intervalDelay = interval;
|
|
58
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();
|
|
59
104
|
}
|
|
60
105
|
/**
|
|
61
106
|
* Sets a currency to track.
|
|
@@ -64,31 +109,61 @@ class CurrencyRateController extends polling_controller_1.PollingController {
|
|
|
64
109
|
*/
|
|
65
110
|
setCurrentCurrency(currentCurrency) {
|
|
66
111
|
return __awaiter(this, void 0, void 0, function* () {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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();
|
|
78
129
|
});
|
|
79
130
|
}
|
|
131
|
+
stopPolling() {
|
|
132
|
+
if (this.intervalId) {
|
|
133
|
+
clearInterval(this.intervalId);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
80
136
|
/**
|
|
81
|
-
*
|
|
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.
|
|
82
151
|
*
|
|
83
|
-
* @
|
|
152
|
+
* @returns The controller state.
|
|
84
153
|
*/
|
|
85
|
-
updateExchangeRate(
|
|
154
|
+
updateExchangeRate() {
|
|
86
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
|
+
}
|
|
87
160
|
const releaseLock = yield this.mutex.acquire();
|
|
88
|
-
const { currentCurrency,
|
|
161
|
+
const { currentCurrency: stateCurrentCurrency, nativeCurrency: stateNativeCurrency, pendingCurrentCurrency, pendingNativeCurrency, } = this.state;
|
|
89
162
|
let conversionDate = null;
|
|
90
163
|
let conversionRate = null;
|
|
91
164
|
let usdConversionRate = null;
|
|
165
|
+
const currentCurrency = pendingCurrentCurrency !== null && pendingCurrentCurrency !== void 0 ? pendingCurrentCurrency : stateCurrentCurrency;
|
|
166
|
+
const nativeCurrency = pendingNativeCurrency !== null && pendingNativeCurrency !== void 0 ? pendingNativeCurrency : stateNativeCurrency;
|
|
92
167
|
// For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.
|
|
93
168
|
const nativeCurrencyForExchangeRate = Object.values(controller_utils_1.TESTNET_TICKER_SYMBOLS).includes(nativeCurrency)
|
|
94
169
|
? controller_utils_1.FALL_BACK_VS_CURRENCY // ETH
|
|
@@ -117,11 +192,15 @@ class CurrencyRateController extends polling_controller_1.PollingController {
|
|
|
117
192
|
try {
|
|
118
193
|
this.update(() => {
|
|
119
194
|
return {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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,
|
|
124
201
|
currentCurrency,
|
|
202
|
+
pendingCurrentCurrency: null,
|
|
203
|
+
pendingNativeCurrency: null,
|
|
125
204
|
usdConversionRate,
|
|
126
205
|
};
|
|
127
206
|
});
|
|
@@ -130,21 +209,11 @@ class CurrencyRateController extends polling_controller_1.PollingController {
|
|
|
130
209
|
releaseLock();
|
|
131
210
|
}
|
|
132
211
|
}
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* Updates exchange rate for the current currency.
|
|
137
|
-
*
|
|
138
|
-
* @param networkClientId - The network client ID used to get a ticker value.
|
|
139
|
-
* @returns The controller state.
|
|
140
|
-
*/
|
|
141
|
-
executePoll(networkClientId) {
|
|
142
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
143
|
-
const networkClient = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
|
|
144
|
-
yield (0, controller_utils_1.safelyExecute)(() => this.updateExchangeRate(networkClient.configuration.ticker));
|
|
212
|
+
return this.state;
|
|
145
213
|
});
|
|
146
214
|
}
|
|
147
215
|
}
|
|
148
216
|
exports.CurrencyRateController = CurrencyRateController;
|
|
217
|
+
_CurrencyRateController_enabled = new WeakMap();
|
|
149
218
|
exports.default = CurrencyRateController;
|
|
150
219
|
//# sourceMappingURL=CurrencyRateController.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CurrencyRateController.js","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iEAIoC;AAKpC,qE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AC,CACnE,EACD;oBACA,MAAM,KAAK,CAAC;iBACb;aACF;oBAAS;gBACR,IAAI;oBACF,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;wBACf,OAAO;4BACL,aAAa,kCACR,aAAa,KAChB,CAAC,cAAc,CAAC,EAAE;oCAChB,cAAc;oCACd,cAAc;iCACf,GACF;4BACD,eAAe;4BACf,iBAAiB;yBAClB,CAAC;oBACJ,CAAC,CAAC,CAAC;iBACJ;wBAAS;oBACR,WAAW,EAAE,CAAC;iBACf;aACF;QACH,CAAC;KAAA;IAED;;;;;OAKG;IACG,WAAW,CAAC,eAAgC;;YAChD,MAAM,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,wCAAwC,EACxC,eAAe,CAChB,CAAC;YACF,MAAM,IAAA,gCAAa,EAAC,GAAG,EAAE,CACvB,IAAI,CAAC,kBAAkB,CAAC,aAAa,CAAC,aAAa,CAAC,MAAM,CAAC,CAC5D,CAAC;QACJ,CAAC;KAAA;CACF;AApJD,wDAoJC;AAED,kBAAe,sBAAsB,CAAC","sourcesContent":["import type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n safelyExecute,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport { PollingController } from '@metamask/polling-controller';\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 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 }\n >;\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 AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype CurrencyRateMessenger = RestrictedControllerMessenger<\n typeof name,\n GetCurrencyRateState | AllowedActions,\n CurrencyRateStateChange,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n usdConversionRate: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\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 PollingController<\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 try {\n this.update((state) => {\n state.currentCurrency = currentCurrency;\n state.currencyRates = {};\n });\n } finally {\n releaseLock();\n }\n await this.updateExchangeRate(currentCurrency);\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\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 currencyRates: {\n ...currencyRates,\n [nativeCurrency]: {\n conversionDate,\n conversionRate,\n },\n },\n currentCurrency,\n usdConversionRate,\n };\n });\n } finally {\n releaseLock();\n }\n }\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 safelyExecute(() =>\n this.updateExchangeRate(networkClient.configuration.ticker),\n );\n }\n}\n\nexport default CurrencyRateController;\n"]}
|
|
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,IAAI;CACxB,CAAC;AAEF;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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"]}
|
package/dist/NftController.d.ts
CHANGED
|
@@ -480,7 +480,7 @@ export declare class NftController extends BaseController<NftConfig, NftState> {
|
|
|
480
480
|
* @param transactionId - NFT transaction id.
|
|
481
481
|
* @param selectedAddress - Hex address of the user account.
|
|
482
482
|
* @param chainId - Id of the current network.
|
|
483
|
-
* @returns a boolean indicating if the reset was well
|
|
483
|
+
* @returns a boolean indicating if the reset was well succeeded or not
|
|
484
484
|
*/
|
|
485
485
|
resetNftTransactionStatusByTransactionId(transactionId: string, selectedAddress: string, chainId: Hex): boolean;
|
|
486
486
|
_requestApproval(suggestedNftMeta: SuggestedNftMeta): Promise<unknown>;
|
package/dist/NftController.js
CHANGED
|
@@ -929,7 +929,7 @@ class NftController extends base_controller_1.BaseController {
|
|
|
929
929
|
* @param transactionId - NFT transaction id.
|
|
930
930
|
* @param selectedAddress - Hex address of the user account.
|
|
931
931
|
* @param chainId - Id of the current network.
|
|
932
|
-
* @returns a boolean indicating if the reset was well
|
|
932
|
+
* @returns a boolean indicating if the reset was well succeeded or not
|
|
933
933
|
*/
|
|
934
934
|
resetNftTransactionStatusByTransactionId(transactionId, selectedAddress, chainId) {
|
|
935
935
|
var _a;
|