forked from Uniswap/smart-order-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base-command.ts
334 lines (309 loc) · 8.74 KB
/
base-command.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
/// <reference types="./types/bunyan-debug-stream" />
import { Command, flags } from '@oclif/command';
import { ParserOutput } from '@oclif/parser/lib/parse';
import DEFAULT_TOKEN_LIST from '@uniswap/default-token-list';
import { Currency, CurrencyAmount, Token } from '@uniswap/sdk-core';
import { MethodParameters } from '@uniswap/v3-sdk';
import { default as bunyan, default as Logger } from 'bunyan';
import bunyanDebugStream from 'bunyan-debug-stream';
import { BigNumber, ethers } from 'ethers';
import NodeCache from 'node-cache';
import {
AlphaRouter,
CachingGasStationProvider,
CachingTokenListProvider,
CachingTokenProviderWithFallback,
ChainId,
CHAIN_IDS_LIST,
EIP1559GasPriceProvider,
GasPrice,
ID_TO_CHAIN_ID,
ID_TO_PROVIDER,
IRouter,
ISwapToRatio,
ITokenProvider,
IV3PoolProvider,
LegacyRouter,
MetricLogger,
NodeJSCache,
routeAmountsToString,
RouteWithValidQuote,
setGlobalLogger,
setGlobalMetric,
TokenProvider,
UniswapMulticallProvider,
V3PoolProvider,
V3QuoteProvider,
} from '../src';
import { LegacyGasPriceProvider } from '../src/providers/legacy-gas-price-provider';
import { OnChainGasPriceProvider } from '../src/providers/on-chain-gas-price-provider';
export abstract class BaseCommand extends Command {
static flags = {
topN: flags.integer({
required: false,
default: 3,
}),
topNTokenInOut: flags.integer({
required: false,
default: 2,
}),
topNSecondHop: flags.integer({
required: false,
default: 0,
}),
topNWithEachBaseToken: flags.integer({
required: false,
default: 2,
}),
topNWithBaseToken: flags.integer({
required: false,
default: 6,
}),
topNWithBaseTokenInSet: flags.boolean({
required: false,
default: false,
}),
topNDirectSwaps: flags.integer({
required: false,
default: 2,
}),
maxSwapsPerPath: flags.integer({
required: false,
default: 3,
}),
minSplits: flags.integer({
required: false,
default: 1,
}),
maxSplits: flags.integer({
required: false,
default: 3,
}),
distributionPercent: flags.integer({
required: false,
default: 5,
}),
chainId: flags.integer({
char: 'c',
required: false,
default: ChainId.MAINNET,
options: CHAIN_IDS_LIST,
}),
tokenListURI: flags.string({
required: false,
}),
router: flags.string({
char: 's',
required: false,
default: 'alpha',
}),
debug: flags.boolean(),
debugJSON: flags.boolean(),
};
private _log: Logger | null = null;
private _router: IRouter<any> | null = null;
private _swapToRatioRouter: ISwapToRatio<any, any> | null = null;
private _tokenProvider: ITokenProvider | null = null;
private _poolProvider: IV3PoolProvider | null = null;
private _blockNumber: number | null = null;
private _multicall2Provider: UniswapMulticallProvider | null = null;
get logger() {
return this._log
? this._log
: bunyan.createLogger({
name: 'Default Logger',
});
}
get router() {
if (this._router) {
return this._router;
} else {
throw 'router not initialized';
}
}
get swapToRatioRouter() {
if (this._swapToRatioRouter) {
return this._swapToRatioRouter;
} else {
throw 'swapToRatioRouter not initialized';
}
}
get tokenProvider() {
if (this._tokenProvider) {
return this._tokenProvider;
} else {
throw 'tokenProvider not initialized';
}
}
get poolProvider() {
if (this._poolProvider) {
return this._poolProvider;
} else {
throw 'poolProvider not initialized';
}
}
get blockNumber() {
if (this._blockNumber) {
return this._blockNumber;
} else {
throw 'blockNumber not initialized';
}
}
get multicall2Provider() {
if (this._multicall2Provider) {
return this._multicall2Provider;
} else {
throw 'multicall2 not initialized';
}
}
async init() {
const query: ParserOutput<any, any> = this.parse();
const {
chainId: chainIdNumb,
router: routerStr,
debug,
debugJSON,
tokenListURI,
} = query.flags;
// initialize logger
const logLevel = debug || debugJSON ? bunyan.DEBUG : bunyan.INFO;
this._log = bunyan.createLogger({
name: 'Uniswap Smart Order Router',
serializers: bunyan.stdSerializers,
level: logLevel,
streams: debugJSON
? undefined
: [
{
level: logLevel,
type: 'stream',
stream: bunyanDebugStream({
basepath: __dirname,
forceColor: false,
showDate: false,
showPid: false,
showLoggerName: false,
showLevel: !!debug,
}),
},
],
});
if (debug || debugJSON) {
setGlobalLogger(this.logger);
}
const metricLogger: MetricLogger = new MetricLogger();
setGlobalMetric(metricLogger);
const chainId = ID_TO_CHAIN_ID(chainIdNumb);
const chainProvider = ID_TO_PROVIDER(chainId);
const provider = new ethers.providers.JsonRpcProvider(
chainProvider,
chainId
);
this._blockNumber = await provider.getBlockNumber();
const tokenCache = new NodeJSCache<Token>(
new NodeCache({ stdTTL: 3600, useClones: false })
);
let tokenListProvider: CachingTokenListProvider;
if (tokenListURI) {
tokenListProvider = await CachingTokenListProvider.fromTokenListURI(
chainId,
tokenListURI,
tokenCache
);
} else {
tokenListProvider = await CachingTokenListProvider.fromTokenList(
chainId,
DEFAULT_TOKEN_LIST,
tokenCache
);
}
const multicall2Provider = new UniswapMulticallProvider(chainId, provider);
this._multicall2Provider = multicall2Provider;
this._poolProvider = new V3PoolProvider(chainId, multicall2Provider);
// initialize tokenProvider
const tokenProviderOnChain = new TokenProvider(chainId, multicall2Provider);
this._tokenProvider = new CachingTokenProviderWithFallback(
chainId,
tokenCache,
tokenListProvider,
tokenProviderOnChain
);
if (routerStr == 'legacy') {
this._router = new LegacyRouter({
chainId,
multicall2Provider,
poolProvider: new V3PoolProvider(chainId, multicall2Provider),
quoteProvider: new V3QuoteProvider(
chainId,
provider,
multicall2Provider
),
tokenProvider: this.tokenProvider,
});
} else {
const gasPriceCache = new NodeJSCache<GasPrice>(
new NodeCache({ stdTTL: 15, useClones: true })
);
// const useDefaultQuoteProvider =
// chainId != ChainId.ARBITRUM_ONE && chainId != ChainId.ARBITRUM_RINKEBY;
const router = new AlphaRouter({
provider,
chainId,
multicall2Provider: multicall2Provider,
gasPriceProvider: new CachingGasStationProvider(
chainId,
new OnChainGasPriceProvider(
chainId,
new EIP1559GasPriceProvider(provider),
new LegacyGasPriceProvider(provider)
),
gasPriceCache
),
});
this._swapToRatioRouter = router;
this._router = router;
}
}
logSwapResults(
routeAmounts: RouteWithValidQuote[],
quote: CurrencyAmount<Currency>,
quoteGasAdjusted: CurrencyAmount<Currency>,
estimatedGasUsedQuoteToken: CurrencyAmount<Currency>,
estimatedGasUsedUSD: CurrencyAmount<Currency>,
methodParameters: MethodParameters | undefined,
blockNumber: BigNumber,
estimatedGasUsed: BigNumber,
gasPriceWei: BigNumber
) {
this.logger.info(`Best Route:`);
this.logger.info(`${routeAmountsToString(routeAmounts)}`);
this.logger.info(`\tRaw Quote Exact In:`);
this.logger.info(
`\t\t${quote.toFixed(Math.min(quote.currency.decimals, 2))}`
);
this.logger.info(`\tGas Adjusted Quote In:`);
this.logger.info(
`\t\t${quoteGasAdjusted.toFixed(
Math.min(quoteGasAdjusted.currency.decimals, 2)
)}`
);
this.logger.info(``);
this.logger.info(
`Gas Used Quote Token: ${estimatedGasUsedQuoteToken.toFixed(
Math.min(estimatedGasUsedQuoteToken.currency.decimals, 6)
)}`
);
this.logger.info(
`Gas Used USD: ${estimatedGasUsedUSD.toFixed(
Math.min(estimatedGasUsedUSD.currency.decimals, 6)
)}`
);
this.logger.info(`Calldata: ${methodParameters?.calldata}`);
this.logger.info(`Value: ${methodParameters?.value}`);
this.logger.info({
blockNumber: blockNumber.toString(),
estimatedGasUsed: estimatedGasUsed.toString(),
gasPriceWei: gasPriceWei.toString(),
});
}
}