Solana web3 js

Basic operations on Solana using web3 js.

Libraries:

var web3 = require('.js');
var splToken = require('');

Connection and generating keypairs:

const connection = new web3.Connection(
web3.clusterApiUrl('testnet'),
'confirmed',
);
// generate keypair
var fromWallet = web3.Keypair.generate();
var toWallet = web3.Keypair.generate();

Get balance:

    console.log(await connection.getBalance(fromWallet.publicKey));
console.log(await connection.getBalance(toWallet.publicKey));
// add some initial balance. Not possible in production.
var fromAirdropSignature = await connection.requestAirdrop(
fromWallet.publicKey,
1000000000, // lambports
);
await connection.confirmTransaction(fromAirdropSignature);
console.log(await connection.getBalance(fromWallet.publicKey));

Transaction:

var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: fromWallet.publicKey,
toPubkey: toWallet.publicKey,
lamports: 10000,
}),
);
// Sign transaction, broadcast, and confirm
var signature = await web3.sendAndConfirmTransaction(
connection,
transaction,
[fromWallet],
);
console.log('SIGNATURE', signature);
console.log(await connection.getBalance(fromWallet.publicKey));
console.log(await connection.getBalance(toWallet.publicKey));

Multi sign transaction(partialSign)

var feePayerWallet = web3.Keypair.generate();
var feePayerAirdropSignature = await connection.requestAirdrop(
feePayerWallet.publicKey,
1000000000, // lambports
);
await connection.confirmTransaction(feePayerAirdropSignature);
var fundedTransaction = new web3.Transaction({
feePayer: feePayerWallet.publicKey
}).add(
web3.SystemProgram.transfer({
fromPubkey: fromWallet.publicKey,
toPubkey: toWallet.publicKey,
lamports: 10000,
}),
);
// partially sign transaction
let blockhashObj = await connection.getRecentBlockhash();
fundedTransaction.recentBlockhash = await blockhashObj.blockhash;
fundedTransaction.partialSign(fromWallet);// encoding tranaction so that we can send it to backend
let endocdeTransction = fundedTransaction.serialize({
requireAllSignatures: false,
verifySignatures: false,
});
// can be transfered over API to backend if required
endocdeTransction = endocdeTransction.toJSON()
let transactionFromJson = web3.Transaction.from(endcodedTransction);transactionFromJson.partialSign(feePayerWallet);const wireTransaction = transactionFromJson.serialize();
const signature = await this.connection.sendRawTransaction(
wireTransaction,
);

Github repo:

Have any suggestions? Feel free to message me on .

--

--

Software Architect, Full Stack Web developer, MEAN/MERN stack, Microservices, etc

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Riddhesh Ganatra

Software Architect, Full Stack Web developer, MEAN/MERN stack, Microservices, etc