Created
September 30, 2024 08:30
-
-
Save Umiiii/abff01cecd0106175129588dfff017f3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
LAMPORTS_PER_SOL, | |
SystemProgram, | |
Transaction, | |
sendAndConfirmTransaction, | |
Keypair, | |
} from "@solana/web3.js"; | |
// Use Playground cluster connection | |
const connection = pg.connection; | |
// Use Playground wallet as sender, generate random keypair as receiver | |
const sender = pg.wallet.keypair; | |
const receiver = new Keypair(); | |
// Check and log balance before transfer | |
const preBalance1 = await connection.getBalance(sender.publicKey); | |
const preBalance2 = await connection.getBalance(receiver.publicKey); | |
console.log("sender prebalance:", preBalance1 / LAMPORTS_PER_SOL); | |
console.log("receiver prebalance:", preBalance2 / LAMPORTS_PER_SOL); | |
console.log("\n"); | |
// Define the amount to transfer | |
const transferAmount = 0.01; // 0.01 SOL | |
// Create a transfer instruction for transferring SOL from wallet_1 to wallet_2 | |
const transferInstruction = SystemProgram.transfer({ | |
fromPubkey: sender.publicKey, | |
toPubkey: receiver.publicKey, | |
lamports: transferAmount * LAMPORTS_PER_SOL, // Convert transferAmount to lamports | |
}); | |
// Add the transfer instruction to a new transaction | |
const transaction = new Transaction().add(transferInstruction); | |
(async () => { | |
const publicKey = receiver.publicKey; | |
connection.onAccountChange( | |
publicKey, | |
(updatedAccountInfo, context) => | |
console.log("Updated account info: ", updatedAccountInfo), | |
"confirmed" | |
); | |
})(); | |
// Send the transaction to the network | |
const transactionSignature = await sendAndConfirmTransaction( | |
connection, | |
transaction, | |
[sender] // signer | |
); | |
// Check and log balance after transfer | |
const postBalance1 = await connection.getBalance(sender.publicKey); | |
const postBalance2 = await connection.getBalance(receiver.publicKey); | |
console.log("sender postbalance:", postBalance1 / LAMPORTS_PER_SOL); | |
console.log("receiver postbalance:", postBalance2 / LAMPORTS_PER_SOL); | |
console.log("\n"); | |
console.log( | |
"Transaction Signature:", | |
`https://explorer.solana.com/tx/${transactionSignature}?cluster=devnet` | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment