#!/usr/bin/env python3 """Convert expected Base USDC payout rows from CSV to the receipt fetcher's JSON.""" import argparse import csv import json import re from pathlib import Path REQUIRED = {"reference", "transaction_hash", "recipient", "amount_usdc"} HASH = re.compile(r"0x[0-9a-f]{64}", re.IGNORECASE) ADDRESS = re.compile(r"0x[0-9a-f]{40}", re.IGNORECASE) USDC = re.compile(r"([0-9]{1,72})(?:\.([0-9]{1,6}))?") LOG_INDEX = re.compile(r"(?:[0-9]{1,20}|0x[0-9a-f]{1,16})", re.IGNORECASE) def convert(path): rows, references, positions = [], set(), set() with path.open(encoding="utf-8-sig", newline="") as data: reader = csv.DictReader(data, strict=True) headers = reader.fieldnames or [] if not REQUIRED.issubset(headers) or len(headers) != len(set(headers)): raise ValueError("CSV requires unique headers including reference, transaction_hash, recipient, and amount_usdc.") for raw in reader: if len(rows) == 200: raise ValueError("Supply at most 200 payout rows.") line = reader.line_num if None in raw or any(raw[key] is None for key in REQUIRED): raise ValueError(f"Line {line} does not match the CSV header.") reference = raw["reference"].strip() transaction = raw["transaction_hash"].strip().lower() recipient = raw["recipient"].strip().lower() amount = USDC.fullmatch(raw["amount_usdc"].strip()) if not reference or len(reference.encode("utf-16-le")) > 200 or reference in references: raise ValueError(f"Line {line} requires a unique reference of 1 to 100 characters.") if not HASH.fullmatch(transaction) or not ADDRESS.fullmatch(recipient): raise ValueError(f"Line {line} requires a valid transaction hash and recipient.") if not amount: raise ValueError(f"Line {line} requires a USDC decimal with up to six fractional digits.") micros = int(amount[1]) * 1_000_000 + int((amount[2] or "").ljust(6, "0")) if not 0 < micros < 2**256: raise ValueError(f"Line {line} has a USDC amount outside the supported range.") item = {"reference": reference, "transaction_hash": transaction, "recipient": recipient, "amount_micros": str(micros)} index = (raw.get("log_index") or "").strip() if index: if not LOG_INDEX.fullmatch(index): raise ValueError(f"Line {line} has an invalid log index.") number = int(index, 16 if index.lower().startswith("0x") else 10) position = (transaction, number) if number >= 2**64 or position in positions: raise ValueError(f"Line {line} has an out-of-range or duplicate log index.") positions.add(position) item["log_index"] = hex(number) references.add(reference) rows.append(item) if not rows: raise ValueError("Supply at least one payout row.") return rows def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("csv", type=Path) args = parser.parse_args() try: print(json.dumps(convert(args.csv), indent=2)) except (OSError, csv.Error, ValueError) as error: parser.exit(1, f"{error}\n") if __name__ == "__main__": main()