fix calculateSlippageAmount (#1497)

This commit is contained in:
Moody Salem 2021-05-10 14:22:26 -05:00 committed by GitHub
parent 948e01a196
commit 57786335df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 1 deletions

@ -50,6 +50,30 @@ describe('utils', () => {
calculateSlippageAmount(tokenAmount, new Percent(10000, 10_000)).map((bound) => bound.toString())
).toEqual(['0', '200'])
})
it('works for 18 decimals', () => {
const tokenAmount = new TokenAmount(new Token(ChainId.MAINNET, AddressZero, 18), '100')
expect(() => calculateSlippageAmount(tokenAmount, new Percent(-1, 10_000))).toThrow('Unexpected slippage')
expect(() => calculateSlippageAmount(tokenAmount, new Percent(10_001, 10_000))).toThrow('Unexpected slippage')
expect(calculateSlippageAmount(tokenAmount, new Percent(0, 10_000)).map((bound) => bound.toString())).toEqual([
'100',
'100',
])
expect(calculateSlippageAmount(tokenAmount, new Percent(5, 100)).map((bound) => bound.toString())).toEqual([
'95',
'105',
])
expect(calculateSlippageAmount(tokenAmount, new Percent(100, 10_000)).map((bound) => bound.toString())).toEqual([
'99',
'101',
])
expect(calculateSlippageAmount(tokenAmount, new Percent(200, 10_000)).map((bound) => bound.toString())).toEqual([
'98',
'102',
])
expect(
calculateSlippageAmount(tokenAmount, new Percent(10000, 10_000)).map((bound) => bound.toString())
).toEqual(['0', '200'])
})
})
describe('#isAddress', () => {

@ -66,7 +66,11 @@ export function calculateGasMargin(value: BigNumber): BigNumber {
const ONE = new Fraction(1, 1)
export function calculateSlippageAmount(value: CurrencyAmount, slippage: Percent): [JSBI, JSBI] {
if (slippage.lessThan(0) || slippage.greaterThan(ONE)) throw new Error('Unexpected slippage')
return [value.multiply(ONE.subtract(slippage)).quotient, value.multiply(ONE.add(slippage)).quotient]
const decimalScaled = JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(value.currency.decimals))
return [
value.multiply(ONE.subtract(slippage)).multiply(decimalScaled).quotient,
value.multiply(ONE.add(slippage)).multiply(decimalScaled).quotient,
]
}
// account is not optional