@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,181 @@
1
+ import { x402Client } from "@x402/core/client";
2
+ import { describe, it, expect } from "vitest";
3
+ import {
4
+ registerClearingClient,
5
+ clearingRequirements,
6
+ clearingInvoice,
7
+ clearingPaymentOf,
8
+ clearingPaymentMismatch,
9
+ clearingPaymentId,
10
+ } from "./clearing-x402.js";
11
+ import {
12
+ createClearingSigner,
13
+ clearingUnits,
14
+ decodeSend,
15
+ encodeSend,
16
+ outgoingRoot,
17
+ invoiceMessage,
18
+ } from "./clearing-codec.js";
19
+ import type { ClearingInvoice } from "./clearing-codec.js";
20
+ import type { ClearingPaid } from "./clearing-client.js";
21
+
22
+ describe("native x402 invoice binding", () => {
23
+ const payer = createClearingSigner(`0x${"12".repeat(32)}`);
24
+ const operator = createClearingSigner(`0x${"23".repeat(32)}`);
25
+ const requirements = clearingRequirements(
26
+ {
27
+ network: "eip155:1337",
28
+ asset: `0x${"11".repeat(20)}`,
29
+ settlement: `0x${"22".repeat(20)}`,
30
+ recipient: operator.publicKey,
31
+ serviceUrl: "http://localhost:7091",
32
+ },
33
+ 5n,
34
+ "/coffee/cart-1",
35
+ );
36
+ const invoice = clearingInvoice(
37
+ requirements,
38
+ `${requirements.extra!.invoicePrefix}:purchase-1`,
39
+ );
40
+ const entries = [
41
+ { recipient: operator.publicKey, cumulative: "5", count: "1" },
42
+ ];
43
+ const body = encodeSend({
44
+ anchor: `0x${"00".repeat(32)}`,
45
+ epoch: 1n,
46
+ payer: payer.publicKey,
47
+ sequence: 0n,
48
+ debit: 5n,
49
+ vector: outgoingRoot([
50
+ { recipient: operator.publicKey, cumulative: 5n, count: 1n },
51
+ ]),
52
+ });
53
+ const paid: ClearingPaid = {
54
+ invoice,
55
+ entries,
56
+ invoiceSignature: payer.sign(
57
+ "_METAL_CLEARING_INVOICE",
58
+ invoiceMessage(invoice, body),
59
+ ),
60
+ receipt: {
61
+ body,
62
+ payerSignature: payer.sign("_COMMONWARE_CLEARING_VECTOR_SEND", body),
63
+ operatorSignature: operator.sign("_COMMONWARE_CLEARING_VECTOR_ACK", body),
64
+ },
65
+ };
66
+ it.each([
67
+ { amount: 19n * 10n ** 18n, unit: 10n ** 12n },
68
+ { amount: ((1n << 64n) - 1n) * 10n ** 30n, unit: 10n ** 30n },
69
+ ])("binds a $amount base-unit invoice", ({ amount, unit }) => {
70
+ const largeInvoice = { ...invoice, amount: amount.toString() };
71
+ const cumulative = clearingUnits(amount, unit);
72
+ const vector = [{ recipient: operator.publicKey, cumulative, count: 1n }];
73
+ const largeBody = encodeSend({
74
+ ...decodeSend(body),
75
+ debit: cumulative,
76
+ vector: outgoingRoot(vector),
77
+ });
78
+ const largePaid: ClearingPaid = {
79
+ invoice: largeInvoice,
80
+ entries: [{ ...entries[0]!, cumulative: cumulative.toString() }],
81
+ invoiceSignature: payer.sign(
82
+ "_METAL_CLEARING_INVOICE",
83
+ invoiceMessage(largeInvoice, largeBody),
84
+ ),
85
+ receipt: {
86
+ body: largeBody,
87
+ payerSignature: payer.sign("_COMMONWARE_CLEARING_VECTOR_SEND", largeBody),
88
+ operatorSignature: operator.sign(
89
+ "_COMMONWARE_CLEARING_VECTOR_ACK",
90
+ largeBody,
91
+ ),
92
+ },
93
+ };
94
+ expect(clearingPaymentOf({ payload: largePaid as never })).toEqual(largePaid);
95
+ expect(
96
+ clearingPaymentMismatch(largePaid, {
97
+ ...requirements,
98
+ amount: amount.toString(),
99
+ }),
100
+ ).toBeNull();
101
+ expect(
102
+ clearingPaymentOf({
103
+ payload: {
104
+ ...largePaid,
105
+ invoice: { ...largeInvoice, amount: (amount + 1n).toString() },
106
+ },
107
+ }),
108
+ ).toBeNull();
109
+ });
110
+ it.each([-1n, 1n << 256n])(
111
+ "rejects an invoice amount outside uint256: %s",
112
+ (amount) => {
113
+ expect(() =>
114
+ invoiceMessage({ ...invoice, amount: amount.toString() }, body),
115
+ ).toThrow();
116
+ },
117
+ );
118
+ it("rejects altered invoice amounts and cross-resource reuse", () => {
119
+ expect(clearingPaymentOf({ payload: paid as never })).toEqual(paid);
120
+ expect(
121
+ clearingPaymentOf({
122
+ payload: { ...paid, invoice: { ...invoice, amount: "6" } },
123
+ }),
124
+ ).toBeNull();
125
+ expect(clearingPaymentMismatch(paid, requirements)).toBeNull();
126
+ expect(
127
+ clearingPaymentMismatch(paid, {
128
+ ...requirements,
129
+ extra: { ...requirements.extra, invoicePrefix: `0x${"33".repeat(32)}` },
130
+ }),
131
+ ).toBe("invoice");
132
+ expect(clearingPaymentId(paid)).toBe(
133
+ clearingPaymentId({
134
+ ...paid,
135
+ invoice: { ...invoice, id: invoice.id + "other" },
136
+ }),
137
+ );
138
+ });
139
+ it("rejects a different vector or cumulative debit", () => {
140
+ expect(
141
+ clearingPaymentOf({
142
+ payload: { ...paid, entries: [{ ...entries[0], cumulative: "6" }] },
143
+ }),
144
+ ).toBeNull();
145
+ });
146
+ it("retries the pending invoice after the x402 adapter loses a response", async () => {
147
+ let pending: ClearingInvoice | null = null;
148
+ const ids: string[] = [];
149
+ const payer = {
150
+ async pendingInvoice() {
151
+ return pending;
152
+ },
153
+ payable: () => true,
154
+ async pay(next: ClearingInvoice) {
155
+ ids.push(next.id);
156
+ if (!pending) {
157
+ pending = next;
158
+ throw new Error("response lost");
159
+ }
160
+ expect(next).toEqual(pending);
161
+ pending = null;
162
+ return { ...paid, invoice: next };
163
+ },
164
+ };
165
+ const client = registerClearingClient(
166
+ new x402Client().setSpendControls({ allowedAssets: true }),
167
+ "eip155:1337",
168
+ payer as never,
169
+ );
170
+ const offer = {
171
+ x402Version: 2,
172
+ resource: { url: "/coffee/cart-1" },
173
+ accepts: [requirements],
174
+ };
175
+ await expect(client.createPaymentPayload(offer)).rejects.toThrow(
176
+ "response lost",
177
+ );
178
+ await client.createPaymentPayload(offer);
179
+ expect(ids[0]).toBe(ids[1]);
180
+ });
181
+ });
@@ -0,0 +1,279 @@
1
+ import type { PaymentRequirements, PaymentPayload } from "@x402/core/types";
2
+ import type { x402Client } from "@x402/core/client";
3
+ import { createPublicClient, http, sha256, stringToHex, type Hex } from "viem";
4
+ import { clearingAbi } from "./clearing-abi.js";
5
+ import {
6
+ CLEARING_SCHEME,
7
+ clearingUnits,
8
+ decodeSend,
9
+ invoiceMessage,
10
+ verifyClearingSignature,
11
+ verifyReceipt,
12
+ outgoingRoot,
13
+ type ClearingInvoice,
14
+ } from "./clearing-codec.js";
15
+ import type { ClearingPaid, createClearingClient } from "./clearing-client.js";
16
+
17
+ export interface ClearingSeller {
18
+ network: `eip155:${number}`;
19
+ asset: Hex;
20
+ settlement: Hex;
21
+ recipient: Hex;
22
+ serviceUrl: string;
23
+ }
24
+ /** A resource-bound invoice namespace; the payer appends a unique payment id. */
25
+ export function clearingRequirements(
26
+ seller: ClearingSeller,
27
+ amount: bigint,
28
+ resource: string,
29
+ ): PaymentRequirements {
30
+ if (amount <= 0n) throw new Error("invalid clearing price");
31
+ return {
32
+ scheme: CLEARING_SCHEME,
33
+ network: seller.network,
34
+ asset: seller.asset,
35
+ amount: amount.toString(),
36
+ payTo: seller.recipient,
37
+ maxTimeoutSeconds: 60,
38
+ extra: {
39
+ settlement: seller.settlement,
40
+ serviceUrl: seller.serviceUrl,
41
+ invoicePrefix: sha256(stringToHex(resource)),
42
+ },
43
+ };
44
+ }
45
+ export function clearingInvoice(
46
+ requirements: PaymentRequirements,
47
+ id: string,
48
+ ): ClearingInvoice {
49
+ const extra = requirements.extra;
50
+ if (
51
+ requirements.scheme !== CLEARING_SCHEME ||
52
+ !/^0x[0-9a-fA-F]{66}$/.test(requirements.payTo) ||
53
+ typeof extra?.settlement !== "string" ||
54
+ !/^0x[0-9a-fA-F]{40}$/.test(extra.settlement) ||
55
+ typeof extra.invoicePrefix !== "string" ||
56
+ !/^0x[0-9a-f]{64}$/.test(extra.invoicePrefix) ||
57
+ !id.startsWith(extra.invoicePrefix + ":")
58
+ )
59
+ throw new Error("invalid clearing requirement");
60
+ return {
61
+ id,
62
+ network: requirements.network,
63
+ asset: requirements.asset as Hex,
64
+ settlement: extra.settlement as Hex,
65
+ recipient: requirements.payTo as Hex,
66
+ amount: requirements.amount,
67
+ };
68
+ }
69
+ export function clearingPaymentOf(
70
+ payload: Pick<PaymentPayload, "payload">,
71
+ ): ClearingPaid | null {
72
+ try {
73
+ const paid = payload.payload as unknown as ClearingPaid;
74
+ const body = decodeSend(paid.receipt.body);
75
+ invoiceMessage(paid.invoice, paid.receipt.body);
76
+ const entries = paid.entries.map((e) => ({
77
+ ...e,
78
+ cumulative: BigInt(e.cumulative),
79
+ count: BigInt(e.count),
80
+ }));
81
+ if (
82
+ entries.length > 1024 ||
83
+ outgoingRoot(entries) !== body.vector ||
84
+ entries.reduce((n, e) => n + e.cumulative, 0n) !== body.debit ||
85
+ !verifyClearingSignature(
86
+ body.payer,
87
+ "_METAL_CLEARING_INVOICE",
88
+ invoiceMessage(paid.invoice, paid.receipt.body),
89
+ paid.invoiceSignature,
90
+ )
91
+ )
92
+ return null;
93
+ return paid;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ export function clearingPaymentMismatch(
99
+ paid: ClearingPaid,
100
+ requirements: PaymentRequirements,
101
+ ): string | null {
102
+ try {
103
+ return invoiceMessage(
104
+ clearingInvoice(requirements, paid.invoice.id),
105
+ paid.receipt.body,
106
+ ) === invoiceMessage(paid.invoice, paid.receipt.body)
107
+ ? null
108
+ : "invoice";
109
+ } catch {
110
+ return "invoice";
111
+ }
112
+ }
113
+ export function clearingPaymentId(paid: ClearingPaid): string {
114
+ return `${paid.invoice.network}:bajillion:${paid.invoice.settlement.toLowerCase()}:${sha256(paid.receipt.body)}`;
115
+ }
116
+ /** Both the RPC and service URL must come from the seller's trusted configuration. */
117
+ export async function verifyClearingPayment(
118
+ paid: ClearingPaid,
119
+ requirements: PaymentRequirements,
120
+ config: { rpcUrl: string; serviceUrl: string; settlement: Hex },
121
+ ) {
122
+ if (
123
+ clearingPaymentMismatch(paid, requirements) ||
124
+ paid.invoice.settlement.toLowerCase() !== config.settlement.toLowerCase()
125
+ )
126
+ throw new Error("clearing invoice mismatch");
127
+ if (
128
+ !clearingPaymentOf({ payload: paid as unknown as Record<string, unknown> })
129
+ )
130
+ throw new Error("invalid clearing payment");
131
+ const send = decodeSend(paid.receipt.body);
132
+ const client = createPublicClient({ transport: http(config.rpcUrl) });
133
+ const [context, fault, asset, chainId, unit] = await Promise.all([
134
+ client.readContract({
135
+ address: config.settlement,
136
+ abi: clearingAbi,
137
+ functionName: "contextOf",
138
+ args: [send.epoch],
139
+ }),
140
+ client.readContract({
141
+ address: config.settlement,
142
+ abi: clearingAbi,
143
+ functionName: "fault",
144
+ }),
145
+ client.readContract({
146
+ address: config.settlement,
147
+ abi: clearingAbi,
148
+ functionName: "token",
149
+ }),
150
+ client.getChainId(),
151
+ client.readContract({
152
+ address: config.settlement,
153
+ abi: clearingAbi,
154
+ functionName: "unit",
155
+ }),
156
+ ]);
157
+ if (
158
+ fault ||
159
+ `eip155:${chainId}` !== paid.invoice.network ||
160
+ asset.toLowerCase() !== paid.invoice.asset.toLowerCase() ||
161
+ context.anchor !== send.anchor ||
162
+ !verifyReceipt(paid.receipt, context.operatorKey)
163
+ )
164
+ throw new Error("invalid clearing receipt");
165
+ const previous = paid.previous;
166
+ let before: ClearingPaid["entries"] = [];
167
+ if (send.sequence === 0n) {
168
+ if (previous) throw new Error("unexpected predecessor receipt");
169
+ } else {
170
+ if (!previous || !verifyReceipt(previous.receipt, context.operatorKey))
171
+ throw new Error("missing predecessor receipt");
172
+ const prior = decodeSend(previous.receipt.body);
173
+ before = previous.entries;
174
+ if (
175
+ prior.epoch !== send.epoch ||
176
+ prior.anchor !== send.anchor ||
177
+ prior.payer !== send.payer ||
178
+ prior.sequence + 1n !== send.sequence ||
179
+ outgoingRoot(
180
+ before.map((e) => ({
181
+ ...e,
182
+ cumulative: BigInt(e.cumulative),
183
+ count: BigInt(e.count),
184
+ })),
185
+ ) !== prior.vector
186
+ )
187
+ throw new Error("invalid predecessor vector");
188
+ }
189
+ const expected = new Map(
190
+ before.map((e) => [e.recipient.toLowerCase(), { ...e }]),
191
+ );
192
+ const key = paid.invoice.recipient.toLowerCase();
193
+ const old = expected.get(key);
194
+ // The invoice is in token base units; the vector counts clearing units.
195
+ expected.set(key, {
196
+ recipient: paid.invoice.recipient,
197
+ cumulative: (
198
+ (old ? BigInt(old.cumulative) : 0n) +
199
+ clearingUnits(BigInt(paid.invoice.amount), unit)
200
+ ).toString(),
201
+ count: ((old ? BigInt(old.count) : 0n) + 1n).toString(),
202
+ });
203
+ if (
204
+ expected.size !== paid.entries.length ||
205
+ paid.entries.some((e) => {
206
+ const wanted = expected.get(e.recipient.toLowerCase());
207
+ return (
208
+ !wanted ||
209
+ wanted.count !== e.count ||
210
+ wanted.cumulative !== e.cumulative
211
+ );
212
+ })
213
+ )
214
+ throw new Error("invoice is not the incremental payment");
215
+ // The operator's durable invoice journal attests the incremental charge,
216
+ // which cannot be inferred from a cumulative vector alone.
217
+ const response = await fetch(
218
+ new URL(
219
+ `/receipt/${send.payer}/${encodeURIComponent(paid.invoice.id)}?epoch=${send.epoch}`,
220
+ config.serviceUrl,
221
+ ),
222
+ { signal: AbortSignal.timeout(10_000) },
223
+ );
224
+ if (!response.ok) throw new Error("clearing receipt unavailable");
225
+ const recorded = (await response.json()) as ClearingPaid | null;
226
+ if (
227
+ !recorded ||
228
+ recorded.receipt.body !== paid.receipt.body ||
229
+ recorded.receipt.operatorSignature !== paid.receipt.operatorSignature ||
230
+ invoiceMessage(recorded.invoice, recorded.receipt.body) !==
231
+ invoiceMessage(paid.invoice, paid.receipt.body)
232
+ )
233
+ throw new Error("clearing invoice not retained");
234
+ return {
235
+ payer: send.payer,
236
+ id: clearingPaymentId(paid),
237
+ status: "preconfirmed" as const,
238
+ };
239
+ }
240
+ export function registerClearingClient(
241
+ client: x402Client,
242
+ network: `eip155:${number}`,
243
+ payer: Pick<
244
+ ReturnType<typeof createClearingClient>,
245
+ "pay" | "payable" | "pendingInvoice"
246
+ >,
247
+ ) {
248
+ client.register(network, {
249
+ scheme: CLEARING_SCHEME,
250
+ async createPaymentPayload(x402Version, requirements) {
251
+ const pending = await payer.pendingInvoice();
252
+ const suffix = globalThis.crypto.randomUUID();
253
+ const invoice = clearingInvoice(
254
+ requirements,
255
+ pending?.id ?? `${requirements.extra?.invoicePrefix}:${suffix}`,
256
+ );
257
+ const paid = await payer.pay(invoice);
258
+ return {
259
+ x402Version,
260
+ payload: paid as unknown as Record<string, unknown>,
261
+ };
262
+ },
263
+ });
264
+ // The stock client keeps only `authorization` offers when any remain after
265
+ // its policies, and a clearing offer is `upfront`: so a payer set up for
266
+ // clearing keeps the clearing offers its wallet can pay, when there are any.
267
+ client.registerPolicy((_, offers) => {
268
+ const clearing = offers.filter((offer) => {
269
+ if (offer.scheme !== CLEARING_SCHEME || offer.network !== network) return false;
270
+ try {
271
+ return payer.payable(clearingInvoice(offer, `${offer.extra?.invoicePrefix}:`));
272
+ } catch {
273
+ return false;
274
+ }
275
+ });
276
+ return clearing.length > 0 ? clearing : offers;
277
+ });
278
+ return client;
279
+ }