Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(optimism): Optimism regenesis support #2703

Merged
merged 24 commits into from
Nov 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
31d41c1
feat(optimism): optimistic kovan local regenesis changes
moodysalem Oct 14, 2021
46f1b78
use the regenesis version of the sdk
moodysalem Oct 14, 2021
8f38f7b
remove the override no longer necessary
moodysalem Oct 14, 2021
04a2711
Merge branch 'main' into optimistic-kovan-local-regenesis
moodysalem Oct 14, 2021
da2c46b
diff rpc url
moodysalem Oct 14, 2021
8e5159d
Merge branch 'main' into optimistic-kovan-local-regenesis
moodysalem Oct 19, 2021
5d5ba26
back to kovan url
moodysalem Oct 19, 2021
61e8ecf
lint error
moodysalem Oct 19, 2021
a6216c9
Merge branch 'main' into optimistic-kovan-local-regenesis
moodysalem Oct 26, 2021
9417b98
Optimism mainnet regenesis test (#2695)
moodysalem Oct 27, 2021
1f3e9c7
Merge branch 'main' into optimism-regenesis
moodysalem Oct 27, 2021
6095740
bump the sdk version
moodysalem Oct 27, 2021
aa16170
copy the list
moodysalem Oct 28, 2021
022d6cd
multicall address regenesis change
moodysalem Nov 1, 2021
4b37c80
Merge branch 'main' into optimism-regenesis
moodysalem Nov 1, 2021
a980ee9
Merge branch 'main' into optimism-regenesis
moodysalem Nov 3, 2021
925a5fd
Merge branch 'main' into optimism-regenesis
moodysalem Nov 9, 2021
8107023
revert the gas limit special casing for optimism
moodysalem Nov 9, 2021
683b671
Merge branch 'main' into optimism-regenesis
moodysalem Nov 11, 2021
4c7d867
bump the sdk version
moodysalem Nov 11, 2021
f568a1c
remove a couple other temporary edits
moodysalem Nov 11, 2021
df6e28b
unused test case
moodysalem Nov 11, 2021
0ce8e89
specific version of v3-sdk
moodysalem Nov 11, 2021
6d95d74
Merge branch 'main' into optimism-regenesis
moodysalem Nov 11, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"@uniswap/v2-sdk": "^3.0.0-alpha.2",
"@uniswap/v3-core": "1.0.0",
"@uniswap/v3-periphery": "^1.1.1",
"@uniswap/v3-sdk": "^3.4.1",
"@uniswap/v3-sdk": "3.6.3",
"@web3-react/core": "^6.0.9",
"@web3-react/fortmatic-connector": "^6.0.9",
"@web3-react/injected-connector": "^6.0.7",
Expand Down
6 changes: 4 additions & 2 deletions src/constants/addresses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ type AddressMap = { [chainId: number]: string }

export const UNI_ADDRESS: AddressMap = constructSameAddressMap('0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984')
export const MULTICALL_ADDRESS: AddressMap = {
...constructSameAddressMap('0x1F98415757620B543A52E61c46B32eB19261F984', [SupportedChainId.OPTIMISTIC_KOVAN]),
[SupportedChainId.OPTIMISM]: '0x90f872b3d8f33f305e0250db6A2761B354f7710A',
...constructSameAddressMap('0x1F98415757620B543A52E61c46B32eB19261F984', [
SupportedChainId.OPTIMISTIC_KOVAN,
SupportedChainId.OPTIMISM,
]),
[SupportedChainId.ARBITRUM_ONE]: '0xadF885960B47eA2CD9B55E6DAc6B42b7Cb2806dB',
[SupportedChainId.ARBITRUM_RINKEBY]: '0xa501c031958F579dB7676fF1CE78AD305794d579',
}
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useApproveCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export function useApproveCallback(

return tokenContract
.approve(spender, useExact ? amountToApprove.quotient.toString() : MaxUint256, {
gasLimit: calculateGasMargin(chainId, estimatedGas),
gasLimit: calculateGasMargin(estimatedGas),
})
.then((response: TransactionResponse) => {
addTransaction(response, { type: TransactionType.APPROVAL, tokenAddress: token.address, spender })
Expand Down
2 changes: 0 additions & 2 deletions src/hooks/useClientSideV3Trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import { useV3Quoter } from './useContract'
import { useActiveWeb3React } from './web3'

const QUOTE_GAS_OVERRIDES: { [chainId: number]: number } = {
[SupportedChainId.OPTIMISM]: 6_000_000,
[SupportedChainId.OPTIMISTIC_KOVAN]: 6_000_000,
[SupportedChainId.ARBITRUM_ONE]: 25_000_000,
[SupportedChainId.ARBITRUM_RINKEBY]: 25_000_000,
}
Expand Down
4 changes: 1 addition & 3 deletions src/hooks/useSwapCallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,7 @@ export function useSwapCallback(
to: address,
data: calldata,
// let the wallet try if we can't estimate the gas
...('gasEstimate' in bestCallOption
? { gasLimit: calculateGasMargin(chainId, bestCallOption.gasEstimate) }
: {}),
...('gasEstimate' in bestCallOption ? { gasLimit: calculateGasMargin(bestCallOption.gasEstimate) } : {}),
...(value && !isZero(value) ? { value } : {}),
})
.then((response) => {
Expand Down
115 changes: 14 additions & 101 deletions src/pages/AddLiquidity/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ 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 { CHAIN_INFO, SupportedChainId } from '../../constants/chains'
import { ZERO_PERCENT } from '../../constants/misc'
import { WETH9_EXTENDED } from '../../constants/tokens'
import { useCurrency } from '../../hooks/Tokens'
Expand Down Expand Up @@ -205,60 +204,6 @@ export default function AddLiquidity({
outOfRange ? ZERO_PERCENT : DEFAULT_ADD_IN_RANGE_SLIPPAGE_TOLERANCE
)

// only called on optimism, atm
async function onCreate() {
if (!chainId || !library) return

if (chainId && library && position && account && deadline && baseCurrency && quoteCurrency && positionManager) {
const { calldata, value } = NonfungiblePositionManager.createCallParameters(position.pool)

const txn: { to: string; data: string; value: string } = {
to: NONFUNGIBLE_POSITION_MANAGER_ADDRESSES[chainId],
data: calldata,
value,
}

setAttemptingTxn(true)

library
.getSigner()
.estimateGas(txn)
.then((estimate) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(chainId, estimate),
}
return library
.getSigner()
.sendTransaction(newTxn)
.then((response: TransactionResponse) => {
setAttemptingTxn(false)
addTransaction(response, {
type: TransactionType.CREATE_V3_POOL,
baseCurrencyId: currencyId(baseCurrency),
quoteCurrencyId: currencyId(quoteCurrency),
})
// dont set txn hash as we dont want submitted txn screen for create
ReactGA.event({
category: 'Liquidity',
action: 'Create',
label: [currencies[Field.CURRENCY_A]?.symbol, currencies[Field.CURRENCY_B]?.symbol].join('/'),
})
})
})
.catch((error) => {
console.error('Failed to send transaction', error)
setAttemptingTxn(false)
// we only care if the error is something _other_ than the user rejected the tx
if (error?.code !== 4001) {
console.error(error)
}
})
} else {
return
}
}

async function onAdd() {
if (!chainId || !library || !account) return

Expand Down Expand Up @@ -322,7 +267,7 @@ export default function AddLiquidity({
.then((estimate) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(chainId, estimate),
gasLimit: calculateGasMargin(estimate),
}

return library
Expand Down Expand Up @@ -418,22 +363,16 @@ export default function AddLiquidity({
[currencyIdA, currencyIdB, history, onLeftRangeInput, onRightRangeInput]
)

// flag for whether pool creation must be a separate tx
const mustCreateSeparately =
noLiquidity && (chainId === SupportedChainId.OPTIMISM || chainId === SupportedChainId.OPTIMISTIC_KOVAN)

const handleDismissConfirmation = useCallback(() => {
setShowConfirm(false)
// if there was a tx hash, we want to clear the input
if (txHash) {
onFieldAInput('')
// dont jump to pool page if creating
if (!mustCreateSeparately) {
history.push('/pool')
}
history.push('/pool')
}
setTxHash('')
}, [history, mustCreateSeparately, onFieldAInput, txHash])
}, [history, onFieldAInput, txHash])

const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B)

Expand All @@ -458,15 +397,11 @@ export default function AddLiquidity({
const showApprovalB =
!argentWalletContract && approvalB !== ApprovalState.APPROVED && !!parsedAmounts[Field.CURRENCY_B]

const pendingText = mustCreateSeparately
? `Creating ${currencies[Field.CURRENCY_A]?.symbol}/${currencies[Field.CURRENCY_B]?.symbol} ${
feeAmount ? feeAmount / 10000 : ''
}% Pool`
: `Supplying ${!depositADisabled ? parsedAmounts[Field.CURRENCY_A]?.toSignificant(6) : ''} ${
!depositADisabled ? currencies[Field.CURRENCY_A]?.symbol : ''
} ${!outOfRange ? 'and' : ''} ${!depositBDisabled ? parsedAmounts[Field.CURRENCY_B]?.toSignificant(6) : ''} ${
!depositBDisabled ? currencies[Field.CURRENCY_B]?.symbol : ''
}`
const pendingText = `Supplying ${!depositADisabled ? parsedAmounts[Field.CURRENCY_A]?.toSignificant(6) : ''} ${
!depositADisabled ? currencies[Field.CURRENCY_A]?.symbol : ''
} ${!outOfRange ? 'and' : ''} ${!depositBDisabled ? parsedAmounts[Field.CURRENCY_B]?.toSignificant(6) : ''} ${
!depositBDisabled ? currencies[Field.CURRENCY_B]?.symbol : ''
}`

const Buttons = () =>
addIsUnsupported ? (
Expand Down Expand Up @@ -519,32 +454,18 @@ export default function AddLiquidity({
)}
</RowBetween>
)}
{mustCreateSeparately && (
<ButtonError onClick={onCreate} disabled={!isValid || attemptingTxn || !position}>
{attemptingTxn ? (
<Dots>
<Trans>Confirm Create</Trans>
</Dots>
) : (
<Text fontWeight={500}>{errorMessage ? errorMessage : <Trans>Create</Trans>}</Text>
)}
</ButtonError>
)}
<ButtonError
onClick={() => {
expertMode ? onAdd() : setShowConfirm(true)
}}
disabled={
mustCreateSeparately ||
!isValid ||
(!argentWalletContract && approvalA !== ApprovalState.APPROVED && !depositADisabled) ||
(!argentWalletContract && approvalB !== ApprovalState.APPROVED && !depositBDisabled)
}
error={!isValid && !!parsedAmounts[Field.CURRENCY_A] && !!parsedAmounts[Field.CURRENCY_B]}
>
<Text fontWeight={500}>
{mustCreateSeparately ? <Trans>Add</Trans> : errorMessage ? errorMessage : <Trans>Preview</Trans>}
</Text>
<Text fontWeight={500}>{errorMessage ? errorMessage : <Trans>Preview</Trans>}</Text>
</ButtonError>
</AutoColumn>
)
Expand Down Expand Up @@ -793,19 +714,11 @@ export default function AddLiquidity({
textAlign="left"
color={theme.primaryText1}
>
{mustCreateSeparately ? (
<Trans>
{`This pool must be initialized on ${
chainId && CHAIN_INFO ? CHAIN_INFO[chainId].label : ''
} before you can add liquidity. To initialize, select a starting price for the pool. Then, enter your liquidity price range and deposit amount.`}
</Trans>
) : (
<Trans>
This pool must be initialized before you can add liquidity. To initialize, select a
starting price for the pool. Then, enter your liquidity price range and deposit
amount. Gas fees will be higher than usual due to the initialization transaction.
</Trans>
)}
<Trans>
This pool must be initialized before you can add liquidity. To initialize, select a
starting price for the pool. Then, enter your liquidity price range and deposit
amount. Gas fees will be higher than usual due to the initialization transaction.
</Trans>
</TYPE.body>
</BlueCard>
)}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/AddLiquidityV2/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export default function AddLiquidity({
.then((estimatedGasLimit) =>
method(...args, {
...(value ? { value } : {}),
gasLimit: calculateGasMargin(chainId, estimatedGasLimit),
gasLimit: calculateGasMargin(estimatedGasLimit),
}).then((response) => {
setAttemptingTxn(false)

Expand Down
2 changes: 1 addition & 1 deletion src/pages/MigrateV2/MigrateV2Pair.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ function V2PairMigration({
.multicall(data)
.then((gasEstimate) => {
return migrator
.multicall(data, { gasLimit: calculateGasMargin(chainId, gasEstimate) })
.multicall(data, { gasLimit: calculateGasMargin(gasEstimate) })
.then((response: TransactionResponse) => {
ReactGA.event({
category: 'Migrate',
Expand Down
7 changes: 2 additions & 5 deletions src/pages/Pool/PositionPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { RowBetween, RowFixed } from 'components/Row'
import { Dots } from 'components/swap/styleds'
import Toggle from 'components/Toggle'
import TransactionConfirmationModal, { ConfirmationModalContent } from 'components/TransactionConfirmationModal'
import { SupportedChainId } from 'constants/chains'
import { useToken } from 'hooks/Tokens'
import { useV3NFTPositionManagerContract } from 'hooks/useContract'
import useIsTickAtLimit from 'hooks/useIsTickAtLimit'
Expand Down Expand Up @@ -443,7 +442,7 @@ export function PositionPage({
.then((estimate) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(chainId, estimate),
gasLimit: calculateGasMargin(estimate),
}

return library
Expand Down Expand Up @@ -514,15 +513,13 @@ export function PositionPage({
)
}

const onOptimisticChain = chainId && [SupportedChainId.OPTIMISM, SupportedChainId.OPTIMISTIC_KOVAN].includes(chainId)
const showCollectAsWeth = Boolean(
ownsNFT &&
(feeValue0?.greaterThan(0) || feeValue1?.greaterThan(0)) &&
currency0 &&
currency1 &&
(currency0.isNative || currency1.isNative) &&
!collectMigrationHash &&
!onOptimisticChain
!collectMigrationHash
)

return loading || poolState === PoolState.LOADING || !feeAmount ? (
Expand Down
7 changes: 2 additions & 5 deletions src/pages/RemoveLiquidity/V3.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { AddRemoveTabs } from 'components/NavigationTabs'
import { AutoRow, RowBetween, RowFixed } from 'components/Row'
import Slider from 'components/Slider'
import Toggle from 'components/Toggle'
import { SupportedChainId } from 'constants/chains'
import { useV3NFTPositionManagerContract } from 'hooks/useContract'
import useDebouncedChangeHandler from 'hooks/useDebouncedChangeHandler'
import useTheme from 'hooks/useTheme'
Expand Down Expand Up @@ -140,7 +139,7 @@ function Remove({ tokenId }: { tokenId: BigNumber }) {
.then((estimate) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(chainId, estimate),
gasLimit: calculateGasMargin(estimate),
}

return library
Expand Down Expand Up @@ -262,10 +261,8 @@ function Remove({ tokenId }: { tokenId: BigNumber }) {
)
}

const onOptimisticChain = chainId && [SupportedChainId.OPTIMISM, SupportedChainId.OPTIMISTIC_KOVAN].includes(chainId)
const showCollectAsWeth = Boolean(
!onOptimisticChain &&
liquidityValue0?.currency &&
liquidityValue0?.currency &&
liquidityValue1?.currency &&
(liquidityValue0.currency.isNative ||
liquidityValue1.currency.isNative ||
Expand Down
2 changes: 1 addition & 1 deletion src/pages/RemoveLiquidity/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export default function RemoveLiquidity({
const safeGasEstimates: (BigNumber | undefined)[] = await Promise.all(
methodNames.map((methodName) =>
router.estimateGas[methodName](...args)
.then((estimateGas) => calculateGasMargin(chainId, estimateGas))
.then((estimateGas) => calculateGasMargin(estimateGas))
.catch((error) => {
console.error(`estimateGas failed`, methodName, args, error)
return undefined
Expand Down
2 changes: 1 addition & 1 deletion src/state/claim/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export function useClaimCallback(account: string | null | undefined): {

return distributorContract.estimateGas['claim'](...args, {}).then((estimatedGasLimit) => {
return distributorContract
.claim(...args, { value: null, gasLimit: calculateGasMargin(chainId, estimatedGasLimit) })
.claim(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
type: TransactionType.CLAIM,
Expand Down
6 changes: 3 additions & 3 deletions src/state/governance/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ export function useDelegateCallback(): (delegatee: string | undefined) => undefi
if (!uniContract) throw new Error('No UNI Contract!')
return uniContract.estimateGas.delegate(...args, {}).then((estimatedGasLimit) => {
return uniContract
.delegate(...args, { value: null, gasLimit: calculateGasMargin(chainId, estimatedGasLimit) })
.delegate(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
type: TransactionType.DELEGATE,
Expand Down Expand Up @@ -335,7 +335,7 @@ export function useVoteCallback(): {
const args = [proposalId, voteOption === VoteOption.Against ? 0 : voteOption === VoteOption.For ? 1 : 2]
return latestGovernanceContract.estimateGas.castVote(...args, {}).then((estimatedGasLimit) => {
return latestGovernanceContract
.castVote(...args, { value: null, gasLimit: calculateGasMargin(chainId, estimatedGasLimit) })
.castVote(...args, { value: null, gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
type: TransactionType.VOTE,
Expand Down Expand Up @@ -375,7 +375,7 @@ export function useCreateProposalCallback(): (

return latestGovernanceContract.estimateGas.propose(...args).then((estimatedGasLimit) => {
return latestGovernanceContract
.propose(...args, { gasLimit: calculateGasMargin(chainId, estimatedGasLimit) })
.propose(...args, { gasLimit: calculateGasMargin(estimatedGasLimit) })
.then((response: TransactionResponse) => {
addTransaction(response, {
type: TransactionType.SUBMIT_PROPOSAL,
Expand Down
10 changes: 1 addition & 9 deletions src/state/wallet/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Interface } from '@ethersproject/abi'
import { Currency, CurrencyAmount, Ether, Token } from '@uniswap/sdk-core'
import ERC20ABI from 'abis/erc20.json'
import { Erc20Interface } from 'abis/types/Erc20'
import { SupportedChainId } from 'constants/chains'
import JSBI from 'jsbi'
import { useMemo } from 'react'

Expand Down Expand Up @@ -52,11 +51,6 @@ export function useETHBalances(uncheckedAddresses?: (string | undefined)[]): {
)
}

const TOKEN_BALANCE_GAS_OVERRIDE: { [chainId: number]: number } = {
[SupportedChainId.OPTIMISM]: 250_000,
[SupportedChainId.OPTIMISTIC_KOVAN]: 250_000,
}

/**
* Returns a map of token addresses to their eventually consistent token balances for a single account.
*/
Expand All @@ -69,12 +63,10 @@ export function useTokenBalancesWithLoadingIndicator(
[tokens]
)

const { chainId } = useActiveWeb3React()

const validatedTokenAddresses = useMemo(() => validatedTokens.map((vt) => vt.address), [validatedTokens])
const ERC20Interface = new Interface(ERC20ABI) as Erc20Interface
const balances = useMultipleContractSingleData(validatedTokenAddresses, ERC20Interface, 'balanceOf', [address], {
gasRequired: (chainId && TOKEN_BALANCE_GAS_OVERRIDE[chainId]) ?? 100_000,
gasRequired: 100_000,
})

const anyLoading: boolean = useMemo(() => balances.some((callState) => callState.loading), [balances])
Expand Down
Loading