Last active
March 13, 2025 12:28
-
-
Save ParsaAminpour/d8af25afdb54e0f6cace3e11b039d005 to your computer and use it in GitHub Desktop.
SPL Token Transfer
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
const { Keypair, Transaction, Connection, PublicKey } = require("@solana/web3.js"); | |
const { getAssociatedTokenAddress, createTransferCheckedInstruction, createAssociatedTokenAccountInstruction } = require("@solana/spl-token"); | |
const { bs58 } = require("@coral-xyz/anchor/dist/cjs/utils/bytes"); | |
const owner = 'AoE9wryGTiVPGAGJ5gZvK2NrmGbPwmKC93JfEGtEifXX' | |
const spltoken = new PublicKey("31PA6pBcHVPgJN5QDDqHzarrkd3uGkGzYmAKigcYWurj"); | |
const sourceWallet = Keypair.fromSecretKey(bs58.decode(owner)); | |
const connection = new Connection("https://api.devnet.solana.com"); | |
const destWallet = new PublicKey("ReplaceWithYourDesireDestination"); | |
const tokens = 2; | |
async function genAta(){ | |
let ata = await getAssociatedTokenAddress( | |
spltoken, | |
destWallet, | |
false | |
); | |
let tx = new Transaction(); | |
tx.add( | |
createAssociatedTokenAccountInstruction( | |
sourceWallet.publicKey, | |
ata, | |
destWallet, | |
spltoken | |
) | |
); | |
console.log(`create ata txhash: ${await connection.sendTransaction(tx, [sourceWallet])}`); | |
await new Promise((resolve) => setTimeout(resolve, 100)); | |
return true; | |
} | |
const solanaTransferSpl = async () => { | |
let amount = tokens * 10 ** 9; | |
let sourceTokenRaw = await getAssociatedTokenAddress( | |
spltoken, | |
sourceWallet.publicKey, | |
false | |
); | |
let destTokenRaw = await getAssociatedTokenAddress( | |
spltoken, | |
destWallet, | |
false | |
); | |
let sourceATA = sourceTokenRaw.toBase58(); | |
let destATA = destTokenRaw.toBase58(); | |
try { | |
let transaction = new Transaction(); | |
transaction.add( | |
createTransferCheckedInstruction( | |
new PublicKey(sourceATA), | |
spltoken, | |
new PublicKey(destATA), | |
sourceWallet.publicKey, | |
amount, | |
9 | |
) | |
) | |
let tx = await connection.sendTransaction(transaction, [sourceWallet]) | |
console.log('Tokens transferred Successfully, Receipt: ' + tx); | |
return; | |
} | |
catch { | |
let generateAta = await genAta(); | |
if (generateAta) { | |
await new Promise((resolve) => setTimeout(resolve, 15000)); | |
solanaTransferSpl(); | |
return; | |
} | |
}; | |
} | |
solanaTransferSpl() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment