Is NEAR Intents volume a leading indicator of real usage?

We tested it on 104 weeks of on-chain data. Neither Intents activity nor the NEAR price leads real-user growth. Intents grew while NEAR's own user base shrank: it measures a different population.

Real users (signers plus relayed end users, minus accounts with 1,000+ actions a week) were dominated by one app: KaiChing sub-accounts were 82.9% of all account-weeks and disappeared in April 2026; outside KaiChing, weekly real users fell from 3,699,019 to 284,872 (92.3% lower).

Real users (signers plus relayed end users, minus accounts with 1,000+ actions a week) were dominated by one app: KaiChing sub-accounts were 82.9% of all account-weeks and disappeared in April 2026; outside KaiChing, weekly real users fell from 3,699,019 to 284,872 (92.3% lower).

stage/s1_tx_accounts.sql
-- name: s1_tx_accounts  (HEAVY, run once)
-- One row per (ISO week, signing account): how many transactions it signed that
-- week, how many of them went straight to intents.near, and on how many days it was active.
-- Columns read: block_date, signer_account_id, receiver_account_id (no args/payloads).
-- window: 2024-10-28 .. 2026-10-25 = 104 full ISO weeks (Monday .. Sunday)
CREATE OR REPLACE TABLE `{stage}.s1_tx_accounts` AS
SELECT
  DATE_TRUNC(block_date, ISOWEEK)            AS week,
  signer_account_id                          AS account_id,
  COUNT(*)                                   AS n_tx,
  COUNTIF(receiver_account_id = 'intents.near') AS n_tx_to_intents,
  COUNT(DISTINCT block_date)                 AS active_days
FROM `bigquery-public-data.crypto_near_mainnet_us.transactions`
WHERE block_date BETWEEN '2024-10-28' AND '2026-10-25'
GROUP BY week, account_id
stage/s2_receipt_roles.sql
-- name: s2_receipt_roles  (HEAVY, run once)
-- From receipt-level actions, two things in a single scan:
--   role 'relayed_user'   : DELEGATE_ACTION rows (is_delegate_action = TRUE). On NEAR a
--                           meta-transaction's delegate receipt is addressed to the end
--                           user (receiver); signer/predecessor are the relayer. So the
--                           relayed end user is receipt_receiver_account_id.
--   role 'intents_action' : every action executed on intents.near (all callers: solvers,
--                           relayers, users, token contracts forwarding deposits).
-- Columns read: block_date, is_delegate_action, receipt_receiver_account_id.
-- window: 2024-10-28 .. 2026-10-25 = 104 full ISO weeks
CREATE OR REPLACE TABLE `{stage}.s2_receipt_roles` AS
SELECT
  DATE_TRUNC(block_date, ISOWEEK) AS week,
  IF(is_delegate_action, 'relayed_user', 'intents_action') AS role,
  receipt_receiver_account_id     AS account_id,
  COUNT(*)                        AS n_actions,
  COUNT(DISTINCT block_date)      AS active_days
FROM `bigquery-public-data.crypto_near_mainnet_us.receipt_actions`
WHERE block_date BETWEEN '2024-10-28' AND '2026-10-25'
  AND (is_delegate_action OR receipt_receiver_account_id = 'intents.near')
GROUP BY week, role, account_id
stage/s5_relayed_gapfill.sql
-- name: s5_relayed_gapfill  (HEAVY, run once)
-- Data-quality fix found by probe p7: before late February 2025 the public dataset has
-- DELEGATE_ACTION rows whose is_delegate_action flag is FALSE (on 2025-01-15 every one of
-- them; on 2025-03-15 flag and action_kind agree exactly). s2 keys on the flag, so it
-- misses relayed users in the early weeks. This table re-derives relayed end users from
-- action_kind = 'DELEGATE_ACTION' for the first 18 ISO weeks (through the week in which the
-- flag starts). q1 takes relayed users from s5 for weeks <= 2025-02-24 and from s2 after,
-- so no week is counted from both tables.
-- Columns read: block_date, action_kind, receipt_receiver_account_id.
-- window: 2024-10-28 .. 2025-03-02 (18 ISO weeks)
CREATE OR REPLACE TABLE `{stage}.s5_relayed_gapfill` AS
SELECT
  DATE_TRUNC(block_date, ISOWEEK) AS week,
  receipt_receiver_account_id     AS account_id,
  COUNT(*)                        AS n_actions,
  COUNT(DISTINCT block_date)      AS active_days
FROM `bigquery-public-data.crypto_near_mainnet_us.receipt_actions`
WHERE block_date BETWEEN '2024-10-28' AND '2025-03-02'
  AND action_kind = 'DELEGATE_ACTION'
GROUP BY week, account_id
queries/q1_weekly_usage.sql
-- name: q1_weekly_usage
-- question: Per ISO week, how many accounts used NEAR, split by account family, and how
--           many of them look like real users rather than automation?
-- reads: {stage}.s1_tx_accounts (tx signers), {stage}.s2_receipt_roles (relayed end users
--        + actions on intents.near) and {stage}.s5_relayed_gapfill (relayed end users for
--        the weeks before the dataset's is_delegate_action flag is populated). s2 is ~60 GB,
--        so it is read ONCE, here.
-- relayed source: s5 (action_kind = DELEGATE_ACTION) for weeks <= 2025-02-24, s2 (flag)
--        from 2025-03-03; flagged_relayed_week shows what the flag alone would give.
-- definitions (per week, per account):
--   signer        signed >= 1 transaction
--   relayed       was the end user of >= 1 meta-transaction (DELEGATE_ACTION receiver)
--   users_any     signer OR relayed (distinct accounts; an account counted once)
--   heavy         >= 1000 signed tx + relayed actions in the week (relayers, solvers, bots)
--   users_real    users_any minus heavy
--   users_engaged users_real active on >= 2 distinct days of the week
--   new_users     users_real whose first appearance in the 104-week window is this week
--   retained      users_real that were also active (signer or relayed) the previous week
-- family: account-name pattern (implicit 64-hex, EVM-style 0x, *.tg = HOT, *.sweat = Sweat,
--         *.users.kaiching = KaiChing app sub-accounts (largest relayed suffix, probe p6),
--         other *.near, other). Families partition accounts, so totals = sum over families.
-- fp_*: order-independent content fingerprints of the stage rows read (detects drift).
-- window: 2024-10-28 .. 2026-10-25 (104 ISO weeks)
WITH tx AS (
  SELECT week, account_id, n_tx, n_tx_to_intents, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%d|%d|%d', week, account_id, n_tx, n_tx_to_intents, active_days)) AS fp
  FROM `{stage}.s1_tx_accounts`
  WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
), s2 AS (
  SELECT week, role, account_id, n_actions, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%s|%d|%d', week, role, account_id, n_actions, active_days)) AS fp
  FROM `{stage}.s2_receipt_roles`
  WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
), s5 AS (
  SELECT week, account_id, n_actions, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%d|%d', week, account_id, n_actions, active_days)) AS fp
  FROM `{stage}.s5_relayed_gapfill`
  WHERE week BETWEEN '2024-10-28' AND '2025-02-24'
), intents AS (
  SELECT week,
         SUM(IF(role = 'intents_action', n_actions, 0)) AS intents_actions,
         COUNTIF(role = 'relayed_user')                 AS flagged_relayed,
         BIT_XOR(fp)                                    AS fp_s2
  FROM s2 GROUP BY week
), rel AS (
  SELECT week, account_id, n_actions, active_days, fp FROM s2
  WHERE role = 'relayed_user' AND week >= '2025-03-03'
  UNION ALL
  SELECT week, account_id, n_actions, active_days, fp FROM s5
), acct AS (
  SELECT
    week,
    COALESCE(tx.account_id, rel.account_id)               AS account_id,
    tx.account_id IS NOT NULL                             AS is_signer,
    rel.account_id IS NOT NULL                            AS is_relayed,
    IFNULL(tx.n_tx, 0)                                    AS n_tx,
    IFNULL(tx.n_tx_to_intents, 0)                         AS n_tx_to_intents,
    IFNULL(rel.n_actions, 0)                              AS n_relayed,
    GREATEST(IFNULL(tx.active_days, 0), IFNULL(rel.active_days, 0)) AS days,
    tx.fp AS fp_tx, rel.fp AS fp_rel
  FROM tx FULL OUTER JOIN rel USING (week, account_id)
), first_seen AS (
  SELECT account_id, MIN(week) AS first_week FROM acct
  WHERE n_tx + n_relayed < 1000 GROUP BY account_id
), labeled AS (
  SELECT a.*, f.first_week,
    LAG(a.week) OVER (PARTITION BY a.account_id ORDER BY a.week) = DATE_SUB(a.week, INTERVAL 7 DAY) AS was_active_prev,
    a.n_tx + a.n_relayed >= 1000 AS heavy,
    CASE
      WHEN REGEXP_CONTAINS(a.account_id, r'^[0-9a-f]{64}$') THEN 'implicit'
      WHEN STARTS_WITH(a.account_id, '0x')                 THEN 'evm_0x'
      WHEN ENDS_WITH(a.account_id, '.tg')                  THEN 'hot_tg'
      WHEN ENDS_WITH(a.account_id, '.sweat')               THEN 'sweat'
      WHEN REGEXP_CONTAINS(a.account_id, r'\.users\.(preprod-)?kaiching(\.near)?$') THEN 'kaiching'
      WHEN ENDS_WITH(a.account_id, '.near')                THEN 'named_near'
      ELSE 'other'
    END AS family
  FROM acct a LEFT JOIN first_seen f USING (account_id)
)
SELECT
  l.week,
  l.family,
  COUNT(*)                                                    AS users_any,
  COUNTIF(is_signer)                                          AS signers,
  COUNTIF(is_relayed)                                         AS relayed_users,
  COUNTIF(is_signer AND is_relayed)                           AS signer_and_relayed,
  COUNTIF(heavy)                                              AS heavy_accounts,
  COUNTIF(NOT heavy)                                          AS users_real,
  COUNTIF(NOT heavy AND days >= 2)                            AS users_engaged,
  COUNTIF(NOT heavy AND first_week = l.week)                  AS new_users,
  COUNTIF(NOT heavy AND IFNULL(was_active_prev, FALSE))       AS retained,
  SUM(n_tx)                                                   AS tx_signed,
  SUM(n_relayed)                                              AS relayed_actions,
  COUNTIF(n_tx_to_intents > 0)                                AS intents_tx_signers,
  COUNTIF(n_tx_to_intents > 0 AND NOT heavy)                  AS intents_tx_signers_real,
  SUM(n_tx_to_intents)                                        AS intents_tx,
  ANY_VALUE(i.intents_actions)                                AS intents_actions_week,
  ANY_VALUE(i.flagged_relayed)                                AS flagged_relayed_week,
  BIT_XOR(fp_tx)                                              AS fp_tx,
  BIT_XOR(fp_rel)                                             AS fp_rel,
  ANY_VALUE(i.fp_s2)                                          AS fp_s2_week
FROM labeled l LEFT JOIN intents i USING (week)
GROUP BY l.week, l.family
Intents cross-chain token movements rose from about 489 a week (first quarter) to 255,117 (last quarter) while non-KaiChing users shrank; in levels the two are negatively correlated (-0.77, n = 103 weeks), so they are not measuring the same thing.

Intents cross-chain token movements rose from about 489 a week (first quarter) to 255,117 (last quarter) while non-KaiChing users shrank; in levels the two are negatively correlated (-0.77, n = 103 weeks), so they are not measuring the same thing.

stage/s3_intents_token_flows.sql
-- name: s3_intents_token_flows  (HEAVY, run once)
-- Fungible-token (NEP-141) balance changes of the intents.near account, per week.
-- Cross-chain assets on NEAR Intents are the PoA-bridge tokens *.omft.near (one per
-- source-chain asset). ft_events is clustered on contract_account_id, so the scan is
-- pruned with STARTS_WITH on the chain prefixes seen in a 24-day sample, then filtered
-- exactly with ENDS_WITH('.omft.near'). Prefixes not in the list are missed (see THESIS.md).
-- direction: 'in' = intents.near balance increased, 'out' = decreased (burn = bridge-out).
-- Amounts are raw integer token units (no decimals, no prices).
-- window: 2024-10-28 .. 2026-10-25 = 104 full ISO weeks
CREATE OR REPLACE TABLE `{stage}.s3_intents_token_flows` AS
SELECT
  DATE_TRUNC(block_date, ISOWEEK)                          AS week,
  contract_account_id                                      AS token,
  cause,
  IF(STARTS_WITH(delta_amount, '-'), 'out', 'in')          AS direction,
  involved_account_id                                      AS counterparty,
  COUNT(*)                                                 AS n_events,
  SUM(ABS(CAST(delta_amount AS BIGNUMERIC)))               AS raw_amount
FROM `bigquery-public-data.crypto_near_mainnet_us.ft_events`
WHERE block_date BETWEEN '2024-10-28' AND '2026-10-25'
  AND affected_account_id = 'intents.near'
  AND ENDS_WITH(contract_account_id, '.omft.near')
  AND (   STARTS_WITH(contract_account_id, 'eth')   OR STARTS_WITH(contract_account_id, 'base')
       OR STARTS_WITH(contract_account_id, 'sol')   OR STARTS_WITH(contract_account_id, 'gnosis')
       OR STARTS_WITH(contract_account_id, 'arb')   OR STARTS_WITH(contract_account_id, 'hood')
       OR STARTS_WITH(contract_account_id, 'sui')   OR STARTS_WITH(contract_account_id, 'aptos')
       OR STARTS_WITH(contract_account_id, 'aleo')  OR STARTS_WITH(contract_account_id, 'tron')
       OR STARTS_WITH(contract_account_id, 'bera')  OR STARTS_WITH(contract_account_id, 'plasma')
       OR STARTS_WITH(contract_account_id, 'zec')   OR STARTS_WITH(contract_account_id, 'btc')
       OR STARTS_WITH(contract_account_id, 'xrp')   OR STARTS_WITH(contract_account_id, 'ltc')
       OR STARTS_WITH(contract_account_id, 'qtc')   OR STARTS_WITH(contract_account_id, 'doge')
       OR STARTS_WITH(contract_account_id, 'bch')   OR STARTS_WITH(contract_account_id, 'cardano')
       OR STARTS_WITH(contract_account_id, 'starknet') OR STARTS_WITH(contract_account_id, 'dash')
       OR STARTS_WITH(contract_account_id, 'bsc')   OR STARTS_WITH(contract_account_id, 'avax')
       OR STARTS_WITH(contract_account_id, 'pol')   OR STARTS_WITH(contract_account_id, 'op')
       OR STARTS_WITH(contract_account_id, 'ton')   OR STARTS_WITH(contract_account_id, 'stellar'))
GROUP BY week, token, cause, direction, counterparty
queries/q2_intents_flows.sql
-- name: q2_intents_flows
-- question: Per ISO week, how many cross-chain (PoA-bridge *.omft.near) token movements
--           touched intents.near, in which direction, and from how many counterparties?
-- reads: {stage}.s3_intents_token_flows (tiny). chain = asset prefix before '-' or '.'
--        (eth, sol, btc, tron, ...). Burns (cause ft_burn) are withdrawals back to the
--        source chain. Amounts stay in raw token units (no decimals, no prices).
-- window: 2024-10-28 .. 2026-10-25
SELECT
  week,
  REGEXP_EXTRACT(token, r'^([a-z0-9]+)')                  AS chain,
  COUNT(DISTINCT token)                                   AS tokens,
  SUM(IF(direction = 'in', n_events, 0))                  AS events_in,
  SUM(IF(direction = 'out', n_events, 0))                 AS events_out,
  SUM(IF(cause = 'ft_burn', n_events, 0))                 AS events_burn,
  COUNT(DISTINCT IF(direction = 'in', counterparty, NULL)) AS counterparties_in,
  BIT_XOR(FARM_FINGERPRINT(FORMAT('%t|%s|%s|%s|%s|%d|%t', week, token, cause, direction,
          IFNULL(counterparty, ''), n_events, raw_amount)))  AS fp
FROM `{stage}.s3_intents_token_flows`
WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
GROUP BY week, chain
queries/q1_weekly_usage.sql
-- name: q1_weekly_usage
-- question: Per ISO week, how many accounts used NEAR, split by account family, and how
--           many of them look like real users rather than automation?
-- reads: {stage}.s1_tx_accounts (tx signers), {stage}.s2_receipt_roles (relayed end users
--        + actions on intents.near) and {stage}.s5_relayed_gapfill (relayed end users for
--        the weeks before the dataset's is_delegate_action flag is populated). s2 is ~60 GB,
--        so it is read ONCE, here.
-- relayed source: s5 (action_kind = DELEGATE_ACTION) for weeks <= 2025-02-24, s2 (flag)
--        from 2025-03-03; flagged_relayed_week shows what the flag alone would give.
-- definitions (per week, per account):
--   signer        signed >= 1 transaction
--   relayed       was the end user of >= 1 meta-transaction (DELEGATE_ACTION receiver)
--   users_any     signer OR relayed (distinct accounts; an account counted once)
--   heavy         >= 1000 signed tx + relayed actions in the week (relayers, solvers, bots)
--   users_real    users_any minus heavy
--   users_engaged users_real active on >= 2 distinct days of the week
--   new_users     users_real whose first appearance in the 104-week window is this week
--   retained      users_real that were also active (signer or relayed) the previous week
-- family: account-name pattern (implicit 64-hex, EVM-style 0x, *.tg = HOT, *.sweat = Sweat,
--         *.users.kaiching = KaiChing app sub-accounts (largest relayed suffix, probe p6),
--         other *.near, other). Families partition accounts, so totals = sum over families.
-- fp_*: order-independent content fingerprints of the stage rows read (detects drift).
-- window: 2024-10-28 .. 2026-10-25 (104 ISO weeks)
WITH tx AS (
  SELECT week, account_id, n_tx, n_tx_to_intents, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%d|%d|%d', week, account_id, n_tx, n_tx_to_intents, active_days)) AS fp
  FROM `{stage}.s1_tx_accounts`
  WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
), s2 AS (
  SELECT week, role, account_id, n_actions, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%s|%d|%d', week, role, account_id, n_actions, active_days)) AS fp
  FROM `{stage}.s2_receipt_roles`
  WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
), s5 AS (
  SELECT week, account_id, n_actions, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%d|%d', week, account_id, n_actions, active_days)) AS fp
  FROM `{stage}.s5_relayed_gapfill`
  WHERE week BETWEEN '2024-10-28' AND '2025-02-24'
), intents AS (
  SELECT week,
         SUM(IF(role = 'intents_action', n_actions, 0)) AS intents_actions,
         COUNTIF(role = 'relayed_user')                 AS flagged_relayed,
         BIT_XOR(fp)                                    AS fp_s2
  FROM s2 GROUP BY week
), rel AS (
  SELECT week, account_id, n_actions, active_days, fp FROM s2
  WHERE role = 'relayed_user' AND week >= '2025-03-03'
  UNION ALL
  SELECT week, account_id, n_actions, active_days, fp FROM s5
), acct AS (
  SELECT
    week,
    COALESCE(tx.account_id, rel.account_id)               AS account_id,
    tx.account_id IS NOT NULL                             AS is_signer,
    rel.account_id IS NOT NULL                            AS is_relayed,
    IFNULL(tx.n_tx, 0)                                    AS n_tx,
    IFNULL(tx.n_tx_to_intents, 0)                         AS n_tx_to_intents,
    IFNULL(rel.n_actions, 0)                              AS n_relayed,
    GREATEST(IFNULL(tx.active_days, 0), IFNULL(rel.active_days, 0)) AS days,
    tx.fp AS fp_tx, rel.fp AS fp_rel
  FROM tx FULL OUTER JOIN rel USING (week, account_id)
), first_seen AS (
  SELECT account_id, MIN(week) AS first_week FROM acct
  WHERE n_tx + n_relayed < 1000 GROUP BY account_id
), labeled AS (
  SELECT a.*, f.first_week,
    LAG(a.week) OVER (PARTITION BY a.account_id ORDER BY a.week) = DATE_SUB(a.week, INTERVAL 7 DAY) AS was_active_prev,
    a.n_tx + a.n_relayed >= 1000 AS heavy,
    CASE
      WHEN REGEXP_CONTAINS(a.account_id, r'^[0-9a-f]{64}$') THEN 'implicit'
      WHEN STARTS_WITH(a.account_id, '0x')                 THEN 'evm_0x'
      WHEN ENDS_WITH(a.account_id, '.tg')                  THEN 'hot_tg'
      WHEN ENDS_WITH(a.account_id, '.sweat')               THEN 'sweat'
      WHEN REGEXP_CONTAINS(a.account_id, r'\.users\.(preprod-)?kaiching(\.near)?$') THEN 'kaiching'
      WHEN ENDS_WITH(a.account_id, '.near')                THEN 'named_near'
      ELSE 'other'
    END AS family
  FROM acct a LEFT JOIN first_seen f USING (account_id)
)
SELECT
  l.week,
  l.family,
  COUNT(*)                                                    AS users_any,
  COUNTIF(is_signer)                                          AS signers,
  COUNTIF(is_relayed)                                         AS relayed_users,
  COUNTIF(is_signer AND is_relayed)                           AS signer_and_relayed,
  COUNTIF(heavy)                                              AS heavy_accounts,
  COUNTIF(NOT heavy)                                          AS users_real,
  COUNTIF(NOT heavy AND days >= 2)                            AS users_engaged,
  COUNTIF(NOT heavy AND first_week = l.week)                  AS new_users,
  COUNTIF(NOT heavy AND IFNULL(was_active_prev, FALSE))       AS retained,
  SUM(n_tx)                                                   AS tx_signed,
  SUM(n_relayed)                                              AS relayed_actions,
  COUNTIF(n_tx_to_intents > 0)                                AS intents_tx_signers,
  COUNTIF(n_tx_to_intents > 0 AND NOT heavy)                  AS intents_tx_signers_real,
  SUM(n_tx_to_intents)                                        AS intents_tx,
  ANY_VALUE(i.intents_actions)                                AS intents_actions_week,
  ANY_VALUE(i.flagged_relayed)                                AS flagged_relayed_week,
  BIT_XOR(fp_tx)                                              AS fp_tx,
  BIT_XOR(fp_rel)                                             AS fp_rel,
  ANY_VALUE(i.fp_s2)                                          AS fp_s2_week
FROM labeled l LEFT JOIN intents i USING (week)
GROUP BY l.week, l.family
fetch/near_usdt_weekly.json
{
  "description": "NEAR/USDT weekly candles (Monday 00:00 UTC open = ISO week), 104 closed weeks 2024-10-28 .. 2026-10-25. Binance public klines API, no key. Fallback: CoinGecko public market_chart/range (daily NEAR/USD; weekly close = last daily price of each ISO week). The source actually used is recorded in manifest.json.",
  "sources": [
    {"label": "binance", "url": "https://api.binance.com/api/v3/klines?symbol=NEARUSDT&interval=1w&startTime=1730073600000&endTime=1792972799999&limit=1000"},
    {"label": "binance-data", "url": "https://data-api.binance.vision/api/v3/klines?symbol=NEARUSDT&interval=1w&startTime=1730073600000&endTime=1792972799999&limit=1000"},
    {"label": "coingecko", "url": "https://api.coingecko.com/api/v3/coins/near/market_chart/range?vs_currency=usd&from=1730073600&to=1792972800"}
  ]
}
Week-to-week growth in Intents activity or in the NEAR price does not predict growth in real users 1–8 weeks later: 7 of 144 lead correlations clear the 95% band, about the 7.2 you would expect from noise alone.

Week-to-week growth in Intents activity or in the NEAR price does not predict growth in real users 1–8 weeks later: 7 of 144 lead correlations clear the 95% band, about the 7.2 you would expect from noise alone.

analysis.py
"""Thesis model: is NEAR Intents cross-chain activity a better leading indicator of real
network usage than the NEAR price?

Run by `run.py analyze` (and re-run by `verify-cached`) inside the rs-repro image with
ROOT (the pack) and OUT (where derived CSVs go). Inputs are only results/q*.csv (weekly
aggregates from BigQuery) and raw/near_usdt_weekly.json (public price series). Pure
pandas/numpy, no randomness, fixed rounding -> byte-identical outputs.

Outputs (OUT/):
  a_weekly.csv     the 104-week panel: levels and weekly log growth of every series
  a_xcorr.csv      lead/lag cross-correlations, lags -8..+8, with n and a 95% band
  a_oos.csv        out-of-sample test: AR(1) baseline vs AR(1) + lagged indicator
  a_families.csv   real users by account family, per week (for the stacked chart)
  a_chains.csv     cross-chain events by source chain, whole window
  a_nep245.csv     sampled-day NEP-245 ledger accounts next to same-week Intents signers
  a_facts.csv      every number quoted in THESIS.md / the dashboard, as displayed
"""
import json
from pathlib import Path

import numpy as np
import pandas as pd

ROOT = Path(globals().get("ROOT", Path(__file__).resolve().parent))
OUT = Path(globals().get("OUT", ROOT / "results"))
R = ROOT / "results"

# ---- parameters (also declared in THESIS.md front matter) ---------------------------
WEEKS = 104                 # 2024-10-28 .. 2026-10-25
LAGS = range(-8, 9)         # k > 0: indicator leads usage by k weeks
FIT_END = "2026-02-22"      # first 69 weeks (~16 months) fit, last 35 weeks (~8 months) test
BREAK = 0.5                 # |weekly log growth| above this marks a regime-break week
Z95 = 1.96

# ---- load ----------------------------------------------------------------------------
q1 = pd.read_csv(R / "q1_weekly_usage.csv")
q2 = pd.read_csv(R / "q2_intents_flows.csv")
q3 = pd.read_csv(R / "q3_nep245_sample.csv")
kl = json.loads((ROOT / "raw" / "near_usdt_weekly.json").read_text())

if isinstance(kl, list):        # Binance klines: [open_ms, open, high, low, close, ...]
    price = pd.DataFrame({"week": pd.to_datetime([k[0] for k in kl], unit="ms").strftime("%Y-%m-%d"),
                          "price_close": [float(k[4]) for k in kl]})
else:                           # CoinGecko fallback: {"prices": [[ms, usd], ...]} daily
    p = pd.DataFrame(kl["prices"], columns=["ms", "usd"])
    p["day"] = pd.to_datetime(p.ms, unit="ms")
    p["week"] = (p.day - pd.to_timedelta(p.day.dt.weekday, unit="D")).dt.strftime("%Y-%m-%d")
    price = p.sort_values("ms").groupby("week", as_index=False).usd.last().rename(columns={"usd": "price_close"})

usage_cols = ["users_any", "signers", "relayed_users", "heavy_accounts", "users_real", "users_engaged",
              "new_users", "retained", "tx_signed", "relayed_actions", "intents_tx_signers",
              "intents_tx_signers_real", "intents_tx"]
w = q1.groupby("week")[usage_cols].sum()
w["intents_actions"] = q1.groupby("week").intents_actions_week.first()
core = q1[q1.family != "kaiching"].groupby("week")[["users_real", "users_engaged"]].sum()
w["users_core"] = core.users_real          # real users excluding KaiChing app sub-accounts
w["engaged_core"] = core.users_engaged
xc = q2.groupby("week")[["events_in", "events_out", "events_burn"]].sum()
w = w.join(xc, how="left").fillna({"events_in": 0, "events_out": 0, "events_burn": 0})
w["xchain_events"] = w.events_in + w.events_out
w = w.join(price.set_index("week"), how="left").reset_index()
assert len(w) == WEEKS and w.price_close.notna().all(), "panel must cover all 104 weeks"
w = w.sort_values("week").reset_index(drop=True)


def glog(s):
    s = s.where(s > 0)
    return np.log(s).diff()


SERIES = {  # name -> (column, label)
    "users_real": ("users_real", "Real users (signers + relayed, minus heavy)"),
    "users_core": ("users_core", "Real users excluding KaiChing sub-accounts"),
    "users_engaged": ("users_engaged", "Engaged real users (>= 2 active days)"),
    "xchain_events": ("xchain_events", "Intents cross-chain token movements"),
    "intents_actions": ("intents_actions", "Actions executed on intents.near"),
    "price_close": ("price_close", "NEAR/USDT weekly close"),
}
for name, (col, _) in SERIES.items():
    w[f"g_{name}"] = glog(w[col]).round(6)
TARGETS = ("users_real", "users_core", "users_engaged")
for t in TARGETS:  # regime breaks are flagged per usage series, from that series' own growth
    w[f"break_{t}"] = (w[f"g_{t}"].abs() > BREAK).astype(int)
w["break_week"] = w.break_users_real
w["sample"] = np.where(w.week <= FIT_END, "fit", "test")


# ---- lead/lag cross-correlation --------------------------------------------------------
def xcorr(x, y, k):
    """corr(x[t-k], y[t]); k > 0 means x leads y."""
    a = pd.concat([x.shift(k), y], axis=1).dropna()
    n = len(a)
    if n < 10:
        return np.nan, np.nan, n
    # Spearman = Pearson on average ranks (no scipy in the image)
    rx, ry = a.iloc[:, 0].rank(), a.iloc[:, 1].rank()
    return a.iloc[:, 0].corr(a.iloc[:, 1]), rx.corr(ry), n


rows = []
for target in ("users_real", "users_core", "users_engaged"):
    for ind in ("xchain_events", "intents_actions", "price_close"):
        for drop_breaks in (0, 1):
            y = w[f"g_{target}"].where(w[f"break_{target}"] == 0) if drop_breaks else w[f"g_{target}"]
            for k in LAGS:
                r, rho, n = xcorr(w[f"g_{ind}"], y, k)
                rows.append({"target": target, "indicator": ind, "drop_breaks": drop_breaks, "lag": k,
                             "n": n, "pearson": round(r, 2), "spearman": round(rho, 2),
                             "band95": round(Z95 / np.sqrt(n), 2),
                             "significant": int(abs(r) > Z95 / np.sqrt(n))})
xc = pd.DataFrame(rows)


# ---- out-of-sample test ----------------------------------------------------------------
def ols(X, y):
    X1 = np.column_stack([np.ones(len(X)), X])
    beta, *_ = np.linalg.lstsq(X1, y, rcond=None)
    return beta


def predict(beta, X):
    return np.column_stack([np.ones(len(X)), X]) @ beta


oos = []
for target in ("users_real", "users_core", "users_engaged"):
    for ind in ("xchain_events", "intents_actions", "price_close"):
        for drop_breaks in (0, 1):
            d = pd.DataFrame({"week": w.week, "y": w[f"g_{target}"], "y1": w[f"g_{target}"].shift(1),
                              "brk": w[f"break_{target}"], "x": w[f"g_{ind}"]})
            if drop_breaks:
                d = d[(d.brk == 0) & (d.brk.shift(1).fillna(0) == 0)]
            fit = d[d.week <= FIT_END]
            # lag chosen on the fit sample only: best |corr| among leads 1..8
            cands = []
            for k in range(1, 9):
                f = pd.DataFrame({"y": fit.y, "x": d.x.shift(k).reindex(fit.index)}).dropna()
                cands.append((abs(f.x.corr(f.y)), k))
            best_k = max(cands)[1]
            d = d.assign(xk=w[f"g_{ind}"].shift(best_k).reindex(d.index)).dropna()
            fit, test = d[d.week <= FIT_END], d[d.week > FIT_END]
            b0 = ols(fit[["y1"]].values, fit.y.values)
            b1 = ols(fit[["y1", "xk"]].values, fit.y.values)
            e0 = test.y.values - predict(b0, test[["y1"]].values)
            e1 = test.y.values - predict(b1, test[["y1", "xk"]].values)
            rm0, rm1 = np.sqrt(np.mean(e0 ** 2)), np.sqrt(np.mean(e1 ** 2))
            oos.append({"target": target, "indicator": ind, "drop_breaks": drop_breaks, "lag": best_k,
                        "n_fit": len(fit), "n_test": len(test), "coef_x": round(b1[2], 3),
                        "rmse_ar1": round(rm0, 4), "rmse_with_x": round(rm1, 4),
                        "rmse_ratio": round(rm1 / rm0, 3),
                        "improves": int(rm1 < rm0)})
oos = pd.DataFrame(oos)

# ---- families, chains, NEP-245 ------------------------------------------------------------
fam = q1.pivot(index="week", columns="family", values="users_real").fillna(0).astype(int).reset_index()
chains = (q2.groupby("chain")[["events_in", "events_out", "events_burn"]].sum()
          .assign(events=lambda t: t.events_in + t.events_out).sort_values(["events", "chain"], ascending=[False, True])
          .reset_index())
chains["share_pct"] = (100 * chains.events / chains.events.sum()).round(1)
q3 = q3.copy()
q3["week"] = (pd.to_datetime(q3.block_date) - pd.to_timedelta(pd.to_datetime(q3.block_date).dt.weekday, unit="D")).dt.strftime("%Y-%m-%d")
nep = q3.merge(w[["week", "intents_tx_signers_real", "users_real", "users_core"]], on="week", how="left")
nep["ledger_per_tx_signer"] = (nep.ledger_accounts / nep.intents_tx_signers_real).round(1)
nep = nep[["block_date", "week", "ledger_accounts", "transfer_accounts", "mint_accounts", "burn_accounts",
           "transfer_items", "intents_tx_signers_real", "users_real", "users_core", "ledger_per_tx_signer"]]

# ---- facts quoted in prose ----------------------------------------------------------------
F = {}


def fact(key, value):
    F[key] = value


def row(week):
    return w[w.week == week].iloc[0]


first, last = w.iloc[0], w.iloc[-1]
peak = w.loc[w.users_real.idxmax()]
fact("weeks", len(w))
fact("n_fit_weeks", int((w.week <= FIT_END).sum()))
fact("n_test_weeks", int((w.week > FIT_END).sum()))
fact("users_real_first", int(first.users_real)); fact("users_real_last", int(last.users_real))
fact("users_real_peak", int(peak.users_real)); fact("users_real_peak_week", peak.week)
fact("users_real_fall_x_from_peak", round(peak.users_real / last.users_real, 1))
fact("users_core_first", int(first.users_core)); fact("users_core_last", int(last.users_core))
fact("users_core_fall_pct", round(100 * (1 - last.users_core / first.users_core), 1))
fact("signers_first", int(first.signers)); fact("signers_last", int(last.signers))
fact("price_first", round(first.price_close, 3)); fact("price_last", round(last.price_close, 3))
fact("price_change_pct", round(100 * (last.price_close / first.price_close - 1), 1))
fact("price_min", round(w.price_close.min(), 3)); fact("price_min_week", w.loc[w.price_close.idxmin()].week)
fact("price_max", round(w.price_close.max(), 3)); fact("price_max_week", w.loc[w.price_close.idxmax()].week)
fs = w[w.xchain_events > 0].iloc[0]
fact("xchain_first_week", fs.week)
x_early = w[(w.week >= "2024-11-04") & (w.week <= "2025-01-26")].xchain_events.mean()
x_late = w[w.week >= "2026-08-03"].xchain_events.mean()
fact("xchain_mean_first_quarter", int(round(x_early))); fact("xchain_mean_last_quarter", int(round(x_late)))
fact("xchain_growth_x", round(x_late / x_early, 1))
u_early = w[(w.week >= "2024-11-04") & (w.week <= "2025-01-26")].users_core.mean()
u_late = w[w.week >= "2026-08-03"].users_core.mean()
fact("core_mean_first_quarter", int(round(u_early))); fact("core_mean_last_quarter", int(round(u_late)))
fact("xchain_total", int(w.xchain_events.sum())); fact("xchain_burn_total", int(w.events_burn.sum()))
fact("xchain_peak", int(w.xchain_events.max())); fact("xchain_peak_week", w.loc[w.xchain_events.idxmax()].week)
fact("intents_actions_peak", int(w.intents_actions.max())); fact("intents_actions_peak_week", w.loc[w.intents_actions.idxmax()].week)
fact("n_chains", int(len(chains))); fact("top_chain", chains.iloc[0].chain); fact("top_chain_share_pct", chains.iloc[0].share_pct)
fact("n_break_weeks", int(w.break_week.sum()))
for t in TARGETS:
    fact(f"n_break_weeks|{t}", int(w[f"break_{t}"].sum()))
for wk in w[w.break_week == 1].week:
    fact(f"break_{wk}", round(float(row(wk).g_users_real), 2))
# regime artifacts of the KaiChing app (sub-accounts *.users.kaiching)
kc = q1[q1.family == "kaiching"].set_index("week").reindex(w.week).fillna(0)
for wk in ("2024-10-28", "2025-02-10", "2025-02-17", "2025-02-24", "2026-03-23", "2026-03-30", "2026-04-06",
           "2026-09-21", "2026-09-28", "2026-10-05", "2026-10-12"):
    fact(f"kc_signers_{wk}", int(kc.loc[wk].signers)); fact(f"kc_relayed_{wk}", int(kc.loc[wk].relayed_users))
    fact(f"kc_real_{wk}", int(kc.loc[wk].users_real))
fact("kc_new_2026-09-28", int(kc.loc["2026-09-28"].new_users))
fact("kc_share_users_real_pct", round(100 * kc.users_real.sum() / w.users_real.sum(), 1))
fact("kc_peak_real", int(kc.users_real.max())); fact("kc_peak_week", kc.users_real.idxmax())
kc_weeks = kc[kc.users_real > 0]
fact("kc_weeks_present", int(len(kc_weeks)))
fact("kc_share_peak_week_pct", round(100 * kc.loc[kc.users_real.idxmax()].users_real / w.set_index("week").loc[kc.users_real.idxmax()].users_real, 1))
ov = q1[q1.week == "2025-02-24"]
fact("overlap_s5_relayed", int(ov.relayed_users.sum())); fact("overlap_flag_relayed", int(ov.flagged_relayed_week.iloc[0]))
fact("relayed_first_week", int(first.relayed_users)); fact("relayed_share_first_pct", round(100 * first.relayed_users / first.users_any, 1))
fact("users_any_first", int(first.users_any))
fact("signers_2026-09-21", int(row("2026-09-21").signers)); fact("signers_2026-09-28", int(row("2026-09-28").signers))
fact("signers_2026-10-19", int(row("2026-10-19").signers))
fact("heavy_median", int(w.heavy_accounts.median()))
fact("engaged_share_last_pct", round(100 * last.users_engaged / last.users_real, 1))
# cross-correlation summaries (primary = Pearson, all weeks, k = 1..8 leads)
for target in ("users_real", "users_core", "users_engaged"):
    for ind in ("xchain_events", "intents_actions", "price_close"):
        for db in (0, 1):
            s = xc[(xc.target == target) & (xc.indicator == ind) & (xc.drop_breaks == db)]
            lead = s[s.lag > 0]
            best = lead.loc[lead.pearson.abs().idxmax()]
            tag = f"{target}|{ind}|{'nobreak' if db else 'all'}"
            fact(f"xc_best_lag|{tag}", int(best.lag)); fact(f"xc_best_r|{tag}", best.pearson)
            fact(f"xc_best_n|{tag}", int(best.n)); fact(f"xc_band|{tag}", best.band95)
            fact(f"xc_sig_leads|{tag}", int(lead.significant.sum()))
            fact(f"xc_lag0_r|{tag}", s[s.lag == 0].pearson.iloc[0])
            fact(f"xc_lag0_n|{tag}", int(s[s.lag == 0].n.iloc[0])); fact(f"xc_lag0_band|{tag}", s[s.lag == 0].band95.iloc[0])
            fact(f"xc_lag0_sig|{tag}", int(s[s.lag == 0].significant.iloc[0]))
            fact(f"xc_best_spearman|{tag}", best.spearman)
            fact(f"xc_sig_lags_any|{tag}", int(s.significant.sum()))
for _, o in oos.iterrows():
    tag = f"{o.target}|{o.indicator}|{'nobreak' if o.drop_breaks else 'all'}"
    fact(f"oos_ratio|{tag}", o.rmse_ratio); fact(f"oos_lag|{tag}", int(o.lag))
    fact(f"oos_ntest|{tag}", int(o.n_test)); fact(f"oos_nfit|{tag}", int(o.n_fit))
lead_tests = xc[xc.lag > 0]
fact("lead_tests", int(len(lead_tests)))
fact("lead_tests_significant", int(lead_tests.significant.sum()))
fact("lead_tests_expected_by_chance", round(0.05 * len(lead_tests), 1))
for ind in ("xchain_events", "intents_actions", "price_close"):
    li = lead_tests[lead_tests.indicator == ind]
    fact(f"lead_tests|{ind}", int(len(li))); fact(f"lead_sig|{ind}", int(li.significant.sum()))
    fact(f"lead_sig_pos|{ind}", int(((li.significant == 1) & (li.pearson > 0)).sum()))
    fact(f"lead_max_abs_r|{ind}", float(li.pearson.abs().max()))
fact("oos_improves_xchain", int(oos[oos.indicator == "xchain_events"].improves.sum()))
fact("oos_improves_actions", int(oos[oos.indicator == "intents_actions"].improves.sum()))
fact("oos_improves_price", int(oos[oos.indicator == "price_close"].improves.sum()))
fact("oos_cases_per_indicator", int((oos.indicator == "price_close").sum()))
fact("oos_fits", int(len(oos))); fact("oos_within_3pct", int(((oos.rmse_ratio - 1).abs() <= 0.03).sum()))
fact("oos_best_gain_xchain_pct", round(100 * (1 - oos[oos.indicator == "xchain_events"].rmse_ratio.min()), 1))
fact("oos_ratio_min", float(oos.rmse_ratio.min())); fact("oos_ratio_max", float(oos.rmse_ratio.max()))
lvl = w[w.xchain_events > 0]
fact("level_corr_xchain_core", round(np.log(lvl.xchain_events).corr(np.log(lvl.users_core)), 2))
fact("level_corr_price_core", round(np.log(w.price_close).corr(np.log(w.users_core)), 2))
fact("level_corr_n_xchain", int(len(lvl)))
fact("nep245_days", int(len(q3))); fact("nep245_sample_days_planned", 26)
fact("nep245_ledger_max", int(nep.ledger_accounts.max())); fact("nep245_ledger_max_day", nep.loc[nep.ledger_accounts.idxmax()].block_date)
fact("nep245_ledger_last", int(nep.iloc[-1].ledger_accounts)); fact("nep245_last_day", nep.iloc[-1].block_date)
fact("nep245_ratio_median", round(float(nep.ledger_per_tx_signer.median()), 1))
fact("intents_tx_signers_real_last", int(last.intents_tx_signers_real))

facts = pd.DataFrame({"key": list(F), "value": [F[k] for k in F]})
facts["abs_value"] = [abs(v) if isinstance(v, (int, float, np.integer, np.floating)) else "" for v in facts.value]

# ---- write ------------------------------------------------------------------------------------
OUT.mkdir(parents=True, exist_ok=True)
fmt = dict(index=False, lineterminator="\n", float_format="%.10g")
keep = ["week", "sample", "break_week", "price_close", "users_any", "signers", "relayed_users", "heavy_accounts",
        "users_real", "users_core", "users_engaged", "engaged_core", "new_users", "retained",
        "break_users_core", "break_users_engaged", "intents_tx_signers_real",
        "intents_actions", "xchain_events", "events_in", "events_out", "events_burn"] + [f"g_{n}" for n in SERIES]
w[keep].to_csv(OUT / "a_weekly.csv", **fmt)
xc.to_csv(OUT / "a_xcorr.csv", **fmt)
oos.to_csv(OUT / "a_oos.csv", **fmt)
fam.to_csv(OUT / "a_families.csv", **fmt)
chains.to_csv(OUT / "a_chains.csv", **fmt)
nep.to_csv(OUT / "a_nep245.csv", **fmt)
facts.to_csv(OUT / "a_facts.csv", **fmt)
print(f"analysis: {len(w)} weeks, {len(xc)} correlations, {len(oos)} out-of-sample fits, {len(facts)} facts")
queries/q1_weekly_usage.sql
-- name: q1_weekly_usage
-- question: Per ISO week, how many accounts used NEAR, split by account family, and how
--           many of them look like real users rather than automation?
-- reads: {stage}.s1_tx_accounts (tx signers), {stage}.s2_receipt_roles (relayed end users
--        + actions on intents.near) and {stage}.s5_relayed_gapfill (relayed end users for
--        the weeks before the dataset's is_delegate_action flag is populated). s2 is ~60 GB,
--        so it is read ONCE, here.
-- relayed source: s5 (action_kind = DELEGATE_ACTION) for weeks <= 2025-02-24, s2 (flag)
--        from 2025-03-03; flagged_relayed_week shows what the flag alone would give.
-- definitions (per week, per account):
--   signer        signed >= 1 transaction
--   relayed       was the end user of >= 1 meta-transaction (DELEGATE_ACTION receiver)
--   users_any     signer OR relayed (distinct accounts; an account counted once)
--   heavy         >= 1000 signed tx + relayed actions in the week (relayers, solvers, bots)
--   users_real    users_any minus heavy
--   users_engaged users_real active on >= 2 distinct days of the week
--   new_users     users_real whose first appearance in the 104-week window is this week
--   retained      users_real that were also active (signer or relayed) the previous week
-- family: account-name pattern (implicit 64-hex, EVM-style 0x, *.tg = HOT, *.sweat = Sweat,
--         *.users.kaiching = KaiChing app sub-accounts (largest relayed suffix, probe p6),
--         other *.near, other). Families partition accounts, so totals = sum over families.
-- fp_*: order-independent content fingerprints of the stage rows read (detects drift).
-- window: 2024-10-28 .. 2026-10-25 (104 ISO weeks)
WITH tx AS (
  SELECT week, account_id, n_tx, n_tx_to_intents, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%d|%d|%d', week, account_id, n_tx, n_tx_to_intents, active_days)) AS fp
  FROM `{stage}.s1_tx_accounts`
  WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
), s2 AS (
  SELECT week, role, account_id, n_actions, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%s|%d|%d', week, role, account_id, n_actions, active_days)) AS fp
  FROM `{stage}.s2_receipt_roles`
  WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
), s5 AS (
  SELECT week, account_id, n_actions, active_days,
         FARM_FINGERPRINT(FORMAT('%t|%s|%d|%d', week, account_id, n_actions, active_days)) AS fp
  FROM `{stage}.s5_relayed_gapfill`
  WHERE week BETWEEN '2024-10-28' AND '2025-02-24'
), intents AS (
  SELECT week,
         SUM(IF(role = 'intents_action', n_actions, 0)) AS intents_actions,
         COUNTIF(role = 'relayed_user')                 AS flagged_relayed,
         BIT_XOR(fp)                                    AS fp_s2
  FROM s2 GROUP BY week
), rel AS (
  SELECT week, account_id, n_actions, active_days, fp FROM s2
  WHERE role = 'relayed_user' AND week >= '2025-03-03'
  UNION ALL
  SELECT week, account_id, n_actions, active_days, fp FROM s5
), acct AS (
  SELECT
    week,
    COALESCE(tx.account_id, rel.account_id)               AS account_id,
    tx.account_id IS NOT NULL                             AS is_signer,
    rel.account_id IS NOT NULL                            AS is_relayed,
    IFNULL(tx.n_tx, 0)                                    AS n_tx,
    IFNULL(tx.n_tx_to_intents, 0)                         AS n_tx_to_intents,
    IFNULL(rel.n_actions, 0)                              AS n_relayed,
    GREATEST(IFNULL(tx.active_days, 0), IFNULL(rel.active_days, 0)) AS days,
    tx.fp AS fp_tx, rel.fp AS fp_rel
  FROM tx FULL OUTER JOIN rel USING (week, account_id)
), first_seen AS (
  SELECT account_id, MIN(week) AS first_week FROM acct
  WHERE n_tx + n_relayed < 1000 GROUP BY account_id
), labeled AS (
  SELECT a.*, f.first_week,
    LAG(a.week) OVER (PARTITION BY a.account_id ORDER BY a.week) = DATE_SUB(a.week, INTERVAL 7 DAY) AS was_active_prev,
    a.n_tx + a.n_relayed >= 1000 AS heavy,
    CASE
      WHEN REGEXP_CONTAINS(a.account_id, r'^[0-9a-f]{64}$') THEN 'implicit'
      WHEN STARTS_WITH(a.account_id, '0x')                 THEN 'evm_0x'
      WHEN ENDS_WITH(a.account_id, '.tg')                  THEN 'hot_tg'
      WHEN ENDS_WITH(a.account_id, '.sweat')               THEN 'sweat'
      WHEN REGEXP_CONTAINS(a.account_id, r'\.users\.(preprod-)?kaiching(\.near)?$') THEN 'kaiching'
      WHEN ENDS_WITH(a.account_id, '.near')                THEN 'named_near'
      ELSE 'other'
    END AS family
  FROM acct a LEFT JOIN first_seen f USING (account_id)
)
SELECT
  l.week,
  l.family,
  COUNT(*)                                                    AS users_any,
  COUNTIF(is_signer)                                          AS signers,
  COUNTIF(is_relayed)                                         AS relayed_users,
  COUNTIF(is_signer AND is_relayed)                           AS signer_and_relayed,
  COUNTIF(heavy)                                              AS heavy_accounts,
  COUNTIF(NOT heavy)                                          AS users_real,
  COUNTIF(NOT heavy AND days >= 2)                            AS users_engaged,
  COUNTIF(NOT heavy AND first_week = l.week)                  AS new_users,
  COUNTIF(NOT heavy AND IFNULL(was_active_prev, FALSE))       AS retained,
  SUM(n_tx)                                                   AS tx_signed,
  SUM(n_relayed)                                              AS relayed_actions,
  COUNTIF(n_tx_to_intents > 0)                                AS intents_tx_signers,
  COUNTIF(n_tx_to_intents > 0 AND NOT heavy)                  AS intents_tx_signers_real,
  SUM(n_tx_to_intents)                                        AS intents_tx,
  ANY_VALUE(i.intents_actions)                                AS intents_actions_week,
  ANY_VALUE(i.flagged_relayed)                                AS flagged_relayed_week,
  BIT_XOR(fp_tx)                                              AS fp_tx,
  BIT_XOR(fp_rel)                                             AS fp_rel,
  ANY_VALUE(i.fp_s2)                                          AS fp_s2_week
FROM labeled l LEFT JOIN intents i USING (week)
GROUP BY l.week, l.family
queries/q2_intents_flows.sql
-- name: q2_intents_flows
-- question: Per ISO week, how many cross-chain (PoA-bridge *.omft.near) token movements
--           touched intents.near, in which direction, and from how many counterparties?
-- reads: {stage}.s3_intents_token_flows (tiny). chain = asset prefix before '-' or '.'
--        (eth, sol, btc, tron, ...). Burns (cause ft_burn) are withdrawals back to the
--        source chain. Amounts stay in raw token units (no decimals, no prices).
-- window: 2024-10-28 .. 2026-10-25
SELECT
  week,
  REGEXP_EXTRACT(token, r'^([a-z0-9]+)')                  AS chain,
  COUNT(DISTINCT token)                                   AS tokens,
  SUM(IF(direction = 'in', n_events, 0))                  AS events_in,
  SUM(IF(direction = 'out', n_events, 0))                 AS events_out,
  SUM(IF(cause = 'ft_burn', n_events, 0))                 AS events_burn,
  COUNT(DISTINCT IF(direction = 'in', counterparty, NULL)) AS counterparties_in,
  BIT_XOR(FARM_FINGERPRINT(FORMAT('%t|%s|%s|%s|%s|%d|%t', week, token, cause, direction,
          IFNULL(counterparty, ''), n_events, raw_amount)))  AS fp
FROM `{stage}.s3_intents_token_flows`
WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
GROUP BY week, chain
Trained on the first 69 weeks and tested on the last 35, adding Intents activity or price to a simple autoregression never helps consistently: forecast error ranges from 6% better to 16% worse (RMSE ratios 0.939 to 1.163), and most cases are within 3%.

Trained on the first 69 weeks and tested on the last 35, adding Intents activity or price to a simple autoregression never helps consistently: forecast error ranges from 6% better to 16% worse (RMSE ratios 0.939 to 1.163), and most cases are within 3%.

analysis.py
"""Thesis model: is NEAR Intents cross-chain activity a better leading indicator of real
network usage than the NEAR price?

Run by `run.py analyze` (and re-run by `verify-cached`) inside the rs-repro image with
ROOT (the pack) and OUT (where derived CSVs go). Inputs are only results/q*.csv (weekly
aggregates from BigQuery) and raw/near_usdt_weekly.json (public price series). Pure
pandas/numpy, no randomness, fixed rounding -> byte-identical outputs.

Outputs (OUT/):
  a_weekly.csv     the 104-week panel: levels and weekly log growth of every series
  a_xcorr.csv      lead/lag cross-correlations, lags -8..+8, with n and a 95% band
  a_oos.csv        out-of-sample test: AR(1) baseline vs AR(1) + lagged indicator
  a_families.csv   real users by account family, per week (for the stacked chart)
  a_chains.csv     cross-chain events by source chain, whole window
  a_nep245.csv     sampled-day NEP-245 ledger accounts next to same-week Intents signers
  a_facts.csv      every number quoted in THESIS.md / the dashboard, as displayed
"""
import json
from pathlib import Path

import numpy as np
import pandas as pd

ROOT = Path(globals().get("ROOT", Path(__file__).resolve().parent))
OUT = Path(globals().get("OUT", ROOT / "results"))
R = ROOT / "results"

# ---- parameters (also declared in THESIS.md front matter) ---------------------------
WEEKS = 104                 # 2024-10-28 .. 2026-10-25
LAGS = range(-8, 9)         # k > 0: indicator leads usage by k weeks
FIT_END = "2026-02-22"      # first 69 weeks (~16 months) fit, last 35 weeks (~8 months) test
BREAK = 0.5                 # |weekly log growth| above this marks a regime-break week
Z95 = 1.96

# ---- load ----------------------------------------------------------------------------
q1 = pd.read_csv(R / "q1_weekly_usage.csv")
q2 = pd.read_csv(R / "q2_intents_flows.csv")
q3 = pd.read_csv(R / "q3_nep245_sample.csv")
kl = json.loads((ROOT / "raw" / "near_usdt_weekly.json").read_text())

if isinstance(kl, list):        # Binance klines: [open_ms, open, high, low, close, ...]
    price = pd.DataFrame({"week": pd.to_datetime([k[0] for k in kl], unit="ms").strftime("%Y-%m-%d"),
                          "price_close": [float(k[4]) for k in kl]})
else:                           # CoinGecko fallback: {"prices": [[ms, usd], ...]} daily
    p = pd.DataFrame(kl["prices"], columns=["ms", "usd"])
    p["day"] = pd.to_datetime(p.ms, unit="ms")
    p["week"] = (p.day - pd.to_timedelta(p.day.dt.weekday, unit="D")).dt.strftime("%Y-%m-%d")
    price = p.sort_values("ms").groupby("week", as_index=False).usd.last().rename(columns={"usd": "price_close"})

usage_cols = ["users_any", "signers", "relayed_users", "heavy_accounts", "users_real", "users_engaged",
              "new_users", "retained", "tx_signed", "relayed_actions", "intents_tx_signers",
              "intents_tx_signers_real", "intents_tx"]
w = q1.groupby("week")[usage_cols].sum()
w["intents_actions"] = q1.groupby("week").intents_actions_week.first()
core = q1[q1.family != "kaiching"].groupby("week")[["users_real", "users_engaged"]].sum()
w["users_core"] = core.users_real          # real users excluding KaiChing app sub-accounts
w["engaged_core"] = core.users_engaged
xc = q2.groupby("week")[["events_in", "events_out", "events_burn"]].sum()
w = w.join(xc, how="left").fillna({"events_in": 0, "events_out": 0, "events_burn": 0})
w["xchain_events"] = w.events_in + w.events_out
w = w.join(price.set_index("week"), how="left").reset_index()
assert len(w) == WEEKS and w.price_close.notna().all(), "panel must cover all 104 weeks"
w = w.sort_values("week").reset_index(drop=True)


def glog(s):
    s = s.where(s > 0)
    return np.log(s).diff()


SERIES = {  # name -> (column, label)
    "users_real": ("users_real", "Real users (signers + relayed, minus heavy)"),
    "users_core": ("users_core", "Real users excluding KaiChing sub-accounts"),
    "users_engaged": ("users_engaged", "Engaged real users (>= 2 active days)"),
    "xchain_events": ("xchain_events", "Intents cross-chain token movements"),
    "intents_actions": ("intents_actions", "Actions executed on intents.near"),
    "price_close": ("price_close", "NEAR/USDT weekly close"),
}
for name, (col, _) in SERIES.items():
    w[f"g_{name}"] = glog(w[col]).round(6)
TARGETS = ("users_real", "users_core", "users_engaged")
for t in TARGETS:  # regime breaks are flagged per usage series, from that series' own growth
    w[f"break_{t}"] = (w[f"g_{t}"].abs() > BREAK).astype(int)
w["break_week"] = w.break_users_real
w["sample"] = np.where(w.week <= FIT_END, "fit", "test")


# ---- lead/lag cross-correlation --------------------------------------------------------
def xcorr(x, y, k):
    """corr(x[t-k], y[t]); k > 0 means x leads y."""
    a = pd.concat([x.shift(k), y], axis=1).dropna()
    n = len(a)
    if n < 10:
        return np.nan, np.nan, n
    # Spearman = Pearson on average ranks (no scipy in the image)
    rx, ry = a.iloc[:, 0].rank(), a.iloc[:, 1].rank()
    return a.iloc[:, 0].corr(a.iloc[:, 1]), rx.corr(ry), n


rows = []
for target in ("users_real", "users_core", "users_engaged"):
    for ind in ("xchain_events", "intents_actions", "price_close"):
        for drop_breaks in (0, 1):
            y = w[f"g_{target}"].where(w[f"break_{target}"] == 0) if drop_breaks else w[f"g_{target}"]
            for k in LAGS:
                r, rho, n = xcorr(w[f"g_{ind}"], y, k)
                rows.append({"target": target, "indicator": ind, "drop_breaks": drop_breaks, "lag": k,
                             "n": n, "pearson": round(r, 2), "spearman": round(rho, 2),
                             "band95": round(Z95 / np.sqrt(n), 2),
                             "significant": int(abs(r) > Z95 / np.sqrt(n))})
xc = pd.DataFrame(rows)


# ---- out-of-sample test ----------------------------------------------------------------
def ols(X, y):
    X1 = np.column_stack([np.ones(len(X)), X])
    beta, *_ = np.linalg.lstsq(X1, y, rcond=None)
    return beta


def predict(beta, X):
    return np.column_stack([np.ones(len(X)), X]) @ beta


oos = []
for target in ("users_real", "users_core", "users_engaged"):
    for ind in ("xchain_events", "intents_actions", "price_close"):
        for drop_breaks in (0, 1):
            d = pd.DataFrame({"week": w.week, "y": w[f"g_{target}"], "y1": w[f"g_{target}"].shift(1),
                              "brk": w[f"break_{target}"], "x": w[f"g_{ind}"]})
            if drop_breaks:
                d = d[(d.brk == 0) & (d.brk.shift(1).fillna(0) == 0)]
            fit = d[d.week <= FIT_END]
            # lag chosen on the fit sample only: best |corr| among leads 1..8
            cands = []
            for k in range(1, 9):
                f = pd.DataFrame({"y": fit.y, "x": d.x.shift(k).reindex(fit.index)}).dropna()
                cands.append((abs(f.x.corr(f.y)), k))
            best_k = max(cands)[1]
            d = d.assign(xk=w[f"g_{ind}"].shift(best_k).reindex(d.index)).dropna()
            fit, test = d[d.week <= FIT_END], d[d.week > FIT_END]
            b0 = ols(fit[["y1"]].values, fit.y.values)
            b1 = ols(fit[["y1", "xk"]].values, fit.y.values)
            e0 = test.y.values - predict(b0, test[["y1"]].values)
            e1 = test.y.values - predict(b1, test[["y1", "xk"]].values)
            rm0, rm1 = np.sqrt(np.mean(e0 ** 2)), np.sqrt(np.mean(e1 ** 2))
            oos.append({"target": target, "indicator": ind, "drop_breaks": drop_breaks, "lag": best_k,
                        "n_fit": len(fit), "n_test": len(test), "coef_x": round(b1[2], 3),
                        "rmse_ar1": round(rm0, 4), "rmse_with_x": round(rm1, 4),
                        "rmse_ratio": round(rm1 / rm0, 3),
                        "improves": int(rm1 < rm0)})
oos = pd.DataFrame(oos)

# ---- families, chains, NEP-245 ------------------------------------------------------------
fam = q1.pivot(index="week", columns="family", values="users_real").fillna(0).astype(int).reset_index()
chains = (q2.groupby("chain")[["events_in", "events_out", "events_burn"]].sum()
          .assign(events=lambda t: t.events_in + t.events_out).sort_values(["events", "chain"], ascending=[False, True])
          .reset_index())
chains["share_pct"] = (100 * chains.events / chains.events.sum()).round(1)
q3 = q3.copy()
q3["week"] = (pd.to_datetime(q3.block_date) - pd.to_timedelta(pd.to_datetime(q3.block_date).dt.weekday, unit="D")).dt.strftime("%Y-%m-%d")
nep = q3.merge(w[["week", "intents_tx_signers_real", "users_real", "users_core"]], on="week", how="left")
nep["ledger_per_tx_signer"] = (nep.ledger_accounts / nep.intents_tx_signers_real).round(1)
nep = nep[["block_date", "week", "ledger_accounts", "transfer_accounts", "mint_accounts", "burn_accounts",
           "transfer_items", "intents_tx_signers_real", "users_real", "users_core", "ledger_per_tx_signer"]]

# ---- facts quoted in prose ----------------------------------------------------------------
F = {}


def fact(key, value):
    F[key] = value


def row(week):
    return w[w.week == week].iloc[0]


first, last = w.iloc[0], w.iloc[-1]
peak = w.loc[w.users_real.idxmax()]
fact("weeks", len(w))
fact("n_fit_weeks", int((w.week <= FIT_END).sum()))
fact("n_test_weeks", int((w.week > FIT_END).sum()))
fact("users_real_first", int(first.users_real)); fact("users_real_last", int(last.users_real))
fact("users_real_peak", int(peak.users_real)); fact("users_real_peak_week", peak.week)
fact("users_real_fall_x_from_peak", round(peak.users_real / last.users_real, 1))
fact("users_core_first", int(first.users_core)); fact("users_core_last", int(last.users_core))
fact("users_core_fall_pct", round(100 * (1 - last.users_core / first.users_core), 1))
fact("signers_first", int(first.signers)); fact("signers_last", int(last.signers))
fact("price_first", round(first.price_close, 3)); fact("price_last", round(last.price_close, 3))
fact("price_change_pct", round(100 * (last.price_close / first.price_close - 1), 1))
fact("price_min", round(w.price_close.min(), 3)); fact("price_min_week", w.loc[w.price_close.idxmin()].week)
fact("price_max", round(w.price_close.max(), 3)); fact("price_max_week", w.loc[w.price_close.idxmax()].week)
fs = w[w.xchain_events > 0].iloc[0]
fact("xchain_first_week", fs.week)
x_early = w[(w.week >= "2024-11-04") & (w.week <= "2025-01-26")].xchain_events.mean()
x_late = w[w.week >= "2026-08-03"].xchain_events.mean()
fact("xchain_mean_first_quarter", int(round(x_early))); fact("xchain_mean_last_quarter", int(round(x_late)))
fact("xchain_growth_x", round(x_late / x_early, 1))
u_early = w[(w.week >= "2024-11-04") & (w.week <= "2025-01-26")].users_core.mean()
u_late = w[w.week >= "2026-08-03"].users_core.mean()
fact("core_mean_first_quarter", int(round(u_early))); fact("core_mean_last_quarter", int(round(u_late)))
fact("xchain_total", int(w.xchain_events.sum())); fact("xchain_burn_total", int(w.events_burn.sum()))
fact("xchain_peak", int(w.xchain_events.max())); fact("xchain_peak_week", w.loc[w.xchain_events.idxmax()].week)
fact("intents_actions_peak", int(w.intents_actions.max())); fact("intents_actions_peak_week", w.loc[w.intents_actions.idxmax()].week)
fact("n_chains", int(len(chains))); fact("top_chain", chains.iloc[0].chain); fact("top_chain_share_pct", chains.iloc[0].share_pct)
fact("n_break_weeks", int(w.break_week.sum()))
for t in TARGETS:
    fact(f"n_break_weeks|{t}", int(w[f"break_{t}"].sum()))
for wk in w[w.break_week == 1].week:
    fact(f"break_{wk}", round(float(row(wk).g_users_real), 2))
# regime artifacts of the KaiChing app (sub-accounts *.users.kaiching)
kc = q1[q1.family == "kaiching"].set_index("week").reindex(w.week).fillna(0)
for wk in ("2024-10-28", "2025-02-10", "2025-02-17", "2025-02-24", "2026-03-23", "2026-03-30", "2026-04-06",
           "2026-09-21", "2026-09-28", "2026-10-05", "2026-10-12"):
    fact(f"kc_signers_{wk}", int(kc.loc[wk].signers)); fact(f"kc_relayed_{wk}", int(kc.loc[wk].relayed_users))
    fact(f"kc_real_{wk}", int(kc.loc[wk].users_real))
fact("kc_new_2026-09-28", int(kc.loc["2026-09-28"].new_users))
fact("kc_share_users_real_pct", round(100 * kc.users_real.sum() / w.users_real.sum(), 1))
fact("kc_peak_real", int(kc.users_real.max())); fact("kc_peak_week", kc.users_real.idxmax())
kc_weeks = kc[kc.users_real > 0]
fact("kc_weeks_present", int(len(kc_weeks)))
fact("kc_share_peak_week_pct", round(100 * kc.loc[kc.users_real.idxmax()].users_real / w.set_index("week").loc[kc.users_real.idxmax()].users_real, 1))
ov = q1[q1.week == "2025-02-24"]
fact("overlap_s5_relayed", int(ov.relayed_users.sum())); fact("overlap_flag_relayed", int(ov.flagged_relayed_week.iloc[0]))
fact("relayed_first_week", int(first.relayed_users)); fact("relayed_share_first_pct", round(100 * first.relayed_users / first.users_any, 1))
fact("users_any_first", int(first.users_any))
fact("signers_2026-09-21", int(row("2026-09-21").signers)); fact("signers_2026-09-28", int(row("2026-09-28").signers))
fact("signers_2026-10-19", int(row("2026-10-19").signers))
fact("heavy_median", int(w.heavy_accounts.median()))
fact("engaged_share_last_pct", round(100 * last.users_engaged / last.users_real, 1))
# cross-correlation summaries (primary = Pearson, all weeks, k = 1..8 leads)
for target in ("users_real", "users_core", "users_engaged"):
    for ind in ("xchain_events", "intents_actions", "price_close"):
        for db in (0, 1):
            s = xc[(xc.target == target) & (xc.indicator == ind) & (xc.drop_breaks == db)]
            lead = s[s.lag > 0]
            best = lead.loc[lead.pearson.abs().idxmax()]
            tag = f"{target}|{ind}|{'nobreak' if db else 'all'}"
            fact(f"xc_best_lag|{tag}", int(best.lag)); fact(f"xc_best_r|{tag}", best.pearson)
            fact(f"xc_best_n|{tag}", int(best.n)); fact(f"xc_band|{tag}", best.band95)
            fact(f"xc_sig_leads|{tag}", int(lead.significant.sum()))
            fact(f"xc_lag0_r|{tag}", s[s.lag == 0].pearson.iloc[0])
            fact(f"xc_lag0_n|{tag}", int(s[s.lag == 0].n.iloc[0])); fact(f"xc_lag0_band|{tag}", s[s.lag == 0].band95.iloc[0])
            fact(f"xc_lag0_sig|{tag}", int(s[s.lag == 0].significant.iloc[0]))
            fact(f"xc_best_spearman|{tag}", best.spearman)
            fact(f"xc_sig_lags_any|{tag}", int(s.significant.sum()))
for _, o in oos.iterrows():
    tag = f"{o.target}|{o.indicator}|{'nobreak' if o.drop_breaks else 'all'}"
    fact(f"oos_ratio|{tag}", o.rmse_ratio); fact(f"oos_lag|{tag}", int(o.lag))
    fact(f"oos_ntest|{tag}", int(o.n_test)); fact(f"oos_nfit|{tag}", int(o.n_fit))
lead_tests = xc[xc.lag > 0]
fact("lead_tests", int(len(lead_tests)))
fact("lead_tests_significant", int(lead_tests.significant.sum()))
fact("lead_tests_expected_by_chance", round(0.05 * len(lead_tests), 1))
for ind in ("xchain_events", "intents_actions", "price_close"):
    li = lead_tests[lead_tests.indicator == ind]
    fact(f"lead_tests|{ind}", int(len(li))); fact(f"lead_sig|{ind}", int(li.significant.sum()))
    fact(f"lead_sig_pos|{ind}", int(((li.significant == 1) & (li.pearson > 0)).sum()))
    fact(f"lead_max_abs_r|{ind}", float(li.pearson.abs().max()))
fact("oos_improves_xchain", int(oos[oos.indicator == "xchain_events"].improves.sum()))
fact("oos_improves_actions", int(oos[oos.indicator == "intents_actions"].improves.sum()))
fact("oos_improves_price", int(oos[oos.indicator == "price_close"].improves.sum()))
fact("oos_cases_per_indicator", int((oos.indicator == "price_close").sum()))
fact("oos_fits", int(len(oos))); fact("oos_within_3pct", int(((oos.rmse_ratio - 1).abs() <= 0.03).sum()))
fact("oos_best_gain_xchain_pct", round(100 * (1 - oos[oos.indicator == "xchain_events"].rmse_ratio.min()), 1))
fact("oos_ratio_min", float(oos.rmse_ratio.min())); fact("oos_ratio_max", float(oos.rmse_ratio.max()))
lvl = w[w.xchain_events > 0]
fact("level_corr_xchain_core", round(np.log(lvl.xchain_events).corr(np.log(lvl.users_core)), 2))
fact("level_corr_price_core", round(np.log(w.price_close).corr(np.log(w.users_core)), 2))
fact("level_corr_n_xchain", int(len(lvl)))
fact("nep245_days", int(len(q3))); fact("nep245_sample_days_planned", 26)
fact("nep245_ledger_max", int(nep.ledger_accounts.max())); fact("nep245_ledger_max_day", nep.loc[nep.ledger_accounts.idxmax()].block_date)
fact("nep245_ledger_last", int(nep.iloc[-1].ledger_accounts)); fact("nep245_last_day", nep.iloc[-1].block_date)
fact("nep245_ratio_median", round(float(nep.ledger_per_tx_signer.median()), 1))
fact("intents_tx_signers_real_last", int(last.intents_tx_signers_real))

facts = pd.DataFrame({"key": list(F), "value": [F[k] for k in F]})
facts["abs_value"] = [abs(v) if isinstance(v, (int, float, np.integer, np.floating)) else "" for v in facts.value]

# ---- write ------------------------------------------------------------------------------------
OUT.mkdir(parents=True, exist_ok=True)
fmt = dict(index=False, lineterminator="\n", float_format="%.10g")
keep = ["week", "sample", "break_week", "price_close", "users_any", "signers", "relayed_users", "heavy_accounts",
        "users_real", "users_core", "users_engaged", "engaged_core", "new_users", "retained",
        "break_users_core", "break_users_engaged", "intents_tx_signers_real",
        "intents_actions", "xchain_events", "events_in", "events_out", "events_burn"] + [f"g_{n}" for n in SERIES]
w[keep].to_csv(OUT / "a_weekly.csv", **fmt)
xc.to_csv(OUT / "a_xcorr.csv", **fmt)
oos.to_csv(OUT / "a_oos.csv", **fmt)
fam.to_csv(OUT / "a_families.csv", **fmt)
chains.to_csv(OUT / "a_chains.csv", **fmt)
nep.to_csv(OUT / "a_nep245.csv", **fmt)
facts.to_csv(OUT / "a_facts.csv", **fmt)
print(f"analysis: {len(w)} weeks, {len(xc)} correlations, {len(oos)} out-of-sample fits, {len(facts)} facts")
Intents keeps balances in its own NEP-245 ledger: on 2026-09-30 30,607 accounts appeared in it in a single day, while only a few hundred to a few thousand accounts a week sign transactions to intents.near themselves.

Intents keeps balances in its own NEP-245 ledger: on 2026-09-30 30,607 accounts appeared in it in a single day, while only a few hundred to a few thousand accounts a week sign transactions to intents.near themselves.

stage/s4_nep245_sample.sql
-- name: s4_nep245_sample  (HEAVY, run once; SAMPLED)
-- NEAR Intents keeps user balances inside intents.near as NEP-245 multi-tokens. Those
-- events are NOT in ft_events (which only carries nep141); they exist only as
-- EVENT_JSON log lines in execution_outcomes. A full-window log scan dry-runs at about
-- 2.4 TB (over budget), so we sample one day every 4 weeks: the Wednesday of every
-- 4th ISO week, 26 days. One row per (day, event, account) with the number of
-- event entries naming that account (owner_id, old_owner_id or new_owner_id).
-- window: 2024-10-28 .. 2026-10-25, sampled days listed below
CREATE OR REPLACE TABLE `{stage}.s4_nep245_sample` AS
WITH ev AS (
  SELECT block_date, SAFE.PARSE_JSON(SUBSTR(l.element, 12)) AS j
  FROM `bigquery-public-data.crypto_near_mainnet_us.execution_outcomes`, UNNEST(logs.list) AS l
  WHERE block_date BETWEEN '2024-10-28' AND '2026-10-25'
    AND block_date IN ('2024-10-30','2024-11-27','2024-12-25','2025-01-22','2025-02-19','2025-03-19','2025-04-16','2025-05-14','2025-06-11','2025-07-09','2025-08-06','2025-09-03','2025-10-01','2025-10-29','2025-11-26','2025-12-24','2026-01-21','2026-02-18','2026-03-18','2026-04-15','2026-05-13','2026-06-10','2026-07-08','2026-08-05','2026-09-02','2026-09-30')
    AND executor_account_id = 'intents.near'
    AND STARTS_WITH(l.element, 'EVENT_JSON:')
    AND l.element LIKE '%"nep245"%'
), items AS (
  SELECT block_date, LAX_STRING(j.event) AS event, d
  FROM ev, UNNEST(JSON_QUERY_ARRAY(j, '$.data')) AS d
)
SELECT block_date, event, account_id, COUNT(*) AS n_items
FROM items,
  UNNEST(ARRAY_CONCAT(
    IF(LAX_STRING(d.owner_id)     IS NULL, [], [LAX_STRING(d.owner_id)]),
    IF(LAX_STRING(d.old_owner_id) IS NULL, [], [LAX_STRING(d.old_owner_id)]),
    IF(LAX_STRING(d.new_owner_id) IS NULL, [], [LAX_STRING(d.new_owner_id)]))) AS account_id
GROUP BY block_date, event, account_id
queries/q3_nep245_sample.sql
-- name: q3_nep245_sample
-- question: On the 26 sampled days, how many distinct accounts appear in NEAR Intents'
--           internal NEP-245 ledger (mt_mint / mt_transfer / mt_burn), and how many events?
-- reads: {stage}.s4_nep245_sample (tiny; one day every 4 weeks, see stage/s4)
-- window: 2024-10-28 .. 2026-10-25 (sampled days only)
SELECT
  block_date,
  COUNT(DISTINCT account_id)                                       AS ledger_accounts,
  COUNT(DISTINCT IF(event = 'mt_transfer', account_id, NULL))      AS transfer_accounts,
  COUNT(DISTINCT IF(event = 'mt_mint', account_id, NULL))          AS mint_accounts,
  COUNT(DISTINCT IF(event = 'mt_burn', account_id, NULL))          AS burn_accounts,
  SUM(IF(event = 'mt_transfer', n_items, 0))                       AS transfer_items,
  SUM(IF(event = 'mt_mint', n_items, 0))                           AS mint_items,
  SUM(IF(event = 'mt_burn', n_items, 0))                           AS burn_items,
  BIT_XOR(FARM_FINGERPRINT(FORMAT('%t|%s|%s|%d', block_date, event, account_id, n_items))) AS fp
FROM `{stage}.s4_nep245_sample`
WHERE block_date BETWEEN '2024-10-28' AND '2026-10-25'
GROUP BY block_date
Cross-chain movements came from 24 source chains; ETH assets alone were 27.3%.

Cross-chain movements came from 24 source chains; ETH assets alone were 27.3%.

stage/s3_intents_token_flows.sql
-- name: s3_intents_token_flows  (HEAVY, run once)
-- Fungible-token (NEP-141) balance changes of the intents.near account, per week.
-- Cross-chain assets on NEAR Intents are the PoA-bridge tokens *.omft.near (one per
-- source-chain asset). ft_events is clustered on contract_account_id, so the scan is
-- pruned with STARTS_WITH on the chain prefixes seen in a 24-day sample, then filtered
-- exactly with ENDS_WITH('.omft.near'). Prefixes not in the list are missed (see THESIS.md).
-- direction: 'in' = intents.near balance increased, 'out' = decreased (burn = bridge-out).
-- Amounts are raw integer token units (no decimals, no prices).
-- window: 2024-10-28 .. 2026-10-25 = 104 full ISO weeks
CREATE OR REPLACE TABLE `{stage}.s3_intents_token_flows` AS
SELECT
  DATE_TRUNC(block_date, ISOWEEK)                          AS week,
  contract_account_id                                      AS token,
  cause,
  IF(STARTS_WITH(delta_amount, '-'), 'out', 'in')          AS direction,
  involved_account_id                                      AS counterparty,
  COUNT(*)                                                 AS n_events,
  SUM(ABS(CAST(delta_amount AS BIGNUMERIC)))               AS raw_amount
FROM `bigquery-public-data.crypto_near_mainnet_us.ft_events`
WHERE block_date BETWEEN '2024-10-28' AND '2026-10-25'
  AND affected_account_id = 'intents.near'
  AND ENDS_WITH(contract_account_id, '.omft.near')
  AND (   STARTS_WITH(contract_account_id, 'eth')   OR STARTS_WITH(contract_account_id, 'base')
       OR STARTS_WITH(contract_account_id, 'sol')   OR STARTS_WITH(contract_account_id, 'gnosis')
       OR STARTS_WITH(contract_account_id, 'arb')   OR STARTS_WITH(contract_account_id, 'hood')
       OR STARTS_WITH(contract_account_id, 'sui')   OR STARTS_WITH(contract_account_id, 'aptos')
       OR STARTS_WITH(contract_account_id, 'aleo')  OR STARTS_WITH(contract_account_id, 'tron')
       OR STARTS_WITH(contract_account_id, 'bera')  OR STARTS_WITH(contract_account_id, 'plasma')
       OR STARTS_WITH(contract_account_id, 'zec')   OR STARTS_WITH(contract_account_id, 'btc')
       OR STARTS_WITH(contract_account_id, 'xrp')   OR STARTS_WITH(contract_account_id, 'ltc')
       OR STARTS_WITH(contract_account_id, 'qtc')   OR STARTS_WITH(contract_account_id, 'doge')
       OR STARTS_WITH(contract_account_id, 'bch')   OR STARTS_WITH(contract_account_id, 'cardano')
       OR STARTS_WITH(contract_account_id, 'starknet') OR STARTS_WITH(contract_account_id, 'dash')
       OR STARTS_WITH(contract_account_id, 'bsc')   OR STARTS_WITH(contract_account_id, 'avax')
       OR STARTS_WITH(contract_account_id, 'pol')   OR STARTS_WITH(contract_account_id, 'op')
       OR STARTS_WITH(contract_account_id, 'ton')   OR STARTS_WITH(contract_account_id, 'stellar'))
GROUP BY week, token, cause, direction, counterparty
queries/q2_intents_flows.sql
-- name: q2_intents_flows
-- question: Per ISO week, how many cross-chain (PoA-bridge *.omft.near) token movements
--           touched intents.near, in which direction, and from how many counterparties?
-- reads: {stage}.s3_intents_token_flows (tiny). chain = asset prefix before '-' or '.'
--        (eth, sol, btc, tron, ...). Burns (cause ft_burn) are withdrawals back to the
--        source chain. Amounts stay in raw token units (no decimals, no prices).
-- window: 2024-10-28 .. 2026-10-25
SELECT
  week,
  REGEXP_EXTRACT(token, r'^([a-z0-9]+)')                  AS chain,
  COUNT(DISTINCT token)                                   AS tokens,
  SUM(IF(direction = 'in', n_events, 0))                  AS events_in,
  SUM(IF(direction = 'out', n_events, 0))                 AS events_out,
  SUM(IF(cause = 'ft_burn', n_events, 0))                 AS events_burn,
  COUNT(DISTINCT IF(direction = 'in', counterparty, NULL)) AS counterparties_in,
  BIT_XOR(FARM_FINGERPRINT(FORMAT('%t|%s|%s|%s|%s|%d|%t', week, token, cause, direction,
          IFNULL(counterparty, ''), n_events, raw_amount)))  AS fp
FROM `{stage}.s3_intents_token_flows`
WHERE week BETWEEN '2024-10-28' AND '2026-10-25'
GROUP BY week, chain

Reproduce

Every query has a fixed date window and a SHA-256 fingerprint. make verify-cached re-checks everything offline; make verify re-runs the aggregates on BigQuery.

queryrowsresult sha256
q1_weekly_usage701d9d7733890d6bbdb…
q2_intents_flows152612aee07ffb4f39ab…
q3_nep245_sample252911bcced94a5ab0…