Skip to content

Wallet Balance API

Query token balances across multiple blockchain networks for any wallet address. This API provides real-time balance information for supported tokens.

Endpoint

GET /v1/wallet/balance

Authentication

This endpoint requires API key authentication:

Authorization: Bearer YOUR_API_KEY

Query Parameters

ParameterTypeRequiredDescription
addressstringWallet address to query
chainIdsstringComma-separated chain IDs to filter by
tokensstringComma-separated token addresses to filter by
includeNativebooleanInclude native token balances (default: true)
includeZerobooleanInclude zero balances (default: false)

Example Requests

# Get all balances for an address
GET /v1/wallet/balance?address=0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8
 
# Get balances on specific chains
GET /v1/wallet/balance?address=0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8&chainIds=1,137,10
 
# Get specific token balances
GET /v1/wallet/balance?address=0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8&tokens=0xA0b86a33E6441b8e776f89d2b5B977c737C5e0b6

Response Format

Success Response

{
  "success": true,
  "data": {
    "address": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8",
    "totalValueUsd": "15847.32",
    "balances": [
      {
        "chainId": 1,
        "chainName": "Ethereum",
        "tokens": [
          {
            "address": "0x0000000000000000000000000000000000000000",
            "symbol": "ETH",
            "name": "Ethereum",
            "decimals": 18,
            "balance": "2.456789123456789012",
            "balanceRaw": "2456789123456789012",
            "valueUsd": "6034.56",
            "price": "2456.78",
            "isNative": true
          },
          {
            "address": "0xA0b86a33E6441b8e776f89d2b5B977c737C5e0b6",
            "symbol": "USDC",
            "name": "USD Coin",
            "decimals": 6,
            "balance": "5000.123456",
            "balanceRaw": "5000123456",
            "valueUsd": "5000.12",
            "price": "1.0001",
            "isNative": false
          }
        ]
      },
      {
        "chainId": 137,
        "chainName": "Polygon",
        "tokens": [
          {
            "address": "0x0000000000000000000000000000000000000000",
            "symbol": "MATIC",
            "name": "Polygon",
            "decimals": 18,
            "balance": "1000.0",
            "balanceRaw": "1000000000000000000000",
            "valueUsd": "850.00",
            "price": "0.85",
            "isNative": true
          },
          {
            "address": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
            "symbol": "USDC",
            "name": "USD Coin",
            "decimals": 6,
            "balance": "3962.640000",
            "balanceRaw": "3962640000",
            "valueUsd": "3962.64",
            "price": "1.0001",
            "isNative": false
          }
        ]
      }
    ],
    "summary": {
      "totalChains": 2,
      "totalTokens": 4,
      "lastUpdated": 1759231185
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Response Fields

FieldTypeDescription
addressstringQueried wallet address
totalValueUsdstringTotal portfolio value in USD
balancesarrayBalance data grouped by chain
summaryobjectSummary statistics

Token Balance Object

FieldTypeDescription
addressstringToken contract address (0x0 for native)
symbolstringToken symbol
namestringToken full name
decimalsnumberToken decimal places
balancestringHuman-readable balance
balanceRawstringRaw balance (smallest unit)
valueUsdstringUSD value of balance
pricestringCurrent token price in USD
isNativebooleanWhether this is the native chain token

Batch Balance Query

Query balances for multiple addresses:

POST /v1/wallet/balance/batch

Request Body

{
  "addresses": [
    "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8",
    "0x8ba1f109551bD432803012645Hac136c22C501e5"
  ],
  "chainIds": [1, 137, 10],
  "includeNative": true,
  "includeZero": false
}

Response Format

{
  "success": true,
  "data": {
    "results": [
      {
        "address": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8",
        "totalValueUsd": "15847.32",
        "balances": [...]
      },
      {
        "address": "0x8ba1f109551bD432803012645Hac136c22C501e5",
        "totalValueUsd": "8234.56",
        "balances": [...]
      }
    ],
    "summary": {
      "totalAddresses": 2,
      "totalValueUsd": "24081.88",
      "lastUpdated": 1759231185
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Error Responses

Invalid Address

{
  "success": false,
  "error": {
    "code": "INVALID_ADDRESS",
    "message": "Invalid wallet address format",
    "details": {
      "address": "invalid_address",
      "expectedFormat": "0x followed by 40 hexadecimal characters"
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Unsupported Chain

{
  "success": false,
  "error": {
    "code": "UNSUPPORTED_CHAIN",
    "message": "Chain ID not supported",
    "details": {
      "chainId": 999,
      "supportedChains": [1, 10, 137, 42161, 8453]
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Code Examples

JavaScript/TypeScript

import { CyberPaySDK } from '@cyberpay/sdk';
 
const sdk = new CyberPaySDK({
  apiKey: 'YOUR_API_KEY',
  environment: 'production'
});
 
async function getWalletBalance(address: string) {
  try {
    const balance = await sdk.wallet.getBalance({
      address,
      chainIds: [1, 137, 10, 42161, 8453],
      includeNative: true,
      includeZero: false
    });
    
    console.log('Wallet balance:', balance);
    console.log('Total value:', balance.totalValueUsd);
    
    // Group by token symbol
    const tokenSummary = {};
    balance.balances.forEach(chain => {
      chain.tokens.forEach(token => {
        if (!tokenSummary[token.symbol]) {
          tokenSummary[token.symbol] = {
            totalBalance: 0,
            totalValue: 0,
            chains: []
          };
        }
        tokenSummary[token.symbol].totalBalance += parseFloat(token.balance);
        tokenSummary[token.symbol].totalValue += parseFloat(token.valueUsd);
        tokenSummary[token.symbol].chains.push(chain.chainName);
      });
    });
    
    console.log('Token summary:', tokenSummary);
    return balance;
  } catch (error) {
    console.error('Error fetching wallet balance:', error);
    throw error;
  }
}
 
// Batch query example
async function getBatchBalances(addresses: string[]) {
  try {
    const balances = await sdk.wallet.getBatchBalance({
      addresses,
      chainIds: [1, 137, 10],
      includeNative: true
    });
    
    console.log('Batch balances:', balances);
    return balances;
  } catch (error) {
    console.error('Error fetching batch balances:', error);
    throw error;
  }
}

React Hook Example

import { useState, useEffect } from 'react';
import { CyberPaySDK } from '@cyberpay/sdk';
 
export function useWalletBalance(address: string, chainIds?: number[]) {
  const [balance, setBalance] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  useEffect(() => {
    if (!address) return;
    
    const fetchBalance = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const sdk = new CyberPaySDK({ 
          apiKey: process.env.REACT_APP_CYBERPAY_API_KEY 
        });
        
        const result = await sdk.wallet.getBalance({
          address,
          chainIds,
          includeNative: true,
          includeZero: false
        });
        
        setBalance(result);
      } catch (err: any) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    
    fetchBalance();
  }, [address, chainIds]);
  
  return { balance, loading, error };
}
 
// Usage in component
function WalletBalanceDisplay({ address }: { address: string }) {
  const { balance, loading, error } = useWalletBalance(address, [1, 137, 10]);
  
  if (loading) return <div>Loading balances...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!balance) return null;
  
  return (
    <div className="wallet-balance">
      <h3>Wallet Balance</h3>
      <p>Total Value: ${balance.totalValueUsd}</p>
      
      {balance.balances.map((chain: any) => (
        <div key={chain.chainId} className="chain-balance">
          <h4>{chain.chainName}</h4>
          {chain.tokens.map((token: any) => (
            <div key={token.address} className="token-balance">
              <span>{token.balance} {token.symbol}</span>
              <span>${token.valueUsd}</span>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

cURL Examples

# Get wallet balance
curl -X GET "https://api.cyberpay.org/v1/wallet/balance?address=0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8&chainIds=1,137,10" \
  -H "Authorization: Bearer YOUR_API_KEY"
 
# Batch balance query
curl -X POST "https://api.cyberpay.org/v1/wallet/balance/batch" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "addresses": [
      "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8e8",
      "0x8ba1f109551bD432803012645Hac136c22C501e5"
    ],
    "chainIds": [1, 137, 10],
    "includeNative": true
  }'

Supported Networks

NetworkChain IDNative TokenStatus
Ethereum1ETH✅ Live
Polygon137MATIC✅ Live
Optimism10ETH✅ Live
Arbitrum42161ETH✅ Live
Base8453ETH✅ Live

Rate Limits

  • Standard: 100 requests per minute
  • Premium: 1000 requests per minute
  • Enterprise: Custom limits available

Best Practices

Performance

  • Use batch queries for multiple addresses
  • Filter by specific chains when possible
  • Cache results for frequently queried addresses
  • Set appropriate includeZero based on use case

Error Handling

  • Validate address format before API calls
  • Handle network timeouts gracefully
  • Implement retry logic for temporary failures
  • Check for unsupported chains

Security

  • Never expose API keys in client-side code
  • Validate addresses on both client and server
  • Implement rate limiting on your endpoints
  • Log balance queries for audit purposes

Use Cases

Portfolio Tracking

  • Display user's complete crypto portfolio
  • Calculate total portfolio value
  • Track balance changes over time
  • Generate portfolio reports

Payment Validation

  • Verify user has sufficient balance before payment
  • Check token allowances for ERC-20 payments
  • Validate payment capability across chains
  • Estimate gas requirements

DeFi Integration

  • Check collateral balances for lending
  • Verify liquidity provider positions
  • Monitor yield farming rewards
  • Track staking balances

Next Steps

Support