-
-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathRatesController.ts
237 lines (211 loc) · 6.5 KB
/
RatesController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import { BaseController } from '@metamask/base-controller';
import { Mutex } from 'async-mutex';
import type { Draft } from 'immer';
import { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';
import type {
ConversionRates,
RatesControllerState,
RatesControllerOptions,
RatesControllerMessenger,
} from './types';
export const name = 'RatesController';
/**
* Supported cryptocurrencies that can be used as a base currency. The value needs to be compatible
* with CryptoCompare's API which is the default source for the rates.
*
* See: https://min-api.cryptocompare.com/documentation?key=Price&cat=multipleSymbolsPriceEndpoint
*/
export enum Cryptocurrency {
Btc = 'btc',
Solana = 'sol',
}
const DEFAULT_INTERVAL = 180000;
const metadata = {
fiatCurrency: { persist: true, anonymous: true },
rates: { persist: true, anonymous: true },
cryptocurrencies: { persist: true, anonymous: true },
};
const defaultState = {
fiatCurrency: 'usd',
rates: {
[Cryptocurrency.Btc]: {
conversionDate: 0,
conversionRate: 0,
},
[Cryptocurrency.Solana]: {
conversionDate: 0,
conversionRate: 0,
},
},
cryptocurrencies: [Cryptocurrency.Btc, Cryptocurrency.Solana],
};
export class RatesController extends BaseController<
typeof name,
RatesControllerState,
RatesControllerMessenger
> {
readonly #mutex = new Mutex();
readonly #fetchMultiExchangeRate;
readonly #includeUsdRate;
#intervalLength: number;
#intervalId: NodeJS.Timeout | undefined;
/**
* Creates a RatesController instance.
*
* @param options - Constructor options.
* @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
* @param options.interval - The polling interval, in milliseconds.
* @param options.messenger - A reference to the messaging system.
* @param options.state - Initial state to set on this controller.
* @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
*/
constructor({
interval = DEFAULT_INTERVAL,
messenger,
state,
includeUsdRate,
fetchMultiExchangeRate = defaultFetchExchangeRate,
}: RatesControllerOptions) {
super({
name,
metadata,
messenger,
state: { ...defaultState, ...state },
});
this.#includeUsdRate = includeUsdRate;
this.#fetchMultiExchangeRate = fetchMultiExchangeRate;
this.#intervalLength = interval;
}
/**
* 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`.
* This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.
*
* @template R - The return type of the function `callback`.
* @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.
* @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.
* @example
* async function criticalLogic() {
* // Critical logic code goes here.
* }
*
* // Execute criticalLogic within a lock.
* const result = await this.#withLock(criticalLogic);
*/
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
async #withLock<R>(callback: () => R) {
const releaseLock = await this.#mutex.acquire();
try {
return callback();
} finally {
releaseLock();
}
}
/**
* Executes the polling operation to update rates.
*/
async #executePoll(): Promise<void> {
await this.#updateRates();
}
/**
* Updates the rates by fetching new data.
*/
async #updateRates(): Promise<void> {
await this.#withLock(async () => {
const { fiatCurrency, cryptocurrencies } = this.state;
const response: Record<
Cryptocurrency,
Record<string, number>
> = await this.#fetchMultiExchangeRate(
fiatCurrency,
cryptocurrencies,
this.#includeUsdRate,
);
const updatedRates: ConversionRates = {};
for (const [cryptocurrency, values] of Object.entries(response)) {
updatedRates[cryptocurrency] = {
conversionDate: Date.now(),
conversionRate: values[fiatCurrency],
...(this.#includeUsdRate && { usdConversionRate: values.usd }),
};
}
this.update(
(state: Draft<RatesControllerState>): RatesControllerState => {
return {
...state,
rates: updatedRates,
};
},
);
});
}
/**
* Starts the polling process.
*/
async start(): Promise<void> {
if (this.#intervalId) {
return;
}
this.messagingSystem.publish(`${name}:pollingStarted`);
this.#intervalId = setInterval(() => {
this.#executePoll().catch(console.error);
}, this.#intervalLength);
}
/**
* Stops the polling process.
*/
async stop(): Promise<void> {
if (!this.#intervalId) {
return;
}
clearInterval(this.#intervalId);
this.#intervalId = undefined;
this.messagingSystem.publish(`${name}:pollingStopped`);
}
/**
* Returns the current list of cryptocurrency.
* @returns The cryptocurrency list.
*/
getCryptocurrencyList(): Cryptocurrency[] {
const { cryptocurrencies } = this.state;
return cryptocurrencies;
}
/**
* Sets the list of supported cryptocurrencies.
* @param cryptocurrencies - The list of supported cryptocurrencies.
*/
async setCryptocurrencyList(
cryptocurrencies: Cryptocurrency[],
): Promise<void> {
await this.#withLock(() => {
this.update(
(state: Draft<RatesControllerState>): RatesControllerState => {
return {
...state,
cryptocurrencies,
};
},
);
});
}
/**
* Sets the internal fiat currency and update rates accordingly.
* @param fiatCurrency - The fiat currency.
*/
async setFiatCurrency(fiatCurrency: string): Promise<void> {
if (fiatCurrency === '') {
throw new Error('The currency can not be an empty string');
}
await this.#withLock(() => {
this.update(
(state: Draft<RatesControllerState>): RatesControllerState => {
return {
...state,
fiatCurrency,
};
},
);
});
await this.#updateRates();
}
}