Search code examples
javascriptsolanasolana-web3js

How to get a token mint address from a transaction signature in Solana web3


How do get the token mint address from a transaction signature in Solana web3?

Here's an example. https://explorer.solana.com/tx/4y2zCnN1ciucLE6z91J7cQXz4skhCpoBJqhcecfuri5zp2NMSYejopTvGq2sYS9Ud5AkRirFkLXocZKdNfzWudG3?cluster=devnet

This is the transaction signature. 4y2zCnN1ciucLE6z91J7cQXz4skhCpoBJqhcecfuri5zp2NMSYejopTvGq2sYS9Ud5AkRirFkLXocZKdNfzWudG3

I want the token mint address so I can look up the metadata. DzAP4MvZNzV6zUrAW9wKXzDrpgRmEPa1QHhrSBEB823W

I can't figure out how to get the token mint from the transaction signature.


Solution

  • There are several ways you could do that.

    Solution 1

    You can check the instruction #5 i.e the Candy Machine: Mint instruction (code here) the mint account is the account number 6 (code) and the metadata account is the account number 5 (code)

    In JS it would be something like:

    import { Connection, clusterApiUrl } from "@solana/web3.js";
    
    const connection = new Connection(clusterApiUrl("devnet"));
    
    async function getMint(tx: string) {
      const result = await connection.getTransaction(tx);
    
      const metadaIndex = result?.transaction.message.instructions[4].accounts[4];
      const mintIndex = result?.transaction.message.instructions[4].accounts[5];
    
      if (!metadaIndex || !mintIndex) {
        throw new Error("Account not found");
      }
    
      return {
        mint: result?.transaction.message.accountKeys[mintIndex],
        metadata: result?.transaction.message.accountKeys[metadaIndex],
      };
    }
    
    getMint(
      "4y2zCnN1ciucLE6z91J7cQXz4skhCpoBJqhcecfuri5zp2NMSYejopTvGq2sYS9Ud5AkRirFkLXocZKdNfzWudG3"
    );
    
    

    And it will return

    {
      mint: 'DzAP4MvZNzV6zUrAW9wKXzDrpgRmEPa1QHhrSBEB823W',
      metadata: '4YR5CeLEZCF7qVpvHQfYoL84gQQb6uj5sGbaAqP2Eqgj'
    }
    

    Solution 2

    Another solution would be to look at the instruction #4 i.e the Token Program: Mint To and extract the first key

    In JS it would be

    import { Connection, clusterApiUrl } from "@solana/web3.js";
    
    const connection = new Connection(clusterApiUrl("devnet"));
    
    async function getMint(tx: string) {
      const result = await connection.getTransaction(tx);
    
      const mintIndex = result?.transaction.message.instructions[3].accounts[0];
    
      if (!mintIndex) {
        throw new Error("Account not found");
      }
    
      return {
        mint: result?.transaction.message.accountKeys[mintIndex],
      };
    }
    
    getMint(
      "4y2zCnN1ciucLE6z91J7cQXz4skhCpoBJqhcecfuri5zp2NMSYejopTvGq2sYS9Ud5AkRirFkLXocZKdNfzWudG3"
    );
    
    

    And it will return

    { mint: 'DzAP4MvZNzV6zUrAW9wKXzDrpgRmEPa1QHhrSBEB823W' }