How to send SPL token in Swift

Issue #867

Using https://github.com/ajamaica/Solana.Swift and the sendSPLToken method. Note that the from is the token account address and amount can have decimals

solana.action.sendSPLTokens(
    mintAddress: MINT_ADDRESS,
    from: SENDER_TOKEN_ACCOUNT_ADDRESS,
    to: RECEIVER_WALLET_ADDDRESS,
    amount: UInt64(Float(amount) * units),
    allowUnfundedRecipient: true,
    onComplete: { result in
        continuation.resume(with: result)
    }
)

We can also cross-reference to the solana web3.js library for how to create mint and transfer token

import { clusterApiUrl, Connection, Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';
import { createMint, getOrCreateAssociatedTokenAccount, mintTo, transfer } from '../src'; // @FIXME: replace with @solana/spl-token

(async () => {
    // Connect to cluster
    const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');

    // Generate a new wallet keypair and airdrop SOL
    const fromWallet = Keypair.generate();
    const fromAirdropSignature = await connection.requestAirdrop(fromWallet.publicKey, LAMPORTS_PER_SOL);

    // Wait for airdrop confirmation
    await connection.confirmTransaction(fromAirdropSignature);

    // Generate a new wallet to receive newly minted token
    const toWallet = Keypair.generate();

    // Create new token mint
    const mint = await createMint(connection, fromWallet, fromWallet.publicKey, null, 9);

    // Get the token account of the fromWallet address, and if it does not exist, create it
    const fromTokenAccount = await getOrCreateAssociatedTokenAccount(
        connection,
        fromWallet,
        mint,
        fromWallet.publicKey
    );

    // Get the token account of the toWallet address, and if it does not exist, create it
    const toTokenAccount = await getOrCreateAssociatedTokenAccount(connection, fromWallet, mint, toWallet.publicKey);

    // Mint 1 new token to the "fromTokenAccount" account we just created
    let signature = await mintTo(
        connection,
        fromWallet,
        mint,
        fromTokenAccount.address,
        fromWallet.publicKey,
        [],
        1000000000
    );
    console.log('mint tx:', signature);

    // Transfer the new token to the "toTokenAccount" we just created
    signature = await transfer(
        connection,
        fromWallet,
        fromTokenAccount.address,
        toTokenAccount.address,
        fromWallet.publicKey,
        [],
        1000000000
    );
    console.log('transfer tx:', signature);
})();

Troubleshoot

If you get the below error

Transaction simulation failed: Attempt to debit an account but found no record of a prior credit Make sure you’re testing in the correct cluster and that the sender has some SOL

Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation