How to Create an Account
To create an account on Solana, invoke the
System Program's createAccount
instruction. This instruction requires you to specify the the number of bytes
(space
) for the new account and fund it with lamports for the allocated bytes
(rent). The account's owner program is set as the program specified in the
instruction. The Solana runtime enforces that only this owner program can modify
the account's data or transfer lamports from it.
On Solana, only the System Program can create new accounts. To create accounts
owned by other programs, invoke the createAccount
instruction to create a new
account and set the owner program to the desired program. The new program owner
can then initialize the account data through its own instructions.
import {airdropFactory,appendTransactionMessageInstructions,createSolanaRpc,createSolanaRpcSubscriptions,createTransactionMessage,generateKeyPairSigner,getSignatureFromTransaction,lamports,pipe,sendAndConfirmTransactionFactory,setTransactionMessageFeePayerSigner,setTransactionMessageLifetimeUsingBlockhash,signTransactionMessageWithSigners} from "@solana/kit";import {getCreateAccountInstruction,SYSTEM_PROGRAM_ADDRESS} from "@solana-program/system";const rpc = createSolanaRpc("http://localhost:8899");const rpcSubscriptions = createSolanaRpcSubscriptions("ws://localhost:8900");const sender = await generateKeyPairSigner();const LAMPORTS_PER_SOL = 1_000_000_000n;await airdropFactory({ rpc, rpcSubscriptions })({recipientAddress: sender.address,lamports: lamports(LAMPORTS_PER_SOL), // 1 SOLcommitment: "confirmed"});const newAccount = await generateKeyPairSigner();const space = 0n;const rentLamports = await rpc.getMinimumBalanceForRentExemption(space).send();const createAccountInstruction = getCreateAccountInstruction({payer: sender,newAccount: newAccount,lamports: rentLamports,programAddress: SYSTEM_PROGRAM_ADDRESS,space});const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();const transactionMessage = pipe(createTransactionMessage({ version: 0 }),(tx) => setTransactionMessageFeePayerSigner(sender, tx),(tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),(tx) => appendTransactionMessageInstructions([createAccountInstruction], tx) // Use new instruction);const signedTransaction =await signTransactionMessageWithSigners(transactionMessage);await sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions })(signedTransaction,{ commitment: "confirmed" });const transactionSignature = getSignatureFromTransaction(signedTransaction);console.log("Transaction Signature for create account:", transactionSignature);
Is this page helpful?