Các Thao Tác SPL Token

Yêu cầu cargo add --dev litesvm-token spl-token

Bài Kiểm Thử Hoàn Chỉnh

tests/spl_token_test.rs
use litesvm::LiteSVM;
use litesvm_token::{
get_spl_account,
spl_token::{native_mint::DECIMALS, state::Account as TokenAccount},
CreateAssociatedTokenAccount, CreateMint, MintTo, Transfer,
};
use solana_sdk::{
native_token::LAMPORTS_PER_SOL,
signature::{Keypair, Signer},
};
#[test]
fn test_token_transfer() {
let mut svm = LiteSVM::new();
// Create payer account and fund it
let payer = Keypair::new();
svm.airdrop(&payer.pubkey(), 10 * LAMPORTS_PER_SOL).unwrap();
// Create two users
let alice = Keypair::new();
let bob = Keypair::new();
// Create a new SPL token mint with alice as the mint authority
let mint = CreateMint::new(&mut svm, &payer)
.authority(&alice.pubkey())
.decimals(DECIMALS)
.send()
.unwrap();
// Create associated token accounts (ATAs) for alice and bob
let alice_token_account = CreateAssociatedTokenAccount::new(&mut svm, &payer, &mint)
.owner(&alice.pubkey())
.send()
.unwrap();
let bob_token_account = CreateAssociatedTokenAccount::new(&mut svm, &payer, &mint)
.owner(&bob.pubkey())
.send()
.unwrap();
// Mint 1000 tokens to Alice's account
MintTo::new(&mut svm, &payer, &mint, &alice_token_account, 1000)
.owner(&alice)
.send()
.unwrap();
// Transfer 400 tokens from Alice to Bob
Transfer::new(&mut svm, &payer, &mint, &bob_token_account, 400)
.source(&alice_token_account)
.owner(&alice)
.send()
.unwrap();
// Verify balances
let alice_account: TokenAccount = get_spl_account(&svm, &alice_token_account).unwrap();
let bob_account: TokenAccount = get_spl_account(&svm, &bob_token_account).unwrap();
let alice_balance = alice_account.amount;
let bob_balance = bob_account.amount;
assert_eq!(alice_balance, 600);
assert_eq!(bob_balance, 400);
println!("SPL token transfer successful!");
}

Những Điểm Chính

  1. litesvm-token: Crate hỗ trợ giúp đơn giản hóa việc kiểm thử SPL token
  2. Tạo Mint: Tạo một mint với số thập phân và các quyền hạn được chỉ định
  3. Token Accounts: Tạo token account để lưu trữ token cho người dùng
    • Để hiểu sự khác biệt giữa cái này và ATA, hãy đọc phần này.
  4. Đúc Token: Đúc token vào token account bằng cách sử dụng quyền hạn mint
  5. Số Thập Phân: Hãy nhớ tính đến số thập phân khi chỉ định số lượng

Xem Thêm

Is this page helpful?

Mục lục

Chỉnh sửa trang