@metalntwx/metal-pay 0.2.0 → 0.3.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.
Files changed (70) hide show
  1. package/README.md +72 -33
  2. package/dist/clearing-abi.d.ts +1836 -0
  3. package/dist/clearing-abi.js +2361 -0
  4. package/dist/clearing-client.d.ts +49 -159
  5. package/dist/clearing-client.js +191 -564
  6. package/dist/clearing-codec.d.ts +57 -0
  7. package/dist/clearing-codec.js +173 -0
  8. package/dist/clearing-custody.d.ts +191 -0
  9. package/dist/clearing-custody.js +490 -0
  10. package/dist/clearing-server.d.ts +30 -49
  11. package/dist/clearing-server.js +87 -67
  12. package/dist/clearing-x402.d.ts +29 -0
  13. package/dist/clearing-x402.js +203 -0
  14. package/dist/client.d.ts +7 -13
  15. package/dist/client.js +16 -18
  16. package/dist/index.d.ts +4 -1
  17. package/dist/index.js +4 -1
  18. package/dist/mandates/binding.d.ts +4 -27
  19. package/dist/mandates/binding.js +5 -9
  20. package/dist/mandates/checkout.js +5 -5
  21. package/dist/mandates/client.js +4 -3
  22. package/dist/mandates/l3a.d.ts +2 -2
  23. package/dist/mandates/l3a.js +5 -4
  24. package/dist/mandates/seller.d.ts +1 -1
  25. package/dist/mandates/seller.js +1 -1
  26. package/dist/mandates/verify.d.ts +4 -6
  27. package/dist/mandates/verify.js +42 -66
  28. package/dist/mandates/vi/credential.js +4 -4
  29. package/dist/node.d.ts +11 -0
  30. package/dist/node.js +97 -0
  31. package/package.json +18 -11
  32. package/src/clearing-abi.ts +2361 -0
  33. package/src/clearing-client.ts +303 -0
  34. package/src/clearing-codec.test.ts +57 -0
  35. package/src/clearing-codec.ts +251 -0
  36. package/src/clearing-custody.test.ts +534 -0
  37. package/src/clearing-custody.ts +665 -0
  38. package/src/clearing-fixture.json +37 -0
  39. package/src/clearing-server.test.ts +388 -0
  40. package/src/clearing-server.ts +123 -0
  41. package/src/clearing-x402.test.ts +181 -0
  42. package/src/clearing-x402.ts +279 -0
  43. package/src/client.test.ts +325 -0
  44. package/src/client.ts +156 -0
  45. package/src/index.ts +33 -0
  46. package/src/mandates/account.ts +91 -0
  47. package/src/mandates/binding.ts +280 -0
  48. package/src/mandates/chain.ts +68 -0
  49. package/src/mandates/checkout.ts +368 -0
  50. package/src/mandates/client.ts +159 -0
  51. package/src/mandates/extension.ts +48 -0
  52. package/src/mandates/index.ts +121 -0
  53. package/src/mandates/ingest.ts +42 -0
  54. package/src/mandates/jcs.ts +16 -0
  55. package/src/mandates/l3a.ts +216 -0
  56. package/src/mandates/seller.ts +91 -0
  57. package/src/mandates/verify.ts +532 -0
  58. package/src/mandates/vi/credential.ts +477 -0
  59. package/src/mandates/vi/issue.ts +118 -0
  60. package/src/mandates/vi/sd-jwt.ts +189 -0
  61. package/src/networks.test.ts +16 -0
  62. package/src/networks.ts +152 -0
  63. package/src/node.test.ts +24 -0
  64. package/src/node.ts +96 -0
  65. package/src/server.test.ts +223 -0
  66. package/src/server.ts +77 -0
  67. package/dist/clearing.d.ts +0 -204
  68. package/dist/clearing.js +0 -151
  69. package/dist/file-storage.d.ts +0 -39
  70. package/dist/file-storage.js +0 -195
@@ -0,0 +1,532 @@
1
+ // Verifying a mandate and its payments from the chain, with no Metal service:
2
+ // the mandate's binding on the principal's account; the credential in hand
3
+ // against what was bound, and its signatures under the issuer the chain
4
+ // recorded; and each payment or refusal under the mandate as the agent key's
5
+ // per-payment mandate, rebuilt byte for byte from the transaction that
6
+ // carried it. Any JSON-RPC node serves the reads, with no historical state:
7
+ // the account's code is read at the latest block, and a clone's code never
8
+ // changes, so what it is now it was when it bound and paid. What a verifier
9
+ // cannot rebuild (the budget's running total, the nonce's single use) is read
10
+ // as the contract recorded it in the event and checked against the limits.
11
+
12
+ import {
13
+ type Address,
14
+ type Hash,
15
+ type Hex,
16
+ type ParseEventLogsReturnType,
17
+ type PublicClient,
18
+ type RpcLog,
19
+ decodeFunctionData,
20
+ formatLog,
21
+ getAbiItem,
22
+ hexToBigInt,
23
+ isAddressEqual,
24
+ numberToHex,
25
+ erc20Abi,
26
+ parseEventLogs,
27
+ slice,
28
+ toFunctionSelector,
29
+ } from "viem";
30
+ import {
31
+ type AgentKey,
32
+ type Constraints,
33
+ type L3aFields,
34
+ type Pull,
35
+ REASONS,
36
+ REFUSALS,
37
+ type ReasonName,
38
+ type Terms,
39
+ decodeAgentKey,
40
+ encodeAgentKey,
41
+ mandateBindingAbi,
42
+ mandateReference,
43
+ reasonName,
44
+ sameAgentKey,
45
+ } from "./binding.js";
46
+ import { accountFactoryFor, metalNetwork } from "../networks.js";
47
+ import { assertMetalAccount, metalAccountCode, metalAccountFactoryAbi } from "./account.js";
48
+ import { publicMessage } from "./chain.js";
49
+ import { verifyCheckoutMandate, x402Offer, lineItemOf } from "./checkout.js";
50
+ import { type Json, jcs } from "./jcs.js";
51
+ import { buildL3a, mandateNonce, serializeL3a, transactionIdOf, verifyL3aSignature } from "./l3a.js";
52
+ import { type Credential, type TrustedIssuer, extractTerms, hashCredential, issuerKeyId, verifyCredential } from "./vi/credential.js";
53
+
54
+ interface LogPosition { block: bigint; transactionIndex: number; logIndex: number }
55
+ function before(a: LogPosition, b: LogPosition): boolean {
56
+ return a.block < b.block || (a.block === b.block && (a.transactionIndex < b.transactionIndex || (a.transactionIndex === b.transactionIndex && a.logIndex < b.logIndex)));
57
+ }
58
+ function position(log: { blockNumber: bigint | null; transactionIndex: number | null; logIndex: number | null }): LogPosition {
59
+ if (log.blockNumber === null || log.transactionIndex === null || log.logIndex === null) throw new Error("pending mandate event");
60
+ return { block: log.blockNumber, transactionIndex: log.transactionIndex, logIndex: log.logIndex };
61
+ }
62
+
63
+ export interface VerifyStep {
64
+ step: 1 | 2 | 3 | 4;
65
+ title: string;
66
+ outcome: "pass" | "fail" | "skipped";
67
+ detail: string;
68
+ }
69
+
70
+ export const STEP_TITLES = {
71
+ 1: "The mandate is bound on the principal's account: hash(C), the limits, the payees, the mandate key and the issuer key are on chain",
72
+ 2: "The credential in hand hashes to the bound hash(C) and states the bound limits, payees and mandate key",
73
+ 3: "The credential's signatures: the issuer's under a trusted key that is the one recorded at binding, the owner's under the key the issuer bound",
74
+ 4: "Each payment and refusal is the mandate key's per-payment mandate, rebuilt from its transaction, inside the mandate at its block",
75
+ } as const;
76
+
77
+ /** A mandate as its `MandateBound` event records it. */
78
+ export interface BoundMandate {
79
+ ref: Hex;
80
+ principal: Address;
81
+ block: bigint;
82
+ txHash: Hash;
83
+ hashC: Hex;
84
+ issuerKey: Hex;
85
+ agentKey: AgentKey;
86
+ constraints: Constraints;
87
+ terms: Terms;
88
+ /** The block of its revocation, when it was revoked (a replacement revokes too). */
89
+ revokedBlock?: bigint;
90
+ revokedPosition?: LogPosition;
91
+ /** The mandate that replaced it. */
92
+ successor?: Hex;
93
+ }
94
+
95
+ export interface VerifiedPayment {
96
+ kind: "payment" | "refusal";
97
+ txHash: Hash;
98
+ block: bigint;
99
+ to: Address;
100
+ amount: bigint;
101
+ /** The ERC-3009 nonce the token recorded; a seller's `/settlements` row carries it for a payment the facilitator settled. */
102
+ nonce?: Hex;
103
+ reason?: ReasonName;
104
+ /** The L3a SD-JWT, as the VI reference serialises it, when the transaction carried one. */
105
+ perPaymentMandate?: string;
106
+ problems: string[];
107
+ }
108
+
109
+ export interface MandateVerification {
110
+ ok: boolean;
111
+ steps: VerifyStep[];
112
+ mandate?: BoundMandate;
113
+ payments: VerifiedPayment[];
114
+ }
115
+
116
+ export interface VerifyMandateOptions {
117
+ /** The MetalAccountFactory whose clones are trusted, chosen by the verifier, never by the payer; the one `@metalntwx/metal-pay` names for the chain unless given. */
118
+ accountFactory?: Address;
119
+ /** The credential the mandate was bound from; without it steps 2 and 3 are skipped. */
120
+ credential?: Credential;
121
+ /** The issuers whose signature on the credential is accepted; without them step 3 is skipped. */
122
+ trustedIssuers?: readonly TrustedIssuer[];
123
+ /** The seller's x402 payment requirements, to check that the one payment verified was signed over them. */
124
+ requirements?: Json;
125
+ /** The agent's signed offer for the one payment verified, which must be the one its per-payment mandate names. */
126
+ checkoutMandate?: string;
127
+ /** The mandate to verify in a transaction that settles payments under several, for a verifier with no credential; the credential names it otherwise. */
128
+ ref?: Hex;
129
+ }
130
+
131
+ const short = (hex: Hex) => `${hex.slice(0, 10)}…`;
132
+ /** A reason as the facilitator names it to a payer. */
133
+ const named = (reason: ReasonName) => (reason === "None" ? "none" : REFUSALS[reason].reason);
134
+ const message = publicMessage;
135
+
136
+ /** Terms as JSON for comparison: integers as decimal strings, hex lowercase. */
137
+ function toJson(value: unknown): Json {
138
+ return JSON.parse(JSON.stringify(value, (_k, v: unknown) => (typeof v === "bigint" ? v.toString() : typeof v === "string" && /^0x[0-9a-fA-F]*$/.test(v) ? v.toLowerCase() : v))) as Json;
139
+ }
140
+
141
+ /**
142
+ * Why `reason` (`None` for a payment) contradicts what the transfer, the
143
+ * bound terms and the block decide, or undefined. Mandate Binding's checks a
144
+ * verifier can decide, in its order: revocation, expiry, the window, the
145
+ * payee set, the per-payment cap and the recurrence dates. The budget, the
146
+ * occurrences and the nonce's single use depend on the running state the
147
+ * event records, and are checked from it by the caller.
148
+ */
149
+ function reasonContradiction(reason: ReasonName, pull: Pick<Pull, "to" | "value" | "validAfter" | "validBefore">, m: BoundMandate, at: LogPosition & { timestamp: bigint }): string | undefined {
150
+ const c = m.constraints;
151
+ const t = at.timestamp;
152
+ const decided: [ReasonName, boolean][] = [
153
+ ["Revoked", m.revokedPosition !== undefined && before(m.revokedPosition, at)],
154
+ ["Expired", t > c.expiry],
155
+ ["OutsideWindow", t <= pull.validAfter || t >= pull.validBefore],
156
+ ["PayeeNotAllowed", hexToBigInt(m.terms.openSdHash) === 0n && !m.terms.payees.some((p) => isAddressEqual(p.account, pull.to))],
157
+ ["OverPerPaymentCap", pull.value > c.perPaymentCap],
158
+ ["OutsideRecurrence", t < c.recurrenceStart || t > c.recurrenceEnd],
159
+ ];
160
+ const first = decided.find(([, holds]) => holds)?.[0];
161
+ const own = decided.find(([r]) => r === reason);
162
+ if (own !== undefined) {
163
+ if (!own[1]) return `${named(reason)} does not hold for it`;
164
+ return first === undefined || first === reason ? undefined : `${named(first)} holds, and Mandate Binding checks it before ${named(reason)}`;
165
+ }
166
+ if (first === undefined) return undefined;
167
+ if (reason === "None") return `it breaks the mandate: ${named(first)}`;
168
+ return REASONS.indexOf(first) < REASONS.indexOf(reason) ? `${named(first)} holds, and Mandate Binding checks it before ${named(reason)}` : undefined;
169
+ }
170
+
171
+ interface Carried { pull: Pull; fields: L3aFields }
172
+
173
+ /** The selector a payment's calldata carries: `pull` on the principal, whoever submitted it. */
174
+ const PULL_SELECTOR = toFunctionSelector(getAbiItem({ abi: mandateBindingAbi, name: "pull" }));
175
+
176
+ /**
177
+ * Every pull that `input` carries: at the top level, or inside whatever
178
+ * wrapped the call (a multicall, a sponsor's batch, the quorum's own
179
+ * execute). Each occurrence of the selector in the calldata is tried as a
180
+ * call's start; the one the event's digest names is the payment's, and a
181
+ * forged candidate rebuilds to another digest.
182
+ */
183
+ function carriedL3as(input: Hex): Carried[] {
184
+ const found: Carried[] = [];
185
+ const body = input.slice(2);
186
+ for (let at = body.indexOf(PULL_SELECTOR.slice(2)); at !== -1; at = body.indexOf(PULL_SELECTOR.slice(2), at + 2)) {
187
+ if (at % 2 !== 0) continue;
188
+ try {
189
+ const call = decodeFunctionData({ abi: mandateBindingAbi, data: `0x${body.slice(at)}` });
190
+ if (call.functionName !== "pull") continue;
191
+ const [pull, fields] = call.args;
192
+ found.push({ pull: { ...pull }, fields: { ...fields } });
193
+ } catch {
194
+ // Not a call that starts here.
195
+ }
196
+ }
197
+ return found;
198
+ }
199
+
200
+ /**
201
+ * The candidate that is the outcome the event records: it rebuilds to the
202
+ * recorded digest, moves the mandate's token, and its nonce commits to the
203
+ * mandate and that digest (the L3a hashes neither the token nor the nonce,
204
+ * so a copy with either changed is not it); among those, one signed by the
205
+ * agent key comes first, so unrelated calldata with the same L3a (a copy
206
+ * under another signature) cannot stand in for the payment. One another
207
+ * mandate's terms cannot rebuild is not a candidate.
208
+ */
209
+ function carriedL3a(input: Hex, chainId: number, m: BoundMandate, o: Pick<Outcome, "l3aDigest">): Carried {
210
+ const rank = (c: Carried): number => {
211
+ try {
212
+ const l3a = buildL3a(chainId, m.terms, c.pull, c.fields);
213
+ if (slice(l3a.digest, 0, 20).toLowerCase() !== o.l3aDigest.toLowerCase()) return 0;
214
+ if (!isAddressEqual(c.pull.token, m.constraints.token) || mandateNonce(m.ref, l3a.digest) !== c.pull.nonce.toLowerCase()) return 0;
215
+ return 1 + (verifyL3aSignature(m.agentKey, l3a.digest, c.fields.r, c.fields.s) ? 1 : 0);
216
+ } catch {
217
+ return 0;
218
+ }
219
+ };
220
+ const candidates = carriedL3as(input);
221
+ let carried: Carried | undefined;
222
+ let best = 0;
223
+ for (const c of candidates) {
224
+ const r = rank(c);
225
+ if (r > best) [carried, best] = [c, r];
226
+ }
227
+ if (carried === undefined) throw new Error(candidates.length === 0 ? "the transaction carries no pull on the principal" : "no pull the transaction carries rebuilds to the per-payment mandate the event records");
228
+ return carried;
229
+ }
230
+
231
+ type MandateEvent = ParseEventLogsReturnType<typeof mandateBindingAbi, undefined, true>[number];
232
+
233
+ /**
234
+ * The mandate's events on the principal between two blocks, oldest first: one
235
+ * `eth_getLogs` for every event kind, since each puts the reference in its
236
+ * first topic. A node caps the range one request may span, each by its own
237
+ * rule and in its own words, so a refused range is halved until the node
238
+ * answers; an error that holds for a single block is the node's.
239
+ */
240
+ async function mandateEvents(client: PublicClient, principal: Address, ref: Hex, fromBlock: bigint, toBlock: bigint): Promise<MandateEvent[]> {
241
+ const out: MandateEvent[] = [];
242
+ let span = toBlock - fromBlock + 1n;
243
+ for (let start = fromBlock; start <= toBlock;) {
244
+ const end = start + span - 1n > toBlock ? toBlock : start + span - 1n;
245
+ try {
246
+ const logs = await client.request({ method: "eth_getLogs", params: [{ address: principal, fromBlock: numberToHex(start), toBlock: numberToHex(end), topics: [null, ref] }] });
247
+ out.push(...parseEventLogs({ abi: mandateBindingAbi, logs: (logs as RpcLog[]).map((log) => formatLog(log)), strict: true }));
248
+ start = end + 1n;
249
+ } catch (error) {
250
+ if (span <= 1n) throw error;
251
+ span /= 2n;
252
+ }
253
+ }
254
+ return out;
255
+ }
256
+
257
+ /**
258
+ * The mandate `ref` as the principal's account bound it: its state names the
259
+ * block, so the scan for its events starts there and never at genesis.
260
+ * `toBlock` bounds the scan when only the events up to one block matter.
261
+ */
262
+ async function boundMandate(client: PublicClient, principal: Address, ref: Hex, factory: Address, toBlock?: bigint): Promise<{ mandate?: BoundMandate; events: MandateEvent[]; problems: string[] }> {
263
+ const state = await client.readContract({ address: principal, abi: mandateBindingAbi, functionName: "mandates", args: [ref] });
264
+ if (!isAddressEqual(state.principal, principal)) return { events: [], problems: [`no mandate ${short(ref)} is bound on ${principal}`] };
265
+ const from = state.boundBlock;
266
+ const to = toBlock ?? (await client.getBlockNumber());
267
+ const events = await mandateEvents(client, principal, ref, from, to);
268
+ const bound = events.filter((e) => e.eventName === "MandateBound");
269
+ if (bound.length !== 1) return { events, problems: [bound.length === 0 ? `no MandateBound for ${short(ref)} on ${principal} in block ${from}, where its state says it was bound` : `${bound.length} MandateBound events for ${short(ref)}`] };
270
+ const [log] = bound;
271
+ if (log === undefined || log.eventName !== "MandateBound" || log.blockNumber === null || log.transactionHash === null) return { events, problems: ["the MandateBound event is pending"] };
272
+ try { await assertMetalAccount(client, principal, factory); }
273
+ catch (error) { return { events, problems: [message(error)] }; }
274
+ const agentKey = decodeAgentKey(log.args.agentKey);
275
+ const problems: string[] = [];
276
+ if (mandateReference(principal, agentKey, log.args.hashC).toLowerCase() !== ref.toLowerCase()) problems.push("the reference does not derive from the principal, the mandate key and hash(C)");
277
+ const revoked = events.find((e) => e.eventName === "MandateRevoked");
278
+ const replaced = events.find((e) => e.eventName === "MandateReplaced");
279
+ const revokedBlock = revoked?.blockNumber ?? undefined;
280
+ const successor = replaced?.eventName === "MandateReplaced" ? replaced.args.successor : undefined;
281
+ return {
282
+ mandate: {
283
+ ref: ref.toLowerCase() as Hex,
284
+ principal,
285
+ block: log.blockNumber,
286
+ txHash: log.transactionHash,
287
+ hashC: log.args.hashC,
288
+ issuerKey: log.args.issuerKey,
289
+ agentKey,
290
+ constraints: { ...log.args.constraints },
291
+ terms: { ...log.args.terms, payees: log.args.terms.payees.map((p) => ({ ...p })) },
292
+ ...(revokedBlock === undefined || revoked === undefined ? {} : { revokedBlock, revokedPosition: position(revoked) }),
293
+ ...(successor === undefined ? {} : { successor }),
294
+ },
295
+ events,
296
+ problems,
297
+ };
298
+ }
299
+
300
+ interface Outcome extends LogPosition {
301
+ kind: "payment" | "refusal";
302
+ txHash: Hash;
303
+ block: bigint;
304
+ to: Address;
305
+ amount: bigint;
306
+ l3aDigest: Hex;
307
+ agentKey: Hex;
308
+ spent?: bigint;
309
+ occurrences?: bigint;
310
+ reason?: ReasonName;
311
+ }
312
+
313
+ /** The payments and refusals among `events`, oldest first; with `only`, those one transaction carried. */
314
+ function outcomesOf(events: readonly MandateEvent[], only: Hash | undefined): Outcome[] {
315
+ const outcomes: Outcome[] = [];
316
+ for (const log of events) {
317
+ if (log.blockNumber === null || log.transactionHash === null) continue;
318
+ if (log.eventName === "MandatePayment") {
319
+ const { to, amount, l3aDigest, agentKey, spent, occurrences } = log.args;
320
+ outcomes.push({ ...position(log), kind: "payment", txHash: log.transactionHash, block: log.blockNumber, to, amount, l3aDigest, agentKey, spent, occurrences });
321
+ } else if (log.eventName === "MandateRefused") {
322
+ const { to, amount, l3aDigest, agentKey, reason } = log.args;
323
+ outcomes.push({ ...position(log), kind: "refusal", txHash: log.transactionHash, block: log.blockNumber, to, amount, l3aDigest, agentKey, reason: reasonName(reason) });
324
+ }
325
+ }
326
+ outcomes.sort((a, b) => before(a, b) ? -1 : before(b, a) ? 1 : 0);
327
+ return only === undefined ? outcomes : outcomes.filter((o) => o.txHash.toLowerCase() === only.toLowerCase());
328
+ }
329
+
330
+ async function verifyOutcome(client: PublicClient, chainId: number, m: BoundMandate, o: Outcome, one: { requirements?: Json; checkoutMandate?: string; checkoutSdHash?: Hex }): Promise<VerifiedPayment> {
331
+ const verified: VerifiedPayment = { kind: o.kind, txHash: o.txHash, block: o.block, to: o.to, amount: o.amount, ...(o.reason === undefined ? {} : { reason: o.reason }), problems: [] };
332
+ const found = verified.problems;
333
+ const agentKey = decodeAgentKey(o.agentKey);
334
+ if (!sameAgentKey(agentKey, m.agentKey)) found.push("not the bound mandate key");
335
+ try {
336
+ const [tx, block] = await Promise.all([client.getTransaction({ hash: o.txHash }), client.getBlock({ blockNumber: o.block })]);
337
+ const { pull, fields } = carriedL3a(tx.input, chainId, m, o);
338
+ if (!isAddressEqual(pull.token, m.constraints.token)) found.push("another token than the mandate's");
339
+ const receipt = await client.getTransactionReceipt({ hash: o.txHash });
340
+ if (receipt.status !== "success" || receipt.blockNumber !== o.block) found.push("no successful receipt at the recorded block");
341
+ if (o.kind === "payment") {
342
+ const transfers = parseEventLogs({ abi: erc20Abi, logs: receipt.logs, eventName: "Transfer", strict: true });
343
+ if (!transfers.some(t => isAddressEqual(t.address, m.constraints.token) && isAddressEqual(t.args.from, m.principal) && isAddressEqual(t.args.to, pull.to) && t.args.value === pull.value && t.logIndex < o.logIndex)) found.push("no matching token transfer before the payment event");
344
+ }
345
+ const l3a = buildL3a(chainId, m.terms, pull, fields);
346
+ verified.perPaymentMandate = serializeL3a(l3a, fields.r, fields.s);
347
+ if (slice(l3a.digest, 0, 20).toLowerCase() !== o.l3aDigest.toLowerCase()) found.push("its digest is not the one the event records");
348
+ verified.nonce = pull.nonce;
349
+ if (mandateNonce(m.ref, l3a.digest) !== pull.nonce.toLowerCase()) found.push("its nonce does not commit to the mandate and the per-payment mandate");
350
+ if (!verifyL3aSignature(m.agentKey, l3a.digest, fields.r, fields.s)) found.push("not the bound mandate key's signature");
351
+ if (!isAddressEqual(pull.to, o.to)) found.push("another payee than the event records");
352
+ if (pull.value !== o.amount) found.push("another amount than the event records");
353
+ if (one.checkoutMandate !== undefined) {
354
+ // The offer served, when the verifier served it; the signed order's own otherwise.
355
+ const offer = one.requirements !== null && typeof one.requirements === "object" && !Array.isArray(one.requirements) ? x402Offer(one.requirements) : undefined;
356
+ found.push(...verifyCheckoutMandate(one.checkoutMandate, {
357
+ agent: m.agentKey,
358
+ kid: m.terms.kid,
359
+ payee: pull.to,
360
+ ...(offer === undefined ? {} : { offer, lineItemId: lineItemOf(offer) }),
361
+ window: pull,
362
+ transactionId: fields.transactionId,
363
+ amount: pull.value,
364
+ ...(one.checkoutSdHash === undefined ? {} : { checkoutSdHash: one.checkoutSdHash }),
365
+ }).problems);
366
+ } else if (one.requirements !== undefined && transactionIdOf(one.requirements).toLowerCase() !== fields.transactionId.toLowerCase()) {
367
+ found.push("not signed over the requirements given");
368
+ }
369
+ if (one.requirements !== undefined) {
370
+ const r = one.requirements;
371
+ if (r === null || typeof r !== "object" || Array.isArray(r)
372
+ || typeof r.asset !== "string" || r.asset.toLowerCase() !== pull.token.toLowerCase()
373
+ || typeof r.payTo !== "string" || r.payTo.toLowerCase() !== pull.to.toLowerCase()
374
+ || r.amount !== pull.value.toString() || r.network !== `eip155:${chainId}`) found.push("the transfer does not satisfy the requirements given");
375
+ }
376
+ const at = { ...o, timestamp: block.timestamp };
377
+ if (o.kind === "payment") {
378
+ const broken = reasonContradiction("None", pull, m, at);
379
+ if (broken !== undefined) found.push(broken);
380
+ if (o.spent !== undefined && o.spent > m.constraints.budget) found.push("over the budget");
381
+ if (o.occurrences !== undefined && o.occurrences > m.constraints.maxOccurrences) found.push("over the occurrence cap");
382
+ } else if (o.reason !== undefined) {
383
+ const contradiction = reasonContradiction(o.reason, pull, m, at);
384
+ if (contradiction !== undefined) found.push(`refused for ${named(o.reason)}: ${contradiction}`);
385
+ }
386
+ } catch (error) {
387
+ found.push(message(error));
388
+ }
389
+ return verified;
390
+ }
391
+
392
+ type Found = { mandate?: BoundMandate; events: readonly MandateEvent[]; problems: string[] };
393
+
394
+ async function verify(client: PublicClient, found: Found, opts: VerifyMandateOptions & { accountFactory: Address }, only: { tx: Hash; events: readonly MandateEvent[] } | undefined): Promise<MandateVerification> {
395
+ const steps: VerifyStep[] = [];
396
+ const record = (step: VerifyStep["step"], problems: string[], passed: string) =>
397
+ steps.push({ step, title: STEP_TITLES[step], outcome: problems.length > 0 ? "fail" : "pass", detail: problems.length > 0 ? problems.join("; ") : passed });
398
+ const skip = (step: VerifyStep["step"], why: string) => steps.push({ step, title: STEP_TITLES[step], outcome: "skipped", detail: why });
399
+
400
+ const m = found.mandate;
401
+ if (m === undefined) {
402
+ record(1, found.problems, "");
403
+ skip(2, "no binding to check against");
404
+ skip(3, "no binding to check against");
405
+ skip(4, "no binding to check against");
406
+ return { ok: false, steps, payments: [] };
407
+ }
408
+ record(
409
+ 1,
410
+ found.problems,
411
+ `${short(m.ref)} bound in block ${m.block} by ${m.principal}: hash(C) ${m.hashC}, issuer key ${m.issuerKey}, mandate key ${short(encodeAgentKey(m.agentKey))}, ${m.terms.payees.length} payee(s)` +
412
+ `${m.revokedBlock === undefined ? "" : `, revoked in block ${m.revokedBlock}`}${m.successor === undefined ? "" : `, replaced by ${short(m.successor)}`}`,
413
+ );
414
+
415
+ const c = opts.credential;
416
+ let credentialIsBound = false;
417
+ if (c === undefined) {
418
+ skip(2, "no credential in hand");
419
+ } else {
420
+ const problems: string[] = [];
421
+ if (hashCredential(c).toLowerCase() !== m.hashC.toLowerCase()) problems.push("hash(C) of the credential in hand is not the bound hash");
422
+ else {
423
+ try {
424
+ const stated = extractTerms(c);
425
+ const differs = [
426
+ ["principal", isAddressEqual(stated.principal, m.principal)],
427
+ ["mandate key", sameAgentKey(stated.agentKey, m.agentKey)],
428
+ ["limits", jcs(toJson(stated.constraints)) === jcs(toJson(m.constraints))],
429
+ ["payees", jcs(toJson(stated.terms)) === jcs(toJson(m.terms))],
430
+ ].filter(([, same]) => !same);
431
+ if (differs.length > 0) problems.push(`the bound ${differs.map(([name]) => name).join(", ")} differ from the credential's`);
432
+ } catch (error) {
433
+ problems.push(message(error));
434
+ }
435
+ }
436
+ credentialIsBound = problems.length === 0;
437
+ record(2, problems, "the credential hashes to the bound hash(C), and binds exactly the limits, payees and mandate key it states");
438
+ }
439
+
440
+ if (c === undefined || !credentialIsBound) skip(3, c === undefined ? "no credential in hand" : "the credential in hand is not the bound one");
441
+ else if (opts.trustedIssuers === undefined || opts.trustedIssuers.length === 0) skip(3, "no trusted issuer given");
442
+ else {
443
+ const problems: string[] = [];
444
+ try {
445
+ const boundAt = await client.getBlock({ blockNumber: m.block });
446
+ const { issuer } = await verifyCredential(c, { trustedIssuers: opts.trustedIssuers, account: m.principal, now: Number(boundAt.timestamp) });
447
+ if (issuerKeyId(issuer.jwk).toLowerCase() !== m.issuerKey.toLowerCase()) problems.push("the trusted issuer's key is not the issuer key recorded at binding");
448
+ } catch (error) {
449
+ problems.push(message(error));
450
+ }
451
+ record(3, problems, "the issuer's signature verifies under the trusted key the chain recorded, the owner's under the key the issuer bound, and the credential was valid when bound");
452
+ }
453
+
454
+ const chainId = await client.getChainId();
455
+ const outcomes = outcomesOf(only === undefined ? found.events : only.events, only?.tx);
456
+ const payments: VerifiedPayment[] = [];
457
+ const checkoutSdHash = c !== undefined && credentialIsBound ? extractTerms(c).checkoutSdHash : undefined;
458
+ const one = outcomes.length === 1 ? { ...opts, ...(checkoutSdHash === undefined ? {} : { checkoutSdHash }) } : {};
459
+ for (const o of outcomes) payments.push(await verifyOutcome(client, chainId, m, o, one));
460
+ const problems = payments.filter((p) => p.problems.length > 0).map((p) => `${p.kind} in ${short(p.txHash)}: ${p.problems.join(", ")}`);
461
+ if (only !== undefined && outcomes.length === 0) problems.push(`transaction ${only.tx} carries no payment or refusal under ${short(m.ref)}`);
462
+ if ((opts.requirements !== undefined || opts.checkoutMandate !== undefined) && outcomes.length > 1) problems.push("requirements or a signed offer given, but more than one payment to check them against");
463
+ const paid = payments.filter((p) => p.kind === "payment").length;
464
+ record(4, problems, `${paid} payment(s) and ${payments.length - paid} refusal(s), each the bound mandate key's per-payment mandate rebuilt byte for byte from its transaction, inside the mandate at its block`);
465
+
466
+ return { ok: steps.every((s) => s.outcome !== "fail"), steps, mandate: m, payments };
467
+ }
468
+
469
+ /** The factory the verifier trusts on `client`'s chain: the caller's, else the one the network table names. */
470
+ async function trustedFactory(client: PublicClient, override: Address | undefined): Promise<Address> {
471
+ if (override !== undefined) return override;
472
+ const chainId = await client.getChainId();
473
+ const network = metalNetwork(`eip155:${chainId}`);
474
+ if (network === undefined) throw new Error(`chain ${chainId} is not a Metal network; pass accountFactory`);
475
+ return accountFactoryFor(network, undefined, "pass accountFactory");
476
+ }
477
+
478
+ /**
479
+ * The four steps over a credential and the chain: the mandate the credential
480
+ * describes, bound on the account it names, and every payment and refusal
481
+ * under it.
482
+ */
483
+
484
+ export async function verifyMandate(client: PublicClient, opts: VerifyMandateOptions & { credential: Credential }): Promise<MandateVerification> {
485
+ const terms = extractTerms(opts.credential);
486
+ const ref = mandateReference(terms.principal, terms.agentKey, hashCredential(opts.credential));
487
+ const accountFactory = await trustedFactory(client, opts.accountFactory);
488
+ return verify(client, await boundMandate(client, terms.principal, ref, accountFactory), { ...opts, accountFactory }, undefined);
489
+ }
490
+
491
+ /**
492
+ * The four steps over one transaction: the mandate its payment or refusal
493
+ * names, found from the event the principal's account emitted, and that one
494
+ * outcome. A seller holds no credential, so steps 2 and 3 are skipped unless
495
+ * one is given; with the x402 `requirements` it served, the payment is
496
+ * checked to have been signed over them.
497
+ */
498
+ export async function verifyMandatePayment(client: PublicClient, opts: VerifyMandateOptions & { tx: Hash }): Promise<MandateVerification> {
499
+ const receipt = await client.getTransactionReceipt({ hash: opts.tx });
500
+ const accountFactory = await trustedFactory(client, opts.accountFactory);
501
+ const logs = parseEventLogs({ abi: mandateBindingAbi, logs: receipt.logs, eventName: ["MandatePayment", "MandateRefused"], strict: true });
502
+ // Only an account the trusted factory made emits a mandate's outcome; any
503
+ // other contract in the transaction may copy the event's shape. A read
504
+ // that fails is not an answer: it propagates, so a verification never
505
+ // passes on part of a transaction's outcomes.
506
+ const clone = metalAccountCode(await client.readContract({ address: accountFactory, abi: metalAccountFactoryAbi, functionName: "implementation" }));
507
+ const emitters = new Map<string, boolean>();
508
+ for (const address of new Set(logs.map((log) => log.address.toLowerCase() as Address))) {
509
+ emitters.set(address, (await client.getCode({ address }))?.toLowerCase() === clone);
510
+ }
511
+ const carried = logs.filter((log) => emitters.get(log.address.toLowerCase()) === true);
512
+ if (carried.length === 0) throw new Error(logs.length === 0 ? `transaction ${opts.tx} carries no payment or refusal under a mandate` : `transaction ${opts.tx} carries mandate outcomes only from ${[...emitters.keys()].join(", ")}, no account of the trusted factory ${accountFactory}`);
513
+ // One transaction may settle payments under several mandates (a sponsor's
514
+ // batch). `ref` or the credential in hand names the one to verify; a
515
+ // credential that names none of them is still checked against a single
516
+ // mandate, and fails there; without either, several are ambiguous.
517
+ const named = (log: (typeof carried)[number]) => `${log.address.toLowerCase()}:${log.args.ref.toLowerCase()}`;
518
+ const mandates = [...new Set(carried.map(named))];
519
+ const listed = mandates.map((k) => short(k.split(":")[1] as Hex)).join(", ");
520
+ const wanted = opts.ref !== undefined ? opts.ref : opts.credential !== undefined ? mandateReference(extractTerms(opts.credential).principal, extractTerms(opts.credential).agentKey, hashCredential(opts.credential)) : undefined;
521
+ let chosen = wanted === undefined ? undefined : mandates.find((k) => k.endsWith(`:${wanted.toLowerCase()}`));
522
+ if (chosen === undefined) {
523
+ if (opts.ref !== undefined) throw new Error(`transaction ${opts.tx} carries no payment or refusal under ${short(opts.ref)}; it carries outcomes under ${listed}`);
524
+ if (mandates.length > 1) throw new Error(`transaction ${opts.tx} carries outcomes under ${mandates.length} mandates (${listed})${opts.credential === undefined ? "; pass the credential, or the ref, of the one to verify" : ", none the credential's"}`);
525
+ chosen = mandates[0]!;
526
+ }
527
+ const [principal, ref] = chosen.split(":") as [Address, Hex];
528
+ // The mandate's events up to this payment's block decide whether it was revoked by then; the outcome itself is in the receipt.
529
+ const found = await boundMandate(client, principal, ref, accountFactory, receipt.blockNumber);
530
+ const events = carried.filter((log) => named(log) === chosen) as unknown as MandateEvent[];
531
+ return verify(client, found, { ...opts, accountFactory }, { tx: opts.tx, events });
532
+ }