Search code examples
web3jssolana

How to get a reference to a former created Token in Solana (client side, JS)


I'm able to create a token and mint it into an spl account address. But when I restart my program, how do I get a reference to that Token, so that I mint again?

const web3 = require("@solana/web3.js");
const splToken = require('@solana/spl-token');
const { PublicKey, Keypair, Transaction, SystemProgram, LAMPORTS_PER_SOL, sendAndConfirmTransaction, clusterApiUrl } = require("@solana/web3.js");

let secretKey = Uint8Array.from([233, 65, 11, rest of my secret]);
let fromWindowsWallet = Keypair.fromSecretKey(secretKey);

let connection = new web3.Connection(clusterApiUrl('devnet'));

(async () => {
    //create my new token mint
     let SWAB = await splToken.Token.createMint(
         connection,
         fromWindowsWallet,
         fromWindowsWallet.publicKey,
         fromWindowsWallet.publicKey,
         2,
         splToken.TOKEN_PROGRAM_ID,
     );
    console.log(SWAB.publicKey) // -> PublicKey {
                      _bn: <BN: 2643549b60882496a15407c2f1a6139dd2c4128879480b1d56fdd464550db22b>
  }
// ... continue with that Token SWAB
}

So when I restart my program, how can I get a reference to the Token SWAB again? I tried:

let pubKey = new PublicKey("<BN: 6ddf6e1d765a193d9cbe146ceeb79ac1cb485ed5f5b37913a8cf5857eff00a9>");
let SWAB = new splToken.Token(
        connection,
        pubKey,
        splToken.TOKEN_PROGRAM_ID,
        fromWindowsWallet
    )

but that throws: Error: Non-base58 character


Solution

  • After creating the Token I can get the pubKey with:

    console.log(SWAB.publicKey.toBase58())  // 3aN3KP6kQdBvTHTeK785Uuykddram97B844RoJc19VNS
    

    Then I can get a reference to the Token like this and continue minting:

    let pubKey = new PublicKey('3aN3KP6kQdBvTHTeK785Uuykddram97B844RoJc19VNS');
    let SWAB = new splToken.Token(
            connection,
            pubKey,
            splToken.TOKEN_PROGRAM_ID,
            fromWindowsWallet
        )
    

    (connection and fromWindowsWallet are defined in the code of my question)