Using the SDK, I was able to obtain a “TokenBalanceMap” using the following code:
const accountBalance = await new AccountBalanceQuery()
.setAccountId(accountId)
.setTokenIds([tokenId])
.execute(client);
const tokenBalance = accountBalance.tokens;
But the tokens
property is marked as @deprecated
(SDK version is 2.31.0). What’s the recommended way to do this?
Using the mirror nodes is the recommended way to check if an account is currently associated with an HTS token. It’s important to note when you associate with a token it will show you have a 0 balance of that token. Once you receive that token your balance will go up as expected.
Here is how you can check using the mirror nodes:
First, construct a fetch request to get account info by account id.
const testnetUrl = 'https://testnet.mirrornode.hedera.com/';
// fetch the account info
const accountInfo = await fetch(`${testnetUrl}api/v1/accounts/${accountId}`, {method: "GET"});
convert the response to json and grab the associated tokens list from the json
const associatedTokensList = accountInfoJson.balance.tokens;
Here is a link to the Hedera Mirror Node REST API swagger documentation https://testnet.mirrornode.hedera.com/api/v1/docs/#/