Client-Side Integration with TypeScript and Web3.js

10 min read

Welcome to the bridge between your web interface and the Solana runtime! Up to this point, you may have written Rust programs that sit calmly inside Solana's Sealevel engine. But an on-chain program without a client interface is like an arcade machine with no coin slot and no joystick: mathematically sound, but completely unreachable by real humans.

In this guide, we dive into building client applications using TypeScript, @solana/web3.js, and the Anchor client library (@coral-xyz/anchor).


Scope & Boundaries: What the Client Can and Cannot Do 🧭

Before writing a single line of code, let's establish the sandbox boundaries:

delphi
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        JSON-RPC / WSS         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           CLIENT APPS                β”‚   ────────────────────────►   β”‚            SOLANA RUNTIME            β”‚
β”‚  β€’ Builds Instructions               β”‚                               β”‚  β€’ Enforces Program Logic (Rust)     β”‚
β”‚  β€’ Requests Signatures (Wallets)     β”‚   ◄────────────────────────   β”‚  β€’ Commits State to Ledger           β”‚
β”‚  β€’ Monitors State via Subscriptions  β”‚      Simulated / Confirmed    β”‚  β€’ Validates Signatures & Fees       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  • What is possible: You can construct transactions, request cryptographic signatures from user wallets, submit payloads to RPC nodes, deserialize raw account buffers into typed objects, and listen to state changes in real time.
  • What is NOT possible: The client cannot arbitrarily change account data on its own, bypass signature verification, or guarantee that a transaction will land just because it was dispatched.
  • Why the boundary exists: The client lives in an untrusted environment (a user's browser or an external script). The blockchain ledger strictly treats client messages as proposals. Only the validators running the on-chain programs can approve or reject state mutations.

1. Connecting to RPC, Wallets, and Keypair Generation πŸ”Œ

Definition & Problem

To interact with Solana, your application needs an endpoint to send requests to and a cryptographic identity to authorize those requests. Without an RPC (Remote Procedure Call) connection, your frontend is completely deaf and blind to the network. Without a Keypair or Wallet Adapter, your application cannot sign transactions to pay for compute or authenticate actions.

The RPC Connection & Commitment Levels

A Connection instance is your gateway to an RPC node. Solana uses three standard commitment levels that reflect how deep a block is in validator consensus:

Commitment Level Description Typical Latency Best Used For...
processed Node received transaction and queried local state. ~400ms Snappy optimistic UI updates.
confirmed 66%+ of active stake voted on the block. ~1–2s Industry standard for most dApp flows.
finalized 31+ confirmed blocks built on top of this block. ~12–15s High-stakes transfers or bridge operations.
typescript
import { Connection, clusterApiUrl } from "@solana/web3.js";

// Connect to Solana Devnet with 'confirmed' commitment
const rpcUrl = clusterApiUrl("devnet");
const connection = new Connection(rpcUrl, "confirmed");

console.log("Connected to cluster:", connection.rpcEndpoint);

⚠️ Industry Tip: Never rely on public endpoints like api.devnet.solana.com or api.mainnet-beta.solana.com in production! Public nodes employ aggressive rate limits (HTTP 429 Too Many Requests). Production applications always route traffic through dedicated RPC providers (such as Helius, QuickNode, or Triton).


Identity: Keypairs vs. Wallets

An identity in Solana is an Ed25519 Keypair.

  • Public Key: Your address (base58-encoded string, 32 bytes). Safe to share.
  • Secret Key: 64-byte array containing the private seed. Keep it secret, keep it safe πŸ§™.

Generating a Local Keypair (Backend / Scripting)

typescript
import { Keypair } from "@solana/web3.js";

// Generate a brand new, random keypair
const ephemeralKeypair = Keypair.generate();
console.log("Public Key:", ephemeralKeypair.publicKey.toBase58());

// Restoring a keypair from an environment variable (Uint8Array)
// process.env.SECRET_KEY should be a JSON array string: "[12, 34, ...]"
const secretKey = Uint8Array.from(JSON.parse(process.env.SECRET_KEY || "[]"));
const restoredKeypair = Keypair.fromSecretKey(secretKey);

The Wallet Adapter (Frontend / Browser)

In a client web application, never load user private keys directly. Instead, you interface with browser extensions (like Phantom, Solflare, or Backpack) using the Solana Wallet Adapter. The browser extension signs payloads in an isolated sandbox, returning signatures back to your app:

typescript
// Conceptual interface provided by @solana/wallet-adapter-base
interface AnchorWallet {
  publicKey: PublicKey;
  signTransaction<T extends Transaction | VersionedTransaction>(tx: T): Promise<T>;
  signAllTransactions<T extends Transaction | VersionedTransaction>(txs: T[]): Promise<T[]>;
}

2. Building, Signing, and Sending Transactions via @solana/web3.js πŸ“¦

Definition & Problem

Blockchains do not have arbitrary "REST endpoints" to alter state. You cannot simply POST /transfer with a body. Instead, you build a Transaction: a cryptographically sealed envelope packed with one or more atomic Instructions, a recent blockhash, and one or more cryptographic signatures.

Modern Standard: Versioned Transactions (v0)

While legacy transactions served Solana for years, Versioned Transactions (TransactionMessage + VersionedTransaction) are the modern industry standard. They support Address Lookup Tables (ALTs), reducing transaction size overhead and packing more work into a single block.

The Anatomy of an Instruction

Every instruction requires three parts:

  1. programId: The address of the deployed on-chain program.
  2. keys: An array of metadata describing every account read or written to (pubkey, isSigner, isWritable).
  3. data: A raw binary Buffer containing the arguments and action discriminator.
mipsasm
       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
       β”‚             VersionedTransaction (v0)                  β”‚
       β”‚                                                        β”‚
       β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
       β”‚  β”‚               TransactionMessage                 β”‚  β”‚
       β”‚  β”‚  β€’ Payer: Public Key                             β”‚  β”‚
       β”‚  β”‚  β€’ Recent Blockhash (Prevents replay attacks)    β”‚  β”‚
       β”‚  β”‚  β€’ Instructions:                                 β”‚  β”‚
       β”‚  β”‚     [1] Compute Budget Priority Fee              β”‚  β”‚
       β”‚  β”‚     [2] SystemProgram Transfer                   β”‚  β”‚
       β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
       β”‚                                                        β”‚
       β”‚  Signatures: [ Payer_Sig, ... ]                        β”‚
       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Hands-On: Priority Fees + Native SOL Transfer

During high network activity, transactions without priority fees can be deprioritized by validators. In modern development, always attach Compute Budget instructions.

typescript
import {
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  PublicKey,
  SystemProgram,
  TransactionMessage,
  VersionedTransaction,
  ComputeBudgetProgram
} from "@solana/web3.js";

async function sendSolWithPriority(
  connection: Connection,
  payer: Keypair,
  recipient: PublicKey,
  amountSol: number
) {
  // 1. Fetch latest blockhash and last valid block height
  const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash("confirmed");

  // 2. Define Compute Budget instructions (Priority Fees)
  const setComputeLimit = ComputeBudgetProgram.setComputeUnitLimit({
    units: 50_000, // Allocate compute budget
  });

  const setPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
    microLamports: 10_000, // Price per compute unit in micro-lamports
  });

  // 3. Define the actual business logic (Transfer SOL)
  const transferIx = SystemProgram.transfer({
    fromPubkey: payer.publicKey,
    toPubkey: recipient,
    lamports: amountSol * LAMPORTS_PER_SOL,
  });

  // 4. Assemble instructions inside a modern TransactionMessage (v0)
  const messageV0 = new TransactionMessage({
    payerKey: payer.publicKey,
    recentBlockhash: blockhash,
    instructions: [setComputeLimit, setPriorityFee, transferIx],
  }).compileToV0Message();

  // 5. Create VersionedTransaction and sign it
  const transaction = new VersionedTransaction(messageV0);
  transaction.sign([payer]);

  // 6. Broadcast raw transaction
  const signature = await connection.sendTransaction(transaction, {
    skipPreflight: false, // Preflight runs a local simulation first
    maxRetries: 3,
  });

  console.log(`Transaction sent! Signature: ${signature}`);

  // 7. Confirm transaction status
  const confirmation = await connection.confirmTransaction(
    {
      signature,
      blockhash,
      lastValidBlockHeight,
    },
    "confirmed"
  );

  if (confirmation.value.err) {
    throw new Error(`Transaction failed: ${JSON.stringify(confirmation.value.err)}`);
  }

  console.log(`Transaction successfully confirmed at slot: ${confirmation.context.slot}`);
}

πŸ›‘ The 1232-Byte Hard Limit: IPv6 MTU limits dictate that a Solana transaction packet cannot exceed 1232 bytes. If you attempt to pack too many accounts or instructions into a single transaction without Address Lookup Tables (ALTs), compilation will fail with a serialization size error.


3. Consuming Anchor IDL with Anchor Client Libraries βš“

Definition & Problem

Writing raw instructions requires manually calculating 8-byte function discriminators, serializing parameters with Borsh, and remembering every single account pubkey and its read/write flags. One flipped boolean, and the transaction reverts.

The Solution: The Anchor Interface Definition Language (IDL). An IDL is a JSON specification representing your on-chain program's entire APIβ€”its instructions, arguments, account structs, and custom errors. With @coral-xyz/anchor, your TypeScript environment reads this IDL and automatically builds a type-safe client.


Setting Up the AnchorProvider and Program

To talk to an Anchor program, you need:

  1. A Connection (the network pipe).
  2. A Wallet (the signer).
  3. The Idl (the schema file, typically generated in target/idl/<program_name>.json).
typescript
import * as anchor from "@coral-xyz/anchor";
import { Program, AnchorProvider } from "@coral-xyz/anchor";
import { Connection, Keypair } from "@solana/web3.js";
import idl from "./idl/counter_program.json";
import { CounterProgram } from "./types/counter_program"; // Generated by `anchor build`

// 1. Establish provider
const connection = new Connection("https://api.devnet.solana.com", "confirmed");
const wallet = new anchor.Wallet(Keypair.generate()); // In React, use useAnchorWallet()
const provider = new AnchorProvider(connection, wallet, {
  commitment: "confirmed",
});
anchor.setProvider(provider);

// 2. Instantiate the program interface with strong typing
const programId = new anchor.web3.PublicKey(idl.address);
const program = new Program<CounterProgram>(idl as CounterProgram, provider);

Executing Instructions via the Methods Builder

Anchor utilizes a fluent Methods Builder pattern (program.methods.<instructionName>(...args)). It automatically resolves system accounts, derives Program Derived Addresses (PDAs) if configured in the IDL, and formats the transaction envelope behind the scenes.

typescript
async function initializeCounter(counterKeypair: Keypair, authority: anchor.web3.PublicKey) {
  // Anchor handles serialization, discriminators, and instruction packaging
  const txSignature = await program.methods
    .initialize(new anchor.BN(100)) // Pass arguments (e.g., initial count: 100)
    .accounts({
      counter: counterKeypair.publicKey,
      authority: authority,
      systemProgram: anchor.web3.SystemProgram.programId,
    })
    .signers([counterKeypair]) // Additional signers besides the provider wallet
    .rpc(); // Sends and confirms the transaction

  console.log("Counter initialized! Signature:", txSignature);
}

Reading and Deserializing On-Chain State

Gone are the days of slicing raw memory buffers (data.subarray(8, 16)). Anchor automatically parses account data according to the IDL schema:

typescript
async function readCounterData(counterPubkey: anchor.web3.PublicKey) {
  // Fetch and deserialize a single account
  const counterAccount = await program.account.counter.fetch(counterPubkey);
  
  console.log("Authority:", counterAccount.authority.toBase58());
  console.log("Current Count:", counterAccount.count.toNumber());

  // Fetch all accounts of type 'counter' matching an optional filter
  const allCounters = await program.account.counter.all([
    {
      memcmp: {
        offset: 8, // Skip 8-byte Anchor account discriminator
        bytes: counterAccount.authority.toBase58(),
      },
    },
  ]);

  console.log(`Found ${allCounters.length} counters for this authority.`);
}

4. Listening to Account Changes with WebSocket Subscriptions 🎧

Definition & Problem

Polling an RPC endpoint every 500ms using connection.getAccountInfo() burns through RPC rate limits, introduces UI lag, and creates unnecessary traffic. WebSockets (WSS) provide a persistent, push-based communication channel where the RPC node notifies your client the moment validator consensus updates an account's state.


Using @solana/web3.js Native WebSockets

The Connection object maintains an underlying WebSocket connection. You can register listeners for individual accounts, program-owned accounts, or transaction confirmations:

typescript
import { Connection, PublicKey } from "@solana/web3.js";

function watchAccountBalance(connection: Connection, targetAccount: PublicKey) {
  console.log(`Subscribing to updates for: ${targetAccount.toBase58()}`);

  // Returns a subscription ID (number)
  const subscriptionId = connection.onAccountChange(
    targetAccount,
    (accountInfo, context) => {
      console.log(`\nπŸ”” Update received at slot: ${context.slot}`);
      console.log(`New Balance: ${accountInfo.lamports / 1e9} SOL`);
      console.log(`Raw Data Length: ${accountInfo.data.length} bytes`);
    },
    "confirmed" // Commitment level for notifications
  );

  // Return a cleanup function to prevent memory leaks!
  return async () => {
    console.log("Unsubscribing from account...");
    await connection.removeAccountChangeListener(subscriptionId);
  };
}

Reactive Anchor State Listeners

When building with Anchor, you can subscribe to program-level events emitted on-chain (emit!() in Rust):

typescript
// Listening for an event defined in Anchor: `emit!(CounterIncremented { ... })`
const eventListenerId = program.addEventListener(
  "CounterIncremented",
  (event, slot) => {
    console.log(`Event emitted at slot ${slot}`);
    console.log(`New value: ${event.newValue.toString()}`);
  }
);

// Cleanup when component unmounts
async function stopListening() {
  await program.removeEventListener(eventListenerId);
}

Edge Cases and Subscription Failure Modes πŸ› οΈ

WebSockets over the internet are not infallible:

  1. Network Drops & Reconnections: If a consumer's internet disconnects, the WebSocket terminates silently. Standard RPC endpoints do not backfill missed messages that occurred during the outage.
  2. The "Missed Event" Pattern: For critical applications, always pair a WebSocket subscription with a periodic fallback poll or an explicit read before triggering critical UI workflows.

Summary Checklist πŸ“‹

Goal Tool / Method
Initialize Connection new Connection(endpoint, commitment)
Local Keypair Generation Keypair.generate()
Build Modern Tx new TransactionMessage(...).compileToV0Message()
Ensure Delivery Under Load ComputeBudgetProgram.setComputeUnitPrice(...)
Anchor Client Binding new Program<Type>(idl, provider)
Invoke Anchor Instruction await program.methods.myMethod().rpc()
Reactive State Updates connection.onAccountChange(...) / program.addEventListener(...)

References & Extra Reading πŸ“š

Challenge

Client Setup & State Management Conceptual Challenge

As a developer integrating a decentralized application (dApp) utilizing Solana and Anchor, you are responsible for setting up the client-side environment. This component is responsible for establishing connectivity and managing real-time state updates without causing resource leaks.

Please answer the following questions thoroughly, focusing on the specific mechanics and best practices outlined in modern Solana TypeScript development.

  1. Which three critical NPM packages must be imported to enable a complete client-side interaction with a Solana program built with Anchor (assuming TypeScript)? Briefly explain the primary role of each.

  2. When initializing a Connection to a Solana RPC endpoint, which commitment level should a developer use for a high-stakes transaction (e.g., transferring significant funds or approving a major configuration change), and why?

  3. You have successfully instantiated an AnchorProvider. You need to subscribe to real-time account state changes for a specific account ID to drive your UI. Which specific object/method should you call on the established connection, and what critical action must you perform in the cleanup function of your component to prevent memory leaks?

Expected result

A detailed technical response covering the required libraries and their functions, the rationale for choosing the correct RPC commitment level for high-stakes operations, and the precise API call/cleanup mechanism for state change subscriptions.

plain text

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.