Search code examples
reactjsjsxtokensolanasolana-web3js

How to get Metadata from a Token adress using web3 js on SOLANA


I get a list of tokens own by a publicKey thanks to that method :

connection
.getParsedTokenAccountsByOwner(
  new PublicKey(publicKey.toBase58()),
  {
    programId: TOKEN_PROGRAM_ID
  }
)
.then((b) => {
  const owner = b?.value?.[0].account.owner;
  const pb = b?.value?.[0].pubkey;

  const nonZeroAccounts = b?.value?.filter(
    (obj) => obj.account.data.parsed.info.tokenAmount.uiAmount > 0
  );
  setTokens(JSON.stringify(nonZeroAccounts, null, 2));

return value for an account that own 1 token for example :

{
"account": {
  "data": {
    "parsed": {
      "info": {
        "isNative": false,
        "mint": "example",
        "owner": "example",
        "state": "initialized",
        "tokenAmount": {
          "amount": "1",
          "decimals": 0,
          "uiAmount": 1,
          "uiAmountString": "1"
        }
      },
      "type": "account"
    },
    "program": "spl-token",
    "space": 165
  },
  "executable": false,
  "lamports": 2039280,
  "owner": {
    "_bn": "example"
  },
  "rentEpoch": 245
},
"pubkey": {
  "_bn": "example"
}

Now that I have these informations, I would like to know how to get the metadata of that token


Solution

  • After Soubriquet request, I ll add here the actual working code.

    Metaplex doc isnt always up to date, so don't trust it.

        const Metadata = require("@metaplex-foundation/mpl-token-metadata");
        
        async function getMetadataPDA(mint) 
            {
              const [publicKey] = await web3.PublicKey.findProgramAddress(
                [Buffer.from("metadata"), 
                Metadata.PROGRAM_ID.toBuffer(), 
                mint.toBuffer()],
                Metadata.PROGRAM_ID
              );
              return publicKey;
            }
        
        let pda = await getMetadataPDA(mint);
        let res = await Metadata.Metadata.fromAccountAddress(connection, account);
    

    Consider that mint is a PublicKey, not a string.

    Here is JSON structure of the returned values https://docs.metaplex.com/token-metadata/Versions/v1.0.0/nft-standard