-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.ts
204 lines (194 loc) · 7.03 KB
/
index.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
import type {
CalleeNames,
CalleeFunctions,
MarketData,
CollateralConfig,
CollateralSymbol,
Pool,
PriceWithPools,
GetCalleeDataParams,
} from '../types';
import memoizee from 'memoizee';
import BigNumber from '../bignumber';
import UniswapV2CalleeDai from './UniswapV2CalleeDai';
import UniswapV2LpTokenCalleeDai from './UniswapV2LpTokenCalleeDai';
import WstETHCurveUniv3Callee from './WstETHCurveUniv3Callee';
import CurveLpTokenUniv3Callee from './CurveLpTokenUniv3Callee';
import UniswapV3Callee from './UniswapV3Callee';
import OneInchCallee from './OneInchCallee';
import rETHCurveUniv3Callee from './rETHCurveUniv3Callee';
import UniswapV2LockstakeCallee from './UniswapV2LockstakeCallee';
import { getCollateralConfigByType, getCollateralConfigBySymbol } from '../constants/COLLATERALS';
import { routeToPool } from './helpers/pools';
import { getOneInchMarketData } from './helpers/oneInch';
export const MARKET_DATA_RECORDS_CACHE_MS = 29 * 1000;
const allCalleeFunctions: Record<CalleeNames, CalleeFunctions> = {
UniswapV2CalleeDai,
UniswapV2LpTokenCalleeDai,
WstETHCurveUniv3Callee,
CurveLpTokenUniv3Callee,
UniswapV3Callee,
rETHCurveUniv3Callee,
OneInchCallee,
UniswapV2LockstakeCallee,
};
export const getCalleeData = async function (
network: string,
collateralType: string,
marketId: string,
profitAddress: string,
params?: GetCalleeDataParams
): Promise<string> {
const collateral = getCollateralConfigByType(collateralType);
const marketData = collateral.exchanges[marketId];
if (!marketData || !marketData.callee || !allCalleeFunctions[marketData.callee]) {
throw new Error(`Unsupported collateral type "${collateralType}"`);
}
return await allCalleeFunctions[marketData.callee].getCalleeData(
network,
collateral,
marketId,
profitAddress,
params
);
};
export const getPools = async (
network: string,
collateral: CollateralConfig,
marketId: string
): Promise<Pool[] | undefined> => {
const calleeConfig = collateral.exchanges[marketId];
if ('route' in calleeConfig) {
return await routeToPool(network, calleeConfig.route, collateral.symbol);
}
if ('automaticRouter' in calleeConfig) {
throw new Error('This function should not be called for callees whre autorouter is enabled');
}
return undefined;
};
const _getMarketDataById = async function (
network: string,
collateral: CollateralConfig,
marketId: string,
amount: BigNumber = new BigNumber('1')
): Promise<MarketData> {
const calleeConfig = collateral.exchanges[marketId];
if (!allCalleeFunctions[calleeConfig?.callee]) {
throw new Error(`Unsupported callee "${calleeConfig?.callee}" for collateral symbol "${collateral.symbol}"`);
}
let marketPriceResult: { marketPrice: PriceWithPools; errorMessage?: string };
try {
const marketPrice = await allCalleeFunctions[calleeConfig.callee].getMarketPrice(
network,
collateral,
marketId,
amount
);
marketPriceResult = { marketPrice };
} catch (error: any) {
marketPriceResult = {
marketPrice: { price: new BigNumber(NaN), pools: undefined },
errorMessage: error?.message,
};
}
if (calleeConfig.callee === 'OneInchCallee') {
const apiExchangeData = await getOneInchMarketData(network, collateral, amount, marketId);
return {
...calleeConfig,
marketUnitPrice: marketPriceResult.marketPrice.price,
errorMessage: marketPriceResult.errorMessage,
oneInch: apiExchangeData,
};
}
const { marketPrice } = marketPriceResult;
const marketUnitPrice = marketPrice.price;
if (calleeConfig.callee !== 'UniswapV2LpTokenCalleeDai' && marketPrice.pools) {
return {
...calleeConfig,
marketUnitPrice: marketUnitPrice ? marketUnitPrice : new BigNumber(NaN),
pools: marketPrice.pools,
};
}
if (calleeConfig.callee === 'UniswapV2LpTokenCalleeDai') {
return {
...calleeConfig,
marketUnitPrice: marketUnitPrice ? marketUnitPrice : new BigNumber(NaN),
};
}
throw new Error('No pools found where expected');
};
export const getMarketDataById = memoizee(_getMarketDataById, {
promise: true,
maxAge: MARKET_DATA_RECORDS_CACHE_MS,
length: 4,
normalizer: (args: any[]) => {
return JSON.stringify(args);
},
});
export const getMarketDataRecords = async function (
network: string,
collateralSymbol: CollateralSymbol,
amount: BigNumber = new BigNumber('1'),
useAutoRouter = false
): Promise<Record<string, MarketData>> {
const collateral = getCollateralConfigBySymbol(collateralSymbol);
let marketDataRecords = {};
for (const [marketId, exchange] of Object.entries(collateral.exchanges)) {
let marketData: MarketData;
try {
// turn off autorouter during tests because it takes too long
if (
(process.env.NODE_ENV === 'test' || !useAutoRouter) &&
'automaticRouter' in exchange &&
exchange.automaticRouter
) {
marketData = {
marketUnitPrice: new BigNumber(NaN),
pools: [], // dummy value: MarketData requires either a pool or tokens
};
} else {
marketData = await getMarketDataById(network, collateral, marketId, amount);
}
} catch (error: any) {
marketData = {
errorMessage: error?.message,
marketUnitPrice: new BigNumber(NaN),
pools: [], // dummy value: MarketData requires either a pool or tokens
};
}
marketDataRecords = {
...marketDataRecords,
[marketId]: {
...marketData,
},
};
}
return marketDataRecords;
};
export const getBestMarketId = async function (marketDataRecords: Record<string, MarketData>): Promise<string> {
const marketDataRecordsSorted = Object.entries(marketDataRecords);
marketDataRecordsSorted.sort((a, b) => {
// push NaNs to the end
if (a[1].marketUnitPrice.isNaN() && b[1].marketUnitPrice.isNaN()) {
return 1;
}
if (a[1].marketUnitPrice.isNaN()) {
return 1;
}
if (b[1].marketUnitPrice.isNaN()) {
return -1;
}
return a[1].marketUnitPrice.minus(b[1].marketUnitPrice).multipliedBy(-1).toNumber();
});
return marketDataRecordsSorted[0][0];
};
export const getMarketPrice = async function (
network: string,
collateralSymbol: string,
amount: BigNumber = new BigNumber('1')
): Promise<BigNumber> {
const marketDataRecords = await getMarketDataRecords(network, collateralSymbol, amount);
const bestMarketId = await getBestMarketId(marketDataRecords);
return marketDataRecords[bestMarketId].marketUnitPrice;
};
export default allCalleeFunctions;