Hello! Welcome to the next phase of your Solana journey.
Having spent the last few modules mastering the art of building on-chain programs with Rust and Anchor, you're now ready to build the other half of the equation: the client-side application that users will interact with. This is where your extensive front-end development experience will be a significant asset.
In this lesson, we'll dive into Module 11, "Client-Side Development with @solana/web3.js". Our goal is to set up a modern TypeScript project, install the essential @solana/web3.js library, and write the code to establish a connection to a Solana RPC endpoint. This connection is the fundamental first step for any dApp to communicate with the Solana blockchain.
Let's get started.
1. The Role of @solana/web3.js and RPC Endpoints
Before we write any code, let's clarify the key components.
-
@solana/web3.js: This is the official JavaScript/TypeScript library for interacting with the Solana blockchain. It provides the tools to create keys, construct transactions, and—most importantly for today—communicate with a Solana node. Think of it as the equivalent ofethers.jsorweb3.jsin the Ethereum ecosystem. -
RPC Endpoint: RPC stands for "Remote Procedure Call". An RPC endpoint is a URL that points to a Solana node (or a cluster of nodes) that listens for requests from your application. When your dApp needs to get information from the blockchain (like an account balance) or submit a transaction, it sends a request to this RPC endpoint. The node then processes the request and sends back a response. It's effectively the API server for the blockchain.
A New Era: @solana/web3.js v2.0
A significant recent development is the release of @solana/web3.js version 2.0. As a seasoned developer, you know the importance of staying current. The new version is a complete redesign, moving from a class-based (new Connection(...)) to a more modern, functional, and tree-shakable paradigm.
This new version offers substantial benefits:
- Smaller Bundle Sizes: Thanks to tree-shaking, your final application will only include the parts of the library you actually use.
- Improved Performance: It leverages native browser and Node.js cryptography APIs for faster operations.
- Enhanced Flexibility: The functional design makes the library more composable and customizable.
For these reasons, we will be focusing exclusively on the v2.0 SDK.
2. Setting Up Your Frontend Project
Let's set up a clean Node.js project with TypeScript. Given your background, these steps will be familiar, but we'll focus on the specific dependencies for Solana.
First, create a new directory for your project and initialize it.
mkdir solana-client-example
cd solana-client-example
npm init -y
Next, let's install the necessary packages. We'll use the Helius guide as our reference for this setup.
How to Start Building with the Solana Web3.js 2.0 SDK
The following article, 'How to Start Building with the Solana Web3.js 2.0 SDK' from Helius, provides an excellent guide to the new library. We'll use its 'Installation' section to set up our project.
Please read the section titled 'Installation'. Focus on the npm install command it recommends. We will use these packages in our project.
Based on the guide, let's install the packages. We'll use esrun as a convenient way to execute our TypeScript files directly.
npm install @solana/web3.js@2 typescript
npm install -D esrun @types/node
@solana/web3.js@2: The core library. Specifying@2ensures we get the latest major version.typescript,@types/node: Standard for any TypeScript project.esrun: A zero-config TypeScript runner.
Finally, create a src directory and a new file inside it named index.ts.
mkdir src
touch src/index.ts
Your project is now ready for some Solana-specific code!
3. Establishing a Connection to a Solana RPC Endpoint
With the project set up, our main task is to connect to a Solana cluster. In v2.0 of @solana/web3.js, this is done with a functional approach. There are two primary functions for creating a connection, corresponding to the two main web protocols:
createSolanaRpc(url): Creates an RPC client for sending requests over HTTP. This is used for one-off calls like fetching account data, getting the latest blockhash, or sending a transaction.createSolanaRpcSubscriptions(url): Creates an RPC client for managing real-time subscriptions over WebSockets. This is used for listening to events, like account changes or transaction confirmation notifications.
Let's start by studying the relevant sections from the Helius article and a video from Solandy that demonstrates these new functions.
How to Start Building with the Solana Web3.js 2.0 SDK
First, let's return to the Helius article to see the code for creating RPC connections.
Please read the section titled 'Configure RPC Connections'. Note the use of createSolanaRpc and createSolanaRpcSubscriptions.
Solana kit (forermly web3.js v2.0.0) officially released [Solana Tutorial] - Nov 12th '24
Now, let's watch a short segment from Solandy that visually walks through setting up these connections with the new functional API. This will help solidify your understanding.
Watch the segment from 21:59 to 23:37. The presenter explains the difference between the HTTP and WebSocket connections and shows how to create them using createSolanaRpc and createSolanaRpcSubscriptions.
Now, let's put this into practice. Open your src/index.ts file and add the following code. We will connect to Solana's Devnet, a test network for developers, and fetch the current slot to verify our connection is working.
// src/index.ts
import { createSolanaRpc } from '@solana/web3.js';
// Public RPC endpoint for Solana's Devnet.
const RPC_URL = 'https://api.devnet.solana.com';
async function main() {
console.log('Connecting to Solana Devnet...');
// Create an RPC client.
const rpc = createSolanaRpc(RPC_URL);
try {
// Fetch the current slot number. This is a simple way to verify the connection.
const slot = await rpc.getSlot().send();
console.log(`✅ Connection successful!`);
console.log(`Current slot: ${slot}`);
} catch (error) {
console.error('❌ Failed to connect to the cluster:', error);
}
}
main();
To run this script, execute the following command in your terminal:
npx esrun src/index.ts
If everything is correct, you should see an output like this:
Connecting to Solana Devnet...
✅ Connection successful!
Current slot: 371984231
(The slot number will be different, as it's constantly increasing.)
Congratulations! You've successfully connected a client-side application to the Solana blockchain using the modern @solana/web3.js v2 SDK.
Test your understanding!
Modify the main function in your index.ts file to fetch and log the version of the Solana cluster software instead of the current slot.
Hint: Look for a method on the rpc object that sounds like it would get the version. All RPC methods are available directly on the rpc object you created.
Show answer
You would replace rpc.getSlot().send() with rpc.getVersion().send().
// src/index.ts
import { createSolanaRpc } from '@solana/web3.js';
const RPC_URL = 'https://api.devnet.solana.com';
async function main() {
console.log('Connecting to Solana Devnet...');
const rpc = createSolanaRpc(RPC_URL);
try {
// Fetch the version of the Solana cluster.
const version = await rpc.getVersion().send();
console.log(`✅ Connection successful!`);
console.log(`Solana cluster version:`, version['solana-core']);
} catch (error) {
console.error('❌ Failed to connect to the cluster:', error);
}
}
main();
Running this will give you the version string of the validator software running on Devnet.
4. Public vs. Private RPC Endpoints
A quick but important note: We used https://api.devnet.solana.com, which is a free, public RPC endpoint provided by the Solana Foundation. While this is great for development and testing, it's rate-limited and not recommended for production applications.
When you build a real dApp, you will want to use a dedicated RPC provider like Helius, Triton, QuickNode, or Chainstack. These services offer higher rate limits, better performance, and more reliability, which are crucial for a good user experience.
Conclusion
In this lesson, you've taken the first crucial step into client-side Solana development. You have successfully bridged the gap from the on-chain world of Rust programs to the off-chain world of user-facing applications.
Here are the key takeaways:
@solana/web3.jsis the primary library for interacting with Solana from JavaScript and TypeScript.- The new v2.0 SDK uses a modern, functional approach and is the recommended standard for new projects.
- You can set up a basic project by installing
@solana/web3.js@2andtypescript. - The
createSolanaRpcfunction is used to create an HTTP-based client for making RPC requests. - A simple call like
getSlot()orgetVersion()is an effective way to test your connection to a Solana cluster.
In our next lesson, we will build directly on this foundation. We'll use our established RPC connection to fetch and deserialize data from an on-chain account, allowing us to read the state created by our Solana programs.
Can't find a good explanation? Sign up and we'll make it for you
Sign up