How to Create an Account

Creating an account requires using the System Program createAccount instruction. The Solana runtime will grant the owner program of an account, access to write to its data or transfer lamports. When creating an account, we have to preallocate a fixed storage space in bytes (space) and enough lamports to cover the rent.

import {
createTransaction,
createSolanaClient,
signTransactionMessageWithSigners,
getMinimumBalanceForRentExemption,
generateKeyPairSigner,
} from "gill";
import { loadKeypairSignerFromFile } from "gill/node";
import {
getCreateAccountInstruction,
SYSTEM_PROGRAM_ADDRESS,
} from "gill/programs";
const { rpc, sendAndConfirmTransaction } = createSolanaClient({
urlOrMoniker: "devnet",
});
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const signer = await loadKeypairSignerFromFile();
const newAccount = await generateKeyPairSigner();
const space = 0n; // any extra space in the account
const rentLamports = getMinimumBalanceForRentExemption(space);
// const rentLamports = await rpc.getMinimumBalanceForRentExemption(space).send();
const tx = createTransaction({
version: "legacy",
feePayer: signer,
instructions: [
getCreateAccountInstruction({
lamports: rentLamports,
newAccount: newAccount,
payer: signer,
space: space,
// "wallet" accounts are owned by the system program
programAddress: SYSTEM_PROGRAM_ADDRESS,
}),
],
latestBlockhash,
});
const signedTransaction = await signTransactionMessageWithSigners(tx);
await sendAndConfirmTransaction(signedTransaction);