forked from hummingbot/gateway
-
Notifications
You must be signed in to change notification settings - Fork 2
/
uniswap.ts
491 lines (461 loc) · 14.5 KB
/
uniswap.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
import { UniswapishPriceError } from '../../services/error-handler';
import { isFractionString } from '../../services/validators';
import { UniswapConfig } from './uniswap.config';
import routerAbi from './uniswap_v2_router_abi.json';
import {
ContractInterface,
ContractTransaction,
} from '@ethersproject/contracts';
import { AlphaRouter } from '@uniswap/smart-order-router';
import { Trade, SwapRouter } from '@uniswap/router-sdk';
import {
FeeAmount,
MethodParameters,
Pool,
SwapQuoter,
Trade as UniswapV3Trade,
Route,
FACTORY_ADDRESS,
} from '@uniswap/v3-sdk';
import { abi as IUniswapV3PoolABI } from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json';
import { abi as IUniswapV3FactoryABI } from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Factory.sol/IUniswapV3Factory.json';
import {
Token,
CurrencyAmount,
Percent,
TradeType,
Currency,
} from '@uniswap/sdk-core';
import {
BigNumber,
Transaction,
Wallet,
Contract,
utils,
constants,
} from 'ethers';
import { logger } from '../../services/logger';
import { percentRegexp } from '../../services/config-manager-v2';
import { Ethereum } from '../../chains/ethereum/ethereum';
import { Polygon } from '../../chains/polygon/polygon';
import { ExpectedTrade, Uniswapish } from '../../services/common-interfaces';
import { getAddress } from 'ethers/lib/utils';
export class Uniswap implements Uniswapish {
private static _instances: { [name: string]: Uniswap };
private chain: Ethereum | Polygon;
private _alphaRouter: AlphaRouter;
private _router: string;
private _routerAbi: ContractInterface;
private _gasLimitEstimate: number;
private _ttl: number;
private _maximumHops: number;
private chainId;
private tokenList: Record<string, Token> = {};
private _ready: boolean = false;
private readonly _useRouter: boolean;
private readonly _feeTier: FeeAmount;
private readonly _quoterContractAddress: string;
private constructor(chain: string, network: string) {
const config = UniswapConfig.config;
if (chain === 'ethereum') {
this.chain = Ethereum.getInstance(network);
} else {
this.chain = Polygon.getInstance(network);
}
this.chainId = this.chain.chainId;
this._ttl = UniswapConfig.config.ttl;
this._maximumHops = UniswapConfig.config.maximumHops;
this._alphaRouter = new AlphaRouter({
chainId: this.chainId,
provider: this.chain.provider,
});
this._routerAbi = routerAbi.abi;
this._gasLimitEstimate = UniswapConfig.config.gasLimitEstimate;
this._router = config.uniswapV3SmartOrderRouterAddress(network);
if (config.useRouter === false && config.feeTier == null) {
throw new Error('Must specify fee tier if not using router');
}
if (config.useRouter === false && config.quoterContractAddress == null) {
throw new Error(
'Must specify quoter contract address if not using router'
);
}
this._useRouter = config.useRouter ?? true;
this._feeTier = config.feeTier
? FeeAmount[config.feeTier as keyof typeof FeeAmount]
: FeeAmount.MEDIUM;
this._quoterContractAddress = config.quoterContractAddress(network);
}
public static getInstance(chain: string, network: string): Uniswap {
if (Uniswap._instances === undefined) {
Uniswap._instances = {};
}
if (!(chain + network in Uniswap._instances)) {
Uniswap._instances[chain + network] = new Uniswap(chain, network);
}
return Uniswap._instances[chain + network];
}
/**
* Given a token's address, return the connector's native representation of
* the token.
*
* @param address Token address
*/
public getTokenByAddress(address: string): Token {
return this.tokenList[getAddress(address)];
}
public async init() {
if (!this.chain.ready()) {
await this.chain.init();
}
for (const token of this.chain.storedTokenList) {
this.tokenList[token.address] = new Token(
this.chainId,
token.address,
token.decimals,
token.symbol,
token.name
);
}
this._ready = true;
}
public ready(): boolean {
return this._ready;
}
/**
* Router address.
*/
public get router(): string {
return this._router;
}
/**
* AlphaRouter instance.
*/
public get alphaRouter(): AlphaRouter {
return this._alphaRouter;
}
/**
* Router smart contract ABI.
*/
public get routerAbi(): ContractInterface {
return this._routerAbi;
}
/**
* Default gas limit used to estimate gasCost for swap transactions.
*/
public get gasLimitEstimate(): number {
return this._gasLimitEstimate;
}
/**
* Default time-to-live for swap transactions, in seconds.
*/
public get ttl(): number {
return this._ttl;
}
/**
* Default maximum number of hops for to go through for a swap transactions.
*/
public get maximumHops(): number {
return this._maximumHops;
}
/**
* Gets the allowed slippage percent from the optional parameter or the value
* in the configuration.
*
* @param allowedSlippageStr (Optional) should be of the form '1/10'.
*/
public getAllowedSlippage(allowedSlippageStr?: string): Percent {
if (allowedSlippageStr != null && isFractionString(allowedSlippageStr)) {
const fractionSplit = allowedSlippageStr.split('/');
return new Percent(fractionSplit[0], fractionSplit[1]);
}
const allowedSlippage = UniswapConfig.config.allowedSlippage;
const nd = allowedSlippage.match(percentRegexp);
if (nd) return new Percent(nd[1], nd[2]);
throw new Error(
'Encountered a malformed percent string in the config for ALLOWED_SLIPPAGE.'
);
}
/**
* Given the amount of `baseToken` to put into a transaction, calculate the
* amount of `quoteToken` that can be expected from the transaction.
*
* This is typically used for calculating token sell prices.
*
* @param baseToken Token input for the transaction
* @param quoteToken Output from the transaction
* @param amount Amount of `baseToken` to put into the transaction
*/
async estimateSellTrade(
baseToken: Token,
quoteToken: Token,
amount: BigNumber,
allowedSlippage?: string
): Promise<ExpectedTrade> {
const nativeTokenAmount: CurrencyAmount<Token> =
CurrencyAmount.fromRawAmount(baseToken, amount.toString());
logger.info(
`Fetching trade data for ${baseToken.address}-${quoteToken.address}.`
);
if (this._useRouter) {
const route = await this._alphaRouter.route(
nativeTokenAmount,
quoteToken,
TradeType.EXACT_INPUT,
undefined,
{
maxSwapsPerPath: this.maximumHops,
}
);
if (!route) {
throw new UniswapishPriceError(
`priceSwapIn: no trade pair found for ${baseToken.address} to ${quoteToken.address}.`
);
}
logger.info(
`Best trade for ${baseToken.address}-${quoteToken.address}: ` +
`${route.trade.executionPrice.toFixed(6)}` +
`${baseToken.symbol}.`
);
const expectedAmount = route.trade.minimumAmountOut(
this.getAllowedSlippage(allowedSlippage)
);
return { trade: route.trade, expectedAmount };
} else {
const pool = await this.getPool(baseToken, quoteToken, this._feeTier);
if (!pool) {
throw new UniswapishPriceError(
`priceSwapIn: no trade pair found for ${baseToken.address} to ${quoteToken.address}.`
);
}
const swapRoute = new Route([pool], baseToken, quoteToken);
const quotedAmount = await this.getQuote(
swapRoute,
quoteToken,
nativeTokenAmount,
TradeType.EXACT_INPUT
);
const trade = UniswapV3Trade.createUncheckedTrade({
route: swapRoute,
inputAmount: nativeTokenAmount,
outputAmount: quotedAmount,
tradeType: TradeType.EXACT_INPUT,
});
logger.info(
`Best trade for ${baseToken.address}-${quoteToken.address}: ` +
`${trade.executionPrice.toFixed(6)}` +
`${baseToken.symbol}.`
);
const expectedAmount = trade.minimumAmountOut(
this.getAllowedSlippage(allowedSlippage)
);
return { trade, expectedAmount };
}
}
/**
* Given the amount of `baseToken` desired to acquire from a transaction,
* calculate the amount of `quoteToken` needed for the transaction.
*
* This is typically used for calculating token buy prices.
*
* @param quoteToken Token input for the transaction
* @param baseToken Token output from the transaction
* @param amount Amount of `baseToken` desired from the transaction
*/
async estimateBuyTrade(
quoteToken: Token,
baseToken: Token,
amount: BigNumber,
allowedSlippage?: string
): Promise<ExpectedTrade> {
const nativeTokenAmount: CurrencyAmount<Token> =
CurrencyAmount.fromRawAmount(baseToken, amount.toString());
logger.info(
`Fetching pair data for ${quoteToken.address}-${baseToken.address}.`
);
if (this._useRouter) {
const route = await this._alphaRouter.route(
nativeTokenAmount,
quoteToken,
TradeType.EXACT_OUTPUT,
undefined,
{
maxSwapsPerPath: this.maximumHops,
}
);
if (!route) {
throw new UniswapishPriceError(
`priceSwapOut: no trade pair found for ${quoteToken.address} to ${baseToken.address}.`
);
}
logger.info(
`Best trade for ${quoteToken.address}-${baseToken.address}: ` +
`${route.trade.executionPrice.invert().toFixed(6)} ` +
`${baseToken.symbol}.`
);
const expectedAmount = route.trade.maximumAmountIn(
this.getAllowedSlippage(allowedSlippage)
);
return { trade: route.trade, expectedAmount };
} else {
const pool = await this.getPool(quoteToken, baseToken, this._feeTier);
if (!pool) {
throw new UniswapishPriceError(
`priceSwapOut: no trade pair found for ${quoteToken.address} to ${baseToken.address}.`
);
}
const swapRoute = new Route([pool], quoteToken, baseToken);
const quotedAmount = await this.getQuote(
swapRoute,
quoteToken,
nativeTokenAmount,
TradeType.EXACT_OUTPUT
);
const trade = UniswapV3Trade.createUncheckedTrade({
route: swapRoute,
inputAmount: quotedAmount,
outputAmount: nativeTokenAmount,
tradeType: TradeType.EXACT_OUTPUT,
});
logger.info(
`Best trade for ${baseToken.address}-${quoteToken.address}: ` +
`${trade.executionPrice.invert().toFixed(6)}` +
`${baseToken.symbol}.`
);
const expectedAmount = trade.maximumAmountIn(
this.getAllowedSlippage(allowedSlippage)
);
return { trade, expectedAmount };
}
}
/**
* Given a wallet and a Uniswap trade, try to execute it on blockchain.
*
* @param wallet Wallet
* @param trade Expected trade
* @param gasPrice Base gas price, for pre-EIP1559 transactions
* @param uniswapRouter Router smart contract address
* @param ttl How long the swap is valid before expiry, in seconds
* @param _abi Router contract ABI
* @param gasLimit Gas limit
* @param nonce (Optional) EVM transaction nonce
* @param maxFeePerGas (Optional) Maximum total fee per gas you want to pay
* @param maxPriorityFeePerGas (Optional) Maximum tip per gas you want to pay
*/
async executeTrade(
wallet: Wallet,
trade: Trade<Currency, Currency, TradeType>,
gasPrice: number,
uniswapRouter: string,
ttl: number,
_abi: ContractInterface,
gasLimit: number,
nonce?: number,
maxFeePerGas?: BigNumber,
maxPriorityFeePerGas?: BigNumber,
allowedSlippage?: string
): Promise<Transaction> {
const methodParameters: MethodParameters = SwapRouter.swapCallParameters(
trade,
{
deadlineOrPreviousBlockhash: Math.floor(Date.now() / 1000 + ttl),
recipient: wallet.address,
slippageTolerance: this.getAllowedSlippage(allowedSlippage),
}
);
return this.chain.nonceManager.provideNonce(
nonce,
wallet.address,
async (nextNonce) => {
let tx: ContractTransaction;
if (maxFeePerGas !== undefined || maxPriorityFeePerGas !== undefined) {
tx = await wallet.sendTransaction({
data: methodParameters.calldata,
to: uniswapRouter,
gasLimit: gasLimit.toFixed(0),
value: methodParameters.value,
nonce: nextNonce,
maxFeePerGas,
maxPriorityFeePerGas,
});
} else {
tx = await wallet.sendTransaction({
data: methodParameters.calldata,
to: uniswapRouter,
gasPrice: (gasPrice * 1e9).toFixed(0),
gasLimit: gasLimit.toFixed(0),
value: methodParameters.value,
nonce: nextNonce,
});
}
logger.info(JSON.stringify(tx));
return tx;
}
);
}
private async getPool(
tokenA: Token,
tokenB: Token,
feeTier: FeeAmount
): Promise<Pool | null> {
const uniswapFactory = new Contract(
FACTORY_ADDRESS,
IUniswapV3FactoryABI,
this.chain.provider
);
// Use Uniswap V3 factory to get pool address instead of `Pool.getAddress` to check if pool exists.
const poolAddress = await uniswapFactory.getPool(
tokenA.address,
tokenB.address,
feeTier
);
if (poolAddress === constants.AddressZero) {
return null;
}
const poolContract = new Contract(
poolAddress,
IUniswapV3PoolABI,
this.chain.provider
);
const [liquidity, slot0] = await Promise.all([
poolContract.liquidity(),
poolContract.slot0(),
]);
const [sqrtPriceX96, tick] = slot0;
const pool = new Pool(
tokenA,
tokenB,
this._feeTier,
sqrtPriceX96,
liquidity,
tick
);
return pool;
}
private async getQuote(
swapRoute: Route<Token, Token>,
quoteToken: Token,
amount: CurrencyAmount<Token>,
tradeType: TradeType
) {
const { calldata } = await SwapQuoter.quoteCallParameters(
swapRoute,
amount,
tradeType,
{ useQuoterV2: true }
);
const quoteCallReturnData = await this.chain.provider.call({
to: this._quoterContractAddress,
data: calldata,
});
const quoteTokenRawAmount = utils.defaultAbiCoder.decode(
['uint256'],
quoteCallReturnData
);
const qouteTokenAmount = CurrencyAmount.fromRawAmount(
quoteToken,
quoteTokenRawAmount.toString()
);
return qouteTokenAmount;
}
}