Ghi vào mạng
Trong phần trước, bạn đã học cách đọc dữ liệu từ mạng Solana. Bây giờ bạn sẽ học cách ghi dữ liệu vào mạng. Việc ghi vào mạng Solana liên quan đến việc gửi các giao dịch chứa một hoặc nhiều hướng dẫn.
Các chương trình (hợp đồng thông minh) xác định logic nghiệp vụ cho mỗi hướng dẫn thực hiện. Khi bạn gửi một giao dịch, thời gian chạy Solana thực thi từng hướng dẫn theo trình tự và nguyên tử (nghĩa là hoặc tất cả các hướng dẫn thành công hoặc toàn bộ giao dịch thất bại).
Phần này bao gồm các ví dụ sau:
- Chuyển SOL giữa các tài khoản
- Tạo một token mới
Những ví dụ này cho thấy cách xây dựng và gửi giao dịch để gọi các chương trình Solana. Để biết thêm chi tiết, hãy tham khảo trang Giao dịch và Hướng dẫn và Phí trên Solana.
Chuyển SOL
Trong ví dụ này, bạn sẽ học cách chuyển SOL giữa hai tài khoản.
Trên Solana, mỗi tài khoản có một chương trình cụ thể làm chủ sở hữu. Chỉ chương trình chủ sở hữu mới có thể trừ số dư SOL (lamport) của tài khoản.
System Program là chủ sở hữu cho tất cả các tài khoản "ví". Để chuyển SOL, bạn phải gọi hướng dẫn transfer của System Program.
import {LAMPORTS_PER_SOL,SystemProgram,Transaction,sendAndConfirmTransaction,Keypair,Connection} from "@solana/web3.js";const connection = new Connection("http://localhost:8899", "confirmed");const sender = new Keypair();const receiver = new Keypair();const signature = await connection.requestAirdrop(sender.publicKey,LAMPORTS_PER_SOL);await connection.confirmTransaction(signature, "confirmed");const transferInstruction = SystemProgram.transfer({fromPubkey: sender.publicKey,toPubkey: receiver.publicKey,lamports: 0.01 * LAMPORTS_PER_SOL});const transaction = new Transaction().add(transferInstruction);const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[sender]);console.log("Transaction Signature:", `${transactionSignature}`);const senderBalance = await connection.getBalance(sender.publicKey);const receiverBalance = await connection.getBalance(receiver.publicKey);console.log("Sender Balance:", `${senderBalance}`);console.log("Receiver Balance:", `${receiverBalance}`);
Tạo một Connection
để xử lý việc gửi giao dịch và lấy dữ liệu tài khoản.
Trong ví dụ này, chúng ta đang kết nối đến validator thử nghiệm cục bộ chạy trên
localhost:8899
.
const connection = new Connection("http://localhost:8899", "confirmed");
Tạo các keypair mới để sử dụng làm tài khoản người gửi và người nhận.
Một Keypair
bao gồm:
- Một khóa công khai đóng vai trò là địa chỉ tài khoản
- Một khóa riêng tư được sử dụng để ký các giao dịch
const sender = new Keypair();const receiver = new Keypair();
Trước khi chúng ta có thể chuyển SOL, tài khoản người gửi cần có một số SOL trong số dư.
Trên các mạng khác ngoài mainnet, bạn có thể sử dụng phương thức
requestAirdrop
để nhận SOL cho việc thử nghiệm.
const signature = await connection.requestAirdrop(sender.publicKey,LAMPORTS_PER_SOL);await connection.confirmTransaction(signature, "confirmed");
Phương thức SystemProgram.transfer()
tạo một chỉ thị chuyển SOL từ tài khoản
fromPubkey
đến tài khoản toPubkey
theo số
lượng lamports
được chỉ định.
const transferInstruction = SystemProgram.transfer({fromPubkey: sender.publicKey,toPubkey: receiver.publicKey,lamports: 0.01 * LAMPORTS_PER_SOL});
Tạo một giao dịch và thêm chỉ thị vào giao dịch.
Trong ví dụ này, chúng ta đang tạo một giao dịch với một chỉ thị duy nhất. Tuy nhiên, bạn có thể thêm nhiều chỉ thị vào một giao dịch.
const transaction = new Transaction().add(transferInstruction);
Ký và gửi giao dịch đến mạng.
Cặp khóa người gửi được yêu cầu trong mảng người ký để ủy quyền chuyển SOL từ tài khoản của họ.
const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[sender]);
Chữ ký giao dịch là một định danh duy nhất có thể được sử dụng để tra cứu giao dịch trên Solana Explorer.
Tạo một Token
Trong ví dụ này, bạn sẽ học cách tạo một token mới trên Solana sử dụng Token Extensions Program. Điều này yêu cầu hai chỉ thị:
- Gọi System Program để tạo một tài khoản mới.
- Gọi Token Extensions Program để khởi tạo tài khoản đó như một Mint.
import {Connection,Keypair,SystemProgram,Transaction,sendAndConfirmTransaction,LAMPORTS_PER_SOL} from "@solana/web3.js";import {MINT_SIZE,TOKEN_2022_PROGRAM_ID,createInitializeMint2Instruction,getMinimumBalanceForRentExemptMint,getMint} from "@solana/spl-token";const connection = new Connection("http://localhost:8899", "confirmed");const wallet = new Keypair();// Fund the wallet with SOLconst signature = await connection.requestAirdrop(wallet.publicKey,LAMPORTS_PER_SOL);await connection.confirmTransaction(signature, "confirmed");// Generate keypair to use as address of mint accountconst mint = new Keypair();// Calculate lamports required for rent exemptionconst rentExemptionLamports =await getMinimumBalanceForRentExemptMint(connection);// Instruction to create new account with space for new mint accountconst createAccountInstruction = SystemProgram.createAccount({fromPubkey: wallet.publicKey,newAccountPubkey: mint.publicKey,space: MINT_SIZE,lamports: rentExemptionLamports,programId: TOKEN_2022_PROGRAM_ID});// Instruction to initialize mint accountconst initializeMintInstruction = createInitializeMint2Instruction(mint.publicKey,2, // decimalswallet.publicKey, // mint authoritywallet.publicKey, // freeze authorityTOKEN_2022_PROGRAM_ID);// Build transaction with instructions to create new account and initialize mint accountconst transaction = new Transaction().add(createAccountInstruction,initializeMintInstruction);const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[wallet, // payermint // mint address keypair]);console.log("Transaction Signature:", `${transactionSignature}`);const mintData = await getMint(connection,mint.publicKey,"confirmed",TOKEN_2022_PROGRAM_ID););
Việc tạo token trên Solana yêu cầu sử dụng cả thư viện @solana/web3.js
và
@solana/spl-token
.
- Tạo kết nối
- Tạo một keypair để thanh toán cho giao dịch
- Yêu cầu airdrop để nạp tiền vào keypair
const connection = new Connection("http://localhost:8899", "confirmed");const wallet = new Keypair();const signature = await connection.requestAirdrop(wallet.publicKey,LAMPORTS_PER_SOL);await connection.confirmTransaction(signature, "confirmed");
Tạo một keypair cho mint account.
Public key của keypair này sẽ được sử dụng làm địa chỉ cho mint account.
const mint = new Keypair();
Tính toán số lượng lamport tối thiểu cần thiết cho một mint account.
Hàm getMinimumBalanceForRentExemptMint
tính toán chính xác số lượng SOL (tính
bằng lamport) phải được cấp phát cho dữ liệu trên một mint account.
const rentExemptionLamports =await getMinimumBalanceForRentExemptMint(connection);
Lệnh đầu tiên gọi đến lệnh createAccount
của System Program để:
- Cấp phát số byte cần thiết để lưu trữ dữ liệu mint
- Chuyển lamport từ ví để cấp vốn cho tài khoản mới
- Gán quyền sở hữu của tài khoản cho Token Extensions
program (
TOKEN_2022_PROGRAM_ID
)
const createAccountInstruction = SystemProgram.createAccount({fromPubkey: wallet.publicKey,newAccountPubkey: mint.publicKey,space: MINT_SIZE,lamports: rentExemptionLamports,programId: TOKEN_2022_PROGRAM_ID});
Lệnh thứ hai gọi đến lệnh createInitializeMint2Instruction
của
Token Extensions Program để khởi tạo mint account với các
dữ liệu sau:
- 2 số thập phân
- Ví đóng vai trò là cả mint authority và freeze authority
const initializeMintInstruction = createInitializeMint2Instruction(mint.publicKey,2,wallet.publicKey,wallet.publicKey,TOKEN_2022_PROGRAM_ID);
Thêm cả hai lệnh vào một giao dịch duy nhất.
Bằng cách kết hợp cả hai lệnh vào một giao dịch duy nhất, bạn đảm bảo rằng việc tạo tài khoản và khởi tạo xảy ra một cách nguyên tử. Hoặc là cả hai lệnh thành công, hoặc không lệnh nào thành công.
Cách tiếp cận này phổ biến khi xây dựng các giao dịch Solana phức tạp hơn, vì nó đảm bảo rằng tất cả các lệnh được thực thi cùng nhau.
const transaction = new Transaction().add(createAccountInstruction,initializeMintInstruction);
Ký và gửi giao dịch. Cần có hai chữ ký:
- Wallet ký với tư cách là người thanh toán phí giao dịch và tạo tài khoản
- Mint ký để ủy quyền sử dụng địa chỉ của nó cho tài khoản mới
const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[wallet,mint]);
Chữ ký giao dịch được trả về có thể được sử dụng để kiểm tra giao dịch trên Solana Explorer.
Is this page helpful?