Check Asset Balance

Checking asset balance is supported for an individual address or for multiple addresses.

Get Balance for a single token

Checking the asset balance for an address can be obtained by calling the getBalance method of the DEX contract.

import { wallet } from '@cityofzion/neon-js';

async function getContractBalanceForAddress(asset, address) {
  const addressScriptHash = wallet.getScriptHashFromAddress(address.replace('0x', ''));
  try {
    const res = await executeReadOnlyContractOperation('getBalance', [
      u.reverseHex(asset.replace('0x', '')),
      u.reverseHex(addressScriptHash.replace('0x', '')),
    ]);

    if (res.success && res.result.length >= 1) {
      return u.fixed82num(res.result);
    }
    return 0;
  } catch (e) {
    throw Error(`Failed to fetch contract balance. ${e}`);
  }
}


console.log('APH contract balance for address AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y: '
  + getContractBalanceForAddress('a0777c3ce2b169d4a23bcba4565e3225a0122d95', 'AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y'));

Get Balance for all tokens

const DEX_HASH = '9488220e8654d798f9b9cb9e74bd611ecc83fd0f';
const rpcClient = new rpc.RPCClient('https://mainneo.aphelion-neo.com:10331');

async function getBalancesForAddress(address) {
  const addressScriptHash = wallet.getScriptHashFromAddress(address.replace('0x', ''));
  // Step 1 - Acquire UTXO inputs to use for withdraw
  const res = await rpcClient.query({
      method: 'getcontractbalances',
      params: [
        DEX_HASH,
        addressScriptHash.replace('0x', '')
      ],
    });
  
  return res.result;
}

Example Response

{
        "balance": [
            {
                "asset_hash": "bb3b54ab244b3658155f2db4429fc38ac4cef625",
                "amount": 150
            },
            {
                "asset_hash": "45d493a6f73fa5f404244a5fb8472fc014ca5885",
                "amount": 1217.97
            },
            {
                "asset_hash": "602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7",
                "amount": 37.13
            },
        ],
        "contracthash": "9488220e8654d798f9b9cb9e74bd611ecc83fd0f",
        "address": "NeoAddressWillShowUpHereBeHere"
    }