File size: 13,052 Bytes
5e5f55c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env python3
"""Rebuild the x402 Pulse dataset files from a data_raw.json snapshot.

Source format (same as /tmp/t18/tools/data_raw.json, queried from HIVE402
D1 table settlement_events on 2026-11-21):

{
  "source": "HIVE402 D1 settlement_events (excluded IS NULL), queried ...",
  "totals": {"tx", "payers", "payees", "amount_atomic", "first", "last"},
  "excluded_sml": {"tx", "payers", "payees", "amount_atomic"},
  "since_nov14": {"payers", "tx", "top10_tx", "top100_tx", "one_tx_payers"},
  "top_payee_since_nov14": {
      "pay_to", "name", "tx", "payers", "amount_atomic", "listed_price_usd"
  },
  "supply_snapshot": {
      "as_of", "endpoints", "operators", "verified_payable",
      "paid_verified_endpoints", "catalog_endpoints_paid_board"
  },
  "daily": [[day_utc, settlements, payers, payees, amount_atomic_usdc, under_1c, under_10c], ...],
  "daily_columns": [...]
}

Weekly refresh:
  1. Re-run the settlement_events aggregation (same exclusions: ScriptMasterLabs
     wallets out, EIP-3009 AuthorizationUsed + USDC transfer to a catalog payTo
     on Base) and write a new data_raw.json in this format.
  2. python scripts/regenerate.py --source data/data_raw.json --out .

This script does not query D1 and does not invent numbers.
"""

from __future__ import annotations

import argparse
import csv
import json
import re
import sys
from datetime import date, datetime, timezone
from pathlib import Path


BASE = "https://hive402.scriptmasterlabs.com"
LICENSE = (
    "CC BY 4.0 — reuse freely with attribution and a link to "
    "https://hive402.scriptmasterlabs.com/reports/{slug}"
)

DAILY_OUT_COLUMNS = [
    "day_utc",
    "settlements",
    "paying_wallets",
    "receiving_seller_wallets",
    "usdc_amount",
    "settlements_under_0.01",
    "settlements_under_0.10",
]


def atomic_to_usdc(amount_atomic: int | float) -> float:
    return round(int(amount_atomic) / 1_000_000, 6)


def share(numer: int, denom: int, dp: int = 4) -> float:
    if denom == 0:
        return 0.0
    return round(numer / denom, dp)


def parse_seller_name(raw: str) -> tuple[str, str | None]:
    m = re.match(r"^(.*?)(?:\s+\(([^()]*)\))?$", raw.strip())
    if not m:
        return raw, None
    name, host = m.group(1).strip(), m.group(2)
    return name, host


def week_sum(daily: list, start: str, end: str) -> int:
    return sum(int(row[1]) for row in daily if start <= row[0] <= end)


def build_report(raw: dict, *, published: str, slug: str) -> dict:
    tot = raw["totals"]
    daily = raw["daily"]
    s14 = raw.get("since_nov14") or {}
    ax1 = raw.get("top_payee_since_nov14") or {}
    sup = raw.get("supply_snapshot") or {}
    excluded = raw.get("excluded_sml") or {}

    tx_all = int(tot["tx"])
    u1 = sum(int(r[5]) for r in daily)
    u10 = sum(int(r[6]) for r in daily)

    # Default comparison windows used by the Nov 2026 edition; for later
    # months the caller can still pass the same raw shape and the script will
    # use the last two complete Mon–Sun weeks in the series when these dates
    # are absent.
    week_now = week_sum(daily, "2026-11-14", "2026-11-20")
    week_prev = week_sum(daily, "2026-11-07", "2026-11-13")
    if week_now == 0 or week_prev == 0:
        week_now, week_prev = last_two_complete_weeks(daily)

    seller_name, seller_host = parse_seller_name(str(ax1.get("name") or ""))
    s14_tx = int(s14.get("tx") or 0)
    wow_multiple = share(week_now, week_prev, 2) if week_prev else None

    daily_out = []
    for row in daily:
        daily_out.append(
            [
                row[0],
                int(row[1]),
                int(row[2]),
                int(row[3]),
                atomic_to_usdc(row[4]),
                int(row[5]),
                int(row[6]),
            ]
        )

    wow_display = f"{week_now / week_prev:.1f}×" if week_prev else "n/a"
    ax1_share = share(int(ax1.get("tx") or 0), s14_tx, 4) if s14_tx else None
    ax1_share_pct = f"{(int(ax1.get('tx') or 0) / s14_tx) * 100:.1f}%" if s14_tx else "n/a"

    quotable = (
        f"x402 settlements to sellers in HIVE402's catalog on Base rose {wow_display} week over week, "
        f"from {week_prev:,} (Nov 7–13, 2026) to {week_now:,} (Nov 14–20, 2026); "
        f"one seller, {seller_name}'s Token Verdict, received {ax1_share_pct} of settlements since Nov 14."
        if seller_name.lower().startswith("ax1") and "2026-11" in slug
        else (
            f"x402 settlements to sellers in HIVE402's catalog on Base rose {wow_display} week over week, "
            f"from {week_prev:,} to {week_now:,}; "
            f"the largest seller, {seller_name or 'n/a'}, received {ax1_share_pct} of settlements in the concentration window."
        )
    )
    # Keep the published Nov 2026 wording exactly when we are regenerating that edition.
    if slug == "x402-pulse-2026-11":
        quotable = (
            f"x402 settlements to sellers in HIVE402's catalog on Base rose {wow_display} week over week, "
            f"from {week_prev:,} (Nov 7–13, 2026) to {week_now:,} (Nov 14–20, 2026); "
            f"one seller, ax1's Token Verdict, received {ax1_share_pct} of settlements since Nov 14."
        )

    report = {
        "title": f"x402 Pulse — {title_from_slug(slug)}",
        "publisher": "Script Master Labs LLC (HIVE402)",
        "url": f"{BASE}/reports/{slug}",
        "published": published,
        "license": LICENSE.format(slug=slug),
        "quotable": quotable,
        "scope": (
            "x402 exact settlements on Base mainnet (eip155:8453): USDC transfers to a payTo wallet "
            "listed in HIVE402's catalog, in a transaction that also emitted the USDC contract's "
            "EIP-3009 AuthorizationUsed event. Covers every facilitator. ScriptMasterLabs' own wallets excluded."
        ),
        "window": {"from": tot.get("first"), "to": tot.get("last")},
        "totals": {
            "settlements": tx_all,
            "paying_wallets": int(tot["payers"]),
            "receiving_seller_wallets": int(tot["payees"]),
            "usdc_amount": round(int(tot["amount_atomic"]) / 1_000_000, 2),
        },
        "excluded_scriptmasterlabs_rows": int(excluded.get("tx") or 0),
        "week_over_week": {
            "nov_7_13": week_prev if slug == "x402-pulse-2026-11" else week_prev,
            "nov_14_20": week_now if slug == "x402-pulse-2026-11" else week_now,
            "previous_week": week_prev,
            "current_week": week_now,
            "multiple": wow_multiple,
        },
        "price_mix": {
            "share_under_0_01": share(u1, tx_all, 4),
            "share_under_0_10": share(u10, tx_all, 4),
        },
        "concentration_since_2026_11_14": {
            "paying_wallets": int(s14.get("payers") or 0),
            "settlements": s14_tx,
            "top10_wallet_share": share(int(s14.get("top10_tx") or 0), s14_tx, 4),
            "top100_wallet_share": share(int(s14.get("top100_tx") or 0), s14_tx, 4),
            "wallets_paying_once": int(s14.get("one_tx_payers") or 0),
        },
        "largest_seller_since_2026_11_14": {
            "name": seller_name,
            "resource_host": seller_host,
            "pay_to": ax1.get("pay_to"),
            "settlements": int(ax1.get("tx") or 0),
            "paying_wallets": int(ax1.get("payers") or 0),
            "listed_price_usdc": ax1.get("listed_price_usd"),
            "share_of_settlements": ax1_share,
        },
        "supply_snapshot": sup,
        "daily_columns": DAILY_OUT_COLUMNS,
        "daily": daily_out,
        "source": raw.get("source"),
        "caveats": (
            NOV_2026_CAVEATS if slug == "x402-pulse-2026-11" else default_caveats(daily, tot.get("last"))
        ),
    }
    return report


def title_from_slug(slug: str) -> str:
    m = re.search(r"(\d{4})-(\d{2})$", slug)
    if not m:
        return slug
    year, month = int(m.group(1)), int(m.group(2))
    return date(year, month, 1).strftime("%B %Y")


def last_two_complete_weeks(daily: list[list]) -> tuple[int, int]:
    """Sum the last two complete UTC Mon–Sun weeks present in the series."""
    days = [row[0] for row in daily]
    if not days:
        return 0, 0
    last = date.fromisoformat(days[-1])
    # Step back to the Sunday of the last complete week (if last is not past Sunday, drop the partial week).
    # Monday=0 ... Sunday=6
    if last.weekday() != 6:
        last_sunday = last.fromordinal(last.toordinal() - last.weekday() - 1)
    else:
        last_sunday = last
    prev_monday = last_sunday.fromordinal(last_sunday.toordinal() - 6)
    prev_sunday = last_sunday.fromordinal(last_sunday.toordinal() - 7)
    prev2_monday = last_sunday.fromordinal(last_sunday.toordinal() - 13)
    week_now = week_sum(daily, prev_monday.isoformat(), last_sunday.isoformat())
    week_prev = week_sum(daily, prev2_monday.isoformat(), prev_sunday.isoformat())
    return week_now, week_prev


NOV_2026_CAVEATS = [
    "Scope is HIVE402's catalog, not all of x402: settlements to sellers HIVE402 does not list are not counted.",
    "The catalog grew during the window (receiving seller wallets per day rose from 14 on Oct 18 to 400+ in November), so early-window growth partly reflects coverage growth. The Nov 14–20 jump happened with coverage similar to early November.",
    "Dollar totals include some large EIP-3009 transfers to listed wallets that may not be API calls (one listed wallet received about $60k from 540 transfers since Nov 14 while listing $0.002 prices). Settlement counts and payer counts are the more reliable measures.",
    "A paying wallet is not a person or an agent; one operator can control many wallets, and one wallet can serve many users.",
    "Nov 21 is a partial day (data through 06:41 UTC).",
]


def default_caveats(daily: list, last_ts: str | None) -> list[str]:
    caveats = [
        "Scope is HIVE402's catalog, not all of x402: settlements to sellers HIVE402 does not list are not counted.",
        "The catalog grew during the window, so early-window growth partly reflects coverage growth.",
        "Dollar totals include some large EIP-3009 transfers to listed wallets that may not be API calls. Settlement counts and payer counts are the more reliable measures.",
        "A paying wallet is not a person or an agent; one operator can control many wallets, and one wallet can serve many users.",
    ]
    if last_ts and daily:
        last_day = daily[-1][0]
        try:
            end = datetime.fromisoformat(last_ts.replace("Z", "+00:00"))
            if end.date().isoformat() == last_day and (end.hour, end.minute) != (23, 59):
                caveats.append(
                    f"{last_day} is a partial day (data through {end.strftime('%H:%M')} UTC)."
                )
        except ValueError:
            pass
    return caveats


def write_csv(path: Path, daily: list[list]) -> None:
    with path.open("w", newline="") as f:
        w = csv.writer(f)
        w.writerow(DAILY_OUT_COLUMNS)
        for row in daily:
            # Match the published CSV's six-decimal USDC formatting.
            out = list(row)
            out[4] = f"{float(out[4]):.6f}"
            w.writerow(out)


def infer_slug(raw: dict, override: str | None) -> str:
    if override:
        return override
    last = (raw.get("daily") or [[None]])[-1][0]
    if last and re.match(r"\d{4}-\d{2}-\d{2}", last):
        return f"x402-pulse-{last[:7]}"
    return "x402-pulse"


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(description="Regenerate the x402 Pulse dataset from data_raw.json")
    p.add_argument("--source", type=Path, default=Path("data/data_raw.json"))
    p.add_argument("--out", type=Path, default=Path("."))
    p.add_argument("--slug", default=None, help="File slug, default x402-pulse-YYYY-MM from the last daily row")
    p.add_argument("--published", default=None, help="ISO date, default today (UTC)")
    args = p.parse_args(argv)

    raw = json.loads(args.source.read_text())
    slug = infer_slug(raw, args.slug)
    published = args.published or datetime.now(timezone.utc).date().isoformat()
    report = build_report(raw, published=published, slug=slug)

    out_data = args.out / "data"
    out_data.mkdir(parents=True, exist_ok=True)
    json_path = out_data / f"{slug}.json"
    csv_path = out_data / f"{slug}.csv"
    json_path.write_text(json.dumps(report, indent=2) + "\n")
    write_csv(csv_path, report["daily"])

    # Keep a copy of the source snapshot next to the outputs when regenerating in place.
    dest_raw = out_data / "data_raw.json"
    if args.source.resolve() != dest_raw.resolve():
        dest_raw.write_text(json.dumps(raw, indent=2) + "\n")

    print(f"wrote {json_path}")
    print(f"wrote {csv_path}")
    print(
        f"totals: {report['totals']['settlements']} settlements, "
        f"{report['totals']['paying_wallets']} paying wallets, "
        f"${report['totals']['usdc_amount']:,.2f} USDC"
    )
    return 0


if __name__ == "__main__":
    sys.exit(main())