-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
453 lines (391 loc) · 11.5 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
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
import Sdk from './sdk'
import * as ethers from 'ethers'
import config from './config'
import { allTokens } from './tokenLists'
//import { pairs } from './pairLists'
import { fetchSwapForPair } from './theGraph'
import { getPriceFromSwap, getActionFromSwap } from './price'
import { pairs as monoswapPairs } from './monoswapPairs'
const INFURA_ID = config.get('ETHEREUM_NODE_ID')
export const pairs = monoswapPairs
export function getProvider (network) {
if (network === 'xdaiChain') {
return new ethers.providers.JsonRpcProvider(
config.get('XDAI_NODE_HTTP_URL').toString()
)
}
return new ethers.providers.InfuraProvider(network, INFURA_ID)
}
export function getNetworkFromChainId (chainId: number) {
if (chainId === 1) {
return 'mainnet'
} else if (chainId === 100) {
return 'xdaiChain'
} else if (chainId === 3) {
return 'ropstem'
} else if (chainId === 56) {
return 'bsc'
} else {
throw new Error('Invalid chainId')
}
}
export function getOurTokenList () {
return allTokens
}
export async function getTokenPrices (
symbol: string,
baseSymbols: string[],
chainId: number
) {
return new Promise((resolve: (prices: number[]) => void, reject) => {
const pricePromises = baseSymbols.map(base =>
getTokenPrice(symbol, base, chainId)
)
Promise.all(pricePromises)
.then((prices: number[]) => {
resolve(prices)
})
.catch(reject)
})
}
export async function getTokenPricesFromAddress (
address: string,
baseSymbols: string[],
chainId: number
) {
return new Promise((resolve: (prices: number[]) => void, reject) => {
const pricePromises = baseSymbols.map(base =>
getTokenPriceFromAddress(address, base, chainId)
)
Promise.all(pricePromises)
.then((prices: number[]) => {
resolve(prices)
})
.catch(reject)
})
}
/**
*
* @param symbol 'MKR'
* @param baseSymbol 'USDT'
* @param chainId 1
* @returns
*/
export async function getTokenPriceFromAddress (
address: string,
baseSymbol: string,
chainId: number,
symbol: string = 'Dunno'
) {
try {
const sdk = new Sdk(chainId)
const token = await getTokenFromAddress(address, chainId)
const baseTokenFromList = await getTokenFromList(baseSymbol, chainId)
//const baseToken = await getTokenFromAddress(address, chainId)
const baseToken = await sdk.getSwapToken(baseTokenFromList)
if (!baseToken)
throw Error(`BaseSymbol ${baseSymbol} not found in our token list`)
if (address === baseToken.address) return 1
const provider = getProvider(getNetworkFromChainId(chainId))
const pair = await sdk.getPair(token, baseToken, provider, chainId)
return await sdk.getPrice(pair, token, chainId)
} catch (error) {
console.log(
`Warning, no price for: ---> : ${address}, ${baseSymbol} - ${chainId}`
)
// There may be no pair so return 0
// console.error(error)
// throw new Error(error)
}
}
/**
* Get Token details
*/
export function getTokenFromList (symbol: string, chainId: number) {
const inSymbol =
symbol.toUpperCase() === 'ETH'
? 'WETH'
: symbol.toUpperCase() === 'XDAI'
? 'WXDAI'
: symbol.toUpperCase()
const token = allTokens.find(
o => o.symbol === inSymbol && o.chainId === chainId
)
if (!token)
throw new Error(`Token ${inSymbol} not found for chainId ${chainId}`)
return token
}
function isTestPrice (symbol, baseSymbol) {
return (
(symbol === 'ETH' && baseSymbol === 'USDT') ||
(symbol === 'ETH' && baseSymbol === 'ETH')
)
}
function isETHisETH (symbol, baseSymbol) {
return symbol === 'ETH' && baseSymbol === 'ETH'
}
function isXDAIisXDAI (symbol, baseSymbol) {
return (
(symbol === 'XDAI' || symbol === 'WXDAI') &&
(baseSymbol === 'XDAI' || baseSymbol === 'WXDAI')
)
}
function getTestPrice (symbol, baseSymbol, chainId) {
if (symbol === 'ETH' && baseSymbol === 'USDT') return 2000
if (symbol === 'ETH' && baseSymbol === 'ETH') return 1
throw Error('No test price, this should not happen')
}
function getETHisETHPrice () {
return 1
}
export async function getPairFromAddresses (
addresses: string[],
chainId: number
) {
const sdk = new Sdk(chainId)
const tokensPromises = addresses.map(
async address => await getTokenFromAddress(address, chainId)
)
const tokens = await Promise.all(tokensPromises)
const pair = await sdk.getPair(
tokens[0],
tokens[1],
getProvider(getNetworkFromChainId(chainId)),
chainId
)
return pair
}
export async function getPairFromSymbols (
symbol: string,
baseSymbol: string,
chainId: number
) {
const sdk = new Sdk(chainId)
const token = await sdk.getSwapToken(getTokenFromList(symbol, chainId))
if (!token) throw Error(`Symbol ${symbol} not found in our token list`)
const baseToken = await sdk.getSwapToken(
getTokenFromList(baseSymbol, chainId)
)
if (!baseToken)
throw Error(`BaseSymbol ${baseSymbol} not found in our token list`)
if (token.address === baseToken.address) return 1
try {
const pair = await sdk.getPair(
token,
baseToken,
getProvider(getNetworkFromChainId(chainId)),
chainId
)
return pair
} catch (e) {
return null
}
}
export async function getTokenPriceFromSdk (pair, token, chainId: number) {
try {
const sdk = new Sdk(chainId)
return sdk.getPrice(pair, token, chainId)
} catch (error) {
console.error(error)
throw new Error(error)
}
}
export async function getTokenPriceFromEthPrice (
fromSymbol: string,
toSymbol: string,
chainId: number,
timestamp: number
) {
const sdk = new Sdk(chainId)
let pair
const token = await sdk.getSwapToken(getTokenFromList(fromSymbol, chainId))
try {
pair = await getPairFromSymbols(fromSymbol, 'ETH', chainId)
const ethPerToken = await getTokenPriceFromSdk(pair, token, chainId)
if (toSymbol === 'USD' || toSymbol === 'USDT' || toSymbol === 'USDC') {
const usdPerToken = await convertPriceEthToUsd(ethPerToken, timestamp)
return usdPerToken
} else {
throw new Error(
`Can't convert symbol ${fromSymbol} to base symbol ${toSymbol}`
)
}
} catch (e) {
throw new Error(
` getTokenPriceFromEthPrice can't convert symbol ${fromSymbol} to ${toSymbol} sdkPairs is ${pair}`
)
}
}
export async function getTokenPrice (
symbol: string,
baseSymbol: string,
chainId: number
) {
try {
if (isETHisETH(symbol, baseSymbol)) return getETHisETHPrice()
if (isXDAIisXDAI(symbol, baseSymbol)) return 1
const sdk = new Sdk(chainId)
const pair = await getPairFromSymbols(symbol, baseSymbol, chainId)
if (pair) {
const token = await sdk.getSwapToken(getTokenFromList(symbol, chainId))
return getTokenPriceFromSdk(pair, token, chainId)
} else {
const nowStamp = Date.now()
const price = getTokenPriceFromEthPrice(
symbol,
baseSymbol,
chainId,
nowStamp
)
return price
}
} catch (error) {
console.error(error)
throw new Error(error)
}
}
export async function convertPriceUsdToEth (priceInUsd, timeStamp) {
const priceEthUsdAtTime: number = await getPriceAtTime(
'ETH',
'USDT',
timeStamp,
1
)
const usdPerEth = 1 / priceEthUsdAtTime
const priceEth = priceInUsd / usdPerEth
return priceEth
}
export async function convertPriceEthToUsd (priceInEth, timeStamp) {
const priceEthUsdAtTime: number = await getPriceAtTime(
'ETH',
'USDT',
timeStamp,
1
)
const usdPerEth = 1 / priceEthUsdAtTime
const priceEth = priceInEth * usdPerEth
return priceEth
}
/**
*
* @param symbol 'MKR'
* @param baseSymbol 'USDT'
* @param chainId 1
* @returns
*/
export async function getTokenExecutionPriceFromAddress (
address: string,
baseSymbol: string,
chainId: number,
amount: number
) {
try {
const sdk = new Sdk(chainId)
const token = await getTokenFromAddress(address, chainId)
if (!token)
throw Error(
`Can't find a token for address ${address} not found in our token list`
)
const baseToken = await getTokenFromAddress(address, chainId)
if (!baseToken)
throw Error(`BaseSymbol ${baseSymbol} not found in our token list`)
if (token.address === baseToken.address) return 1
const provider = getProvider(getNetworkFromChainId(chainId))
const pair = await sdk.getPair(token, baseToken, provider, chainId)
const price = sdk.getExecutionPrice(pair, baseToken, amount) // NO await?
return price
// return sdk.getPrice(pair, token, chainId)
} catch (error) {
console.error(error)
throw new Error(error)
}
}
export async function getPriceAtTime (
from: string,
to: string,
timestamp: number,
chainId: number
) {
const sdk = new Sdk(chainId)
const pair = await getPairFromSymbols(from, to, chainId)
if (!pair)
throw new Error(
`No pair found from ${from} to ${to} and chainID ${chainId}`
)
const quoteToken = pair.tokenAmounts[0].token.symbol === from ? 'from' : 'to'
///console.log(`quoteToken ---> : ${quoteToken}`)
// console.log(`pair : ${JSON.stringify(pair, null, 2)}`)
// console.log(`pair.address ---> : ${pair.liquidityToken.address}`)
// console.log(`timestamp ---> : ${timestamp}`)
// console.log(`chainId ---> : ${chainId}`)
const swap = await fetchSwapForPair(
pair.liquidityToken.address.toLowerCase(),
Math.round(timestamp),
chainId
)
const price = getPriceFromSwap(swap, to)
// const action = getActionFromSwap(swap, to)
// let action: string = ''
// let price: number = 0
// if (Number(swap.amount0In) > 0) {
// action = 'buyEth ' + Number(swap.amount0In)
// price = Number(swap.amount0In) / Number(swap.amount1Out)
// } else if (Number(swap.amount0Out) > 0) {
// action = 'sellEth ' + Number(swap.amount0Out)
// price = Number(swap.amount0Out) / Number(swap.amount1In)
// } else {
// throw new Error('Should not happen')
// }
return quoteToken === 'from' ? price : 1 / price
}
async function getTokenFromAddress (address: string, chainId: number) {
const sdk = new Sdk(chainId)
//const tokenFromList = getTokenFromList(symbol, chainId)
const tokenFromList = allTokens.find(
o =>
o.address.toLowerCase() === address.toLowerCase() && o.chainId === chainId
)
//console.log(`tokenFromList : ${JSON.stringify(tokenFromList, null, 2)}`)
let token
if (tokenFromList) {
token = await sdk.getSwapToken(tokenFromList)
} else {
console.error(`WARNING unknown address ${address}`)
token = await sdk.createToken(1, address, 'DUNNO', 'dont know', 18)
}
return token
}
/**
*
* @param symbol 'MKR'
* @param baseSymbol 'USDT'
* @param chainId 1
* @returns
*/
export async function getTokenExecutionPrice (
symbol: string,
baseSymbol: string,
chainId: number,
amount: number
) {
try {
const sdk = new Sdk(chainId)
const token = await sdk.getSwapToken(getTokenFromList(symbol, chainId))
if (!token) throw Error(`Symbol ${symbol} not found in our token list`)
const baseToken = await sdk.getSwapToken(
getTokenFromList(baseSymbol, chainId)
)
if (!baseToken)
throw Error(`BaseSymbol ${baseSymbol} not found in our token list`)
if (token.address === baseToken.address) return 1
const provider = getProvider(getNetworkFromChainId(chainId))
const pair = await sdk.getPair(token, baseToken, provider, chainId)
const price = sdk.getExecutionPrice(pair, baseToken, amount) // NO await?
//console.log(`xprice : ${JSON.stringify(price, null, 2)}`)
return price
// return sdk.getPrice(pair, token, chainId)
} catch (error) {
console.error(error)
throw new Error(error)
}
}