#!/usr/bin/env python3 """SolDuster CLI - close the EMPTY token accounts of a Solana wallet and get the rent back. Made for wallets too large for a browser wallet (trading bots, thousands of accounts). Read this file before running it: it is short on purpose. What it does 1. Lists the token accounts of your wallet (Token and Token-2022 programs). 2. Keeps only accounts with a ZERO balance that are not frozen. Nothing is ever burned. 3. Builds CloseAccount transactions (rent goes back to YOUR wallet) plus one transfer of the SolDuster fee: 10% of the rent up to 1 SOL recovered, 3% above. 4. Without --yes it only prints the summary (dry run). With --yes it signs locally and sends. Your key never leaves this machine: it is only used to sign, with the `solders` library. Usage pip install solders python3 solduster_cli.py --keypair ~/my-wallet.json # dry run python3 solduster_cli.py --keypair ~/my-wallet.json --yes # close for real Options: --rpc URL (your own RPC is faster), --max N (close at most N accounts) The keypair file is either the Solana CLI format (JSON array of 64 numbers) or a base58 secret key. """ import argparse, base64, json, time, urllib.request from solders.hash import Hash from solders.instruction import AccountMeta, Instruction from solders.keypair import Keypair from solders.message import Message from solders.pubkey import Pubkey from solders.system_program import TransferParams, transfer from solders.transaction import Transaction FEE_WALLET = Pubkey.from_string("HtJ9i3BsmakoqAQXXU74zGvPibRpspXETrtP9gZXvqFe") # SolDuster FEE_PCT, FEE_TIER_SOL, FEE_TIER_PCT = 10.0, 1.0, 3.0 PROGRAMS = ("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb") COMPUTE_BUDGET = Pubkey.from_string("ComputeBudget111111111111111111111111111111") PER_TX = 20 # CloseAccount instructions per transaction DEFAULT_RPC = "https://api.mainnet-beta.solana.com" def rpc(url, method, params, tries=5): body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode() err = None for i in range(tries): try: req = urllib.request.Request(url, body, {"Content-Type": "application/json", "User-Agent": "solduster-cli/1"}) with urllib.request.urlopen(req, timeout=60) as r: d = json.load(r) if "error" in d: raise RuntimeError(d["error"].get("message", str(d["error"]))) return d["result"] except Exception as e: # rate limit or network hiccup: wait and retry err = type(e).__name__ if "http" in str(e).lower() else e time.sleep(1.5 * (i + 1)) raise SystemExit(f"RPC error on {method}: {err}") def load_keypair(path): raw = open(path).read().strip() if raw.startswith("["): return Keypair.from_bytes(bytes(json.loads(raw))) return Keypair.from_base58_string(raw) def fee_lamports(gross_lamports): tier = int(FEE_TIER_SOL * 1e9) return int((min(gross_lamports, tier) * FEE_PCT + max(0, gross_lamports - tier) * FEE_TIER_PCT) / 100) def empty_accounts(url, owner): out = [] for prog in PROGRAMS: res = rpc(url, "getTokenAccountsByOwner", [str(owner), {"programId": prog}, {"encoding": "jsonParsed"}]) for a in res["value"]: info = a["account"]["data"]["parsed"]["info"] if info.get("state") != "initialized": # frozen accounts cannot be closed continue if int(info["tokenAmount"]["amount"]) != 0: # never touch an account that holds tokens continue if any((e.get("extension") == "transferFeeAmount" and int((e.get("state") or {}).get("withheldAmount") or 0) > 0) for e in info.get("extensions") or []): # Token-2022 with withheld fees: not closable continue out.append((Pubkey.from_string(a["pubkey"]), Pubkey.from_string(prog), a["account"]["lamports"])) return out def close_ix(account, owner, program): return Instruction(program, bytes([9]), [AccountMeta(account, False, True), AccountMeta(owner, False, True), AccountMeta(owner, True, False)]) def budget_ixs(units, micro_lamports): return [Instruction(COMPUTE_BUDGET, bytes([2]) + units.to_bytes(4, "little"), []), Instruction(COMPUTE_BUDGET, bytes([3]) + micro_lamports.to_bytes(8, "little"), [])] def main(): ap = argparse.ArgumentParser(description="Close empty Solana token accounts and reclaim the rent (SolDuster).") ap.add_argument("--keypair", required=True, help="keypair file (Solana CLI JSON array, or base58 secret key)") ap.add_argument("--rpc", default=DEFAULT_RPC) ap.add_argument("--max", type=int, default=0, help="close at most N accounts (0 = all)") ap.add_argument("--yes", action="store_true", help="really send the transactions (default: dry run)") a = ap.parse_args() kp = load_keypair(a.keypair) owner = kp.pubkey() print(f"Wallet {owner}") accounts = empty_accounts(a.rpc, owner) if a.max: accounts = accounts[:a.max] gross = sum(l for _, _, l in accounts) fee = fee_lamports(gross) n_tx = -(-len(accounts) // PER_TX) print(f"Empty token accounts to close : {len(accounts)}") print(f"Rent returned to your wallet : {gross / 1e9:.6f} SOL") print(f"SolDuster fee : {fee / 1e9:.6f} SOL ({(100 * fee / gross if gross else 0):.2f}%)") print(f"You keep : {(gross - fee) / 1e9:.6f} SOL (minus ~{n_tx * 0.000006:.6f} SOL of network fees)") print(f"Transactions : {n_tx}") if not accounts: return if not a.yes: print("\nDry run: nothing was sent. Add --yes to close these accounts.") return done = closed = paid = 0 failed = [] for i in range(0, len(accounts), PER_TX): batch = accounts[i:i + PER_TX] b_gross = sum(l for _, _, l in batch) b_fee = fee * b_gross // gross # the fee is spread over the transactions, pro rata ixs = budget_ixs(4000 * len(batch) + 2000, 20000) + [close_ix(acc, owner, prog) for acc, prog, _ in batch] if b_fee > 0: ixs.append(transfer(TransferParams(from_pubkey=owner, to_pubkey=FEE_WALLET, lamports=b_fee))) sig = None for attempt in range(3): bh = Hash.from_string(rpc(a.rpc, "getLatestBlockhash", [{"commitment": "confirmed"}])["value"]["blockhash"]) raw = base64.b64encode(bytes(Transaction([kp], Message.new_with_blockhash(ixs, owner, bh), bh))).decode() sim = rpc(a.rpc, "simulateTransaction", [raw, {"encoding": "base64", "commitment": "confirmed"}]) if sim["value"]["err"]: print(f" tx {i // PER_TX + 1}/{n_tx}: simulation failed ({sim['value']['err']}), skipped") break sig = rpc(a.rpc, "sendTransaction", [raw, {"encoding": "base64", "skipPreflight": True, "maxRetries": 5}]) ok = False for _ in range(40): # ~60 s, until the blockhash expires time.sleep(1.5) st = rpc(a.rpc, "getSignatureStatuses", [[sig]])["value"][0] if st and st.get("err"): break if st and st.get("confirmationStatus") in ("confirmed", "finalized"): ok = True break if ok: done += 1; closed += len(batch); paid += b_fee print(f" tx {i // PER_TX + 1}/{n_tx}: {len(batch)} accounts closed https://solscan.io/tx/{sig}") break sig = None if sig is None: failed.append(i // PER_TX + 1) print(f"\nDone: {closed} accounts closed in {done} transactions, fee paid {paid / 1e9:.6f} SOL.") if failed: print(f"Not closed (run again to retry): transactions {failed}") if __name__ == "__main__": main()