You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript查询波场USDT余额?余额异常及uint256疑问

波场USDT余额查询问题与解答

问题描述

使用JavaScript查询波场USDT余额时,实际账户余额为0,但查询结果输出150990000;同时想了解uint256的定义。以下是使用的代码:

const options = {
  method: 'POST',
  headers: {accept: 'application/json', 'content-type': 'application/json'},
  body: JSON.stringify({
    owner_address: 'TUhycsR2geBGknpwqTz3n7i63XqPUWLJjR',
    contract_address: 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf',
    function_selector: 'balanceOf(address)',
    parameter: '000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c',
    visible: true
  })
};
fetch(' https://nile.trongrid.io/wallet/triggerconstantcontract', options)
  .then(response => response.json())
  .then(response => {
    async function ff(){
      console.log(response)
    let outputs = '0x'+response.constant_result[0]

    let result =  await decodeParams(['uint256'], outputs, false)

    console.log(result[0].toNumber())

    }
    ff();
    
  })
  .catch(err => console.error(err));

余额异常原因

  1. 查询地址不匹配:代码中parameter字段填的是其他地址的十六进制值,balanceOf方法实际查询的是parameter对应的账户余额,而非owner_address填写的你的地址,所以得到的是他人账户的余额。
  2. 未处理代币小数位:USDT默认有6位小数,合约返回的uint256数值需要除以10^6才是实际USDT数量。150990000 ÷ 1000000 = 150.99 USDT,这是parameter对应地址的测试网余额。
  3. 测试网环境:调用的是波场Nile测试网节点(nile.trongrid.io),查询的是测试网中的余额,和主网余额无关。若你测试网账户余额为0,自然和查询结果不符。

uint256是什么

uint256是以太坊/Solidity(波场合约兼容该标准)中的无符号256位整数类型:

  • 取值范围从0到2^256-1,能容纳极大数值,避免溢出问题;
  • 代币合约中常用它存储余额、总供应量等数据,因为代币最小单位需要高精度存储,uint256的精度完全满足需求。

修正后的代码

将parameter替换为你自己波场地址的十六进制格式(去掉前缀后补全64位,前24位为0,后40位是地址十六进制值),同时添加小数位处理:

// 可通过TronWeb工具将波场地址转十六进制:TronWeb.address.toHex('你的波场地址')
const userHexAddress = '000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c'; // 替换为你地址的正确十六进制参数
const options = {
  method: 'POST',
  headers: {accept: 'application/json', 'content-type': 'application/json'},
  body: JSON.stringify({
    owner_address: 'TUhycsR2geBGknpwqTz3n7i63XqPUWLJjR',
    contract_address: 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf',
    function_selector: 'balanceOf(address)',
    parameter: userHexAddress,
    visible: true
  })
};

fetch('https://nile.trongrid.io/wallet/triggerconstantcontract', options)
  .then(response => response.json())
  .then(response => {
    async function getBalance() {
      const outputs = '0x' + response.constant_result[0];
      const result = await decodeParams(['uint256'], outputs, false);
      // USDT有6位小数,转换为实际余额
      const actualBalance = result[0].toNumber() / 1000000;
      console.log('实际USDT余额:', actualBalance);
    }
    getBalance();
  })
  .catch(err => console.error(err));

若查询主网余额,需将节点地址替换为https://api.trongrid.io/wallet/triggerconstantcontract,同时使用主网USDT合约地址TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t。

内容的提问来源于stack exchange,提问作者jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:06:24