-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (55 loc) · 2.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Import Solana web3 functionalities
const {
Connection,
PublicKey,
clusterApiUrl,
Keypair,
LAMPORTS_PER_SOL
} = require("@solana/web3.js");
// Create a new keypair
const newPair = new Keypair();
// Exact the public and private key from the keypair
const publicKey = new PublicKey(newPair._keypair.publicKey).toString();
const privateKey = newPair._keypair.secretKey;
// Connect to the Devnet
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
console.log("Public Key of the generated keypair", publicKey);
// Get the wallet balance from a given private key
const getWalletBalance = async () => {
try {
// Connect to the Devnet
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
console.log("Connection object is:", connection);
// Make a wallet (keypair) from privateKey and get its balance
const myWallet = await Keypair.fromSecretKey(privateKey);
const walletBalance = await connection.getBalance(
new PublicKey(newPair.publicKey)
);
console.log(`Wallet balance: ${parseInt(walletBalance) / LAMPORTS_PER_SOL} SOL`);
} catch (err) {
console.log(err);
}
};
const airDropSol = async () => {
try {
// Connect to the Devnet and make a wallet from privateKey
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
const myWallet = await Keypair.fromSecretKey(privateKey);
// Request airdrop of 2 SOL to the wallet
console.log("Airdropping some SOL to my wallet!");
const fromAirDropSignature = await connection.requestAirdrop(
new PublicKey(myWallet.publicKey),
2 * LAMPORTS_PER_SOL
);
await connection.confirmTransaction(fromAirDropSignature);
} catch (err) {
console.log(err);
}
};
// Show the wallet balance before and after airdropping SOL
const mainFunction = async () => {
await getWalletBalance();
await airDropSol();
await getWalletBalance();
}
mainFunction();