Skip to content

Instantly share code, notes, and snippets.

@munanadi
Created December 23, 2021 15:22
Show Gist options
  • Select an option

  • Save munanadi/7fb95a93511b9a64a87950bb8af745be to your computer and use it in GitHub Desktop.

Select an option

Save munanadi/7fb95a93511b9a64a87950bb8af745be to your computer and use it in GitHub Desktop.
Fetches token balances same as solscan API
import { Connection, PublicKey } from "@solana/web3.js";
// var JSON_parse = require("uint8array-json-parser").JSON_parse;
import { TOKEN_PROGRAM_ID, Token } from "@solana/spl-token";
const connection = new Connection("https://solana-api.projectserum.com");
// token account here
const owner = new PublicKey("---------------------");
connection
.getParsedTokenAccountsByOwner(owner, {
programId: TOKEN_PROGRAM_ID
})
.then((b) => {
const owner = b?.value?.[0].account.owner;
const pb = b?.value?.[0].pubkey;
/*
values will look like this.
{
"value": {
"isNative": false,
"mint": "BRLsMczKuaR5w9vSubF4j8HwEGGprVAyyVgS4EX7DKEg",
"owner": "8AH4pCW88KxSRTzQe3dkEsLCDvjHJJJ5usiPcbkaGA3M",
"state": "initialized",
"tokenAmount": {
"amount": "872000",
"decimals": 6,
"uiAmount": 0.872,
"uiAmountString": "0.872"
}
},
"tokenAccount": "GxcNhRVb7orWD8naJScGjH4E8aKnjecfmPRoVo4hxrZK"
},
*/
const values = b?.value?.map((v) => ({
value: v.account.data.parsed.info,
tokenAccount: v.pubkey.toString()
}));
document.getElementById("app").innerHTML = `
<h1>getParsedTokenAccountsByOwner</h1>
<h4>Public Key</h4>
<p>${pb.toString()}</p>
<h4>Owner</h4>
<p>${owner.toString()}</p>
<pre>${JSON.stringify(values, null, 2)}</pre>`;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment