Scripts
Every script, shown in full — copy it with the Copy button, or fetch the raw file with curl. All scripts are Python 3 and use the same pattern: Ed25519 keypair from the encrypted wallet store, testnet RPC wss://testnet.flop.network.
Before you run one: every script takes --label (your wallet label in your encrypted store) and --store / --pw — the address is read from your wallet entry, never hardcoded. Default label is flop-devnet-test-01. Never put a seed phrase or private key in a script.
curl -s https://flop-testnet-agent.pages.dev/scripts/testnet_spend_all.py > testnet_spend_all.py
curl -s https://flop-testnet-agent.pages.dev/scripts/claim2.py > claim2.py
claim2.py
raw .pyDaily faucet claim — builds the challenge, signs it with your key, and POSTs it privately to the faucet (10 FLOP). --room falls back to the Technocore bot room. Verifies the balance on-chain afterwards.
#!/usr/bin/env python3
"""Full 2-step FLOP testnet agent claim (claim2).
Usage: python3 claim2.py [--label <wallet-label>] [--room] [--resume <nonce>]
The wallet label selects which wallet in the encrypted store to claim
with; the address and DID are read from that wallet entry (never
hardcoded). Default label flop-devnet-test-01.
PRIMARY PATH — DIRECT (default): the challenge is SELF-CONSTRUCTED.
The faucet's own web UI (faucet.flop.network, decoded 2026-11-25)
builds the challenge itself — 'flop-faucet-agent/v1|<genesis>|<address>|
<nonce>' — signs it with the wallet and POSTs {address, nonce,
signature} (+ client:'faucet-web') to /v1/testnet/agent-claims. The
Technocore bot room is only ONE way to get a challenge; the server
verifies the signature itself. The bot's "5 requests per DID per 24h"
limit does NOT apply to the direct path — it is the bot's own limit,
not the faucet's. The faucet's own limits: 10 FLOP/24h/address,
86400s cooldown, nonce strictly higher than the last used for the
address. Verified 2026-11-25: a direct POST reached the server (503
'Indexer unavailable; retry later' — signature accepted, backend
transiently down), proving the path works.
PROXY (2026-11-25 20:23 IST, user order; dedicated proxy from
20:35 IST): the proxy is used ONLY for the faucet claim POST to
/v1/testnet/agent-claims — NOTHING ELSE. No balance checks (WS RPC
stays direct), no Technocore room posts or reads (direct), no other
site or service, ever. The proxy exists so the faucet sees the
proxy's IP, not the VM's shared egress IP — the VM's IP hit the
faucet's 24h per-IP cooldown ("This IP funded recently") on
2026-11-25 even though test-01 never got a grant. Credentials live
in proxy.txt (0600) in this same hidden_files dir; if proxy.txt is
absent the claim POST falls back to direct.
FALLBACK PATH — BOT ROOM (--room): post a signed `!faucet request`
in /r/flop-testnet-faucet, wait for the bot's challenge reply, sign
it, POST privately. The room post alone pays NOTHING — there is no
payout queue. Use only if the direct path is ever rejected.
The user's own setup runs test-01 only (user decision 2026-11-24
19:13 IST). Wallets 02-10 HELD. Friends run their own wallet via
--label. Never prints the mnemonic, private key, or the challenge
signature (except sending it privately to the faucet over HTTPS in
the claim POST).
"""
import argparse
import base64
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
import urllib.error
import http.client
sys.path.insert(0, "/home/hatch/workspace/flop-wallet/.venv/lib/python3.12/site-packages")
from substrateinterface import SubstrateInterface, Keypair, KeypairType # noqa: E402
from nacl.signing import SigningKey # noqa: E402
import base58 # noqa: E402 (in the venv on sys.path above)
HOME = "/home/hatch"
ENC = os.path.join(HOME, "workspace/flop-wallet/test-wallets/wallets.json.enc")
PW = os.path.join(HOME, "workspace/flop-wallet/vault/wallet-password.txt")
HF = os.path.join(HOME, "workspace/goals/flop-labs-testnet-agent-setup/hidden_files")
PROXY_FILE = os.path.join(HF, "proxy.txt")
# Wallet label / address / DID are resolved in main() from the encrypted
# store by --label (default flop-devnet-test-01); nothing is hardcoded.
LABEL = None
ADDRESS = None
DID = None
ROOM = "flop-testnet-faucet"
ROOM_URL = "https://technocore.chat/r/flop-testnet-faucet"
CLAIM_URL = "https://faucet.flop.network/v1/testnet/agent-claims"
BOT_DID = "did:key:z6MktjwdcBkwC6xo9wi4KY4ckWvn1GQHdQ1qzkaZtWqHAoxs"
GENESIS = "0x918abd58fb16306b30ef3886514cfaebffecb4de43e82b6f8ec4795c43cfd800"
UA = {"User-Agent": "Mozilla/5.0"}
CHALLENGE_RE = re.compile(r'"(flop-faucet-agent/v1\|[^"]+)"')
def load_proxy_opener():
"""Build a urllib opener routing through the saved proxy (proxy.txt).
The faucet's per-IP cooldown is keyed to the source IP, so claims
go out via the user's proxy IP instead of the VM's shared egress
IP. Returns None if no proxy file exists — calls then go direct.
The password is read from the file (0600) and never printed.
"""
try:
cfg = {}
with open(PROXY_FILE) as f:
for line in f:
line = line.strip()
if "=" in line:
k, v = line.split("=", 1)
cfg[k.strip()] = v.strip()
proxy_url = (f"http://{cfg['username']}:{cfg['password']}"
f"@{cfg['host']}:{cfg['port']}")
except Exception as e:
print(f"no proxy configured ({e}) — going direct")
return None
print(f"proxy configured: {cfg['host']}:{cfg['port']} (IP hidden)")
return urllib.request.build_opener(
urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url}))
PROXY_OPENER = load_proxy_opener()
# Set by --direct (main): force the claim POST direct, bypassing the
# proxy even when proxy.txt exists. The 14:27 run uses this (user
# decision 2026-11-26): the VM direct IP lifts ~12:22 IST, the proxy
# IP not until ~20:38 IST, so a direct claim at 14:27 can land hours
# before the proxy one. The 07:19 and 20:41 runs still use the proxy.
FORCE_DIRECT = False
def urlopen(req, timeout=60):
"""Open a URL, via the proxy when configured, else direct.
--direct forces direct even when the proxy is configured."""
if PROXY_OPENER is not None and not FORCE_DIRECT:
return PROXY_OPENER.open(req, timeout=timeout)
return urllib.request.urlopen(req, timeout=timeout)
def decrypt_wallets():
out = subprocess.run(
["openssl", "enc", "-d", "-aes-256-cbc", "-iter", "200000",
"-in", ENC, "-pass", f"file:{PW}"],
capture_output=True, check=True)
return json.loads(out.stdout.decode())
def did_from_pubkey_hex(pubkey_hex):
"""did:key for an Ed25519 public key (multicodec 0xed01 + key).
Verified: reproduces test-01's did:key exactly."""
return "did:key:z" + base58.b58encode(
bytes([0xed, 0x01]) + bytes.fromhex(pubkey_hex)).decode()
def b64url_nopad(b: bytes) -> str:
return base64.urlsafe_b64encode(b).decode().rstrip("=")
def http_get_json(url, tries=3):
# Use curl: urllib hits IncompleteRead on the Technocore room JSON
# (server closes the connection mid-response) and every poll failed
# on 2026-11-25, so the script never saw the room. curl works.
for i in range(tries):
try:
out = subprocess.run(
["curl", "-s", "-m", "30", "-A", "Mozilla/5.0", url],
capture_output=True, check=True, timeout=40)
return json.loads(out.stdout.decode())
except Exception as e:
print(f"GET {url} failed ({e}), retry {i + 1}/{tries}")
time.sleep(5)
raise RuntimeError(f"GET {url} failed after {tries} tries")
def http_post_json(url, payload, tries=3, use_proxy=False):
"""POST JSON. use_proxy=True ONLY for the faucet claim POST
(CLAIM_URL) — the proxy is for faucet claims only, nothing else.
Every other POST (e.g. the Technocore room post) goes direct."""
body = json.dumps(payload).encode()
for i in range(tries):
try:
req = urllib.request.Request(
url, data=body,
headers={"Content-Type": "application/json", **UA},
method="POST")
opener = urlopen if use_proxy else urllib.request.urlopen
with opener(req, timeout=60) as r:
raw = r.read().decode()
print(f"POST {url} -> HTTP {r.status}: {raw[:400]}")
return r.status, json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
raw = e.read().decode()[:400]
print(f"POST {url} -> HTTP {e.code}: {raw}")
if e.code in (400, 401, 403, 404, 422):
return e.code, {"error": raw}
time.sleep(10)
except Exception as e:
print(f"POST {url} failed ({e}), retry {i + 1}/{tries}")
time.sleep(10)
raise RuntimeError(f"POST {url} failed after {tries} tries")
def direct_claim(kp):
"""Self-constructed challenge claim — no bot room needed.
Build the challenge locally (same string the faucet web UI builds),
sign it, POST privately. Retries on 502/503 honoring the server's
retryAfterSeconds. Returns (ok, response, nonce, challenge).
"""
for attempt in range(1, 7):
nonce = str(int(time.time() * 1000))
challenge = f"flop-faucet-agent/v1|{GENESIS}|{ADDRESS}|{nonce}"
sig = SigningKey(kp.private_key).sign(challenge.encode("utf-8")).signature
body = json.dumps({
"client": "faucet-web", "address": ADDRESS,
"nonce": nonce, "signature": "0x" + sig.hex()}).encode()
try:
req = urllib.request.Request(
CLAIM_URL, data=body,
headers={"Content-Type": "application/json", **UA}, method="POST")
with urlopen(req, timeout=60) as r:
raw = r.read().decode()
print(f"direct claim attempt {attempt} -> HTTP {r.status}: {raw[:300]}")
return True, json.loads(raw) if raw else {}, nonce, challenge
except urllib.error.HTTPError as e:
raw = e.read().decode()[:400]
print(f"direct claim attempt {attempt} -> HTTP {e.code}: {raw}")
try:
resp = json.loads(raw)
except Exception:
resp = {"error": raw}
if e.code in (502, 503):
wait = 60
try:
wait = int(resp.get("retryAfterSeconds") or 60)
except Exception:
pass
print(f"faucet busy ({resp.get('reason')}), retrying in {wait + 5}s")
time.sleep(wait + 5)
continue
return False, resp, nonce, challenge
except Exception as e:
print(f"direct claim attempt {attempt} error: {e}")
time.sleep(15)
return False, {"error": "exhausted retries"}, None, None
def check_balance():
"""Return (block, free FLOP) for test-01, or (None, None)."""
for i in range(1, 7):
try:
sub = SubstrateInterface(url="wss://testnet.flop.network")
head = sub.get_chain_head()
blk = sub.get_block_number(head)
acc = sub.query("System", "Account", [ADDRESS], block_hash=head)
f = acc["data"]["free"]
val = getattr(f, "value", None)
if val is None:
val = int(str(f))
return blk, val / 10**18
except Exception as e:
print(f"balance check attempt {i}: {str(e)[:100]}")
time.sleep(30)
return None, None
def main():
global LABEL, ADDRESS, DID, FORCE_DIRECT
ap = argparse.ArgumentParser(description="FLOP testnet agent faucet claim")
ap.add_argument("--label", default="flop-devnet-test-01",
help="wallet label in the encrypted store")
ap.add_argument("--direct", action="store_true",
help="force the claim POST direct, bypassing the proxy")
ap.add_argument("--room", action="store_true",
help="use the Technocore bot room (fallback); default is direct")
ap.add_argument("--resume", default=None,
help="resume a room claim with this nonce")
args = ap.parse_args()
FORCE_DIRECT = args.direct
if FORCE_DIRECT:
print("direct mode: claim POST goes direct, proxy bypassed")
LABEL = args.label
short = LABEL.split("-")[-1]
resume_nonce = args.resume
wallets = decrypt_wallets()
w = next(x for x in wallets if x["label"] == LABEL)
ADDRESS = w["address"]
DID = did_from_pubkey_hex(w["public_key_hex"])
kp = Keypair.create_from_mnemonic(
w["mnemonic"], ss58_format=42, crypto_type=KeypairType.ED25519)
assert kp.ss58_address == ADDRESS, "derived address mismatch"
assert kp.public_key.hex() == w["public_key_hex"], "pubkey mismatch"
print("keypair verified: address + pubkey match stored values")
# Pre-check: don't waste a challenge if already funded today.
blk0, bal0 = check_balance()
print(f"pre-claim balance: block {blk0}, {short} free = {bal0} FLOP")
if bal0 is not None and bal0 >= 10:
print("already funded (>= 10 FLOP) — skipping claim")
return 0
# DIRECT PATH (default): self-constructed challenge, no bot room.
# The bot room is only used with --room (fallback).
if not args.room:
ok, resp, nonce, challenge = direct_claim(kp)
tx = resp.get("txHash") or resp.get("tx_hash") or resp.get("hash")
print(f"direct claim success: {ok}, amount: {resp.get('amount')}, tx: {tx}")
time.sleep(10)
blk1, bal1 = check_balance()
print(f"post-claim balance: block {blk1}, {short} free = {bal1} FLOP")
rec = {
"ts": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
"label": LABEL, "did": DID, "address": ADDRESS,
"method": "direct", "challenge": challenge,
"claim_nonce": nonce, "claim_response": resp, "tx_hash": tx,
"pre_balance": {"block": blk0, "free": bal0},
"post_balance": {"block": blk1, "free": bal1},
"funded": bool(bal1 is not None and bal1 >= 10),
}
with open(os.path.join(HF, "agent-claim-2026-11-25.json"), "w") as f:
json.dump(rec, f, indent=2)
print("record written:", os.path.join(HF, "agent-claim-2026-11-25.json"))
return 0 if rec["funded"] else 3
# ROOM PATH (fallback, --room only) — Step 1: signed room request.
# The room enforces strictly-increasing nonces per DID, and a POST
# can succeed server-side while its response is lost (IncompleteRead).
# So: on an ambiguous POST failure, check the room for our post
# before retrying, and any retry uses a FRESH nonce + fresh signature.
if resume_nonce:
nonce = resume_nonce
text = f"!faucet request {ADDRESS} {nonce}"
print(f"resuming: step-1 post already in room, nonce {nonce}")
else:
nonce = None
for attempt in range(3):
nonce = str(int(time.time() * 1000))
text = f"!faucet request {ADDRESS} {nonce}"
payload = f"{ROOM}|{nonce}|{text}".encode()
sig = SigningKey(kp.private_key).sign(payload).signature
sig_b64 = b64url_nopad(sig)
assert len(sig_b64) == 86, f"sig length {len(sig_b64)}"
try:
# tries=1: main() controls retries (fresh nonce + room check),
# because an internal same-nonce retry would hit the
# strictly-increasing-nonce rule if the first POST landed.
status, _ = http_post_json(
ROOM_URL, {"did": DID, "sig": sig_b64, "nonce": nonce, "text": text},
tries=1)
print(f"step 1 room post -> HTTP {status}, nonce {nonce}")
if status == 200:
break
print(f"step 1 room post rejected (HTTP {status}); retrying with fresh nonce")
except Exception as e:
print(f"step 1 POST ambiguous ({e}) — checking room for our post")
try:
data = http_get_json(ROOM_URL + "?format=json&limit=50")
msgs = data.get("messages") or data.get("records") or []
if any(m.get("text") == text for m in msgs):
print("post IS in the room (response was lost) — proceeding")
break
except Exception as e2:
print(f"room check failed: {e2}")
print("post not found — retrying with fresh nonce")
time.sleep(2)
else:
print("step 1 FAILED: room post not accepted after 3 attempts")
return 1
# Step 2: wait for the bot's challenge reply for our address.
challenge = None
deadline = time.time() + 300
while time.time() < deadline:
time.sleep(5)
try:
data = http_get_json(ROOM_URL + "?format=json&limit=50")
except Exception as e:
print(f"room poll failed: {e}")
continue
msgs = data.get("messages") or data.get("records") or []
for m in msgs:
if m.get("from") != BOT_DID:
continue
t = m.get("text", "")
if "Daily limit reached" in t or "limit reached" in t.lower():
print(f"bot rate-limit reply (seq {m.get('seq')}): {t[:200]}")
print("step 2 FAILED: daily challenge limit reached")
return 2
if ADDRESS not in t:
continue
mm = CHALLENGE_RE.search(t)
if mm:
challenge = mm.group(1)
print(f"step 2 challenge found (seq {m.get('seq')}): {challenge}")
break
if challenge:
break
if not challenge:
print("step 2 FAILED: no bot challenge reply in 5 minutes")
return 2
# Step 3: sign the exact challenge bytes, POST privately.
parts = challenge.split("|")
assert len(parts) == 4 and parts[0] == "flop-faucet-agent/v1", "bad challenge"
assert parts[2] == ADDRESS, f"challenge address mismatch: {parts[2]}"
claim_nonce = parts[3]
csig = SigningKey(kp.private_key).sign(challenge.encode("utf-8")).signature
csig_hex = "0x" + csig.hex()
print(f"step 3 signing challenge (nonce {claim_nonce}) — signature kept private")
status, resp = http_post_json(CLAIM_URL, {
"address": ADDRESS, "nonce": claim_nonce, "signature": csig_hex},
use_proxy=True)
print(f"step 3 claim POST -> HTTP {status}: {json.dumps(resp)[:400]}")
ok = resp.get("success") is True and resp.get("amount") == 10
tx = resp.get("txHash") or resp.get("tx_hash") or resp.get("hash")
print(f"claim success: {ok}, amount: {resp.get('amount')}, tx: {tx}")
# Step 4: verify balance on-chain.
time.sleep(10)
blk1, bal1 = check_balance()
print(f"post-claim balance: block {blk1}, {short} free = {bal1} FLOP")
rec = {
"ts": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
"label": LABEL, "did": DID, "address": ADDRESS,
"room_nonce": nonce, "challenge": challenge,
"claim_nonce": claim_nonce, "claim_http": status,
"claim_response": resp, "tx_hash": tx,
"pre_balance": {"block": blk0, "free": bal0},
"post_balance": {"block": blk1, "free": bal1},
"funded": bool(bal1 is not None and bal1 >= 10),
}
with open(os.path.join(HF, "agent-claim-2026-11-25.json"), "w") as f:
json.dump(rec, f, indent=2)
print("record written:", os.path.join(HF, "agent-claim-2026-11-25.json"))
return 0 if rec["funded"] else 3
if __name__ == "__main__":
raise SystemExit(main())
enroll_devnet.py
raw .pyEnrolls a wallet on the devnet API (api.flop.network) and saves an API key. Inference currently fails — no miner online on devnet.
#!/usr/bin/env python3
"""Enroll a wallet on the FLOP gateway API (api.flop.network) and run a
minimal inference spend to prove the path works.
Usage: python3 enroll_devnet.py [--label <wallet-label>]
The wallet label selects which wallet in the encrypted store to enroll
with; the address is read from that wallet entry (never hardcoded).
Default label flop-devnet-test-01.
NOTE: api.flop.network currently serves DEVNET (its /health reports
network devnet, the challenge says 'devnet gateway key', devnet genesis).
This spends DEVNET FLOP only, not the testnet 10 FLOP, and does not count
toward the testnet airdrop. The testnet gateway (gateway.testnet.flop.network)
is still dead. This is a mechanism test only.
Flow: GET challenge -> sign exact message bytes with test-01 Ed25519 key
-> POST {address, message, signature} to /v1/enroll/wallet -> use the
returned API key for one tiny /v1/chat/completions call (max_tokens 5).
Never prints the mnemonic, private key, or the full API key.
"""
import argparse
import json
import os
import subprocess
import sys
import time
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
ENC = os.path.expanduser("~/workspace/flop-wallet/test-wallets/wallets.json.enc")
PW = os.path.expanduser("~/workspace/flop-wallet/vault/wallet-password.txt")
API = "https://api.flop.network"
KEYFILE = os.path.expanduser(
"~/workspace/goals/flop-labs-testnet-agent-setup/hidden_files/devnet-api-key.txt")
def decrypt_wallets(store=ENC, pw=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 http_json(method, url, payload=None, headers=None):
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
req.add_header("User-Agent", "Mozilla/5.0")
for k, v in (headers or {}).items():
req.add_header(k, v)
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, json.loads(r.read().decode())
except urllib.error.HTTPError as e:
try:
body = json.loads(e.read().decode())
except Exception:
body = {"raw": "unparsable"}
return e.code, body
def main():
global ADDRESS
ap = argparse.ArgumentParser(description="Enroll a wallet on the devnet gateway API")
ap.add_argument("--label", default="flop-devnet-test-01",
help="wallet label in the encrypted store")
ap.add_argument("--store", default=ENC)
ap.add_argument("--pw", default=PW)
args = ap.parse_args()
from substrateinterface import Keypair, KeypairType
from nacl.signing import SigningKey
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"
print("keypair ok:", ADDRESS)
# 1. Fresh challenge (5-min expiry).
status, ch = http_json(
"GET", f"{API}/v1/enroll/wallet/challenge?address={ADDRESS}")
print("challenge status:", status)
if status != 200:
print("challenge failed:", ch)
return 1
message = ch["message"]
print("challenge message first line:", message.splitlines()[0])
print("challenge expires_at:", ch.get("expires_at"))
# 2. Sign the exact message bytes with Ed25519.
sig = SigningKey(kp.private_key).sign(message.encode("utf-8")).signature
sig_hex = "0x" + sig.hex()
print("signed (signature kept private)")
# 3. Enroll.
status, res = http_json("POST", f"{API}/v1/enroll/wallet", {
"address": ADDRESS, "message": message, "signature": sig_hex})
print("enroll status:", status)
print("enroll response:", json.dumps(res)[:600])
if status not in (200, 201):
print("enroll failed")
return 1
# Find the API key in the response (field name may vary).
api_key = None
for k in ("api_key", "key", "token", "gateway_key"):
if isinstance(res.get(k), str):
api_key = res[k]
break
if not api_key and isinstance(res.get("data"), dict):
for k in ("api_key", "key", "token", "gateway_key"):
if isinstance(res["data"].get(k), str):
api_key = res["data"][k]
break
if not api_key:
print("no API key in enroll response; full keys:", list(res.keys()))
return 1
with open(KEYFILE, "w") as f:
f.write(api_key)
os.chmod(KEYFILE, 0o600)
print("api key saved (prefix):", api_key[:8] + "...")
# 4. Minimal inference: tiny prompt, max_tokens 5.
status, comp = http_json("POST", f"{API}/v1/chat/completions", {
"model": "qwen/qwen2.5-0.5b-instruct",
"messages": [{"role": "user", "content": "Say OK"}],
"max_tokens": 5,
}, headers={"Authorization": f"Bearer {api_key}"})
print("chat status:", status)
print("chat response:", json.dumps(comp)[:1200])
return 0
if __name__ == "__main__":
raise SystemExit(main())
testnet_daily30.py
raw .py26 randomised testnet transactions to complete a 30-transaction day (8 remark, 4 remark with event, 6 burn, 8 batch).
#!/usr/bin/env python3
"""Complete 26 more testnet transactions with a wallet (default test-01).
Already done on testnet today (4): System.remark, System.remark_with_event,
Balances.burn, Utility.batch. This script does 26 more randomized ones
(same mix as the devnet runner: remark / remark_with_event / burn / batch),
so the wallet reaches 30 testnet transactions today.
Usage: python3 testnet_daily30.py [--label <wallet-label>]
The wallet label selects which wallet in the encrypted store to use;
the address is read from that wallet entry (never hardcoded).
Default label flop-devnet-test-01.
Pointed at the testnet RPC (wss://testnet.flop.network). One-off run only,
not a cron. These prove the wallet can do the full daily volume on testnet.
They do NOT count as inference spend for the airdrop.
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"
ENC = os.path.expanduser("~/workspace/flop-wallet/test-wallets/wallets.json.enc")
PW = os.path.expanduser("~/workspace/flop-wallet/vault/wallet-password.txt")
N = 26
def decrypt_wallets(store=ENC, pw=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"testnet probe {label} seq={seq} ts={ts}",
'{"kind":"remark_test","wallet":"%s","seq":%d,"note":"throughput check"}' % (label, seq),
f"ping {h[:16]} {label}",
'{"test":"heartbeat","wallet":"%s","id":"%s"}' % (label, h[:12]),
f"0x{h}",
])
return payload(tpl)
def main():
global ADDRESS
ap = argparse.ArgumentParser(description="26 randomised testnet transactions")
ap.add_argument("--label", default="flop-devnet-test-01",
help="wallet label in the encrypted store")
ap.add_argument("--store", default=ENC)
ap.add_argument("--pw", default=PW)
args = ap.parse_args()
from substrateinterface import SubstrateInterface, Keypair, KeypairType
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 nonce():
return sub.query("System", "Account", [ADDRESS])["nonce"].value
def free():
return sub.query("System", "Account", [ADDRESS])["data"]["free"].value
print(f"start: balance {free() / 10**18:.6f} FLOP, nonce {nonce()}")
ok = 0
counts = {"remark": 0, "remark_with_event": 0, "burn": 0, "batch": 0}
for i in range(N):
r = random.random()
try:
if r < 0.45:
kind, pallet, name, params = (
"remark", "System", "remark",
{"remark": rand_payload("test-01")})
elif r < 0.65:
kind, pallet, name, params = (
"remark_with_event", "System", "remark_with_event",
{"remark": rand_payload("test-01")})
elif r < 0.82:
inner = []
for _ in range(random.randint(2, 4)):
if random.random() < 0.85:
inner.append(sub.compose_call(
"System", "remark",
{"remark": rand_payload("test-01")}))
else:
inner.append(sub.compose_call(
"Balances", "burn",
{"value": random.randint(10**14, 10**15),
"keep_alive": True}))
kind, pallet, name, params = (
"batch", "Utility", "batch", {"calls": inner})
else:
kind, pallet, name, params = (
"burn", "Balances", "burn",
{"value": random.randint(10**14, 3 * 10**15),
"keep_alive": True})
call = sub.compose_call(pallet, name, params)
ext = sub.create_signed_extrinsic(
call=call, keypair=kp, nonce=nonce())
receipt = sub.submit_extrinsic(ext, wait_for_inclusion=True)
if receipt.is_success:
ok += 1
counts[kind] += 1
print(f"{i + 1}/{N} {kind}: ok block={sub.get_block_number(receipt.block_hash)} tx={str(receipt.extrinsic_hash)[:18]}...")
else:
print(f"{i + 1}/{N} {kind}: FAILED {receipt.error_message}")
except Exception as e:
print(f"{i + 1}/{N}: error {str(e)[:160]}")
time.sleep(random.uniform(3, 8))
print(f"done: {ok}/{N} ok counts={counts}")
print(f"end: balance {free() / 10**18:.6f} FLOP, nonce {nonce()}")
return 0 if ok == N else 1
if __name__ == "__main__":
raise SystemExit(main())
testnet_devnet_types.py
raw .pyThe other three transaction types on testnet: System.remark_with_event, Balances.burn, Utility.batch.
#!/usr/bin/env python3
"""Do the remaining devnet transaction types on FLOP TESTNET with a wallet
(default test-01), one at a time, exactly like the devnet runner does
(runner.py), but pointed at the testnet RPC (wss://testnet.flop.network).
Usage: python3 testnet_devnet_types.py [--label <wallet-label>]
The wallet label selects which wallet in the encrypted store to use;
the address is read from that wallet entry (never hardcoded).
Default label flop-devnet-test-01.
Already done on testnet: System.remark (block 100855).
This script does the other three types:
1. System.remark_with_event
2. Balances.burn (dust, keep_alive=True)
3. Utility.batch (2x System.remark bundled)
Each is a separate extrinsic; nonce is re-read before each submit.
These prove the wallet can do every devnet transaction type on testnet.
They do NOT count as inference spend for the airdrop.
Never prints the mnemonic or private key.
"""
import argparse
import json
import os
import subprocess
import sys
import time
RPC_URL = "wss://testnet.flop.network"
ENC = os.path.expanduser("~/workspace/flop-wallet/test-wallets/wallets.json.enc")
PW = os.path.expanduser("~/workspace/flop-wallet/vault/wallet-password.txt")
def decrypt_wallets(store=ENC, pw=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 get_nonce(sub):
return sub.query("System", "Account", [ADDRESS])["nonce"].value
def get_free(sub):
return sub.query("System", "Account", [ADDRESS])["data"]["free"].value
def submit(sub, kp, kind, pallet, call_name, params):
nonce = get_nonce(sub)
call = sub.compose_call(pallet, call_name, params)
ext = sub.create_signed_extrinsic(call=call, keypair=kp, nonce=nonce)
receipt = sub.submit_extrinsic(ext, wait_for_inclusion=True)
print(f"{kind}: success={receipt.is_success} "
f"tx={receipt.extrinsic_hash} block={receipt.block_hash and sub.get_block_number(receipt.block_hash)}")
if not receipt.is_success:
print(f" error: {receipt.error_message}")
return receipt.is_success
def main():
global ADDRESS
ap = argparse.ArgumentParser(description="Remaining devnet tx types on FLOP testnet")
ap.add_argument("--label", default="flop-devnet-test-01",
help="wallet label in the encrypted store")
ap.add_argument("--store", default=ENC)
ap.add_argument("--pw", default=PW)
args = ap.parse_args()
from substrateinterface import SubstrateInterface, Keypair, KeypairType
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}")
print(f"start: balance {get_free(sub) / 10**18:.6f} FLOP, nonce {get_nonce(sub)}")
ok = True
# 1. remark_with_event
ok &= submit(sub, kp, "remark_with_event", "System", "remark_with_event",
{"remark": payload("testnet probe test-01 remark_with_event")})
# 2. burn (dust, keep_alive=True)
ok &= submit(sub, kp, "burn", "Balances", "burn",
{"value": 10**14, "keep_alive": True})
# 3. batch of 2 remarks
inner = [
sub.compose_call("System", "remark",
{"remark": payload("testnet probe test-01 batch #1")}),
sub.compose_call("System", "remark",
{"remark": payload("testnet probe test-01 batch #2")}),
]
ok &= submit(sub, kp, "batch(2x remark)", "Utility", "batch",
{"calls": inner})
print(f"end: balance {get_free(sub) / 10**18:.6f} FLOP, nonce {get_nonce(sub)}")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())
testnet_remark.py
raw .pyOne System.remark on testnet — the proof a wallet can transact on the testnet chain.
#!/usr/bin/env python3
"""Single System.remark on FLOP TESTNET with a wallet (default test-01),
exactly like the devnet runner does (runner.py run_wallet), but pointed
at the testnet RPC (wss://testnet.flop.network — the RPC the explorer
testnet.flopscan.io reads from). One transaction only, tiny fee. Proves
the wallet can transact on testnet. Does NOT count as inference spend
(that needs the gateway).
Usage: python3 testnet_remark.py [--label <wallet-label>]
The wallet label selects which wallet in the encrypted store to use;
the address is read from that wallet entry (never hardcoded).
Default label flop-devnet-test-01.
Never prints the mnemonic or private key.
"""
import argparse
import json
import os
import subprocess
import sys
import time
RPC_URL = "wss://testnet.flop.network"
ENC = os.path.expanduser("~/workspace/flop-wallet/test-wallets/wallets.json.enc")
PW = os.path.expanduser("~/workspace/flop-wallet/vault/wallet-password.txt")
def decrypt_wallets(store=ENC, pw=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 main():
global ADDRESS
ap = argparse.ArgumentParser(description="One System.remark on FLOP testnet")
ap.add_argument("--label", default="flop-devnet-test-01",
help="wallet label in the encrypted store")
ap.add_argument("--store", default=ENC)
ap.add_argument("--pw", default=PW)
args = ap.parse_args()
from substrateinterface import SubstrateInterface, Keypair, KeypairType
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"
print("keypair ok:", ADDRESS)
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}")
print("connected, chain head block:", sub.get_block_number(sub.get_chain_head()))
acct = sub.query("System", "Account", [ADDRESS])
free = acct["data"]["free"].value
nonce = acct["nonce"].value
print(f"balance: {free / 10**18:.4f} FLOP, nonce: {nonce}")
payload = "0x" + "testnet probe test-01".encode().hex()
call = sub.compose_call("System", "remark", {"remark": payload})
ext = sub.create_signed_extrinsic(call=call, keypair=kp, nonce=nonce)
print("submitting remark...")
receipt = sub.submit_extrinsic(ext, wait_for_inclusion=True)
print("is_success:", receipt.is_success)
print("extrinsic_hash:", receipt.extrinsic_hash)
print("block_hash:", receipt.block_hash)
if receipt.block_hash:
print("block number:", sub.get_block_number(receipt.block_hash))
if not receipt.is_success:
print("error:", receipt.error_message)
return 1
acct2 = sub.query("System", "Account", [ADDRESS])
print(f"after: balance {acct2['data']['free'].value / 10**18:.6f} FLOP, nonce {acct2['nonce'].value}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
testnet_spend_all.py
raw .pyThe daily spend-all — 40–50 randomised transactions spending ~all of the 10 FLOP in one run; leaves a 0.05 FLOP reserve; exits if the balance is under 1 FLOP.
#!/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())
testnet_tip_test.py
raw .pyTiny tip proof — a 0.01 FLOP tip on a remark costs 0.012273 FLOP total.
#!/usr/bin/env python3
"""Tiny tip test on FLOP TESTNET with a wallet (default test-01): prove that setting a high
`tip` on an extrinsic actually makes the transaction cost that much more.
Does ONE System.remark with a small tip (0.01 FLOP). Reads the balance
before and after and prints the actual cost (fee + tip). If the cost is
~0.01 FLOP above the normal ~0.002 FLOP base fee, the tip mechanism works
and the spend-all script can use it to spend huge amounts per tx.
Usage: python3 testnet_tip_test.py [--label <wallet-label>]
The wallet label selects which wallet in the encrypted store to use;
the address is read from that wallet entry (never hardcoded).
Default label flop-devnet-test-01.
Never prints the mnemonic or private key.
"""
import argparse
import json
import os
import subprocess
import sys
import time
RPC_URL = "wss://testnet.flop.network"
ENC = os.path.expanduser("~/workspace/flop-wallet/test-wallets/wallets.json.enc")
PW = os.path.expanduser("~/workspace/flop-wallet/vault/wallet-password.txt")
TIP = 10**16 # 0.01 FLOP
def decrypt_wallets(store=ENC, pw=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 main():
global ADDRESS
ap = argparse.ArgumentParser(description="Tip test on FLOP testnet")
ap.add_argument("--label", default="flop-devnet-test-01",
help="wallet label in the encrypted store")
ap.add_argument("--store", default=ENC)
ap.add_argument("--pw", default=PW)
args = ap.parse_args()
from substrateinterface import SubstrateInterface, Keypair, KeypairType
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
before = free()
print(f"before: balance {before / 10**18:.6f} FLOP, nonce {nonce()}")
call = sub.compose_call(
"System", "remark",
{"remark": "0x" + "testnet tip test".encode().hex()})
ext = sub.create_signed_extrinsic(
call=call, keypair=kp, nonce=nonce(), tip=TIP)
receipt = sub.submit_extrinsic(ext, wait_for_inclusion=True)
after = free()
cost = before - after
print(f"tip test: success={receipt.is_success} "
f"tx={receipt.extrinsic_hash} "
f"block={sub.get_block_number(receipt.block_hash)}")
print(f"after: balance {after / 10**18:.6f} FLOP, nonce {nonce()}")
print(f"actual cost: {cost / 10**18:.6f} FLOP "
f"(tip was {TIP / 10**18:.6f} FLOP, base fee ~0.002 FLOP)")
if cost >= TIP:
print("TIP WORKS: cost >= tip, the tip was charged.")
else:
print("TIP DID NOT WORK AS EXPECTED: cost < tip.")
return 0 if receipt.is_success else 1
if __name__ == "__main__":
raise SystemExit(main())