Skip to content

Commit

Permalink
Merge pull request #9 from Lwx7832/main
Browse files Browse the repository at this point in the history
add close ATA
  • Loading branch information
XingqiWang authored Jan 25, 2025
2 parents 27b0409 + 8500a3e commit 496a92e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions example-05-closeATA/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
当您的钱包中持有新代币时,都会为其创建一个特定的代币帐户。每次创建一个账户,都会支付约0.002 SOL的租金。本工具可帮你一键退租。
55 changes: 55 additions & 0 deletions example-05-closeATA/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const { Connection, PublicKey, Transaction, SystemProgram, sendAndConfirmTransaction, Keypair } = require("@solana/web3.js");
const SPLTOKEN = require('@solana/spl-token');
const bs58 = require('bs58');

const RPC_ENDPOINT = 'https://aged-stylish-glade.solana-mainnet.quiknode.pro/xxx/';

const connection = new Connection(RPC_ENDPOINT, 'confirmed');

async function closeTokenAccounts(ownerAddress, payerKeyPair) {
const ownerPublicKey = new PublicKey(ownerAddress);

const tokenAccounts = await connection.getTokenAccountsByOwner(ownerPublicKey, { programId: SPLTOKEN.TOKEN_PROGRAM_ID });
const accountInfos = tokenAccounts.value;

const processedAccounts = accountInfos.map(infos => {
//解密getTokenAccountsByOwner返回的令牌账户data信息
const decoded = SPLTOKEN.AccountLayout.decode(infos.account.data);
return {
pubkey: infos.pubkey.toBase58(),
mint: decoded.mint.toBase58(),
lamports: parseInt(infos.account.lamports, 10),//剩余租金
amount: parseInt(decoded.amount, 10), //持币数量
isNative:decoded.isNative.toString(), //是否平台币
closeAuthorityOption: decoded.closeAuthorityOption.toString() //关闭权限 0是关 1是开
};
});

let transaction = new Transaction();
for (let accountinfo of processedAccounts) {
if (accountinfo.isNative == 0 && accountinfo.amount == "0" && accountinfo.closeAuthorityOption == "0") {
// 创建关闭账户的指令
const closeAccountInstruction = SPLTOKEN.createCloseAccountInstruction(
new PublicKey(accountinfo.pubkey),
ownerPublicKey,
ownerPublicKey,
[],
);
transaction.add(closeAccountInstruction);
}
}

try {
const signature = await sendAndConfirmTransaction(connection, transaction, [payerKeyPair]);
console.error('signature:', signature);
} catch (error) {
console.error('交易发送失败:', error);
}
}

const walletPrivateKey = ''; // 发送者私钥
const payerKeyPair = Keypair.fromSecretKey(bs58.decode(walletPrivateKey));

const walletPublic = ''; // 发送者公钥

closeTokenAccounts(walletPublic, payerKeyPair).catch(console.error);

0 comments on commit 496a92e

Please sign in to comment.