#!/usr/bin/env python3 """Spend ALL of a testnet agent wallet's FLOP in one daily run (40-50 txs). Daily spend-all routine. Run it once a day after the faucet claim, so the wallet never holds unspent FLOP overnight. Proven first by testnet_tip_test.py: a `tip` on an extrinsic is actually charged (0.01 FLOP tip cost 0.012273 FLOP total). So the way to spend huge gas on this chain is the TIP (priority fee to the block author) plus Balances.burn (destroys FLOP directly) plus large payloads/batches (higher length/weight fees). NOTE — contract deploy / mint are NOT possible on FLOP: the chain has NO Contracts, Assets, NFT, or EVM pallets, so there is no contract to deploy and nothing to mint. The 5 kinds below are everything that can take huge gas on this chain. RANDOMISED PER RUN (so no two agents look the same, even though the logic is identical): - tx count: random 40-50 per run. - tx kinds: shuffled, each kind appears at least twice, the rest random. - spend per tx: a RANDOM multiple (0.5x-1.6x) of the fair share, so one tx might spend 0.1 FLOP and the next 0.4 FLOP. The last tx mops up whatever is left. No two runs spend the same fee per tx. - large-remark payload: random 2-8 KB per tx. - batch size: random 2-6 inner calls. - delay between txs: random 2-15 s (desyncs agents from each other). - payload text: random per tx. The script self-corrects: before each tx it re-reads the balance and recomputes the fair share from what is actually left, so it always ends at the reserve no matter how the random amounts fell. Reserve 0.05 FLOP keeps the account alive. 5 kinds: 1. Balances.burn (large value, keep_alive=True) — destroys FLOP. 2. System.remark with high tip. 3. System.remark_with_event with high tip. 4. Utility.batch (2-6 inner remarks) with high tip. 5. System.remark with a LARGE (random 2-8 KB) payload + high tip. Usage: python3 testnet_spend_all.py [--label flop-devnet-test-01] The wallet label selects which wallet in the encrypted store to spend from; the address is read from that wallet entry (never hardcoded). Default store: ~/workspace/flop-wallet/test-wallets/wallets.json.enc (password in ~/workspace/flop-wallet/vault/wallet-password.txt). Override with --store / --pw. These are on-chain fees/burns. They do NOT count as settled inference spend for the airdrop — only inference does. This script spends the balance on-chain because the user ordered it. Never prints the mnemonic or private key. """ import argparse import json import os import random import subprocess import sys import time RPC_URL = "wss://testnet.flop.network" DEFAULT_STORE = os.path.expanduser( "~/workspace/flop-wallet/test-wallets/wallets.json.enc") DEFAULT_PW = os.path.expanduser( "~/workspace/flop-wallet/vault/wallet-password.txt") RESERVE = 5 * 10**16 # 0.05 FLOP left at the end FEE_BUFFER = 3 * 10**15 # 0.003 FLOP, covers the ~0.0023 base fee MIN_PER_TX = 10**16 # 0.01 FLOP — least any tx will spend KINDS = ["burn", "remark", "remark_with_event", "batch", "large_remark"] def decrypt_wallets(store, pw): out = subprocess.run( ["openssl", "enc", "-d", "-aes-256-cbc", "-iter", "200000", "-in", store, "-pass", f"file:{pw}"], capture_output=True, check=True) return json.loads(out.stdout.decode()) def payload(text): return "0x" + text.encode().hex() def rand_payload(label): seq = random.randint(1, 99999) h = os.urandom(16).hex() ts = int(time.time()) tpl = random.choice([ f"spend-all {label} seq={seq} ts={ts}", '{"kind":"spend_all","wallet":"%s","seq":%d}' % (label, seq), f"gas {h[:16]} {label}", ]) return payload(tpl) def build_kinds(num_txs): """Randomised kind list: every kind at least twice, rest random, whole list shuffled so the order differs every run.""" kinds = [] for k in KINDS: kinds.extend([k, k]) while len(kinds) < num_txs: kinds.append(random.choice(KINDS)) random.shuffle(kinds) return kinds def main(): ap = argparse.ArgumentParser(description="Daily spend-all on FLOP testnet") ap.add_argument("--label", default="flop-devnet-test-01", help="wallet label in the encrypted store") ap.add_argument("--store", default=DEFAULT_STORE) ap.add_argument("--pw", default=DEFAULT_PW) ap.add_argument("--reserve-flop", type=float, default=0.05) ap.add_argument("--min-balance", type=float, default=1.0, help="exit without spending if balance is below this (FLOP)") ap.add_argument("--min-txs", type=int, default=40) ap.add_argument("--max-txs", type=int, default=50) args = ap.parse_args() from substrateinterface import SubstrateInterface, Keypair, KeypairType reserve = int(args.reserve_flop * 10**18) wallets = decrypt_wallets(args.store, args.pw) w = next(x for x in wallets if x["label"] == args.label) address = w["address"] kp = Keypair.create_from_mnemonic( w["mnemonic"], ss58_format=42, crypto_type=KeypairType.ED25519) assert kp.ss58_address == address, "derived address mismatch" sub = None last = None for i in range(5): try: sub = SubstrateInterface(url=RPC_URL, ws_options={"timeout": 120}) sub.init_runtime() break except Exception as e: last = e print(f"RPC connect attempt {i + 1} failed ({type(e).__name__}), retrying...") time.sleep(10) if sub is None: raise RuntimeError(f"cannot reach testnet RPC: {last}") def free(): return sub.query("System", "Account", [address])["data"]["free"].value def nonce(): return sub.query("System", "Account", [address])["nonce"].value num_txs = random.randint(args.min_txs, args.max_txs) kinds = build_kinds(num_txs) label = args.label.split("-")[-1] # e.g. "test-01" start_bal = free() if start_bal < int(args.min_balance * 10**18): print(f"balance {start_bal / 10**18:.6f} FLOP < {args.min_balance} FLOP, nothing to spend — exiting.") return 0 print(f"start: balance {start_bal / 10**18:.6f} FLOP, nonce {nonce()}, " f"reserve {reserve / 10**18:.2f} FLOP, {num_txs} txs (random)") ok = 0 counts = {k: 0 for k in KINDS} for i in range(num_txs): kind = kinds[i] txs_left = num_txs - i remaining = max(0, free() - reserve) fair = remaining // txs_left if txs_left else 0 if i == num_txs - 1: # last tx mops up everything left amount = remaining else: # random multiple of the fair share, clamped so later txs # still have at least MIN_PER_TX each amount = int(fair * random.uniform(0.5, 1.6)) cap = remaining - (txs_left - 1) * MIN_PER_TX amount = max(MIN_PER_TX, min(amount, cap)) spend = max(0, amount - FEE_BUFFER) try: if kind == "burn": call = sub.compose_call( "Balances", "burn", {"value": spend, "keep_alive": True}) tip = 0 elif kind == "remark": call = sub.compose_call( "System", "remark", {"remark": rand_payload(label)}) tip = spend elif kind == "remark_with_event": call = sub.compose_call( "System", "remark_with_event", {"remark": rand_payload(label)}) tip = spend elif kind == "batch": inner = [] for _ in range(random.randint(2, 6)): inner.append(sub.compose_call( "System", "remark", {"remark": rand_payload(label)})) call = sub.compose_call("Utility", "batch", {"calls": inner}) tip = spend else: # large_remark — random 2-8 KB payload size = random.randint(2048, 8192) big = "0x" + os.urandom(size).hex() call = sub.compose_call( "System", "remark", {"remark": big}) tip = spend ext = sub.create_signed_extrinsic( call=call, keypair=kp, nonce=nonce(), tip=tip) receipt = sub.submit_extrinsic(ext, wait_for_inclusion=True) if receipt.is_success: ok += 1 counts[kind] += 1 print(f"{i + 1}/{num_txs} {kind}: ok " f"spend~{spend / 10**18:.4f} FLOP " f"block={sub.get_block_number(receipt.block_hash)} " f"bal={free() / 10**18:.4f}") else: print(f"{i + 1}/{num_txs} {kind}: FAILED {receipt.error_message}") except Exception as e: print(f"{i + 1}/{num_txs} {kind}: error {str(e)[:160]}") time.sleep(random.uniform(2, 15)) print(f"done: {ok}/{num_txs} ok counts={counts}") print(f"end: balance {free() / 10**18:.6f} FLOP, nonce {nonce()}") return 0 if ok == num_txs else 1 if __name__ == "__main__": raise SystemExit(main())