Ghi dữ liệu vào Mạng lưới

Trong phần trước, bạn đã học cách đọc dữ liệu từ mạng lưới Solana. Bây giờ hãy khám phá cách ghi dữ liệu vào mạng. Việc ghi dữ liệu vào mạng lưới Solana liên quan đến việc gửi các giao dịch chứa một hoặc nhiều chỉ thị.

Các chương trình (smart contract) xử lý các chỉ thị này theo logic nghiệp vụ của họ cho mỗi chỉ thị tương ứng. Khi bạn gửi một giao dịch, runtime của Solana thực thi từng chỉ thị theo trình tự và nguyên tử (nghĩa là hoặc tất cả các chỉ thị thành công hoặc toàn bộ giao dịch thất bại).

Trong phần này, bạn sẽ thấy hai ví dụ cơ bản:

  1. Chuyển SOL giữa các tài khoản
  2. 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 các trang Giao dịch và Chỉ thị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ể giảm 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 chỉ thị transfer của System Program.

Transfer SOL
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}`);
Click to execute the code.

Đây là các bước để xây dựng giao dịch tương tác với bất kỳ chương trình nào trên Solana.

Tạo chỉ thị bạn muốn gọi.

Instruction
const transferInstruction = SystemProgram.transfer({
fromPubkey: sender.publicKey,
toPubkey: receiver.publicKey,
lamports: 0.01 * LAMPORTS_PER_SOL
});

Thêm chỉ thị vào giao dịch:

Transaction
const transaction = new Transaction().add(transferInstruction);

Ký và gửi giao dịch:

Send Transaction
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[sender] // signer keypair
);

Tạo token

Trong ví dụ này, bạn sẽ học cách tạo một token mới trên Solana bằng cách sử dụng Token Extensions Program. Điều này yêu cầu hai chỉ thị:

  1. Gọi System Program để tạo một tài khoản mới.
  2. Gọi Token Extensions Program để khởi tạo tài khoản đó như một Mint.
Create Mint Account
import {
Connection,
Keypair,
SystemProgram,
Transaction,
sendAndConfirmTransaction,
LAMPORTS_PER_SOL
} from "@solana/web3.js";
import {
MINT_SIZE,
TOKEN_2022_PROGRAM_ID,
createInitializeMint2Instruction,
getMinimumBalanceForRentExemptMint
} from "@solana/spl-token";
const connection = new Connection("http://localhost:8899", "confirmed");
const wallet = new Keypair();
// Fund the wallet with SOL
const signature = await connection.requestAirdrop(
wallet.publicKey,
LAMPORTS_PER_SOL
);
await connection.confirmTransaction(signature, "confirmed");
// Generate keypair to use as address of mint account
const mint = new Keypair();
// Calculate lamports required for rent exemption
const rentExemptionLamports =
await getMinimumBalanceForRentExemptMint(connection);
// Instruction to create new account with space for new mint account
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: wallet.publicKey,
newAccountPubkey: mint.publicKey,
space: MINT_SIZE,
lamports: rentExemptionLamports,
programId: TOKEN_2022_PROGRAM_ID
});
// Instruction to initialize mint account
const initializeMintInstruction = createInitializeMint2Instruction(
mint.publicKey,
2, // decimals
wallet.publicKey, // mint authority
wallet.publicKey, // freeze authority
TOKEN_2022_PROGRAM_ID
);
// Build transaction with instructions to create new account and initialize mint account
const transaction = new Transaction().add(
createAccountInstruction,
initializeMintInstruction
);
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[
wallet, // payer
mint // mint address keypair
]
);
console.log("Mint Account:", `${mint.publicKey}`);
console.log("Transaction Signature:", `${transactionSignature}`);
Click to execute the code.

Dưới đây là phân tích từng bước về những gì ví dụ thực hiện:

Tạo kết nối và nạp tiền vào ví

Connection and Wallet
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 tài khoản Mint

Mint Keypair
const mint = new Keypair();

Tính toán số lamport tối thiểu để miễn phí rent

Rent Exemption
const rentExemptionLamports =
await getMinimumBalanceForRentExemptMint(connection);

Tạo một lệnh để tạo tài khoản mới

  1. Phân bổ không gian cần thiết để lưu trữ dữ liệu mint
  2. Chuyển lamports từ ví để cấp vốn cho tài khoản mới
  3. Gán quyền sở hữu của tài khoản cho chương trình Token Extensions (TOKEN_2022_PROGRAM_ID)
Create Account Instruction
const createAccountInstruction = SystemProgram.createAccount({
fromPubkey: wallet.publicKey,
newAccountPubkey: mint.publicKey,
space: MINT_SIZE,
lamports: rentExemptionLamports,
programId: TOKEN_2022_PROGRAM_ID
});

Tạo một lệnh để khởi tạo tài khoản Mint

Initialize Mint Instruction
const initializeMintInstruction = createInitializeMint2Instruction(
mint.publicKey,
2, // decimals
wallet.publicKey, // mint authority
wallet.publicKey, // freeze authority
TOKEN_2022_PROGRAM_ID
);

Thêm cả hai lệnh vào một giao dịch

Build Transaction
const transaction = new Transaction().add(
createAccountInstruction,
initializeMintInstruction
);

Gửi và xác nhận giao dịch với cả hai người ký bắt buộc

Send Transaction
const transactionSignature = await sendAndConfirmTransaction(
connection,
transaction,
[wallet, mint]
);

In tài khoản Mint và chữ ký giao dịch

Output
console.log("Mint Account:", `${mint.publicKey}`);
console.log("Transaction Signature:", `${transactionSignature}`);

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.

Is this page helpful?

Mục lục

Chỉnh sửa trang