How to Transfer SOL and SPL Tokens Using Anchor?

Solana is a promising alternative among the blockchain networks that would help in building the future of web3. You might wonder about the possibilities of building web3 solutions on Ethereum. However, Ethereum has been bogged down by the problems of scalability and interoperability. Therefore, Solana has emerged as a promising alternative to Ethereum for blockchain and web3 development.

You are here to learn how to transfer SOL and SPL tokens using Anchor on Solana for a reason. Anchor is a dedicated framework for Solana that helps in faster development of secure Solana programs. When you work with Solana and Anchor, you will come across situations where you have to send SOL or SPL tokens between users. For example, NFT transfers or user payments to the treasury. Let us find out how you can send SOL and SPL tokens using Anchor for Solana blockchain.

Build your identity as a certified blockchain and web3 expert with 101 Blockchains’ Blockchain & Web3 Certifications designed to provide enhanced career prospects.

What Do You Need to Transfer Tokens Using Anchor?

Before you learn how to transfer SOL using Anchor or send SPL tokens, you must know the important requirements for the process. You have to create a Solana program with the help of Anchor and Solana Playground. In addition, you have to create a program instruction for transferring SOL tokens between two users. You must also create a program instruction to transfer SPL tokens between two accounts. On top of it, you would also need tests for verifying the token transfers.

If you want to complete an Anchor SPL token transfer successfully, then you would need basic experience in Anchor programming. On top of that, you must know how to send transactions on Solana by using JavaScript. You would also need a fundamental knowledge of TypeScript or JavaScript and Rust programming language. Another important prerequisite for transferring SOL and SPL tokens using Anchor is an updated modern browser, such as Google Chrome. You would also need some important dependencies with specific versions, such as the following.

  • anchor-lang v0.26.0
  • anchor-spl v0.26.0
  • solana-program v1.14.12
  • spl-token v3.5.0

Certified Enterprise Blockchain Professional Certification

Understanding the Details of SPL Tokens

You might be curious about the methods recommended for transferring SOL and SPL tokens by using Anchor. However, you can find a clear answer to “What is an SPL transfer?” by diving into the details of SPL tokens. SPL or Solana Program Library tokens are a critical component in the Solana development lifecycle. You should learn how to transfer SPL tokens are they are essential for different functions such as,

  • Sending NFTs in bulk to another wallet.
  • Management of token flows between escrow accounts.
  • Airdropping whitelist tokens to the community.

It is also important to remember that the process for Anchor SPL token transfer is different from transferring SOL tokens. Therefore, you must understand the workings of SPL tokens to move further in the journey of Solana development. One of the crucial aspects of understanding SPL tokens would focus on an overview of SPL token accounts. The important components in the Solana Token Program account include Associated Token Accounts and Mint IDs. Here is a brief overview of the working of the two components in a Solana Token Program account.

  • Mint IDs

Each SPL token features a unique mint ID, which can help differentiate it from other types of tokens. You should notice that an Anchor SPL token would have a unique mint address. For example, the mint ID of USDC SPL token is different from that of the SAMO token.

  • Associated Token Accounts

The Solana Token Program also extracts a token account key from the main System account address of the user. In addition, the program would also derive a token mint address that can help users create a main token account for each token in their ownership. The main token account is known as Associated Token Account, which is a unique account associated with the user and particular token mint.

As you learn how to transfer SOL and SPL tokens using Anchor, you must remember that token transfers always happen between two ATAs with similar associated mint addresses. In addition, it is important to remember that all accounts do not have an ATA present for each mint.

Start learning Blockchain with World’s first Blockchain Skill Paths with quality resources tailored by industry experts now!

Step-by-Step Guide for Transferring SOL and SPL Tokens Using Anchor

You can find the ideal approach to transfer SPL and SOL tokens with Anchor framework by following different steps in a sequence. Here is an outline of the different steps that you would need for transferring SOL and SPL tokens using Anchor.

Initiating the Project

The first step in guides that explain “What is an SPL transfer?” would point to initiating the project. You can visit https://beta.solpg.io/ to create a new project with Solana Playground. It is a browser-based Solana code editor that helps in faster project setup and also supports the effective operation of the project. You could also use your own code editor. However, the steps in this discussion would align with the steps required on Solana Playground.

  • First of all, you have the select the ‘Create a new project’ option.
  • Input the name of the project as ‘transfers’ and then choose the “Anchor (Rust)” option.

With these two steps, you can initialize your token transfer project on Anchor.

Creating and Connecting a Wallet

As you want to learn how to transfer SOL using Anchor, you could utilize a ‘throw-away’ wallet. It can help you understand the method for transferring SOL and SPL tokens without any dedicated tools. Interestingly, you can use Solana Playground for creating a ‘throw-away’ wallet. You have to look for a red dot on the bottom left corner of the browser window, where you can find the ‘Not connected’ message. Click on the red dot, and Solana Playground will generate a new wallet or help you import your own wallet.

You can save the wallet for later use and then click on continue when you are ready to move forward. It would create a new wallet that would be connected to the Solana devnet. You must also note that Solana Playground would airdrop some SOL tokens automatically to the new wallet. However, you should request additional SOL tokens to ensure that you have the right amount of tokens for deploying the transfer program.

How can you request the additional SOL tokens for the program to transfer Anchor SPL token and SOL tokens? You could utilize Solana CLI commands in the browser terminal to request additional SOL tokens. The command ‘solana airdrop 2’ would help in obtaining a drop of 2 SOL tokens in your wallet. Now, your wallet would be connected to the devnet with a balance of 6 SOL tokens.

Want to learn about the fundamentals of blockchain? Enroll now in the Blockchains Fundamentals Free Course

Creation of the Transfer Program

With the initial setup ready for the transfer process, you have to create the transfer program. You can begin the process by opening the ‘lib.rs’ to delete the starter code. After you have a blank slate, you can start creating the program. The process of Anchor SPL token transfer would start with importing the crucial dependencies. You should add the following on the top of the file for importing the dependencies.

use anchor_lang::prelude::*;

use anchor_spl::token::{self, Token, TokenAccount, Transfer as SplTransfer};

use solana_program::system_instruction;

declare_id!("11111111111111111111111111111111");

The imported dependencies will help you use the Anchor framework, the system program, and the SPL token program. In addition, Solana Playground would also automatically update the ‘declare_id!’ upon deploying the program.

Certified Enterprise Blockchain Architect Certification

Creating the SOL Transfer Function

You can transfer SOL using Anchor by creating a function for the same. The transfer function would require a clear definition of a struct. You can add the following code to the program.

#[derive(Accounts)]

pub struct TransferLamports<'info> {

    #[account(mut)]

    pub from: Signer<'info>,

    #[account(mut)]

    pub to: AccountInfo<'info>,

    pub system_program: Program<'info, System>,

}

The struct provides the definition of the ‘from’ account for signing the transaction and transferring SOL to the ‘to’ account. In addition, the system program can help in managing the transfer. You must note that the ‘#[account (mut)]’ attribute would showcase the program would work on modifying the account. In the next step to transfer SOL token, you have to create the function that would be responsible for managing the transfer. Here is a snippet that you can add to the program.

#[program]

pub mod solana_lamport_transfer {

    use super::*;

    pub fn transfer_lamports(ctx: Context<TransferLamports>, amount: u64) -> Result<()> {

        let from_account = &ctx.accounts.from;

        let to_account = &ctx.accounts.to;


        // Create the transfer instruction

        let transfer_instruction = system_instruction::transfer(from_account.key, to_account.key, amount);


        // Invoke the transfer instruction

        anchor_lang::solana_program::program::invoke_signed(

            &transfer_instruction,

            &[

                from_account.to_account_info(),

                to_account.clone(),

                ctx.accounts.system_program.to_account_info(),

            ],

            &[],

        )?;


        Ok(())

    }

}

Here is an explanation of the different aspects of the snippet.

The ‘#[program]’ attribute specifies that the module is an Anchor program. It helps in generating the boilerplate required for defining the entry point of the program. It also works for automatic management of account deserialization and validation.

The ‘solana_lamport_transfer’ module helps in importing the important items from the parent module by leveraging ‘use super::*;’.

The ‘transfer_lamports’ function receives an ‘amount’ and ‘Context’ as the arguments. ‘Context’ argument includes the account information required for the transaction. On the other hand, the ‘amount’ specifies the number of lamports or SOL tokens you want to transfer.

You could also notice how the snippet helps in creating references to the ‘to_account’ and ‘from_account’ from the context. These references would play a crucial role in the transfer.

You can also find the ‘system_instruction: :transfer’ function as an essential tool for creating a transfer function. The transfer function takes the public key of the ‘from_account’ and the ‘to_account’ alongside the ‘amount’ that you want to send as the arguments.

You would also need the ‘anchor_lang::solana_program::program::invoke_signed’ function for invoking the transfer function. It utilizes the transaction signer or the ‘from_account’ by taking the transfer instruction, which is an array of account information. The account information is derived from the ‘system_program,’ ‘from_account,’ and ‘to_account.’ In addition, it also delivers an empty array for signers.

Finally, the ‘transfer_lamports’ function would return the value ‘Ok(())’ for showcasing a successful execution. You can ensure functionality of the transfer function by clicking on the ‘Build’ button or by typing the command ‘anchor build’ in the terminal.

Excited to learn about the potential use cases for web3 technologies, Enroll now in the Certified Web 3.0 Professional Certification

Creating the Function for Transferring SPL Tokens

The next highlight in a guide to transfer SOL and SPL tokens using Anchor focuses on creating a function for transferring SPL tokens. First of all, you have to create a new context for the function. You should add the following snippet to your program within the ‘TransferLamports’ struct.

#[derive(Accounts)]

pub struct TransferSpl<'info> {

    pub from: Signer<'info>,

    #[account(mut)]

    pub from_ata: Account<'info, TokenAccount>,

    #[account(mut)]

    pub to_ata: Account<'info, TokenAccount>,

    pub token_program: Program<'info, Token>,

}

The struct would need the ‘from’ wallet, the token program, and ATA of the ‘from’ wallet and the ‘to’ wallet. You would not require the primary account of the destination wallet, as it would remain unchanged. You can add the following function in the ‘transfer_lamports’ instruction.

    pub fn transfer_spl_tokens(ctx: Context<TransferSpl>, amount: u64) -> Result<()> {

        let destination = &ctx.accounts.to_ata;

        let source = &ctx.accounts.from_ata;

        let token_program = &ctx.accounts.token_program;

        let authority = &ctx.accounts.from;


        // Transfer tokens from taker to initializer

        let cpi_accounts = SplTransfer {

            from: source.to_account_info().clone(),

            to: destination.to_account_info().clone(),

            authority: authority.to_account_info().clone(),

        };

        let cpi_program = token_program.to_account_info();


        token::transfer(

            CpiContext::new(cpi_program, cpi_accounts),

            amount)?;

        Ok(())

    }

Here is a breakdown of the important components of the function.

‘transfer_spl_tokens’ function receives an ‘amount’ and ‘Context’ as the arguments. The ‘TransferSpl’ context includes the account information required for the transaction for transferring SOL tokens.

The Anchor SPL token transfer function also includes creating references to the ‘authority,’ ‘destination,’ ‘token_program,’ and ‘source’ from the context. The variables serve as representatives of the signer’s wallet, destination ATA, token program, and source ATA, respectively.

You should also notice the ‘SplTransfer’ struct that includes account information of ‘authority,’ ‘source,’ and ‘destination.’ The struct would provide account information when you make a cross-program invocation to the Anchor SPL token program.

It is also important to note the use of a new ‘CpiContext’ for calling the ‘token::transfer’ function. The ‘CpiContext’ uses the ‘cpi_program,’ ‘amount,’ and ‘cpi_accounts’ in the function that performs the actual transfer of tokens between specified ATAs.

Finally, you can return an ‘Ok(())’ to indicate successful execution. Subsequently, you can build the program again and check whether it works properly by clicking on ‘Build’ option or entering the command ‘anchor build’ in the terminal.

Start learning Blockchain with World’s first Blockchain Career Paths with quality resources tailored by industry experts now!

Conclusion

The review of the steps to transfer SOL and SPL tokens using Anchor shows that the process is straightforward. Interestingly, you have many references in Anchor documentation and guides on Anchor programming in Solana. Anchor is a trusted framework for faster development of secure Solana programs.

However, SOL token transfer is essential for validating transactions on Solana blockchain. Similarly, SPL tokens are crucial requirements for NFT development and transfer on Solana blockchain. Learn more about Anchor and its important components to understand the best practices for using it in Solana development right now.

Unlock your career with 101 Blockchains' Learning Programs

*Disclaimer: The article should not be taken as, and is not intended to provide any investment advice. Claims made in this article do not constitute investment advice and should not be taken as such. 101 Blockchains shall not be responsible for any loss sustained by any person who relies on this article. Do your own research!

The post How to Transfer SOL and SPL Tokens Using Anchor? appeared first on 101 Blockchains.

Read the original article on 101blockchains.com