@priors/mcp 0.12.2 → 0.14.0

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.
@@ -0,0 +1,562 @@
1
+ // ERC-8004 credit profile ("erc8004-credit/v1", docs/ERC-8004-CREDIT.md): credit history written as ordinary
2
+ // ERC-8004 reputation entries, lender-neutral. Pure, no network: the writer builds leaves, roots and files here; the
3
+ // reader (sdk/credit-reader.mjs) decodes and checks them against the chain.
4
+ //
5
+ // One idea carries it: a credit event is only worth what the chain can prove. Every closed loan is a leaf that names
6
+ // the lender's own log (tx hash and log index) that closed it; a statement commits to all of an agent's closed loans in
7
+ // a block window with a Merkle root, and any reader can rebuild that root from the lender's logs alone. Statements of
8
+ // one (writer, agent) are chained by hash and windows are contiguous, so a lender cannot drop a default from a source it
9
+ // declares without leaving a gap or a mismatch anyone can see.
10
+ //
11
+ // Entries (tag1, value with valueDecimals = the asset's decimals, tag2 = the class):
12
+ // credit.statement value = principal repaid on time in the window; file = the statement
13
+ // credit.defaulted value = principal defaulted; one entry per default, posted when it happens; file = its leaf
14
+ // Classes: "unsecured", "secured:<kind>" (stock, pt, lst, stable, nft, other). A statement's tag2 is its loans' class,
15
+ // or "mixed" when the window holds more than one; the per-class split is in the file. The class is the lender's claim
16
+ // (a lender's logs do not say it in a standard way); everything else in a statement is rebuilt from the chain.
17
+ //
18
+ // Files are canonical JSON (RFC 8785 for the values used here: keys sorted, no whitespace, integers only), so one file
19
+ // has one byte string and one meaning. Ids (agentId, loan) and amounts are decimal strings: they are uint256.
20
+ import { ethers } from "ethers";
21
+
22
+ export const PROFILE = "erc8004-credit/v1";
23
+ export const TAG_STATEMENT = "credit.statement";
24
+ export const TAG_DEFAULTED = "credit.defaulted";
25
+ export const TAGS = [TAG_STATEMENT, TAG_DEFAULTED];
26
+ /** Leaf outcomes. RECOVERED is reserved: a v1 file never carries it. */
27
+ export const ON_TIME = 1, LATE = 2, DEFAULTED = 3, RECOVERED = 4;
28
+ export const OUTCOMES = { [ON_TIME]: "onTime", [LATE]: "late", [DEFAULTED]: "defaulted", [RECOVERED]: "recovered" };
29
+ export const ANCHORS = 5; // the latest leaves a statement carries in full, so a light reader can check without a log scan
30
+ export const MAX_FILE_BYTES = 4096; // the writer's target: anchors are dropped (oldest first, never a total or the root) to fit
31
+ export const FILE_LIMIT = 8192; // no v1 file is larger; a reader rejects one that is
32
+ export const MAX_SOURCES = 16, MAX_ANCHORS = 16;
33
+ export const DATA_URI_PREFIX = "data:application/json;base64,";
34
+ export const MIXED = "mixed";
35
+ export const CLASSES = ["unsecured", "secured:stock", "secured:pt", "secured:lst", "secured:stable", "secured:nft", "secured:other"];
36
+
37
+ const abi = ethers.AbiCoder.defaultAbiCoder();
38
+ const big = (v) => BigInt(String(v ?? 0));
39
+ const lc = (a) => String(a || "").toLowerCase();
40
+ const UINT256_MAX = 2n ** 256n - 1n, INT128_MAX = 2n ** 127n - 1n, UINT32_MAX = 2 ** 32 - 1;
41
+ const DEC = /^(0|[1-9][0-9]{0,77})$/;
42
+
43
+ /**
44
+ * A uint256 (an agent id, a loan id, an amount) as a BigInt, from a bigint, a decimal string or a Number that is an
45
+ * exact integer. A Number past 2^53 has already lost digits, so it is refused rather than rounded.
46
+ */
47
+ export function toId(v, what = "id") {
48
+ if (typeof v === "number") {
49
+ if (Number.isSafeInteger(v) && v >= 0) return BigInt(v);
50
+ throw new RangeError(`${what} ${v} is not an exact integer: pass it as a decimal string or a bigint`);
51
+ }
52
+ if (typeof v === "bigint" && v >= 0n && v <= UINT256_MAX) return v;
53
+ if (typeof v === "string" && DEC.test(v) && BigInt(v) <= UINT256_MAX) return BigInt(v);
54
+ throw new TypeError(`${what} must be a uint256 (a bigint or a decimal string), not ${typeof v === "string" ? JSON.stringify(v.slice(0, 40)) : String(v).slice(0, 40)}`);
55
+ }
56
+ const dec = (v, what) => toId(v, what).toString();
57
+
58
+ /** Leaf fields, as committed: (chainId, contract, agentId, loanId, amount, dueAt, closedAt, outcome, txHash, logIndex). */
59
+ export const LEAF_TYPES = ["uint256", "address", "uint256", "uint256", "uint256", "uint64", "uint64", "uint8", "bytes32", "uint32"];
60
+
61
+ /**
62
+ * A leaf's hash: keccak256(bytes.concat(keccak256(abi.encode(...)))), the double hash OpenZeppelin's MerkleProof
63
+ * expects (a leaf can never be mistaken for an inner node). `src` is the leaf's source ({ chainId, contract }).
64
+ */
65
+ export function leafHash(leaf, src, agentId) {
66
+ const inner = ethers.keccak256(abi.encode(LEAF_TYPES, [
67
+ big(src.chainId), ethers.getAddress(src.contract), toId(agentId, "agentId"), toId(leaf.loan, "loan"), toId(leaf.amount, "amount"),
68
+ toId(leaf.dueAt, "dueAt"), toId(leaf.closedAt, "closedAt"), Number(leaf.outcome), leaf.tx, Number(leaf.log),
69
+ ]));
70
+ return ethers.keccak256(inner);
71
+ }
72
+
73
+ /** Commutative pair hash (OpenZeppelin MerkleProof._hashPair). */
74
+ const pair = (a, b) => (BigInt(a) < BigInt(b) ? ethers.keccak256(ethers.concat([a, b])) : ethers.keccak256(ethers.concat([b, a])));
75
+
76
+ /** Merkle levels over leaf hashes in leaf order; an odd node is carried up unchanged. levels[0] = leaves. */
77
+ function levels(hashes) {
78
+ const out = [hashes.slice()];
79
+ while (out.at(-1).length > 1) {
80
+ const cur = out.at(-1), next = [];
81
+ for (let i = 0; i < cur.length; i += 2) next.push(i + 1 < cur.length ? pair(cur[i], cur[i + 1]) : cur[i]);
82
+ out.push(next);
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /** The root of a list of leaf hashes; ZeroHash for none. */
88
+ export function merkleRoot(hashes) {
89
+ if (!hashes.length) return ethers.ZeroHash;
90
+ return levels(hashes).at(-1)[0];
91
+ }
92
+
93
+ /** The proof for leaf `i` (verifies with OpenZeppelin MerkleProof.verify(proof, root, leafHash)). */
94
+ export function merkleProof(hashes, i) {
95
+ const proof = [];
96
+ let idx = i;
97
+ for (const lvl of levels(hashes).slice(0, -1)) {
98
+ const sib = idx ^ 1;
99
+ if (sib < lvl.length) proof.push(lvl[sib]);
100
+ idx >>= 1;
101
+ }
102
+ return proof;
103
+ }
104
+
105
+ export function verifyProof(proof, root, leaf) {
106
+ let h = leaf;
107
+ for (const p of proof) h = pair(h, p);
108
+ return h === root;
109
+ }
110
+
111
+ /** Leaves in their committed order: by close block, then log index (then source, for two sources in one block). */
112
+ export function sortLeaves(leaves) {
113
+ return leaves.slice().sort((a, b) => Number(a.block) - Number(b.block) || Number(a.log) - Number(b.log) || Number(a.src || 0) - Number(b.src || 0));
114
+ }
115
+
116
+ /** Root over leaves (already sorted) given the statement's sources. */
117
+ export function rootOf(leaves, sources, agentId) {
118
+ return merkleRoot(leaves.map((l) => leafHash(l, sources[Number(l.src || 0)], agentId)));
119
+ }
120
+
121
+ /** The outcome a leaf must carry, from what the chain says: a default, or a repayment on time or late. */
122
+ export const outcomeOf = ({ defaulted, closedAt, dueAt }) => (defaulted ? DEFAULTED : Number(closedAt) <= Number(dueAt) ? ON_TIME : LATE);
123
+
124
+ const zero = () => ({ count: 0, amount: "0" });
125
+ const add = (t, amount) => { t.count++; t.amount = (big(t.amount) + big(amount)).toString(); };
126
+
127
+ /** Totals by outcome over leaves: { onTime, late, defaulted, recovered }, each { count, amount } (base units). */
128
+ export function totalsOf(leaves) {
129
+ const t = { onTime: zero(), late: zero(), defaulted: zero(), recovered: zero() };
130
+ for (const l of leaves) { const k = OUTCOMES[Number(l.outcome)]; if (k) add(t[k], l.amount); }
131
+ return t;
132
+ }
133
+
134
+ /** A leaf as written in a file (anchors, a default entry): every committed field, plus its class, its block and the
135
+ * opening log (openBlock, openTx, openLog) a light reader reads dueAt from. */
136
+ export const leafOut = (l) => ({
137
+ src: Number(l.src || 0), cls: l.cls || "unsecured", loan: dec(l.loan, "loan"), amount: dec(l.amount, "amount"), dueAt: Number(l.dueAt), closedAt: Number(l.closedAt), outcome: Number(l.outcome), block: Number(l.block), tx: lc(l.tx), log: Number(l.log),
138
+ ...(l.openTx ? { openBlock: Number(l.openBlock), openTx: lc(l.openTx), openLog: Number(l.openLog) } : {}),
139
+ });
140
+
141
+ const iso = (t) => new Date(Number(t) * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
142
+
143
+ /** The spec's MUST fields of an ERC-8004 feedback file. agentId and value are decimal strings (uint256, int128). */
144
+ function head({ chainId, identityRegistry, agentId, writer, createdAt, value, decimals, tag1, tag2 }) {
145
+ return {
146
+ agentRegistry: `eip155:${chainId}:${ethers.getAddress(identityRegistry)}`,
147
+ agentId: dec(agentId, "agentId"),
148
+ clientAddress: `eip155:${chainId}:${ethers.getAddress(writer)}`,
149
+ createdAt: iso(createdAt),
150
+ value: String(value), valueDecimals: Number(decimals),
151
+ tag1, tag2,
152
+ };
153
+ }
154
+
155
+ /** A source as a file names it: chain, contract, the blocks it was active in ([first, last], last null while it
156
+ * lends), the events a reader rebuilds leaves from, and their field names. */
157
+ export function sourceOut(s) {
158
+ return {
159
+ chainId: Number(s.chainId), contract: ethers.getAddress(s.contract),
160
+ blocks: [Number(s.blocks?.[0] ?? 0), s.blocks?.[1] == null ? null : Number(s.blocks[1])],
161
+ events: { open: s.events.open, repaid: s.events.repaid, defaulted: s.events.defaulted },
162
+ fields: { amount: s.fields?.amount || "amount", dueAt: s.fields?.dueAt || "dueAt" },
163
+ };
164
+ }
165
+
166
+ /** A statement's tag2: its leaves' one class, "mixed" for several, `fallback` (the line's class) for none. */
167
+ export function classOf(leaves, fallback = "unsecured") {
168
+ const set = [...new Set(leaves.map((l) => l.cls || "unsecured"))];
169
+ return set.length === 0 ? fallback : set.length === 1 ? set[0] : MIXED;
170
+ }
171
+
172
+ /**
173
+ * A statement: every loan of `agentId` with this lender closed in [fromBlock, toBlock], committed by `root`, with
174
+ * totals (all, and by class), what was opened and what is outstanding at toBlock, and the latest leaves in full.
175
+ * `prev` is the previous statement's feedbackHash in the same (writer, agent) chain (null for seq 1); fromBlock must be
176
+ * its toBlock + 1. `cls` is the class of the agent's line, used as tag2 when the window closed no loan. `agentId`: a
177
+ * bigint, a decimal string, or a Number below 2^53.
178
+ */
179
+ export function statementFile({ chainId, identityRegistry, writer, agentId, cls = "unsecured", asset, decimals, sources, seq, prev, window, leaves, opened, outstanding, createdAt, lender = null, anchors = ANCHORS }) {
180
+ const sorted = sortLeaves(leaves);
181
+ if (sorted.some((l) => !sources[Number(l.src || 0)])) throw new Error("a leaf names a source the statement does not carry");
182
+ const totals = totalsOf(sorted);
183
+ const byClass = {};
184
+ for (const k of [...new Set(sorted.map((l) => l.cls || "unsecured"))].sort()) byClass[k] = totalsOf(sorted.filter((l) => (l.cls || "unsecured") === k));
185
+ const f = head({ chainId, identityRegistry, agentId, writer, createdAt, value: totals.onTime.amount, decimals, tag1: TAG_STATEMENT, tag2: classOf(sorted, cls) });
186
+ f.credit = {
187
+ v: PROFILE,
188
+ ...(lender ? { lender } : {}),
189
+ asset, decimals: Number(decimals),
190
+ sources: sources.map(sourceOut),
191
+ seq: Number(seq), prev: prev ? lc(prev) : null,
192
+ window: { fromBlock: Number(window.fromBlock), toBlock: Number(window.toBlock), toTime: Number(window.toTime) },
193
+ opened: { count: Number(opened.count), amount: dec(opened.amount, "opened.amount") },
194
+ closed: totals,
195
+ classes: byClass,
196
+ outstanding: { count: Number(outstanding.count), amount: dec(outstanding.amount, "outstanding.amount") },
197
+ leaves: sorted.length,
198
+ root: rootOf(sorted, sources, agentId),
199
+ anchors: sorted.slice(-anchors).map(leafOut),
200
+ };
201
+ return f;
202
+ }
203
+
204
+ /** A default, posted when it happens (it is also a leaf of the next statement). */
205
+ export function defaultFile({ chainId, identityRegistry, writer, agentId, asset, decimals, source, leaf, createdAt, lender = null }) {
206
+ if (Number(leaf.outcome) !== DEFAULTED) throw new Error("a default entry carries a defaulted leaf");
207
+ const f = head({ chainId, identityRegistry, agentId, writer, createdAt, value: dec(leaf.amount, "amount"), decimals, tag1: TAG_DEFAULTED, tag2: leaf.cls || "unsecured" });
208
+ f.credit = { v: PROFILE, ...(lender ? { lender } : {}), asset, decimals: Number(decimals), sources: [sourceOut(source)], leaf: leafOut({ ...leaf, src: 0 }) };
209
+ return f;
210
+ }
211
+
212
+ /**
213
+ * A file's canonical JSON: RFC 8785 (JCS) for the values this profile uses. Object keys sorted by UTF-16 code units, no
214
+ * whitespace, strings as JSON.stringify writes them, numbers only as safe integers. Throws on anything else.
215
+ */
216
+ export function canonicalJSON(v) {
217
+ if (v === null || typeof v === "boolean") return JSON.stringify(v);
218
+ if (typeof v === "string") {
219
+ if (!v.isWellFormed()) throw new TypeError("a string with a lone surrogate is not I-JSON");
220
+ return JSON.stringify(v);
221
+ }
222
+ if (typeof v === "number") {
223
+ if (!Number.isSafeInteger(v)) throw new TypeError(`${v} is not a safe integer: write it as a decimal string`);
224
+ return String(v);
225
+ }
226
+ if (Array.isArray(v)) return `[${v.map(canonicalJSON).join(",")}]`;
227
+ if (typeof v === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(v))) {
228
+ return `{${Object.keys(v).filter((k) => v[k] !== undefined).sort().map((k) => `${canonicalJSON(k)}:${canonicalJSON(v[k])}`).join(",")}}`;
229
+ }
230
+ throw new TypeError(`a ${typeof v} is not JSON`);
231
+ }
232
+
233
+ /**
234
+ * Bytes, data: URI and keccak256 of a file, in canonical JSON; the oldest anchors are dropped until it fits in `max`
235
+ * bytes. Throws if the file is not a valid v1 file: a writer never posts what a reader rejects.
236
+ */
237
+ export function encodeFile(file, { max = MAX_FILE_BYTES } = {}) {
238
+ const cap = Math.min(max, FILE_LIMIT);
239
+ let f = file;
240
+ let bytes = ethers.toUtf8Bytes(canonicalJSON(f));
241
+ while (bytes.length > cap && f.credit?.anchors?.length) {
242
+ f = { ...f, credit: { ...f.credit, anchors: f.credit.anchors.slice(1) } };
243
+ bytes = ethers.toUtf8Bytes(canonicalJSON(f));
244
+ }
245
+ if (bytes.length > cap) throw new Error(`the file is ${bytes.length} bytes, over ${cap}`);
246
+ const problems = validateFile(f);
247
+ if (problems.length) throw new Error(`not a valid ${PROFILE} file: ${problems.join("; ")}`);
248
+ return { file: f, bytes, size: bytes.length, feedbackURI: DATA_URI_PREFIX + ethers.encodeBase64(bytes), feedbackHash: ethers.keccak256(bytes) };
249
+ }
250
+
251
+ const B64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
252
+ /** The bytes a credit entry's URI carries: exactly "data:application/json;base64," then canonical base64 (RFC 4648,
253
+ * padded, nothing else); null for anything else. */
254
+ export function decodeDataURI(uri) {
255
+ if (typeof uri !== "string" || !uri.startsWith(DATA_URI_PREFIX)) return null;
256
+ const b64 = uri.slice(DATA_URI_PREFIX.length);
257
+ if (!B64.test(b64)) return null;
258
+ const bytes = ethers.decodeBase64(b64);
259
+ return ethers.encodeBase64(bytes) === b64 ? bytes : null;
260
+ }
261
+
262
+ /**
263
+ * A file from its bytes, read strictly: at most FILE_LIMIT bytes, UTF-8, JSON, and exactly its own canonical encoding.
264
+ * The last check rejects duplicate keys (a parser keeps one of them), whitespace, and any other way to write a number.
265
+ * Returns { file, problems }; file is null when the bytes are not a canonical JSON file.
266
+ */
267
+ export function parseFile(bytes) {
268
+ if (!(bytes instanceof Uint8Array)) return { file: null, problems: ["the file is not bytes"] };
269
+ if (bytes.length > FILE_LIMIT) return { file: null, problems: [`the file is ${bytes.length} bytes, over the ${FILE_LIMIT}-byte limit`] };
270
+ let text, file, again = null;
271
+ try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); } catch (_) { return { file: null, problems: ["the file is not UTF-8"] }; }
272
+ try { file = JSON.parse(text); } catch (_) { return { file: null, problems: ["the file is not JSON"] }; }
273
+ try { again = canonicalJSON(file); } catch (_) { /* not canonical */ }
274
+ if (again !== text) return { file: null, problems: ["the file is not canonical JSON (RFC 8785: keys sorted, no whitespace, no duplicate key, integers only)"] };
275
+ return { file, problems: [] };
276
+ }
277
+
278
+ // ---- the schema --------------------------------------------------------------------------------------------------
279
+ const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
280
+ const isInt = (v, max = Number.MAX_SAFE_INTEGER, min = 0) => Number.isSafeInteger(v) && v >= min && v <= max;
281
+ const isDec = (v, max = UINT256_MAX) => typeof v === "string" && DEC.test(v) && BigInt(v) <= max;
282
+ const isHash = (v) => typeof v === "string" && /^0x[0-9a-f]{64}$/.test(v);
283
+ const isAddr = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{40}$/.test(v) && ethers.getAddress(v) === v;
284
+ const isText = (v, max) => typeof v === "string" && v.length >= 1 && v.length <= max && v.isWellFormed() && !/[\u0000-\u001f\u007f-\u009f]/.test(v);
285
+ const CAIP10 = /^eip155:([1-9][0-9]{0,15}):(0x[0-9a-fA-F]{40})$/;
286
+ const CAIP19 = /^eip155:([1-9][0-9]{0,15})\/erc20:(0x[0-9a-fA-F]{40})$/;
287
+ const chainOf = (re, v) => { const m = typeof v === "string" ? re.exec(v) : null; return m && Number.isSafeInteger(Number(m[1])) && isAddr(m[2]) ? { chainId: Number(m[1]), address: m[2] } : null; };
288
+ const isTime = (v) => typeof v === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(v) && Number.isFinite(Date.parse(v)) && iso(Date.parse(v) / 1000) === v;
289
+ const show = (v) => JSON.stringify(String(v).slice(0, 40));
290
+
291
+ /** A v1 asset: a CAIP-19 ERC-20 id, "eip155:<chainId>/erc20:<checksummed address>". { chainId, address } or null. */
292
+ export const parseAsset = (asset) => chainOf(CAIP19, asset);
293
+
294
+ /** Problems with `o`'s keys: a missing required key, or one the schema does not have. */
295
+ function keysOf(o, allowed, where, p, optional = []) {
296
+ for (const k of Object.keys(o)) if (!allowed.includes(k)) p.push(`${where}: unknown field ${show(k)}`);
297
+ for (const k of allowed) if (!optional.includes(k) && !Object.hasOwn(o, k)) p.push(`${where}: no ${k}`);
298
+ }
299
+ const HEAD = ["agentRegistry", "agentId", "clientAddress", "createdAt", "value", "valueDecimals", "tag1", "tag2", "credit"];
300
+ const STATEMENT = ["v", "lender", "asset", "decimals", "sources", "seq", "prev", "window", "opened", "closed", "classes", "outstanding", "leaves", "root", "anchors"];
301
+ const DEFAULT = ["v", "lender", "asset", "decimals", "sources", "leaf"];
302
+ const LEAF = ["src", "cls", "loan", "amount", "dueAt", "closedAt", "outcome", "block", "tx", "log", "openBlock", "openTx", "openLog"];
303
+ const KINDS = ["onTime", "late", "defaulted", "recovered"];
304
+
305
+ function tally(t, where, p) {
306
+ if (!isObj(t)) return p.push(`${where} is not { count, amount }`);
307
+ keysOf(t, ["count", "amount"], where, p);
308
+ if (!isInt(t.count)) p.push(`${where}.count is not a count`);
309
+ if (!isDec(t.amount)) p.push(`${where}.amount is not a decimal string of base units`);
310
+ }
311
+ function byOutcome(t, where, p) {
312
+ if (!isObj(t)) return p.push(`${where} is not { onTime, late, defaulted, recovered }`);
313
+ keysOf(t, KINDS, where, p);
314
+ for (const k of KINDS) if (Object.hasOwn(t, k)) tally(t[k], `${where}.${k}`, p);
315
+ }
316
+ function leafShape(l, nSources, where, p) {
317
+ if (!isObj(l)) return p.push(`${where} is not a leaf`);
318
+ keysOf(l, LEAF, where, p);
319
+ if (!isInt(l.src, nSources - 1)) p.push(`${where}: src does not name one of the file's sources`);
320
+ if (!CLASSES.includes(l.cls)) p.push(`${where}: cls ${show(l.cls)} is not a class`);
321
+ if (!isDec(l.loan)) p.push(`${where}: loan is not a uint256 decimal string`);
322
+ if (!isDec(l.amount)) p.push(`${where}: amount is not a decimal string of base units`);
323
+ for (const k of ["dueAt", "closedAt", "block", "openBlock"]) if (Object.hasOwn(l, k) && !isInt(l[k])) p.push(`${where}: ${k} is not an integer`);
324
+ if (![ON_TIME, LATE, DEFAULTED].includes(l.outcome)) p.push(`${where}: outcome is not 1, 2 or 3 (4, recovered, is reserved in v1)`);
325
+ for (const k of ["tx", "openTx"]) if (Object.hasOwn(l, k) && !isHash(l[k])) p.push(`${where}: ${k} is not a transaction hash`);
326
+ for (const k of ["log", "openLog"]) if (Object.hasOwn(l, k) && !isInt(l[k], UINT32_MAX)) p.push(`${where}: ${k} is not a log index`);
327
+ if (isInt(l.openBlock) && isInt(l.block) && l.openBlock > l.block) p.push(`${where}: opened after it closed`);
328
+ }
329
+ /** Problems with one declared event; its topic0, or null when it is not a usable event. */
330
+ function eventShape(sig, kind, fields, where, p) {
331
+ const fail = (m) => { p.push(`${where}: events.${kind} ${m}`); return null; };
332
+ if (!isText(sig, 512)) return fail("is not a signature");
333
+ let frag;
334
+ try { frag = ethers.EventFragment.from(`event ${sig}`); } catch (_) { return fail("is not an event signature"); }
335
+ if (frag.anonymous) return fail("is anonymous");
336
+ const names = frag.inputs.map((i) => i.name);
337
+ if (new Set(names).size !== names.length) p.push(`${where}: events.${kind} repeats a parameter name`);
338
+ const need = ["loanId", "agentId", fields?.amount, ...(kind === "open" ? [fields?.dueAt] : [])];
339
+ for (const n of need) if (typeof n === "string" && !frag.inputs.some((i) => i.name === n && /^uint\d*$/.test(i.type))) p.push(`${where}: events.${kind} has no uint parameter ${show(n)}`);
340
+ return frag.topicHash;
341
+ }
342
+
343
+ /** Problems with a source as a file (or a reader's manifest) declares it. */
344
+ export function validateSource(s, where = "source") {
345
+ const p = [];
346
+ if (!isObj(s)) return [`${where} is not a source`];
347
+ keysOf(s, ["chainId", "contract", "blocks", "events", "fields"], where, p);
348
+ if (!isInt(s.chainId, Number.MAX_SAFE_INTEGER, 1)) p.push(`${where}: chainId is not a chain id`);
349
+ if (!isAddr(s.contract)) p.push(`${where}: contract is not a checksummed address`);
350
+ const b = s.blocks;
351
+ if (!Array.isArray(b) || b.length !== 2 || !isInt(b[0]) || !(b[1] === null || (isInt(b[1]) && b[1] >= b[0]))) p.push(`${where}: blocks is not [first block, last block or null]`);
352
+ const fieldsOk = isObj(s.fields) && Object.keys(s.fields).length === 2 && ["amount", "dueAt"].every((k) => typeof s.fields[k] === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(s.fields[k]));
353
+ if (!fieldsOk) p.push(`${where}: fields is not { amount, dueAt } (parameter names)`);
354
+ if (!isObj(s.events)) p.push(`${where}: events is not { open, repaid, defaulted }`);
355
+ else {
356
+ keysOf(s.events, ["open", "repaid", "defaulted"], `${where}.events`, p);
357
+ const topics = ["open", "repaid", "defaulted"].map((k) => eventShape(s.events[k], k, fieldsOk ? s.fields : null, where, p));
358
+ if (topics.every(Boolean) && new Set(topics).size !== 3) p.push(`${where}: two of its events are the same event`);
359
+ }
360
+ return p;
361
+ }
362
+
363
+ /**
364
+ * The strict, bounded schema of a v1 file, and what a file must say about itself: the value is the on-time principal,
365
+ * the outcome counts add up to the leaves, recovery is zero (reserved), the classes add up to the totals, the root fits
366
+ * the leaf count, the anchors are leaves of the window in leaf order whose outcomes fit their dates. Never throws:
367
+ * returns a list of problems, empty for a valid file.
368
+ */
369
+ export function validateFile(f) {
370
+ if (!isObj(f) || !isObj(f.credit) || f.credit.v !== PROFILE) return [`not an ${PROFILE} file`];
371
+ const c = f.credit;
372
+ const isStatement = f.tag1 === TAG_STATEMENT;
373
+ if (!isStatement && f.tag1 !== TAG_DEFAULTED) return [`unknown tag1 ${show(f.tag1)}`];
374
+ const p = [];
375
+ keysOf(f, HEAD, "the file", p);
376
+ const reg = chainOf(CAIP10, f.agentRegistry), client = chainOf(CAIP10, f.clientAddress);
377
+ if (!reg) p.push("agentRegistry is not eip155:<chainId>:<checksummed address>");
378
+ if (!client) p.push("clientAddress is not eip155:<chainId>:<checksummed address>");
379
+ else if (reg && reg.chainId !== client.chainId) p.push("clientAddress and agentRegistry name different chains");
380
+ if (!isDec(f.agentId)) p.push("agentId is not a uint256 decimal string");
381
+ if (!isTime(f.createdAt)) p.push("createdAt is not a UTC time (YYYY-MM-DDTHH:MM:SSZ)");
382
+ if (!isDec(f.value, INT128_MAX)) p.push("value is not a decimal string of base units (int128)");
383
+ if (!isInt(f.valueDecimals, 255)) p.push("valueDecimals is not 0 to 255");
384
+ if (!(CLASSES.includes(f.tag2) || (isStatement && f.tag2 === MIXED))) p.push(`tag2 ${show(f.tag2)} is not a class`);
385
+ keysOf(c, isStatement ? STATEMENT : DEFAULT, "credit", p, ["lender"]);
386
+ if (Object.hasOwn(c, "lender")) {
387
+ const l = c.lender;
388
+ if (!isObj(l) || !isText(l.name, 64) || Object.keys(l).some((k) => !["name", "about"].includes(k)) || (Object.hasOwn(l, "about") && !isText(l.about, 256))) p.push("lender is not { name (1 to 64 characters), about (optional, 1 to 256) } without control characters");
389
+ }
390
+ if (!parseAsset(c.asset)) p.push(`asset ${show(c.asset)} is not a CAIP-19 ERC-20 id (eip155:<chainId>/erc20:<checksummed address>)`);
391
+ if (!isInt(c.decimals, 255)) p.push("decimals is not 0 to 255");
392
+ else if (c.decimals !== f.valueDecimals) p.push("valueDecimals is not the asset's decimals");
393
+ const nMax = isStatement ? MAX_SOURCES : 1;
394
+ if (!Array.isArray(c.sources) || c.sources.length < 1 || c.sources.length > nMax) p.push(isStatement ? `sources is not a list of 1 to ${MAX_SOURCES} sources` : "sources is not exactly one source");
395
+ else {
396
+ c.sources.forEach((s, i) => p.push(...validateSource(s, `source ${i}`)));
397
+ const ids = c.sources.map((s) => `${s?.chainId}:${lc(s?.contract)}`);
398
+ if (new Set(ids).size !== ids.length) p.push("two sources are the same contract");
399
+ }
400
+ const n = Array.isArray(c.sources) ? c.sources.length : 0;
401
+ if (!isStatement) {
402
+ leafShape(c.leaf, n, "leaf", p);
403
+ if (p.length) return p;
404
+ if (c.leaf.outcome !== DEFAULTED) p.push("no defaulted leaf");
405
+ else if (c.leaf.amount !== f.value) p.push("value is not the defaulted principal");
406
+ if (c.leaf.cls !== f.tag2) p.push("tag2 is not the leaf's class");
407
+ return p;
408
+ }
409
+ if (!isInt(c.seq, Number.MAX_SAFE_INTEGER, 1)) p.push("seq is not a positive integer");
410
+ if (!(c.prev === null || isHash(c.prev))) p.push("prev is not null or a hash");
411
+ if (!isObj(c.window)) p.push("window is not { fromBlock, toBlock, toTime }");
412
+ else {
413
+ keysOf(c.window, ["fromBlock", "toBlock", "toTime"], "window", p);
414
+ for (const k of ["fromBlock", "toBlock", "toTime"]) if (Object.hasOwn(c.window, k) && !isInt(c.window[k])) p.push(`window.${k} is not an integer`);
415
+ }
416
+ tally(c.opened, "opened", p);
417
+ tally(c.outstanding, "outstanding", p);
418
+ byOutcome(c.closed, "closed", p);
419
+ if (!isObj(c.classes) || Object.keys(c.classes).length > CLASSES.length) p.push("classes is not { <class>: totals }");
420
+ else for (const [k, v] of Object.entries(c.classes)) { if (!CLASSES.includes(k)) p.push(`classes: ${show(k)} is not a class`); byOutcome(v, `classes.${show(k)}`, p); }
421
+ if (!isInt(c.leaves)) p.push("leaves is not a count");
422
+ if (!isHash(c.root)) p.push("root is not a hash");
423
+ if (!Array.isArray(c.anchors) || c.anchors.length > MAX_ANCHORS) p.push(`anchors is not a list of at most ${MAX_ANCHORS} leaves`);
424
+ else c.anchors.forEach((a, i) => leafShape(a, n, `anchor ${i}`, p));
425
+ if (p.length) return p;
426
+
427
+ // what the file says about itself
428
+ if (f.value !== c.closed.onTime.amount) p.push("value is not the on-time principal");
429
+ if (KINDS.reduce((s, k) => s + c.closed[k].count, 0) !== c.leaves) p.push("outcome counts do not add up to the leaf count");
430
+ if (c.closed.recovered.count !== 0 || c.closed.recovered.amount !== "0") p.push("recovered is reserved in v1: its count and amount must be 0");
431
+ const cls = Object.keys(c.classes);
432
+ for (const k of KINDS) {
433
+ const count = cls.reduce((s, x) => s + c.classes[x][k].count, 0), amount = cls.reduce((s, x) => s + BigInt(c.classes[x][k].amount), 0n);
434
+ if (count !== c.closed[k].count || amount.toString() !== c.closed[k].amount) { p.push("classes do not add up to closed"); break; }
435
+ }
436
+ if (cls.some((x) => KINDS.every((k) => c.classes[x][k].count === 0))) p.push("a class with no loan");
437
+ if (cls.length && f.tag2 !== (cls.length === 1 ? cls[0] : MIXED)) p.push("tag2 is not the class of the window's loans");
438
+ if (!cls.length && f.tag2 === MIXED) p.push("tag2 is mixed with no loan");
439
+ if (c.leaves === 0 && c.root !== ethers.ZeroHash) p.push("no leaves but a root");
440
+ if (c.leaves > 0 && c.root === ethers.ZeroHash) p.push(`a zero root over ${c.leaves} leaves`);
441
+ if (c.anchors.length > c.leaves) p.push("more anchors than leaves");
442
+ if (!(c.window.fromBlock <= c.window.toBlock)) p.push("window is empty");
443
+ if (c.seq === 1 ? c.prev !== null : c.prev === null) p.push("prev does not fit seq");
444
+ c.anchors.forEach((a, i) => {
445
+ if (a.block < c.window.fromBlock || a.block > c.window.toBlock) p.push(`anchor loan ${a.loan}: closed outside the window`);
446
+ const b = c.anchors[i - 1];
447
+ if (b && !(b.block < a.block || (b.block === a.block && b.log < a.log))) p.push(`anchor loan ${a.loan}: anchors are not in leaf order`);
448
+ if ((a.outcome === ON_TIME || a.outcome === LATE) && a.outcome !== outcomeOf({ closedAt: a.closedAt, dueAt: a.dueAt })) p.push(`anchor loan ${a.loan}: outcome does not fit its dates`);
449
+ });
450
+ return p;
451
+ }
452
+
453
+ /**
454
+ * Shape checks a reader runs on a decoded file before touching the chain: the schema and what the file says about
455
+ * itself (validateFile), then the spec fields against the entry the registry logged. Returns a list of problems.
456
+ */
457
+ export function checkFile(f, entry) {
458
+ const p = validateFile(f);
459
+ if (p.length) return p;
460
+ let id = null;
461
+ try { id = toId(entry?.agentId, "agentId"); } catch (_) { /* reported below */ }
462
+ if (id === null || id !== BigInt(f.agentId)) p.push("agentId differs from the entry");
463
+ if (lc(f.clientAddress.split(":")[2]) !== lc(entry?.client)) p.push("clientAddress is not the entry's writer");
464
+ if (f.tag1 !== entry?.tag1 || f.tag2 !== entry?.tag2) p.push("tag1/tag2 differ from the entry");
465
+ if (f.value !== String(entry?.value) || f.valueDecimals !== Number(entry?.valueDecimals)) p.push("value/valueDecimals differ from the entry");
466
+ return p;
467
+ }
468
+
469
+ const keyOf = (s) => `${Number(s.chainId)}:${lc(s.contract)}`;
470
+ const reaches = (s, from, to) => Number(s.blocks[0]) <= to && (s.blocks[1] == null || Number(s.blocks[1]) >= from);
471
+ /** Whether two declarations of a source read the same events and fields (the signatures exactly, parameter names too). */
472
+ export const sameEvents = (a, b) => ["open", "repaid", "defaulted"].every((k) => a.events[k] === b.events[k]) && a.fields.amount === b.fields.amount && a.fields.dueAt === b.fields.dueAt;
473
+
474
+ /**
475
+ * The sources a chain covers. Each source is covered from its first block: the first statement that declares it starts
476
+ * at or before blocks[0] (for seq 1, at or before every source it declares), and every later statement whose window
477
+ * the source's blocks reach declares it again. A declaration does not change (its end may go from null to a block).
478
+ * With `manifest` (the reader's own list of the writer's sources) every manifest source counts as declared from the
479
+ * chain's start, the files may declare no other source, and their events and fields are the manifest's.
480
+ */
481
+ function checkSources(chain, manifest) {
482
+ const p = [];
483
+ const seen = new Map();
484
+ const man = manifest ? new Map(manifest.map((s) => [keyOf(s), s])) : null;
485
+ const start = chain.length ? Number(chain[0].file.credit.window.fromBlock) : 0;
486
+ if (man) for (const m of man.values()) if (Number(m.blocks[0]) < start) p.push(`seq ${chain[0].file.credit.seq} starts at block ${start}, after the first block of source ${m.contract} (${m.blocks[0]}) in the reader's manifest: its loans before ${start} are in no statement`);
487
+ for (const s of chain) {
488
+ const c = s.file.credit, tag = `seq ${c.seq}`;
489
+ const from = Number(c.window.fromBlock), to = Number(c.window.toBlock);
490
+ const here = new Map((c.sources || []).map((x) => [keyOf(x), x]));
491
+ for (const [k, x] of here) {
492
+ const was = seen.get(k);
493
+ if (!was) {
494
+ if (Number(x.blocks[0]) < from && !man?.has(k)) p.push(`${tag} starts at block ${from}, after the first block of source ${x.contract} (${x.blocks[0]}): its loans before ${from} are in no statement`);
495
+ seen.set(k, x);
496
+ } else if (Number(x.blocks[0]) !== Number(was.blocks[0]) || !sameEvents(x, was) || (was.blocks[1] != null && x.blocks[1] !== was.blocks[1])) {
497
+ p.push(`${tag}: source ${x.contract}'s declaration changed (first block, end, events or fields)`);
498
+ } else seen.set(k, x);
499
+ if (man) {
500
+ const m = man.get(k);
501
+ if (!m) p.push(`${tag}: source ${x.contract} is not in the reader's manifest`);
502
+ else if (!sameEvents(x, m)) p.push(`${tag}: source ${x.contract}'s events or fields are not the reader's manifest's`);
503
+ }
504
+ }
505
+ for (const [k, x] of seen) if (!here.has(k) && !man?.has(k) && reaches(x, from, to)) p.push(`${tag} does not declare source ${x.contract}, which an earlier statement declared and whose blocks reach this window`);
506
+ if (man) for (const [k, m] of man) if (!here.has(k) && reaches(m, from, to)) p.push(`${tag} does not declare source ${m.contract} of the reader's manifest, whose blocks reach this window`);
507
+ }
508
+ return p;
509
+ }
510
+
511
+ /**
512
+ * Walk one (writer, agent) chain of statements in seq order: seq starts at 1 and steps by 1, each prev is the
513
+ * previous feedbackHash, each window starts right after the previous one, every source is covered from its first block
514
+ * (checkSources), and the asset and its decimals never change. `manifest`: the sources the reader trusts this writer
515
+ * to have (see checkSources). Returns problems (a gap is a problem).
516
+ */
517
+ export function checkChain(statements, { manifest = null } = {}) {
518
+ const p = [];
519
+ let last = null;
520
+ for (const s of statements) {
521
+ const c = s.file.credit;
522
+ if (!last) {
523
+ if (Number(c.seq) !== 1) p.push(`the chain starts at seq ${c.seq}, not 1`);
524
+ } else {
525
+ if (Number(c.seq) !== Number(last.file.credit.seq) + 1) p.push(`seq ${last.file.credit.seq} is followed by ${c.seq}`);
526
+ if (lc(c.prev) !== lc(last.feedbackHash)) p.push(`seq ${c.seq}: prev is not seq ${last.file.credit.seq}'s hash`);
527
+ if (Number(c.window.fromBlock) !== Number(last.file.credit.window.toBlock) + 1) p.push(`seq ${c.seq}: window starts at ${c.window.fromBlock}, not right after ${last.file.credit.window.toBlock}`);
528
+ }
529
+ last = s;
530
+ }
531
+ p.push(...checkSources(statements, manifest));
532
+ const first = statements[0]?.file.credit;
533
+ for (const s of statements.slice(1)) {
534
+ const c = s.file.credit;
535
+ if (c.asset !== first.asset || c.decimals !== first.decimals) p.push(`seq ${c.seq}: asset ${c.asset} (${c.decimals} decimals) differs from seq ${first.seq}'s ${first.asset} (${first.decimals} decimals): one writer, one asset per agent`);
536
+ }
537
+ return p;
538
+ }
539
+
540
+ /** Totals over a chain's statements (the reader adds these up itself: getSummary averages, it does not sum), in the
541
+ * chain's one asset. */
542
+ export function chainTotals(statements) {
543
+ const first = statements[0]?.file.credit;
544
+ const t = { asset: first?.asset ?? null, decimals: first ? Number(first.decimals) : null, statements: statements.length, onTime: zero(), late: zero(), defaulted: zero(), recovered: zero(), opened: zero(), outstanding: zero(), toBlock: 0 };
545
+ for (const s of statements) {
546
+ const c = s.file.credit;
547
+ for (const k of KINDS) { t[k].count += Number(c.closed[k].count); t[k].amount = (big(t[k].amount) + big(c.closed[k].amount)).toString(); }
548
+ t.opened.count += Number(c.opened.count); t.opened.amount = (big(t.opened.amount) + big(c.opened.amount)).toString();
549
+ t.outstanding = { count: Number(c.outstanding.count), amount: String(c.outstanding.amount) };
550
+ t.toBlock = Number(c.window.toBlock);
551
+ }
552
+ return t;
553
+ }
554
+
555
+ /** An event signature's fragment and where its indexed params sit (topics[1..3]). */
556
+ export function eventInfo(sig) {
557
+ const frag = ethers.EventFragment.from(sig.startsWith("event ") ? sig : `event ${sig}`);
558
+ const topicOf = {};
559
+ let k = 1;
560
+ for (const inp of frag.inputs) if (inp.indexed) topicOf[inp.name] = k++;
561
+ return { frag, iface: new ethers.Interface([frag]), topic0: frag.topicHash, topicOf };
562
+ }