Skip to content

Commit

Permalink
feat: add sw3-2.0 transfer sol
Browse files Browse the repository at this point in the history
  • Loading branch information
amilz committed Sep 3, 2024
1 parent e2edf2f commit a4527ee
Show file tree
Hide file tree
Showing 3 changed files with 136 additions and 0 deletions.
104 changes: 104 additions & 0 deletions solana/web3.js-2.0/basics/transferSol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import {
airdropFactory,
createKeyPairSignerFromBytes,
createSolanaRpc,
createSolanaRpcSubscriptions,
generateKeyPairSigner,
lamports,
sendAndConfirmTransactionFactory,
pipe,
createTransactionMessage,
setTransactionMessageFeePayer,
setTransactionMessageLifetimeUsingBlockhash,
appendTransactionMessageInstruction,
signTransactionMessageWithSigners,
getSignatureFromTransaction,
address,
} from "@solana/web3.js";
import { getTransferSolInstruction } from "@solana-program/system";
import user2secret from "./keypair.json"; // Create with `solana-keygen new -o ./keypair.json --no-bip39-passphrase`

const LAMPORTS_PER_SOL = BigInt(1_000_000_000);

async function main() {
// 1 - Establish connection to Solana cluster
// Change as needed to the network you're using.
// Get a free Devnet or Mainnet endpoint from:
// https://www.quicknode.com/signup?utm_source=internal&utm_campaign=sample-apps&utm_content=solana-web3.js-2.0-transfer-sol
const httpProvider = 'http://127.0.0.1:8899';
const wssProvider = 'ws://127.0.0.1:8900';
const rpc = createSolanaRpc(httpProvider);
const rpcSubscriptions = createSolanaRpcSubscriptions(wssProvider);
console.log(`✅ - Established connection to ${httpProvider}`);

// 2 - Generate signers
const user1 = await generateKeyPairSigner();
console.log(`✅ - New user1 address created: ${user1.address}`);
const user2 = await createKeyPairSignerFromBytes(new Uint8Array(user2secret));
console.log(`✅ - user2 address generated from file: ${user2.address}`);

// 3 - Airdrop SOL to accounts
// Using RPC method
const tx1 = await rpc.requestAirdrop(
user1.address,
lamports(LAMPORTS_PER_SOL),
{ commitment: 'processed' }
).send();
console.log(`✅ - user1 airdropped 1 SOL using RPC methods`);
console.log(`✅ - tx1: ${tx1}`);

// Using factory function
const airdrop = airdropFactory({ rpc, rpcSubscriptions });
const tx2 = await airdrop({
commitment: 'processed',
lamports: lamports(LAMPORTS_PER_SOL),
recipientAddress: user2.address
});
console.log(`✅ - user2 airdropped 1 SOL using Factory Function`);
console.log(`✅ - tx2: ${tx2}`);

// 4 - Create transfer transaction
const otherAccount = await generateKeyPairSigner();

const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const transactionMessage = pipe(
createTransactionMessage({ version: 0 }),
tx => setTransactionMessageFeePayer(user1.address, tx),
tx => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
tx => appendTransactionMessageInstruction(
getTransferSolInstruction({
amount: lamports(LAMPORTS_PER_SOL / BigInt(2)),
destination: user2.address,
source: user1,
}),
tx
),
/* OPTIONAL: Uncomment to add another transfer instruction
tx => appendTransactionMessageInstruction(
getTransferSolInstruction({
amount: lamports(LAMPORTS_PER_SOL / BigInt(3)),
destination: address(otherAccount.address),
source: user1,
}),
tx
)
*/
);

// 5 - Sign and send transaction
const signedTransaction = await signTransactionMessageWithSigners(transactionMessage);
const sendAndConfirmTransaction = sendAndConfirmTransactionFactory({ rpc, rpcSubscriptions });

try {
await sendAndConfirmTransaction(
signedTransaction,
{ commitment: 'confirmed', skipPreflight: true }
);
const signature = getSignatureFromTransaction(signedTransaction);
console.log('✅ - Transfer transaction:', signature);
} catch (e) {
console.error('Transfer failed:', e);
}
}

main();
21 changes: 21 additions & 0 deletions solana/web3.js-2.0/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "web3-rc",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@solana-program/compute-budget": "^0.5.0",
"@solana-program/system": "^0.5.0",
"@solana-program/token": "^0.2.1",
"@solana/web3.js": "^2.0.0-rc.1"
},
"devDependencies": {
"@types/node": "^22.5.2"
}
}
11 changes: 11 additions & 0 deletions solana/web3.js-2.0/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}

0 comments on commit a4527ee

Please sign in to comment.