Skip to content

Commit

Permalink
Fix: wrong token being used for price button on Pontus-X (#521)
Browse files Browse the repository at this point in the history
* refactor: dedicated native and approved balances

* fix: native token typing
  • Loading branch information
moritzkirstein authored Mar 15, 2024
1 parent d491607 commit 9e84d71
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 54 deletions.
34 changes: 19 additions & 15 deletions src/@context/Automation/AutomationProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -65,8 +60,12 @@ function AutomationProvider({ children }) {
address: autoWallet?.address as `0x${string}`
})

const [nativeBalance, setNativeBalance] = useState<NativeTokenBalance>()
const [balance, setBalance] = useState<UserBalance>({})
const [balance, setBalance] = useState<UserBalance>({
native: {
symbol: 'eth',
balance: '0'
}
})

const [hasDeleteRequest, setHasDeleteRequest] = useState(false)

Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -207,7 +212,6 @@ function AutomationProvider({ children }) {
autoWallet,
autoWalletAddress,
balance,
nativeBalance,
isAutomationEnabled,
isLoading,
decryptPercentage,
Expand Down
21 changes: 13 additions & 8 deletions src/@hooks/useBalance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { getTokenBalance } from '@utils/wallet'

interface BalanceProviderValue {
balance: UserBalance
getApprovedTokenBalances: (address: string) => Promise<UserBalance>
getApprovedTokenBalances: (address: string) => Promise<TokenBalances>
}

function useBalance(): BalanceProviderValue {
Expand All @@ -22,12 +22,15 @@ function useBalance(): BalanceProviderValue {
const { chain } = useNetwork()

const [balance, setBalance] = useState<UserBalance>({
eth: '0'
native: {
symbol: 'eth',
balance: '0'
}
})

const getApprovedTokenBalances = useCallback(
async (address: string): Promise<UserBalance> => {
const newBalance: UserBalance = {}
async (address: string): Promise<TokenBalances> => {
const newBalance: TokenBalances = {}

if (approvedBaseTokens?.length > 0) {
await Promise.allSettled(
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 8 additions & 0 deletions src/@types/TokenBalance.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
interface UserBalance {
native: {
symbol: string
balance: string
}
approved?: TokenBalances
}

interface TokenBalances {
[key: string]: string
}
6 changes: 3 additions & 3 deletions src/@utils/wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
)
Expand Down
4 changes: 2 additions & 2 deletions src/components/Asset/AssetActions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -154,7 +154,7 @@ export default function AssetActions({

const balanceToUse = isAutomationEnabled ? automationBalance : balance

const baseTokenBalance = getTokenBalanceFromSymbol(
const baseTokenBalance = getApprovedTokenBalanceFromSymbol(
balanceToUse,
asset?.accessDetails?.baseToken?.symbol
)
Expand Down
16 changes: 8 additions & 8 deletions src/components/Header/UserPreferences/Automation/Balance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<>
<div className={styles.wrapper}>
<div className={styles.balance}>
<ul>
{nativeBalance && (
<li key={`automation-balance-${nativeBalance.symbol}`}>
<span>{nativeBalance.symbol}</span>:{' '}
{Number(nativeBalance.balance).toFixed(4)}
{balance.native && (
<li key={`automation-balance-${balance.native.symbol}`}>
<span>{balance.native.symbol}</span>:{' '}
{Number(balance.native.balance).toFixed(4)}
</li>
)}
</ul>
</div>
<div className={styles.balance}>
<ul>
{balance &&
Object.keys(balance).map((currency) => (
{balance.approved &&
Object.keys(balance.approved).map((currency) => (
<li key={`automation-balance-${currency}`}>
<span>{currency}</span>:{' '}
{Number(balance[currency]).toFixed(4)}
{Number(balance.approved[currency]).toFixed(4)}
</li>
))}
</ul>
Expand Down
8 changes: 4 additions & 4 deletions src/components/Header/UserPreferences/Automation/Details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ export default function Details({
const {
autoWallet,
autoWalletAddress,
balance,
isAutomationEnabled,
nativeBalance,
isLoading,
hasValidEncryptedWallet,
setIsAutomationEnabled
Expand All @@ -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 (
<div className={styles.details}>
Expand Down
20 changes: 8 additions & 12 deletions src/components/Header/UserPreferences/Automation/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,23 @@ 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<boolean>(false)
const [hasZeroERC20TokenBalances, setHasZeroERC20TokenBalances] =
useState<boolean>(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,
Expand Down

0 comments on commit 9e84d71

Please sign in to comment.