Skip to content

Commit

Permalink
refactor: dedicated native and approved balances
Browse files Browse the repository at this point in the history
  • Loading branch information
moritzkirstein committed Mar 11, 2024
1 parent 7809ce8 commit 72a4967
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 39 deletions.
25 changes: 10 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,9 @@ 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: {}
})

const [hasDeleteRequest, setHasDeleteRequest] = useState(false)

Expand Down Expand Up @@ -98,16 +94,16 @@ function AutomationProvider({ children }) {
if (!autoWallet) return

try {
const newBalance: UserBalance = { native: {} }
if (balanceNativeToken)
setNativeBalance({
symbol: balanceNativeToken?.symbol.toLowerCase() || 'ETH',
balance: balanceNativeToken?.formatted
})
newBalance.native[balanceNativeToken?.symbol.toLowerCase() || 'ETH'] =
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 +203,6 @@ function AutomationProvider({ children }) {
autoWallet,
autoWalletAddress,
balance,
nativeBalance,
isAutomationEnabled,
isLoading,
decryptPercentage,
Expand Down
18 changes: 10 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,14 @@ function useBalance(): BalanceProviderValue {
const { chain } = useNetwork()

const [balance, setBalance] = useState<UserBalance>({
eth: '0'
native: {
eth: '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 +66,11 @@ function useBalance(): BalanceProviderValue {
try {
const userBalance = balanceNativeToken?.formatted
const key = balanceNativeToken?.symbol.toLowerCase()
const newNativeBalance: UserBalance = { [key]: userBalance }
const newNativeBalance: TokenBalances = { [key]: userBalance }

const newBalance = {
...newNativeBalance,
...(await getApprovedTokenBalances(address))
const newBalance: UserBalance = {
native: newNativeBalance,
approved: await getApprovedTokenBalances(address)
}

setBalance(newBalance)
Expand Down
5 changes: 5 additions & 0 deletions src/@types/TokenBalance.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
interface UserBalance {
native: TokenBalances
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
18 changes: 9 additions & 9 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)}
{Object.keys(balance.native).map((symbol) => (
<li key={`automation-balance-${symbol}`}>
<span>{symbol}</span>:{' '}
{Number(balance.native[symbol]).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

0 comments on commit 72a4967

Please sign in to comment.