Skip to content

Instantly share code, notes, and snippets.

@moviendome
Created September 12, 2021 02:58
Show Gist options
  • Save moviendome/51a0cccd8559050abe84d2cbcb393e4c to your computer and use it in GitHub Desktop.
Save moviendome/51a0cccd8559050abe84d2cbcb393e4c to your computer and use it in GitHub Desktop.
Solana Web3 JS Basic Example
const web3 = require("@solana/web3.js");
console.log("Generate keypair...");
const keypair = web3.Keypair.generate();
console.log("Public Key:", keypair.publicKey.toString());
console.log("Secret Key:", keypair.secretKey);
console.log("\n");
console.log("Connect to Solana...");
const connection = new web3.Connection(web3.clusterApiUrl('devnet'));
(async () => {
console.log("Requesting Airdrop...");
console.log("\n");
const airdrop = await connection.requestAirdrop(keypair.publicKey, web3.LAMPORTS_PER_SOL);
await connection.confirmTransaction(airdrop);
const balance = await connection.getBalance(keypair.publicKey);
console.log(`Balance after airdrop: ${balance/web3.LAMPORTS_PER_SOL} SOL`);
console.log("Send transfer...");
const receiver = web3.Keypair.generate();
const transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: keypair.publicKey,
toPubkey: receiver.publicKey,
lamports: 300000000,
})
);
const signature = await web3.sendAndConfirmTransaction(
connection,
transaction,
[keypair]
);
console.log("Updated balances...");
const balanceSender = await connection.getBalance(keypair.publicKey);
const balanceReceiver = await connection.getBalance(receiver.publicKey);
console.log(`Balance Sender : ${balanceSender/web3.LAMPORTS_PER_SOL} SOL`);
console.log(`Balance Receiver: ${balanceReceiver/web3.LAMPORTS_PER_SOL} SOL`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment