-
-
Notifications
You must be signed in to change notification settings - Fork 192
/
codefi-v2.ts
432 lines (411 loc) · 10.8 KB
/
codefi-v2.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import { handleFetch } from '@metamask/controller-utils';
import type { Hex } from '@metamask/utils';
import { hexToNumber } from '@metamask/utils';
import {
circuitBreaker,
ConsecutiveBreaker,
ExponentialBackoff,
handleAll,
type IPolicy,
retry,
wrap,
CircuitState,
} from 'cockatiel';
import type {
AbstractTokenPricesService,
TokenPrice,
TokenPricesByTokenAddress,
} from './abstract-token-prices-service';
/**
* The shape of the data that the /spot-prices endpoint returns.
*/
type SpotPricesEndpointData<
TokenAddress extends Hex,
Currency extends string,
> = Record<TokenAddress, Record<Currency, number>>;
/**
* The list of currencies that can be supplied as the `vsCurrency` parameter to
* the `/spot-prices` endpoint, in lowercase form.
*/
export const SUPPORTED_CURRENCIES = [
// Bitcoin
'btc',
// Ether
'eth',
// Litecoin
'ltc',
// Bitcoin Cash
'bch',
// Binance Coin
'bnb',
// EOS
'eos',
// XRP
'xrp',
// Lumens
'xlm',
// Chainlink
'link',
// Polkadot
'dot',
// Yearn.finance
'yfi',
// US Dollar
'usd',
// United Arab Emirates Dirham
'aed',
// Argentine Peso
'ars',
// Australian Dollar
'aud',
// Bangladeshi Taka
'bdt',
// Bahraini Dinar
'bhd',
// Bermudian Dollar
'bmd',
// Brazil Real
'brl',
// Canadian Dollar
'cad',
// Swiss Franc
'chf',
// Chilean Peso
'clp',
// Chinese Yuan
'cny',
// Czech Koruna
'czk',
// Danish Krone
'dkk',
// Euro
'eur',
// British Pound Sterling
'gbp',
// Hong Kong Dollar
'hkd',
// Hungarian Forint
'huf',
// Indonesian Rupiah
'idr',
// Israeli New Shekel
'ils',
// Indian Rupee
'inr',
// Japanese Yen
'jpy',
// South Korean Won
'krw',
// Kuwaiti Dinar
'kwd',
// Sri Lankan Rupee
'lkr',
// Burmese Kyat
'mmk',
// Mexican Peso
'mxn',
// Malaysian Ringgit
'myr',
// Nigerian Naira
'ngn',
// Norwegian Krone
'nok',
// New Zealand Dollar
'nzd',
// Philippine Peso
'php',
// Pakistani Rupee
'pkr',
// Polish Zloty
'pln',
// Russian Ruble
'rub',
// Saudi Riyal
'sar',
// Swedish Krona
'sek',
// Singapore Dollar
'sgd',
// Thai Baht
'thb',
// Turkish Lira
'try',
// New Taiwan Dollar
'twd',
// Ukrainian hryvnia
'uah',
// Venezuelan bolívar fuerte
'vef',
// Vietnamese đồng
'vnd',
// South African Rand
'zar',
// IMF Special Drawing Rights
'xdr',
// Silver - Troy Ounce
'xag',
// Gold - Troy Ounce
'xau',
// Bits
'bits',
// Satoshi
'sats',
] as const;
/**
* A currency that can be supplied as the `vsCurrency` parameter to
* the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.
*/
type SupportedCurrency =
| (typeof SUPPORTED_CURRENCIES)[number]
| Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;
/**
* The list of chain IDs that can be supplied in the URL for the `/spot-prices`
* endpoint, but in hexadecimal form (for consistency with how we represent
* chain IDs in other places).
* @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
*/
export const SUPPORTED_CHAIN_IDS = [
// Ethereum Mainnet
'0x1',
// OP Mainnet
'0xa',
// Cronos Mainnet
'0x19',
// BNB Smart Chain Mainnet
'0x38',
// Syscoin Mainnet
'0x39',
// OKXChain Mainnet
'0x42',
// Hoo Smart Chain
'0x46',
// Meter Mainnet
'0x52',
// TomoChain
'0x58',
// Gnosis
'0x64',
// Velas EVM Mainnet
'0x6a',
// Fuse Mainnet
'0x7a',
// Huobi ECO Chain Mainnet
'0x80',
// Polygon Mainnet
'0x89',
// Fantom Opera
'0xfa',
// Boba Network
'0x120',
// KCC Mainnet
'0x141',
// zkSync Era Mainnet
'0x144',
// Theta Mainnet
'0x169',
// Metis Andromeda Mainnet
'0x440',
// Moonbeam
'0x504',
// Moonriver
'0x505',
// Base
'0x2105',
// Shiden
'0x150',
// Smart Bitcoin Cash
'0x2710',
// Arbitrum One
'0xa4b1',
// Celo Mainnet
'0xa4ec',
// Oasis Emerald
'0xa516',
// Avalanche C-Chain
'0xa86a',
// Polis Mainnet
'0x518af',
// Aurora Mainnet
'0x4e454152',
// Harmony Mainnet Shard 0
'0x63564c40',
// Linea Mainnet
'0xe708',
] as const;
/**
* A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,
* but in hexadecimal form (for consistency with how we represent chain IDs in
* other places).
*/
type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
/**
* All requests to V2 of the Price API start with this.
*/
const BASE_URL = 'https://price-api.metafi.codefi.network/v2';
const DEFAULT_TOKEN_PRICE_RETRIES = 3;
// Each update attempt will result (1 + retries) calls if the server is down
const DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES =
(1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;
const DEFAULT_DEGRADED_THRESHOLD = 5_000;
/**
* This version of the token prices service uses V2 of the Codefi Price API to
* fetch token prices.
*/
export class CodefiTokenPricesServiceV2
implements
AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>
{
#tokenPricePolicy: IPolicy;
/**
* Construct a Codefi Token Price Service.
*
* @param options - Constructor options
* @param options.degradedThreshold - The threshold between "normal" and "degrated" service,
* in milliseconds.
* @param options.retries - Number of retry attempts for each token price update.
* @param options.maximumConsecutiveFailures - The maximum number of consecutive failures
* allowed before breaking the circuit and pausing further updates.
* @param options.onBreak - An event handler for when the circuit breaks, useful for capturing
* metrics about network failures.
* @param options.onDegraded - An event handler for when the circuit remains closed, but requests
* are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).
* @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks
* from too many consecutive failures.
*/
constructor({
degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,
retries = DEFAULT_TOKEN_PRICE_RETRIES,
maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,
onBreak,
onDegraded,
circuitBreakDuration = 30 * 60 * 1000,
}: {
degradedThreshold?: number;
retries?: number;
maximumConsecutiveFailures?: number;
onBreak?: () => void;
onDegraded?: () => void;
circuitBreakDuration?: number;
} = {}) {
// Construct a policy that will retry each update, and halt further updates
// for a certain period after too many consecutive failures.
const retryPolicy = retry(handleAll, {
maxAttempts: retries,
backoff: new ExponentialBackoff(),
});
const circuitBreakerPolicy = circuitBreaker(handleAll, {
halfOpenAfter: circuitBreakDuration,
breaker: new ConsecutiveBreaker(maximumConsecutiveFailures),
});
if (onBreak) {
circuitBreakerPolicy.onBreak(onBreak);
}
if (onDegraded) {
retryPolicy.onGiveUp(() => {
if (circuitBreakerPolicy.state === CircuitState.Closed) {
onDegraded();
}
});
retryPolicy.onSuccess(({ duration }) => {
if (
circuitBreakerPolicy.state === CircuitState.Closed &&
duration > degradedThreshold
) {
onDegraded();
}
});
}
this.#tokenPricePolicy = wrap(retryPolicy, circuitBreakerPolicy);
}
/**
* Retrieves prices in the given currency for the tokens identified by the
* given addresses which are expected to live on the given chain.
*
* @param args - The arguments to function.
* @param args.chainId - An EIP-155 chain ID.
* @param args.tokenAddresses - Addresses for tokens that live on the chain.
* @param args.currency - The desired currency of the token prices.
* @returns The prices for the requested tokens.
*/
async fetchTokenPrices({
chainId,
tokenAddresses,
currency,
}: {
chainId: SupportedChainId;
tokenAddresses: Hex[];
currency: SupportedCurrency;
}): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {
const chainIdAsNumber = hexToNumber(chainId);
const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);
url.searchParams.append('tokenAddresses', tokenAddresses.join(','));
url.searchParams.append('vsCurrency', currency);
const pricesByCurrencyByTokenAddress: SpotPricesEndpointData<
Lowercase<Hex>,
Lowercase<SupportedCurrency>
> = await this.#tokenPricePolicy.execute(() =>
handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),
);
return tokenAddresses.reduce(
(
obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,
tokenAddress,
) => {
// The Price API lowercases both currency and token addresses, so we have
// to keep track of them and make sure we return the original versions.
const lowercasedTokenAddress =
tokenAddress.toLowerCase() as Lowercase<Hex>;
const lowercasedCurrency =
currency.toLowerCase() as Lowercase<SupportedCurrency>;
const price =
pricesByCurrencyByTokenAddress[lowercasedTokenAddress]?.[
lowercasedCurrency
];
if (!price) {
// console error instead of throwing to not interrupt the fetching of other tokens in case just one fails
console.error(
`Could not find price for "${tokenAddress}" in "${currency}"`,
);
}
const tokenPrice: TokenPrice<Hex, SupportedCurrency> = {
tokenAddress,
value: price,
currency,
};
return {
...obj,
...(tokenPrice.value !== undefined
? { [tokenAddress]: tokenPrice }
: {}),
};
},
{},
) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;
}
/**
* Type guard for whether the API can return token prices for the given chain
* ID.
*
* @param chainId - The chain ID to check.
* @returns True if the API supports the chain ID, false otherwise.
*/
validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {
const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;
return typeof chainId === 'string' && supportedChainIds.includes(chainId);
}
/**
* Type guard for whether the API can return token prices in the given
* currency.
*
* @param currency - The currency to check. If a string, can be either
* lowercase or uppercase.
* @returns True if the API supports the currency, false otherwise.
*/
validateCurrencySupported(currency: unknown): currency is SupportedCurrency {
const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;
return (
typeof currency === 'string' &&
supportedCurrencies.includes(currency.toLowerCase())
);
}
}