diff --git a/src/utils/index.test.ts b/src/utils/index.test.ts index e1a870245c..ac00099700 100644 --- a/src/utils/index.test.ts +++ b/src/utils/index.test.ts @@ -28,7 +28,8 @@ describe('utils', () => { describe('#calculateSlippageAmount', () => { it('bounds are correct', () => { const tokenAmount = new TokenAmount(new Token(ChainId.MAINNET, AddressZero, 0), '100') - expect(() => calculateSlippageAmount(tokenAmount, new Percent(-1, 10_000))).toThrow() + 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', @@ -44,7 +45,6 @@ describe('utils', () => { expect( calculateSlippageAmount(tokenAmount, new Percent(10000, 10_000)).map((bound) => bound.toString()) ).toEqual(['0', '200']) - expect(() => calculateSlippageAmount(tokenAmount, new Percent(10001, 10_000))).toThrow() }) }) diff --git a/src/utils/index.ts b/src/utils/index.ts index cf50d831a2..de196335e0 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -3,7 +3,7 @@ import { getAddress } from '@ethersproject/address' import { AddressZero } from '@ethersproject/constants' import { JsonRpcSigner, Web3Provider } from '@ethersproject/providers' import { BigNumber } from '@ethersproject/bignumber' -import { ChainId, Percent, Token, CurrencyAmount, Currency, ETHER } from '@uniswap/sdk-core' +import { ChainId, Percent, Token, CurrencyAmount, Currency, ETHER, Fraction } from '@uniswap/sdk-core' import { JSBI } from '@uniswap/v2-sdk' import { FeeAmount } from '@uniswap/v3-sdk/dist/' import { TokenAddressMap } from '../state/lists/hooks' @@ -63,17 +63,10 @@ export function calculateGasMargin(value: BigNumber): BigNumber { return value.mul(BigNumber.from(10000).add(BigNumber.from(1000))).div(BigNumber.from(10000)) } +const ONE = new Fraction(1, 1) export function calculateSlippageAmount(value: CurrencyAmount, slippage: Percent): [JSBI, JSBI] { - if ( - JSBI.lessThan(slippage.numerator, JSBI.BigInt(0)) || - JSBI.greaterThan(slippage.numerator, JSBI.BigInt(10_000)) || - !JSBI.equal(slippage.denominator, JSBI.BigInt(10_000)) - ) - throw new Error('Unexpected slippage') - return [ - JSBI.divide(JSBI.multiply(value.raw, JSBI.subtract(JSBI.BigInt(10000), slippage.numerator)), JSBI.BigInt(10000)), - JSBI.divide(JSBI.multiply(value.raw, JSBI.add(JSBI.BigInt(10000), slippage.numerator)), JSBI.BigInt(10000)), - ] + 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] } // account is not optional