uniQ
uniQ

Reputation: 125

Transfer SPL Token using Rust

Is there a way to transfer SPL tokens from on wallet to another. I have done some research and I found that I have to initialize account first using Create Associated Account and then use Token Transfer?

Is there any code examples where I can transfer tokens or a library which helps with creating account/token transfer. etc

Upvotes: 0

Views: 2574

Answers (2)

Jon C
Jon C

Reputation: 8452

You can directly use the spl-token crate for instructions and types used by the token program: https://docs.rs/spl-token/latest/spl_token/

If you need to create associated token accounts, you can use the spl-associated-token-account crate: https://docs.rs/spl-associated-token-account/latest/spl_associated_token_account/index.html

If you're on-chain, you can create a transfer instruction and pass it in along with the required accounts, ie:

        let ix = spl_token::instruction::transfer(
            token_program.key,
            source.key,
            destination.key,
            authority.key,
            &[],
            amount,
        )?;
        invoke(
            &ix,
            &[source, destination, authority, token_program],
        )

This was adapted from the token-swap transfer code: https://github.com/solana-labs/solana-program-library/blob/b2fad8a0781bddd90c8e9b768184f55306265cef/token-swap/program/src/processor.rs#L138

It's correct that you need to create the source and destination accounts first, and it's preferred for those to be associated token accounts. You can create them on-chain using:

let ix = spl_associated_token_account::instruction::create_associated_token_account(
    payer.key,
    wallet.key,
    token_mint.key,
    token_program.key,
);
invoke(
    &ix,
    &[payer, associated_token_account, wallet, token_mint, system_program, token_program, associated_token_account_program],
)

Note that all of these accounts must be sent to your program in order to perform the cross-program invocations.

Upvotes: 2

Anoushk
Anoushk

Reputation: 659

Afaik theres no library but token transfer only works from account to account, theres a transfer function inside anchor which you have to invoke and pass the to and from account infos, you can transfer directly to an address beacuse you wud need account info of receiver too which u can get from a publickey but it can be done through escrow, heres a program that i wrote which sends sol to a PDA and the receiver accepts it from PDA

Github link to escrow program

Upvotes: 0

Related Questions