Skip to main content

getBalance()

getBalance() is a function from privacycash-evm used to retrieve your private ETH or ERC-20 balance from Privacy Cash on an EVM network.

Parameters

ParameterTypeDescription
signaturestringWallet signature of the Privacy Cash sign-in message.
addressstringYour EVM wallet address.
token'eth' | 'usdc' | 'usdt'Optional. Defaults to 'eth'.
networkNetworkConfig | numberOptional. Pass BASE_NETWORK, ETH_NETWORK, or a supported chain ID.

Return Value

PropertyTypeDescription
balancestringTotal private balance as a decimal string (e.g. "0.05").

Example Usage

'use client'
import { BASE_NETWORK, ETH_NETWORK, getBalance } from 'privacycash-evm'
import { useAccount, useChainId } from 'wagmi'
import { useEffect, useState } from 'react'

export function PrivateBalance() {
    const { address } = useAccount()
    const chainId = useChainId()
    const [balance, setBalance] = useState('0')

    useEffect(() => {
        if (!address) return
        const network = chainId === 1 ? ETH_NETWORK : chainId === 8453 ? BASE_NETWORK : undefined
        if (!network) return
        const signature = localStorage.getItem(`evm_sign_${address}`)
        if (!signature) return

        getBalance({ signature, address, token: 'eth', network }).then(res => {
            setBalance(res.balance)
        })
    }, [address, chainId])

    return <div>Private Balance: {balance} ETH</div>
}

Auto-Refresh Pattern

Re-fetch the balance after a deposit or withdrawal completes by tracking a change counter:
const [balanceChanged, setBalanceChanged] = useState(0)
const network = chainId === 1 ? ETH_NETWORK : chainId === 8453 ? BASE_NETWORK : undefined
const token = 'eth'

useEffect(() => {
    if (!address || !network) return
    const signature = localStorage.getItem(`evm_sign_${address}`)
    if (!signature) return
    getBalance({ signature, address, token, network }).then(res => setBalance(res.balance))
}, [balanceChanged, address, token, network])

// After a successful deposit or withdrawal:
setBalanceChanged(prev => prev + 1)

How It Works

getBalance() scans all historic NewCommitment events from the Privacy Cash contract and attempts to decrypt each one locally using the key derived from your signature. UTXOs that decrypt successfully and have not been spent are summed to produce your total balance. No private data leaves the client.