I have a contract address: KT1P8RdJ5MfHMK5phKJ5JsfNfask5v2b2NQS, and a wallet address: tz1MSint56iUqoogrKsvEMEykpbKv2Yhmzss. What can I do?
3 Answers
You can get the token balance of your wallet using this TzKt API. In your case, you will need to add two query parameters. So, the API becomes:
This only selects the balance to return. If you need it to return more information, remove &select=balance
from the end.
-
Awesome, I've been looking for it all morning but couldn't find any results. When I use the Taquito library to retrieve a contract by address, there are methods like getBalance or get_balance, but they don't seem to work for me– SoliderCommented Nov 17, 2023 at 8:54
You may access rpc package's getBalance function with tezosToolkit like below to get both balances.
(async ()=> {
try {
const tezos = new TezosToolkit(ghostnet)
let kt1 = await tezos.rpc.getBalance('KT1P8RdJ5MfHMK5phKJ5JsfNfask5v2b2NQS') // returned in bigNumber
let tz1 = await tezos.rpc.getBalance('tz1MSint56iUqoogrKsvEMEykpbKv2Yhmzss') // returned in bigNumber
console.log('kt1: ', kt1.toNumber())
console.log('tz1: ', tz1.toNumber())
} catch (ex) {
console.log(JSON.stringify(ex))
}
})()
In your comment to another answer, you mention trying the getBalance entrypoint in Taquito. That getBalance entrypoint (as defined in the FA1.2 standard) sends the account's balance to another contract as a callback, so it's not what you'd use to get the balance directly.
There doesn't appear to be any view in the contract that returns the balance directly, so the way to do it in Taquito is to get the contract storage and look up the account's balance in the big-map that it stores token balances in. This works for me:
const { TezosToolkit } = require("@taquito/taquito");
const BigNumber = require('bignumber.js');
const rpcUrl = "https://ghostnet.ecadinfra.com";
const Tezos = new TezosToolkit(rpcUrl);
const contractAddress = "KT1P8RdJ5MfHMK5phKJ5JsfNfask5v2b2NQS";
const walletAddress = "tz1MSint56iUqoogrKsvEMEykpbKv2Yhmzss";
const getBalance = async () => {
const contract = await Tezos.contract.at(contractAddress);
const contractStorage = await contract.storage();
const accountBalance = new BigNumber(await contractStorage['tokens'].get(walletAddress));
console.log(accountBalance.toString()); // 8999998980
}
getBalance();