-
-
Save stonegao/4856de3b753bcaf284eee0c571183552 to your computer and use it in GitHub Desktop.
Close aux token account
This file contains 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
import * as anchor from "@coral-xyz/anchor"; | |
import { PublicKey, Transaction, ComputeBudgetProgram } from "@solana/web3.js"; | |
import * as token from "@solana/spl-token"; | |
const provider = anchor.AnchorProvider.env(); | |
anchor.setProvider(provider); | |
// Assumes your running with `anchor run closeAux --provider.cluster mainnet --provider.wallet ~/.config/solana/your-key.json` | |
const payer = provider.wallet["payer"]; | |
// Function to transfer all tokens and close the source token account | |
async function transferAllTokensAndClose( | |
sourceAccountPublicKey, | |
tokenMintPublicKey | |
) { | |
const sourceAccountInfo = await token.getAccount( | |
provider.connection, | |
sourceAccountPublicKey | |
); | |
const amount = sourceAccountInfo.amount; | |
const destinationAccount = await token.getOrCreateAssociatedTokenAccount( | |
provider.connection, | |
payer, | |
tokenMintPublicKey, | |
payer.publicKey | |
); | |
const transferIx = token.createTransferInstruction( | |
sourceAccountPublicKey, | |
destinationAccount.address, | |
payer.publicKey, | |
amount | |
); | |
const closeAccountIx = token.createCloseAccountInstruction( | |
sourceAccountPublicKey, | |
payer.publicKey, | |
payer.publicKey | |
); | |
const transaction = new Transaction(); | |
// Set compute unit budget and priority fee | |
transaction.add(ComputeBudgetProgram.setComputeUnitLimit({ units: 30000 })); | |
transaction.add( | |
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1000 }) | |
); | |
transaction.add(transferIx); | |
transaction.add(closeAccountIx); | |
transaction.feePayer = payer.publicKey; | |
transaction.recentBlockhash = ( | |
await provider.connection.getLatestBlockhash() | |
).blockhash; | |
console.log("Sending transfer and close account transaction..."); | |
const result = await provider.sendAndConfirm(transaction, [payer]); | |
return result; | |
} | |
async function main() { | |
// Use `spl-token accounts -v` to get the aux account public key | |
const auxAccountPublicKey = new PublicKey( | |
"[your aux account pubkey here]" | |
); | |
const tokenMintPublicKey = new PublicKey( | |
"[the token mint pubkey here]" | |
); | |
// Transfer all tokens and close the aux account | |
await transferAllTokensAndClose(auxAccountPublicKey, tokenMintPublicKey); | |
console.log("All tokens transferred and aux account closed successfully."); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment