区块链中文技术社区

Solana基础 - 如何创建账户

创建帐户需要使用系统程序createAccount 指令。Solana 运行时将授予帐户所有者程序写入其数据或传输 Lamport 的权限。创建帐户时,我们必须预先分配固定的存储空间(以字节为单位)和足够的 Lamport 来支付租金。

import {
  SystemProgram,
  Keypair,
  Transaction,
  sendAndConfirmTransaction,
  Connection,
  clusterApiUrl,
  LAMPORTS_PER_SOL,
} from "@solana/web3.js";

const connection = new Connection(clusterApiUrl("devnet"), "confirmed");

const fromKeypair = Keypair.generate();
const newAccount = Keypair.generate();

// Airdrop SOL for transferring lamports to the created account
const airdropSignature = await connection.requestAirdrop(
  fromKeypair.publicKey,
  LAMPORTS_PER_SOL,
);
await connection.confirmTransaction(airdropSignature);

// amount of space to reserve for the account
const space = 0;

// Seed the created account with lamports for rent exemption
const rentLamports = await connection.getMinimumBalanceForRentExemption(space);

const createAccountTransaction = new Transaction().add(
  SystemProgram.createAccount({
    fromPubkey: fromKeypair.publicKey,
    newAccountPubkey: newAccount.publicKey,
    lamports: rentLamports,
    space,
    programId: SystemProgram.programId,
  }),
);

await sendAndConfirmTransaction(connection, createAccountTransaction, [
  fromKeypair,
  newAccount,
]);

https://solana.com/zh/developers/cookbook/accounts/create-account

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »