Search code examples
javascriptethereumweb3js

How do I get a balance in usdt?


My code:

const tokens = {
  usdt: "0xbA6879d0Df4b09fC678Ca065c00dd345AdF0365e"
}
const minABI = [
  {
    constant: true,
    inputs: [{ name: "_owner", type: "address" }],
    name: "balanceOf",
    outputs: [{ name: "balance", type: "uint256" }],
    type: "function",
  },
];
async function getUsdtBalance() {
  const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
  const Web3Client = new Web3(window.ethereum);

  const contract = new Web3Client.eth.Contract(minABI, tokens.usdt)

  const result = await contract.methods.balanceOf(accounts[0]).call();
  const format = Web3Client.utils.fromWei(result);
  console.log(format)
}

Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.

It's a test network. I have 99 eth, and 0 usdt.

Most likely an error in the ABI, I myself do not understand anything, I took it from the guide.


Solution

  • It looks like the code is working. I also think there is a problem with the ABI. I would change the ABI to something like this:

    const minABI = [
        {
          "inputs": [
            {
              "internalType": "address",
              "name": "account",
              "type": "address"
            }
          ],
          "name": "balanceOf",
          "outputs": [
            {
              "internalType": "uint256",
              "name": "",
              "type": "uint256"
            }
          ],
          "stateMutability": "view",
          "type": "function"
        }
    ];
    

    I have added a field called stateMutability. This field allows you to define how the function should interact with the data in the blockchain. In our case we are not modifying the data, but only reading it, so we set the value to view.

    If there is still a problem, it may make sense to check the token address.