Writing to Network

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

These instructions are processed by programs (smart contracts) that contain the 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, we'll walk through two basic examples:

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

These examples demonstrate 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

Let's start with a simple example of transferring SOL between accounts. To transfer SOL from our Playground wallet, we need to invoke the System Program's transfer instruction.

A key concept of Solana's account model is that only the program that owns an account can deduct an account's lamport (SOL) balance. This means if you want to transfer SOL from a wallet account, you must invoke the System Program since it is the program specified in the owner field of the account.

Open Example

Click this link to open the example in Solana Playground. You'll see the following code:

client.ts
import {
  LAMPORTS_PER_SOL,
  SystemProgram,
  Transaction,
  sendAndConfirmTransaction,
  Keypair,
} from "@solana/web3.js";
 
const sender = pg.wallet.keypair;
const receiver = new Keypair();
 
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(
  pg.connection,
  transaction,
  [sender],
);
 
console.log(
  "Transaction Signature:",
  `https://solana.fm/tx/${transactionSignature}?cluster=devnet-solana`,
);

Run Example

Run the code using the run command.

Terminal
run
Info

Ensure your Playground wallet has devnet SOL. Get devnet SOL from the Solana Faucet.

Click on the output link to view the transaction details on the SolanaFM explorer.

Transfer SOLTransfer SOL

Congratulations! You've just sent your first transaction on Solana! Let's break down what happened:

  • First, we created an instruction specifying what we wanted to do
  • Then, we added that instruction to a transaction
  • Finally, we sent the transaction to be processed by the Solana network

This is the basic pattern for building transactions to interact with the programs on the Solana.

Create a Token

Next, let's create a new token using the Token Extensions Program. This requires two invoking instructions:

  1. Create a new account using the System Program
  2. Initialize the account's data as a Mint using the Token Extensions Program

Open Example

Click this link to open the example in Solana Playground. You'll see the following code:

client.ts
import {
  Connection,
  Keypair,
  SystemProgram,
  Transaction,
  clusterApiUrl,
  sendAndConfirmTransaction,
} from "@solana/web3.js";
import {
  MINT_SIZE,
  TOKEN_2022_PROGRAM_ID,
  createInitializeMint2Instruction,
  getMinimumBalanceForRentExemptMint,
} from "@solana/spl-token";
 
const wallet = pg.wallet;
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
 
// Generate keypair to use as address of mint account
const mint = new Keypair();
 
// Calculate minimum lamports for space required by mint account
const rentLamports = 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: rentLamports,
  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.keypair, // payer
    mint, // mint address keypair
  ],
);
 
console.log(
  "\nTransaction Signature:",
  `https://solana.fm/tx/${transactionSignature}?cluster=devnet-solana`,
);
 
console.log(
  "\nMint Account:",
  `https://solana.fm/address/${mint.publicKey}?cluster=devnet-solana`,
);

Run Example

Run the code using the run command.

Terminal
run
Info

Ensure your Playground wallet has devnet SOL. Get devnet SOL from the Solana Faucet.

You'll see two links printed to the Playground terminal:

  • One for the transaction details
  • One for the newly created mint account

Click the links to inspect the transaction details and the newly created mint account on SolanaFM.

Create TokenCreate Token

Mint AccountMint Account

In this example, we demonstrated how to combine multiple instructions into a single transaction. The transaction contains two key instructions:

  1. Creating a new account using the System Program
  2. Initializing that account as a token mint using the Token Extensions Program

This pattern of combining multiple instructions from different programs into one transaction is common when building more complex Solana transactions. It allows you to sequentially and atomically execute multiple instructions, ensuring they either all succeed or all fail together.

Last updated on

İçindekiler

Sayfayı Düzenle