brainchain-verify 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/verify.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { lookup as dnsLookup, promises as dns } from "node:dns";
2
- import { readFile } from "node:fs/promises";
2
+ import { open, stat } from "node:fs/promises";
3
3
  import { Agent as HttpAgent, request as httpRequest } from "node:http";
4
4
  import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
5
5
  import { BlockList, isIP } from "node:net";
6
6
  import { setTimeout as sleep } from "node:timers/promises";
7
- import { BaseError, createPublicClient, decodeFunctionData, encodeAbiParameters, encodeFunctionData, http, keccak256, pad, parseAbi, parseEventLogs, recoverMessageAddress, recoverTypedDataAddress, toBytes, TransactionReceiptNotFoundError, toHex, } from "viem";
7
+ import { BaseError, createPublicClient, decodeFunctionData, encodeAbiParameters, encodeFunctionData, getAddress, http, keccak256, pad, parseAbi, parseEventLogs, recoverMessageAddress, recoverTypedDataAddress, size, toBytes, TransactionReceiptNotFoundError, toHex, zeroAddress, } from "viem";
8
8
  import { decisionExecutorAbi, decisionLogAbi, modelRegistryAbi, taskBoardAbi } from "./abi.js";
9
9
  import { canonicalStringify } from "./canonical.js";
10
10
  const Kind = { Hire: 1, Grade: 2, Ruling: 3, Change: 4 };
@@ -65,15 +65,49 @@ function rootCause(error) {
65
65
  }
66
66
  return reason;
67
67
  }
68
+ function describe(error) {
69
+ const reason = rootCause(error);
70
+ if (!(error instanceof BaseError))
71
+ return reason ? `${error.message}: ${reason}` : error.message;
72
+ const detail = reason ?? error.details;
73
+ return detail ? `${error.shortMessage} (${detail})` : error.shortMessage;
74
+ }
68
75
  export function errorMessage(error) {
69
76
  if (!(error instanceof Error))
70
77
  return clean(String(error));
71
- const reason = rootCause(error);
72
- if (error instanceof BaseError) {
73
- const detail = reason ?? error.details;
74
- return clean(detail ? `${error.shortMessage} (${detail})` : error.shortMessage);
75
- }
76
- return clean(reason ? `${error.message}: ${reason}` : error.message);
78
+ const rpc = rpcOf(error);
79
+ return clean(rpc ? `${rpc}: ${describe(error)}` : describe(error));
80
+ }
81
+ // Which RPC an error came from, so a failure on --rpc reads apart from one on --registry-rpc.
82
+ const rpcNames = new WeakMap();
83
+ // Only the origin: providers put API keys in the path.
84
+ const rpcLabel = (name, url) => (URL.canParse(url) ? `${name} RPC ${new URL(url).origin}` : `${name} RPC`);
85
+ function fromRpc(error, rpc) {
86
+ if (error instanceof Error)
87
+ rpcNames.set(error, rpc);
88
+ return error;
89
+ }
90
+ function rpcOf(error) {
91
+ for (let next = error; next instanceof Error; next = next.cause) {
92
+ const rpc = rpcNames.get(next);
93
+ if (rpc)
94
+ return rpc;
95
+ }
96
+ return undefined;
97
+ }
98
+ // viem's own default, four tries of 10 seconds, held the tool 40 seconds on an RPC that never answers.
99
+ const RPC_TIMEOUT_MS = 8_000;
100
+ /** An http transport for one RPC, with two tries of 8 seconds, whose errors say which RPC failed: `name` is its chain, as in "BrainChain RPC <origin>". */
101
+ export function rpcTransport(name, url) {
102
+ const transport = http(url, { timeout: RPC_TIMEOUT_MS, retryCount: 1 });
103
+ const rpc = rpcLabel(name, url);
104
+ return (config) => {
105
+ const built = transport(config);
106
+ const request = ((args, options) => built.request(args, options).catch((error) => {
107
+ throw fromRpc(error, rpc);
108
+ }));
109
+ return { ...built, request };
110
+ };
77
111
  }
78
112
  function parseJson(text) {
79
113
  try {
@@ -218,12 +252,17 @@ const MAX_RECORD_BYTES = 4 * 1024 * 1024;
218
252
  const MAX_BRIEF_BYTES = 256 * 1024;
219
253
  const MAX_RECEIPT_BYTES = 64 * 1024;
220
254
  const MAX_MANIFEST_BYTES = 256 * 1024;
221
- /** A location the tool will not read. Trying again would not help. */
255
+ /** A location or payment network the tool will not read. Trying again would not help. */
222
256
  class Refused extends Error {
223
257
  }
258
+ /** More than the thing fetched may be. Not tried again either, but unlike a refused location, a check that could not run. */
259
+ class TooLarge extends Refused {
260
+ }
224
261
  /** A host that answered 404, which for a receipt means it has not been signed yet. */
225
262
  class NotFound extends Error {
226
263
  }
264
+ /** Not there to check: a host's 404, or a location the tool will not read. A host that fails to answer, or sends too much, is a check that could not run. */
265
+ const absent = (error) => error instanceof NotFound || (error instanceof Refused && !(error instanceof TooLarge));
227
266
  const PRIVATE = new BlockList();
228
267
  for (const [net, bits] of [["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16], ["224.0.0.0", 4], ["240.0.0.0", 4]]) {
229
268
  PRIVATE.addSubnet(net, bits, "ipv4");
@@ -288,7 +327,7 @@ function readOnce(uri, url, wanted, signal) {
288
327
  response.on("data", (chunk) => {
289
328
  size += chunk.length;
290
329
  if (size > wanted.limit)
291
- request.destroy(new Refused(`${display(uri)} is larger than the ${Math.round(wanted.limit / 1024)} KB a ${wanted.what} may be, so it was not read`));
330
+ request.destroy(new TooLarge(`${display(uri)} is larger than the ${Math.round(wanted.limit / 1024)} KB a ${wanted.what} may be, so it was not read`));
292
331
  else
293
332
  chunks.push(chunk);
294
333
  });
@@ -323,7 +362,7 @@ async function get(uri, url, wanted, deadline) {
323
362
  async function readBytes(uri, url, wanted, deadline) {
324
363
  const response = await get(uri, url, wanted, deadline);
325
364
  if (response.status === 404) {
326
- const gone = wanted.what === "network manifest" ? "the host has none" : `the host no longer has this ${wanted.what}, so trying again will not help`;
365
+ const gone = wanted.what === "network manifest" ? "the host has none" : `the host has no ${wanted.what} at this address`;
327
366
  throw new NotFound(`${display(uri)} answered with status 404: ${gone}`);
328
367
  }
329
368
  if (response.status < 200 || response.status >= 300)
@@ -334,10 +373,10 @@ async function fetchBytes(uri, wanted) {
334
373
  if (uri.startsWith("data:")) {
335
374
  const comma = uri.indexOf(",");
336
375
  if (comma < 0 || !uri.slice(0, comma).endsWith(";base64"))
337
- throw new Error("only base64 data URIs are supported");
376
+ throw new Refused("only base64 data URIs are supported");
338
377
  const bytes = Uint8Array.from(Buffer.from(uri.slice(comma + 1), "base64"));
339
378
  if (bytes.length > wanted.limit)
340
- throw new Refused(`the ${wanted.what} is larger than the ${Math.round(wanted.limit / 1024)} KB it may be, so it was not read`);
379
+ throw new TooLarge(`the ${wanted.what} is larger than the ${Math.round(wanted.limit / 1024)} KB it may be, so it was not read`);
341
380
  return { bytes, withheld: false };
342
381
  }
343
382
  if (!URL.canParse(uri))
@@ -374,8 +413,8 @@ class Checks {
374
413
  function readDecision({ client, set }, id) {
375
414
  return client.readContract({ address: set.log, abi: decisionLogAbi, functionName: "get", args: [id] });
376
415
  }
377
- /** Bytes that are not what the chain committed to: a disagreement, where an unreachable host is only a check that could not run. */
378
- class BriefMismatch extends Error {
416
+ /** What the chain contradicts, such as bytes that miss their hash: a disagreement, where an unreachable host is only a check that could not run. */
417
+ class Mismatch extends Error {
379
418
  }
380
419
  async function briefOf({ client, set }, task) {
381
420
  const [posted] = await client.getContractEvents({
@@ -390,9 +429,17 @@ async function briefOf({ client, set }, task) {
390
429
  throw new Error(`task ${task} has no Posted event on board ${set.board}`);
391
430
  const { bytes } = await fetchBytes(posted.args.briefURI, { what: "brief", limit: MAX_BRIEF_BYTES, allowPrivate: await allowsPrivate(client) });
392
431
  if (keccak256(bytes) !== posted.args.briefHash.toLowerCase())
393
- throw new BriefMismatch(`task ${task}'s brief does not match its briefHash on chain`);
432
+ throw new Mismatch(`task ${task}'s brief does not match its briefHash on chain`);
394
433
  return parseBrief(decodeText(bytes));
395
434
  }
435
+ /** What a task is about: its brief's title, or the brief's first line, cut to 100 characters. */
436
+ function headline({ title, brief }) {
437
+ const line = [title, brief].flatMap((text) => text.split("\n")).map((l) => l.trim()).find((l) => l.length > 0);
438
+ if (line === undefined)
439
+ return undefined;
440
+ const chars = [...line];
441
+ return clean(chars.length > 100 ? `${chars.slice(0, 99).join("").trimEnd()}…` : line);
442
+ }
396
443
  /** Decision ids about one task on the set's board, oldest first. */
397
444
  export async function decisionsOf({ client, network, set }, task) {
398
445
  const events = await client.getContractEvents({
@@ -450,6 +497,11 @@ export async function verifyDecision(ctx, id, receipt) {
450
497
  }
451
498
  const text = decodeText(fetched.bytes);
452
499
  const record = text === undefined ? undefined : parseJson(text);
500
+ // A proxy's error page says nothing about the record. JSON that is not one is the host's answer.
501
+ if (record === undefined) {
502
+ c.add("fetch", "error", `could not read the record: ${display(location)} sent something other than JSON, such as an error page`);
503
+ return report;
504
+ }
453
505
  if (!isPublished(record)) {
454
506
  c.add("fetch", "fail", `${display(location)} is not a decision record`);
455
507
  return report;
@@ -479,7 +531,7 @@ export async function verifyDecision(ctx, id, receipt) {
479
531
  }
480
532
  c.check("kind", record.kind === kind, `kind: ${record.kind}`, `the record is a ${record.kind}; the chain recorded a ${kind}`);
481
533
  if (decision.kind === Kind.Change) {
482
- c.check("subject", record.subject.toLowerCase() === decision.subject, `subject: ${short(decision.subject)}, the exact call this change names`, "the record's subject differs from the one on chain");
534
+ c.check("subject", record.subject.toLowerCase() === decision.subject, `subject: ${short(decision.subject)}, as recorded on chain. It is tied to the call Jev was shown only once the change is queued`, "the record's subject differs from the one on chain");
483
535
  }
484
536
  else if (outside) {
485
537
  c.add("subject", "ok", outsideSubject(outside));
@@ -533,6 +585,9 @@ export async function verifyDecision(ctx, id, receipt) {
533
585
  if (task !== undefined) {
534
586
  await checkBrief(ctx, c, task, decision, record, state);
535
587
  await checkTaskThreshold(ctx, c, id, task, decision, record);
588
+ const title = await ctx.briefs.get(task)?.then(headline, () => undefined);
589
+ if (title)
590
+ report.title = title;
536
591
  }
537
592
  if (outside) {
538
593
  checkRun(c, decision, record, state, {
@@ -586,7 +641,7 @@ async function withholding(ctx, decision, record, task, outside, block) {
586
641
  const bar = await gradeBar(ctx, block);
587
642
  if (decision.confidenceBps >= bar)
588
643
  return refuse(`this paid grade cleared the ${percent(bar)} bar, so its record is public`);
589
- return { allowed: true, why: `a paid grade is published only once accepted, and ${percent(decision.confidenceBps)} is below the ${percent(bar)} bar` };
644
+ return { allowed: true, why: `a paid grade is published only once accepted, and this one was not: Jev answered ${named(record.answer)}, but at ${percent(decision.confidenceBps)} confidence, below the ${percent(bar)} bar` };
590
645
  }
591
646
  if (task === undefined || taskSubject(network.chainId, set.board, task) !== decision.subject)
592
647
  return refuse("the record does not name the task on chain");
@@ -616,10 +671,18 @@ async function checkBrief(ctx, c, task, decision, record, state) {
616
671
  brief = await pending;
617
672
  }
618
673
  catch (error) {
619
- c.add("brief", error instanceof BriefMismatch ? "fail" : "skip", `brief: ${errorMessage(error)}`);
674
+ c.add("brief", error instanceof Mismatch ? "fail" : absent(error) ? "skip" : "error", `brief: ${errorMessage(error)}`);
620
675
  checkRun(c, decision, record, state);
621
- if (decision.kind === Kind.Grade)
622
- c.add("confidence-recomputed", "skip", "grade confidence: needs the brief's pass level");
676
+ if (decision.kind !== Kind.Grade)
677
+ return;
678
+ if (predatesPaidLevels(record))
679
+ return c.add("confidence-recomputed", "skip", PREDATES_PAID_LEVELS);
680
+ // Without the brief, the record's own pass level still ties the answer to the probabilities.
681
+ const own = ownPassLevel(c, record);
682
+ if (!own)
683
+ return;
684
+ c.add("levels", "skip", `levels: the brief could not be read, so the confidence is recomputed from the record's own ${own.levels} levels, paid from level ${own.passFrom}`);
685
+ checkGradeConfidence(c, record, own.paidKeys);
623
686
  return;
624
687
  }
625
688
  c.check("brief", state.task?.brief === `${brief.title}\n\n${brief.brief}`, `the question quotes task ${task}'s brief, as committed on chain`, `the brief in the question is not task ${task}'s brief`);
@@ -634,10 +697,8 @@ async function checkBrief(ctx, c, task, decision, record, state) {
634
697
  return;
635
698
  const ascending = [...brief.levels].reverse();
636
699
  c.check("levels", same(question.criteria, ascending), "the levels Jev scored against are the brief's, lowest first", "the levels in the question are not the brief's");
637
- if (record.scoreConfidence === undefined && record.panel === undefined) {
638
- c.add("confidence-recomputed", "skip", "grade confidence: this grade predates the rule that gates on the paid levels, so its confidence is Jev's score confidence, which the probabilities alone do not give");
639
- return;
640
- }
700
+ if (predatesPaidLevels(record))
701
+ return c.add("confidence-recomputed", "skip", PREDATES_PAID_LEVELS);
641
702
  checkGradeConfidence(c, record, ascending.map((_, i) => String(i)).slice(ascending.length - 1 - brief.passIndex));
642
703
  }
643
704
  /**
@@ -683,22 +744,31 @@ function checkRun(c, decision, record, state, brief) {
683
744
  const { instructions } = record.request.questions.decision;
684
745
  c.check("checks", typeof instructions === "string" && instructions.endsWith(SHOWN), `${ran}, and the question shows the graders that run`, `${ran}, but the question does not show the graders that run as BrainChain words it`);
685
746
  }
686
- // No brief on chain to compare with. payloadHash commits a whole record's levels and pass level, and nothing commits a withheld record's.
687
- function checkOutsideGrade(c, record, withheld) {
747
+ const predatesPaidLevels = (record) => record.scoreConfidence === undefined && record.panel === undefined;
748
+ const PREDATES_PAID_LEVELS = "grade confidence: this grade predates the rule that gates on the paid levels, so its confidence is Jev's score confidence, which the probabilities alone do not give";
749
+ /** The question's levels and the record's own pass level, where no brief says them. Undefined once a line says why there are none to use. */
750
+ function ownPassLevel(c, record) {
688
751
  const levels = record.request.questions.decision.criteria;
689
752
  const { passFrom } = record;
690
753
  if (!Array.isArray(levels) || passFrom === undefined) {
691
754
  c.add("confidence-recomputed", "skip", "grade confidence: the record does not name its pass level");
692
- return;
755
+ return undefined;
693
756
  }
694
757
  // The lowest level never passes, or every result would.
695
758
  if (typeof passFrom !== "number" || !Number.isInteger(passFrom) || passFrom < 1 || passFrom >= levels.length) {
696
759
  c.add("levels", "fail", `levels: the record's pass level ${JSON.stringify(passFrom)} is not one of levels 1 to ${levels.length - 1} of the ${levels.length} the question lists`);
697
760
  c.add("confidence-recomputed", "skip", "grade confidence: needs a valid pass level");
698
- return;
761
+ return undefined;
699
762
  }
700
- c.add("levels", "skip", `levels: the record's own ${levels.length} levels, paid from level ${passFrom}. No brief on chain says what they should be${withheld ? ", and no hash commits them on this copy" : ""}`);
701
- checkGradeConfidence(c, record, levels.map((_, i) => String(i)).slice(passFrom));
763
+ return { levels: levels.length, passFrom, paidKeys: levels.map((_, i) => String(i)).slice(passFrom) };
764
+ }
765
+ // No brief on chain to compare with. payloadHash commits a whole record's levels and pass level, and nothing commits a withheld record's.
766
+ function checkOutsideGrade(c, record, withheld) {
767
+ const own = ownPassLevel(c, record);
768
+ if (!own)
769
+ return;
770
+ c.add("levels", "skip", `levels: the record's own ${own.levels} levels, paid from level ${own.passFrom}. No brief on chain says what they should be${withheld ? ", and no hash commits them on this copy" : ""}`);
771
+ checkGradeConfidence(c, record, own.paidKeys);
702
772
  }
703
773
  function checkGradeConfidence(c, record, paidKeys) {
704
774
  const parts = paidKeys.map((key) => record.probabilities[key] ?? 0);
@@ -1060,13 +1130,30 @@ function signerOf(receipt) {
1060
1130
  signature: receipt.signature,
1061
1131
  });
1062
1132
  }
1133
+ /** A file, read no further than one byte past `limit`. A device or a pipe can go on for ever, so only a regular file is read. */
1134
+ async function readCapped(path, limit) {
1135
+ const found = await stat(path).catch((error) => {
1136
+ throw ["ENOENT", "ENOTDIR"].includes(error.code ?? "") ? new Refused(`No file at ${display(path)}.`) : error;
1137
+ });
1138
+ if (!found.isFile())
1139
+ throw new Refused(`${display(path)} is not a regular file, so it was not read`);
1140
+ const file = await open(path);
1141
+ try {
1142
+ const bytes = new Uint8Array(limit + 1);
1143
+ const { bytesRead } = await file.read(bytes, 0, bytes.length, 0);
1144
+ return bytes.subarray(0, bytesRead);
1145
+ }
1146
+ finally {
1147
+ await file.close();
1148
+ }
1149
+ }
1063
1150
  /** Reads a receipt from a file or an http(s) URL: the receipt itself, or a reply that carries it as `receipt`. */
1064
1151
  export async function readReceipt(client, source) {
1065
1152
  const bytes = /^https?:\/\//i.test(source)
1066
1153
  ? (await fetchBytes(source, { what: "receipt", limit: MAX_RECEIPT_BYTES, allowPrivate: await allowsPrivate(client) })).bytes
1067
- : await readFile(source);
1154
+ : await readCapped(source, MAX_RECEIPT_BYTES);
1068
1155
  if (bytes.length > MAX_RECEIPT_BYTES)
1069
- throw new Refused(`${display(source)} is larger than the ${MAX_RECEIPT_BYTES / 1024} KB a receipt may be, so it was not read`);
1156
+ throw new TooLarge(`${display(source)} is larger than the ${MAX_RECEIPT_BYTES / 1024} KB a receipt may be, so it was not read`);
1070
1157
  const text = decodeText(bytes);
1071
1158
  const value = text === undefined ? undefined : parseJson(text);
1072
1159
  if (value === undefined)
@@ -1074,6 +1161,8 @@ export async function readReceipt(client, source) {
1074
1161
  const carried = value?.receipt;
1075
1162
  return { from: clean(source), value: typeof carried === "object" && carried !== null ? carried : value };
1076
1163
  }
1164
+ /** Whether a value is a receipt as BrainChain or the x402 extension signs one. */
1165
+ export const isReceipt = (value) => parseReceipt(value) !== undefined;
1077
1166
  /** The decision and log a BrainChain receipt names. The x402 extension's receipt names neither. */
1078
1167
  export function receiptDecision(value) {
1079
1168
  const receipt = parseReceipt(value);
@@ -1100,7 +1189,7 @@ async function servedReceipt(ctx, c, d) {
1100
1189
  const why = error instanceof NotFound
1101
1190
  ? `${display(url)} has none. A task's receipt is signed once the board pays or refunds it, for the grade or ruling it settled on`
1102
1191
  : `could not fetch one: ${errorMessage(error)}`;
1103
- c.add("receipt", "skip", `receipt: ${why}`);
1192
+ c.add("receipt", absent(error) ? "skip" : "error", `receipt: ${why}`);
1104
1193
  return undefined;
1105
1194
  }
1106
1195
  }
@@ -1204,14 +1293,17 @@ async function checkPayment(ctx, c, d, claimed, fields) {
1204
1293
  const origin = hostOf(d.payloadURI);
1205
1294
  if (!origin)
1206
1295
  return c.add("receipt-payment", "skip", `payment: the receipt's payment is the record's. The record is not served by a host, so no network.json names the desk to check ${tx} against`);
1207
- let desk;
1208
- let moved;
1209
- try {
1210
- [desk, moved] = await Promise.all([deskOf(ctx, origin), (ctx.balances ?? balancesOnChain)(network, transaction, asset)]);
1211
- }
1212
- catch (error) {
1213
- return c.add("receipt-payment", "skip", `payment: the receipt's payment is the record's, and ${tx} was not checked: ${errorMessage(error)}`);
1214
- }
1296
+ const [deskRead, movedRead] = await Promise.allSettled([deskOf(ctx, origin), (ctx.balances ?? balancesOnChain)(network, transaction, asset)]);
1297
+ if (deskRead.status === "rejected" || movedRead.status === "rejected") {
1298
+ // A manifest the chain contradicts fails whatever else could not be read, and a host that did not answer outweighs one that has nothing.
1299
+ const reasons = [deskRead, movedRead].flatMap((read) => (read.status === "rejected" ? [read.reason] : []));
1300
+ const reason = reasons.find((r) => r instanceof Mismatch) ?? reasons.find((r) => !absent(r)) ?? reasons[0];
1301
+ if (reason instanceof Mismatch)
1302
+ return c.add("receipt-payment", "fail", `payment: the receipt's payment is the record's, but ${errorMessage(reason)}`);
1303
+ return c.add("receipt-payment", absent(reason) ? "skip" : "error", `payment: the receipt's payment is the record's, and ${tx} was not checked: ${errorMessage(reason)}`);
1304
+ }
1305
+ const desk = deskRead.value;
1306
+ const moved = movedRead.value;
1215
1307
  if (!moved)
1216
1308
  return c.add("receipt-payment", "fail", `payment: ${tx} did not succeed, or is not on that network`);
1217
1309
  const evm = network.startsWith("eip155:");
@@ -1251,69 +1343,90 @@ async function readDesk({ client, network, set }, origin) {
1251
1343
  client.readContract({ address: log, abi: decisionLogAbi, functionName: "brain" }),
1252
1344
  ]);
1253
1345
  if (!eq(signer, brain))
1254
- throw new Error(`${display(uri)} is signed by ${short(signer)}, not by ${short(brain)}, the brain on DecisionLog ${short(log)}`);
1346
+ throw new Mismatch(`${display(uri)} is signed by ${short(signer)}, not by ${short(brain)}, the brain on DecisionLog ${short(log)}`);
1255
1347
  const manifest = parseJson(signed.slice(MANIFEST_PREFIX.length));
1256
1348
  const payees = manifest?.payees;
1257
1349
  const valid = Array.isArray(payees) && payees.every((p) => typeof p === "object" && p !== null && ["network", "asset", "payTo"].every((k) => typeof p[k] === "string"));
1258
1350
  if (manifest?.chainId !== network.chainId || !valid)
1259
- throw new Error(`${display(uri)} does not list the payees of chain ${network.chainId}`);
1351
+ throw new Mismatch(`${display(uri)} does not list the payees of chain ${network.chainId}`);
1260
1352
  const former = Array.isArray(manifest.formerDesks) ? manifest.formerDesks.filter((d) => typeof d === "string") : [];
1261
1353
  return { payees: payees, formerDesks: former };
1262
1354
  }
1355
+ const ROBINHOOD_RPC = "https://rpc.mainnet.chain.robinhood.com";
1356
+ const CHAINS = {
1357
+ "eip155:8453": "Base",
1358
+ "eip155:84532": "Base Sepolia",
1359
+ "eip155:4663": "Robinhood Chain",
1360
+ "eip155:46630": "Robinhood Chain testnet",
1361
+ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "Solana",
1362
+ "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "Solana devnet",
1363
+ };
1263
1364
  // Public RPCs for the networks the desk takes payment on.
1264
1365
  const PAYMENT_RPCS = {
1265
1366
  "eip155:8453": "https://mainnet.base.org",
1266
1367
  "eip155:84532": "https://sepolia.base.org",
1267
- "eip155:4663": "https://rpc.mainnet.chain.robinhood.com",
1368
+ "eip155:4663": ROBINHOOD_RPC,
1268
1369
  "eip155:46630": "https://rpc.testnet.chain.robinhood.com",
1269
1370
  "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "https://api.mainnet-beta.solana.com",
1270
1371
  "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "https://api.devnet.solana.com",
1271
1372
  };
1272
1373
  const TRANSFER = parseAbi(["event Transfer(address indexed from, address indexed to, uint256 value)"]);
1273
- const paymentClients = new Map();
1274
- const balancesOnChain = async (network, transaction, asset) => {
1275
- const rpc = Object.hasOwn(PAYMENT_RPCS, network) ? PAYMENT_RPCS[network] : undefined;
1276
- if (!rpc)
1277
- throw new Error(`the tool has no RPC for ${clean(network)}`);
1278
- if (network.startsWith("solana:"))
1279
- return solanaBalances(rpc, transaction, asset);
1280
- if (!BYTES32.test(transaction))
1281
- return undefined;
1282
- let client = paymentClients.get(network);
1283
- if (!client)
1284
- paymentClients.set(network, (client = createPublicClient({ transport: http(rpc) })));
1285
- const receipt = await client.getTransactionReceipt({ hash: transaction }).catch((error) => {
1286
- if (error instanceof TransactionReceiptNotFoundError)
1374
+ const UNSEEN = "the RPC does not find it yet: a node that lags, or a Solana transaction not yet finalized, can miss one";
1375
+ /** Reads payment transactions from the RPC given for each CAIP-2 network, such as eip155:8453. */
1376
+ export function balancesFrom(rpcs) {
1377
+ const clients = new Map();
1378
+ return async (network, transaction, asset) => {
1379
+ const rpc = Object.hasOwn(rpcs, network) ? rpcs[network] : undefined;
1380
+ if (!rpc)
1381
+ throw new Refused(`the tool has no RPC for ${clean(network)}`);
1382
+ const name = Object.hasOwn(CHAINS, network) ? CHAINS[network] : clean(network);
1383
+ if (network.startsWith("solana:"))
1384
+ return solanaBalances(name, rpc, transaction, asset);
1385
+ if (!BYTES32.test(transaction))
1287
1386
  return undefined;
1288
- throw error;
1289
- });
1290
- if (receipt?.status !== "success")
1291
- return undefined;
1292
- const changes = new Map();
1293
- const add = (owner, value) => changes.set(owner.toLowerCase(), (changes.get(owner.toLowerCase()) ?? 0n) + value);
1294
- for (const { address, args } of parseEventLogs({ abi: TRANSFER, logs: receipt.logs, eventName: "Transfer", strict: true })) {
1295
- if (!eq(address, asset))
1296
- continue;
1297
- add(args.from, -args.value);
1298
- add(args.to, args.value);
1299
- }
1300
- return changes;
1301
- };
1387
+ let client = clients.get(network);
1388
+ if (!client)
1389
+ clients.set(network, (client = createPublicClient({ transport: rpcTransport(name, rpc) })));
1390
+ const receipt = await client.getTransactionReceipt({ hash: transaction }).catch((error) => {
1391
+ throw error instanceof TransactionReceiptNotFoundError ? new Error(UNSEEN) : error;
1392
+ });
1393
+ if (receipt.status !== "success")
1394
+ return undefined;
1395
+ const changes = new Map();
1396
+ const add = (owner, value) => changes.set(owner.toLowerCase(), (changes.get(owner.toLowerCase()) ?? 0n) + value);
1397
+ for (const { address, args } of parseEventLogs({ abi: TRANSFER, logs: receipt.logs, eventName: "Transfer", strict: true })) {
1398
+ if (!eq(address, asset))
1399
+ continue;
1400
+ add(args.from, -args.value);
1401
+ add(args.to, args.value);
1402
+ }
1403
+ return changes;
1404
+ };
1405
+ }
1406
+ const balancesOnChain = balancesFrom(PAYMENT_RPCS);
1302
1407
  /** A Solana transaction's change to each owner's balance of the mint, from its token balances before and after. */
1303
- async function solanaBalances(rpc, signature, mint) {
1304
- const response = await fetch(rpc, {
1408
+ async function solanaBalances(name, rpc, signature, mint) {
1409
+ const label = rpcLabel(name, rpc);
1410
+ const { result, error } = await fetch(rpc, {
1305
1411
  method: "POST",
1306
1412
  headers: { "content-type": "application/json", "user-agent": "brainchain-verify" },
1307
1413
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getTransaction", params: [signature, { encoding: "jsonParsed", commitment: "finalized", maxSupportedTransactionVersion: 0 }] }),
1308
- signal: AbortSignal.timeout(FETCH_MS),
1414
+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
1415
+ })
1416
+ .then(async (response) => {
1417
+ if (!response.ok)
1418
+ throw new Error(`answered with status ${response.status}`);
1419
+ return (await response.json());
1420
+ })
1421
+ .catch((reason) => {
1422
+ throw fromRpc(reason, label);
1309
1423
  });
1310
- if (!response.ok)
1311
- throw new Error(`${rpc} answered with status ${response.status}`);
1312
- const { result, error } = (await response.json());
1313
1424
  if (error)
1314
- throw new Error(`${rpc} answered: ${clean(String(error.message))}`);
1425
+ throw fromRpc(new Error(clean(String(error.message))), label);
1315
1426
  const meta = result?.meta;
1316
- if (!meta || meta.err !== null)
1427
+ if (!meta)
1428
+ throw new Error(UNSEEN);
1429
+ if (meta.err !== null)
1317
1430
  return undefined;
1318
1431
  const changes = new Map();
1319
1432
  for (const [sign, balances] of [[-1n, meta.preTokenBalances], [1n, meta.postTokenBalances]]) {
@@ -1350,3 +1463,308 @@ export function withheldNotChecked(reports) {
1350
1463
  ? "Its answer and confidence agree with the chain. The rest of it, such as the question, its levels and the second grader, is the host's word."
1351
1464
  : "Its answer and confidence agree with the chain, and so do the task's brief, levels and threshold. The rest of it, such as the question and the second grader, is the host's word."));
1352
1465
  }
1466
+ /** BrainChain mainnet's: the registries on Robinhood Chain, and the addresses and agents its docs list (workers#erc-8004-identity). */
1467
+ export const REPUTATION = {
1468
+ network: 274663,
1469
+ chainId: 4663,
1470
+ rpc: ROBINHOOD_RPC,
1471
+ address: "0x8004BAa17C55a88189AE136b182e5fdA19dE9b63",
1472
+ identity: "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432",
1473
+ // The desk key since 10 November 2026, and the one before it.
1474
+ writers: ["0x97D558417c3D61f1074422AD843e1Db1E565b952", "0xafB0C4Ef895D4895040cdC6435B96D3EE8350c6E"],
1475
+ fromBlock: 103375137n,
1476
+ house: { 20424: "claude", 20425: "gpt", 20426: "gemini", 20427: "grok", 20428: "deepseek" },
1477
+ };
1478
+ // EIP-8004's registries, as deployed on Robinhood Chain.
1479
+ const reputationAbi = parseAbi([
1480
+ "event NewFeedback(uint256 indexed agentId, address indexed clientAddress, uint64 feedbackIndex, int128 value, uint8 valueDecimals, string indexed indexedTag1, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash)",
1481
+ "function readFeedback(uint256 agentId, address clientAddress, uint64 feedbackIndex) view returns (int128 value, uint8 valueDecimals, string tag1, string tag2, bool isRevoked)",
1482
+ ]);
1483
+ const identityAbi = parseAbi([
1484
+ "event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)",
1485
+ "event MetadataSet(uint256 indexed agentId, string indexed indexedMetadataKey, string metadataKey, bytes metadataValue)",
1486
+ ]);
1487
+ const TAG = "brainchain";
1488
+ // Robinhood Chain's RPC reads logs over at most this many blocks, and only when each topic it filters on has one value.
1489
+ const LOG_SPAN = 10000000n;
1490
+ // An outside worker's model id is its address, left-padded to 32 bytes.
1491
+ const PADDED = /^0x0{24}([0-9a-f]{40})$/i;
1492
+ const NO_RECEIPT = "no receipt: the entry's feedbackHash is zero. Only a task an agent paid BrainChain for has a signed receipt; house tasks, tasks posted straight on the board, ACP orders and older entries have none";
1493
+ export const entryName = (registry, f) => `${f.agentId}:${eq(f.clientAddress, registry.writers[0] ?? "") ? "" : `${f.clientAddress}:`}${f.feedbackIndex}`;
1494
+ /** An entry as its NewFeedback event states it, with `checks` as its own. */
1495
+ export function entryReport(registry, f, checks) {
1496
+ return {
1497
+ entry: entryName(registry, f),
1498
+ agentId: f.agentId.toString(),
1499
+ clientAddress: f.clientAddress,
1500
+ feedbackIndex: Number(f.feedbackIndex),
1501
+ value: Number(f.value),
1502
+ block: Number(f.block),
1503
+ transaction: f.transaction,
1504
+ endpoint: clean(f.endpoint),
1505
+ feedbackURI: clean(f.feedbackURI),
1506
+ feedbackHash: f.feedbackHash,
1507
+ checks,
1508
+ };
1509
+ }
1510
+ /** Every entry BrainChain wrote for an agent, from the writers given or all of its own, oldest first. */
1511
+ export async function entriesOf(registry, agentId, writers = registry.writers) {
1512
+ const { client, address } = registry;
1513
+ const head = await client.getBlockNumber();
1514
+ const found = [];
1515
+ for (const writer of writers) {
1516
+ for (let from = registry.fromBlock; from <= head; from += LOG_SPAN) {
1517
+ const toBlock = from + LOG_SPAN - 1n < head ? from + LOG_SPAN - 1n : head;
1518
+ const events = await client.getContractEvents({ address, abi: reputationAbi, eventName: "NewFeedback", args: { agentId, clientAddress: writer }, fromBlock: from, toBlock, strict: true });
1519
+ for (const { args, blockNumber, transactionHash } of events) {
1520
+ const { indexedTag1: _, ...entry } = args;
1521
+ found.push({ ...entry, block: blockNumber, transaction: transactionHash });
1522
+ }
1523
+ }
1524
+ }
1525
+ return found.sort((a, b) => (a.block === b.block ? Number(a.feedbackIndex - b.feedbackIndex) : a.block < b.block ? -1 : 1));
1526
+ }
1527
+ /**
1528
+ * One entry, end to end: as the registry holds it, the task its endpoint
1529
+ * names, the receipt its feedbackHash commits to, the decision and payment
1530
+ * that receipt names, and the board's settlement and hire behind its value
1531
+ * and its agent.
1532
+ */
1533
+ export async function verifyEntry(ctx, registry, f) {
1534
+ const c = new Checks();
1535
+ const report = entryReport(registry, f, c.list);
1536
+ await checkStored(registry, c, f);
1537
+ const page = taskPage(ctx.network.sets, f.endpoint);
1538
+ if (page)
1539
+ report.task = Number(page.task);
1540
+ if (page?.board)
1541
+ report.board = page.board;
1542
+ if (page?.set)
1543
+ report.set = page.set.key;
1544
+ checkEndpoint(c, f.endpoint, page);
1545
+ let receipt;
1546
+ if (eq(f.feedbackHash, NO))
1547
+ c.add("feedback-hash", "skip", NO_RECEIPT);
1548
+ else
1549
+ receipt = await entryReceipt(ctx, c, f);
1550
+ if (receipt) {
1551
+ const on = contextFor(ctx, receipt.set);
1552
+ const decided = await verifyDecision(on, receipt.decision, receipt.given);
1553
+ c.list.push(...decided.checks);
1554
+ report.decision = { ...decided, set: receipt.set.key };
1555
+ if (decided.withheld)
1556
+ report.withheld = true;
1557
+ await checkEntryTask(on, c, receipt.decision, page);
1558
+ }
1559
+ if (page?.set) {
1560
+ const placed = { task: page.task, set: page.set };
1561
+ await checkValue(ctx, c, f, placed, receipt?.outcome);
1562
+ await checkWorker(ctx, registry, c, f, placed);
1563
+ }
1564
+ return report;
1565
+ }
1566
+ /** The entry as the registry holds it beside its event, under BrainChain's tags and on its scale. */
1567
+ async function checkStored({ client, address }, c, f) {
1568
+ const [value, decimals, tag1, tag2, revoked] = await client.readContract({ address, abi: reputationAbi, functionName: "readFeedback", args: [f.agentId, f.clientAddress, f.feedbackIndex] });
1569
+ const wrong = [];
1570
+ if (value !== f.value || decimals !== f.valueDecimals || tag1 !== f.tag1 || tag2 !== f.tag2) {
1571
+ wrong.push(`the registry holds ${value} with ${decimals} decimals under ${tag1} and ${tag2}, where its NewFeedback event says ${f.value} with ${f.valueDecimals} under ${f.tag1} and ${f.tag2}`);
1572
+ }
1573
+ if (f.tag1 !== TAG || f.tag2 !== "task")
1574
+ wrong.push(`its tags are ${f.tag1} and ${f.tag2}, where BrainChain writes ${TAG} and task`);
1575
+ if (f.valueDecimals !== 0 || (f.value !== 0n && f.value !== 100n))
1576
+ wrong.push(`its value is ${f.value} with ${f.valueDecimals} decimals, where BrainChain writes 100 or 0 with none`);
1577
+ c.check("entry", wrong.length === 0, `entry: value ${f.value} for agent ${f.agentId} under ${TAG} and task, written by ${short(f.clientAddress)} in block ${f.block}, as the registry holds it${revoked ? ". Revoked since, so the registry's summaries leave it out" : ""}`, `entry: ${wrong.join("; ")}`);
1578
+ }
1579
+ /** The task page BrainChain names as an entry's endpoint: `task?id=<task>&board=<TaskBoard>`, or the id alone before 5 November. */
1580
+ function taskPage(sets, endpoint) {
1581
+ if (!URL.canParse(endpoint))
1582
+ return undefined;
1583
+ const url = new URL(endpoint);
1584
+ const id = url.searchParams.get("id");
1585
+ const board = url.searchParams.get("board");
1586
+ if (!url.pathname.endsWith("/task") || id === null || !/^[1-9]\d{0,77}$/.test(id) || (board !== null && !ADDRESS.test(board)))
1587
+ return undefined;
1588
+ if (board === null)
1589
+ return { task: BigInt(id) };
1590
+ return { task: BigInt(id), board: getAddress(board), set: sets.find((s) => eq(s.board, board)) };
1591
+ }
1592
+ function checkEndpoint(c, endpoint, page) {
1593
+ if (!page)
1594
+ return c.add("endpoint", "fail", `endpoint: ${display(endpoint)} is not a task page, which BrainChain names in every entry`);
1595
+ if (!page.board) {
1596
+ return c.add("endpoint", "skip", `endpoint: task ${page.task}, on no board. Entries from before 5 November name the task alone, and task ids restart with each board, so the task's checks did not run`);
1597
+ }
1598
+ if (!page.set)
1599
+ return c.add("endpoint", "skip", `endpoint: task ${page.task} on board ${short(page.board)}, none of the contract sets this tool carries, so the task's checks did not run`);
1600
+ c.add("endpoint", "ok", `endpoint: task ${page.task} on board ${short(page.board)}, contract set ${page.set.key}`);
1601
+ }
1602
+ /** The receipt at feedbackURI, once its bytes hash to feedbackHash and it names a decision the DecisionLog it names holds, at the address the brain serves that receipt from. */
1603
+ async function entryReceipt(ctx, c, f) {
1604
+ let bytes;
1605
+ try {
1606
+ ({ bytes } = await fetchBytes(f.feedbackURI, { what: "receipt", limit: MAX_RECEIPT_BYTES, allowPrivate: await allowsPrivate(ctx.client) }));
1607
+ }
1608
+ catch (error) {
1609
+ c.add("feedback-hash", "error", `could not fetch the receipt: ${errorMessage(error)}`);
1610
+ return undefined;
1611
+ }
1612
+ const hash = keccak256(bytes);
1613
+ const where = display(f.feedbackURI);
1614
+ if (!eq(hash, f.feedbackHash)) {
1615
+ c.add("feedback-hash", "fail", `feedback hash: the receipt at ${where} hashes to ${short(hash)}, not to feedbackHash ${short(f.feedbackHash)}`);
1616
+ return undefined;
1617
+ }
1618
+ c.add("feedback-hash", "ok", `feedback hash: the receipt at ${where} hashes to feedbackHash ${short(hash)}`);
1619
+ const text = decodeText(bytes);
1620
+ const value = text === undefined ? undefined : parseJson(text);
1621
+ const receipt = parseReceipt(value);
1622
+ if (!receipt || receipt.x402) {
1623
+ c.add("entry-receipt", "fail", `receipt: ${where} is not a receipt as BrainChain signs one`);
1624
+ return undefined;
1625
+ }
1626
+ const { decision, decisionLog, outcome } = receipt.payload;
1627
+ const set = ctx.network.sets.find((s) => eq(s.log, decisionLog));
1628
+ if (!set) {
1629
+ c.add("entry-receipt", "fail", `receipt: names DecisionLog ${short(decisionLog)}, none of the contract sets on ${ctx.network.name}`);
1630
+ return undefined;
1631
+ }
1632
+ const recorded = await ctx.client.readContract({ address: set.log, abi: decisionLogAbi, functionName: "count" });
1633
+ const path = `/receipts/${decisionLog.toLowerCase()}/${decision}.json`;
1634
+ const wrong = [];
1635
+ if (BigInt(decision) < 1n || BigInt(decision) > recorded)
1636
+ wrong.push(`decision ${decision}, and DecisionLog ${short(set.log)} holds decisions 1 to ${recorded}`);
1637
+ if (!URL.canParse(f.feedbackURI) || new URL(f.feedbackURI).pathname !== path)
1638
+ wrong.push(`decision ${decision} on DecisionLog ${short(set.log)}, whose receipt the brain serves at ${path}, not at ${where}`);
1639
+ c.check("entry-receipt", wrong.length === 0, `receipt: names decision ${decision} on DecisionLog ${short(set.log)}, contract set ${set.key}, and is served at that decision's address`, `receipt: names ${list(wrong)}`);
1640
+ return wrong.length === 0 ? { decision: BigInt(decision), set, given: { from: clean(f.feedbackURI), value }, outcome } : undefined;
1641
+ }
1642
+ const setContexts = new WeakMap();
1643
+ /** The context for another contract set on the same network, kept so each set's briefs and desk are read once. */
1644
+ function contextFor(ctx, set) {
1645
+ if (set === ctx.set)
1646
+ return ctx;
1647
+ let known = setContexts.get(ctx);
1648
+ if (!known)
1649
+ setContexts.set(ctx, (known = new Map()));
1650
+ let found = known.get(set.key);
1651
+ if (!found)
1652
+ known.set(set.key, (found = { ...ctx, set, briefs: new Map() }));
1653
+ return found;
1654
+ }
1655
+ async function checkEntryTask(ctx, c, id, page) {
1656
+ if (!page?.set)
1657
+ return c.add("entry-task", "skip", `task: the endpoint names no task on a board this tool carries, so decision ${id} is not tied to one`);
1658
+ const { subject } = await readDecision(ctx, id);
1659
+ const board = short(page.set.board);
1660
+ c.check("entry-task", subject === taskSubject(ctx.network.chainId, page.set.board, page.task), `task: decision ${id} is about task ${page.task} on board ${board}, the task the endpoint names`, `task: decision ${id} on DecisionLog ${short(ctx.set.log)} is not about task ${page.task} on board ${board}, the task the endpoint names`);
1661
+ }
1662
+ /** BrainChain writes 100 for a task the board paid and 0 for one it refunded, and a task's receipt says accepted or rejected for the same. */
1663
+ async function checkValue({ client }, c, f, { task, set }, outcome) {
1664
+ const on = await client.readContract({ address: set.board, abi: taskBoardAbi, functionName: "get", args: [task] });
1665
+ const settled = on.status === Status.Paid ? "paid" : on.status === Status.Refunded ? "refunded" : undefined;
1666
+ if (!settled) {
1667
+ return c.add("entry-value", "fail", `value: task ${task} is ${STATUS[on.status] ?? `status ${on.status}`}. The board has neither paid nor refunded it, and BrainChain writes an entry only once it has`);
1668
+ }
1669
+ const owed = settled === "paid" ? 100n : 0n;
1670
+ const wrong = [];
1671
+ if (f.value !== owed)
1672
+ wrong.push(`the board ${settled} task ${task}, which BrainChain writes as ${owed}`);
1673
+ if (outcome !== undefined && outcome !== (f.value === 100n ? "accepted" : "rejected"))
1674
+ wrong.push(`the receipt says ${outcome}`);
1675
+ c.check("entry-value", wrong.length === 0, `value: ${f.value}, as the board ${settled} task ${task}${outcome === undefined ? "" : ` and the receipt says ${outcome}`}`, `value: ${f.value}, but ${list(wrong)}`);
1676
+ }
1677
+ /** The worker the board hired for the task is the agent: a house worker by its model name, an outside worker by an address that held the agent when it was hired. */
1678
+ async function checkWorker(ctx, registry, c, f, { task, set }) {
1679
+ const hires = await ctx.client.getContractEvents({ address: set.board, abi: taskBoardAbi, eventName: "WorkerHired", args: { id: task }, fromBlock: BigInt(set.fromBlock), strict: true });
1680
+ const hired = hires.at(-1);
1681
+ if (!hired)
1682
+ return c.add("entry-worker", "fail", `worker: the board hired no worker for task ${task}`);
1683
+ const model = hired.args.model.toLowerCase();
1684
+ const agent = f.agentId.toString();
1685
+ const named = (id) => {
1686
+ const house = Object.entries(registry.house).find(([, name]) => keccak256(toBytes(name)) === id);
1687
+ return house ? `${house[1]}, house agent ${house[0]}` : `model ${short(id)}`;
1688
+ };
1689
+ const house = registry.house[agent];
1690
+ if (house !== undefined) {
1691
+ c.check("entry-worker", keccak256(toBytes(house)) === model, `worker: the board hired ${house} for task ${task} as keccak256("${house}"), and agent ${agent} is the house worker ${house}`, `worker: agent ${agent} is the house worker ${house}, and the board hired ${named(model)} for task ${task}`);
1692
+ return;
1693
+ }
1694
+ const account = PADDED.exec(model)?.[1];
1695
+ if (!account)
1696
+ return c.add("entry-worker", "fail", `worker: the board hired ${named(model)} for task ${task}, which no outside agent can be`);
1697
+ const worker = getAddress(`0x${account}`);
1698
+ const { timestamp } = await ctx.client.getBlock({ blockNumber: hired.blockNumber });
1699
+ const held = await holderAt(registry, f.agentId, timestamp);
1700
+ const as = held.owner && eq(held.owner, worker) ? "owned" : held.wallet && eq(held.wallet, worker) ? "was the registered wallet of" : undefined;
1701
+ const holder = held.owner ? `${short(held.owner)} owned it${held.wallet ? ` and ${short(held.wallet)} was its wallet` : ""}` : "nobody held it";
1702
+ c.check("entry-worker", as !== undefined, `worker: the board hired ${short(worker)} for task ${task}, which ${as} agent ${agent} on the identity registry when it was hired`, `worker: the board hired ${short(worker)} for task ${task}, but when it was hired ${holder} on the identity registry`);
1703
+ }
1704
+ const identities = new WeakMap();
1705
+ /** Who owned the agent and which wallet it had registered at `time`, replayed from its events: the registry clears the wallet when the agent changes hands. */
1706
+ async function holderAt(registry, agentId, time) {
1707
+ let known = identities.get(registry);
1708
+ if (!known)
1709
+ identities.set(registry, (known = new Map()));
1710
+ let pending = known.get(agentId);
1711
+ if (!pending)
1712
+ known.set(agentId, (pending = identityEvents(registry, agentId)));
1713
+ let owner;
1714
+ let wallet;
1715
+ for (const event of await pending) {
1716
+ if (event.time > time)
1717
+ break;
1718
+ if (event.transfer) {
1719
+ owner = event.transfer.to === zeroAddress ? undefined : event.transfer.to;
1720
+ if (event.transfer.from !== zeroAddress)
1721
+ wallet = undefined;
1722
+ }
1723
+ else {
1724
+ wallet = event.wallet && size(event.wallet) === 20 ? getAddress(event.wallet) : undefined;
1725
+ }
1726
+ }
1727
+ return { ...(owner ? { owner } : {}), ...(wallet ? { wallet } : {}) };
1728
+ }
1729
+ /** The agent's transfers and agentWallet changes, oldest first, read back from the head to its mint. */
1730
+ async function identityEvents({ client, identity }, agentId) {
1731
+ const found = [];
1732
+ for (let to = await client.getBlockNumber();;) {
1733
+ const fromBlock = to >= LOG_SPAN ? to - LOG_SPAN + 1n : 0n;
1734
+ const span = { address: identity, abi: identityAbi, fromBlock, toBlock: to, strict: true };
1735
+ const [transfers, wallets] = await Promise.all([
1736
+ client.getContractEvents({ ...span, eventName: "Transfer", args: { tokenId: agentId } }),
1737
+ client.getContractEvents({ ...span, eventName: "MetadataSet", args: { agentId, indexedMetadataKey: "agentWallet" } }),
1738
+ ]);
1739
+ for (const { args, blockNumber, logIndex } of transfers)
1740
+ found.push({ block: blockNumber, index: logIndex, event: { transfer: { from: args.from, to: args.to } } });
1741
+ for (const { args, blockNumber, logIndex } of wallets)
1742
+ found.push({ block: blockNumber, index: logIndex, event: { wallet: args.metadataValue } });
1743
+ if (fromBlock === 0n || transfers.some((t) => t.args.from === zeroAddress))
1744
+ break;
1745
+ to = fromBlock - 1n;
1746
+ }
1747
+ found.sort((a, b) => (a.block === b.block ? a.index - b.index : a.block < b.block ? -1 : 1));
1748
+ const times = new Map();
1749
+ for (const { block } of found)
1750
+ if (!times.has(block))
1751
+ times.set(block, client.getBlock({ blockNumber: block }).then((b) => b.timestamp));
1752
+ return Promise.all(found.map(async ({ block, event }) => ({ ...event, time: await times.get(block) })));
1753
+ }
1754
+ /** As for decisions, and `no-receipt` when everything passed and no entry had a receipt to check. */
1755
+ export function entryOutcome(reports) {
1756
+ const outcome = outcomeOf(reports);
1757
+ return outcome === "match" && reports.every((r) => eq(r.feedbackHash, NO)) ? "no-receipt" : outcome;
1758
+ }
1759
+ export function entrySummary(reports) {
1760
+ const outcomes = reports.map((r) => entryOutcome([r]));
1761
+ const count = (outcome) => outcomes.filter((o) => o === outcome).length;
1762
+ return {
1763
+ entries: reports.length,
1764
+ withReceipt: reports.filter((r) => !eq(r.feedbackHash, NO)).length,
1765
+ verified: count("match"),
1766
+ withheld: count("withheld"),
1767
+ failed: count("mismatch"),
1768
+ unverified: count("unverified"),
1769
+ };
1770
+ }