Writing to Network

In the previous section, you learned how to read data from the Solana network. Now explore how to write data to it. Writing to the Solana network involves sending transactions that contain one or more instructions.

Programs (smart contracts) process these instructions according to their business logic for each respective instruction. When you submit a transaction, the Solana runtime executes each instruction in sequence and atomically (meaning either all instructions succeed or the entire transaction fails).

In this section, you'll see two basic examples:

  1. Transferring SOL between accounts
  2. Creating a new token

These examples show how to build and send transactions to invoke Solana programs. For more details, refer to the Transactions and Instructions and Fees on Solana pages.

Transfer SOL

In this example, you'll learn how to transfer SOL between two accounts.

On Solana, each account has a specific program as its owner. Only the program owner can deduct an account's SOL (lamport) balance.

The System Program is the owner for all "wallet" accounts. To transfer SOL, you must invoke the System Program's transfer instruction.

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 'Run' to see output.
Program Logs in the Output are clickable links to Solana Explorer.
You must enable the "Enable Custom URL Param" setting on Solana Explorer.
If not enabled, links will default to localhost:8899 instead of the Mirror.ad RPC URL.

These are the steps for building transactions to interact with any program on Solana.

Create the instruction you want to invoke.

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

Add the instruction to a transaction:

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

Sign and Send the Transaction:

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

Create a Token

In this example, you'll learn how to create a new token on Solana using the Token Extensions Program. This requires two instructions:

  1. Invoke the System Program to create a new account.
  2. Invoke the Token Extensions Program to initialize that account as a 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 'Run' to see output.
Program Logs in the Output are clickable links to Solana Explorer.
You must enable the "Enable Custom URL Param" setting on Solana Explorer.
If not enabled, links will default to localhost:8899 instead of the Mirror.ad RPC URL.

Here's a step-by-step breakdown of what the example does:

Create a connection and fund the wallet

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");

Generate a keypair for the Mint account

Mint Keypair
const mint = new Keypair();

Calculate the minimum lamports for rent exemption

Rent Exemption
const rentExemptionLamports =
await getMinimumBalanceForRentExemptMint(connection);

Create an instruction to create a new account

  1. Allocate the required space for storing mint data
  2. Transfer lamports from the wallet to fund the new account
  3. Assign ownership of the account to the Token Extensions program (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
});

Create an instruction to initialize the Mint account

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

Add both instructions to a transaction

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

Send and confirm the transaction with both required signers

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

Print the Mint account and transaction signature

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

By combining both instructions into a single transaction, you ensure that the account creation and initialization happen atomically. Either both instructions succeed, or neither does. This approach is common when building more complex Solana transactions, as it guarantees that all instructions execute together.

Is this page helpful?

Inhoudsopgave

Pagina Bewerken