-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathutils.ts
781 lines (648 loc) · 28.8 KB
/
utils.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
import {Contract} from 'ethers';
import {Contract as MulticallContract} from "@curvefi/ethcall";
import BigNumber from 'bignumber.js';
import {
Abi,
AbiFunction,
IBasePoolShortItem,
IChainId,
ICurveLiteNetwork,
IDict,
INetworkName,
IRewardFromApi,
IVolumeAndAPYs,
REFERENCE_ASSET,
} from './interfaces';
import {curve} from "./curve.js";
import {
_getCurveLiteNetworks,
_getFactoryAPYs,
_getLiteNetworksData,
_getSubgraphData,
_getVolumes,
} from "./external-api.js";
import {_getAllPoolsFromApi, _getUsdPricesFromApi} from "./cached.js";
import ERC20Abi from './constants/abis/ERC20.json' with { type: 'json' };
import {L2Networks} from './constants/L2Networks.js';
import {volumeNetworks} from "./constants/volumeNetworks.js";
import {getPool} from "./pools/index.js";
import {NETWORK_CONSTANTS} from "./constants/network_constants.js";
export const ETH_ADDRESS = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
// export const MAX_ALLOWANCE = curve.parseUnits(new BigNumber(2).pow(256).minus(1).toFixed(), 0);
export const MAX_ALLOWANCE = BigInt("115792089237316195423570985008687907853269984665640564039457584007913129639935"); // 2**256 - 1
// Formatting numbers
export const _cutZeros = (strn: string): string => {
return strn.replace(/(\.\d*[1-9])0+$/gi, '$1').replace(/\.0+$/gi, '');
}
export const checkNumber = (n: number | string): number | string => {
if (Number(n) !== Number(n)) throw Error(`${n} is not a number`); // NaN
return n
}
export const formatNumber = (n: number | string, decimals = 18): string => {
if (Number(n) !== Number(n)) throw Error(`${n} is not a number`); // NaN
const [integer, fractional] = String(n).split(".");
return !fractional ? integer : integer + "." + fractional.slice(0, decimals);
}
export const parseUnits = (n: number | string, decimals = 18): bigint => {
return curve.parseUnits(formatNumber(n, decimals), decimals);
}
// bignumber.js
export const BN = (val: number | string): BigNumber => new BigNumber(checkNumber(val));
export const toBN = (n: bigint, decimals = 18): BigNumber => {
return BN(curve.formatUnits(n, decimals));
}
export const toStringFromBN = (bn: BigNumber, decimals = 18): string => {
return bn.toFixed(decimals);
}
export const fromBN = (bn: BigNumber, decimals = 18): bigint => {
return curve.parseUnits(toStringFromBN(bn, decimals), decimals)
}
// -------------------
export const isEth = (address: string): boolean => address.toLowerCase() === ETH_ADDRESS.toLowerCase();
export const getEthIndex = (addresses: string[]): number => addresses.map((address: string) => address.toLowerCase()).indexOf(ETH_ADDRESS.toLowerCase());
export const mulBy1_3 = (n: bigint): bigint => n * curve.parseUnits("130", 0) / curve.parseUnits("100", 0);
export const smartNumber = (abstractNumber: bigint | bigint[]): number | number[] => {
if(Array.isArray(abstractNumber)) {
return [Number(abstractNumber[0]), Number(abstractNumber[1])];
} else {
return Number(abstractNumber);
}
}
export const DIGas = (gas: bigint | Array<bigint>): bigint => {
if(Array.isArray(gas)) {
return gas[0];
} else {
return gas;
}
}
export const getGasFromArray = (gas: number[]): number | number[] => {
if(gas[1] === 0) {
return gas[0];
} else {
return gas;
}
}
export const gasSum = (gas: number[], currentGas: number | number[]): number[] => {
if(Array.isArray(currentGas)) {
gas[0] = gas[0] + currentGas[0];
gas[1] = gas[1] + currentGas[1];
} else {
gas[0] = gas[0] + currentGas;
}
return gas;
}
// coins can be either addresses or symbols
export const _getCoinAddressesNoCheck = (...coins: string[] | string[][]): string[] => {
if (coins.length == 1 && Array.isArray(coins[0])) coins = coins[0];
coins = coins as string[];
return coins.map((c) => c.toLowerCase()).map((c) => curve.constants.COINS[c] || c);
}
export const _getCoinAddresses = (...coins: string[] | string[][]): string[] => {
const coinAddresses = _getCoinAddressesNoCheck(...coins);
const availableAddresses = [...Object.keys(curve.constants.DECIMALS), ...curve.constants.GAUGES];
for (const coinAddr of coinAddresses) {
if (!availableAddresses.includes(coinAddr)) throw Error(`Coin with address '${coinAddr}' is not available`);
}
return coinAddresses
}
export const _getCoinDecimals = (...coinAddresses: string[] | string[][]): number[] => {
if (coinAddresses.length == 1 && Array.isArray(coinAddresses[0])) coinAddresses = coinAddresses[0];
coinAddresses = coinAddresses as string[];
return coinAddresses.map((coinAddr) => curve.constants.DECIMALS[coinAddr.toLowerCase()] ?? 18); // 18 for gauges
}
export const _getBalances = async (coins: string[], addresses: string[]): Promise<IDict<string[]>> => {
const coinAddresses = _getCoinAddresses(coins);
const decimals = _getCoinDecimals(coinAddresses);
const ethIndex = getEthIndex(coinAddresses);
if (ethIndex !== -1) {
coinAddresses.splice(ethIndex, 1);
}
const contractCalls = [];
for (const coinAddr of coinAddresses) {
contractCalls.push(...addresses.map((address: string) => curve.contracts[coinAddr].multicallContract.balanceOf(address)));
}
const _response: bigint[] = await curve.multicallProvider.all(contractCalls);
if (ethIndex !== -1) {
const ethBalances: bigint[] = [];
for (const address of addresses) {
ethBalances.push(await curve.provider.getBalance(address));
}
_response.splice(ethIndex * addresses.length, 0, ...ethBalances);
}
const _balances: IDict<bigint[]> = {};
addresses.forEach((address: string, i: number) => {
_balances[address] = coins.map((_, j: number ) => _response[i + (j * addresses.length)]);
});
const balances: IDict<string[]> = {};
for (const address of addresses) {
balances[address] = _balances[address].map((b, i: number ) => curve.formatUnits(b, decimals[i]));
}
return balances;
}
export const _prepareAddresses = (addresses: string[] | string[][]): string[] => {
if (addresses.length == 1 && Array.isArray(addresses[0])) addresses = addresses[0];
if (addresses.length === 0 && curve.signerAddress !== '') addresses = [curve.signerAddress];
addresses = addresses as string[];
return addresses.filter((val, idx, arr) => arr.indexOf(val) === idx)
}
export const _getAddress = (address: string): string => {
address = address || curve.signerAddress;
if (!address) throw Error("Need to connect wallet or pass address into args");
return address
}
export const getBalances = async (coins: string[], ...addresses: string[] | string[][]): Promise<IDict<string[]> | string[]> => {
addresses = _prepareAddresses(addresses);
const balances: IDict<string[]> = await _getBalances(coins, addresses);
return addresses.length === 1 ? balances[addresses[0]] : balances
}
export const _getAllowance = async (coins: string[], address: string, spender: string): Promise<bigint[]> => {
const _coins = [...coins]
const ethIndex = getEthIndex(_coins);
if (ethIndex !== -1) {
_coins.splice(ethIndex, 1);
}
let allowance: bigint[];
if (_coins.length === 1) {
allowance = [await curve.contracts[_coins[0]].contract.allowance(address, spender, curve.constantOptions)];
} else {
const contractCalls = _coins.map((coinAddr) => curve.contracts[coinAddr].multicallContract.allowance(address, spender));
allowance = await curve.multicallProvider.all(contractCalls);
}
if (ethIndex !== -1) {
allowance.splice(ethIndex, 0, MAX_ALLOWANCE);
}
return allowance;
}
// coins can be either addresses or symbols
export const getAllowance = async (coins: string[], address: string, spender: string): Promise<string[]> => {
const coinAddresses = _getCoinAddresses(coins);
const decimals = _getCoinDecimals(coinAddresses);
const _allowance = await _getAllowance(coinAddresses, address, spender);
return _allowance.map((a, i) => curve.formatUnits(a, decimals[i]))
}
// coins can be either addresses or symbols
export const hasAllowance = async (coins: string[], amounts: (number | string)[], address: string, spender: string): Promise<boolean> => {
const coinAddresses = _getCoinAddresses(coins);
const decimals = _getCoinDecimals(coinAddresses);
const _allowance = await _getAllowance(coinAddresses, address, spender);
const _amounts = amounts.map((a, i) => parseUnits(a, decimals[i]));
return _allowance.map((a, i) => a >= _amounts[i]).reduce((a, b) => a && b);
}
export const _ensureAllowance = async (coins: string[], amounts: bigint[], spender: string, isMax = true): Promise<string[]> => {
const address = curve.signerAddress;
const allowance: bigint[] = await _getAllowance(coins, address, spender);
const txHashes: string[] = []
for (let i = 0; i < allowance.length; i++) {
if (allowance[i] < amounts[i]) {
const contract = curve.contracts[coins[i]].contract;
const _approveAmount = isMax ? MAX_ALLOWANCE : amounts[i];
await curve.updateFeeData();
if (allowance[i] > curve.parseUnits("0")) {
const gasLimit = mulBy1_3(DIGas(await contract.approve.estimateGas(spender, curve.parseUnits("0"), curve.constantOptions)));
const resetTx = await contract.approve(spender, curve.parseUnits("0"), { ...curve.options, gasLimit });
txHashes.push(resetTx.hash);
await resetTx.wait();
}
const gasLimit = mulBy1_3(DIGas(await contract.approve.estimateGas(spender, _approveAmount, curve.constantOptions)));
const approveTx = await contract.approve(spender, _approveAmount, { ...curve.options, gasLimit });
txHashes.push(approveTx.hash);
await approveTx.wait();
}
}
return txHashes;
}
// coins can be either addresses or symbols
export const ensureAllowanceEstimateGas = async (coins: string[], amounts: (number | string)[], spender: string, isMax = true): Promise<number | number[]> => {
const coinAddresses = _getCoinAddresses(coins);
const decimals = _getCoinDecimals(coinAddresses);
const _amounts = amounts.map((a, i) => parseUnits(a, decimals[i]));
const address = curve.signerAddress;
const _allowance: bigint[] = await _getAllowance(coinAddresses, address, spender);
let gas = [0,0];
for (let i = 0; i < _allowance.length; i++) {
if (_allowance[i] < _amounts[i]) {
const contract = curve.contracts[coinAddresses[i]].contract;
const _approveAmount = isMax ? MAX_ALLOWANCE : _amounts[i];
if (_allowance[i] > curve.parseUnits("0")) {
let currentGas = smartNumber(await contract.approve.estimateGas(spender, curve.parseUnits("0"), curve.constantOptions));
// For some coins (crv for example ) we can't estimate the second tx gas (approve: 0 --> amount), so we assume it will cost the same amount of gas
if (typeof currentGas === "number") {
currentGas = currentGas * 2;
} else {
currentGas = currentGas.map((g) => g * 2)
}
gas = gasSum(gas, currentGas);
} else {
const currentGas = smartNumber(await contract.approve.estimateGas(spender, _approveAmount, curve.constantOptions));
gas = gasSum(gas, currentGas);
}
}
}
return getGasFromArray(gas);
}
// coins can be either addresses or symbols
export const ensureAllowance = async (coins: string[], amounts: (number | string)[], spender: string, isMax = true): Promise<string[]> => {
const coinAddresses = _getCoinAddresses(coins);
const decimals = _getCoinDecimals(coinAddresses);
const _amounts = amounts.map((a, i) => parseUnits(a, decimals[i]));
return await _ensureAllowance(coinAddresses, _amounts, spender, isMax)
}
export const getPoolIdBySwapAddress = (swapAddress: string): string => {
const poolsData = curve.getPoolsData();
const poolIds = Object.entries(poolsData).filter(([, poolData]) => poolData.swap_address.toLowerCase() === swapAddress.toLowerCase());
if (poolIds.length === 0) return "";
return poolIds[0][0];
}
export const _getRewardsFromApi = async (): Promise<IDict<IRewardFromApi[]>> => {
const network = curve.constants.NETWORK_NAME;
const allTypesExtendedPoolData = await _getAllPoolsFromApi(network, curve.isLiteChain);
const rewardsDict: IDict<IRewardFromApi[]> = {};
for (const extendedPoolData of allTypesExtendedPoolData) {
for (const pool of extendedPoolData.poolData) {
if (pool.gaugeAddress) {
rewardsDict[pool.gaugeAddress.toLowerCase()] = (pool.gaugeRewards ?? pool.gaugeExtraRewards ?? [])
.filter((r) => curve.chainId === 1 || r.tokenAddress.toLowerCase() !== curve.constants.COINS.crv);
}
}
}
return rewardsDict
}
const _usdRatesCache: IDict<{ rate: number, time: number }> = {}
export const _getUsdRate = async (assetId: string): Promise<number> => {
if (curve.chainId === 1 && assetId.toLowerCase() === '0x8762db106b2c2a0bccb3a80d1ed41273552616e8') return 0; // RSR
const pricesFromApi = await _getUsdPricesFromApi();
if (assetId.toLowerCase() in pricesFromApi) return pricesFromApi[assetId.toLowerCase()];
if (assetId === 'USD' || (curve.chainId === 137 && (assetId.toLowerCase() === curve.constants.COINS.am3crv.toLowerCase()))) return 1
let chainName = curve.isLiteChain? await curve.constants.NETWORK_NAME : {
1: 'ethereum',
10: 'optimistic-ethereum',
56: "binance-smart-chain",
100: 'xdai',
137: 'polygon-pos',
196: 'x-layer',
250: 'fantom',
252: 'fraxtal',
324: 'zksync',
1284: 'moonbeam',
2222: 'kava',
5000: 'mantle',
8453: 'base',
42220: 'celo',
43114: 'avalanche',
42161: 'arbitrum-one',
1313161554: 'aurora',
}[curve.chainId];
const nativeTokenName = curve.isLiteChain ? curve.constants?.API_CONSTANTS?.nativeTokenName:{
1: 'ethereum',
10: 'ethereum',
56: 'binancecoin',
100: 'xdai',
137: 'matic-network',
196: 'okb',
250: 'fantom',
252: 'frax-ether',
324: 'ethereum',
1284: 'moonbeam',
2222: 'kava',
5000: 'mantle',
8453: 'ethereum',
42220: 'celo',
43114: 'avalanche-2',
42161: 'ethereum',
1313161554: 'ethereum',
}[curve.chainId] as string;
if (chainName === undefined) {
throw Error('curve object is not initialized')
}
if (nativeTokenName === undefined) {
if(curve.isLiteChain && curve.constants.API_CONSTANTS?.wrappedNativeTokenAddress.toLowerCase() && curve.constants.API_CONSTANTS?.wrappedNativeTokenAddress.toLowerCase() in pricesFromApi) {
return pricesFromApi[curve.constants.API_CONSTANTS?.wrappedNativeTokenAddress.toLowerCase()];
} else {
throw Error('nativeTokenName not found')
}
}
assetId = {
'CRV': 'curve-dao-token',
'EUR': 'stasis-eurs',
'BTC': 'bitcoin',
'ETH': 'ethereum',
'LINK': 'link',
}[assetId.toUpperCase()] || assetId
assetId = isEth(assetId) ? nativeTokenName : assetId.toLowerCase();
// No EURT on Coingecko Polygon
if (curve.chainId === 137 && assetId.toLowerCase() === curve.constants.COINS.eurt) {
chainName = 'ethereum';
assetId = '0xC581b735A1688071A1746c968e0798D642EDE491'.toLowerCase(); // EURT Ethereum
}
// CRV
if (assetId.toLowerCase() === curve.constants.ALIASES.crv) {
assetId = 'curve-dao-token';
}
if(curve.isLiteChain && assetId.toLowerCase() === curve.constants.API_CONSTANTS?.wrappedNativeTokenAddress.toLowerCase()) {
assetId = nativeTokenName
}
if ((_usdRatesCache[assetId]?.time || 0) + 600000 < Date.now()) {
const url = [nativeTokenName, 'ethereum', 'bitcoin', 'link', 'curve-dao-token', 'stasis-eurs'].includes(assetId.toLowerCase()) ?
`https://api.coingecko.com/api/v3/simple/price?ids=${assetId}&vs_currencies=usd` :
`https://api.coingecko.com/api/v3/simple/token_price/${chainName}?contract_addresses=${assetId}&vs_currencies=usd`;
try {
const response = await fetch(url);
const data = await response.json() ?? {};
if (response.status === 200 && data[assetId]?.usd !== undefined) {
_usdRatesCache[assetId] = {
'rate': data[assetId].usd,
'time': Date.now(),
};
} else {
if (!curve.isLiteChain) {
console.warn(`Non-200 response for ${assetId}:`, response.status, data);
}
_usdRatesCache[assetId] = {
'rate': 0,
'time': Date.now(),
};
}
} catch (err: any) {
if (!curve.isLiteChain) {
console.error(`Error fetching USD rate for ${assetId}:`, err.message);
}
_usdRatesCache[assetId] = {
'rate': 0,
'time': Date.now(),
};
}
}
return _usdRatesCache[assetId]['rate']
}
export const getUsdRate = async (coin: string): Promise<number> => {
const [coinAddress] = _getCoinAddressesNoCheck(coin);
return await _getUsdRate(coinAddress);
}
export const getBaseFeeByLastBlock = async (): Promise<number> => {
const provider = curve.provider;
try {
const block = await provider.getBlock('latest');
if(!block) {
return 0.01
}
return Number(block.baseFeePerGas) / (10**9);
} catch (error: any) {
throw new Error(error)
}
}
export const getGasPrice = async () => {
const provider = curve.provider;
return Number((Number((await provider.getFeeData()).gasPrice) / 1e9).toFixed(2));
}
export const getGasPriceFromL1 = async (): Promise<number> => {
if(L2Networks.includes(curve.chainId) && curve.L1WeightedGasPrice) {
return curve.L1WeightedGasPrice + 1e9; // + 1 gwei
} else {
throw Error("This method exists only for L2 networks");
}
}
export const getGasPriceFromL2 = async (): Promise<number> => {
if(curve.chainId === 42161) {
return await getBaseFeeByLastBlock()
}
if(curve.chainId === 196) {
return await getGasPrice() // gwei
}
if(curve.chainId === 324) {
return await getGasPrice() // gwei
}
if(curve.chainId === 5000) {
return await getGasPrice() // gwei
}
if(L2Networks.includes(curve.chainId)) {
const gasPrice = await curve.contracts[curve.constants.ALIASES.gas_oracle_blob].contract.gasPrice({"gasPrice":"0x2000000"});
return Number(gasPrice);
} else {
throw Error("This method exists only for L2 networks");
}
}
export const getGasInfoForL2 = async (): Promise<Record<string, number | null>> => {
if(curve.chainId === 42161) {
const baseFee = await getBaseFeeByLastBlock()
return {
maxFeePerGas: Number(((baseFee * 1.1) + 0.01).toFixed(2)),
maxPriorityFeePerGas: 0.01,
}
} else if(curve.chainId === 196) {
const gasPrice = await getGasPrice()
return {
gasPrice,
}
} else if(curve.chainId === 324) {
const gasPrice = await getGasPrice()
return {
gasPrice,
}
} else if(curve.chainId === 5000) {
const baseFee = await getBaseFeeByLastBlock()
return {
maxFeePerGas: Number(((baseFee * 1.1) + 0.01).toFixed(2)),
maxPriorityFeePerGas: 0.01,
}
} else {
throw Error("This method exists only for L2 networks");
}
}
export const getTxCostsUsd = (ethUsdRate: number, gasPrice: number, gas: number | number[], gasPriceL1 = 0): number => {
if(Array.isArray(gas)) {
return ethUsdRate * ((gas[0] * gasPrice / 1e18) + (gas[1] * gasPriceL1 / 1e18));
} else {
return ethUsdRate * gas * gasPrice / 1e18;
}
}
export const getCurveLiteNetworks = async (): Promise<ICurveLiteNetwork[]> => {
return await _getCurveLiteNetworks()
}
export const getNetworkNameByChainId = (chainId: number, networks: ICurveLiteNetwork[]): string => {
const network = networks.find((network: ICurveLiteNetwork) => network.chainId === chainId);
return network ? network.id : "Unknown Network";
}
export const getNetworkConstants = async (chainId: IChainId | number): Promise<IDict<any>> => {
if (chainId in NETWORK_CONSTANTS) {
return { ...NETWORK_CONSTANTS[chainId], IS_LITE_CHAIN: false};
} else {
const NAME = getNetworkNameByChainId(chainId, await _getCurveLiteNetworks());
if (NAME === "Unknown Network") throw Error(`Wrong chain id: ${chainId}`);
return {... await _getLiteNetworksData(NAME), NAME, IS_LITE_CHAIN: true };
}
}
export const getTVL = async (chainId = curve.chainId): Promise<number> => {
const networkConstants = await getNetworkConstants(chainId);
const allTypesExtendedPoolData = await _getAllPoolsFromApi(networkConstants.NAME, networkConstants.IS_LITE_CHAIN);
return allTypesExtendedPoolData.reduce((sum, data) => sum + (data.tvl ?? data.tvlAll ?? 0), 0)
}
export const getVolumeApiController = async (network: INetworkName): Promise<IVolumeAndAPYs> => {
if(curve.isLiteChain && curve.chainId !== 146) {
throw Error('This method is not supported for the lite version')
}
if(volumeNetworks.getVolumes.includes(curve.chainId)) {
return await _getVolumes(network);
}
if(volumeNetworks.getFactoryAPYs.includes(curve.chainId)) {
return await _getFactoryAPYs(network);
}
if(volumeNetworks.getSubgraphData.includes(curve.chainId)) {
return await _getSubgraphData(network);
}
throw Error(`Can't get volume for network: ${network}`);
}
export const getVolume = async (chainId = curve.chainId): Promise<{ totalVolume: number, cryptoVolume: number, cryptoShare: number }> => {
if(curve.isLiteChain && curve.chainId !== 146) {
throw Error('This method is not supported for the lite version')
}
const networkConstants = await getNetworkConstants(chainId);
const { totalVolume, cryptoVolume, cryptoShare } = await getVolumeApiController(networkConstants.NAME);
return { totalVolume, cryptoVolume, cryptoShare }
}
export const _setContracts = (address: string, abi: any): void => {
curve.contracts[address] = {
abi,
contract: new Contract(address, abi, curve.signer || curve.provider),
multicallContract: new MulticallContract(address, abi),
}
}
// Find k for which x * k = target_x or y * k = target_y
// k = max(target_x / x, target_y / y)
// small_x = x * k
export const _get_small_x = (_x: bigint, _y: bigint, x_decimals: number, y_decimals: number): BigNumber => {
const target_x = BN(10 ** (x_decimals > 5 ? x_decimals - 3 : x_decimals));
const target_y = BN(10 ** (y_decimals > 5 ? y_decimals - 3 : y_decimals));
const x_int_BN = toBN(_x, 0);
const y_int_BN = toBN(_y, 0);
const k = BigNumber.max(target_x.div(x_int_BN), target_y.div(y_int_BN));
return BigNumber.min(x_int_BN.times(k), BN(10 ** x_decimals));
}
export const _get_price_impact = (
_x: bigint,
_y: bigint,
_small_x: bigint,
_small_y: bigint,
x_decimals: number,
y_decimals: number
): BigNumber => {
const x_BN = toBN(_x, x_decimals);
const y_BN = toBN(_y, y_decimals);
const small_x_BN = toBN(_small_x, x_decimals);
const small_y_BN = toBN(_small_y, y_decimals);
const rateBN = y_BN.div(x_BN);
const smallRateBN = small_y_BN.div(small_x_BN);
if (rateBN.gt(smallRateBN)) return BN(0);
return BN(1).minus(rateBN.div(smallRateBN)).times(100);
}
export const getCoinsData = async (...coins: string[] | string[][]): Promise<{name: string, symbol: string, decimals: number}[]> => {
if (coins.length == 1 && Array.isArray(coins[0])) coins = coins[0];
coins = coins as string[];
const coinAddresses = _getCoinAddressesNoCheck(coins);
console.log(coinAddresses);
const ethIndex = getEthIndex(coinAddresses);
if (ethIndex !== -1) {
coinAddresses.splice(ethIndex, 1);
}
const contractCalls = [];
for (const coinAddr of coinAddresses) {
const coinContract = new MulticallContract(coinAddr, ERC20Abi);
contractCalls.push(coinContract.name(), coinContract.symbol(), coinContract.decimals());
}
const _response = await curve.multicallProvider.all(contractCalls);
if (ethIndex !== -1) {
_response.splice(ethIndex * 2, 0, ...['Ethereum', 'ETH', 18]);
}
const res: {name: string, symbol: string, decimals: number}[] = [];
coins.forEach(() => {
res.push({
name: _response.shift() as string,
symbol: _response.shift() as string,
decimals: Number(curve.formatUnits(_response.shift() as string, 0)),
})
});
return res;
}
export const hasDepositAndStake = (): boolean => "deposit_and_stake" in curve.constants.ALIASES;
export const hasRouter = (): boolean => "router" in curve.constants.ALIASES;
export const findAbiFunction = (abi: Abi, methodName: string) =>
abi.filter((item) => item.type == 'function' && item.name === methodName) as AbiFunction[]
export const getCountArgsOfMethodByAbi = (abi: Abi, methodName: string): number => findAbiFunction(abi, methodName)[0]?.inputs.length ?? -1
export const findAbiSignature = (abi: Abi, methodName: string, signature: string) =>
findAbiFunction(abi, methodName).find((func) => func.inputs.map((i) => `${i.type}`).join(',') == signature)
export const getPoolName = (name: string): string => {
const separatedName = name.split(": ")
if(separatedName.length > 1) {
return separatedName[1].trim()
} else {
return separatedName[0].trim()
}
}
export const isStableNgPool = (name: string): boolean => name.includes('factory-stable-ng')
export const assetTypeNameHandler = (assetTypeName: string): REFERENCE_ASSET => {
if (assetTypeName.toUpperCase() === 'UNKNOWN') {
return 'OTHER';
} else {
return assetTypeName.toUpperCase() as REFERENCE_ASSET;
}
}
export const getBasePools = async (): Promise<IBasePoolShortItem[]> => {
const factoryContract = curve.contracts[curve.constants.ALIASES['stable_ng_factory']].contract;
const factoryMulticallContract = curve.contracts[curve.constants.ALIASES['stable_ng_factory']].multicallContract;
const basePoolCount = Number(curve.formatUnits(await factoryContract.base_pool_count(), 0));
const calls = [];
for (let i = 0; i < basePoolCount; i++) {
calls.push(factoryMulticallContract.base_pool_list(i));
}
const basePoolList = (await curve.multicallProvider.all(calls) as string[]).map((item: string) => item.toLowerCase());
const pools = {...curve.constants.STABLE_NG_FACTORY_POOLS_DATA, ...curve.constants.FACTORY_POOLS_DATA, ...curve.constants.POOLS_DATA};
const basePoolIds = Object.keys(pools).filter((item: string) => basePoolList.includes(pools[item].swap_address));
return basePoolIds.map((poolId) => {
const pool = getPool(poolId);
return {
id: poolId,
name: pool.name,
pool: pool.address,
token: pool.lpToken,
coins: pool.underlyingCoinAddresses,
}
})
}
export function log(fnName: string, ...args: unknown[]): void {
if (process.env.NODE_ENV === 'development') {
console.log(`curve-js@${new Date().toISOString()} -> ${fnName}:`, ...args)
}
}
export function runWorker<In extends { type: string }, Out>(code: string, syncFn: () => ((val: In) => Out) | undefined, inputData: In, timeout = 30000): Promise<Out> {
if (typeof Worker === 'undefined') {
// in nodejs run worker in main thread
return Promise.resolve(syncFn()!(inputData));
}
const blob = new Blob([code], { type: 'application/javascript' });
const blobUrl = URL.createObjectURL(blob);
const worker = new Worker(blobUrl, {type: 'module'});
return new Promise<Out>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Timeout')), timeout);
worker.onerror = (e) => {
clearTimeout(timer);
console.error(code, inputData, e);
reject(e);
};
worker.onmessage = (e) => {
const {type, result} = e.data;
if (type === inputData.type) {
clearTimeout(timer);
resolve(result);
// console.log(code, inputData, result, start - Date.now());
}
};
worker.postMessage(inputData);
}).finally(() => {
worker.terminate();
});
}
export const PERIODS = {
DAY: 86400,
WEEK: 604800, // 7 * 86400
MONTH: 2592000, // 30 * 86400
YEAR: 31536000, // 365 * 86400
};