写入网络
在上一节中,您学习了如何从 Solana 网络读取数据。现在来探索如何向其写入数据。向 Solana 网络写入数据涉及发送包含一个或多个指令的交易。
程序(智能合约)根据各自指令的业务逻辑处理这些指令。当您提交交易时,Solana 运行时会按顺序执行每个指令,并以原子方式执行(即所有指令要么全部成功,要么整个交易失败)。
在本节中,您将看到两个基本示例:
- 在账户之间转移 SOL
- 创建一个新代币
这些示例展示了如何构建和发送交易以调用 Solana 程序。有关更多详细信息,请参阅 交易和指令 和 Solana 上的费用 页面。
转移 SOL
在此示例中,您将学习如何在两个账户之间转移 SOL。
在 Solana 上,每个账户都有一个特定的程序作为其所有者。只有程序所有者可以扣除账户的 SOL(lamport)余额。
系统程序是所有“钱包”账户的 所有者。要转移 SOL,您必须调用系统程序的 转移 指令。
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}`);
ConsolePowered by Mirror
Click to execute the code.
以下是构建交易以与 Solana 上的任何程序交互的步骤。
创建您想要调用的指令。
Instruction
const transferInstruction = SystemProgram.transfer({fromPubkey: sender.publicKey,toPubkey: receiver.publicKey,lamports: 0.01 * LAMPORTS_PER_SOL});
将指令添加到交易中:
Transaction
const transaction = new Transaction().add(transferInstruction);
签署并发送交易:
Send Transaction
const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[sender] // signer keypair);
创建一个代币
在此示例中,您将学习如何使用代币扩展程序在 Solana 上创建一个新代币。这需要两个指令:
- 调用系统程序创建一个新账户。
- 调用代币扩展程序将该账户初始化为一个铸币账户。
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 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("Mint Account:", `${mint.publicKey}`);console.log("Transaction Signature:", `${transactionSignature}`);
ConsolePowered by Mirror
Click to execute the code.
以下是示例的逐步分解:
创建连接并为钱包提供资金
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");
为 Mint 账户生成一个 keypair
Mint Keypair
const mint = new Keypair();
计算租金豁免所需的最低 lamports
Rent Exemption
const rentExemptionLamports =await getMinimumBalanceForRentExemptMint(connection);
创建一个指令以创建新账户
- 分配所需空间以存储 mint 数据
- 从钱包转移 lamports以资助新账户
- 将账户的所有权分配给 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});
创建一个指令以初始化 Mint 账户
Initialize Mint Instruction
const initializeMintInstruction = createInitializeMint2Instruction(mint.publicKey,2, // decimalswallet.publicKey, // mint authoritywallet.publicKey, // freeze authorityTOKEN_2022_PROGRAM_ID);
将两个指令添加到一个交易中
Build Transaction
const transaction = new Transaction().add(createAccountInstruction,initializeMintInstruction);
发送并确认包含两个所需签名者的交易
Send Transaction
const transactionSignature = await sendAndConfirmTransaction(connection,transaction,[wallet, mint]);
打印 Mint 账户和交易签名
Output
console.log("Mint Account:", `${mint.publicKey}`);console.log("Transaction Signature:", `${transactionSignature}`);
通过将两个指令合并到一个交易中,可以确保账户创建和初始化原子性地完成。要么两个指令都成功,要么都失败。这种方法在构建更复杂的 Solana 交易时很常见,因为它保证了所有指令一起执行。
Is this page helpful?