Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(indexer): measure how far behind chain head each EVM leg is, not just cursor age

nirholas108eb51c9486
diff --git a/api/_lib/migrations/20260813210000_erc8004_crawl_head_tracking.sql b/api/_lib/migrations/20260813210000_erc8004_crawl_head_tracking.sql
new file mode 100644
index 000000000..af0cf9811
--- /dev/null
+++ b/api/_lib/migrations/20260813210000_erc8004_crawl_head_tracking.sql
@@ -0,0 +1,42 @@
+-- erc8004_crawl_cursor — track how far behind the CHAIN HEAD each EVM leg is,
+-- not just when the cron last touched the row.
+--
+-- Why. On 2026-08-13 the status surface reported the EVM index healthy on 17 of
+-- 21 chains, because the only freshness signal was `updated_at`: proof the cron
+-- ran, not proof the index caught up. A live probe of every configured chain's
+-- real block production told a different story. Reading two block timestamps one
+-- chunk apart on each chain, and comparing the wall-clock span a single 15-minute
+-- tick can cover:
+--
+-- Arbitrum One 1000 blocks = 251s of chain = 0.28x the cron period
+-- Arbitrum Sepolia 1000 blocks = 250s = 0.28x
+-- BNB Chain 1000 blocks = 450s = 0.50x
+-- BSC Testnet 1000 blocks = 450s = 0.50x
+-- Polygon 500 blocks = 750s = 0.83x
+--
+-- Five of twenty-two chains consume less chain time per tick than the tick
+-- itself, so their backlog grows monotonically and forever (Arbitrum One sheds
+-- roughly 250k blocks a day) while every one of them reports a fresh cursor.
+--
+-- head_block and blocks_behind make that a NUMBER on /status. chunk_size makes
+-- the crawl able to do something about it: it grows while a chain is behind and
+-- halves when an RPC rejects the range, so each chain settles at the largest
+-- window its provider actually serves instead of a global guess.
+--
+-- Apply: node scripts/apply-migrations.mjs --apply
+-- Idempotent.
+
+begin;
+
+alter table erc8004_crawl_cursor
+ add column if not exists head_block bigint,
+ add column if not exists blocks_behind bigint not null default 0,
+ add column if not exists chunk_size integer not null default 1000,
+ add column if not exists last_error text;
+
+-- The lag monitor asks for the worst offender across all chains on every
+-- /status render, which is a full scan without this.
+create index if not exists erc8004_crawl_cursor_behind
+ on erc8004_crawl_cursor(blocks_behind desc);
+
+commit;
diff --git a/api/_lib/ops/index-lag.js b/api/_lib/ops/index-lag.js
index f5331e47d..fd79b2d80 100644
--- a/api/_lib/ops/index-lag.js
+++ b/api/_lib/ops/index-lag.js
@@ -18,6 +18,8 @@
// behind, and it is reported first.
import { sql } from '../db.js';
+import { CHAINS } from '../erc8004-chains.js';
+import { SOLANA_SWEEP_BATCH, SOLANA_SWEEP_PERIOD_MIN } from '../solana-agent-events.js';
/** Solana leg: worst per-agent cursor age tolerated before the index is stale. */
export const SOLANA_LAG_DEGRADED_MIN = 90;
@@ -26,6 +28,21 @@ export const SOLANA_LAG_DOWN_MIN = 360;
export const EVM_LAG_DEGRADED_MIN = 120;
export const EVM_LAG_DOWN_MIN = 480;
+/**
+ * Blocks behind head before an EVM chain counts as stale, and as broken.
+ *
+ * Cursor AGE was the only EVM signal until 2026-08-13, and it is the wrong one:
+ * it proves the cron ran, not that the index caught up. A live measurement of
+ * every configured chain's block production that day found five chains
+ * (Arbitrum One, Arbitrum Sepolia, BNB Chain, BSC Testnet, Polygon) consuming
+ * less chain time per tick than the tick itself, so their backlog grew forever
+ * while their cursors stayed minutes old and the status surface said ok. These
+ * thresholds are what makes that visible: roughly an hour of the fastest chain's
+ * block production, and roughly half a day of it.
+ */
+export const EVM_BLOCKS_BEHIND_DEGRADED = 20_000;
+export const EVM_BLOCKS_BEHIND_DOWN = 250_000;
+
const QUERY_TIMEOUT_MS = 4_000;
const minutesSince = (ts) => (ts ? Math.round((Date.now() - new Date(ts).getTime()) / 60_000) : null);
@@ -41,8 +58,13 @@ function withTimeout(promise, ms) {
* Read the freshness of every indexer leg.
*
* @returns {Promise<{
- * solana: { medianLagMin: number|null, worstLagMin: number|null, agents: number, uncrawled: number, events: number },
- * evm: { lagMin: number|null, chains: number, staleChains: number, events: number },
+ * solana: { medianLagMin: number|null, worstLagMin: number|null, agents: number,
+ * uncrawled: number, errored: number, events: number,
+ * sweepCycleMin: number|null, batch: number },
+ * evm: { lagMin: number|null, chains: number, configuredChains: number,
+ * uncrawledChains: number, staleChains: number, worstBlocksBehind: number,
+ * behindChains: number, worstChainId: number|null, worstChainName: string|null,
+ * events: number },
* lastEventAt: string|null,
* lastIndexedAt: string|null,
* }>}
@@ -54,6 +76,7 @@ export async function readIndexLag() {
SELECT
count(*)::int AS agents,
count(*) FILTER (WHERE cur.last_indexed_at IS NULL)::int AS uncrawled,
+ count(*) FILTER (WHERE cur.error IS NOT NULL)::int AS errored,
max(extract(epoch FROM now() - cur.last_indexed_at) / 60)::int AS worst_lag_min,
percentile_disc(0.5) WITHIN GROUP (
ORDER BY extract(epoch FROM now() - cur.last_indexed_at) / 60
@@ -70,7 +93,13 @@ export async function readIndexLag() {
count(*) FILTER (
WHERE updated_at < now() - (${EVM_LAG_DEGRADED_MIN} || ' minutes')::interval
)::int AS stale_chains,
- max(extract(epoch FROM now() - updated_at) / 60)::int AS lag_min
+ count(*) FILTER (WHERE blocks_behind >= ${EVM_BLOCKS_BEHIND_DEGRADED})::int AS behind_chains,
+ max(extract(epoch FROM now() - updated_at) / 60)::int AS lag_min,
+ coalesce(max(blocks_behind), 0)::bigint AS worst_blocks_behind,
+ (
+ SELECT chain_id FROM erc8004_crawl_cursor
+ ORDER BY blocks_behind DESC LIMIT 1
+ )::int AS worst_chain_id
FROM erc8004_crawl_cursor
`,
QUERY_TIMEOUT_MS,
@@ -92,18 +121,32 @@ export async function readIndexLag() {
const e = evm[0] || {};
const t = totals[0] || {};
+ const worstChainId = e.worst_chain_id ?? null;
+
return {
solana: {
medianLagMin: s.median_lag_min ?? null,
worstLagMin: s.worst_lag_min ?? null,
agents: s.agents ?? 0,
uncrawled: s.uncrawled ?? 0,
+ errored: s.errored ?? 0,
events: t.solana_events ?? 0,
+ batch: SOLANA_SWEEP_BATCH,
+ sweepCycleMin: sweepCycleMin(s.agents ?? 0),
},
evm: {
lagMin: e.lag_min ?? null,
chains: e.chains ?? 0,
+ // A chain with no cursor row at all contributes nothing and is invisible
+ // to every aggregate above, so name it separately: 21 cursors against 22
+ // configured chains means one chain has never been crawled once.
+ configuredChains: CHAINS.length,
+ uncrawledChains: Math.max(0, CHAINS.length - (e.chains ?? 0)),
staleChains: e.stale_chains ?? 0,
+ behindChains: e.behind_chains ?? 0,
+ worstBlocksBehind: Number(e.worst_blocks_behind ?? 0),
+ worstChainId,
+ worstChainName: CHAINS.find((c) => c.id === worstChainId)?.name ?? null,
events: t.evm_events ?? 0,
},
lastEventAt: t.last_event_at ? new Date(t.last_event_at).toISOString() : null,
@@ -111,6 +154,19 @@ export async function readIndexLag() {
};
}
+/**
+ * How long one full pass over the Solana directory takes at the configured
+ * sweep rate. This is the number that explains a median lag: a queue drained
+ * oldest-first sits at half its cycle time, so a rising directory silently
+ * raises the floor until someone measures the cycle.
+ * @param {number} agents
+ * @returns {number|null}
+ */
+export function sweepCycleMin(agents) {
+ if (!agents) return null;
+ return Math.ceil(agents / SOLANA_SWEEP_BATCH) * SOLANA_SWEEP_PERIOD_MIN;
+}
+
/**
* Roll index freshness into a subsystem verdict for /status and /api/healthz.
* Never throws: an unreadable index reports `unknown`, like every other check.
@@ -139,27 +195,47 @@ export async function gatherIndexLagHealth() {
};
}
- const solStatus = legStatus(lag.solana.medianLagMin, SOLANA_LAG_DEGRADED_MIN, SOLANA_LAG_DOWN_MIN);
- const evmStatus = legStatus(lag.evm.lagMin, EVM_LAG_DEGRADED_MIN, EVM_LAG_DOWN_MIN);
+ const solStatus = worst(
+ legStatus(lag.solana.medianLagMin, SOLANA_LAG_DEGRADED_MIN, SOLANA_LAG_DOWN_MIN),
+ // A leg crawling every agent and indexing nothing is broken, not fresh.
+ // That exact shape (1,576 cursors, 0 events) hid a crash in the Solana
+ // crawler for two days behind a healthy-looking cursor age.
+ lag.solana.agents > 0 && lag.solana.events === 0 ? 'down' : 'ok',
+ );
+ const evmStatus = worst(
+ legStatus(lag.evm.lagMin, EVM_LAG_DEGRADED_MIN, EVM_LAG_DOWN_MIN),
+ legStatus(lag.evm.worstBlocksBehind, EVM_BLOCKS_BEHIND_DEGRADED, EVM_BLOCKS_BEHIND_DOWN),
+ );
const status = worst(solStatus, evmStatus);
const solPart =
lag.solana.agents === 0
? 'Solana: no agents queued'
: `Solana: ${fmt(lag.solana.medianLagMin)} median lag across ${lag.solana.agents} agents` +
- (lag.solana.uncrawled ? `, ${lag.solana.uncrawled} never crawled` : '');
+ (lag.solana.sweepCycleMin ? ` (${fmt(lag.solana.sweepCycleMin)} full sweep at ${lag.solana.batch}/tick)` : '') +
+ (lag.solana.uncrawled ? `, ${lag.solana.uncrawled} never crawled` : '') +
+ (lag.solana.errored ? `, ${lag.solana.errored} erroring` : '') +
+ `, ${lag.solana.events} events`;
const evmPart =
lag.evm.chains === 0
? 'EVM: no chain cursors'
- : `EVM: ${fmt(lag.evm.lagMin)} worst lag across ${lag.evm.chains} chains` +
- (lag.evm.staleChains ? `, ${lag.evm.staleChains} stale` : '');
- const eventPart = `${lag.solana.events + lag.evm.events} events indexed`;
+ : `EVM: ${fmt(lag.evm.lagMin)} worst cursor age across ${lag.evm.chains}/${lag.evm.configuredChains} chains` +
+ `, worst backlog ${lag.evm.worstBlocksBehind.toLocaleString('en-US')} blocks` +
+ (lag.evm.worstChainName ? ` (${lag.evm.worstChainName})` : '') +
+ (lag.evm.behindChains ? `, ${lag.evm.behindChains} behind` : '') +
+ (lag.evm.staleChains ? `, ${lag.evm.staleChains} stale` : '') +
+ (lag.evm.uncrawledChains ? `, ${lag.evm.uncrawledChains} never crawled` : '') +
+ `, ${lag.evm.events} events`;
- const detail = `${solPart}. ${evmPart}. ${eventPart}.`;
+ const detail = `${solPart}. ${evmPart}.`;
const hint =
status === 'ok'
? undefined
- : 'Check the crawl crons: /api/cron/solana-attestations-crawl and /api/cron/erc8004-crawl. A stale cursor means the job is failing or no longer scheduled.';
+ : lag.solana.agents > 0 && lag.solana.events === 0
+ ? 'The Solana crawl is reaching every agent and recording nothing: read the `error` column on agent_event_cursor, which the sweep stamps on failure.'
+ : lag.evm.worstBlocksBehind >= EVM_BLOCKS_BEHIND_DEGRADED
+ ? 'An EVM chain is behind head, not just stale: the crawl grows its block window while behind, so a backlog that keeps rising means the RPC is rejecting ranges (erc8004_crawl_cursor.last_error) or the cron is being cut short by its budget.'
+ : 'Check the crawl crons: /api/cron/solana-attestations-crawl and /api/cron/erc8004-crawl. A stale cursor means the job is failing or no longer scheduled.';
return { ...base, status, detail, ...(hint ? { hint } : {}), metrics: lag };
}
diff --git a/api/_lib/solana-agent-events.js b/api/_lib/solana-agent-events.js
index 1058f2df5..c925015a0 100644
--- a/api/_lib/solana-agent-events.js
+++ b/api/_lib/solana-agent-events.js
@@ -24,6 +24,7 @@
// the classification is unit-testable against captured mainnet transactions
// without an RPC round trip.
+import { PublicKey } from '@solana/web3.js';
import { sql } from './db.js';
import { solanaConnection } from './solana/connection.js';
import { RPC } from './solana-attestations.js';
@@ -187,21 +188,91 @@ export function classifyAgentTx({ agentRef, signature, slot, blockTime, network,
}
/**
- * Best-effort mint for a SetAgentTokenV1 transaction: the token balances the
- * transaction touched name the mint directly, which beats guessing from the
- * account list. Returns null when the tx moved no token balance.
- * @param {object} tx
- * @param {string} agentRef
+ * Wrapped SOL. It is the QUOTE side of every agent-token launch that funds a
+ * pool, never the agent's own token, and it is the first mint the naive
+ * "any mint this tx touched" reading finds. See agentTokenMintOf().
+ */
+export const WRAPPED_SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+// spl-token instruction types that can only name a mint being created or
+// finalized, in the order of how strongly each identifies THE launched token.
+// setAuthority qualifies only for the two mint-scoped authority types: renouncing
+// mint/freeze authority is the last step of a launch, and a launchpad emits it
+// for the new token and for nothing else.
+const MINT_AUTHORITY_TYPES = new Set(['mintTokens', 'freezeAccount']);
+
+/**
+ * The mint a SetAgentTokenV1 transaction bound to the agent.
+ *
+ * Reading `meta.*TokenBalances` alone is wrong, and measurably so: on mainnet
+ * transaction 5WtcSn4jJubQnEu71nnjKZJZawtgGNeVayiDgG4QsDsCZreJN2W3MQiJpPWszCFcanFRDMVfojNwrPC7SBumRqw8
+ * the only token balance is wrapped SOL, while the token actually launched and
+ * bound to agent ANeykUs3hCNb9B9hVx4sQg7D8hD6MzAyRPJ2M1ays18 is
+ * X8k6vcAvvmkavecwAGk7U4JVoKdntDSNfBZsq6KPLEX, visible only in the inner
+ * spl-token instructions. Every token_launch event the index recorded that way
+ * named the quote asset instead of the agent's coin.
+ *
+ * So prefer STRUCTURAL evidence, which a launch cannot fake: a mint this
+ * transaction initialized, then renounced authority over, then minted supply
+ * from. Token balances remain the last resort for a binding that touched an
+ * already-existing mint, with wrapped SOL and the agent account itself excluded.
+ *
+ * Requires a PARSED transaction (getParsedTransactions); a raw one exposes no
+ * instruction types and falls through to the balance heuristic.
+ *
+ * @param {object} tx parsed confirmed transaction
+ * @param {string} agentRef the agent account, never its own token
* @returns {string|null}
*/
export function agentTokenMintOf(tx, agentRef) {
- const balances = [...(tx?.meta?.postTokenBalances || []), ...(tx?.meta?.preTokenBalances || [])];
- for (const b of balances) {
- if (b?.mint && b.mint !== agentRef) return b.mint;
+ const byPriority = [new Set(), new Set(), new Set()];
+
+ for (const ix of parsedInstructionsOf(tx)) {
+ const info = ix?.parsed?.info;
+ const mint = typeof info?.mint === 'string' ? info.mint : null;
+ if (!mint || mint === WRAPPED_SOL_MINT || mint === agentRef) continue;
+ switch (ix.parsed.type) {
+ case 'initializeMint':
+ case 'initializeMint2':
+ byPriority[0].add(mint);
+ break;
+ case 'setAuthority':
+ if (MINT_AUTHORITY_TYPES.has(info.authorityType)) byPriority[1].add(mint);
+ break;
+ case 'mintTo':
+ case 'mintToChecked':
+ byPriority[2].add(mint);
+ break;
+ default:
+ break;
+ }
+ }
+
+ for (const tier of byPriority) {
+ // A single unambiguous mint at this tier is the answer. Two different
+ // mints initialized in one transaction (a launch plus an LP token, say)
+ // is not something to guess at, so fall through to the next signal.
+ if (tier.size === 1) return [...tier][0];
+ }
+
+ for (const b of [...(tx?.meta?.postTokenBalances || []), ...(tx?.meta?.preTokenBalances || [])]) {
+ if (b?.mint && b.mint !== agentRef && b.mint !== WRAPPED_SOL_MINT) return b.mint;
}
return null;
}
+/**
+ * Every parsed instruction in a transaction, top level and inner (a launchpad
+ * CPIs the token program, so the mint lives in the inner set).
+ * @param {object} tx
+ * @returns {object[]}
+ */
+export function parsedInstructionsOf(tx) {
+ const top = tx?.transaction?.message?.instructions || [];
+ const inner = (tx?.meta?.innerInstructions || []).flatMap((g) => g?.instructions || []);
+ return [...top, ...inner].filter((ix) => ix && typeof ix.parsed?.type === 'string');
+}
+
/**
* The account a Core transfer moved the asset to: the largest SOL-balance
* gainer that is not the fee payer. Null when the balances do not say.
@@ -227,6 +298,25 @@ export function transferRecipientOf(tx, keys) {
const CHAIN = 'solana';
+/**
+ * Agents swept per solana-attestations-crawl tick, and the cron's period.
+ *
+ * These two numbers and the size of the directory decide the index's floor lag:
+ * a queue drained oldest-first has a full-sweep cycle of
+ * `agents / SOLANA_SWEEP_BATCH * SOLANA_SWEEP_PERIOD_MIN` minutes and a median
+ * agent lag of half that. At 40 agents per tick the 1,576-agent directory
+ * measured on 2026-08-13 cycled in 6.6 hours for a 200-minute median, which is
+ * exactly the median the status surface reported: the sweep was not slow, it was
+ * too small. The lag monitor now derives the cycle from these constants, so the
+ * next time the directory outgrows the batch it is visible as a number rather
+ * than as an unexplained median.
+ *
+ * Raising this costs one getSignaturesForAddress per agent per tick; the cron's
+ * wall-clock budget, not this constant, is the real ceiling.
+ */
+export const SOLANA_SWEEP_BATCH = 120;
+export const SOLANA_SWEEP_PERIOD_MIN = 10;
+
/**
* Crawl one Solana agent account's recent signatures into the event index.
* Resumes from agent_event_cursor, so a steady-state run fetches only what
@@ -239,13 +329,29 @@ export async function crawlAgentEvents({ agentRef, network = 'mainnet', limit =
const net = network === 'devnet' ? 'devnet' : 'mainnet';
const conn = solanaConnection({ url: RPC[net], commitment: 'confirmed' });
+ // getSignaturesForAddress takes a PublicKey and calls .toBase58() on it, so
+ // handing it the base58 STRING we carry everywhere else throws
+ // `TypeError: address.toBase58 is not a function` before a single RPC round
+ // trip. That is not a hypothetical: it is why the Solana leg of the index
+ // held 0 events on 2026-08-13 while its 1,576 per-agent cursors all showed
+ // as freshly crawled, since the error path stamps the cursor too.
+ let address;
+ try {
+ address = new PublicKey(agentRef);
+ } catch {
+ // A directory row whose ref is not an account key can never be crawled.
+ // Record it against the cursor instead of throwing every tick forever.
+ await markAgentEventError({ agentRef, network: net, error: 'agent_ref is not a Solana account key' });
+ return { scanned: 0, inserted: 0, rejected: 0 };
+ }
+
const [cursor] = await sql`
SELECT last_tx FROM agent_event_cursor
WHERE chain = ${CHAIN} AND chain_id = 0 AND agent_ref = ${agentRef}
LIMIT 1
`;
- const sigs = await conn.getSignaturesForAddress(agentRef, {
+ const sigs = await conn.getSignaturesForAddress(address, {
limit,
until: cursor?.last_tx || undefined,
});
@@ -256,8 +362,12 @@ export async function crawlAgentEvents({ agentRef, network = 'mainnet', limit =
}
const ok = sigs.filter((s) => !s.err);
+ // Parsed, not raw: agentTokenMintOf() reads the inner spl-token instructions
+ // to tell an agent's launched token from the wrapped SOL that funded it, and
+ // only the parsed encoding carries instruction types. accountKeysOf() and
+ // memoPayloadOf() already accept both shapes.
const txs = ok.length
- ? await conn.getTransactions(
+ ? await conn.getParsedTransactions(
ok.map((s) => s.signature),
{ maxSupportedTransactionVersion: 0 },
)
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 22ebe73d4..7a76786b8 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -397,32 +397,58 @@ async function erc8004CrawlChain(chain) {
});
const toBlock = Math.min(fromBlock + chunkSize - 1, latestBlock);
- // Topic OR-set, not the single Registered topic: an agent's row used to
- // freeze at its registration block because ownership transfers, URI updates
- // and metadata writes were never requested from the RPC at all. See the
- // coverage census in api/_lib/erc8004-registry-events.js.
- const logs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [
- {
- address: chain.registry,
- topics: [REGISTRY_TOPICS],
- fromBlock: '0x' + fromBlock.toString(16),
- toBlock: '0x' + toBlock.toString(16),
- },
- ]);
+ const range = {
+ fromBlock: '0x' + fromBlock.toString(16),
+ toBlock: '0x' + toBlock.toString(16),
+ };
- // The reputation registry lives at its own CREATE2 address on the same
- // network class; scan the identical block range so an agent's trust signals
- // (feedback, revocations, responses) reach the index alongside its identity
- // history. A chain with no reputation deployment yields an empty log list,
- // not an error.
- const reputationLogs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [
- {
- address: reputationRegistryFor(chain.testnet),
- topics: [REPUTATION_TOPICS],
- fromBlock: '0x' + fromBlock.toString(16),
- toBlock: '0x' + toBlock.toString(16),
- },
- ]);
+ let logs;
+ let reputationLogs;
+ try {
+ // Topic OR-set, not the single Registered topic: an agent's row used to
+ // freeze at its registration block because ownership transfers, URI updates
+ // and metadata writes were never requested from the RPC at all. See the
+ // coverage census in api/_lib/erc8004-registry-events.js.
+ logs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [
+ { address: chain.registry, topics: [REGISTRY_TOPICS], ...range },
+ ]);
+
+ // The reputation registry lives at its own CREATE2 address on the same
+ // network class; scan the identical block range so an agent's trust signals
+ // (feedback, revocations, responses) reach the index alongside its identity
+ // history. A chain with no reputation deployment yields an empty log list,
+ // not an error.
+ reputationLogs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [
+ { address: reputationRegistryFor(chain.testnet), topics: [REPUTATION_TOPICS], ...range },
+ ]);
+ } catch (err) {
+ // A range the provider will not serve is the growth loop finding this
+ // chain's real ceiling, not an outage. Halve the window, leave the cursor
+ // where it is, and let the next tick retry the same blocks smaller. Any
+ // other RPC failure is a genuine error and propagates.
+ if (!RANGE_REJECTED.test(String(err?.message || err))) throw err;
+ const reduced = backoffChunkSize(chunkSize);
+ await sql`
+ INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at, head_block, blocks_behind, chunk_size, last_error)
+ VALUES (${chain.id}, ${Math.max(0, fromBlock - 1)}, now(), ${latestBlock},
+ ${Math.max(0, latestBlock - fromBlock + 1)}, ${reduced}, ${'range rejected at ' + chunkSize + ' blocks'})
+ ON CONFLICT (chain_id) DO UPDATE SET
+ updated_at = now(),
+ head_block = excluded.head_block,
+ blocks_behind = excluded.blocks_behind,
+ chunk_size = excluded.chunk_size,
+ last_error = excluded.last_error
+ `;
+ return {
+ inserted: 0,
+ scanned: 0,
+ lastBlock: fromBlock - 1,
+ fromBlock,
+ blocksBehind: Math.max(0, latestBlock - fromBlock + 1),
+ chunkSize: reduced,
+ rangeRejected: true,
+ };
+ }
// Fetch block timestamps for any blocks that produced events.
const blockTimes = {};
@@ -528,12 +554,20 @@ async function erc8004CrawlChain(chain) {
const recorded = events.length ? await recordEvents(events) : { inserted: 0, rejected: 0 };
// Always advance cursor to toBlock so the next run continues from here.
+ // blocks_behind is the honest freshness signal: updated_at only says the cron
+ // ran, and a chain producing blocks faster than the crawl consumes them keeps
+ // a fresh updated_at forever while falling further behind every tick.
+ const blocksBehind = Math.max(0, latestBlock - toBlock);
await sql`
- INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at)
- VALUES (${chain.id}, ${toBlock}, now())
+ INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at, head_block, blocks_behind, chunk_size, last_error)
+ VALUES (${chain.id}, ${toBlock}, now(), ${latestBlock}, ${blocksBehind}, ${chunkSize}, null)
ON CONFLICT (chain_id) DO UPDATE SET
- last_block = GREATEST(erc8004_crawl_cursor.last_block, ${toBlock}),
- updated_at = now()
+ last_block = GREATEST(erc8004_crawl_cursor.last_block, ${toBlock}),
+ updated_at = now(),
+ head_block = excluded.head_block,
+ blocks_behind = excluded.blocks_behind,
+ chunk_size = excluded.chunk_size,
+ last_error = null
`;
return {
@@ -544,9 +578,31 @@ async function erc8004CrawlChain(chain) {
logs: logs.length,
events: recorded.inserted,
byClass,
+ headBlock: latestBlock,
+ blocksBehind,
+ chunkSize,
};
}
+/**
+ * Stamp a caught-up chain's head so the lag monitor can tell "0 blocks behind"
+ * apart from "never measured". A chain with nothing to scan still reports.
+ * @param {number} chainId
+ * @param {number} headBlock
+ * @param {number} lastBlock
+ */
+async function erc8004RecordHead(chainId, headBlock, lastBlock) {
+ await sql`
+ INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at, head_block, blocks_behind, last_error)
+ VALUES (${chainId}, ${lastBlock}, now(), ${headBlock}, 0, null)
+ ON CONFLICT (chain_id) DO UPDATE SET
+ updated_at = now(),
+ head_block = excluded.head_block,
+ blocks_behind = 0,
+ last_error = null
+ `;
+}
+
// Per-class payload for the event index. Keeps the raw on-chain detail that the
// agent-row columns cannot hold (which metadata key changed, the URI at the time
// of the event, whether a transfer was the registration mint).