Skip to content

Commit

Permalink
Don't crash for zero liquidity pairs
Browse files Browse the repository at this point in the history
  • Loading branch information
moodysalem committed May 13, 2020
1 parent 9da0e6a commit f0a6fdb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/entities/trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ export class Trade {
const pair = pairs[i]
// pair irrelevant
if (!pair.token0.equals(amountIn.token) && !pair.token1.equals(amountIn.token)) continue
if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue

let amountOut: TokenAmount
try {
Expand Down Expand Up @@ -234,6 +235,7 @@ export class Trade {
const pair = pairs[i]
// pair irrelevant
if (!pair.token0.equals(amountOut.token) && !pair.token1.equals(amountOut.token)) continue
if (pair.reserve0.equalTo(ZERO) || pair.reserve1.equalTo(ZERO)) continue

let amountIn: TokenAmount
try {
Expand Down
14 changes: 14 additions & 0 deletions test/trade.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ describe('Trade', () => {
const pair_1_2 = new Pair(new TokenAmount(token1, JSBI.BigInt(1200)), new TokenAmount(token2, JSBI.BigInt(1000)))
const pair_1_3 = new Pair(new TokenAmount(token1, JSBI.BigInt(1200)), new TokenAmount(token3, JSBI.BigInt(1300)))

const empty_pair_0_1 = new Pair(new TokenAmount(token0, JSBI.BigInt(0)), new TokenAmount(token1, JSBI.BigInt(0)))

describe('#bestTradeExactIn', () => {
it('throws with empty pairs', () => {
expect(() => Trade.bestTradeExactIn([], new TokenAmount(token0, JSBI.BigInt(100)), token2)).toThrow('PAIRS')
Expand Down Expand Up @@ -40,6 +42,12 @@ describe('Trade', () => {
expect(result[1].outputAmount).toEqual(new TokenAmount(token2, JSBI.BigInt(69)))
})

it('doesnt throw for zero liquidity pairs', () => {
expect(Trade.bestTradeExactIn([empty_pair_0_1], new TokenAmount(token0, JSBI.BigInt(100)), token1)).toHaveLength(
0
)
})

it('respects maxHops', () => {
const result = Trade.bestTradeExactIn(
[pair_0_1, pair_0_2, pair_1_2],
Expand Down Expand Up @@ -224,6 +232,12 @@ describe('Trade', () => {
expect(result[1].outputAmount).toEqual(new TokenAmount(token2, JSBI.BigInt(100)))
})

it('doesnt throw for zero liquidity pairs', () => {
expect(Trade.bestTradeExactOut([empty_pair_0_1], token1, new TokenAmount(token1, JSBI.BigInt(100)))).toHaveLength(
0
)
})

it('respects maxHops', () => {
const result = Trade.bestTradeExactOut(
[pair_0_1, pair_0_2, pair_1_2],
Expand Down

0 comments on commit f0a6fdb

Please sign in to comment.