0

I'm running a Solana node and I'd like to send a transfer request to my running node. I can transfer SOL but I don't know what I need to do for transferring SPL Tokens like GMT or SRM.

I was looking for passing a contract address of the Token somewhere but couldn't figure it out.

const sendSolana = async () => {
  const transaction = new web3.Transaction().add(
    web3.SystemProgram.transfer({
      fromPubkey: fromKeypair_1.publicKey,
      toPubkey: fromKeypair_2.publicKey,
      lamports: web3.LAMPORTS_PER_SOL * parseFloat(0.001), //0.001
    })
  );
  const signature = await web3.sendAndConfirmTransaction(
    connection,
    transaction,
    [fromKeypair_1]
  );
  console.log("SIGNATURE", signature);
};

1 Answer 1

2

You can use [spl-token][1] npm package to transfer SPL tokens. [1]: https://www.npmjs.com/package/@solana/spl-token

In order to transfer SPL tokens, both sender and receiver must have particular associated token accounts. SPL tokens are transferred between those associated token accounts.

Following code transfers SRM token.

const { getOrCreateAssociatedTokenAccount, transfer } = require('@solana/spl-token'); 
const {Connection, Keypair, PublicKey} = require('@solana/web3.js');

const tokenMintAddress = new PublicKey('SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt') // SRM tokenMintAddress

const connection = new Connection('RPC_END_POINT', { commitment: 'confirmed'});

// Need sender wallet's private keys to be used as signer
const senderWallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(fs.readFileSync(KEYPAIR_PATH))));
const receiverPubkey = new PublicKey(recieverPublicWalletAddress) // solana wallet address

// get or create associated tokenAccount's (SRM) for the receiver and sender
const receiverTokenAccount = await getOrCreateAssociatedTokenAccount(
        connection,
        senderWallet, // new token account creation costs some amount of SOL and sender will bear the costs
        tokenMintAddress,
        receiverPubkey 
    );

const senderTokenAccount = await getOrCreateAssociatedTokenAccount(
        connection,
        senderWallet,
        tokenMintAddress,
        senderWallet.publicKey
    );

// Finally do the transfer
    await transfer(
            connection,
            senderWallet,
            senderTokenAccount.address,
            receiverTokenAccount.address,
            senderWallet.publicKey,
            amount * 1000000, // amount of tokens to transfer, need to multiply the decimals (SRM has 6 decimals)
        )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.