-
-
Save allenhark/a826ffedd155680075d710df7cae9ba6 to your computer and use it in GitHub Desktop.
Solana Web3 Snippets
This file contains 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 * as web3 from '@solana/web3.js'; | |
// Create connection | |
function createConnection(url = "https://testnet.solana.com") { | |
return new web3.Connection(url); | |
} | |
const connection = createConnection(); | |
// Generate account | |
import * as bip39 from 'bip39'; | |
import nacl from 'tweetnacl'; | |
function generateAccount(mnemonic) { | |
const seed = await bip39.mnemonicToSeed(mnemonic); | |
const keyPair = nacl.sign.keyPair.fromSeed(seed.slice(0, 32)); | |
return new web3.Account(keyPair.secretKey) | |
} | |
const mnemonic = bip39.generateMnemonic(); | |
console.log("Your password:", mnemonic); | |
const account = generateAccount(mnemonic) | |
// Get balance | |
function getBalance(publicKey) { | |
return connection.getBalance(publicKey); | |
} | |
const balance = getBalance(account.publicKey) | |
// Send transaction | |
function sendTransaction(recipientPublicKey, recipientAmount) { | |
const transaction = new web3.Transaction().add(web3.SystemProgram.transfer({ | |
fromPubkey: account.publicKey, | |
toPubkey: new web3.PublicKey(recipientPublicKey), | |
lamports: recipientAmount, | |
})); | |
const signature = await web3.sendAndConfirmTransaction( | |
connection, | |
transaction, | |
[account] | |
); | |
} | |
// Get history | |
// https://solana-labs.github.io/solana-web3.js/class/src/connection.js~Connection.html#instance-method-getConfirmedSignaturesForAddress | |
function getHistory(publicKey, options = { limit: 20 }) { | |
return connection.getConfirmedSignaturesForAddress2.getBalance(publicKey, options); | |
} | |
const history = getHistory(account.publicKey) | |
// Airdrop request | |
// lamports is 0.000000001 of SOL | |
function requestAirdrop(publicKey, lamports = 1000000) { | |
return connection.requestAirdrop(publicKey, lamports) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Allen! Really appreciate you sharing your code with us... I got a question for you, why are you using nacl instead of using Keypair from solana web3? can you implement derivation path using nacl?