Solana Web3.js Guide: Interacting with the Blockchain

ยท

Introduction to Solana Web3.js

For front-end developers looking to interact with the Solana blockchain, the Solana Web3.js library provides a powerful toolkit. Install it easily via npm:

npm install @solana/web3.js

1. Querying SOL Balance

let connect = new Connection(clusterApiUrl('devnet')); // Connect to Devnet
let secretKey = Uint8Array.from([254, 233, 47, /*...*/ , 112]); // Sample private key
let pay = Keypair.fromSecretKey(secretKey); // Import account
let balance = await connect.getBalance(pay.publicKey); // Get balance in lamports
console.log("balance", `${balance / LAMPORTS_PER_SOL}Sol`); // Convert to SOL

๐Ÿ‘‰ Learn more about Solana account management


2. Transferring SOL

Transactions on Solana consist of instructions. Here's how to create a transfer:

let toPubkey = new PublicKey("B2V5kY..."); // Recipient address
let instruction = SystemProgram.transfer({
  fromPubkey: pay.publicKey,
  toPubkey: toPubkey,
  lamports: 10000000 // 0.01 SOL
});

let latestBlockhash = await connect.getLatestBlockhash();
let messageV0 = new TransactionMessage({
  payerKey: pay.publicKey,
  recentBlockhash: latestBlockhash.blockhash,
  instructions: [instruction]
}).compileToV0Message();

let transaction = new VersionedTransaction(messageV0);
transaction.sign([pay]);
let result = await connect.sendTransaction(transaction);

3. Interacting with Smart Contracts

Interact with deployed programs (like this Hello World contract at 4eFvSUYCL...):

let key1 = {pubkey: pay.publicKey, isSigner: false, isWritable: false};
let data = Buffer.from([0]);
let instruction2 = new TransactionInstruction({
  programId: new PublicKey("4eFvSUYCL..."),
  keys: [key1],
  data: data
});

// Similar transaction construction as above
// ...
let result2 = await connect.sendTransaction(t);

๐Ÿ‘‰ Explore Solana smart contract development


4. Monitoring Accounts

Listen for account changes using WebSocket connections:

let connect = new Connection(clusterApiUrl('devnet'), {
  wsEndpoint: "wss://docs-demo.solana-devnet.quiknode.pro/"
});

connect.onAccountChange(
  pay.publicKey,
  (updatedAccountInfo, context) => {
    console.log("Updated account info: ", updatedAccountInfo);
  },
  "confirmed"
);

FAQ Section

How do I get test SOL for Devnet?

Use Solana faucets to request test SOL for development purposes.

What's the difference between lamports and SOL?

1 SOL = 1,000,000,000 lamports (similar to how 1 BTC = 100,000,000 satoshis).

Why use VersionedTransaction?

VersionedTransaction supports modern transaction features, while the legacy Transaction type is being deprecated.

How can I view my transaction on the blockchain?

Use Solscan.io with your transaction hash to inspect details on-chain.


Conclusion

This guide covers essential Solana Web3.js operations:

For deeper dives into Solana development, check official documentation and developer resources.