Skip to content

Instantly share code, notes, and snippets.

@dimdenGD
Last active January 17, 2025 20:33
Show Gist options
  • Save dimdenGD/07661f2eb129621488843ffba54aff39 to your computer and use it in GitHub Desktop.
Save dimdenGD/07661f2eb129621488843ffba54aff39 to your computer and use it in GitHub Desktop.
Close Solana token accounts and recover rent
import 'dotenv/config';
import { Connection } from '@solana/web3.js';
import { Keypair, Transaction, ComputeBudgetProgram } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID, createCloseAccountInstruction } from '@solana/spl-token';
import bs58 from 'bs58';
const chunks = (array, chunkSize = 20) => {
let res = [];
for (let currentChunk = 0; currentChunk < array.length; currentChunk += chunkSize) {
res.push(array.slice(currentChunk, currentChunk + chunkSize));
}
return res;
};
const wallet = Keypair.fromSecretKey(bs58.decode(process.argv[2] ?? process.env.PRIVATE_KEY));
const connection = new Connection("https://api.mainnet-beta.solana.com");
const tokenAccounts = await connection.getParsedTokenAccountsByOwner(wallet.publicKey, { programId: TOKEN_PROGRAM_ID });
const filteredAccounts = tokenAccounts.value.filter(account => account.account.data.parsed.info.tokenAmount.uiAmount === 0);
let i = 0;
const chs = chunks(filteredAccounts);
for (const chunk of chs) {
const recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
const txn = new Transaction();
const addPriorityFee = ComputeBudgetProgram.setComputeUnitPrice({
microLamports: 100000,
});
txn.add(addPriorityFee);
chunk.forEach(async (account) => {
txn.feePayer = wallet.publicKey;
txn.recentBlockhash = recentBlockhash;
txn.add(createCloseAccountInstruction(account.pubkey, wallet.publicKey, wallet.publicKey));
});
txn.sign(wallet);
const serializedTransaction = txn.serialize();
await connection.sendRawTransaction(serializedTransaction);
i += chunk.length;
console.log(`Closed ${i}/${filteredAccounts.length} accounts`);
await new Promise(resolve => setTimeout(resolve, 3000));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment