fix: deep link by swapping sooner after user interaction (#6073)

* build: conedison@1.5

* fix: use conedison/sendTransaction when able

* build: dedup

* build: upgrade conedison again

* build: deduplicate

* fix: nits
This commit is contained in:
Zach Pomerantz 2023-03-06 15:14:47 -08:00 committed by GitHub
parent 585d67c44a
commit 3eeb467266
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 92 additions and 132 deletions

@ -135,7 +135,7 @@
"@types/react-window-infinite-loader": "^1.0.6",
"@uniswap/analytics": "^1.3.1",
"@uniswap/analytics-events": "^2.4.0",
"@uniswap/conedison": "^1.4.0",
"@uniswap/conedison": "^1.5.1",
"@uniswap/governance": "^1.0.2",
"@uniswap/liquidity-staker": "^1.0.2",
"@uniswap/merkle-distributor": "1.0.1",

@ -28,3 +28,7 @@ export const BLOCKED_PRICE_IMPACT_NON_EXPERT: Percent = new Percent(JSBI.BigInt(
export const ZERO_PERCENT = new Percent('0')
export const ONE_HUNDRED_PERCENT = new Percent('1')
// gas margin to ensure successful transactions
export const TX_GAS_MARGIN = 0.2
export const NFT_TX_GAS_MARGIN = 0.05

@ -3,14 +3,15 @@ import { BigNumber } from '@ethersproject/bignumber'
import { t } from '@lingui/macro'
import { sendAnalyticsEvent } from '@uniswap/analytics'
import { SwapEventName } from '@uniswap/analytics-events'
import { sendTransaction } from '@uniswap/conedison/provider/index'
import { Trade } from '@uniswap/router-sdk'
import { Currency, Percent, TradeType } from '@uniswap/sdk-core'
import { SwapRouter, UNIVERSAL_ROUTER_ADDRESS } from '@uniswap/universal-router-sdk'
import { FeeOptions, toHex } from '@uniswap/v3-sdk'
import { useWeb3React } from '@web3-react/core'
import { TX_GAS_MARGIN } from 'constants/misc'
import { formatSwapSignedAnalyticsEventProperties } from 'lib/utils/analytics'
import { useCallback } from 'react'
import { calculateGasMargin } from 'utils/calculateGasMargin'
import isZero from 'utils/isZero'
import { swapErrorToUserReadableMessage } from 'utils/swapErrorToUserReadableMessage'
@ -52,30 +53,19 @@ export function useUniversalRouterSwapCallback(
...(value && !isZero(value) ? { value: toHex(value) } : {}),
}
let gasEstimate: BigNumber
try {
gasEstimate = await provider.estimateGas(tx)
} catch (gasError) {
console.warn(gasError)
throw new Error('Your swap is expected to fail')
}
const gasLimit = calculateGasMargin(gasEstimate)
const response = await provider
.getSigner()
.sendTransaction({ ...tx, gasLimit })
.then((response) => {
sendAnalyticsEvent(
SwapEventName.SWAP_SIGNED,
formatSwapSignedAnalyticsEventProperties({ trade, txHash: response.hash })
const response = await sendTransaction(provider, tx, TX_GAS_MARGIN).then((response) => {
sendAnalyticsEvent(
SwapEventName.SWAP_SIGNED,
formatSwapSignedAnalyticsEventProperties({ trade, txHash: response.hash })
)
if (tx.data !== response.data) {
sendAnalyticsEvent(SwapEventName.SWAP_MODIFIED_IN_WALLET, { txHash: response.hash })
throw new InvalidSwapError(
t`Your swap was modified through your wallet. If this was a mistake, please cancel immediately or risk losing your funds.`
)
if (tx.data !== response.data) {
sendAnalyticsEvent(SwapEventName.SWAP_MODIFIED_IN_WALLET, { txHash: response.hash })
throw new InvalidSwapError(
t`Your swap was modified through your wallet. If this was a mistake, please cancel immediately or risk losing your funds.`
)
}
return response
})
}
return response
})
return response
} catch (swapError: unknown) {
if (swapError instanceof InvalidSwapError) throw swapError

@ -194,7 +194,7 @@ const Bag = () => {
const purchaseAssets = async (routingData: RouteResponse, purchasingWithErc20: boolean) => {
if (!provider || !routingData) return
const purchaseResponse = await sendTransaction(
provider?.getSigner(),
provider,
itemsInBag.filter((item) => item.status !== BagItemStatus.UNAVAILABLE).map((item) => item.asset),
routingData,
purchasingWithErc20

@ -2,9 +2,11 @@ import { Interface } from '@ethersproject/abi'
import { BigNumber } from '@ethersproject/bignumber'
import { hexStripZeros } from '@ethersproject/bytes'
import { ContractReceipt } from '@ethersproject/contracts'
import type { JsonRpcSigner } from '@ethersproject/providers'
import { JsonRpcProvider } from '@ethersproject/providers'
import { sendAnalyticsEvent } from '@uniswap/analytics'
import { NFTEventName } from '@uniswap/analytics-events'
import { sendTransaction } from '@uniswap/conedison/provider/index'
import { NFT_TX_GAS_MARGIN } from 'constants/misc'
import create from 'zustand'
import { devtools } from 'zustand/middleware'
@ -21,7 +23,7 @@ interface TxState {
clearTxHash: () => void
purchasedWithErc20: boolean
sendTransaction: (
signer: JsonRpcSigner,
provider: JsonRpcProvider,
selectedAssets: UpdatedGenieAsset[],
transactionData: RouteResponse,
purchasedWithErc20: boolean
@ -36,21 +38,18 @@ export const useSendTransaction = create<TxState>()(
purchasedWithErc20: false,
clearTxHash: () => set({ txHash: '' }),
setState: (newState) => set(() => ({ state: newState })),
sendTransaction: async (signer, selectedAssets, transactionData, purchasedWithErc20) => {
const address = await signer.getAddress()
sendTransaction: async (provider, selectedAssets, transactionData, purchasedWithErc20) => {
const address = await provider.getSigner().getAddress()
try {
const txNoGasLimit = {
set({ state: TxStateType.Signing })
const tx = {
to: transactionData.to,
value: transactionData.valueToSend ? BigNumber.from(transactionData.valueToSend) : undefined,
data: transactionData.data,
}
const res = await sendTransaction(provider, tx, NFT_TX_GAS_MARGIN)
const gasLimit = (await signer.estimateGas(txNoGasLimit)).mul(105).div(100)
// tx['gasLimit'] = gasLimit
const tx = { ...txNoGasLimit, gasLimit } // TODO test this works when firing off tx
set({ state: TxStateType.Signing })
const res = await signer.sendTransaction(tx)
set({ state: TxStateType.Confirming })
set({ txHash: res.hash })
set({ purchasedWithErc20 })

@ -3,6 +3,7 @@ import type { TransactionResponse } from '@ethersproject/providers'
import { Trans } from '@lingui/macro'
import { TraceEvent } from '@uniswap/analytics'
import { BrowserEvent, InterfaceElementName, InterfaceEventName } from '@uniswap/analytics-events'
import { sendTransaction } from '@uniswap/conedison/provider/index'
import { Currency, CurrencyAmount, Percent } from '@uniswap/sdk-core'
import { FeeAmount, NonfungiblePositionManager } from '@uniswap/v3-sdk'
import { useWeb3React } from '@web3-react/core'
@ -37,7 +38,7 @@ import Row, { AutoRow, RowBetween, RowFixed } from '../../components/Row'
import { SwitchLocaleLink } from '../../components/SwitchLocaleLink'
import TransactionConfirmationModal, { ConfirmationModalContent } from '../../components/TransactionConfirmationModal'
import { NONFUNGIBLE_POSITION_MANAGER_ADDRESSES } from '../../constants/addresses'
import { ZERO_PERCENT } from '../../constants/misc'
import { TX_GAS_MARGIN, ZERO_PERCENT } from '../../constants/misc'
import { WRAPPED_NATIVE_CURRENCY } from '../../constants/tokens'
import { useCurrency } from '../../hooks/Tokens'
import { ApprovalState, useApproveCallback } from '../../hooks/useApproveCallback'
@ -55,7 +56,6 @@ import { TransactionType } from '../../state/transactions/types'
import { useIsExpertMode, useUserSlippageToleranceWithDefault } from '../../state/user/hooks'
import { ExternalLink, ThemedText } from '../../theme'
import approveAmountCalldata from '../../utils/approveAmountCalldata'
import { calculateGasMargin } from '../../utils/calculateGasMargin'
import { currencyId } from '../../utils/currencyId'
import { maxAmountSpend } from '../../utils/maxAmountSpend'
import { Dots } from '../Pool/styleds'
@ -288,36 +288,24 @@ export default function AddLiquidity() {
setAttemptingTxn(true)
provider
.getSigner()
.estimateGas(txn)
.then((estimate) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(estimate),
}
return provider
.getSigner()
.sendTransaction(newTxn)
.then((response: TransactionResponse) => {
setAttemptingTxn(false)
addTransaction(response, {
type: TransactionType.ADD_LIQUIDITY_V3_POOL,
baseCurrencyId: currencyId(baseCurrency),
quoteCurrencyId: currencyId(quoteCurrency),
createPool: Boolean(noLiquidity),
expectedAmountBaseRaw: parsedAmounts[Field.CURRENCY_A]?.quotient?.toString() ?? '0',
expectedAmountQuoteRaw: parsedAmounts[Field.CURRENCY_B]?.quotient?.toString() ?? '0',
feeAmount: position.pool.fee,
})
setTxHash(response.hash)
sendEvent({
category: 'Liquidity',
action: 'Add',
label: [currencies[Field.CURRENCY_A]?.symbol, currencies[Field.CURRENCY_B]?.symbol].join('/'),
})
})
sendTransaction(provider, txn, TX_GAS_MARGIN)
.then((response: TransactionResponse) => {
setAttemptingTxn(false)
addTransaction(response, {
type: TransactionType.ADD_LIQUIDITY_V3_POOL,
baseCurrencyId: currencyId(baseCurrency),
quoteCurrencyId: currencyId(quoteCurrency),
createPool: Boolean(noLiquidity),
expectedAmountBaseRaw: parsedAmounts[Field.CURRENCY_A]?.quotient?.toString() ?? '0',
expectedAmountQuoteRaw: parsedAmounts[Field.CURRENCY_B]?.quotient?.toString() ?? '0',
feeAmount: position.pool.fee,
})
setTxHash(response.hash)
sendEvent({
category: 'Liquidity',
action: 'Add',
label: [currencies[Field.CURRENCY_A]?.symbol, currencies[Field.CURRENCY_B]?.symbol].join('/'),
})
})
.catch((error) => {
console.error('Failed to send transaction', error)

@ -3,6 +3,7 @@ import type { TransactionResponse } from '@ethersproject/providers'
import { Trans } from '@lingui/macro'
import { Trace } from '@uniswap/analytics'
import { InterfacePageName } from '@uniswap/analytics-events'
import { sendTransaction } from '@uniswap/conedison/provider/index'
import { Currency, CurrencyAmount, Fraction, Percent, Price, Token } from '@uniswap/sdk-core'
import { NonfungiblePositionManager, Pool, Position } from '@uniswap/v3-sdk'
import { useWeb3React } from '@web3-react/core'
@ -18,6 +19,7 @@ import { RowBetween, RowFixed } from 'components/Row'
import { Dots } from 'components/swap/styleds'
import Toggle from 'components/Toggle'
import TransactionConfirmationModal, { ConfirmationModalContent } from 'components/TransactionConfirmationModal'
import { TX_GAS_MARGIN } from 'constants/misc'
import { useToken } from 'hooks/Tokens'
import { useV3NFTPositionManagerContract } from 'hooks/useContract'
import useIsTickAtLimit from 'hooks/useIsTickAtLimit'
@ -45,7 +47,6 @@ import RateToggle from '../../components/RateToggle'
import { SwitchLocaleLink } from '../../components/SwitchLocaleLink'
import { usePositionTokenURI } from '../../hooks/usePositionTokenURI'
import { TransactionType } from '../../state/transactions/types'
import { calculateGasMargin } from '../../utils/calculateGasMargin'
import { ExplorerDataType, getExplorerLink } from '../../utils/getExplorerLink'
import { LoadingRows } from './styleds'
@ -463,36 +464,24 @@ export function PositionPage() {
value,
}
provider
.getSigner()
.estimateGas(txn)
.then((estimate) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(estimate),
}
sendTransaction(provider, txn, TX_GAS_MARGIN)
.then((response: TransactionResponse) => {
setCollectMigrationHash(response.hash)
setCollecting(false)
return provider
.getSigner()
.sendTransaction(newTxn)
.then((response: TransactionResponse) => {
setCollectMigrationHash(response.hash)
setCollecting(false)
sendEvent({
category: 'Liquidity',
action: 'CollectV3',
label: [currency0ForFeeCollectionPurposes.symbol, currency1ForFeeCollectionPurposes.symbol].join('/'),
})
sendEvent({
category: 'Liquidity',
action: 'CollectV3',
label: [currency0ForFeeCollectionPurposes.symbol, currency1ForFeeCollectionPurposes.symbol].join('/'),
})
addTransaction(response, {
type: TransactionType.COLLECT_FEES,
currencyId0: currencyId(currency0ForFeeCollectionPurposes),
currencyId1: currencyId(currency1ForFeeCollectionPurposes),
expectedCurrencyOwed0: CurrencyAmount.fromRawAmount(currency0ForFeeCollectionPurposes, 0).toExact(),
expectedCurrencyOwed1: CurrencyAmount.fromRawAmount(currency1ForFeeCollectionPurposes, 0).toExact(),
})
})
addTransaction(response, {
type: TransactionType.COLLECT_FEES,
currencyId0: currencyId(currency0ForFeeCollectionPurposes),
currencyId1: currencyId(currency1ForFeeCollectionPurposes),
expectedCurrencyOwed0: CurrencyAmount.fromRawAmount(currency0ForFeeCollectionPurposes, 0).toExact(),
expectedCurrencyOwed1: CurrencyAmount.fromRawAmount(currency1ForFeeCollectionPurposes, 0).toExact(),
})
})
.catch((error) => {
setCollecting(false)

@ -1,6 +1,7 @@
import { BigNumber } from '@ethersproject/bignumber'
import type { TransactionResponse } from '@ethersproject/providers'
import { Trans } from '@lingui/macro'
import { sendTransaction } from '@uniswap/conedison/provider/index'
import { CurrencyAmount, Percent } from '@uniswap/sdk-core'
import { NonfungiblePositionManager } from '@uniswap/v3-sdk'
import { useWeb3React } from '@web3-react/core'
@ -18,6 +19,7 @@ import { AddRemoveTabs } from 'components/NavigationTabs'
import { AutoRow, RowBetween, RowFixed } from 'components/Row'
import Slider from 'components/Slider'
import Toggle from 'components/Toggle'
import { TX_GAS_MARGIN } from 'constants/misc'
import { useV3NFTPositionManagerContract } from 'hooks/useContract'
import useDebouncedChangeHandler from 'hooks/useDebouncedChangeHandler'
import useTransactionDeadline from 'hooks/useTransactionDeadline'
@ -35,7 +37,6 @@ import { ThemedText } from 'theme'
import TransactionConfirmationModal, { ConfirmationModalContent } from '../../components/TransactionConfirmationModal'
import { WRAPPED_NATIVE_CURRENCY } from '../../constants/tokens'
import { TransactionType } from '../../state/transactions/types'
import { calculateGasMargin } from '../../utils/calculateGasMargin'
import { currencyId } from '../../utils/currencyId'
import AppBody from '../AppBody'
import { ResponsiveHeaderText, SmallMaxButton, Wrapper } from './styled'
@ -133,34 +134,22 @@ function Remove({ tokenId }: { tokenId: BigNumber }) {
value,
}
provider
.getSigner()
.estimateGas(txn)
.then((estimate) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(estimate),
}
return provider
.getSigner()
.sendTransaction(newTxn)
.then((response: TransactionResponse) => {
sendEvent({
category: 'Liquidity',
action: 'RemoveV3',
label: [liquidityValue0.currency.symbol, liquidityValue1.currency.symbol].join('/'),
})
setTxnHash(response.hash)
setAttemptingTxn(false)
addTransaction(response, {
type: TransactionType.REMOVE_LIQUIDITY_V3,
baseCurrencyId: currencyId(liquidityValue0.currency),
quoteCurrencyId: currencyId(liquidityValue1.currency),
expectedAmountBaseRaw: liquidityValue0.quotient.toString(),
expectedAmountQuoteRaw: liquidityValue1.quotient.toString(),
})
})
sendTransaction(provider, txn, TX_GAS_MARGIN)
.then((response: TransactionResponse) => {
sendEvent({
category: 'Liquidity',
action: 'RemoveV3',
label: [liquidityValue0.currency.symbol, liquidityValue1.currency.symbol].join('/'),
})
setTxnHash(response.hash)
setAttemptingTxn(false)
addTransaction(response, {
type: TransactionType.REMOVE_LIQUIDITY_V3,
baseCurrencyId: currencyId(liquidityValue0.currency),
quoteCurrencyId: currencyId(liquidityValue1.currency),
expectedAmountBaseRaw: liquidityValue0.quotient.toString(),
expectedAmountQuoteRaw: liquidityValue1.quotient.toString(),
})
})
.catch((error) => {
setAttemptingTxn(false)

@ -1,9 +1,10 @@
import { BigNumber } from '@ethersproject/bignumber'
import { TX_GAS_MARGIN } from 'constants/misc'
/**
* Returns the gas value plus a margin for unexpected or variable gas costs
* @param value the gas value to pad
*/
export function calculateGasMargin(value: BigNumber): BigNumber {
return value.mul(120).div(100)
return value.add(value.mul(Math.floor(TX_GAS_MARGIN * 100)).div(100))
}

@ -5003,10 +5003,10 @@
react "^18.2.0"
react-dom "^18.2.0"
"@uniswap/conedison@^1.3.0", "@uniswap/conedison@^1.4.0":
version "1.4.0"
resolved "https://registry.yarnpkg.com/@uniswap/conedison/-/conedison-1.4.0.tgz#44ad96333b92913a57be34bf5effcfee6534cba1"
integrity sha512-ZZMfPTjUiYpLvO0SuMPGNzkFrRpzf+bQYSL/CzaYKGSVdorRUj4XpeMdjlbuKUtHqUEunOWE8eDL3J1Hl4HOUg==
"@uniswap/conedison@^1.3.0", "@uniswap/conedison@^1.5.1":
version "1.5.1"
resolved "https://registry.yarnpkg.com/@uniswap/conedison/-/conedison-1.5.1.tgz#91527cc9928ce0187f30a5eb4abb705b8f0cd013"
integrity sha512-VJqUW4l54QVj5a4vAzAlWWd193iCcT8HMugFPB28S2Uqhs2elAg/RDQmiPOf9TOFB635MdBlD0S6xUuqo7FB4A==
"@uniswap/default-token-list@^2.0.0":
version "2.2.0"