Skip to content

Commit

Permalink
fix(twap): allow creating orders with 100% slippage (cowprotocol#3897)
Browse files Browse the repository at this point in the history
  • Loading branch information
shoom3301 authored Feb 26, 2024
1 parent 0275de9 commit 05a604d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { atom } from 'jotai'

import { FractionUtils } from '@cowprotocol/common-utils'
import { walletInfoAtom } from '@cowprotocol/wallet'
import { CurrencyAmount, Token } from '@uniswap/sdk-core'

Expand Down Expand Up @@ -38,7 +39,9 @@ export const twapSlippageAdjustedBuyAmount = atom<CurrencyAmount<Token> | null>(
const slippage = get(twapOrderSlippageAtom)

const slippageAmount = outputCurrencyAmount.multiply(slippage)
return outputCurrencyAmount.subtract(slippageAmount) as CurrencyAmount<Token>
const buyAmount = outputCurrencyAmount.subtract(slippageAmount) as CurrencyAmount<Token>

return FractionUtils.amountToAtLeastOneWei(buyAmount)
})

export const twapOrderAtom = atom<TWAPOrder | null>((get) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { NATIVE_CURRENCY_ADDRESS } from '@cowprotocol/common-const'
import { getIsNativeToken } from '@cowprotocol/common-utils'
import { FractionUtils, getIsNativeToken } from '@cowprotocol/common-utils'

import { TWAPOrder, TWAPOrderStruct } from '../types'

export function twapOrderToStruct(order: TWAPOrder): TWAPOrderStruct {
const buyToken = order.buyAmount.currency
const minPartLimit = FractionUtils.amountToAtLeastOneWei(order.buyAmount.divide(order.numOfParts))

return {
sellToken: order.sellAmount.currency.address,
buyToken: getIsNativeToken(buyToken) ? NATIVE_CURRENCY_ADDRESS : buyToken.address,
receiver: order.receiver,
partSellAmount: order.sellAmount.divide(order.numOfParts).quotient.toString(),
minPartLimit: order.buyAmount.divide(order.numOfParts).quotient.toString(),
minPartLimit: minPartLimit.quotient.toString(),
t0: order.startTime,
n: order.numOfParts,
t: order.timeInterval,
Expand Down
9 changes: 9 additions & 0 deletions libs/common-utils/src/fractionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,13 @@ export class FractionUtils {

return new Fraction(JSBI.BigInt(numerator), JSBI.BigInt(denominator))
}

/**
* When an amount equals zero, return 1 wei, otherwise return amount
*
* @param amount
*/
static amountToAtLeastOneWei(amount: CurrencyAmount<Token>): CurrencyAmount<Token> {
return JSBI.EQ(amount.quotient, 0) ? CurrencyAmount.fromRawAmount(amount.currency, 1) : amount
}
}

0 comments on commit 05a604d

Please sign in to comment.