Skip to main content

Usage

from chipi_sdk import GetTokenBalanceParams, ChainToken, Chain

balance = sdk.get_token_balance(
    params=GetTokenBalanceParams(
        chain_token=ChainToken.USDC,
        chain=Chain.STARKNET,
        wallet_public_key="0x04...abc",
    )
)

Parameters

  • chain_token (ChainToken): Token to query (e.g., ChainToken.USDC, ChainToken.ETH)
  • chain (Chain): Blockchain network (e.g., Chain.STARKNET)
  • wallet_public_key (str, optional): Wallet address. Use this or external_user_id
  • external_user_id (str, optional): External user ID. Use this or wallet_public_key

Return Value

Returns a GetTokenBalanceResponse object containing:
  • chain: Blockchain network
  • chain_token: Token type
  • chain_token_address: On-chain contract address for the token
  • decimals: Token decimal places
  • balance: Token balance as a string

Example Implementation

from chipi_sdk import ChipiSDK, ChipiSDKConfig, GetTokenBalanceParams, ChainToken, Chain

# Initialize SDK
sdk = ChipiSDK(
    config=ChipiSDKConfig(
        api_public_key="pk_prod_your_public_key",
        api_secret_key="sk_prod_your_secret_key",
    )
)

def check_balance(wallet_address: str):
    """Check USDC balance for a wallet."""
    try:
        balance = sdk.get_token_balance(
            params=GetTokenBalanceParams(
                chain_token=ChainToken.USDC,
                chain=Chain.STARKNET,
                wallet_public_key=wallet_address,
            )
        )

        print(f"Token: {balance.chain_token}")
        print(f"Balance: {balance.balance}")
        print(f"Decimals: {balance.decimals}")
        print(f"Contract: {balance.chain_token_address}")

        return balance

    except Exception as error:
        print(f"Failed to get balance: {error}")
        raise

# Usage
balance = check_balance("0x04...abc")

Async Version

For async applications, use aget_token_balance:
import asyncio

async def check_balance_async(wallet_address: str):
    """Check USDC balance asynchronously."""
    balance = await sdk.aget_token_balance(
        params=GetTokenBalanceParams(
            chain_token=ChainToken.USDC,
            chain=Chain.STARKNET,
            wallet_public_key=wallet_address,
        )
    )
    return balance

# Run async
balance = asyncio.run(check_balance_async("0x04...abc"))

Query by External User ID

You can query balance using the external user ID instead of the wallet address:
balance = sdk.get_token_balance(
    params=GetTokenBalanceParams(
        chain_token=ChainToken.USDC,
        chain=Chain.STARKNET,
        external_user_id="user-123",
    )
)

Checking Multiple Token Balances

from chipi_sdk import GetTokenBalanceParams, ChainToken, Chain, ChipiApiError

def get_all_balances(wallet_address: str):
    """Get balances for all supported tokens."""
    tokens = [
        ChainToken.USDC,
        ChainToken.ETH,
        ChainToken.STRK,
        ChainToken.USDT,
        ChainToken.DAI,
        ChainToken.WBTC,
    ]

    balances = {}
    for token in tokens:
        try:
            result = sdk.get_token_balance(
                params=GetTokenBalanceParams(
                    chain_token=token,
                    chain=Chain.STARKNET,
                    wallet_public_key=wallet_address,
                )
            )
            balances[token.value] = result.balance
        except ChipiApiError as e:
            print(f"Failed to fetch {token.value}: {e.message}")
            balances[token.value] = None

    return balances

# Usage
all_balances = get_all_balances("0x04...abc")
for token, amount in all_balances.items():
    print(f"{token}: {amount}")

Balance Check Before Transfer

A common pattern is checking the balance before initiating a transfer:
from chipi_sdk import (
    GetTokenBalanceParams,
    GetWalletParams,
    TransferParams,
    ChainToken,
    Chain,
)

def transfer_with_balance_check(
    user_id: str,
    recipient: str,
    amount: str,
    pin: str,
):
    """Transfer USDC after verifying sufficient balance."""
    # Get wallet
    wallet_response = sdk.get_wallet(
        params=GetWalletParams(external_user_id=user_id)
    )

    if not wallet_response:
        raise ValueError(f"Wallet not found for user: {user_id}")

    # Check balance
    balance = sdk.get_token_balance(
        params=GetTokenBalanceParams(
            chain_token=ChainToken.USDC,
            chain=Chain.STARKNET,
            wallet_public_key=wallet_response.wallet.public_key,
        )
    )

    from decimal import Decimal

    if Decimal(balance.balance) < Decimal(amount):
        raise ValueError(
            f"Insufficient balance: {balance.balance} USDC available, "
            f"{amount} USDC required"
        )

    # Execute transfer
    tx_hash = sdk.transfer(
        params=TransferParams(
            encrypt_key=pin,
            wallet=wallet_response.wallet,
            token=ChainToken.USDC,
            recipient=recipient,
            amount=amount,
        )
    )

    print(f"Transfer successful: {tx_hash}")
    return tx_hash

# Usage
tx = transfer_with_balance_check(
    user_id="user-123",
    recipient="0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
    amount="25.0",
    pin="secure-pin-1234",
)

Error Handling

from chipi_sdk import ChipiApiError, GetTokenBalanceParams, ChainToken, Chain

def safe_get_balance(wallet_address: str, token: ChainToken = ChainToken.USDC):
    """Get token balance with error handling."""
    try:
        balance = sdk.get_token_balance(
            params=GetTokenBalanceParams(
                chain_token=token,
                chain=Chain.STARKNET,
                wallet_public_key=wallet_address,
            )
        )

        return {
            "success": True,
            "balance": balance.balance,
            "token": balance.chain_token,
            "decimals": balance.decimals,
        }

    except ChipiApiError as e:
        print(f"API error: {e.message}")
        return {
            "success": False,
            "error": e.message,
            "status": e.status,
        }
    except Exception as e:
        print(f"Unexpected error: {e}")
        return {
            "success": False,
            "error": str(e),
        }

# Usage
result = safe_get_balance("0x04...abc")
if result["success"]:
    print(f"Balance: {result['balance']}")
else:
    print(f"Error: {result['error']}")