O que faz a transferência de tokens?
A transferência de tokens move tokens de uma token account para outra token account do mesmo mint. As transferências não alteram o fornecimento do mint. Elas apenas atualizam os saldos entre token accounts.Como transferir tokens
A transferência de tokens usa a instruçãoTransfer ou
TransferChecked do Token Program.
Os exemplos abaixo usam TransferChecked, que exige que o chamador
forneça o mint e as casas decimais para que a instrução possa verificar o mint esperado
e a precisão do token antes de mover tokens entre contas.
No Token Extension Program, Transfer está obsoleta em favor de
TransferChecked ou TransferCheckedWithFee.
O proprietário da conta de origem ou um delegado aprovado assina a transferência. No
Token Extension Program, um delegado permanente do mint também pode autorizar a
transferência se o mint tiver a extensão de delegado permanente ativada.
Referência do código-fonte
| Item | Descrição | Token Program | Token Extension Program |
|---|---|---|---|
Account | O estado da token account armazena os saldos atualizados por uma transferência. | Código-fonte | Código-fonte |
Transfer | Uma instrução de transferência que move tokens entre token accounts sem exigir que o chamador forneça o mint ou as casas decimais. No Token Extension Program, use TransferChecked. | Código-fonte | Código-fonte |
TransferChecked | Uma instrução de transferência que exige que o chamador forneça o mint e as casas decimais e verifica esses valores antes de mover tokens entre token accounts do mesmo mint. | Código-fonte | Código-fonte |
process_transfer | Lógica de processamento compartilhada para transferências de tokens. | Código-fonte | Código-fonte |
Kit
Estes exemplos usam@solana/kit.
import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { solanaRpc, rpcAirdrop } from "@solana/kit-plugin-rpc";
import { generatedPayer, airdropPayer } from "@solana/kit-plugin-signer";
import {
findAssociatedTokenPda,
tokenProgram,
TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";
const client = await createClient()
.use(generatedPayer())
.use(
solanaRpc({
rpcUrl: "http://localhost:8899",
rpcSubscriptionsUrl: "ws://localhost:8900"
})
)
.use(rpcAirdrop())
.use(airdropPayer(lamports(1_000_000_000n)))
.use(tokenProgram());
const mint = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
// Setup: create a mint and fund the payer's ATA before transferring tokens.
await client.sendTransaction([
await client.token.instructions.createMint({
newMint: mint,
decimals: 2,
mintAuthority: client.payer.address,
freezeAuthority: client.payer.address
}),
await client.token.instructions.mintToATA({
mint: mint.address,
owner: client.payer.address,
mintAuthority: client.payer,
amount: 100n,
decimals: 2
})
]);
const result = await client.token.instructions
.transferToATA({
mint: mint.address, // Mint for the token being transferred.
authority: client.payer, // Owner or delegate approving the transfer.
recipient: recipient.address, // Account that owns the destination token account.
amount: 25n, // Token amount in base units.
decimals: 2 // Decimals defined on the mint account.
})
.sendTransaction();
const [sourceTokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: client.payer.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [destinationTokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: recipient.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [sourceTokenAccountData, destinationTokenAccountData] =
await client.token.accounts.token.fetchAll([
sourceTokenAccount,
destinationTokenAccount
]);
console.log("Mint Address:", mint.address);
console.log("\nSource Token Account Address:", sourceTokenAccount);
console.log("Source Token Account:", sourceTokenAccountData.data);
console.log("\nDestination Token Account Address:", destinationTokenAccount);
console.log("Destination Token Account:", destinationTokenAccountData.data);
console.log("\nTransaction Signature:", result.context.signature);
import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { solanaRpc, rpcAirdrop } from "@solana/kit-plugin-rpc";
import { generatedPayer, airdropPayer } from "@solana/kit-plugin-signer";
import {
fetchAllToken,
findAssociatedTokenPda,
getCreateMintInstructionPlan,
getMintToATAInstructionPlanAsync,
getTransferToATAInstructionPlanAsync,
TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";
const client = await createClient()
.use(generatedPayer())
.use(
solanaRpc({
rpcUrl: "http://localhost:8899",
rpcSubscriptionsUrl: "ws://localhost:8900"
})
)
.use(rpcAirdrop())
.use(airdropPayer(lamports(1_000_000_000n)));
const mint = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
// Setup: create a mint and fund the payer's ATA before transferring tokens.
await client.sendTransaction([
await getCreateMintInstructionPlan(client, {
payer: client.payer,
newMint: mint,
decimals: 2,
mintAuthority: client.payer.address,
freezeAuthority: client.payer.address
}),
await getMintToATAInstructionPlanAsync({
payer: client.payer,
mint: mint.address,
owner: client.payer.address,
mintAuthority: client.payer,
amount: 100n,
decimals: 2
})
]);
const result = await client.sendTransaction(
await getTransferToATAInstructionPlanAsync({
payer: client.payer, // Account funding account creation.
mint: mint.address, // Mint for the token being transferred.
authority: client.payer, // Owner or delegate approving the transfer.
recipient: recipient.address, // Account that owns the destination token account.
amount: 25n, // Token amount in base units.
decimals: 2 // Decimals defined on the mint account.
})
);
const [sourceTokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: client.payer.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [destinationTokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: recipient.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [sourceTokenAccountData, destinationTokenAccountData] =
await fetchAllToken(client.rpc, [
sourceTokenAccount,
destinationTokenAccount
]);
console.log("Mint Address:", mint.address);
console.log("\nSource Token Account Address:", sourceTokenAccount);
console.log("Source Token Account:", sourceTokenAccountData.data);
console.log("\nDestination Token Account Address:", destinationTokenAccount);
console.log("Destination Token Account:", destinationTokenAccountData.data);
console.log("\nTransaction Signature:", result.context.signature);
import { createClient, generateKeyPairSigner, lamports } from "@solana/kit";
import { solanaRpc, rpcAirdrop } from "@solana/kit-plugin-rpc";
import { generatedPayer, airdropPayer } from "@solana/kit-plugin-signer";
import {
fetchAllToken,
findAssociatedTokenPda,
getCreateAssociatedTokenInstructionAsync,
getCreateMintInstructionPlan,
getMintToATAInstructionPlanAsync,
getTransferCheckedInstruction,
TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";
const client = await createClient()
.use(generatedPayer())
.use(
solanaRpc({
rpcUrl: "http://localhost:8899",
rpcSubscriptionsUrl: "ws://localhost:8900"
})
)
.use(rpcAirdrop())
.use(airdropPayer(lamports(1_000_000_000n)));
const mint = await generateKeyPairSigner();
const recipient = await generateKeyPairSigner();
const [sourceTokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: client.payer.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [destinationTokenAccount] = await findAssociatedTokenPda({
mint: mint.address,
owner: recipient.address,
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
// Setup: create a mint, fund the payer's ATA, and create the recipient's ATA.
await client.sendTransaction([
await getCreateMintInstructionPlan(client, {
payer: client.payer,
newMint: mint,
decimals: 2,
mintAuthority: client.payer.address,
freezeAuthority: client.payer.address
}),
await getMintToATAInstructionPlanAsync({
payer: client.payer,
mint: mint.address,
owner: client.payer.address,
mintAuthority: client.payer,
amount: 100n,
decimals: 2
}),
await getCreateAssociatedTokenInstructionAsync({
payer: client.payer,
mint: mint.address,
owner: recipient.address
})
]);
const result = await client.sendTransaction([
getTransferCheckedInstruction({
source: sourceTokenAccount, // Token account sending the tokens.
mint: mint.address, // Mint for the token being transferred.
destination: destinationTokenAccount, // Token account receiving the tokens.
authority: client.payer, // Owner or delegate approving the transfer.
amount: 25n, // Token amount in base units.
decimals: 2 // Decimals defined on the mint account.
})
]);
const [sourceTokenAccountData, destinationTokenAccountData] =
await fetchAllToken(client.rpc, [
sourceTokenAccount,
destinationTokenAccount
]);
console.log("Mint Address:", mint.address);
console.log("\nSource Token Account Address:", sourceTokenAccount);
console.log("Source Token Account:", sourceTokenAccountData.data);
console.log("\nDestination Token Account Address:", destinationTokenAccount);
console.log("Destination Token Account:", destinationTokenAccountData.data);
console.log("\nTransaction Signature:", result.context.signature);
Web3.js v3
Estes exemplos usam a API v3 baseada em classes do@solana/web3.js com
construtores de instruções @solana-program.
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
Transaction,
LAMPORTS_PER_SOL
} from "@solana/web3.js";
import {
findAssociatedTokenPda,
getCreateMintInstructionPlan,
getMintToATAInstructionPlanAsync,
getTokenDecoder,
getTransferToATAInstructionPlanAsync,
TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";
// Setup: create a mint and fund the payer's ATA before transferring tokens.
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = await Keypair.generate();
const recipient = await Keypair.generate();
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature
});
const mint = await Keypair.generate();
await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
}).add(
await getCreateMintInstructionPlan(
{
getMinimumBalance: (space: number) =>
connection.getMinimumBalanceForRentExemption(space)
},
{
payer: feePayer,
newMint: mint,
decimals: 2,
mintAuthority: feePayer.publicKey.toBase58(),
freezeAuthority: feePayer.publicKey.toBase58()
}
),
await getMintToATAInstructionPlanAsync({
payer: feePayer,
owner: feePayer.publicKey.toBase58(),
mint: mint.publicKey.toBase58(),
mintAuthority: feePayer,
amount: 100,
decimals: 2
})
),
[feePayer, mint]
);
const transferBlockhash = await connection.getLatestBlockhash();
const result = await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: transferBlockhash.blockhash,
lastValidBlockHeight: transferBlockhash.lastValidBlockHeight
}).add(
await getTransferToATAInstructionPlanAsync({
payer: feePayer, // Account paying transaction fees and account creation.
mint: mint.publicKey.toBase58(), // Mint for the token being transferred.
authority: feePayer, // Owner or delegate approving the transfer.
recipient: recipient.publicKey.toBase58(), // Wallet receiving the tokens.
amount: 25, // Token amount in base units.
decimals: 2 // Decimals defined on the mint account.
})
),
[feePayer]
);
const [feePayerATA] = await findAssociatedTokenPda({
mint: mint.publicKey.toBase58(),
owner: feePayer.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [recipientATA] = await findAssociatedTokenPda({
mint: mint.publicKey.toBase58(),
owner: recipient.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const senderAccountInfo = await connection.getAccountInfo(
new PublicKey(feePayerATA)
);
const senderTokenAccount = getTokenDecoder().decode(senderAccountInfo!.data);
const recipientAccountInfo = await connection.getAccountInfo(
new PublicKey(recipientATA)
);
const recipientTokenAccount = getTokenDecoder().decode(
recipientAccountInfo!.data
);
console.log("Mint Address:", mint.publicKey.toBase58());
console.log("\nSource Token Account Address:", feePayerATA);
console.log("Source Token Account:", senderTokenAccount);
console.log("\nDestination Token Account Address:", recipientATA);
console.log("Destination Token Account:", recipientTokenAccount);
console.log("\nTransaction Signature:", result);
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
LAMPORTS_PER_SOL
} from "@solana/web3.js";
import {
findAssociatedTokenPda,
getCreateAssociatedTokenIdempotentInstruction,
getInitializeMint2Instruction,
getMintSize,
getMintToCheckedInstruction,
getTokenDecoder,
getTransferCheckedInstruction,
TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";
// Setup: create a mint, fund the payer's ATA, and create the recipient's ATA.
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = await Keypair.generate();
const recipient = await Keypair.generate();
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature
});
const mint = await Keypair.generate();
const space = getMintSize();
const mintRent = await connection.getMinimumBalanceForRentExemption(space);
const [feePayerATA] = await findAssociatedTokenPda({
mint: mint.publicKey.toBase58(),
owner: feePayer.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [recipientATA] = await findAssociatedTokenPda({
mint: mint.publicKey.toBase58(),
owner: recipient.publicKey.toBase58(),
tokenProgram: TOKEN_PROGRAM_ADDRESS
});
await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
}).add(
SystemProgram.createAccount({
fromPubkey: feePayer.publicKey,
newAccountPubkey: mint.publicKey,
space,
lamports: mintRent,
programId: new PublicKey(TOKEN_PROGRAM_ADDRESS)
}),
getInitializeMint2Instruction({
mint: mint.publicKey,
decimals: 2,
mintAuthority: feePayer.publicKey.toBase58(),
freezeAuthority: feePayer.publicKey.toBase58()
}),
getCreateAssociatedTokenIdempotentInstruction({
payer: feePayer,
ata: feePayerATA,
owner: feePayer.publicKey,
mint: mint.publicKey
}),
getCreateAssociatedTokenIdempotentInstruction({
payer: feePayer,
ata: recipientATA,
owner: recipient.publicKey,
mint: mint.publicKey
}),
getMintToCheckedInstruction({
mint: mint.publicKey,
token: feePayerATA,
mintAuthority: feePayer,
amount: 100,
decimals: 2
})
),
[feePayer, mint]
);
const transferBlockhash = await connection.getLatestBlockhash();
const result = await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: transferBlockhash.blockhash,
lastValidBlockHeight: transferBlockhash.lastValidBlockHeight
}).add(
getTransferCheckedInstruction({
source: feePayerATA, // Token account sending the tokens.
mint: mint.publicKey, // Mint for the token being transferred.
destination: recipientATA, // Token account receiving the tokens.
authority: feePayer, // Owner or delegate approving the transfer.
amount: 25, // Token amount in base units.
decimals: 2 // Decimals defined on the mint account.
})
),
[feePayer]
);
const senderAccountInfo = await connection.getAccountInfo(
new PublicKey(feePayerATA)
);
const senderTokenAccount = getTokenDecoder().decode(senderAccountInfo!.data);
const recipientAccountInfo = await connection.getAccountInfo(
new PublicKey(recipientATA)
);
const recipientTokenAccount = getTokenDecoder().decode(
recipientAccountInfo!.data
);
console.log("Mint Address:", mint.publicKey.toBase58());
console.log("\nSource Token Account Address:", feePayerATA);
console.log("Source Token Account:", senderTokenAccount);
console.log("\nDestination Token Account Address:", recipientATA);
console.log("Destination Token Account:", recipientTokenAccount);
console.log("\nTransaction Signature:", result);
Rust
Adicione estas dependências aoCargo.toml (testado com Rust 1.89 e 1.98):
Cargo.toml
[dependencies]
anyhow = "1"
tokio = { version = "1", features = ["full"] }
solana-client = "2"
solana-commitment-config = "2"
solana-sdk = "2"
solana-system-interface = "1"
spl-token-interface = "1"
spl-associated-token-account-interface = "1"
Rust
use anyhow::Result;
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
program_pack::Pack,
signature::{Keypair, Signer},
transaction::Transaction,
};
use solana_system_interface::instruction::create_account;
use spl_associated_token_account_interface::{
address::get_associated_token_address, instruction::create_associated_token_account,
};
use spl_token_interface::{
id as token_program_id,
instruction::{initialize_mint, mint_to_checked, transfer_checked},
state::{Account, Mint},
};
#[tokio::main]
async fn main() -> Result<()> {
let client = RpcClient::new_with_commitment(
String::from("http://localhost:8899"),
CommitmentConfig::confirmed(),
);
let recipient = Keypair::new();
// Setup: create a mint, fund the payer's ATA, and create the recipient's ATA.
let fee_payer = Keypair::new();
let decimals = 2;
let airdrop_signature = client
.request_airdrop(&fee_payer.pubkey(), 1_000_000_000)
.await?;
loop {
let confirmed = client.confirm_transaction(&airdrop_signature).await?;
if confirmed {
break;
}
}
let mint = Keypair::new();
let mint_rent = client
.get_minimum_balance_for_rent_exemption(Mint::LEN)
.await?;
let source_token_address = get_associated_token_address(
&fee_payer.pubkey(),
&mint.pubkey(),
);
let destination_token_address = get_associated_token_address(
&recipient.pubkey(),
&mint.pubkey(),
);
let latest_blockhash = client.get_latest_blockhash().await?;
let setup_transaction = Transaction::new_signed_with_payer(
&[
create_account(
&fee_payer.pubkey(),
&mint.pubkey(),
mint_rent,
Mint::LEN as u64,
&token_program_id(),
),
initialize_mint(
&token_program_id(),
&mint.pubkey(),
&fee_payer.pubkey(),
Some(&fee_payer.pubkey()),
decimals,
)?,
create_associated_token_account(
&fee_payer.pubkey(),
&fee_payer.pubkey(),
&mint.pubkey(),
&token_program_id(),
),
create_associated_token_account(
&fee_payer.pubkey(),
&recipient.pubkey(),
&mint.pubkey(),
&token_program_id(),
),
mint_to_checked(
&token_program_id(),
&mint.pubkey(),
&source_token_address,
&fee_payer.pubkey(),
&[],
100,
decimals,
)?,
],
Some(&fee_payer.pubkey()),
&[&fee_payer, &mint],
latest_blockhash,
);
client
.send_and_confirm_transaction(&setup_transaction)
.await?;
let transfer_amount = 25;
let transaction = Transaction::new_signed_with_payer(
&[
transfer_checked(
&token_program_id(), // Token program to invoke.
&source_token_address, // Token account sending the tokens.
&mint.pubkey(), // Mint for the token being transferred.
&destination_token_address, // Token account receiving the tokens.
&fee_payer.pubkey(), // Owner or delegate approving the transfer.
&[], // Additional multisig signers.
transfer_amount, // Token amount in base units.
decimals, // Decimals defined on the mint account.
)?,
],
Some(&fee_payer.pubkey()),
&[&fee_payer],
latest_blockhash,
);
let transaction_signature = client.send_and_confirm_transaction(&transaction).await?;
let source_token_account = client.get_account(&source_token_address).await?;
let source_token_data = Account::unpack(&source_token_account.data)?;
let destination_token_account = client.get_account(&destination_token_address).await?;
let destination_token_data = Account::unpack(&destination_token_account.data)?;
println!("Mint Address: {}", mint.pubkey());
println!("\nSource Token Account Address: {}", source_token_address);
println!("Source Token Account: {:#?}", source_token_data);
println!(
"\nDestination Token Account Address: {}",
destination_token_address
);
println!("Destination Token Account: {:#?}", destination_token_data);
println!("\nTransaction Signature: {}", transaction_signature);
Ok(())
}
Python
Este exemplo usasolana (solana-py) 0.41 e solders:
Terminal
pip install solana==0.41.0 solders==0.29.0
Python
#!/usr/bin/env python3
import asyncio
import json
from solana.rpc.async_api import AsyncClient
from solders.keypair import Keypair
from solders.message import Message
from solders.system_program import create_account, CreateAccountParams
from solders.transaction import Transaction
from solders.token.state import TokenAccount, TokenAccountState
from spl.token.instructions import (
create_associated_token_account,
get_associated_token_address,
initialize_mint,
mint_to_checked,
transfer_checked,
)
from spl.token.models import (
InitializeMintParams,
MintToCheckedParams,
TransferCheckedParams,
)
from spl.token.constants import MINT_LEN, TOKEN_PROGRAM_ID
DECIMALS = 2
AMOUNT_TO_MINT = 100
AMOUNT_TO_TRANSFER = 25
def token_account_to_dict(account: TokenAccount) -> dict:
return {
"mint": str(account.mint),
"owner": str(account.owner),
"amount": account.amount,
"delegate": None if account.delegate is None else str(account.delegate),
"delegated_amount": account.delegated_amount,
"is_initialized": account.state != TokenAccountState.Uninitialized,
"is_frozen": account.state == TokenAccountState.Frozen,
"is_native": account.is_native,
"close_authority": None if account.close_authority is None else str(account.close_authority),
}
async def main():
rpc = AsyncClient("http://localhost:8899")
receiver = Keypair()
async with rpc:
# Setup: create a mint, source token account, destination token account, and source token balance.
fee_payer = Keypair()
airdrop_signature = (await rpc.request_airdrop(fee_payer.pubkey(), 1_000_000_000)).value
await rpc.confirm_transaction(airdrop_signature)
mint = Keypair()
source_token_account = get_associated_token_address(fee_payer.pubkey(), mint.pubkey())
destination_token_account = get_associated_token_address(receiver.pubkey(), mint.pubkey())
mint_rent = (await rpc.get_minimum_balance_for_rent_exemption(MINT_LEN)).value
setup_instructions = [
create_account(CreateAccountParams(from_pubkey=fee_payer.pubkey(), to_pubkey=mint.pubkey(), lamports=mint_rent, space=MINT_LEN, owner=TOKEN_PROGRAM_ID)),
initialize_mint(InitializeMintParams(decimals=DECIMALS, program_id=TOKEN_PROGRAM_ID, mint=mint.pubkey(), mint_authority=fee_payer.pubkey())),
create_associated_token_account(fee_payer.pubkey(), fee_payer.pubkey(), mint.pubkey(), TOKEN_PROGRAM_ID),
create_associated_token_account(fee_payer.pubkey(), receiver.pubkey(), mint.pubkey(), TOKEN_PROGRAM_ID),
mint_to_checked(MintToCheckedParams(program_id=TOKEN_PROGRAM_ID, mint=mint.pubkey(), dest=source_token_account, mint_authority=fee_payer.pubkey(), amount=AMOUNT_TO_MINT, decimals=DECIMALS)),
]
setup_blockhash = await rpc.get_latest_blockhash()
setup_transaction = Transaction(
[fee_payer, mint],
Message(setup_instructions, fee_payer.pubkey()),
setup_blockhash.value.blockhash,
)
await rpc.send_transaction(setup_transaction)
transfer_tokens_instruction = transfer_checked(
TransferCheckedParams(
program_id=TOKEN_PROGRAM_ID, # Token program to invoke.
source=source_token_account, # Token account sending the tokens.
mint=mint.pubkey(), # Mint for the token being transferred.
dest=destination_token_account, # Token account receiving the tokens.
owner=fee_payer.pubkey(), # Account that owns the source token account.
amount=AMOUNT_TO_TRANSFER, # Token amount in base units.
decimals=DECIMALS, # Decimals defined on the mint account.
)
)
latest_blockhash = await rpc.get_latest_blockhash()
transaction = Transaction(
[fee_payer],
Message([transfer_tokens_instruction], fee_payer.pubkey()),
latest_blockhash.value.blockhash,
)
result = await rpc.send_transaction(transaction)
source_token_account_info = TokenAccount.from_bytes((await rpc.get_account_info(source_token_account)).value.data)
destination_token_account_info = TokenAccount.from_bytes((await rpc.get_account_info(destination_token_account)).value.data)
source_account = token_account_to_dict(source_token_account_info)
destination_account = token_account_to_dict(destination_token_account_info)
print("Mint Address:", mint.pubkey())
print("\nSource Token Account Address:", source_token_account)
print("Source Token Account:")
print(json.dumps(source_account, indent=2))
print("\nDestination Token Account Address:", destination_token_account)
print("Destination Token Account:")
print(json.dumps(destination_account, indent=2))
print("\nTransaction Signature:", result.value)
if __name__ == "__main__":
asyncio.run(main())
Web3.js (legado)
Estes exemplos usam o@solana/web3.js 1.x legado com @solana/spl-token.
@solana/web3.js 1.x is no longer actively maintainedIt receives critical fixes only. Use Kit for new code. To migrate existing code, follow the Kit upgrade guide, or the web3.js v3 migration guide to keep the class-based API.To run this code, install 1.x with npm install @solana/web3.js@1. A plain npm install @solana/web3.js installs v3, which this code doesn’t run on.import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js";
import {
createAssociatedTokenAccount,
createMint,
getAccount,
mintToChecked,
TOKEN_PROGRAM_ID,
transferChecked
} from "@solana/spl-token";
// Setup: create a mint, fund the payer's ATA, and create the recipient's ATA.
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = Keypair.generate();
const recipient = Keypair.generate();
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature
});
const mintPubkey = await createMint(
connection,
feePayer,
feePayer.publicKey,
feePayer.publicKey,
2,
Keypair.generate(),
{
commitment: "confirmed"
},
TOKEN_PROGRAM_ID
);
const feePayerATA = await createAssociatedTokenAccount(
connection,
feePayer,
mintPubkey,
feePayer.publicKey,
{
commitment: "confirmed"
},
TOKEN_PROGRAM_ID
);
const recipientATA = await createAssociatedTokenAccount(
connection,
feePayer,
mintPubkey,
recipient.publicKey,
{
commitment: "confirmed"
},
TOKEN_PROGRAM_ID
);
await mintToChecked(
connection,
feePayer,
mintPubkey,
feePayerATA,
feePayer,
100,
2,
[],
{
commitment: "confirmed"
},
TOKEN_PROGRAM_ID
);
const result = await transferChecked(
connection, // Connection to the local validator.
feePayer, // Account paying transaction fees.
feePayerATA, // Token account sending the tokens.
mintPubkey, // Mint for the token being transferred.
recipientATA, // Token account receiving the tokens.
feePayer, // Owner or delegate approving the transfer.
25, // Token amount in base units.
2, // Decimals defined on the mint account.
[], // Additional multisig signers.
{
commitment: "confirmed" // Confirmation options for the transaction.
},
TOKEN_PROGRAM_ID // Token program to invoke.
);
const senderTokenAccount = await getAccount(
connection,
feePayerATA,
"confirmed",
TOKEN_PROGRAM_ID
);
const recipientTokenAccount = await getAccount(
connection,
recipientATA,
"confirmed",
TOKEN_PROGRAM_ID
);
console.log("Mint Address:", mintPubkey.toBase58());
console.log("\nSource Token Account Address:", feePayerATA.toBase58());
console.log("Source Token Account:", senderTokenAccount);
console.log("\nDestination Token Account Address:", recipientATA.toBase58());
console.log("Destination Token Account:", recipientTokenAccount);
console.log("\nTransaction Signature:", result);
import {
Connection,
Keypair,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
LAMPORTS_PER_SOL
} from "@solana/web3.js";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
createAssociatedTokenAccountInstruction,
createInitializeMintInstruction,
createMintToCheckedInstruction,
createTransferCheckedInstruction,
getAccount,
getAssociatedTokenAddressSync,
getMinimumBalanceForRentExemptMint,
MINT_SIZE,
TOKEN_PROGRAM_ID
} from "@solana/spl-token";
// Setup: create a mint, fund the payer's ATA, and create the recipient's ATA.
const connection = new Connection("http://localhost:8899", "confirmed");
const latestBlockhash = await connection.getLatestBlockhash();
const feePayer = Keypair.generate();
const recipient = Keypair.generate();
const airdropSignature = await connection.requestAirdrop(
feePayer.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction({
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
signature: airdropSignature
});
const mint = Keypair.generate();
const mintRent = await getMinimumBalanceForRentExemptMint(connection);
const feePayerATA = getAssociatedTokenAddressSync(
mint.publicKey,
feePayer.publicKey,
false, // allowOwnerOffCurve
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID
);
const recipientATA = getAssociatedTokenAddressSync(
mint.publicKey,
recipient.publicKey,
false, // allowOwnerOffCurve
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID
);
await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: latestBlockhash.blockhash,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight
}).add(
SystemProgram.createAccount({
fromPubkey: feePayer.publicKey,
newAccountPubkey: mint.publicKey,
space: MINT_SIZE,
lamports: mintRent,
programId: TOKEN_PROGRAM_ID
}),
createInitializeMintInstruction(
mint.publicKey,
2,
feePayer.publicKey,
feePayer.publicKey,
TOKEN_PROGRAM_ID
),
createAssociatedTokenAccountInstruction(
feePayer.publicKey,
feePayerATA,
feePayer.publicKey,
mint.publicKey,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID
),
createAssociatedTokenAccountInstruction(
feePayer.publicKey,
recipientATA,
recipient.publicKey,
mint.publicKey,
TOKEN_PROGRAM_ID,
ASSOCIATED_TOKEN_PROGRAM_ID
),
createMintToCheckedInstruction(
mint.publicKey,
feePayerATA,
feePayer.publicKey,
100,
2,
[],
TOKEN_PROGRAM_ID
)
),
[feePayer, mint]
);
const transferBlockhash = await connection.getLatestBlockhash();
const result = await sendAndConfirmTransaction(
connection,
new Transaction({
feePayer: feePayer.publicKey,
blockhash: transferBlockhash.blockhash,
lastValidBlockHeight: transferBlockhash.lastValidBlockHeight
}).add(
createTransferCheckedInstruction(
feePayerATA, // Token account sending the tokens.
mint.publicKey, // Mint for the token being transferred.
recipientATA, // Token account receiving the tokens.
feePayer.publicKey, // Owner or delegate approving the transfer.
25, // Token amount in base units.
2, // Decimals defined on the mint account.
[], // Additional multisig signers.
TOKEN_PROGRAM_ID // Token program to invoke.
)
),
[feePayer]
);
const senderTokenAccount = await getAccount(
connection,
feePayerATA,
"confirmed",
TOKEN_PROGRAM_ID
);
const recipientTokenAccount = await getAccount(
connection,
recipientATA,
"confirmed",
TOKEN_PROGRAM_ID
);
console.log("Mint Address:", mint.publicKey.toBase58());
console.log("\nSource Token Account Address:", feePayerATA.toBase58());
console.log("Source Token Account:", senderTokenAccount);
console.log("\nDestination Token Account Address:", recipientATA.toBase58());
console.log("Destination Token Account:", recipientTokenAccount);
console.log("\nTransaction Signature:", result);