From eb30e2e5b4cf8e4e4b724058aea13b5e43b3d2b3 Mon Sep 17 00:00:00 2001 From: Noisekit <28145325+noisekit@users.noreply.github.com> Date: Thu, 12 Dec 2024 19:38:06 +1100 Subject: [PATCH] Avoid wallet provider completely (#94) * Avoid wallet provider completely * Use correct signer * Reduce precision for USDC Andromeda deposits * Use wallet provider for signing txns * Fix USDC Balance display for Max on Andromeda * Cleanup * Fix tsc --- .../components/DepositModal/DepositModal.tsx | 13 +++- .../DepositModal/StataDepositModal.tsx | 9 ++- .../WithdrawModal/WithdrawModal.tsx | 4 +- liquidity/lib/useAccounts/useAccounts.ts | 8 +- liquidity/lib/useAllowance/useAllowance.ts | 4 +- liquidity/lib/useApprove/useApprove.ts | 9 +-- liquidity/lib/useBlockchain/useBlockchain.tsx | 75 +++++++------------ liquidity/lib/useBorrow/useBorrow.tsx | 3 +- .../useClaimAllRewards/useClaimAllRewards.tsx | 2 +- liquidity/lib/useClearDebt/useClearDebt.tsx | 3 +- .../useCollateralPriceUpdates.ts | 4 +- .../useCollateralPrices.ts | 9 +-- .../useConvertStataUSDC.ts | 7 +- liquidity/lib/useDeposit/useDeposit.tsx | 3 +- .../useDepositBaseAndromeda.tsx | 3 +- liquidity/lib/useEthBalance/useEthBalance.ts | 4 +- liquidity/lib/useGasPrice/useGasPrice.ts | 2 +- .../lib/useManagePermissions/package.json | 1 + .../useManagePermissions.ts | 14 +++- liquidity/lib/useMigrate/package.json | 1 + liquidity/lib/useMigrate/useMigrate.ts | 16 ++-- liquidity/lib/useMigrateUSD/package.json | 1 + liquidity/lib/useMigrateUSD/useMigrateUSD.ts | 14 ++-- liquidity/lib/useRepay/useRepay.tsx | 3 +- .../useRepayBaseAndromeda.tsx | 3 +- .../lib/useTransferAccountId/package.json | 1 + .../useTransferAccountId.ts | 16 ++-- liquidity/lib/useUndelegate/useUndelegate.tsx | 3 +- .../useUndelegateBaseAndromeda.tsx | 3 +- liquidity/lib/useUnwrapStataUSDC/package.json | 1 + .../useUnwrapStataUSDC/useUnwrapStataUSDC.ts | 22 ++++-- liquidity/lib/useWithdraw/useWithdraw.tsx | 3 +- .../useWithdrawBaseAndromeda.tsx | 3 +- liquidity/lib/useWrapEth/package.json | 1 + liquidity/lib/useWrapEth/useWrapEth.ts | 37 ++++++--- liquidity/lib/withERC7412/withERC7412.ts | 20 +++-- .../ClosePosition/ClosePositionOneStep.tsx | 23 +++--- .../ui/src/components/Deposit/Deposit.tsx | 49 ++++++++---- liquidity/ui/src/utils/onboard.ts | 2 +- yarn.lock | 6 ++ 40 files changed, 238 insertions(+), 167 deletions(-) diff --git a/liquidity/components/DepositModal/DepositModal.tsx b/liquidity/components/DepositModal/DepositModal.tsx index 06bd3c5aa..029288255 100644 --- a/liquidity/components/DepositModal/DepositModal.tsx +++ b/liquidity/components/DepositModal/DepositModal.tsx @@ -1,7 +1,7 @@ import { ArrowBackIcon } from '@chakra-ui/icons'; import { Button, Divider, Link, Text, useToast } from '@chakra-ui/react'; import { Amount } from '@snx-v3/Amount'; -import { ZEROWEI } from '@snx-v3/constants'; +import { D18, ZEROWEI } from '@snx-v3/constants'; import { ContractError } from '@snx-v3/ContractError'; import { currency } from '@snx-v3/format'; import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; @@ -22,6 +22,7 @@ import { useWrapEth } from '@snx-v3/useWrapEth'; import { Wei, wei } from '@synthetixio/wei'; import { useQueryClient } from '@tanstack/react-query'; import { useMachine } from '@xstate/react'; +import { ethers } from 'ethers'; import React from 'react'; import { ChangeStat } from '../../ui/src/components/ChangeStat/ChangeStat'; import { CRatioChangeStat } from '../../ui/src/components/CRatioBar/CRatioChangeStat'; @@ -87,9 +88,17 @@ export function DepositModal({ const { approve, requireApproval } = useApprove({ contractAddress: network?.preset === 'andromeda' ? synth?.token?.address : collateralType?.tokenAddress, + amount: collateralChange.lte(availableCollateral) ? wei(0).toBN() - : collateralChange.sub(availableCollateral).toBN(), + : network?.preset === 'andromeda' && synth + ? collateralChange + .sub(availableCollateral) + .toBN() + // Reduce precision for approval of USDC on Andromeda + .mul(ethers.utils.parseUnits('1', synth.token.decimals)) + .div(D18) + : collateralChange.sub(availableCollateral).toBN(), spender: network?.preset === 'andromeda' ? SpotMarketProxy?.address : CoreProxy?.address, }); //Collateral Approval Done diff --git a/liquidity/components/DepositModal/StataDepositModal.tsx b/liquidity/components/DepositModal/StataDepositModal.tsx index ff1bfe9c7..cde0fb748 100644 --- a/liquidity/components/DepositModal/StataDepositModal.tsx +++ b/liquidity/components/DepositModal/StataDepositModal.tsx @@ -132,7 +132,14 @@ export function StataDepositModal({ const { approve: approveStata, requireApproval: requireApprovalStata } = useApprove({ contractAddress: synth?.token?.address, amount: synth - ? stataApprovalNeeded.toBN().mul(ethers.utils.parseUnits('1', synth.token.decimals)).div(D18) + ? stataApprovalNeeded + .toBN() + .mul(ethers.utils.parseUnits('1', synth.token.decimals)) + .div(D18) + + // extra 1% approval + .mul(101) + .div(100) : undefined, spender: SpotMarketProxy?.address, }); diff --git a/liquidity/components/WithdrawModal/WithdrawModal.tsx b/liquidity/components/WithdrawModal/WithdrawModal.tsx index b13707b4a..86aaa3d07 100644 --- a/liquidity/components/WithdrawModal/WithdrawModal.tsx +++ b/liquidity/components/WithdrawModal/WithdrawModal.tsx @@ -5,7 +5,7 @@ import { ZEROWEI } from '@snx-v3/constants'; import { ContractError } from '@snx-v3/ContractError'; import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; import { Multistep } from '@snx-v3/Multistep'; -import { useDefaultProvider, useNetwork, useWallet } from '@snx-v3/useBlockchain'; +import { useProvider, useNetwork, useWallet } from '@snx-v3/useBlockchain'; import { useCollateralType } from '@snx-v3/useCollateralTypes'; import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; import { useIsSynthStataUSDC } from '@snx-v3/useIsSynthStataUSDC'; @@ -32,7 +32,7 @@ export function WithdrawModal({ status: 'idle', }); - const provider = useDefaultProvider(); + const provider = useProvider(); const { activeWallet } = useWallet(); const [params] = useParams(); const toast = useToast({ isClosable: true, duration: 9000 }); diff --git a/liquidity/lib/useAccounts/useAccounts.ts b/liquidity/lib/useAccounts/useAccounts.ts index 1da30b433..87ab995a7 100644 --- a/liquidity/lib/useAccounts/useAccounts.ts +++ b/liquidity/lib/useAccounts/useAccounts.ts @@ -66,17 +66,19 @@ export function useCreateAccount() { const { data: CoreProxy } = useCoreProxy(); const signer = useSigner(); const { network } = useNetwork(); + const provider = useProvider(); + const client = useQueryClient(); return { enabled: Boolean(network && CoreProxy), mutation: useMutation({ mutationFn: async function () { try { - if (!(CoreProxy && signer)) throw 'OMFG'; + if (!(CoreProxy && signer && provider)) throw 'OMFG'; const CoreProxyContract = new ethers.Contract(CoreProxy.address, CoreProxy.abi, signer); const tx = await CoreProxyContract['createAccount()'](); - const res = await tx.wait(); + const receipt = await provider.waitForTransaction(tx.hash); await client.invalidateQueries({ queryKey: [`${network?.id}-${network?.preset}`, 'Accounts'], @@ -84,7 +86,7 @@ export function useCreateAccount() { let newAccountId: string | undefined; - res.logs.forEach((log: any) => { + receipt.logs.forEach((log: any) => { if (log.topics[0] === CoreProxyContract.interface.getEventTopic('AccountCreated')) { const accountId = CoreProxyContract.interface.decodeEventLog( 'AccountCreated', diff --git a/liquidity/lib/useAllowance/useAllowance.ts b/liquidity/lib/useAllowance/useAllowance.ts index 90be5ce70..28d6b4a92 100644 --- a/liquidity/lib/useAllowance/useAllowance.ts +++ b/liquidity/lib/useAllowance/useAllowance.ts @@ -1,5 +1,5 @@ import { useQuery } from '@tanstack/react-query'; -import { useWallet, useNetwork, useDefaultProvider } from '@snx-v3/useBlockchain'; +import { useWallet, useNetwork, useProvider } from '@snx-v3/useBlockchain'; import { BigNumber, Contract } from 'ethers'; const abi = ['function allowance(address, address) view returns (uint256)']; @@ -13,7 +13,7 @@ export const useAllowance = ({ }) => { const { activeWallet } = useWallet(); const { network } = useNetwork(); - const provider = useDefaultProvider(); + const provider = useProvider(); return useQuery({ queryKey: [ diff --git a/liquidity/lib/useApprove/useApprove.ts b/liquidity/lib/useApprove/useApprove.ts index e4912c54a..2b5c7b8ff 100644 --- a/liquidity/lib/useApprove/useApprove.ts +++ b/liquidity/lib/useApprove/useApprove.ts @@ -59,12 +59,7 @@ export const useApprove = ( const gasPricesPromised = getGasPrice({ provider }); const gasLimitPromised = contract.estimateGas.approve(spender, amountToApprove); - - const populatedTxnPromised = contract - .connect(signer) - .populateTransaction.approve(spender, amountToApprove, { - gasLimit: gasLimitPromised, - }); + const populatedTxnPromised = contract.populateTransaction.approve(spender, amountToApprove); const [gasPrices, gasLimit, populatedTxn] = await Promise.all([ gasPricesPromised, @@ -82,7 +77,7 @@ export const useApprove = ( log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); refetchAllowance(); diff --git a/liquidity/lib/useBlockchain/useBlockchain.tsx b/liquidity/lib/useBlockchain/useBlockchain.tsx index d9c36b6a4..f6bc2fe75 100644 --- a/liquidity/lib/useBlockchain/useBlockchain.tsx +++ b/liquidity/lib/useBlockchain/useBlockchain.tsx @@ -1,5 +1,5 @@ import { IconProps } from '@chakra-ui/react'; -import { INFURA_KEY as DEFAULT_INFURA_KEY } from '@snx-v3/constants'; +import { INFURA_KEY } from '@snx-v3/constants'; import { importPythERC7412Wrapper } from '@snx-v3/contracts'; import { ArbitrumIcon, @@ -30,7 +30,7 @@ export type Network = { hexId: string; token: string; name: string; - rpcUrl: () => string; + rpcUrl: string; label: string; isSupported: boolean; publicRpcUrl: string; @@ -43,7 +43,7 @@ export const UNSUPPORTED_NETWORK: Network = { hexId: `0x${Number(0).toString(16)}`, token: 'ETH', name: 'unsupported', - rpcUrl: () => '', + rpcUrl: '', publicRpcUrl: '', label: 'Unsupported', isSupported: false, @@ -93,8 +93,7 @@ export const BASE_ANDROMEDA: Network = { hexId: `0x${Number(8453).toString(16)}`, token: 'ETH', name: 'base', - rpcUrl: (INFURA_KEY?: string) => - `https://base-mainnet.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://base-mainnet.infura.io/v3/${INFURA_KEY}`, label: 'Base', isSupported: true, publicRpcUrl: 'https://base.publicnode.com', @@ -107,8 +106,7 @@ export const MAINNET: Network = { hexId: `0x${Number(1).toString(16)}`, token: 'ETH', name: 'mainnet', - rpcUrl: (INFURA_KEY?: string) => - `https://mainnet.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://mainnet.infura.io/v3/${INFURA_KEY}`, label: 'Ethereum', isSupported: true, publicRpcUrl: 'https://ethereum.publicnode.com', @@ -121,8 +119,7 @@ export const OPTIMISM: Network = { hexId: `0x${Number(10).toString(16)}`, token: 'ETH', name: 'optimism-mainnet', - rpcUrl: (INFURA_KEY?: string) => - `https://optimism-mainnet.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://optimism-mainnet.infura.io/v3/${INFURA_KEY}`, label: 'Optimism', isSupported: true, publicRpcUrl: 'https://mainnet.optimism.io', @@ -135,8 +132,7 @@ export const SEPOLIA: Network = { hexId: `0x${Number(11155111).toString(16)}`, token: 'ETH', name: 'sepolia', - rpcUrl: (INFURA_KEY?: string) => - `https://sepolia.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://sepolia.infura.io/v3/${INFURA_KEY}`, label: 'Sepolia Testnet', isSupported: true, publicRpcUrl: 'https://ethereum-sepolia.publicnode.com', @@ -149,8 +145,7 @@ export const BASE_SEPOLIA: Network = { hexId: `0x${Number(84532).toString(16)}`, token: 'ETH', name: 'base-sepolia', - rpcUrl: (INFURA_KEY?: string) => - `https://base-sepolia.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://base-sepolia.infura.io/v3/${INFURA_KEY}`, label: 'Base Sepolia', isSupported: true, publicRpcUrl: 'https://sepolia.base.org', @@ -163,7 +158,7 @@ export const CANNON: Network = { hexId: `0x${Number(13370).toString(16)}`, token: 'ETH', name: 'cannon', - rpcUrl: () => `http://127.0.0.1:8545`, + rpcUrl: `http://127.0.0.1:8545`, label: 'Cannon', isSupported: false, // hidden by default but if wallet switched to Cannon it will be visible publicRpcUrl: 'http://127.0.0.1:8545', @@ -176,8 +171,7 @@ export const OPTIMISM_SEPOLIA: Network = { hexId: `0x${Number(11155420).toString(16)}`, token: 'ETH', name: 'optimism-sepolia', - rpcUrl: (INFURA_KEY?: string) => - `https://optimism-sepolia.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://optimism-sepolia.infura.io/v3/${INFURA_KEY}`, label: 'Optimism Sepolia', isSupported: false, publicRpcUrl: 'https://sepolia.optimism.io/', @@ -190,8 +184,7 @@ export const ARBITRUM_SEPOLIA: Network = { hexId: `0x${Number(421614).toString(16)}`, token: 'ETH', name: 'arbitrum-sepolia', - rpcUrl: (INFURA_KEY?: string) => - `https://arbitrum-sepolia.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://arbitrum-sepolia.infura.io/v3/${INFURA_KEY}`, label: 'Arbitrum Sepolia', isSupported: true, publicRpcUrl: 'https://sepolia-rollup.arbitrum.io/rpc', @@ -204,8 +197,7 @@ export const ARBITRUM: Network = { hexId: `0x${Number(42161).toString(16)}`, token: 'ETH', name: 'arbitrum', - rpcUrl: (INFURA_KEY?: string) => - `https://arbitrum-mainnet.infura.io/v3/${INFURA_KEY ?? DEFAULT_INFURA_KEY}`, + rpcUrl: `https://arbitrum-mainnet.infura.io/v3/${INFURA_KEY}`, label: 'Arbitrum', isSupported: true, publicRpcUrl: 'https://arb1.arbitrum.io/rpc', @@ -218,7 +210,7 @@ export const SNAX: Network = { hexId: `0x${Number(2192).toString(16)}`, token: 'ETH', name: 'SNAX', - rpcUrl: () => 'https://mainnet.snaxchain.io/', + rpcUrl: 'https://mainnet.snaxchain.io/', label: 'Snaxchain', isSupported: true, publicRpcUrl: 'https://mainnet.snaxchain.io/', @@ -231,7 +223,7 @@ export const SNAXTESTNET: Network = { hexId: `0x${Number(13001).toString(16)}`, token: 'ETH', name: 'SNAX', - rpcUrl: () => 'https://testnet.snaxchain.io/', + rpcUrl: 'https://testnet.snaxchain.io/', label: 'Snaxchain', isSupported: true, publicRpcUrl: 'https://testnet.snaxchain.io/', @@ -294,18 +286,13 @@ export function useProviderForChain(customNetwork?: Network) { return provider; } } - return network ? new ethers.providers.JsonRpcProvider(network.rpcUrl()) : null; + return new ethers.providers.JsonRpcProvider(network.rpcUrl); }, }); return provider; } -export function useDefaultProvider() { - const { network } = useNetwork(); - return useProviderForChain(network); -} - export function useWallet() { const [{ wallet }, connect, disconnect] = useConnectWallet(); @@ -356,19 +343,17 @@ export function useNetwork() { }; } -export function useIsConnected(): boolean { - const [{ wallet }] = useConnectWallet(); - return Boolean(wallet); -} - export function useSigner() { - const provider = useProvider(); - const { activeWallet } = useWallet(); + const { network } = useNetwork(); + const [{ wallet }] = useConnectWallet(); + const activeWallet = wallet?.accounts?.[0]; const { data: signer } = useQuery({ - queryKey: ['Wallet signer', activeWallet?.address], - enabled: Boolean(provider && activeWallet), + queryKey: [`${network?.id}-${network?.preset}`, 'Signer', activeWallet?.address], + enabled: Boolean(wallet && activeWallet), queryFn: () => { - if (!(provider && activeWallet)) throw 'OMFG'; + if (!(wallet && activeWallet)) throw 'OMFG'; + const provider = + getMagicProvider() ?? new ethers.providers.Web3Provider(wallet.provider, 'any'); return provider.getSigner(activeWallet.address); }, }); @@ -376,16 +361,6 @@ export function useSigner() { } export function useProvider() { - const [{ wallet }] = useConnectWallet(); - - const { data: provider } = useQuery({ - queryKey: ['Wallet provider', wallet?.accounts.map((a) => a.address)], - enabled: Boolean(wallet), - queryFn: () => { - if (!wallet) throw 'OMFG'; - return getMagicProvider() ?? new ethers.providers.Web3Provider(wallet.provider, 'any'); - }, - }); - - return provider; + const { network } = useNetwork(); + return useProviderForChain(network); } diff --git a/liquidity/lib/useBorrow/useBorrow.tsx b/liquidity/lib/useBorrow/useBorrow.tsx index 9b224edee..f8222a165 100644 --- a/liquidity/lib/useBorrow/useBorrow.tsx +++ b/liquidity/lib/useBorrow/useBorrow.tsx @@ -74,6 +74,7 @@ export const useBorrow = ({ const walletAddress = await signer.getAddress(); const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useBorrow', @@ -90,7 +91,7 @@ export const useBorrow = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useClaimAllRewards/useClaimAllRewards.tsx b/liquidity/lib/useClaimAllRewards/useClaimAllRewards.tsx index a30c86738..d0ea2b594 100644 --- a/liquidity/lib/useClaimAllRewards/useClaimAllRewards.tsx +++ b/liquidity/lib/useClaimAllRewards/useClaimAllRewards.tsx @@ -113,7 +113,7 @@ export function useClaimAllRewards({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); client.invalidateQueries({ diff --git a/liquidity/lib/useClearDebt/useClearDebt.tsx b/liquidity/lib/useClearDebt/useClearDebt.tsx index 76699752c..0a0ac948b 100644 --- a/liquidity/lib/useClearDebt/useClearDebt.tsx +++ b/liquidity/lib/useClearDebt/useClearDebt.tsx @@ -95,6 +95,7 @@ export const useClearDebt = ({ const walletAddress = await signer.getAddress(); const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useRepay', @@ -111,7 +112,7 @@ export const useClearDebt = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts b/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts index 431b9ecb9..3cb0a1754 100644 --- a/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts +++ b/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts @@ -8,7 +8,7 @@ import { importPythVerfier, } from '@snx-v3/contracts'; import { parseUnits } from '@snx-v3/format'; -import { Network, useDefaultProvider, useNetwork, useWallet } from '@snx-v3/useBlockchain'; +import { Network, useProvider, useNetwork, useWallet } from '@snx-v3/useBlockchain'; import { networksOffline } from '@snx-v3/usePoolsList'; import { wei } from '@synthetixio/wei'; import { useQuery } from '@tanstack/react-query'; @@ -154,7 +154,7 @@ export const useOfflinePrices = (collaterals?: Collaterals[]) => { export const useCollateralPriceUpdates = (customNetwork?: Network) => { const { network: currentNetwork } = useNetwork(); const network = customNetwork || currentNetwork; - const provider = useDefaultProvider(); + const provider = useProvider(); const { activeWallet } = useWallet(); const walletAddress = activeWallet?.address; diff --git a/liquidity/lib/useCollateralPrices/useCollateralPrices.ts b/liquidity/lib/useCollateralPrices/useCollateralPrices.ts index d0a49da3d..5191168a1 100644 --- a/liquidity/lib/useCollateralPrices/useCollateralPrices.ts +++ b/liquidity/lib/useCollateralPrices/useCollateralPrices.ts @@ -1,10 +1,5 @@ import { contractsHash, stringToHash } from '@snx-v3/tsHelpers'; -import { - Network, - useDefaultProvider, - useNetwork, - useProviderForChain, -} from '@snx-v3/useBlockchain'; +import { Network, useProvider, useNetwork, useProviderForChain } from '@snx-v3/useBlockchain'; import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; import { useCoreProxy } from '@snx-v3/useCoreProxy'; import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; @@ -58,7 +53,7 @@ export const useCollateralPrices = (customNetwork?: Network) => { ? collateralData?.map((x) => x.tokenAddress).concat(usdTokens.sUSD) : collateralData?.map((x) => x.tokenAddress); - const connectedProvider = useDefaultProvider(); + const connectedProvider = useProvider(); const offlineProvider = useProviderForChain(customNetwork); const provider = customNetwork ? offlineProvider : connectedProvider; diff --git a/liquidity/lib/useConvertStataUSDC/useConvertStataUSDC.ts b/liquidity/lib/useConvertStataUSDC/useConvertStataUSDC.ts index ab2492cc9..1068ec610 100644 --- a/liquidity/lib/useConvertStataUSDC/useConvertStataUSDC.ts +++ b/liquidity/lib/useConvertStataUSDC/useConvertStataUSDC.ts @@ -1,5 +1,5 @@ import { D18, D27, D6 } from '@snx-v3/constants'; -import { useNetwork, useSigner, useWallet } from '@snx-v3/useBlockchain'; +import { useNetwork, useProvider, useSigner, useWallet } from '@snx-v3/useBlockchain'; import { useStaticAaveUSDC } from '@snx-v3/useStaticAaveUSDC'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { debug } from 'debug'; @@ -16,13 +16,14 @@ export function useConvertStataUSDC({ }) { const { network } = useNetwork(); const signer = useSigner(); + const provider = useProvider(); const { data: StaticAaveUSDC } = useStaticAaveUSDC(); const queryClient = useQueryClient(); const { activeWallet } = useWallet(); return useMutation({ mutationFn: async () => { - if (!(StaticAaveUSDC && signer && activeWallet)) { + if (!(StaticAaveUSDC && signer && provider && activeWallet)) { throw new Error('Not ready'); } if (!stataAmountNeeded.gt(0)) { @@ -69,7 +70,7 @@ export function useConvertStataUSDC({ }); log('txn', txn); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); return receipt; diff --git a/liquidity/lib/useDeposit/useDeposit.tsx b/liquidity/lib/useDeposit/useDeposit.tsx index 57bd14ada..f7f1610b9 100644 --- a/liquidity/lib/useDeposit/useDeposit.tsx +++ b/liquidity/lib/useDeposit/useDeposit.tsx @@ -108,6 +108,7 @@ export const useDeposit = ({ } const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useDeposit', @@ -124,7 +125,7 @@ export const useDeposit = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useDepositBaseAndromeda/useDepositBaseAndromeda.tsx b/liquidity/lib/useDepositBaseAndromeda/useDepositBaseAndromeda.tsx index 8f6416dcf..673686994 100644 --- a/liquidity/lib/useDepositBaseAndromeda/useDepositBaseAndromeda.tsx +++ b/liquidity/lib/useDepositBaseAndromeda/useDepositBaseAndromeda.tsx @@ -173,6 +173,7 @@ export const useDepositBaseAndromeda = ({ } const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useDepositBaseAndromeda', @@ -189,7 +190,7 @@ export const useDepositBaseAndromeda = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useEthBalance/useEthBalance.ts b/liquidity/lib/useEthBalance/useEthBalance.ts index 413a18bda..0fd7f5cd4 100644 --- a/liquidity/lib/useEthBalance/useEthBalance.ts +++ b/liquidity/lib/useEthBalance/useEthBalance.ts @@ -1,5 +1,5 @@ import { useQuery } from '@tanstack/react-query'; -import { useWallet, useNetwork, useDefaultProvider } from '@snx-v3/useBlockchain'; +import { useWallet, useNetwork, useProvider } from '@snx-v3/useBlockchain'; import { ZodBigNumber } from '@snx-v3/zod'; import { wei } from '@synthetixio/wei'; @@ -7,7 +7,7 @@ const BalanceSchema = ZodBigNumber.transform((x) => wei(x)); export function useEthBalance() { const { activeWallet } = useWallet(); - const provider = useDefaultProvider(); + const provider = useProvider(); const { network } = useNetwork(); return useQuery({ diff --git a/liquidity/lib/useGasPrice/useGasPrice.ts b/liquidity/lib/useGasPrice/useGasPrice.ts index 9d72ecb6c..d26c2bf76 100644 --- a/liquidity/lib/useGasPrice/useGasPrice.ts +++ b/liquidity/lib/useGasPrice/useGasPrice.ts @@ -3,7 +3,7 @@ import { ethers } from 'ethers'; import { useNetwork, useProvider } from '@snx-v3/useBlockchain'; import { feeSuggestion } from '@snx-v3/feeSuggestion'; -const getGasPriceFromProvider = async (provider: ethers.providers.JsonRpcProvider) => { +const getGasPriceFromProvider = async (provider: ethers.providers.BaseProvider) => { try { const gasPrice = await provider.getGasPrice(); return { diff --git a/liquidity/lib/useManagePermissions/package.json b/liquidity/lib/useManagePermissions/package.json index 46db23ff1..08fb304a7 100644 --- a/liquidity/lib/useManagePermissions/package.json +++ b/liquidity/lib/useManagePermissions/package.json @@ -8,6 +8,7 @@ "@snx-v3/useCoreProxy": "workspace:*", "@snx-v3/useMulticall3": "workspace:*", "@tanstack/react-query": "^5.8.3", + "debug": "^4.3.7", "ethers": "^5.7.2" } } diff --git a/liquidity/lib/useManagePermissions/useManagePermissions.ts b/liquidity/lib/useManagePermissions/useManagePermissions.ts index 1caf4744e..2ac343522 100644 --- a/liquidity/lib/useManagePermissions/useManagePermissions.ts +++ b/liquidity/lib/useManagePermissions/useManagePermissions.ts @@ -1,9 +1,12 @@ -import { useSigner } from '@snx-v3/useBlockchain'; +import { useProvider, useSigner } from '@snx-v3/useBlockchain'; import { useCoreProxy } from '@snx-v3/useCoreProxy'; import { useMulticall3 } from '@snx-v3/useMulticall3'; import { useMutation } from '@tanstack/react-query'; +import debug from 'debug'; import { ethers } from 'ethers'; +const log = debug('snx:useManagePermissions'); + type Permissions = Array; const getPermissionDiff = ( existing: Permissions, @@ -39,10 +42,11 @@ export const useManagePermissions = ({ const { data: CoreProxy } = useCoreProxy(); const { data: Multicall3 } = useMulticall3(); const signer = useSigner(); + const provider = useProvider(); return useMutation({ mutationFn: async () => { - if (!(CoreProxy && Multicall3 && signer)) { + if (!(CoreProxy && Multicall3 && signer && provider)) { throw 'OMFG'; } @@ -74,8 +78,10 @@ export const useManagePermissions = ({ })); const Multicall3Contract = new ethers.Contract(Multicall3.address, Multicall3.abi, signer); - const tx = await Multicall3Contract.aggregate3([...grantCalls, ...revokeCalls]); - await tx.wait(); + const txn = await Multicall3Contract.aggregate3([...grantCalls, ...revokeCalls]); + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); } catch (error: any) { throw error; } diff --git a/liquidity/lib/useMigrate/package.json b/liquidity/lib/useMigrate/package.json index 644a4a6e6..e4ea5b248 100644 --- a/liquidity/lib/useMigrate/package.json +++ b/liquidity/lib/useMigrate/package.json @@ -14,6 +14,7 @@ "@snx-v3/useLegacyMarket": "workspace:*", "@synthetixio/wei": "^2.74.4", "@tanstack/react-query": "^5.8.3", + "debug": "^4.3.7", "ethers": "^5.7.2", "react": "^18.2.0" } diff --git a/liquidity/lib/useMigrate/useMigrate.ts b/liquidity/lib/useMigrate/useMigrate.ts index e059cd633..5297de2fa 100644 --- a/liquidity/lib/useMigrate/useMigrate.ts +++ b/liquidity/lib/useMigrate/useMigrate.ts @@ -1,21 +1,24 @@ import { ZEROWEI } from '@snx-v3/constants'; import { extractErrorData } from '@snx-v3/parseContractError'; import { contractsHash } from '@snx-v3/tsHelpers'; -import { useDefaultProvider, useNetwork, useSigner } from '@snx-v3/useBlockchain'; +import { useProvider, useNetwork, useSigner } from '@snx-v3/useBlockchain'; import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; import { getGasPrice } from '@snx-v3/useGasPrice'; import { useGasSpeed } from '@snx-v3/useGasSpeed'; import { useLegacyMarket } from '@snx-v3/useLegacyMarket'; import { wei } from '@synthetixio/wei'; import { useQuery, useQueryClient } from '@tanstack/react-query'; +import debug from 'debug'; import { ethers } from 'ethers'; import { useCallback, useMemo, useState } from 'react'; +const log = debug('snx:useMigrate'); + export function useMigrate() { const [isLoading, setIsLoading] = useState(false); const [isSuccess, setIsSuccess] = useState(false); const { network } = useNetwork(); - const provider = useDefaultProvider(); + const provider = useProvider(); const signer = useSigner(); const { data: LegacyMarket } = useLegacyMarket(); const { gasSpeed } = useGasSpeed(); @@ -31,7 +34,7 @@ export function useMigrate() { ], enabled: Boolean(signer && LegacyMarket), queryFn: async function () { - if (!(LegacyMarket && signer)) throw 'OMFG'; + if (!(LegacyMarket && signer && provider)) throw 'OMFG'; const LegacyMarketContract = new ethers.Contract( LegacyMarket.address, @@ -80,7 +83,7 @@ export function useMigrate() { const migrate = useCallback(async () => { try { - if (!(LegacyMarket && signer && transaction)) throw 'OMFG'; + if (!(LegacyMarket && signer && provider && transaction)) throw 'OMFG'; setIsLoading(true); setIsSuccess(false); const gasPrices = await getGasPrice({ provider: signer.provider }); @@ -107,7 +110,10 @@ export function useMigrate() { const txn = await LegacyMarketContract.migrate(accountId, { ...gasOptionsForTransaction, }); - await txn.wait(); + + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); setIsLoading(false); setIsSuccess(true); diff --git a/liquidity/lib/useMigrateUSD/package.json b/liquidity/lib/useMigrateUSD/package.json index 8e5bf9453..16360ade4 100644 --- a/liquidity/lib/useMigrateUSD/package.json +++ b/liquidity/lib/useMigrateUSD/package.json @@ -13,6 +13,7 @@ "@snx-v3/useLegacyMarket": "workspace:*", "@synthetixio/wei": "^2.74.4", "@tanstack/react-query": "^5.8.3", + "debug": "^4.3.7", "ethers": "^5.7.2", "react": "^18.2.0" } diff --git a/liquidity/lib/useMigrateUSD/useMigrateUSD.ts b/liquidity/lib/useMigrateUSD/useMigrateUSD.ts index f137af21e..ed327ece6 100644 --- a/liquidity/lib/useMigrateUSD/useMigrateUSD.ts +++ b/liquidity/lib/useMigrateUSD/useMigrateUSD.ts @@ -1,4 +1,4 @@ -import { useDefaultProvider, useNetwork, useSigner } from '@snx-v3/useBlockchain'; +import { useProvider, useNetwork, useSigner } from '@snx-v3/useBlockchain'; import { useLegacyMarket } from '@snx-v3/useLegacyMarket'; import { useCallback, useState } from 'react'; import { getGasPrice } from '@snx-v3/useGasPrice'; @@ -9,6 +9,9 @@ import { useGasSpeed } from '@snx-v3/useGasSpeed'; import { extractErrorData } from '@snx-v3/parseContractError'; import { useQueryClient } from '@tanstack/react-query'; import { ethers } from 'ethers'; +import debug from 'debug'; + +const log = debug('snx:useMigrateUSD'); export function useMigrateUSD({ amount }: { amount: Wei }) { const [isLoading, setIsLoading] = useState(false); @@ -16,13 +19,13 @@ export function useMigrateUSD({ amount }: { amount: Wei }) { const signer = useSigner(); const { data: LegacyMarket } = useLegacyMarket(); const { gasSpeed } = useGasSpeed(); - const provider = useDefaultProvider(); + const provider = useProvider(); const queryClient = useQueryClient(); const { network } = useNetwork(); const migrate = useCallback(async () => { try { - if (!(LegacyMarket && signer)) { + if (!(LegacyMarket && signer && provider)) { throw 'OMFG'; } setIsLoading(true); @@ -45,8 +48,9 @@ export function useMigrateUSD({ amount }: { amount: Wei }) { }); const txn = await signer.sendTransaction({ ...transaction, ...gasOptionsForTransaction }); - - await txn.wait(); + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); setIsLoading(false); setIsSuccess(true); diff --git a/liquidity/lib/useRepay/useRepay.tsx b/liquidity/lib/useRepay/useRepay.tsx index f2712a09a..191bcef77 100644 --- a/liquidity/lib/useRepay/useRepay.tsx +++ b/liquidity/lib/useRepay/useRepay.tsx @@ -85,6 +85,7 @@ export const useRepay = ({ } const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useRepay', @@ -101,7 +102,7 @@ export const useRepay = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useRepayBaseAndromeda/useRepayBaseAndromeda.tsx b/liquidity/lib/useRepayBaseAndromeda/useRepayBaseAndromeda.tsx index 86534203b..4fcfe239b 100644 --- a/liquidity/lib/useRepayBaseAndromeda/useRepayBaseAndromeda.tsx +++ b/liquidity/lib/useRepayBaseAndromeda/useRepayBaseAndromeda.tsx @@ -146,6 +146,7 @@ export const useRepayBaseAndromeda = ({ const walletAddress = await signer.getAddress(); const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useRepay', @@ -162,7 +163,7 @@ export const useRepayBaseAndromeda = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useTransferAccountId/package.json b/liquidity/lib/useTransferAccountId/package.json index 237b0951d..002be7509 100644 --- a/liquidity/lib/useTransferAccountId/package.json +++ b/liquidity/lib/useTransferAccountId/package.json @@ -7,6 +7,7 @@ "@snx-v3/useAccountProxy": "workspace:*", "@snx-v3/useBlockchain": "workspace:*", "@tanstack/react-query": "^5.8.3", + "debug": "^4.3.7", "ethers": "^5.7.2" } } diff --git a/liquidity/lib/useTransferAccountId/useTransferAccountId.ts b/liquidity/lib/useTransferAccountId/useTransferAccountId.ts index eaa401259..a2eede5d7 100644 --- a/liquidity/lib/useTransferAccountId/useTransferAccountId.ts +++ b/liquidity/lib/useTransferAccountId/useTransferAccountId.ts @@ -1,26 +1,32 @@ import { useAccountProxy } from '@snx-v3/useAccountProxy'; -import { useSigner, useWallet } from '@snx-v3/useBlockchain'; +import { useProvider, useSigner, useWallet } from '@snx-v3/useBlockchain'; import { useMutation } from '@tanstack/react-query'; +import debug from 'debug'; import { ethers } from 'ethers'; +const log = debug('snx:useTransferAccountId'); + export function useTransferAccountId(to: string, accountId: string) { const { data: AccountProxy } = useAccountProxy(); const { activeWallet } = useWallet(); const signer = useSigner(); + const provider = useProvider(); const walletAddress = activeWallet?.address; return useMutation({ mutationFn: async () => { if (!AccountProxy) throw new Error('AccountProxy not defined'); - if (!(walletAddress && signer)) throw new Error('Wallet is not connected'); + if (!(walletAddress && signer && provider)) throw new Error('Wallet is not connected'); const AccountProxyContract = new ethers.Contract( AccountProxy.address, AccountProxy.abi, signer ); - const tx = await AccountProxyContract.transferFrom(walletAddress, to, accountId); - const response = await tx.wait(); - return response; + const txn = await AccountProxyContract.transferFrom(walletAddress, to, accountId); + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); + return receipt; }, }); } diff --git a/liquidity/lib/useUndelegate/useUndelegate.tsx b/liquidity/lib/useUndelegate/useUndelegate.tsx index e41f56305..bd4fbaefd 100644 --- a/liquidity/lib/useUndelegate/useUndelegate.tsx +++ b/liquidity/lib/useUndelegate/useUndelegate.tsx @@ -62,6 +62,7 @@ export const useUndelegate = ({ } const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useUndelegate', @@ -78,7 +79,7 @@ export const useUndelegate = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useUndelegateBaseAndromeda/useUndelegateBaseAndromeda.tsx b/liquidity/lib/useUndelegateBaseAndromeda/useUndelegateBaseAndromeda.tsx index 234f8cc75..5a99bf6d6 100644 --- a/liquidity/lib/useUndelegateBaseAndromeda/useUndelegateBaseAndromeda.tsx +++ b/liquidity/lib/useUndelegateBaseAndromeda/useUndelegateBaseAndromeda.tsx @@ -118,6 +118,7 @@ export function useUndelegateBaseAndromeda({ collateralChange }: { collateralCha const walletAddress = await signer.getAddress(); const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useUndelegateBase', @@ -134,7 +135,7 @@ export function useUndelegateBaseAndromeda({ collateralChange }: { collateralCha log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useUnwrapStataUSDC/package.json b/liquidity/lib/useUnwrapStataUSDC/package.json index 12f77db52..de10ff4da 100644 --- a/liquidity/lib/useUnwrapStataUSDC/package.json +++ b/liquidity/lib/useUnwrapStataUSDC/package.json @@ -12,6 +12,7 @@ "@snx-v3/useStaticAaveUSDC": "workspace:*", "@synthetixio/wei": "^2.74.4", "@tanstack/react-query": "^5.8.3", + "debug": "^4.3.7", "ethers": "^5.7.2", "react": "^18.2.0" } diff --git a/liquidity/lib/useUnwrapStataUSDC/useUnwrapStataUSDC.ts b/liquidity/lib/useUnwrapStataUSDC/useUnwrapStataUSDC.ts index 741fe1029..ed2b9a008 100644 --- a/liquidity/lib/useUnwrapStataUSDC/useUnwrapStataUSDC.ts +++ b/liquidity/lib/useUnwrapStataUSDC/useUnwrapStataUSDC.ts @@ -1,24 +1,29 @@ import { ZEROWEI } from '@snx-v3/constants'; -import { useDefaultProvider, useSigner, useWallet } from '@snx-v3/useBlockchain'; +import { useNetwork, useProvider, useSigner, useWallet } from '@snx-v3/useBlockchain'; import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; import { getGasPrice } from '@snx-v3/useGasPrice'; import { useGasSpeed } from '@snx-v3/useGasSpeed'; import { useStaticAaveUSDC } from '@snx-v3/useStaticAaveUSDC'; import { wei } from '@synthetixio/wei'; import { useMutation, useQueryClient } from '@tanstack/react-query'; +import debug from 'debug'; import { ethers } from 'ethers'; +const log = debug('snx:useUnwrapStataUSDC'); + export function useUnwrapStataUSDC() { const signer = useSigner(); + const provider = useProvider(); + const { network } = useNetwork(); + const { data: StaticAaveUSDC } = useStaticAaveUSDC(); const { gasSpeed } = useGasSpeed(); - const provider = useDefaultProvider(); const queryClient = useQueryClient(); const { activeWallet } = useWallet(); return useMutation({ mutationFn: async (amount: ethers.BigNumber) => { - if (!StaticAaveUSDC || !signer || amount.lte(0)) { + if (!StaticAaveUSDC || !signer || !provider || amount.lte(0)) { return; } const StaticAaveUSDCContract = new ethers.Contract( @@ -44,13 +49,16 @@ export function useUnwrapStataUSDC() { }); const txn = await signer.sendTransaction({ ...transaction, ...gasOptionsForTransaction }); - - return await txn.wait(); + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); + return receipt; }, mutationKey: ['unwrapStataUSDC'], onSuccess: async () => { - await queryClient.invalidateQueries({ exact: false, queryKey: ['TokenBalance'] }); - await queryClient.refetchQueries({ exact: false, queryKey: ['TokenBalance'] }); + await queryClient.invalidateQueries({ + queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'], + }); }, }); } diff --git a/liquidity/lib/useWithdraw/useWithdraw.tsx b/liquidity/lib/useWithdraw/useWithdraw.tsx index 53bedf4af..5a4a37a05 100644 --- a/liquidity/lib/useWithdraw/useWithdraw.tsx +++ b/liquidity/lib/useWithdraw/useWithdraw.tsx @@ -75,6 +75,7 @@ export const useWithdraw = ({ } const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useWithdraw', @@ -91,7 +92,7 @@ export const useWithdraw = ({ log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useWithdrawBaseAndromeda/useWithdrawBaseAndromeda.tsx b/liquidity/lib/useWithdrawBaseAndromeda/useWithdrawBaseAndromeda.tsx index 25016dc03..97618a570 100644 --- a/liquidity/lib/useWithdrawBaseAndromeda/useWithdrawBaseAndromeda.tsx +++ b/liquidity/lib/useWithdrawBaseAndromeda/useWithdrawBaseAndromeda.tsx @@ -200,6 +200,7 @@ export const useWithdrawBaseAndromeda = ({ amountToWithdraw }: { amountToWithdra const walletAddress = await signer.getAddress(); const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, allCalls, 'useWithdrawBase', @@ -216,7 +217,7 @@ export const useWithdrawBaseAndromeda = ({ amountToWithdraw }: { amountToWithdra log('txn', txn); dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - const receipt = await txn.wait(); + const receipt = await provider.waitForTransaction(txn.hash); log('receipt', receipt); dispatch({ type: 'success' }); } catch (error: any) { diff --git a/liquidity/lib/useWrapEth/package.json b/liquidity/lib/useWrapEth/package.json index 63405caa0..21b7657fa 100644 --- a/liquidity/lib/useWrapEth/package.json +++ b/liquidity/lib/useWrapEth/package.json @@ -10,6 +10,7 @@ "@snx-v3/useTokenBalance": "workspace:*", "@synthetixio/wei": "^2.74.4", "@tanstack/react-query": "^5.8.3", + "debug": "^4.3.7", "ethers": "^5.7.2", "react": "^18.2.0" } diff --git a/liquidity/lib/useWrapEth/useWrapEth.ts b/liquidity/lib/useWrapEth/useWrapEth.ts index 4221f5773..823a2013e 100644 --- a/liquidity/lib/useWrapEth/useWrapEth.ts +++ b/liquidity/lib/useWrapEth/useWrapEth.ts @@ -1,16 +1,18 @@ -import { useSigner } from '@snx-v3/useBlockchain'; +import { useProvider, useSigner } from '@snx-v3/useBlockchain'; import { useCollateralType } from '@snx-v3/useCollateralTypes'; import { useEthBalance } from '@snx-v3/useEthBalance'; import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { Contract } from 'ethers'; -import { useMutation } from '@tanstack/react-query'; import Wei from '@synthetixio/wei'; +import { useMutation } from '@tanstack/react-query'; +import debug from 'debug'; +import { Contract } from 'ethers'; import { useCallback } from 'react'; -const minimalWETHABI = ['function deposit() payable', 'function withdraw(uint256 wad)']; +const log = debug('snx:useWrapEth'); export const useWrapEth = () => { const signer = useSigner(); + const provider = useProvider(); const { data: ethCollateral } = useCollateralType('WETH'); const { data: ethBalance, refetch: refetchETHBalance } = useEthBalance(); @@ -20,10 +22,17 @@ export const useWrapEth = () => { const { mutateAsync, isPending } = useMutation({ mutationFn: async (amount: Wei) => { - if (!ethCollateral || !signer) return; - const contract = new Contract(ethCollateral?.tokenAddress, minimalWETHABI, signer); + if (!ethCollateral || !signer || !provider) return; + const contract = new Contract( + ethCollateral?.tokenAddress, + ['function deposit() payable'], + signer + ); const txn = await contract.deposit({ value: amount.toBN() }); - await txn.wait(); + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); + return receipt; }, }); @@ -50,6 +59,7 @@ export const useWrapEth = () => { export const useUnWrapEth = () => { const signer = useSigner(); + const provider = useProvider(); const { data: ethCollateral } = useCollateralType('WETH'); const { data: ethBalance, refetch: refetchETHBalance } = useEthBalance(); @@ -59,10 +69,17 @@ export const useUnWrapEth = () => { const { mutateAsync, isPending } = useMutation({ mutationFn: async (amount: Wei) => { - if (!ethCollateral || !signer) return; - const contract = new Contract(ethCollateral?.tokenAddress, minimalWETHABI, signer); + if (!ethCollateral || !signer || !provider) return; + const contract = new Contract( + ethCollateral?.tokenAddress, + ['function withdraw(uint256 wad)'], + signer + ); const txn = await contract.withdraw(amount.toBN()); - await txn.wait(); + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); + return receipt; }, }); diff --git a/liquidity/lib/withERC7412/withERC7412.ts b/liquidity/lib/withERC7412/withERC7412.ts index 438fd31fb..f15e9b460 100644 --- a/liquidity/lib/withERC7412/withERC7412.ts +++ b/liquidity/lib/withERC7412/withERC7412.ts @@ -7,14 +7,14 @@ import { importClosePosition, importCoreProxy, importMulticall3, - importSpotMarketProxy, importPythERC7412Wrapper, importPythVerfier, + importSpotMarketProxy, importUSDProxy, } from '@snx-v3/contracts'; import { extractErrorData, PYTH_ERRORS } from '@snx-v3/parseContractError'; import { notNil } from '@snx-v3/tsHelpers'; -import { deploymentHasERC7412, getMagicProvider, Network } from '@snx-v3/useBlockchain'; +import { deploymentHasERC7412, Network } from '@snx-v3/useBlockchain'; import { ethers } from 'ethers'; const IS_DEBUG = @@ -167,7 +167,7 @@ async function getMulticallTransaction( network: Network, calls: (ethers.PopulatedTransaction & { requireSuccess?: boolean })[], from: string, - provider: ethers.providers.JsonRpcProvider + provider: ethers.providers.BaseProvider ) { const Multicall3Contract = await importMulticall3(network.id, network.preset); const Multicall3Interface = new ethers.utils.Interface(Multicall3Contract.abi); @@ -196,17 +196,14 @@ async function getMulticallTransaction( * If a tx requires ERC7412 pattern, wrap your tx with this function. */ export const withERC7412 = async ( + provider: ethers.providers.BaseProvider, network: Network, calls: (ethers.PopulatedTransaction & { requireSuccess?: boolean })[], label: string, from: string ) => { - // Make sure we're always using JSONRpcProvider, the web3 provider coming from the signer might have bugs causing errors to miss revert data - const jsonRpcProvider = - getMagicProvider() ?? new ethers.providers.JsonRpcProvider(network.rpcUrl()); - if (!(await deploymentHasERC7412(network.id, network.preset))) { - return await getMulticallTransaction(network, calls, from, jsonRpcProvider); + return await getMulticallTransaction(network, calls, from, provider); } const AllErrorsContract = await importAllErrors(network.id, network.preset); @@ -223,7 +220,7 @@ export const withERC7412 = async ( if (IS_DEBUG) { await logMulticall({ network, calls, label }); } - return await getMulticallTransaction(network, calls, from, jsonRpcProvider); + return await getMulticallTransaction(network, calls, from, provider); } catch (error: Error | any) { console.error(error); let errorData = extractErrorData(error); @@ -234,7 +231,7 @@ export const withERC7412 = async ( ); // Some wallets swallows the revert reason when calling estimate gas,try to get the error by using provider.call // provider.call wont actually revert, instead the error data is just returned - const lookedUpError = await jsonRpcProvider.call(error.transaction); + const lookedUpError = await provider.call(error.transaction); errorData = lookedUpError; } catch (newError: any) { console.error(newError); @@ -306,7 +303,7 @@ export const withERC7412 = async ( */ export async function erc7412Call( network: Network, - provider: ethers.providers.Provider, + provider: ethers.providers.BaseProvider, calls: ethers.PopulatedTransaction[], decode: (x: string[] | string) => T, label: string @@ -320,6 +317,7 @@ export async function erc7412Call( multicallTxn, gasLimit, } = await withERC7412( + provider, network, calls.filter(notNil).map((call) => (call.from ? call : { ...call, from })), // fill missing "from" label, diff --git a/liquidity/ui/src/components/ClosePosition/ClosePositionOneStep.tsx b/liquidity/ui/src/components/ClosePosition/ClosePositionOneStep.tsx index fff1cb1e3..7097f6a6e 100644 --- a/liquidity/ui/src/components/ClosePosition/ClosePositionOneStep.tsx +++ b/liquidity/ui/src/components/ClosePosition/ClosePositionOneStep.tsx @@ -84,10 +84,10 @@ export function ClosePositionOneStep({ const { mutate: execClosePosition } = useMutation({ mutationFn: async function () { - log('params: %O', params); - log('collateralType: %O', collateralType); - log('accountCollateral: %O', accountCollateral); - log('positionDebt: %O', positionDebt); + log('params', params); + log('collateralType', collateralType); + log('accountCollateral', accountCollateral); + log('positionDebt', positionDebt); setTxState({ step: 1, status: 'pending' }); if ( @@ -128,7 +128,7 @@ export function ClosePositionOneStep({ ); const freshPriceUpdateTxn = await fetchPriceUpdateTxn({ PythVerfier, pythFeeds }); - log('freshPriceUpdateTxn: %O', freshPriceUpdateTxn); + log('freshPriceUpdateTxn', freshPriceUpdateTxn); const freshPositionDebt = freshPriceUpdateTxn.value ? await fetchPositionDebtWithPriceUpdate({ @@ -147,14 +147,14 @@ export function ClosePositionOneStep({ poolId: params.poolId, collateralTypeTokenAddress: collateralType.tokenAddress, }); - log('freshPositionDebt: %O', freshPositionDebt); + log('freshPositionDebt', freshPositionDebt); const adjustedAllowance = freshPositionDebt.lt(1) ? // For the case when debt fluctuates from negative/zero to slightly positive ethers.utils.parseEther('1.00') : // Add extra buffer for debt fluctuations freshPositionDebt.mul(120).div(100); - log('adjustedAllowance: %O', adjustedAllowance); + log('adjustedAllowance', adjustedAllowance); // "function approve(address to, uint256 tokenId)", @@ -181,6 +181,7 @@ export function ClosePositionOneStep({ const walletAddress = await signer.getAddress(); const { multicallTxn: erc7412Tx, gasLimit } = await withERC7412( + provider, network, calls, 'useClosePosition', @@ -194,10 +195,10 @@ export function ClosePositionOneStep({ }); const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - console.log('[closePosition] txn hash', txn.hash); // eslint-disable-line no-console - log('txn %O', txn); - const receipt = await txn.wait(); - log('receipt %O', receipt); + log('txn', txn); + const receipt = await provider.waitForTransaction(txn.hash); + log('receipt', receipt); + return receipt; }, onSuccess: async () => { diff --git a/liquidity/ui/src/components/Deposit/Deposit.tsx b/liquidity/ui/src/components/Deposit/Deposit.tsx index 54e13ea26..2c4aca70d 100644 --- a/liquidity/ui/src/components/Deposit/Deposit.tsx +++ b/liquidity/ui/src/components/Deposit/Deposit.tsx @@ -77,10 +77,10 @@ export function Deposit() { collateralBalance && stataUSDCRate ) { - const stataAmount = liquidityPosition.availableCollateral - .add(stataBalance) - .add(collateralBalance); - return stataAmount.add(usdcBalance.div(wei(stataUSDCRate, 27))); + const stataAmount = liquidityPosition.availableCollateral // synth stata deposited + .add(stataBalance) // stata in wallet + .add(collateralBalance); // synth stata in wallet + return stataAmount.add(usdcBalance.div(wei(stataUSDCRate, 27)).mul(97).div(100)); // Add 97% of wallet USDC } if ( collateralType?.symbol === 'USDC' && @@ -137,22 +137,41 @@ export function Deposit() { value={liquidityPosition?.availableCollateral} /> - + {!isStataUSDC ? ( + + ) : null} - {isStataUSDC && usdcBalance && stataUSDCRate ? ( + {isStataUSDC && + liquidityPosition && + usdcBalance && + stataBalance && + collateralBalance && + stataUSDCRate ? ( <> - + diff --git a/liquidity/ui/src/utils/onboard.ts b/liquidity/ui/src/utils/onboard.ts index b62c5b493..3266cb060 100644 --- a/liquidity/ui/src/utils/onboard.ts +++ b/liquidity/ui/src/utils/onboard.ts @@ -23,7 +23,7 @@ export const chains: ChainWithDecimalId[] = Object.values( id: network.id, token: network.token, label: network.label, - rpcUrl: network.rpcUrl(), + rpcUrl: network.rpcUrl, publicRpcUrl: network.publicRpcUrl, }, }); diff --git a/yarn.lock b/yarn.lock index 74d7711f1..161b3b0fc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5713,6 +5713,7 @@ __metadata: "@snx-v3/useCoreProxy": "workspace:*" "@snx-v3/useMulticall3": "workspace:*" "@tanstack/react-query": "npm:^5.8.3" + debug: "npm:^4.3.7" ethers: "npm:^5.7.2" languageName: unknown linkType: soft @@ -5731,6 +5732,7 @@ __metadata: "@snx-v3/useLegacyMarket": "workspace:*" "@synthetixio/wei": "npm:^2.74.4" "@tanstack/react-query": "npm:^5.8.3" + debug: "npm:^4.3.7" ethers: "npm:^5.7.2" react: "npm:^18.2.0" languageName: unknown @@ -5749,6 +5751,7 @@ __metadata: "@snx-v3/useLegacyMarket": "workspace:*" "@synthetixio/wei": "npm:^2.74.4" "@tanstack/react-query": "npm:^5.8.3" + debug: "npm:^4.3.7" ethers: "npm:^5.7.2" react: "npm:^18.2.0" languageName: unknown @@ -6081,6 +6084,7 @@ __metadata: "@snx-v3/useAccountProxy": "workspace:*" "@snx-v3/useBlockchain": "workspace:*" "@tanstack/react-query": "npm:^5.8.3" + debug: "npm:^4.3.7" ethers: "npm:^5.7.2" languageName: unknown linkType: soft @@ -6178,6 +6182,7 @@ __metadata: "@snx-v3/useStaticAaveUSDC": "workspace:*" "@synthetixio/wei": "npm:^2.74.4" "@tanstack/react-query": "npm:^5.8.3" + debug: "npm:^4.3.7" ethers: "npm:^5.7.2" react: "npm:^18.2.0" languageName: unknown @@ -6320,6 +6325,7 @@ __metadata: "@snx-v3/useTokenBalance": "workspace:*" "@synthetixio/wei": "npm:^2.74.4" "@tanstack/react-query": "npm:^5.8.3" + debug: "npm:^4.3.7" ethers: "npm:^5.7.2" react: "npm:^18.2.0" languageName: unknown