In this part, you will learn how to edit and create components for minting tokens directly to the minter's wallet on the frontend side of your DApp.
illustration
b
Transferring Minted Tokens to Another Wallet

We'll now explore how to transfer SPL tokens to another user. Start by opening the TransferToken.tsx component file in your project.

As before, you'll see steps for importing necessary elements and setting up the Interface Definition Language (IDL) for creating the Program API. This setup is crucial for making RPC (Remote Procedure Call) transfers.

First, we start a new transaction using Solana's Web3.js:

const transaction = new web3.Transaction();

Next, we collect user input for the following:

  • mint account: The account of the token to be transferred.
  • recipientPubKey: The public key of the recipient.
  • amount: The amount of tokens to be transferred.

We adjust the amount to account for the smallest token divisions (lamports):

const mintPubKey = new web3.PublicKey(event.target.mint.value);
const recipientPubKey = new web3.PublicKey(event.target.recipient.value);
let amount = event.target.amount.value;
amount = amount * 10 ** 9; // Adjusting for lamports

We need to create ATAs for both the sender and the recipient, using the same token mint:

const senderAta = await getAssociatedTokenAddress(
 mintPubKey,
 publicKey,
    false,
 TOKEN_PROGRAM_ID,
 ASSOCIATED_TOKEN_PROGRAM_ID
);

const receiverAta = await getAssociatedTokenAddress(
 mintPubKey,
 recipientPubKey,
    false,
 TOKEN_PROGRAM_ID,
 ASSOCIATED_TOKEN_PROGRAM_ID
);

Next, we check if the receiver's ATA exists and, if not, add an instruction to create it:

try {
    await getAccount(connection, receiverAta);
} catch (e) {
 transaction.add(
        createAssociatedTokenAccountInstruction(
 publicKey,
 receiverAta,
 recipientPubKey,
 mintPubKey,
 TOKEN_PROGRAM_ID,
 ASSOCIATED_TOKEN_PROGRAM_ID
        )
    );
}

Finally, we set up the RPC call to transfer tokens using the contract's methods:

const transferTx = await program.methods
    .transferTokens(amount)
    .accounts({
 from: senderAta,
 to: receiverAta,
 owner: publicKey,
    })
    .instruction();

transaction.add(transferTx);

const signature = await sendTransaction(transaction, connection);

await connection.confirmTransaction(signature, "confirmed");

And that wraps up our module on minting and transferring SPL tokens in a DApp—from the front end to the backend.

Stay tuned for more on client-contract interactions in the next module!