-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspl.js
73 lines (68 loc) · 2.93 KB
/
spl.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
66
67
68
69
70
71
72
73
// Write JavaScript Code
const bs58 = require('bs58');
const {
Connection,
Keypair,
PublicKey,
clusterApiUrl,
} = require("@solana/web3.js");
const fs = require('fs');
const { getOrCreateAssociatedTokenAccount, transfer } = require("@solana/spl-token");
const PRIVATE_KEY = ""; // Your private key in Base58 encoding
// The address of the USDC token on Solana Devnet
const USDC_DEV_PUBLIC_KEY = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
// Convert the private key from Base58 to a byte array and create a Keypair
const senderPrivateKeyBytes = bs58.decode(PRIVATE_KEY);
const senderKeypair = Keypair.fromSecretKey(senderPrivateKeyBytes);
// Create a new connection to the Solana Mainnet
const connection = new Connection(clusterApiUrl("mainnet-beta"), "confirmed");
// Read the rewards.json file
const rewards = JSON.parse(fs.readFileSync('rewards.json', 'utf8'));
(async () => {
try {
// Fetch the sender's USDC token account
const senderTokenAccount = await getOrCreateAssociatedTokenAccount(
connection,
senderKeypair,
new PublicKey(USDC_DEV_PUBLIC_KEY),
senderKeypair.publicKey,
);
for (let i = 0; i < rewards.length; i++) {
// Fetch or create the receiver's associated token account for USDC
const receiverTokenAccount = await getOrCreateAssociatedTokenAccount(
connection,
senderKeypair,
new PublicKey(USDC_DEV_PUBLIC_KEY),
new PublicKey(rewards[i].publicKey),
true, // Allow creating a token account for the receiver if it doesn't exist
);
// Perform the transfer
let signature;
for (let attempt = 0; attempt < 5; attempt++) {
try {
signature = await transfer(
connection,
senderKeypair,
senderTokenAccount.address,
receiverTokenAccount.address,
senderKeypair.publicKey,
rewards[i].amount * 1_000_000,
);
break;
} catch (error) {
console.log(`Error performing the transfer, retrying (${attempt + 1}/5)...`);
if (attempt === 4) {
console.error('Failed to perform the transfer after 5 attempts', error);
throw error;
}
}
}
// Log the transaction signature and the receiver's address
console.log(`Transaction signature: ${signature}`);
console.log(`Sent to address: ${rewards[i].publicKey}`);
console.log(`You can verify the transaction on https://explorer.solana.com/tx/${signature}?cluster=mainnet-beta`);
}
} catch (error) {
console.error("Error performing the transfer:", error);
}
})();