0

I've been trying the code below to get the spl-token account address for a specific token in a Solana wallet from the Solana wallet address, but I am having issues getting the result I am looking for. I run:

const web3 = require('@solana/web3.js');

(async () => {
  const solana = new web3.Connection("https://api.mainnet-beta.solana.com");

//the public solana address
  const accountPublicKey = new web3.PublicKey(
    "2B1Uy1UTnsaN1rBNJLrvk8rzTf5V187wkhouWJSApvGT"
  );

//mintAccount = the token mint address
  const mintAccount = new web3.PublicKey(
    "GLmaRDRmYd4u3YLfnj9eq1mrwxa1YfSweZYYZXZLTRdK"
  );
  console.log(
    await solana.getTokenAccountsByOwner(accountPublicKey, {
      mint: mintAccount,
    })
  );
})();

I'm looking for the token account address in the return, 6kRT2kAVsBThd5cz6gaQtomaBwLxSp672RoRPGizikH4. I get:

{ context: { slot: 116402202 }, value: [ { account: [Object], pubkey: [PublicKey] } ] }

I can drill down through this a bit using .value[0].pubkey or .value[0].account but ultimately can't get to the information i'm looking for, which is a return of 6kRT2kAVsBThd5cz6gaQtomaBwLxSp672RoRPGizikH4

Does anyone know what is going wrong? (Note I do not want to use the getOrCreateAssociatedAccountInfo() method, i'm trying to get the token account address without handling the wallets keypair)

Iceee
  • 31
  • 1
  • 4

2 Answers2

3

ISSUE SOLVED: I needed to grab the correct _BN data and convert, solution below.

const web3 = require('@solana/web3.js');

(async () => {
  const solana = new web3.Connection("https://api.mainnet-beta.solana.com");

//the public solana address
  const accountPublicKey = new web3.PublicKey(
    "2B1Uy1UTnsaN1rBNJLrvk8rzTf5V187wkhouWJSApvGT"
  );

//mintAccount = the token mint address
  const mintAccount = new web3.PublicKey(
    "GLmaRDRmYd4u3YLfnj9eq1mrwxa1YfSweZYYZXZLTRdK"
  );
  const account = await solana.getTokenAccountsByOwner(accountPublicKey, {
      mint: mintAccount});

      console.log(account.value[0].pubkey.toString());

})();

Iceee
  • 31
  • 1
  • 4
0

That will certainly work as a heavy-handed approach. As an alternative, you can try to just search for the associated token account owned by that wallet without creating it if it doesn't exist.

You would essentially follow the logic at https://github.com/solana-labs/solana-program-library/blob/0a61bc4ea30f818d4c86f4fe1863100ed261c64d/token/js/client/token.js#L539 except without the whole catch block.

Jon C
  • 7,019
  • 10
  • 17