Skip to content

Commit

Permalink
Merge branch 'main' into feat/addLiquidityPermit2
Browse files Browse the repository at this point in the history
  • Loading branch information
agualis committed Sep 24, 2024
2 parents a720db9 + de13451 commit f2c0788
Show file tree
Hide file tree
Showing 15 changed files with 191 additions and 47 deletions.
8 changes: 4 additions & 4 deletions lib/config/networks/polygon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,17 @@ const networkConfig: NetworkConfig = {
wNativeAsset: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
},
nativeAsset: {
name: 'Matic',
name: 'Pol',
address: '0x0000000000000000000000000000000000001010',
symbol: 'MATIC',
symbol: 'POL',
decimals: 18,
},
defaultSwapTokens: {
tokenIn: '0x0000000000000000000000000000000000001010',
},
popularTokens: {
'0x0000000000000000000000000000000000001010': 'MATIC',
'0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270': 'WMATIC',
'0x0000000000000000000000000000000000001010': 'POL',
'0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270': 'WPOL',
'0xfa68fb4628dff1028cfec22b4162fccd0d45efb6': 'MaticX',
'0x7ceb23fd6bc0add59e62ac25578270cff1b9f619': 'WETH',
'0x9a71012b13ca4d3d0cdc72a177df3ef03b0e76a3': 'BAL',
Expand Down
2 changes: 1 addition & 1 deletion lib/debug-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const usdcAddress = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' as const
export const usdtAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7' as const

export const ethAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' as const
export const maticAddress = '0x0000000000000000000000000000000000001010' as const
export const polAddress = '0x0000000000000000000000000000000000001010' as const

export const vEth = '0x4bc3263eb5bb2ef7ad9ab6fb68be80e43b43801f' as const

Expand Down
11 changes: 10 additions & 1 deletion lib/modules/pool/actions/add-liquidity/form/AddLiquidityForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import { useUserAccount } from '@/lib/modules/web3/UserAccountProvider'
import { ConnectWallet } from '@/lib/modules/web3/ConnectWallet'
import { BalAlert } from '@/lib/shared/components/alerts/BalAlert'
import { SafeAppAlert } from '@/lib/shared/components/alerts/SafeAppAlert'
import { useTokens } from '@/lib/modules/tokens/TokensProvider'

// small wrapper to prevent out of context error
export function AddLiquidityForm() {
Expand Down Expand Up @@ -87,6 +88,7 @@ function AddLiquidityMainForm() {
const { setValidationError } = useTokenInputsValidation()
const { balanceFor, isBalancesLoading } = useTokenBalances()
const { isConnected } = useUserAccount()
const { startTokenPricePolling } = useTokens()

useEffect(() => {
setPriceImpact(priceImpactQuery.data)
Expand Down Expand Up @@ -148,6 +150,13 @@ function AddLiquidityMainForm() {
}
}, [addLiquidityTxHash])

function onModalClose() {
// restart polling for token prices when modal is closed again
startTokenPricePolling()

previewModalDisclosure.onClose()
}

return (
<Box w="full" maxW="lg" mx="auto" pb="2xl">
<Card>
Expand Down Expand Up @@ -259,7 +268,7 @@ function AddLiquidityMainForm() {
finalFocusRef={nextBtn}
isOpen={previewModalDisclosure.isOpen}
onOpen={previewModalDisclosure.onOpen}
onClose={previewModalDisclosure.onClose}
onClose={onModalClose}
/>
{!!validTokens.length && (
<NativeAssetSelectModal
Expand Down
11 changes: 11 additions & 0 deletions lib/modules/pool/actions/add-liquidity/modal/AddLiquidityModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useOnUserAccountChanged } from '@/lib/modules/web3/useOnUserAccountChan
import { AddLiquiditySummary } from './AddLiquiditySummary'
import { useAddLiquidityReceipt } from '@/lib/modules/transactions/transaction-steps/receipts/receipt.hooks'
import { useUserAccount } from '@/lib/modules/web3/UserAccountProvider'
import { useTokens } from '@/lib/modules/tokens/TokensProvider'

type Props = {
isOpen: boolean
Expand All @@ -39,6 +40,8 @@ export function AddLiquidityModal({
const { pool, chain } = usePool()
const { redirectToPoolPage } = usePoolRedirect(pool)
const { userAddress } = useUserAccount()
const { stopTokenPricePolling } = useTokens()

const receiptProps = useAddLiquidityReceipt({
chain,
txHash: addLiquidityTxHash,
Expand All @@ -47,6 +50,14 @@ export function AddLiquidityModal({

useResetStepIndexOnOpen(isOpen, transactionSteps)

useEffect(() => {
if (isOpen) {
// stop polling for token prices when modal is opened to prevent unwanted re-renders
stopTokenPricePolling()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen])

useEffect(() => {
if (addLiquidityTxHash && !window.location.pathname.includes(addLiquidityTxHash)) {
window.history.replaceState({}, '', `./add-liquidity/${addLiquidityTxHash}`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { parseUnits } from 'viem'
import { SimulationError } from '@/lib/shared/components/errors/SimulationError'
import { InfoIcon } from '@/lib/shared/components/icons/InfoIcon'
import { SafeAppAlert } from '@/lib/shared/components/alerts/SafeAppAlert'

import { useTokens } from '@/lib/modules/tokens/TokensProvider'
const TABS: ButtonGroupOption[] = [
{
value: 'proportional',
Expand Down Expand Up @@ -70,6 +70,7 @@ export function RemoveLiquidityForm() {
const { redirectToPoolPage } = usePoolRedirect(pool)
const nextBtn = useRef(null)
const [activeTab, setActiveTab] = useState(TABS[0])
const { startTokenPricePolling } = useTokens()

useEffect(() => {
setPriceImpact(priceImpactQuery.data)
Expand All @@ -91,6 +92,9 @@ export function RemoveLiquidityForm() {
}

const onModalClose = () => {
// restart polling for token prices when modal is closed again
startTokenPricePolling()

if (transactionSteps.lastTransactionConfirmingOrConfirmed) {
// If the transaction is confirming or confirmed, it's very likely that
// they no longer have a pool balance. To be safe, always redirect to the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useOnUserAccountChanged } from '@/lib/modules/web3/useOnUserAccountChan
import { RemoveLiquiditySummary } from './RemoveLiquiditySummary'
import { useRemoveLiquidityReceipt } from '@/lib/modules/transactions/transaction-steps/receipts/receipt.hooks'
import { useUserAccount } from '@/lib/modules/web3/UserAccountProvider'
import { useTokens } from '@/lib/modules/tokens/TokensProvider'

type Props = {
isOpen: boolean
Expand All @@ -38,6 +39,7 @@ export function RemoveLiquidityModal({
const { pool, chain } = usePool()
const { redirectToPoolPage } = usePoolRedirect(pool)
const { userAddress } = useUserAccount()
const { stopTokenPricePolling } = useTokens()

const receiptProps = useRemoveLiquidityReceipt({
chain,
Expand All @@ -47,6 +49,14 @@ export function RemoveLiquidityModal({

useResetStepIndexOnOpen(isOpen, transactionSteps)

useEffect(() => {
if (isOpen) {
// stop polling for token prices when modal is opened to prevent unwanted re-renders
stopTokenPricePolling()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isOpen])

useEffect(() => {
if (removeLiquidityTxHash && !window.location.pathname.includes(removeLiquidityTxHash)) {
window.history.replaceState({}, '', `./remove-liquidity/${removeLiquidityTxHash}`)
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/swap/SwapDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function OrderRoute() {

const queryData = simulationQuery.data as SdkSimulateSwapResponse
const orderRouteVersion = queryData ? queryData.protocolVersion : 2
const hopCount = queryData?.routes[0]?.hops?.length ?? 0
const hopCount = queryData ? queryData.routes[0]?.hops?.length : 0

return (
<HStack justify="space-between" w="full">
Expand Down
6 changes: 6 additions & 0 deletions lib/modules/swap/SwapForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { parseSwapError } from './swap.helpers'
import { useUserAccount } from '../web3/UserAccountProvider'
import { ConnectWallet } from '../web3/ConnectWallet'
import { SafeAppAlert } from '@/lib/shared/components/alerts/SafeAppAlert'
import { useTokens } from '../tokens/TokensProvider'

export function SwapForm() {
const {
Expand Down Expand Up @@ -70,6 +71,7 @@ export function SwapForm() {
const finalRefTokenOut = useRef(null)
const isMounted = useIsMounted()
const { isConnected } = useUserAccount()
const { startTokenPricePolling } = useTokens()

const isLoadingSwaps = simulationQuery.isLoading
const isLoading = isLoadingSwaps || !isMounted
Expand Down Expand Up @@ -98,7 +100,11 @@ export function SwapForm() {
}

function onModalClose() {
// restart polling for token prices when modal is closed again
startTokenPricePolling()

previewModalDisclosure.onClose()

if (swapTxHash) {
resetSwapAmounts()
replaceUrlPath()
Expand Down
11 changes: 10 additions & 1 deletion lib/modules/swap/modal/SwapModal.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable react-hooks/exhaustive-deps */
'use client'

import { Modal, ModalBody, ModalCloseButton, ModalContent, ModalProps } from '@chakra-ui/react'
Expand All @@ -18,6 +19,7 @@ import { useOnUserAccountChanged } from '../../web3/useOnUserAccountChanged'
import { SwapSummary } from './SwapSummary'
import { useSwapReceipt } from '../../transactions/transaction-steps/receipts/receipt.hooks'
import { useUserAccount } from '../../web3/UserAccountProvider'
import { useTokens } from '../../tokens/TokensProvider'

type Props = {
isOpen: boolean
Expand All @@ -35,6 +37,7 @@ export function SwapPreviewModal({
const { isDesktop } = useBreakpoints()
const initialFocusRef = useRef(null)
const { userAddress } = useUserAccount()
const { stopTokenPricePolling } = useTokens()

const { transactionSteps, swapAction, isWrap, selectedChain, swapTxHash, hasQuoteContext } =
useSwap()
Expand All @@ -51,9 +54,15 @@ export function SwapPreviewModal({
if (!isWrap && swapTxHash && !window.location.pathname.includes(swapTxHash)) {
window.history.pushState({}, '', `/swap/${chainToSlugMap[selectedChain]}/${swapTxHash}`)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [swapTxHash])

useEffect(() => {
if (isOpen) {
// stop polling for token prices when modal is opened to prevent unwanted re-renders
stopTokenPricePolling()
}
}, [isOpen])

useOnUserAccountChanged(onClose)

return (
Expand Down
31 changes: 18 additions & 13 deletions lib/modules/tokens/TokensProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import { isSameAddress } from '@/lib/shared/utils/addresses'
import { useMandatoryContext } from '@/lib/shared/utils/contexts'
import { bn, Numberish } from '@/lib/shared/utils/numbers'
import { useQuery } from '@apollo/experimental-nextjs-app-support/ssr'
import { useQuery } from '@apollo/client'
import { Dictionary, zipObject } from 'lodash'
import { createContext, PropsWithChildren, useCallback } from 'react'
import { Address } from 'viem'
Expand All @@ -31,24 +31,27 @@ export function _useTokens(
variables: GetTokensQueryVariables
) {
const skipQuery = useSkipInitialQuery(variables)
const pollInterval = mins(3).toMs()

// skip initial fetch on mount so that initialData is used
const { data: tokensData } = useQuery(GetTokensDocument, {
variables,
skip: skipQuery,
})
const { data: tokenPricesData, loading: isLoadingTokenPrices } = useQuery(
GetTokenPricesDocument,
{
variables,
// The server provides us with an initial data set, but we immediately reload the potentially
// stale data to ensure the prices we show are up to date. Every 3 mins, we requery token prices
initialFetchPolicy: 'no-cache',
nextFetchPolicy: 'cache-and-network',
pollInterval: mins(3).toMs(),
notifyOnNetworkStatusChange: true,
}
)
const {
data: tokenPricesData,
loading: isLoadingTokenPrices,
startPolling,
stopPolling,
} = useQuery(GetTokenPricesDocument, {
variables,
// The server provides us with an initial data set, but we immediately reload the potentially
// stale data to ensure the prices we show are up to date. Every 3 mins, we requery token prices
initialFetchPolicy: 'no-cache',
nextFetchPolicy: 'cache-and-network',
pollInterval,
notifyOnNetworkStatusChange: true,
})

const tokens = tokensData?.tokens || initTokenData.tokens
const prices = tokenPricesData?.tokenPrices || initTokenPricesData.tokenPrices
Expand Down Expand Up @@ -153,6 +156,8 @@ export function _useTokens(
usdValueForToken,
calcWeightForBalance,
calcTotalUsdValue,
startTokenPricePolling: () => startPolling(pollInterval),
stopTokenPricePolling: stopPolling,
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { testHook } from '@/test/utils/custom-renderers'
import { waitFor } from '@testing-library/react'

import { getGqlChain } from '@/lib/config/app.config'
import { maticAddress } from '@/lib/debug-helpers'
import { polAddress } from '@/lib/debug-helpers'
import { GqlChain } from '@/lib/shared/services/api/generated/graphql'
import { Address, Hash } from 'viem'
import { polygon } from 'viem/chains'
Expand Down Expand Up @@ -78,7 +78,7 @@ test('queries add liquidity with native token', async () => {

expect(result.current.sentTokens).toEqual([
{
tokenAddress: maticAddress,
tokenAddress: polAddress,
humanAmount: '1',
},
])
Expand Down Expand Up @@ -111,11 +111,11 @@ test('queries remove liquidity transaction', async () => {
})

describe('queries swap transaction', () => {
const maticAddress = '0x0000000000000000000000000000000000001010'
const wMaticAddress = '0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270'
const polAddress = '0x0000000000000000000000000000000000001010'
const wPolAddress = '0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270'
const daiAddress = '0x8f3cf7ad23cd3cadbd9735aff958023239c6a063'

test('when the native asset is not included (from DAI to WMATIC)', async () => {
test('when the native asset is not included (from DAI to WPOL)', async () => {
const userAddress = '0xf76142b79Db34E57852d68F9c52C0E24f7349647'
// https://polygonscan.com/tx/0x11380dcffb24c512da18f032d9f7354d154cfda6bbab0633df182fcd202c4244
const txHash = '0x11380dcffb24c512da18f032d9f7354d154cfda6bbab0633df182fcd202c4244'
Expand All @@ -131,11 +131,11 @@ describe('queries swap transaction', () => {

expect(result.current.receivedToken).toEqual({
humanAmount: '1.419839650912753603',
tokenAddress: wMaticAddress,
tokenAddress: wPolAddress,
})
})

test('when the native asset is the token in (from MATIC to DAI)', async () => {
test('when the native asset is the token in (from POL to DAI)', async () => {
const userAddress = '0xf76142b79Db34E57852d68F9c52C0E24f7349647'
// https://polygonscan.com/tx/0x78ddd90502509a264a5e8f4f3732668db669e7614f4887f2a233ce39e5eafa7c
const txHash = '0x78ddd90502509a264a5e8f4f3732668db669e7614f4887f2a233ce39e5eafa7c'
Expand All @@ -146,7 +146,7 @@ describe('queries swap transaction', () => {

expect(result.current.sentToken).toEqual({
humanAmount: '1',
tokenAddress: maticAddress,
tokenAddress: polAddress,
})

expect(result.current.receivedToken).toEqual({
Expand All @@ -155,7 +155,7 @@ describe('queries swap transaction', () => {
})
})

test('when the native asset is the token out (from DAI to MATIC)', async () => {
test('when the native asset is the token out (from DAI to POL)', async () => {
const userAddress = '0xf76142b79Db34E57852d68F9c52C0E24f7349647'
// https://polygonscan.com/tx/0xe0b75845d13ae12029c8dfef68488b3bf35347460fafdb3a15a5c7f884226288
const txHash = '0xe0b75845d13ae12029c8dfef68488b3bf35347460fafdb3a15a5c7f884226288'
Expand All @@ -171,7 +171,7 @@ describe('queries swap transaction', () => {

expect(result.current.receivedToken).toEqual({
humanAmount: '0.241277224191485579',
tokenAddress: maticAddress,
tokenAddress: polAddress,
})
})
})
Expand Down
8 changes: 4 additions & 4 deletions lib/modules/web3/contracts/useMulticall.integration.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { daiAddress, maticAddress } from '@/lib/debug-helpers'
import { daiAddress, polAddress } from '@/lib/debug-helpers'
import { alternativeTestUserAccount, defaultTestUserAccount } from '@/test/anvil/anvil-setup'
import { testHook } from '@/test/utils/custom-renderers'
import { waitFor } from '@testing-library/react'
Expand All @@ -17,10 +17,10 @@ describe('Performs multicall in multiple chains', () => {
}

const polygonRequest: ChainContractConfig = {
id: 'maticBalance',
id: 'polBalance',
chainId: polygon.id,
abi: erc20Abi,
address: maticAddress,
address: polAddress,
functionName: 'balanceOf',
args: [alternativeTestUserAccount],
}
Expand All @@ -44,7 +44,7 @@ describe('Performs multicall in multiple chains', () => {
await waitFor(() => expect(result.current.results[polygon.id].data).toBeDefined())
expect(result.current.results[polygon.id].data).toMatchInlineSnapshot(`
{
"maticBalance": {
"polBalance": {
"result": 10000000000000000000000n,
"status": "success",
},
Expand Down
Loading

0 comments on commit f2c0788

Please sign in to comment.