From 9e84d714d1828057133c9efdc25252638b788dad Mon Sep 17 00:00:00 2001 From: Moritz Kirstein Date: Fri, 15 Mar 2024 13:49:03 +0100 Subject: [PATCH] Fix: wrong token being used for price button on Pontus-X (#521) * refactor: dedicated native and approved balances * fix: native token typing --- .../Automation/AutomationProvider.tsx | 34 +++++++++++-------- src/@hooks/useBalance.tsx | 21 +++++++----- src/@types/TokenBalance.d.ts | 8 +++++ src/@utils/wallet/index.ts | 6 ++-- .../Compute/FormComputeDataset.tsx | 4 +-- src/components/Asset/AssetActions/index.tsx | 4 +-- .../UserPreferences/Automation/Balance.tsx | 16 ++++----- .../UserPreferences/Automation/Details.tsx | 8 ++--- .../UserPreferences/Automation/index.tsx | 20 +++++------ 9 files changed, 67 insertions(+), 54 deletions(-) diff --git a/src/@context/Automation/AutomationProvider.tsx b/src/@context/Automation/AutomationProvider.tsx index f75f67026..db4fb3c3b 100644 --- a/src/@context/Automation/AutomationProvider.tsx +++ b/src/@context/Automation/AutomationProvider.tsx @@ -21,16 +21,11 @@ export enum AUTOMATION_MODES { ADVANCED = 'advanced' } -export interface NativeTokenBalance { - symbol: string - balance: string -} export interface AutomationProviderValue { autoWallet: Wallet autoWalletAddress: string isAutomationEnabled: boolean balance: UserBalance - nativeBalance: NativeTokenBalance isLoading: boolean decryptPercentage: number hasValidEncryptedWallet: boolean @@ -65,8 +60,12 @@ function AutomationProvider({ children }) { address: autoWallet?.address as `0x${string}` }) - const [nativeBalance, setNativeBalance] = useState() - const [balance, setBalance] = useState({}) + const [balance, setBalance] = useState({ + native: { + symbol: 'eth', + balance: '0' + } + }) const [hasDeleteRequest, setHasDeleteRequest] = useState(false) @@ -98,16 +97,22 @@ function AutomationProvider({ children }) { if (!autoWallet) return try { + const newBalance: UserBalance = { + native: { + symbol: 'eth', + balance: '0' + } + } if (balanceNativeToken) - setNativeBalance({ - symbol: balanceNativeToken?.symbol.toLowerCase() || 'ETH', - balance: balanceNativeToken?.formatted - }) + newBalance.native.symbol = + balanceNativeToken?.symbol.toLowerCase() || 'eth' + newBalance.native.balance = balanceNativeToken?.formatted if (approvedBaseTokens?.length > 0) { - const newBalance = await getApprovedTokenBalances(autoWallet?.address) - setBalance(newBalance) - } else setBalance(undefined) + const approved = await getApprovedTokenBalances(autoWallet?.address) + newBalance.approved = approved + } + setBalance(newBalance) } catch (error) { LoggerInstance.error('[AutomationProvider] Error: ', error.message) } @@ -207,7 +212,6 @@ function AutomationProvider({ children }) { autoWallet, autoWalletAddress, balance, - nativeBalance, isAutomationEnabled, isLoading, decryptPercentage, diff --git a/src/@hooks/useBalance.tsx b/src/@hooks/useBalance.tsx index 2eacb2f38..9462ae76b 100644 --- a/src/@hooks/useBalance.tsx +++ b/src/@hooks/useBalance.tsx @@ -11,7 +11,7 @@ import { getTokenBalance } from '@utils/wallet' interface BalanceProviderValue { balance: UserBalance - getApprovedTokenBalances: (address: string) => Promise + getApprovedTokenBalances: (address: string) => Promise } function useBalance(): BalanceProviderValue { @@ -22,12 +22,15 @@ function useBalance(): BalanceProviderValue { const { chain } = useNetwork() const [balance, setBalance] = useState({ - eth: '0' + native: { + symbol: 'eth', + balance: '0' + } }) const getApprovedTokenBalances = useCallback( - async (address: string): Promise => { - const newBalance: UserBalance = {} + async (address: string): Promise => { + const newBalance: TokenBalances = {} if (approvedBaseTokens?.length > 0) { await Promise.allSettled( @@ -64,11 +67,13 @@ function useBalance(): BalanceProviderValue { try { const userBalance = balanceNativeToken?.formatted const key = balanceNativeToken?.symbol.toLowerCase() - const newNativeBalance: UserBalance = { [key]: userBalance } - const newBalance = { - ...newNativeBalance, - ...(await getApprovedTokenBalances(address)) + const newBalance: UserBalance = { + native: { + symbol: key, + balance: userBalance + }, + approved: await getApprovedTokenBalances(address) } setBalance(newBalance) diff --git a/src/@types/TokenBalance.d.ts b/src/@types/TokenBalance.d.ts index d51e735d1..bd117f8c5 100644 --- a/src/@types/TokenBalance.d.ts +++ b/src/@types/TokenBalance.d.ts @@ -1,3 +1,11 @@ interface UserBalance { + native: { + symbol: string + balance: string + } + approved?: TokenBalances +} + +interface TokenBalances { [key: string]: string } diff --git a/src/@utils/wallet/index.ts b/src/@utils/wallet/index.ts index b37f41878..9121e1af8 100644 --- a/src/@utils/wallet/index.ts +++ b/src/@utils/wallet/index.ts @@ -176,12 +176,12 @@ export async function getTokenBalance( } } -export function getTokenBalanceFromSymbol( +export function getApprovedTokenBalanceFromSymbol( balance: UserBalance, symbol: string ): string { if (!symbol) return - - const baseTokenBalance = balance?.[symbol.toLocaleLowerCase()] + const { approved } = balance + const baseTokenBalance = approved?.[symbol.toLocaleLowerCase()] return baseTokenBalance || '0' } diff --git a/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx b/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx index 49aae0c78..2b79c5431 100644 --- a/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx +++ b/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx @@ -10,7 +10,7 @@ import { useAsset } from '@context/Asset' import content from '../../../../../content/pages/startComputeDataset.json' import { Asset, ComputeEnvironment, ZERO_ADDRESS } from '@oceanprotocol/lib' import { getAccessDetails } from '@utils/accessDetailsAndPricing' -import { getTokenBalanceFromSymbol } from '@utils/wallet' +import { getApprovedTokenBalanceFromSymbol } from '@utils/wallet' import { MAX_DECIMALS } from '@utils/constants' import Decimal from 'decimal.js' import { useAccount } from 'wagmi' @@ -273,7 +273,7 @@ export default function FormStartCompute({ totalPrices.forEach((price) => { const balanceToUse = isAutomationEnabled ? automationBalance : balance - const baseTokenBalance = getTokenBalanceFromSymbol( + const baseTokenBalance = getApprovedTokenBalanceFromSymbol( balanceToUse, price.symbol ) diff --git a/src/components/Asset/AssetActions/index.tsx b/src/components/Asset/AssetActions/index.tsx index f05cc638b..e62e3f82d 100644 --- a/src/components/Asset/AssetActions/index.tsx +++ b/src/components/Asset/AssetActions/index.tsx @@ -11,7 +11,7 @@ import { useIsMounted } from '@hooks/useIsMounted' import styles from './index.module.css' import { useFormikContext } from 'formik' import { FormPublishData } from '@components/Publish/_types' -import { getTokenBalanceFromSymbol } from '@utils/wallet' +import { getApprovedTokenBalanceFromSymbol } from '@utils/wallet' import AssetStats from './AssetStats' import { isAddressWhitelisted } from '@utils/ddo' import { useAccount, useProvider, useNetwork, useSigner } from 'wagmi' @@ -154,7 +154,7 @@ export default function AssetActions({ const balanceToUse = isAutomationEnabled ? automationBalance : balance - const baseTokenBalance = getTokenBalanceFromSymbol( + const baseTokenBalance = getApprovedTokenBalanceFromSymbol( balanceToUse, asset?.accessDetails?.baseToken?.symbol ) diff --git a/src/components/Header/UserPreferences/Automation/Balance.tsx b/src/components/Header/UserPreferences/Automation/Balance.tsx index 7146592ae..9df1fe1bf 100644 --- a/src/components/Header/UserPreferences/Automation/Balance.tsx +++ b/src/components/Header/UserPreferences/Automation/Balance.tsx @@ -3,28 +3,28 @@ import { useAutomation } from '../../../../@context/Automation/AutomationProvide import styles from './Balance.module.css' export default function Balance(): ReactElement { - const { nativeBalance, balance } = useAutomation() + const { balance } = useAutomation() return ( <>
    - {nativeBalance && ( -
  • - {nativeBalance.symbol}:{' '} - {Number(nativeBalance.balance).toFixed(4)} + {balance.native && ( +
  • + {balance.native.symbol}:{' '} + {Number(balance.native.balance).toFixed(4)}
  • )}
    - {balance && - Object.keys(balance).map((currency) => ( + {balance.approved && + Object.keys(balance.approved).map((currency) => (
  • {currency}:{' '} - {Number(balance[currency]).toFixed(4)} + {Number(balance.approved[currency]).toFixed(4)}
  • ))}
diff --git a/src/components/Header/UserPreferences/Automation/Details.tsx b/src/components/Header/UserPreferences/Automation/Details.tsx index 86146bd25..52e0b4190 100644 --- a/src/components/Header/UserPreferences/Automation/Details.tsx +++ b/src/components/Header/UserPreferences/Automation/Details.tsx @@ -64,8 +64,8 @@ export default function Details({ const { autoWallet, autoWalletAddress, + balance, isAutomationEnabled, - nativeBalance, isLoading, hasValidEncryptedWallet, setIsAutomationEnabled @@ -84,11 +84,11 @@ export default function Details({ }, [hasValidEncryptedWallet]) useEffect(() => { - if (!automationConfig.roughTxGasEstimate || !nativeBalance?.balance) return + if (!automationConfig.roughTxGasEstimate) return setRoughTxCountEstimate( - Number(nativeBalance.balance) / automationConfig.roughTxGasEstimate + Number(balance.native.balance) / automationConfig.roughTxGasEstimate ) - }, [nativeBalance?.balance, automationConfig?.roughTxGasEstimate]) + }, [balance.native, automationConfig?.roughTxGasEstimate]) return (
diff --git a/src/components/Header/UserPreferences/Automation/index.tsx b/src/components/Header/UserPreferences/Automation/index.tsx index f5f2b94e4..44ca5c520 100644 --- a/src/components/Header/UserPreferences/Automation/index.tsx +++ b/src/components/Header/UserPreferences/Automation/index.tsx @@ -12,13 +12,8 @@ import styles from './index.module.css' const cx = classNames.bind(styles) export default function Automation(): ReactElement { - const { - autoWallet, - isAutomationEnabled, - hasValidEncryptedWallet, - balance, - nativeBalance - } = useAutomation() + const { autoWallet, isAutomationEnabled, hasValidEncryptedWallet, balance } = + useAutomation() const [hasZeroNetworkTokenBalance, setHasZeroNetworkTokenBalance] = useState(false) @@ -26,13 +21,14 @@ export default function Automation(): ReactElement { useState(false) useEffect(() => { - balance && + balance.approved && setHasZeroERC20TokenBalances( - Object.keys(balance)?.filter((token) => Number(balance[token]) <= 0) - .length > 0 + Object.keys(balance.approved)?.filter( + (token) => Number(balance.approved[token]) <= 0 + ).length > 0 ) - setHasZeroNetworkTokenBalance(Number(nativeBalance?.balance) <= 0) - }, [balance, nativeBalance]) + setHasZeroNetworkTokenBalance(Number(balance.native.balance) <= 0) + }, [balance]) const wrapperClasses = cx({ automation: true,