Skip to content

Commit

Permalink
Merge pull request #3554 from cowprotocol/release/1.54.0
Browse files Browse the repository at this point in the history
Release/1.54.0
  • Loading branch information
shoom3301 authored Dec 26, 2023
2 parents 0dc940e + 784d3a8 commit a6b514e
Show file tree
Hide file tree
Showing 25 changed files with 247 additions and 63 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export function useApproveCallback(
addTransaction({
hash: response.hash,
summary: amountToApprove.greaterThan('0') ? `Approve ${token.symbol}` : `Revoke ${token.symbol} approval`,
approval: { tokenAddress: token.address, spender },
approval: { tokenAddress: token.address, spender, amount: '0x' + amountToApprove.quotient.toString(16) },
})
return response
})
Expand Down
23 changes: 21 additions & 2 deletions apps/cowswap-frontend/src/common/updaters/FinalizeTxUpdater.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useSetAtom } from 'jotai'
import { useEffect, useMemo } from 'react'

import { useAddPriorityAllowance } from '@cowprotocol/balances-and-allowances'
import { GetReceipt, useBlockNumber, useGetReceipt } from '@cowprotocol/common-hooks'
import { SupportedChainId } from '@cowprotocol/cow-sdk'
import { useWalletInfo } from '@cowprotocol/wallet'
import { TransactionReceipt } from '@ethersproject/abstract-provider'
import { useWeb3React } from '@web3-react/core'
Expand Down Expand Up @@ -53,13 +55,15 @@ export function shouldCheck(lastBlockNumber: number, tx: TxInterface): boolean {
}

interface CheckEthereumTransactions {
chainId: number
chainId: SupportedChainId
account: string | undefined
transactions: EnhancedTransactionDetails[]
lastBlockNumber: number
getReceipt: GetReceipt
getSafeInfo: GetSafeInfo
dispatch: AppDispatch
addPopup: ReturnType<typeof useAddPopup>
addPriorityAllowance: ReturnType<typeof useAddPriorityAllowance>
removeInFlightOrderId: (update: string) => void
nativeCurrencySymbol: string
cancelOrdersBatch: CancelOrdersBatchCallback
Expand All @@ -72,11 +76,21 @@ function finalizeEthereumTransaction(
transaction: EnhancedTransactionDetails,
params: CheckEthereumTransactions
) {
const { chainId, addPopup, dispatch } = params
const { chainId, account, addPopup, dispatch, addPriorityAllowance } = params
const { hash } = transaction

console.log(`[FinalizeTxUpdater] Transaction ${receipt.transactionHash} has been mined`, receipt)

// Once approval tx is mined, we add the priority allowance to immediately allow the user to place orders
if (transaction.approval) {
addPriorityAllowance({
chainId,
account,
blockNumber: receipt.blockNumber,
tokenAddress: transaction.approval.tokenAddress,
})
}

dispatch(
finalizeTransaction({
chainId,
Expand Down Expand Up @@ -264,6 +278,7 @@ export function FinalizeTxUpdater(): null {
const cancelOrdersBatch = useCancelOrdersBatch()
const getReceipt = useGetReceipt(chainId)
const getSafeInfo = useGetSafeInfo()
const addPriorityAllowance = useAddPriorityAllowance()
const addPopup = useAddPopup()
const removeInFlightOrderId = useSetAtom(removeInFlightOrderIdAtom)
const nativeCurrencySymbol = useNativeCurrency().symbol || 'ETH'
Expand Down Expand Up @@ -292,6 +307,8 @@ export function FinalizeTxUpdater(): null {
removeInFlightOrderId,
nativeCurrencySymbol,
cancelOrdersBatch,
addPriorityAllowance,
account,
})

return () => {
Expand All @@ -300,6 +317,7 @@ export function FinalizeTxUpdater(): null {
}
}, [
chainId,
account,
provider,
transactions,
lastBlockNumber,
Expand All @@ -310,6 +328,7 @@ export function FinalizeTxUpdater(): null {
removeInFlightOrderId,
nativeCurrencySymbol,
cancelOrdersBatch,
addPriorityAllowance,
])

return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ interface AccountElementProps {
export function AccountElement({ className, isWidgetMode, pendingActivities }: AccountElementProps) {
const { account, chainId } = useWalletInfo()
const isChainIdUnsupported = useIsProviderNetworkUnsupported()
const userEthBalance = useNativeCurrencyAmount()
const userEthBalance = useNativeCurrencyAmount(chainId, account)
const toggleAccountModal = useToggleAccountModal()
const nativeToken = NATIVE_CURRENCY_BUY_TOKEN[chainId].symbol

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export function useApproveCallback({
addTransaction({
hash: response.hash,
summary: optionalParams?.transactionSummary || 'Approve ' + amountToApprove.currency.symbol,
approval: { tokenAddress: token.address, spender },
approval: { tokenAddress: token.address, spender, amount: '0x' + amountToApprove.quotient.toString(16) },
})
return response
})
Expand Down Expand Up @@ -216,16 +216,19 @@ export function useApproveCallback({
optionalParams?.modalMessage || `Revoke ${token.symbol} approval from ${spenderCurrency?.symbol || spender}`,
ConfirmOperationType.REVOKE_APPROVE_TOKEN
)

const amount = '0'

return (
tokenContract
.approve(spender, '0', {
.approve(spender, amount, {
gasLimit: calculateGasMargin(estimatedGas),
})
.then((response: TransactionResponse) => {
addTransaction({
hash: response.hash,
summary: optionalParams?.transactionSummary || `Revoke ${token.symbol} approval from ${spender}`,
approval: { tokenAddress: getWrappedToken(token).address, spender },
approval: { tokenAddress: getWrappedToken(token).address, spender, amount },
})
})
// .catch((error: Error) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
calculateValidTo,
getQuoteUnsupportedToken,
} from '@cowprotocol/common-utils'
import { PriceQuality } from '@cowprotocol/cow-sdk'
import { PriceQuality, OrderKind } from '@cowprotocol/cow-sdk'
import { useAddUnsupportedToken, useIsUnsupportedToken, useRemoveUnsupportedToken } from '@cowprotocol/tokens'

import { useGetGpPriceStrategy } from 'legacy/hooks/useGetGpPriceStrategy'
Expand All @@ -29,6 +29,8 @@ import GpQuoteError, {
isValidQuoteError,
} from 'api/gnosisProtocol/errors/QuoteError'

import { logSwapParams } from '../../modules/swap/helpers/logSwapParams'

interface HandleQuoteErrorParams {
quoteData: QuoteInformationObject | LegacyFeeQuoteParams
error: unknown
Expand Down Expand Up @@ -184,6 +186,13 @@ export function useRefetchQuoteCallback() {
removeGpUnsupportedToken(previouslyUnsupportedToken)
}

logSwapParams('quote', {
sellAmount: quoteData.kind === OrderKind.SELL ? quoteData.amount : price.value.amount,
buyAmount: quoteData.kind === OrderKind.BUY ? quoteData.amount : price.value.amount,
feeAmount: fee.value.amount,
sellDecimals: quoteData.fromDecimals,
buyDecimals: quoteData.toDecimals,
})
// Update quote
updateQuote({ ...quoteData, isBestQuote })
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ describe('transaction reducer', () => {
describe('addTransaction', () => {
it('adds the transaction', () => {
const beforeTime = new Date().getTime()
const approval = { tokenAddress: 'abc', spender: 'def', amount: '0x1' }

store.dispatch(
addTransaction({
hash: '0x0',
hashType: HashType.ETHEREUM_TX,
chainId: 1,
summary: 'hello world',
approval: { tokenAddress: 'abc', spender: 'def' },
approval,
from: 'abc',
})
)
Expand All @@ -30,7 +32,7 @@ describe('transaction reducer', () => {
expect(tx).toBeTruthy()
expect(tx?.hash).toEqual('0x0')
expect(tx?.summary).toEqual('hello world')
expect(tx?.approval).toEqual({ tokenAddress: 'abc', spender: 'def' })
expect(tx?.approval).toEqual(approval)
expect(tx?.from).toEqual('abc')
expect(tx?.addedTime).toBeGreaterThanOrEqual(beforeTime)
})
Expand Down Expand Up @@ -62,7 +64,7 @@ describe('transaction reducer', () => {
hash: '0x0',
hashType: HashType.ETHEREUM_TX,
chainId: 4,
approval: { spender: '0x0', tokenAddress: '0x0' },
approval: { spender: '0x0', tokenAddress: '0x0', amount: '0x1' },
summary: 'hello world',
from: '0x0',
})
Expand Down Expand Up @@ -117,7 +119,7 @@ describe('transaction reducer', () => {
hash: '0x0',
hashType: HashType.ETHEREUM_TX,
chainId: 4,
approval: { spender: '0x0', tokenAddress: '0x0' },
approval: { spender: '0x0', tokenAddress: '0x0', amount: '0x1' },
summary: 'hello world',
from: '0x0',
})
Expand All @@ -138,7 +140,7 @@ describe('transaction reducer', () => {
hash: '0x0',
hashType: HashType.ETHEREUM_TX,
chainId: 4,
approval: { spender: '0x0', tokenAddress: '0x0' },
approval: { spender: '0x0', tokenAddress: '0x0', amount: '0x1' },
summary: 'hello world',
from: '0x0',
})
Expand Down Expand Up @@ -170,7 +172,7 @@ describe('transaction reducer', () => {
hashType: HashType.ETHEREUM_TX,
chainId: 1,
summary: 'hello world',
approval: { tokenAddress: 'abc', spender: 'def' },
approval: { tokenAddress: 'abc', spender: 'def', amount: '0x1' },
from: 'abc',
})
)
Expand All @@ -180,7 +182,7 @@ describe('transaction reducer', () => {
hashType: HashType.ETHEREUM_TX,
chainId: 4,
summary: 'hello world',
approval: { tokenAddress: 'abc', spender: 'def' },
approval: { tokenAddress: 'abc', spender: 'def', amount: '0x1' },
from: 'abc',
})
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ export interface EnhancedTransactionDetails {
data?: any // any attached data type

// Operations
approval?: { tokenAddress: string; spender: string }
approval?: {
tokenAddress: string
spender: string
// Hex string
amount: string
}
presign?: { orderId: string }
claim?: { recipient: string; cowAmountRaw?: string; indices: number[] }
swapVCow?: boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { useMemo } from 'react'

import { Order, PENDING_STATES } from 'legacy/state/orders/actions'

import { getIsComposableCowOrder } from 'utils/orderUtils/getIsComposableCowOrder'
import { getIsNotComposableCowOrder } from 'utils/orderUtils/getIsNotComposableCowOrder'

import { TabOrderTypes } from '../../../pure/OrdersTableContainer'
import { groupOrdersTable } from '../../../utils/groupOrdersTable'
import { getParsedOrderFromTableItem, isParsedOrder, OrderTableItem } from '../../../utils/orderTableGroupUtils'

Expand All @@ -19,7 +23,7 @@ const ordersSorter = (a: OrderTableItem, b: OrderTableItem) => {

const ORDERS_LIMIT = 100

export function useOrdersTableList(allOrders: Order[]): OrdersTableList {
export function useOrdersTableList(allOrders: Order[], orderType: TabOrderTypes): OrdersTableList {
const allSortedOrders = useMemo(() => {
return groupOrdersTable(allOrders).sort(ordersSorter)
}, [allOrders])
Expand All @@ -29,6 +33,14 @@ export function useOrdersTableList(allOrders: Order[]): OrdersTableList {
(acc, item) => {
const order = isParsedOrder(item) ? item : item.parent

const advancedTabNonAdvancedOrder = orderType === TabOrderTypes.ADVANCED && getIsNotComposableCowOrder(order)
const limitTabNonLimitOrder = orderType === TabOrderTypes.LIMIT && getIsComposableCowOrder(order)

if (advancedTabNonAdvancedOrder || limitTabNonLimitOrder) {
// Skip if order type doesn't match
return acc
}

if (PENDING_STATES.includes(order.status)) {
acc.pending.push(item)
} else {
Expand All @@ -41,5 +53,5 @@ export function useOrdersTableList(allOrders: Order[]): OrdersTableList {
)

return { pending: pending.slice(0, ORDERS_LIMIT), history: history.slice(0, ORDERS_LIMIT) }
}, [allSortedOrders])
}, [allSortedOrders, orderType])
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function OrdersTableWidget({
const location = useLocation()
const navigate = useNavigate()
const cancelOrder = useCancelOrder()
const ordersList = useOrdersTableList(allOrders)
const ordersList = useOrdersTableList(allOrders, orderType)
const { allowsOffchainSigning } = useWalletDetails()
const pendingOrdersPrices = useAtomValue(pendingOrdersPricesAtom)
const ordersToCancel = useAtomValue(ordersToCancelAtom)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ describe('getAmountsForSignature()', () => {

/**
* Sell amount is just what user entered
* Output amount calculated as: (outputAmount - slippage) - fee
* Output amount calculated as: outputAmount - slippage
*/
it('Sell order', () => {
const trade = getTrade({ tradeType: TradeType.EXACT_INPUT, inputAmount, outputAmount, feeAmount })
Expand All @@ -114,13 +114,12 @@ describe('getAmountsForSignature()', () => {
// Input amount the same, because we don't subtract fee
expect(result.inputAmount.toFixed()).toEqual('3012.000000')

// Fee in WETH = 0.005312084993359893
// outputAmount = (2 - 5%) - 0.005312 = 1.89468
expect(result.outputAmount.toFixed()).toEqual('1.894687915006640106')
// outputAmount = 2 - 5% = 1.894953
expect(result.outputAmount.toFixed()).toEqual('1.894953519256308100')
})

/**
* Sell amount calculated as: (inputAmount + slippage) + fee
* Sell amount calculated as: inputAmount + slippage
* Output amount is just what user entered
*/
it('Buy order', () => {
Expand All @@ -133,8 +132,8 @@ describe('getAmountsForSignature()', () => {
kind: OrderKind.BUY,
})

// inputAmount = (3012 + 5%) + 8 = 3170
expect(result.inputAmount.toFixed()).toEqual('3170.600000')
// inputAmount = 3012 + 5% = 3162.600000
expect(result.inputAmount.toFixed()).toEqual('3162.600000')

// Output amount the same, because this is buy order
expect(result.outputAmount.toFixed()).toEqual('2.000000000000000000')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,13 @@ interface AmountForSignatureParams {

function inputAmountForSignature(params: AmountForSignatureParams): CurrencyAmount<Currency> {
const { trade, allowedSlippage, kind, featureFlags } = params
const fee = trade.fee.feeAsCurrency
const slippageCoeff = ONE_FRACTION.add(allowedSlippage)

if (featureFlags.swapZeroFee) {
if (kind === OrderKind.SELL) {
return trade.inputAmount
} else {
return trade.inputAmountWithoutFee
.multiply(slippageCoeff) // add slippage
.add(fee) // add fee
return trade.inputAmountWithoutFee.multiply(slippageCoeff) // add slippage
}
}

Expand All @@ -41,13 +38,7 @@ function outputAmountForSignature(params: AmountForSignatureParams): CurrencyAmo

if (featureFlags.swapZeroFee) {
if (kind === OrderKind.SELL) {
const shouldRevertPrice = trade.executionPrice.quoteCurrency.equals(trade.fee.feeAsCurrency.currency)
const price = shouldRevertPrice ? trade.executionPrice.invert() : trade.executionPrice
const feeInOutputCurrency = price.quote(trade.fee.feeAsCurrency)

return trade.outputAmountWithoutFee
.multiply(slippageCoeff) // subtract slippage
.subtract(feeInOutputCurrency) // subtract fee
return trade.outputAmount.multiply(slippageCoeff) // subtract slippage
} else {
return trade.outputAmountWithoutFee
}
Expand Down
12 changes: 12 additions & 0 deletions apps/cowswap-frontend/src/modules/swap/helpers/logSwapParams.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
type SwapParamsData = Record<string, string | number | null | undefined>

const CACHE: Record<string, SwapParamsData> = {}

export function logSwapParams(key: string, data: SwapParamsData) {
const cached = CACHE[key]

if (cached && JSON.stringify(cached) === JSON.stringify(data)) return

CACHE[key] = data
console.log(`[SWAP PARAMS] ${key}`, data)
}
Loading

2 comments on commit a6b514e

@vercel
Copy link

@vercel vercel bot commented on a6b514e Dec 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on a6b514e Dec 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

cosmos – ./

cosmos-cowswap.vercel.app
cosmos-git-main-cowswap.vercel.app
cowswap-seven.vercel.app
cosmos.cow.fi

Please sign in to comment.