Solana Web3.js version 2.x and higher: a beginner’s guide
As a TypeScript developer, you’re probably familiar with the basics of Solana blockchain programming. However, if you’re new to Web3.js, Solana’s official web interface library, things can get confusing quickly. In this article, we will consider several basic examples of using Solana Web3.js version 2.x and higher.
Library Installation
Before we dive into the code, make sure you have the latest Solana CLI installed on your computer. You can install it using npm:
npm install solana-cli @solana/web3js
Setting up a new cluster
To use Web3.js with a new cluster, create an .env
file in the root directory and add your cluster’s private key as follows:
SOLANA_KEY=your-cluster-private-key
Replace your-cluster-private-key
with your actual Solana cluster private key.
Cluster connection
Create a new JavaScript file (eg main.ts
) and import the web3.js
library. You will need to use the solana' object to connect to the cluster:
import { web3 } from '@solana/web3js';
const cluster = new web3.WebsocketCluster({
url: 'wss://your-cluster-url',
});
// Generate a key pair for your account
async function generateKeyPair() {
const keyPath = process.env.SOLANA_KEY;
const key = await web3.generateKeypairs(keyPath);
return { key, cluster };
}
const { key, cluster } = await generateKeyPair();
Create a new account
Use the web3object to create a new account:
Account created: ${account.publicKey.toString()}
async function createAccount() {
try {
const account = await web3.account.createAccount(key);
console.log(
);
} catch (error) {
console.error(error);
}
}
Bet & Unlock
To make a bet on an account, use the web3object to send a transaction:
Token stake ${transaction.amount}
async function stake() {
try {
const transaction = await web3.account.stakeAccount(key, { amount: '10' });
console.log(
);
} catch (error) {
console.error(error);
}
}
To unlock your account, use the web3object to send a transaction:
Account unlocked: ${transaction.publicKey.toString()}
async function unlock() {
try {
const transaction = await web3.account.unlockAccount(key);
console.log(
);
} catch (error) {
console.error(error);
}
}
Smart Contracts
To interact with smart contracts, use the web3` object to send transactions and perform functions:
async function deployContract() {
try {
const contract = await web3.eth_contract.createContract({
contractAddress: '0x...Your Contract Address...',
accounts: ['your-account-key'],
bytecode: '0x...Contract Bytecode...',
});
console.log('Contract deployed');
} catch (error) {
console.error(error);
}
}
Getting Started
This simple example will get you started with Solana Web3.js version 2.x and higher. Remember to replace the placeholders with the actual data of your cluster.
If you have any problems or questions, don’t hesitate to ask!
Resources:
- Official [Solana Web3.js documentation](
- [Solana CLI documentation](
- [Web3.js GitHub repository](
Leave a Reply