Skip to content

Instantly share code, notes, and snippets.

@munanadi
Created October 27, 2021 23:00
Show Gist options
  • Select an option

  • Save munanadi/52481ddebda0ae1a87bea067086cac07 to your computer and use it in GitHub Desktop.

Select an option

Save munanadi/52481ddebda0ae1a87bea067086cac07 to your computer and use it in GitHub Desktop.
To close Associated Accounts
/*
THIS IS NOT THE IDEAL WAY OF DOING THIS.
SHOULD ONLY RUN THIS IN A LOCAL SECURE ENV
WE ARE EXPLICITLY USING OUR PRIVATE KEY HERE, WHICH IS NOT ADVISABLE.
*/
import { Connection, PublicKey, Keypair, Transaction } from "@solana/web3.js";
import { TOKEN_PROGRAM_ID, Token } from "@solana/spl-token";
const connection = new Connection("https://solana-api.projectserum.com");
// TODO: Get this txn signed from a frontend wallet.
// Explicityl copy pasted `keypair.json` here
const bytes = ["CONTENTS_OFF_KEYPAIR.JSON_GO_HERE"];
const OWNER_ACCOUNT = new PublicKey("PUBKEY_OF_KEYPAIR.JSON");
connection
.getParsedTokenAccountsByOwner(
OWNER_ACCOUNT,
{
programId: TOKEN_PROGRAM_ID
}
)
.then(async (b) => {
// All accounts OWNDER_ACCOUNT holds
const allAccounts = b?.value.map(account => {
let accountAdd = account.pubkey.toString();
let { mint, tokenAmount } = account.account.data.parsed.info;
return {
tokenAccount: accountAdd,
mintAddress: mint,
balance: tokenAmount.uiAmount
};
});
// console.log(allAccounts)
// These are accounts that will have zero balances,
// For example a associated account of an NFT which you sent to someone else
const emptyAccounts = allAccounts.filter(account => account.balance === 0);
console.log("Empty Accounts -> ", emptyAccounts)
// TODO:
// LOOP OVER THE EMPTY ACCOUNT's `tokenAccount` to get rid of it.
let acc = Keypair.fromSecretKey(new Uint8Array(bytes));
// console.log(acc.publicKey.toBase58())
let ix = Token.createCloseAccountInstruction(
TOKEN_PROGRAM_ID,
new PublicKey("TOKEN_ACCOUNT"), // `tokenAccount` will go here as a PublicKey()
OWNER_ACCOUNT,
OWNER_ACCOUNT,
[acc]
)
let tx = new Transaction();
tx.add(ix);
tx.feePayer = acc.publicKey;
tx.recentBlockhash = (await connection.getRecentBlockhash()).blockhash;
// console.log(tx)
let hash = await connection.sendTransaction(tx, [acc], { skipPreflight: true, preflightCommitment: "processed" })
console.log(hash)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment