forked from Uniswap/v2-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pair.ts
398 lines (366 loc) 路 17.1 KB
/
pair.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
import { BigintIsh, Price, sqrt, Token, CurrencyAmount, Percent } from '@uniswap/sdk-core'
import invariant from 'tiny-invariant'
import JSBI from 'jsbi'
import { pack, keccak256 } from '@ethersproject/solidity'
import { getCreate2Address } from '@ethersproject/address'
import { BigNumber } from '@ethersproject/bignumber'
import {
FACTORY_ADDRESS,
INIT_CODE_HASH,
MINIMUM_LIQUIDITY,
FIVE,
_997,
_1000,
ONE,
ZERO,
BASIS_POINTS,
ONE_HUNDRED_PERCENT,
ZERO_PERCENT
} from '../constants'
import { InsufficientReservesError, InsufficientInputAmountError } from '../errors'
export const computePairAddress = ({
factoryAddress,
tokenA,
tokenB
}: {
factoryAddress: string
tokenA: Token
tokenB: Token
}): string => {
const [token0, token1] = tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA] // does safety checks
return getCreate2Address(
factoryAddress,
keccak256(['bytes'], [pack(['address', 'address'], [token0.address, token1.address])]),
INIT_CODE_HASH
)
}
export class Pair {
public readonly liquidityToken: Token
private readonly tokenAmounts: [CurrencyAmount<Token>, CurrencyAmount<Token>]
public static getAddress(tokenA: Token, tokenB: Token): string {
return computePairAddress({ factoryAddress: FACTORY_ADDRESS, tokenA, tokenB })
}
public constructor(currencyAmountA: CurrencyAmount<Token>, tokenAmountB: CurrencyAmount<Token>) {
const tokenAmounts = currencyAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
? [currencyAmountA, tokenAmountB]
: [tokenAmountB, currencyAmountA]
this.liquidityToken = new Token(
tokenAmounts[0].currency.chainId,
Pair.getAddress(tokenAmounts[0].currency, tokenAmounts[1].currency),
18,
'UNI-V2',
'Uniswap V2'
)
this.tokenAmounts = tokenAmounts as [CurrencyAmount<Token>, CurrencyAmount<Token>]
}
/**
* Returns true if the token is either token0 or token1
* @param token to check
*/
public involvesToken(token: Token): boolean {
return token.equals(this.token0) || token.equals(this.token1)
}
/**
* Returns the current mid price of the pair in terms of token0, i.e. the ratio of reserve1 to reserve0
*/
public get token0Price(): Price<Token, Token> {
const result = this.tokenAmounts[1].divide(this.tokenAmounts[0])
return new Price(this.token0, this.token1, result.denominator, result.numerator)
}
/**
* Returns the current mid price of the pair in terms of token1, i.e. the ratio of reserve0 to reserve1
*/
public get token1Price(): Price<Token, Token> {
const result = this.tokenAmounts[0].divide(this.tokenAmounts[1])
return new Price(this.token1, this.token0, result.denominator, result.numerator)
}
/**
* Return the price of the given token in terms of the other token in the pair.
* @param token token to return price of
*/
public priceOf(token: Token): Price<Token, Token> {
invariant(this.involvesToken(token), 'TOKEN')
return token.equals(this.token0) ? this.token0Price : this.token1Price
}
/**
* Returns the chain ID of the tokens in the pair.
*/
public get chainId(): number {
return this.token0.chainId
}
public get token0(): Token {
return this.tokenAmounts[0].currency
}
public get token1(): Token {
return this.tokenAmounts[1].currency
}
public get reserve0(): CurrencyAmount<Token> {
return this.tokenAmounts[0]
}
public get reserve1(): CurrencyAmount<Token> {
return this.tokenAmounts[1]
}
public reserveOf(token: Token): CurrencyAmount<Token> {
invariant(this.involvesToken(token), 'TOKEN')
return token.equals(this.token0) ? this.reserve0 : this.reserve1
}
/**
* getAmountOut is the linear algebra of reserve ratio against amountIn:amountOut.
* https://ethereum.stackexchange.com/questions/101629/what-is-math-for-uniswap-calculates-the-amountout-and-amountin-why-997-and-1000
* has the math deduction for the reserve calculation without fee-on-transfer fees.
*
* With fee-on-transfer tax, intuitively it's just:
* inputAmountWithFeeAndTax = 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
* = (1 - amountIn.sellFeesBips / 10000) * amountInWithFee
* where amountInWithFee is the amountIn after taking out the LP fees
* outputAmountWithTax = amountOut * (1 - amountOut.buyFeesBips / 10000)
*
* But we are illustrating the math deduction below to ensure that's the case.
*
* before swap A * B = K where A = reserveIn B = reserveOut
*
* after swap A' * B' = K where only k is a constant value
*
* getAmountOut
*
* A' = A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn # here 0.3% is deducted
* B' = B - amountOut * (1 - amountOut.buyFeesBips / 10000)
* amountOut = (B - B') / (1 - amountOut.buyFeesBips / 10000) # where A' * B' still is k
* = (B - K/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
* /
* (1 - amountOut.buyFeesBips / 10000)
* = (B - AB/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
* /
* (1 - amountOut.buyFeesBips / 10000)
* = ((BA + B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn - AB)/(A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn))
* /
* (1 - amountOut.buyFeesBips / 10000)
* = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn / (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
* /
* (1 - amountOut.buyFeesBips / 10000)
* amountOut * (1 - amountOut.buyFeesBips / 10000) = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
* /
* (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
*
* outputAmountWithTax = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn
* /
* (A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn)
* = (B * 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn * 1000
* /
* ((A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn) * 1000)
* = (B * (1 - amountIn.sellFeesBips / 10000) 997 * * amountIn
* /
* (1000 * A + (1 - amountIn.sellFeesBips / 10000) * 997 * amountIn)
* = (B * (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee)
* /
* (1000 * A + (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee)
* = (B * inputAmountWithFeeAndTax)
* /
* (1000 * A + inputAmountWithFeeAndTax)
*
* inputAmountWithFeeAndTax = (1 - amountIn.sellFeesBips / 10000) * inputAmountWithFee
* outputAmountWithTax = amountOut * (1 - amountOut.buyFeesBips / 10000)
*
* @param inputAmount
*/
public getOutputAmount(
inputAmount: CurrencyAmount<Token>,
calculateFotFees: boolean = false
): [CurrencyAmount<Token>, Pair] {
invariant(this.involvesToken(inputAmount.currency), 'TOKEN')
if (JSBI.equal(this.reserve0.quotient, ZERO) || JSBI.equal(this.reserve1.quotient, ZERO)) {
throw new InsufficientReservesError()
}
const inputReserve = this.reserveOf(inputAmount.currency)
const outputReserve = this.reserveOf(inputAmount.currency.equals(this.token0) ? this.token1 : this.token0)
const percentAfterSellFees = calculateFotFees ? this.derivePercentAfterSellFees(inputAmount) : ZERO_PERCENT
const inputAmountAfterTax = percentAfterSellFees.greaterThan(ZERO_PERCENT)
? CurrencyAmount.fromRawAmount(
inputAmount.currency,
percentAfterSellFees.multiply(inputAmount).quotient // fraction.quotient will round down by itself, which is desired
)
: inputAmount
const inputAmountWithFeeAndAfterTax = JSBI.multiply(inputAmountAfterTax.quotient, _997)
const numerator = JSBI.multiply(inputAmountWithFeeAndAfterTax, outputReserve.quotient)
const denominator = JSBI.add(JSBI.multiply(inputReserve.quotient, _1000), inputAmountWithFeeAndAfterTax)
const outputAmount = CurrencyAmount.fromRawAmount(
inputAmount.currency.equals(this.token0) ? this.token1 : this.token0,
JSBI.divide(numerator, denominator) // JSBI.divide will round down by itself, which is desired
)
if (JSBI.equal(outputAmount.quotient, ZERO)) {
throw new InsufficientInputAmountError()
}
const percentAfterBuyFees = calculateFotFees ? this.derivePercentAfterBuyFees(outputAmount) : ZERO_PERCENT
const outputAmountAfterTax = percentAfterBuyFees.greaterThan(ZERO_PERCENT)
? CurrencyAmount.fromRawAmount(
outputAmount.currency,
outputAmount.multiply(percentAfterBuyFees).quotient // fraction.quotient will round down by itself, which is desired
)
: outputAmount
if (JSBI.equal(outputAmountAfterTax.quotient, ZERO)) {
throw new InsufficientInputAmountError()
}
return [
outputAmountAfterTax,
new Pair(inputReserve.add(inputAmountAfterTax), outputReserve.subtract(outputAmountAfterTax))
]
}
/**
* getAmountIn is the linear algebra of reserve ratio against amountIn:amountOut.
* https://ethereum.stackexchange.com/questions/101629/what-is-math-for-uniswap-calculates-the-amountout-and-amountin-why-997-and-1000
* has the math deduction for the reserve calculation without fee-on-transfer fees.
*
* With fee-on-transfer fees, intuitively it's just:
* outputAmountWithTax = amountOut / (1 - amountOut.buyFeesBips / 10000)
* inputAmountWithTax = amountIn / (1 - amountIn.sellFeesBips / 10000) / 0.997
*
* But we are illustrating the math deduction below to ensure that's the case.
*
* before swap A * B = K where A = reserveIn B = reserveOut
*
* after swap A' * B' = K where only k is a constant value
*
* getAmountIn
*
* B' = B - amountOut * (1 - amountOut.buyFeesBips / 10000)
* A' = A + 0.997 * (1 - amountIn.sellFeesBips / 10000) * amountIn # here 0.3% is deducted
* amountIn = (A' - A) / (0.997 * (1 - amountIn.sellFeesBips / 10000))
* = (K / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)) - A)
* /
* (0.997 * (1 - amountIn.sellFeesBips / 10000))
* = (AB / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)) - A)
* /
* (0.997 * (1 - amountIn.sellFeesBips / 10000))
* = ((AB - AB + A * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
* /
* (0.997 * (1 - amountIn.sellFeesBips / 10000))
* = ((A * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
* /
* (0.997 * (1 - amountIn.sellFeesBips / 10000))
* = ((A * 1000 * amountOut / (1 - amountOut.buyFeesBips / 10000)) / (B - amountOut / (1 - amountOut.buyFeesBips / 10000)))
* /
* (997 * (1 - amountIn.sellFeesBips / 10000))
*
* outputAmountWithTax = amountOut / (1 - amountOut.buyFeesBips / 10000)
* inputAmountWithTax = amountIn / (997 * (1 - amountIn.sellFeesBips / 10000))
* = (A * outputAmountWithTax * 1000) / ((B - outputAmountWithTax) * 997)
*
* @param outputAmount
*/
public getInputAmount(
outputAmount: CurrencyAmount<Token>,
calculateFotFees: boolean = false
): [CurrencyAmount<Token>, Pair] {
invariant(this.involvesToken(outputAmount.currency), 'TOKEN')
const percentAfterBuyFees = calculateFotFees ? this.derivePercentAfterBuyFees(outputAmount) : ZERO_PERCENT
const outputAmountBeforeTax = percentAfterBuyFees.greaterThan(ZERO_PERCENT)
? CurrencyAmount.fromRawAmount(
outputAmount.currency,
JSBI.add(outputAmount.divide(percentAfterBuyFees).quotient, ONE) // add 1 for rounding up
)
: outputAmount
if (
JSBI.equal(this.reserve0.quotient, ZERO) ||
JSBI.equal(this.reserve1.quotient, ZERO) ||
JSBI.greaterThanOrEqual(outputAmount.quotient, this.reserveOf(outputAmount.currency).quotient) ||
JSBI.greaterThanOrEqual(outputAmountBeforeTax.quotient, this.reserveOf(outputAmount.currency).quotient)
) {
throw new InsufficientReservesError()
}
const outputReserve = this.reserveOf(outputAmount.currency)
const inputReserve = this.reserveOf(outputAmount.currency.equals(this.token0) ? this.token1 : this.token0)
const numerator = JSBI.multiply(JSBI.multiply(inputReserve.quotient, outputAmountBeforeTax.quotient), _1000)
const denominator = JSBI.multiply(JSBI.subtract(outputReserve.quotient, outputAmountBeforeTax.quotient), _997)
const inputAmount = CurrencyAmount.fromRawAmount(
outputAmount.currency.equals(this.token0) ? this.token1 : this.token0,
JSBI.add(JSBI.divide(numerator, denominator), ONE) // add 1 here is part of the formula, no rounding needed here, since there will not be decimal at this point
)
const percentAfterSellFees = calculateFotFees ? this.derivePercentAfterSellFees(inputAmount) : ZERO_PERCENT
const inputAmountBeforeTax = percentAfterSellFees.greaterThan(ZERO_PERCENT)
? CurrencyAmount.fromRawAmount(
inputAmount.currency,
JSBI.add(inputAmount.divide(percentAfterSellFees).quotient, ONE) // add 1 for rounding up
)
: inputAmount
return [inputAmountBeforeTax, new Pair(inputReserve.add(inputAmount), outputReserve.subtract(outputAmount))]
}
public getLiquidityMinted(
totalSupply: CurrencyAmount<Token>,
tokenAmountA: CurrencyAmount<Token>,
tokenAmountB: CurrencyAmount<Token>
): CurrencyAmount<Token> {
invariant(totalSupply.currency.equals(this.liquidityToken), 'LIQUIDITY')
const tokenAmounts = tokenAmountA.currency.sortsBefore(tokenAmountB.currency) // does safety checks
? [tokenAmountA, tokenAmountB]
: [tokenAmountB, tokenAmountA]
invariant(tokenAmounts[0].currency.equals(this.token0) && tokenAmounts[1].currency.equals(this.token1), 'TOKEN')
let liquidity: JSBI
if (JSBI.equal(totalSupply.quotient, ZERO)) {
liquidity = JSBI.subtract(
sqrt(JSBI.multiply(tokenAmounts[0].quotient, tokenAmounts[1].quotient)),
MINIMUM_LIQUIDITY
)
} else {
const amount0 = JSBI.divide(JSBI.multiply(tokenAmounts[0].quotient, totalSupply.quotient), this.reserve0.quotient)
const amount1 = JSBI.divide(JSBI.multiply(tokenAmounts[1].quotient, totalSupply.quotient), this.reserve1.quotient)
liquidity = JSBI.lessThanOrEqual(amount0, amount1) ? amount0 : amount1
}
if (!JSBI.greaterThan(liquidity, ZERO)) {
throw new InsufficientInputAmountError()
}
return CurrencyAmount.fromRawAmount(this.liquidityToken, liquidity)
}
public getLiquidityValue(
token: Token,
totalSupply: CurrencyAmount<Token>,
liquidity: CurrencyAmount<Token>,
feeOn: boolean = false,
kLast?: BigintIsh
): CurrencyAmount<Token> {
invariant(this.involvesToken(token), 'TOKEN')
invariant(totalSupply.currency.equals(this.liquidityToken), 'TOTAL_SUPPLY')
invariant(liquidity.currency.equals(this.liquidityToken), 'LIQUIDITY')
invariant(JSBI.lessThanOrEqual(liquidity.quotient, totalSupply.quotient), 'LIQUIDITY')
let totalSupplyAdjusted: CurrencyAmount<Token>
if (!feeOn) {
totalSupplyAdjusted = totalSupply
} else {
invariant(!!kLast, 'K_LAST')
const kLastParsed = JSBI.BigInt(kLast)
if (!JSBI.equal(kLastParsed, ZERO)) {
const rootK = sqrt(JSBI.multiply(this.reserve0.quotient, this.reserve1.quotient))
const rootKLast = sqrt(kLastParsed)
if (JSBI.greaterThan(rootK, rootKLast)) {
const numerator = JSBI.multiply(totalSupply.quotient, JSBI.subtract(rootK, rootKLast))
const denominator = JSBI.add(JSBI.multiply(rootK, FIVE), rootKLast)
const feeLiquidity = JSBI.divide(numerator, denominator)
totalSupplyAdjusted = totalSupply.add(CurrencyAmount.fromRawAmount(this.liquidityToken, feeLiquidity))
} else {
totalSupplyAdjusted = totalSupply
}
} else {
totalSupplyAdjusted = totalSupply
}
}
return CurrencyAmount.fromRawAmount(
token,
JSBI.divide(JSBI.multiply(liquidity.quotient, this.reserveOf(token).quotient), totalSupplyAdjusted.quotient)
)
}
private derivePercentAfterSellFees(inputAmount: CurrencyAmount<Token>): Percent {
const sellFeeBips = inputAmount.currency.sellFeeBps
if (sellFeeBips?.gt(BigNumber.from(0))) {
return ONE_HUNDRED_PERCENT.subtract(new Percent(JSBI.BigInt(sellFeeBips)).divide(BASIS_POINTS))
} else {
return ZERO_PERCENT
}
}
private derivePercentAfterBuyFees(outputAmount: CurrencyAmount<Token>): Percent {
const buyFeeBps = outputAmount.currency.buyFeeBps
if (buyFeeBps?.gt(BigNumber.from(0))) {
return ONE_HUNDRED_PERCENT.subtract(new Percent(JSBI.BigInt(buyFeeBps)).divide(BASIS_POINTS))
} else {
return ZERO_PERCENT
}
}
}