Welcome to this fast-paced, hands-on guide to Solana-web3.js, the essential JavaScript library for building on the Solana blockchain. Whether you're new to Solana development or brushing up on core interactions, this tutorial delivers practical insights in under 10 minutes.
We'll walk through three foundational operations:
- Minting an SPL token
- Sending SOL transactions
- Delegating SOL natively
All code examples are designed for clarity and immediate use. By the end, you’ll have a working script that performs real blockchain actions using @solana/web3.js and @solana/spl-token.
Getting Started with Solana-web3.js
Before diving into transactions and token creation, ensure your environment is ready.
Import Required Libraries
Start by installing the necessary packages:
npm install @solana/web3.js @solana/spl-token bs58Then import them in your script:
const solanaWeb3 = require('@solana/web3.js');
const splToken = require('@solana/spl-token');
const bs58 = require('bs58');@solana/web3.js: Core library for connecting to and interacting with the Solana network.@solana/spl-token: Handles SPL token operations like minting and transfers.bs58: Decodes Base58-encoded private keys (commonly used in Solana wallets).
👉 Jumpstart your Solana development with powerful tools and resources.
Setting Up Your Environment
Create the Main Async Function
JavaScript’s async/await pattern is ideal for blockchain interactions due to their asynchronous nature.
async function main() {
// All logic will go here
}
main();Connect to the Solana Network
You need an RPC endpoint to communicate with the blockchain. For reliability and high performance, consider using a dedicated infrastructure provider.
const connection = new solanaWeb3.Connection(
"https://nd-729-020-604.p2pify.com/89254f3e5bf61205d9558141245b8a80",
{
wsEndpoint: "wss://ws-nd-729-020-604.p2pify.com/89254f3e5bf61205d9558141245b8a80"
}
);This connects to a public or hosted node. Replace it with your own secure endpoint when deploying.
Load Your Wallet
Use a private key from environment variables for security:
const walletKeyPair = solanaWeb3.Keypair.fromSecretKey(
new Uint8Array(bs58.decode(process.env.PRIVATE_KEY))
);Ensure your .env file contains the Base58-decoded private key.
Check Wallet Balance
Verify funds before proceeding:
const balance = await connection.getBalance(walletKeyPair.publicKey);
console.log(`Balance: ${balance / solanaWeb3.LAMPORTS_PER_SOL} SOL`);Lamports are the smallest unit of SOL (1 SOL = 1,000,000,000 lamports).
1. Minting an SPL Token
SPL tokens are Solana’s equivalent of ERC-20 tokens on Ethereum.
Create the Mint
const mint = await splToken.createMint(
connection,
walletKeyPair,
walletKeyPair.publicKey,
null,
9
);Parameters:
connection: Active connection.walletKeyPair: Payer and mint authority.walletKeyPair.publicKey: Mint authority (controls supply).null: No freeze authority (can be set later).9: Token decimals.
Generate Associated Token Account
Tokens require a token account to be held:
const tokenAccount = await splToken.getOrCreateAssociatedTokenAccount(
connection,
walletKeyPair,
mint,
walletKeyPair.publicKey
);This creates a unique account tied to your wallet for holding this specific token.
Mint Tokens
Now issue tokens into circulation:
await splToken.mintTo(
connection,
walletKeyPair,
mint,
tokenAccount.address,
walletKeyPair.publicKey,
1000000000 // e.g., 1 billion tokens (adjust based on decimals)
);After running this, your wallet will hold the newly minted SPL tokens.
2. Sending a SOL Transaction
Transfer native SOL between accounts.
Generate a Recipient Wallet
For testing, generate a new keypair:
const secondWalletKeyPair = solanaWeb3.Keypair.generate();
console.log("Recipient public key:", secondWalletKeyPair.publicKey.toBase58());Build and Send the Transaction
const transaction = new solanaWeb3.Transaction().add(
solanaWeb3.SystemProgram.transfer({
fromPubkey: walletKeyPair.publicKey,
toPubkey: secondWalletKeyPair.publicKey,
lamports: solanaWeb3.LAMPORTS_PER_SOL * 0.001 // Send 0.001 SOL
})
);
const signature = await solanaWeb3.sendAndConfirmTransaction(
connection,
transaction,
[walletKeyPair]
);
console.log("Transaction successful with signature:", signature);This sends a small amount of SOL and confirms the transaction on-chain.
3. Delegating SOL (Staking)
Stake SOL to earn rewards by delegating to a validator.
Create a Stake Account
Each delegation requires a separate stake account:
const stakeAccount = solanaWeb3.Keypair.generate();
const createStakeAccountInstruction = solanaWeb3.StakeProgram.createAccount({
fromPubkey: walletKeyPair.publicKey,
stakePubkey: stakeAccount.publicKey,
authorized: new solanaWeb3.Authorized(walletKeyPair.publicKey, walletKeyPair.publicKey),
lamports: solanaWeb3.LAMPORTS_PER_SOL * 0.02 // Stake 0.02 SOL
});Submit Stake Account Creation
const createStakeAccountTransaction = new solanaWeb3.Transaction().add(createStakeAccountInstruction);
createStakeAccountTransaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
createStakeAccountTransaction.feePayer = walletKeyPair.publicKey;
createStakeAccountTransaction.partialSign(stakeAccount);
await solanaWeb3.sendAndConfirmTransaction(
connection,
createStakeAccountTransaction,
[walletKeyPair, stakeAccount]
);Note: The stake account must sign partially since it's being created.
Delegate to a Validator
Replace {input the public key here} with a real validator’s public key:
const votePubkey = new solanaWeb3.PublicKey('ValidatorPublicKeyGoesHere');
const delegateInstruction = solanaWeb3.StakeProgram.delegate({
stakePubkey: stakeAccount.publicKey,
authorizedPubkey: walletKeyPair.publicKey,
votePubkey
});
const delegateTransaction = new solanaWeb3.Transaction().add(delegateInstruction);
delegateTransaction.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
delegateTransaction.feePayer = walletKeyPair.publicKey;
delegateTransaction.sign(walletKeyPair);
await solanaWeb3.sendAndConfirmTransaction(
connection,
delegateTransaction,
[walletKeyPair]
);You’ve now successfully staked SOL!
👉 Explore advanced blockchain interactions with cutting-edge development tools.
Frequently Asked Questions (FAQ)
Q: What is solana-web3.js used for?
A: It’s the primary JavaScript SDK for interacting with the Solana blockchain—used for sending transactions, querying data, managing accounts, and building dApps.
Q: Can I mint tokens without paying fees?
A: No. Minting requires SOL to cover transaction and account creation fees (e.g., rent-exempt balance for token accounts).
Q: Is it safe to use process.env.PRIVATE_KEY?
A: Yes, as long as .env files are git-ignored and never exposed publicly. Never hardcode private keys in source files.
Q: How do I find a validator’s public key to delegate to?
A: Use Solana explorers like Solana.fm or CLI commands like solana validators to view active validators and their keys.
Q: What happens if I lose my stake account keypair?
A: You may lose control over your staked funds. Always back up keypairs securely.
Q: Can I undo a delegation?
A: Yes—via deactivation (not covered here), which starts an unstaking process taking several epochs.
Core Keywords
- Solana-web3.js
- SPL token minting
- Send SOL transaction
- Delegate SOL
- Solana blockchain
- JavaScript SDK
- Stake account
- Blockchain development
These keywords naturally appear throughout this guide to enhance SEO while maintaining readability and technical accuracy.
👉 Unlock full potential in blockchain development—start building today.
With these fundamentals mastered, you're well-equipped to build powerful applications on Solana. Continue exploring advanced topics like token swaps, program deployment, and on-chain data analysis to level up your skills.