Introduction
This TypeScript tutorial will guide you through fetching, updating, and transferring wallet balances on the Solana blockchain. By the end, you'll know how to transfer SOL between wallets and create a new wallet.
Step 1: Setting Up Your TypeScript Project
First, set up your TypeScript project:
npm init -y
npm install --save-dev typescript
npx tsc --init
Step 2: Installing Solana Web3.js Library
Install the Solana Web3.js library:
npm install --save @solana/web3.js
Step 3: Creating a New Wallet
To create a new wallet, run the following command:
solana-keygen new --outfile ~/.config/solana/id2.json
Make sure to copy the generated secret key from the id2.json
file, as you'll need it for your transactions.
Step 4: Adding SOL Transfer Functionality
Create transfer-sol.ts
:
import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction, sendAndConfirmTransaction } from "@solana/web3.js";
// Transfer SOL function
export const transferSol = async (from: Keypair, to: PublicKey, amount: number) => {
const conn = new Connection("http://127.0.0.1:8899", "confirmed");
const transaction = new Transaction();
const instruction = SystemProgram.transfer({
fromPubkey: from.publicKey,
toPubkey: to,
lamports: amount * LAMPORTS_PER_SOL
});
transaction.add(instruction);
await sendAndConfirmTransaction(conn, transaction, [from]);
console.log('Transfer completed');
};
// Replace 'your_secret' with your actual secret key from id2.json
const secret = Uint8Array.from([your_secret]);
const fromKeyPair = Keypair.fromSecretKey(secret);
const toPublicKey = new PublicKey("Your Public Key"); // Replace with recipient's public key
(async () => {
// Airdrop
await airdrop(fromKeyPair.publicKey, 5);
// Fetch initial balances
const initialBalanceFrom = await showBalance(fromKeyPair.publicKey);
console.log(`Initial balance of from wallet: ${initialBalanceFrom}`);
const initialBalanceTo = await showBalance(toPublicKey);
console.log(`Initial balance of to wallet: ${initialBalanceTo}`);
// Perform SOL transfer
await transferSol(fromKeyPair, toPublicKey, 2);
// Fetch post-transfer balances
const postBalanceFrom = await showBalance(fromkeyPair.publicKey)
console.log(`Post balance of wallet is ${postBalanceFrom}`)
const postBalanceTo = await showBalance(topublicKey);
console.log(`Post balance of wallet is ${postBalanceTo}`);
})();
Step 5: Building and Executing Your Project
Build your project:
npm run build
Run your project:
node dist/transfer-sol.js
Conclusion
You've successfully created a new Solana wallet and transferred SOL between wallets using TypeScript. Continue exploring Solana's capabilities to build even more powerful and innovative applications 🚀!
P.S. If you need help with airdropping SOL or checking wallet balances, check out my Airdrop & Wallet Balance post for a detailed guide.
Top comments (0)