forked from Uniswap/interface
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.ts
More file actions
508 lines (457 loc) · 14.7 KB
/
types.ts
File metadata and controls
508 lines (457 loc) · 14.7 KB
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
import { MixedRouteSDK, ONE, Protocol, Trade } from '@uniswap/router-sdk'
import { ChainId, Currency, CurrencyAmount, Fraction, Percent, Price, Token, TradeType } from '@uniswap/sdk-core'
import { DutchOrderInfo, DutchOrderInfoJSON, DutchOrderTrade as IDutchOrderTrade } from '@uniswap/uniswapx-sdk'
import { Route as V2Route } from '@uniswap/v2-sdk'
import { Route as V3Route } from '@uniswap/v3-sdk'
import { ZERO_PERCENT } from 'constants/misc'
export enum TradeState {
LOADING = 'loading',
INVALID = 'invalid',
STALE = 'stale',
NO_ROUTE_FOUND = 'no_route_found',
VALID = 'valid',
}
export enum QuoteMethod {
ROUTING_API = 'ROUTING_API',
QUICK_ROUTE = 'QUICK_ROUTE',
CLIENT_SIDE = 'CLIENT_SIDE',
CLIENT_SIDE_FALLBACK = 'CLIENT_SIDE_FALLBACK', // If client-side was used after the routing-api call failed.
}
// This is excluded from `RouterPreference` enum because it's only used
// internally for token -> USDC trades to get a USD value.
export const INTERNAL_ROUTER_PREFERENCE_PRICE = 'price' as const
export enum RouterPreference {
X = 'uniswapx',
API = 'api',
CLIENT = 'client',
}
export interface GetQuoteArgs {
tokenInAddress: string
tokenInChainId: ChainId
tokenInDecimals: number
tokenInSymbol?: string
tokenOutAddress: string
tokenOutChainId: ChainId
tokenOutDecimals: number
tokenOutSymbol?: string
amount: string
account?: string
routerPreference: RouterPreference | typeof INTERNAL_ROUTER_PREFERENCE_PRICE
tradeType: TradeType
needsWrapIfUniswapX: boolean
uniswapXForceSyntheticQuotes: boolean
uniswapXEthOutputEnabled: boolean
uniswapXExactOutputEnabled: boolean
// legacy field indicating the user disabled UniswapX during the opt-in period, or dismissed the UniswapX opt-in modal.
userDisabledUniswapX: boolean
// temporary field indicating the user disabled UniswapX during the transition to the opt-out model
userOptedOutOfUniswapX: boolean
isUniswapXDefaultEnabled: boolean
inputTax: Percent
outputTax: Percent
}
export type GetQuickQuoteArgs = {
amount: string
tokenInAddress: string
tokenInChainId: ChainId
tokenInDecimals: number
tokenInSymbol?: string
tokenOutAddress: string
tokenOutChainId: ChainId
tokenOutDecimals: number
tokenOutSymbol?: string
tradeType: TradeType
inputTax: Percent
outputTax: Percent
}
// from https://github.com/Uniswap/routing-api/blob/main/lib/handlers/schema.ts
type TokenInRoute = Pick<Token, 'address' | 'chainId' | 'symbol' | 'decimals'>
export type V3PoolInRoute = {
type: 'v3-pool'
tokenIn: TokenInRoute
tokenOut: TokenInRoute
sqrtRatioX96: string
liquidity: string
tickCurrent: string
fee: string
amountIn?: string
amountOut?: string
// not used in the interface
address?: string
}
type V2Reserve = {
token: TokenInRoute
quotient: string
}
export type V2PoolInRoute = {
type: 'v2-pool'
tokenIn: TokenInRoute
tokenOut: TokenInRoute
reserve0: V2Reserve
reserve1: V2Reserve
amountIn?: string
amountOut?: string
// not used in the interface
// avoid returning it from the client-side smart-order-router
address?: string
}
export interface ClassicQuoteData {
quoteId?: string
requestId?: string
blockNumber: string
amount: string
amountDecimals: string
gasPriceWei: string
gasUseEstimate: string
gasUseEstimateQuote: string
gasUseEstimateQuoteDecimals: string
gasUseEstimateUSD: string
methodParameters?: { calldata: string; value: string }
quote: string
quoteDecimals: string
quoteGasAdjusted: string
quoteGasAdjustedDecimals: string
route: Array<(V3PoolInRoute | V2PoolInRoute)[]>
routeString: string
}
type URADutchOrderQuoteResponse = {
routing: URAQuoteType.DUTCH_LIMIT
quote: {
auctionPeriodSecs: number
deadlineBufferSecs: number
startTimeBufferSecs: number
orderInfo: DutchOrderInfoJSON
quoteId?: string
requestId?: string
slippageTolerance: string
}
allQuotes: Array<URAQuoteResponse>
}
type URAClassicQuoteResponse = {
routing: URAQuoteType.CLASSIC
quote: ClassicQuoteData
allQuotes: Array<URAQuoteResponse>
}
export type URAQuoteResponse = URAClassicQuoteResponse | URADutchOrderQuoteResponse
export type QuickRouteResponse = {
tokenIn: {
address: string
decimals: number
symbol: string
name: string
}
tokenOut: {
address: string
decimals: number
symbol: string
name: string
}
tradeType: 'EXACT_IN' | 'EXACT_OUT'
quote: {
amount: string
path: string
}
}
export function isClassicQuoteResponse(data: URAQuoteResponse): data is URAClassicQuoteResponse {
return data.routing === URAQuoteType.CLASSIC
}
export enum TradeFillType {
Classic = 'classic', // Uniswap V1, V2, and V3 trades with on-chain routes
UniswapX = 'uniswap_x', // off-chain trades, no routes
None = 'none', // for preview trades, cant be used for submission
}
export type ApproveInfo = { needsApprove: true; approveGasEstimateUSD: number } | { needsApprove: false }
export type WrapInfo = { needsWrap: true; wrapGasEstimateUSD: number } | { needsWrap: false }
export class ClassicTrade extends Trade<Currency, Currency, TradeType> {
public readonly fillType = TradeFillType.Classic
approveInfo: ApproveInfo
gasUseEstimateUSD?: number // gas estimate for swaps
blockNumber: string | null | undefined
isUniswapXBetter: boolean | undefined
requestId: string | undefined
quoteMethod: QuoteMethod
inputTax: Percent
outputTax: Percent
constructor({
gasUseEstimateUSD,
blockNumber,
isUniswapXBetter,
requestId,
quoteMethod,
approveInfo,
inputTax,
outputTax,
...routes
}: {
gasUseEstimateUSD?: number
totalGasUseEstimateUSD?: number
blockNumber?: string | null
isUniswapXBetter?: boolean
requestId?: string
quoteMethod: QuoteMethod
approveInfo: ApproveInfo
inputTax: Percent
outputTax: Percent
v2Routes: {
routev2: V2Route<Currency, Currency>
inputAmount: CurrencyAmount<Currency>
outputAmount: CurrencyAmount<Currency>
}[]
v3Routes: {
routev3: V3Route<Currency, Currency>
inputAmount: CurrencyAmount<Currency>
outputAmount: CurrencyAmount<Currency>
}[]
tradeType: TradeType
mixedRoutes?: {
mixedRoute: MixedRouteSDK<Currency, Currency>
inputAmount: CurrencyAmount<Currency>
outputAmount: CurrencyAmount<Currency>
}[]
}) {
super(routes)
this.blockNumber = blockNumber
this.gasUseEstimateUSD = gasUseEstimateUSD
this.isUniswapXBetter = isUniswapXBetter
this.requestId = requestId
this.quoteMethod = quoteMethod
this.approveInfo = approveInfo
this.inputTax = inputTax
this.outputTax = outputTax
}
public get totalTaxRate(): Percent {
return this.inputTax.add(this.outputTax)
}
public get postTaxOutputAmount() {
// Ideally we should calculate the final output amount by ammending the inputAmount based on the input tax and then applying the output tax,
// but this isn't currently possible because V2Trade reconstructs the total inputAmount based on the swap routes
// TODO(WEB-2761): Amend V2Trade objects in the v2-sdk to have a separate field for post-input tax routes
return this.outputAmount.multiply(new Fraction(ONE).subtract(this.totalTaxRate))
}
public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<Currency> {
// Since universal-router-sdk reconstructs V2Trade objects, overriding this method does not actually change the minimumAmountOut that gets submitted on-chain
// Our current workaround is to add tax rate to slippage tolerance before we submit the trade to universal-router-sdk in useUniversalRouter.ts
// So the purpose of this override is so the UI displays the same minimum amount out as what is submitted on-chain
return super.minimumAmountOut(slippageTolerance.add(this.totalTaxRate), amountOut)
}
// gas estimate for maybe approve + swap
public get totalGasUseEstimateUSD(): number | undefined {
if (this.approveInfo.needsApprove && this.gasUseEstimateUSD) {
return this.approveInfo.approveGasEstimateUSD + this.gasUseEstimateUSD
}
return this.gasUseEstimateUSD
}
}
export class DutchOrderTrade extends IDutchOrderTrade<Currency, Currency, TradeType> {
public readonly fillType = TradeFillType.UniswapX
quoteId?: string
requestId?: string
wrapInfo: WrapInfo
approveInfo: ApproveInfo
// The gas estimate of the reference classic trade, if there is one.
classicGasUseEstimateUSD?: number
auctionPeriodSecs: number
startTimeBufferSecs: number
deadlineBufferSecs: number
slippageTolerance: Percent
inputTax = ZERO_PERCENT
outputTax = ZERO_PERCENT
constructor({
currencyIn,
currenciesOut,
orderInfo,
tradeType,
quoteId,
requestId,
wrapInfo,
approveInfo,
classicGasUseEstimateUSD,
auctionPeriodSecs,
startTimeBufferSecs,
deadlineBufferSecs,
slippageTolerance,
}: {
currencyIn: Currency
currenciesOut: Currency[]
orderInfo: DutchOrderInfo
tradeType: TradeType
quoteId?: string
requestId?: string
approveInfo: ApproveInfo
wrapInfo: WrapInfo
classicGasUseEstimateUSD?: number
auctionPeriodSecs: number
startTimeBufferSecs: number
deadlineBufferSecs: number
slippageTolerance: Percent
}) {
super({ currencyIn, currenciesOut, orderInfo, tradeType })
this.quoteId = quoteId
this.requestId = requestId
this.approveInfo = approveInfo
this.wrapInfo = wrapInfo
this.classicGasUseEstimateUSD = classicGasUseEstimateUSD
this.auctionPeriodSecs = auctionPeriodSecs
this.deadlineBufferSecs = deadlineBufferSecs
this.slippageTolerance = slippageTolerance
this.startTimeBufferSecs = startTimeBufferSecs
}
public get totalGasUseEstimateUSD(): number {
if (this.wrapInfo.needsWrap && this.approveInfo.needsApprove) {
return this.wrapInfo.wrapGasEstimateUSD + this.approveInfo.approveGasEstimateUSD
}
if (this.wrapInfo.needsWrap) return this.wrapInfo.wrapGasEstimateUSD
if (this.approveInfo.needsApprove) return this.approveInfo.approveGasEstimateUSD
return 0
}
/** For UniswapX, handling token taxes in the output amount is outsourced to quoters */
public get postTaxOutputAmount() {
return this.outputAmount
}
}
export class PreviewTrade {
public readonly fillType = TradeFillType.None
public readonly quoteMethod = QuoteMethod.QUICK_ROUTE
public readonly tradeType: TradeType
public readonly inputAmount: CurrencyAmount<Currency>
public readonly outputAmount: CurrencyAmount<Currency>
inputTax: Percent
outputTax: Percent
constructor({
inputAmount,
outputAmount,
tradeType,
inputTax,
outputTax,
}: {
inputAmount: CurrencyAmount<Currency>
outputAmount: CurrencyAmount<Currency>
tradeType: TradeType
inputTax: Percent
outputTax: Percent
}) {
this.inputAmount = inputAmount
this.outputAmount = outputAmount
this.tradeType = tradeType
this.inputTax = inputTax
this.outputTax = outputTax
}
public get totalTaxRate(): Percent {
return this.inputTax.add(this.outputTax)
}
public get postTaxOutputAmount() {
// Ideally we should calculate the final output amount by ammending the inputAmount based on the input tax and then applying the output tax,
// but this isn't currently possible because V2Trade reconstructs the total inputAmount based on the swap routes
// TODO(WEB-2761): Amend V2Trade objects in the v2-sdk to have a separate field for post-input tax routes
return this.outputAmount.multiply(new Fraction(ONE).subtract(this.totalTaxRate))
}
// below methods are copied from router-sdk
// Trade https://github.com/Uniswap/router-sdk/blob/main/src/entities/trade.ts#L10
public minimumAmountOut(slippageTolerance: Percent, amountOut = this.outputAmount): CurrencyAmount<Currency> {
if (this.tradeType === TradeType.EXACT_OUTPUT) {
return amountOut
} else {
const slippageAdjustedAmountOut = new Fraction(ONE)
.add(slippageTolerance)
.invert()
.multiply(amountOut.quotient).quotient
return CurrencyAmount.fromRawAmount(amountOut.currency, slippageAdjustedAmountOut)
}
}
public maximumAmountIn(slippageTolerance: Percent, amountIn = this.inputAmount): CurrencyAmount<Currency> {
if (this.tradeType === TradeType.EXACT_INPUT) {
return amountIn
} else {
const slippageAdjustedAmountIn = new Fraction(ONE).add(slippageTolerance).multiply(amountIn.quotient).quotient
return CurrencyAmount.fromRawAmount(amountIn.currency, slippageAdjustedAmountIn)
}
}
private _executionPrice: Price<Currency, Currency> | undefined
/**
* The price expressed in terms of output amount/input amount.
*/
public get executionPrice(): Price<Currency, Currency> {
return (
this._executionPrice ??
(this._executionPrice = new Price(
this.inputAmount.currency,
this.outputAmount.currency,
this.inputAmount.quotient,
this.outputAmount.quotient
))
)
}
public worstExecutionPrice(slippageTolerance: Percent): Price<Currency, Currency> {
return new Price(
this.inputAmount.currency,
this.outputAmount.currency,
this.maximumAmountIn(slippageTolerance).quotient,
this.minimumAmountOut(slippageTolerance).quotient
)
}
}
export type SubmittableTrade = ClassicTrade | DutchOrderTrade
export type InterfaceTrade = SubmittableTrade | PreviewTrade
export enum QuoteState {
SUCCESS = 'Success',
NOT_FOUND = 'Not found',
}
export type QuoteResult =
| {
state: QuoteState.NOT_FOUND
data?: undefined
}
| {
state: QuoteState.SUCCESS
data: URAQuoteResponse
}
export type TradeResult =
| {
state: QuoteState.NOT_FOUND
trade?: undefined
latencyMs?: number
}
| {
state: QuoteState.SUCCESS
trade: SubmittableTrade
latencyMs?: number
}
export type PreviewTradeResult =
| {
state: QuoteState.NOT_FOUND
trade?: undefined
latencyMs?: number
}
| {
state: QuoteState.SUCCESS
trade: PreviewTrade
latencyMs?: number
}
export enum PoolType {
V2Pool = 'v2-pool',
V3Pool = 'v3-pool',
}
// swap router API special cases these strings to represent native currencies
// all chains except for bnb chain and polygon
// have "ETH" as native currency symbol
export enum SwapRouterNativeAssets {
MATIC = 'MATIC',
BNB = 'BNB',
AVAX = 'AVAX',
ETH = 'ETH',
XDAI = 'xDAI',
}
export enum URAQuoteType {
CLASSIC = 'CLASSIC',
DUTCH_LIMIT = 'DUTCH_LIMIT',
}
type ClassicAPIConfig = {
protocols: Protocol[]
}
type UniswapXConfig = {
swapper?: string
exclusivityOverrideBps?: number
auctionPeriodSecs?: number
startTimeBufferSecs?: number
}
export type RoutingConfig = (UniswapXConfig | ClassicAPIConfig)[]