@integraledger/profile-facilitator 0.4.0 → 0.5.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.
Files changed (91) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +781 -456
  3. package/dist/answers.d.ts +11 -4
  4. package/dist/answers.js +24 -0
  5. package/dist/core.d.ts +51 -0
  6. package/dist/core.js +758 -0
  7. package/dist/http.d.ts +20 -3
  8. package/dist/http.js +32 -7
  9. package/dist/index.d.ts +12 -36
  10. package/dist/index.js +9 -162
  11. package/dist/module.d.ts +372 -0
  12. package/dist/module.js +13 -0
  13. package/dist/modules/algorand/index.d.ts +22 -0
  14. package/dist/modules/algorand/index.js +247 -0
  15. package/dist/modules/algorand/own.d.ts +26 -0
  16. package/dist/modules/algorand/own.js +231 -0
  17. package/dist/modules/aptos/index.d.ts +23 -0
  18. package/dist/modules/aptos/index.js +232 -0
  19. package/dist/modules/cardano/index.d.ts +18 -0
  20. package/dist/modules/cardano/index.js +124 -0
  21. package/dist/modules/casper/index.d.ts +120 -0
  22. package/dist/modules/casper/index.js +442 -0
  23. package/dist/modules/concordium/index.d.ts +16 -0
  24. package/dist/modules/concordium/index.js +77 -0
  25. package/dist/modules/erc7710/index.d.ts +26 -0
  26. package/dist/modules/erc7710/index.js +220 -0
  27. package/dist/modules/evm/forms.d.ts +74 -0
  28. package/dist/modules/evm/forms.js +204 -0
  29. package/dist/modules/evm/index.d.ts +40 -0
  30. package/dist/modules/evm/index.js +154 -0
  31. package/dist/modules/evm/node.d.ts +29 -0
  32. package/dist/modules/evm/node.js +222 -0
  33. package/dist/modules/hedera/executor.d.ts +63 -0
  34. package/dist/modules/hedera/executor.js +343 -0
  35. package/dist/modules/hedera/index.d.ts +23 -0
  36. package/dist/modules/hedera/index.js +136 -0
  37. package/dist/modules/hedera/mirror.d.ts +32 -0
  38. package/dist/modules/hedera/mirror.js +111 -0
  39. package/dist/modules/index.d.ts +23 -0
  40. package/dist/modules/index.js +24 -0
  41. package/dist/modules/lnbtc/index.d.ts +10 -0
  42. package/dist/modules/lnbtc/index.js +112 -0
  43. package/dist/modules/near/index.d.ts +18 -0
  44. package/dist/modules/near/index.js +246 -0
  45. package/dist/modules/polkadot/index.d.ts +12 -0
  46. package/dist/modules/polkadot/index.js +149 -0
  47. package/dist/modules/polkadot/rail.d.ts +40 -0
  48. package/dist/{polkadot.js → modules/polkadot/rail.js} +214 -288
  49. package/dist/modules/solana/index.d.ts +60 -0
  50. package/dist/modules/solana/index.js +326 -0
  51. package/dist/modules/solana/reader.d.ts +25 -0
  52. package/dist/modules/solana/reader.js +194 -0
  53. package/dist/modules/solana/state.d.ts +6 -0
  54. package/dist/modules/solana/state.js +103 -0
  55. package/dist/modules/starknet/index.d.ts +35 -0
  56. package/dist/modules/starknet/index.js +548 -0
  57. package/dist/modules/starknet/node.d.ts +78 -0
  58. package/dist/modules/starknet/node.js +339 -0
  59. package/dist/modules/stellar/index.d.ts +44 -0
  60. package/dist/modules/stellar/index.js +481 -0
  61. package/dist/modules/stellar/node.d.ts +57 -0
  62. package/dist/modules/stellar/node.js +151 -0
  63. package/dist/modules/sui/index.d.ts +16 -0
  64. package/dist/modules/sui/index.js +310 -0
  65. package/dist/modules/sui/node.d.ts +49 -0
  66. package/dist/modules/sui/node.js +197 -0
  67. package/dist/modules/ton/index.d.ts +16 -0
  68. package/dist/modules/ton/index.js +73 -0
  69. package/dist/modules/tron/index.d.ts +12 -0
  70. package/dist/modules/tron/index.js +120 -0
  71. package/dist/modules/tron/rail.d.ts +32 -0
  72. package/dist/{tron.js → modules/tron/rail.js} +206 -195
  73. package/dist/modules/xrpl/index.d.ts +28 -0
  74. package/dist/modules/xrpl/index.js +299 -0
  75. package/dist/modules/xrpl/node.d.ts +52 -0
  76. package/dist/modules/xrpl/node.js +231 -0
  77. package/dist/modules/xrpl/upto.d.ts +5 -0
  78. package/dist/modules/xrpl/upto.js +269 -0
  79. package/dist/record.d.ts +131 -0
  80. package/dist/record.js +330 -0
  81. package/dist/unexpected.d.ts +3 -2
  82. package/dist/unexpected.js +2 -1
  83. package/dist/wrapper.d.ts +68 -0
  84. package/dist/wrapper.js +126 -0
  85. package/package.json +48 -12
  86. package/dist/polkadot.d.ts +0 -21
  87. package/dist/store.d.ts +0 -59
  88. package/dist/store.js +0 -103
  89. package/dist/tron.d.ts +0 -12
  90. /package/dist/{base58check.d.ts → modules/tron/base58check.d.ts} +0 -0
  91. /package/dist/{base58check.js → modules/tron/base58check.js} +0 -0
package/dist/core.js ADDED
@@ -0,0 +1,758 @@
1
+ /**
2
+ * The settler's core: x402's facilitator class (`x402Facilitator` of `@x402/core/facilitator`) holding one wrapper per
3
+ * configured scheme and network, for `/verify` and for `/settle` each, the record, the fee budget, the caller's
4
+ * credential and the operator log, behind `GET /supported`, `POST /verify` and `POST /settle` over `node:http`. The core
5
+ * holds no chain's rule and no key: each module's facilitator verifies and settles, and the core decides only what its
6
+ * record, its budget and lcp's read of the chain tell it.
7
+ */
8
+ import { createHash, timingSafeEqual } from "node:crypto";
9
+ import { createServer } from "node:http";
10
+ import { x402Facilitator } from "@x402/core/facilitator";
11
+ import { failed, guarded, invalid, isObject, operatorLine, pending, readShape, } from "./answers.js";
12
+ import { NODE_TIMEOUT_MS, readRequestJson, sendJson, sleep, X402_REQUEST_MAX_BYTES } from "./http.js";
13
+ import { answerReserve, feesOn, inTime, keepUntil, keyOf, moduleState, openPool, openRecord, sweeping, } from "./record.js";
14
+ import { settleReason, unexpectedSettle, unexpectedVerify } from "./unexpected.js";
15
+ import { declared, kindOf, modulesOf, route, unsound, Wrapper } from "./wrapper.js";
16
+ const DEFAULT_SETTLE_WAIT_MS = 30_000;
17
+ /** How often a settle that finds another settle holding the claim reads the record again. */
18
+ const WATCH_MS = 1_000;
19
+ /** RFC 6750's `b64token`, the characters a bearer credential may hold. */
20
+ const B64TOKEN = /^[A-Za-z0-9\-._~+/]+=*$/;
21
+ /** The body's `paymentRequirements.network` when it is a string, else "". */
22
+ function networkOf(body) {
23
+ const requirements = isObject(body) ? body["paymentRequirements"] : undefined;
24
+ const network = isObject(requirements) ? requirements["network"] : undefined;
25
+ return typeof network === "string" ? network : "";
26
+ }
27
+ function hostPort(listen) {
28
+ const m = /^\[?([^\]]*)\]?:(\d{1,5})$/.exec(listen);
29
+ const port = m === null ? NaN : Number(m[2]);
30
+ if (m === null || !(port >= 0 && port <= 65_535))
31
+ throw new TypeError(`listen must be "host:port": ${listen}`);
32
+ return { host: m[1], port };
33
+ }
34
+ /** The budgets as configured, each checked: a positive amount, a positive whole number of seconds, one per network. */
35
+ function budgetsOf(configured) {
36
+ const seen = new Set();
37
+ return configured.map((b) => {
38
+ const amount = typeof b.amount === "bigint" ? b.amount : /^[0-9]+$/.test(b.amount) ? BigInt(b.amount) : -1n;
39
+ if (amount <= 0n)
40
+ throw new TypeError(`the fee budget of ${b.network}: its amount is not a positive integer`);
41
+ if (!Number.isSafeInteger(b.periodSeconds) || b.periodSeconds <= 0) {
42
+ throw new TypeError(`the fee budget of ${b.network}: its period is not a positive number of seconds`);
43
+ }
44
+ if (seen.has(b.network))
45
+ throw new TypeError(`${b.network} has two fee budgets`);
46
+ seen.add(b.network);
47
+ return { network: b.network, amount, periodSeconds: b.periodSeconds };
48
+ });
49
+ }
50
+ /** Whether `req` presents the credential whose SHA-256 is `expected`, compared in constant time. */
51
+ function presents(req, expected) {
52
+ const header = req.headers["authorization"];
53
+ const m = typeof header === "string" ? /^Bearer +(\S+) *$/i.exec(header) : null;
54
+ const given = createHash("sha256")
55
+ .update(m?.[1] ?? "")
56
+ .digest();
57
+ return timingSafeEqual(given, expected) && m !== null;
58
+ }
59
+ /** Whether two spellings of a transaction id name one transaction: the same digits, with or without `0x`, in any case. */
60
+ function sameTransaction(a, b) {
61
+ const plain = (t) => t.replace(/^0x/i, "").toLowerCase();
62
+ return plain(a) === plain(b);
63
+ }
64
+ /** A JSON value with each object's members in the order of their names, so that one value has one spelling. */
65
+ function canonical(v) {
66
+ if (Array.isArray(v))
67
+ return v.map(canonical);
68
+ if (typeof v !== "object" || v === null)
69
+ return v;
70
+ const o = v;
71
+ return Object.fromEntries(Object.keys(o).sort().map((k) => [k, canonical(o[k])]));
72
+ }
73
+ /** The digest of a payment's body as presented: its payload and its requirements, whatever order their members came in. */
74
+ function bodyOf(p) {
75
+ return createHash("sha256")
76
+ .update(JSON.stringify(canonical({ payload: p.payload, requirements: p.requirements })))
77
+ .digest("hex");
78
+ }
79
+ /** A read the core could not make: nothing is known of the instrument. */
80
+ const UNREAD = { outcome: "live", answer: { state: "unreadable", reason: "transport", foreign: [] } };
81
+ /**
82
+ * Starts the settler with the modules of `list` that `c` names. The public start function passes the settler's own
83
+ * list; a test passes one of its own.
84
+ */
85
+ export async function serveSettler(c, list) {
86
+ const { host, port } = hostPort(c.listen);
87
+ const settleWaitMs = Number.isFinite(c.settleWaitMs) && c.settleWaitMs > 0 ? c.settleWaitMs : DEFAULT_SETTLE_WAIT_MS;
88
+ const log = guarded(c.operatorLog ?? operatorLine);
89
+ if (c.credential !== undefined && !B64TOKEN.test(c.credential)) {
90
+ throw new TypeError("credential must be a bearer token: letters, digits and -._~+/, then any =");
91
+ }
92
+ const credential = c.credential === undefined ? undefined : createHash("sha256").update(c.credential).digest();
93
+ const budgets = budgetsOf(c.feeBudgets ?? []);
94
+ const pool = await openPool(c.store.url, log);
95
+ // If the settler does not start, what it opened is closed before its error goes to the caller unchanged: the
96
+ // modules, the sweep and the pool.
97
+ const closers = [];
98
+ let stopSweep = () => { };
99
+ try {
100
+ const record = await openRecord(pool);
101
+ const fees = feesOn(pool, budgets);
102
+ stopSweep = sweeping(record, fees, log);
103
+ // The modules the configuration names, each started from its own member alone.
104
+ const configured = c;
105
+ const registrations = [];
106
+ const offered = [];
107
+ // The modules started with the fee meter of their network: their keys' fees are counted as they send.
108
+ const metered = new Set();
109
+ for (const listed of list) {
110
+ const own = configured[listed.name];
111
+ if (own === undefined)
112
+ continue;
113
+ const starter = await listed.load();
114
+ const meters = new Set();
115
+ const core = {
116
+ log,
117
+ settleWaitMs,
118
+ state: moduleState(pool, listed.name),
119
+ meter: (network) => {
120
+ meters.add(network);
121
+ return fees.meter(network, () => Date.now(), log);
122
+ },
123
+ };
124
+ const started = await starter.start(own, core);
125
+ if (started.close !== undefined)
126
+ closers.push(started.close);
127
+ registrations.push(...started.registrations);
128
+ offered.push(...(started.handoffs ?? []));
129
+ for (const r of started.registrations)
130
+ for (const m of modulesOf(r))
131
+ if (meters.has(m.network))
132
+ metered.add(m);
133
+ for (const o of started.handoffs ?? [])
134
+ if (meters.has(o.network))
135
+ metered.add(o.handoff.module);
136
+ }
137
+ // Each own module offered to another module's registration goes behind that registration's own modules.
138
+ for (const o of offered) {
139
+ const at = registrations.findIndex((r) => r.network === o.network && r.module.facilitator.scheme === o.scheme);
140
+ if (at < 0)
141
+ throw new TypeError(`an own module is offered to ${o.scheme} on ${o.network}, which no module registers`);
142
+ const r = registrations[at];
143
+ registrations[at] = { ...r, own: [...r.own, o.handoff] };
144
+ }
145
+ const kinds = new Map();
146
+ const networks = new Set();
147
+ for (const r of registrations) {
148
+ const why = unsound(r);
149
+ if (why !== undefined)
150
+ throw new TypeError(why);
151
+ const at = `${r.module.facilitator.scheme} ${r.network}`;
152
+ if (kinds.has(at))
153
+ throw new TypeError(`two registrations of ${at}`);
154
+ kinds.set(at, kindOf(r, fees.budgeted(r.network)));
155
+ networks.add(r.network);
156
+ }
157
+ for (const b of budgets) {
158
+ if (!networks.has(b.network))
159
+ throw new TypeError(`the fee budget of ${b.network}: no module serves it`);
160
+ }
161
+ // A budget holds only where it counts every fee a key pays: each module with a key meters its sends or shows
162
+ // the fee of what its facilitator sent.
163
+ for (const r of registrations) {
164
+ if (!fees.budgeted(r.network))
165
+ continue;
166
+ for (const m of modulesOf(r)) {
167
+ if (m.descriptor.key === "none" || m.fees.charged !== undefined || metered.has(m))
168
+ continue;
169
+ throw new TypeError(`the fee budget of ${r.network}: the ${m.descriptor.name} module's key pays fees it neither meters nor shows`);
170
+ }
171
+ }
172
+ const keyed = [...kinds.values()].filter((k) => k.key !== "none");
173
+ if (credential === undefined && keyed.length > 0) {
174
+ throw new TypeError(`a module holds a key (${keyed.map((k) => `${k.scheme} on ${k.network}`).join(", ")}): credential is required`);
175
+ }
176
+ // x402's class twice, one wrapper per kind in each: `facilitator`'s wrappers verify in `/verify`'s phase, and give
177
+ // `/supported`; `settling`'s verify in `/settle`'s, for the check `/settle` makes before it submits, and submit.
178
+ const facilitator = new x402Facilitator();
179
+ const settling = new x402Facilitator();
180
+ for (const kind of kinds.values()) {
181
+ facilitator.register(kind.network, new Wrapper(kind, "verify"));
182
+ settling.register(kind.network, new Wrapper(kind, "settle"));
183
+ }
184
+ function supported() {
185
+ const s = facilitator.getSupported();
186
+ return { kinds: s.kinds, extensions: s.extensions, signers: s.signers };
187
+ }
188
+ /** The kind that serves the request's scheme and network, or why none does. */
189
+ function kindAt(r) {
190
+ const { scheme, network } = r.paymentRequirements;
191
+ if (!networks.has(network))
192
+ return "invalid_network";
193
+ return kinds.get(`${scheme} ${network}`) ?? "unsupported_scheme";
194
+ }
195
+ function paymentOf(r) {
196
+ return {
197
+ payload: r.paymentPayload,
198
+ requirements: r.paymentRequirements,
199
+ };
200
+ }
201
+ /** Whether a spent budget refuses the payment: the module's key pays its fee, and its payer did not broadcast it. */
202
+ function gated(m, p) {
203
+ return m.fees.paysFee(p) && !m.fees.payerBroadcast(p);
204
+ }
205
+ /** The fields that name an attempt's payment in an operator entry. */
206
+ function about(a, more = {}) {
207
+ const entry = { event: "", network: a.network };
208
+ if (more.payer !== undefined)
209
+ entry.payer = more.payer;
210
+ const transaction = more.transaction ?? (a.instrumented.instrument.by === "transaction" ? a.instrumented.instrument.transaction : undefined);
211
+ if (transaction !== undefined)
212
+ entry.transaction = transaction;
213
+ return entry;
214
+ }
215
+ /**
216
+ * lcp's read of the attempt's instrument through its module, ending by the attempt's `waitUntil`, resuming from
217
+ * `search`. A read the deadline leaves no time for is not made, and one that fails is given to the operator log:
218
+ * either leaves the instrument live, as an unreadable answer does.
219
+ */
220
+ async function readChain(a, held) {
221
+ if (a.waitUntil - performance.now() <= 0)
222
+ return UNREAD;
223
+ try {
224
+ return await a.module.record.read(a.payment, {
225
+ deadline: a.waitUntil,
226
+ ...(held.search === undefined ? {} : { search: held.search }),
227
+ ...(held.since === undefined ? {} : { from: held.since }),
228
+ ...(held.transaction === undefined ? {} : { transaction: held.transaction }),
229
+ });
230
+ }
231
+ catch (e) {
232
+ log({ ...about(a), event: "read-failed" }, e);
233
+ return UNREAD;
234
+ }
235
+ }
236
+ /**
237
+ * Counts the fee of a transaction the attempt's published class sent, where its network has a budget. It is asked
238
+ * once the answer is stored, on its own bounds, since the class's settle runs on its own and can outlast the
239
+ * request.
240
+ */
241
+ async function countFee(a, transaction) {
242
+ const charged = a.module.fees.charged;
243
+ if (!fees.budgeted(a.network) || charged === undefined || !gated(a.module, a.payment))
244
+ return;
245
+ try {
246
+ const deadline = performance.now() + NODE_TIMEOUT_MS;
247
+ const shown = await charged.call(a.module.fees, a.payment, { transaction, deadline });
248
+ await inTime(fees.count(a.network, transaction, shown.fee, shown.included, Date.now()), Infinity);
249
+ }
250
+ catch (e) {
251
+ log({ ...about(a, { transaction }), event: "fee-not-counted" }, e);
252
+ }
253
+ }
254
+ /**
255
+ * Keeps a transaction the attempt's submission named in its row, before anything else is asked, so that a read
256
+ * or a repeat knows it; a failure goes to the log. The store call has its own bound, the request's being spent.
257
+ */
258
+ async function note(a, transaction) {
259
+ try {
260
+ await inTime(record.sent(a.network, a.key, transaction), Infinity);
261
+ }
262
+ catch (e) {
263
+ log({ ...about(a, { transaction }), event: "store-call-failed", call: "sent" }, e);
264
+ }
265
+ }
266
+ /** Ends the attempt's hold of its claim, keeping what it learnt; a failure goes to the log, and the hold lapses. */
267
+ async function release(a, learnt) {
268
+ try {
269
+ await inTime(record.release(a.network, a.key, learnt), Infinity);
270
+ }
271
+ catch (e) {
272
+ log({ ...about(a), event: "store-call-failed", call: "release" }, e);
273
+ }
274
+ }
275
+ /**
276
+ * Makes the attempt's row final. True where this call made it final, false where another call had; undefined
277
+ * where the store did not answer, which goes to the log.
278
+ */
279
+ async function finish(a, f) {
280
+ const now = Date.now();
281
+ try {
282
+ return await inTime(record.finish(a.network, a.key, {
283
+ pairing: a.instrumented.pairing,
284
+ outcome: f.outcome,
285
+ answer: f.answer,
286
+ ...(f.transaction === undefined ? {} : { transaction: f.transaction }),
287
+ ...(f.payer === undefined ? {} : { payer: f.payer }),
288
+ keepUntil: keepUntil(a.instrumented.keep, a.instrumented.nonce, f.claimed ?? now),
289
+ now,
290
+ }),
291
+ // Its own bound: what the chain showed is stored even where the request's deadline has passed.
292
+ Infinity);
293
+ }
294
+ catch (e) {
295
+ log({ ...about(a, f), event: "answer-not-stored" }, e);
296
+ return undefined;
297
+ }
298
+ }
299
+ /** `/settle`'s answer to a row that is final: never a second success, and the transaction it names. */
300
+ function answerFinal(a, row) {
301
+ return failed("invalid_transaction_state", row.transaction ?? "", a.network);
302
+ }
303
+ /**
304
+ * The answer, once lcp's read shows the instrument final, and the row made final. A success is this settler's only
305
+ * where it sent the payment (`sent`, every transaction its submissions for the claim named) and the read shows
306
+ * settled one of those transactions, or the payment presented itself, which lcp's read can name otherwise than the
307
+ * submission did (a Polkadot extrinsic by its timepoint, not its hash); and only to the call that made the row
308
+ * final. A landed act that is another body than the one presented is never that call's success. One that landed by
309
+ * another route is `invalid_transaction_state` naming it. A failed instrument is `invalid_transaction_state` naming
310
+ * the transaction the read found, or the last one the settler sent, or the class's own failure where it named the
311
+ * transaction it sent.
312
+ */
313
+ async function byFinalRead(a, read, sent, payer, claimed, classAnswer) {
314
+ const answer = read.answer;
315
+ const kept = { ...(payer === undefined ? {} : { payer }), ...(claimed === undefined ? {} : { claimed }) };
316
+ if (answer.state === "settled") {
317
+ const mine = sent.find((t) => sameTransaction(answer.transaction, t));
318
+ if (mine !== undefined && answer.presented === "no") {
319
+ // The settler's transaction, of another body under this instrument than this call presents: not this call's
320
+ // success, and the row stays the claim's.
321
+ await release(a, {});
322
+ return failed("invalid_transaction_state", answer.transaction, a.network);
323
+ }
324
+ if (mine !== undefined || (sent.length > 0 && answer.presented === "yes")) {
325
+ const transaction = mine ?? answer.transaction;
326
+ const success = { success: true, transaction, network: a.network, payer: payer ?? "" };
327
+ const wrote = await finish(a, { outcome: "settled", answer: success, transaction, ...kept });
328
+ void countFee(a, transaction);
329
+ if (wrote === undefined)
330
+ return pending(transaction, a.network);
331
+ return wrote ? success : failed("invalid_transaction_state", transaction, a.network);
332
+ }
333
+ const refused = failed("invalid_transaction_state", answer.transaction, a.network);
334
+ await finish(a, { outcome: "settled", answer: refused, transaction: answer.transaction, ...kept });
335
+ return refused;
336
+ }
337
+ const last = sent.at(-1);
338
+ if (last !== undefined)
339
+ void countFee(a, last);
340
+ const own = classAnswer !== undefined && classAnswer.transaction !== "" ? classAnswer : undefined;
341
+ const named = answer.transaction ?? own?.transaction ?? last;
342
+ const refused = own ?? failed("invalid_transaction_state", named ?? "", a.network);
343
+ await finish(a, { outcome: answer.reason, answer: refused, ...(named === undefined ? {} : { transaction: named }), ...kept });
344
+ return refused;
345
+ }
346
+ /**
347
+ * For a claim this attempt holds: the fee budget, just before anything is sent; the submission of what
348
+ * the payer signed, through x402's class and the kind's wrapper; then the answer: a success the class gives once
349
+ * it is stored final, else by lcp's read. `sent` is every transaction earlier submissions for the claim named.
350
+ */
351
+ async function submit(a, payer, sent, claimed, since) {
352
+ if (gated(a.module, a.payment)) {
353
+ let spent;
354
+ try {
355
+ spent = await inTime(fees.spent(a.network, Date.now()), a.deadline);
356
+ }
357
+ catch (e) {
358
+ await release(a, {});
359
+ return unexpectedSettle(log, { ...about(a, { ...(payer === undefined ? {} : { payer }) }), event: "store-call-failed", call: "fee" }, e);
360
+ }
361
+ if (spent) {
362
+ await release(a, {});
363
+ return failed("fee_budget_spent", "", a.network);
364
+ }
365
+ }
366
+ if (a.waitUntil - performance.now() <= 0) {
367
+ await release(a, {});
368
+ return unexpectedSettle(log, { ...about(a), event: "settle-deadline-passed", before: "submission", settleWaitMs });
369
+ }
370
+ let s;
371
+ let thrown;
372
+ try {
373
+ s = await settling.settle(a.payment.payload, a.payment.requirements);
374
+ }
375
+ catch (e) {
376
+ thrown = { cause: e };
377
+ }
378
+ const failure = { ...about(a, { ...(payer === undefined ? {} : { payer }) }), event: "settle-error" };
379
+ const named = s !== undefined && s.transaction !== "" ? s.transaction : undefined;
380
+ if (s?.success === true) {
381
+ // A success is given only once the row holds it final, with the transaction it names where it names one (a
382
+ // published class's settle of a zero amount names none): a repeat is then answered from the record.
383
+ const answerPayer = s.payer ?? payer;
384
+ const wrote = await finish(a, {
385
+ outcome: "settled",
386
+ answer: s,
387
+ ...(named === undefined ? {} : { transaction: named }),
388
+ ...(answerPayer === undefined ? {} : { payer: answerPayer }),
389
+ claimed,
390
+ });
391
+ if (named !== undefined)
392
+ void countFee(a, named);
393
+ if (wrote === true)
394
+ return s;
395
+ if (wrote === false)
396
+ return failed("invalid_transaction_state", named ?? "", a.network);
397
+ // A success that names no transaction and could not be stored: no pending answer can name it.
398
+ if (named === undefined)
399
+ return unexpectedSettle(log, { ...about(a), event: "success-not-stored" });
400
+ return pending(named, a.network);
401
+ }
402
+ const all = named === undefined || sent.some((t) => sameTransaction(t, named)) ? sent : [...sent, named];
403
+ if (named !== undefined) {
404
+ await note(a, named);
405
+ void countFee(a, named);
406
+ }
407
+ const read = await readChain(a, { since, transaction: all.at(-1) });
408
+ if (thrown !== undefined && (read.outcome === "final" || all.length > 0))
409
+ log(failure, thrown.cause);
410
+ if (read.outcome === "final")
411
+ return byFinalRead(a, read, all, s?.payer ?? payer, claimed, s);
412
+ const live = read.answer;
413
+ await release(a, live.state === "pending" && live.search !== undefined ? { search: live.search } : {});
414
+ if (s !== undefined && named !== undefined) {
415
+ // A failed result that consumed nothing is the class's own answer; anything else sent is not yet shown.
416
+ const consumedNothing = live.state === "pending" && live.reason === "instrument-live" && live.transaction !== undefined;
417
+ return consumedNothing ? s : pending(named, a.network);
418
+ }
419
+ if (s !== undefined)
420
+ return s;
421
+ const last = all.at(-1);
422
+ return last === undefined ? unexpectedSettle(log, failure, thrown?.cause) : pending(last, a.network);
423
+ }
424
+ /**
425
+ * A claim another settle holds and may be sending: the row is read until that settle answers or its hold ends,
426
+ * and the chain then, and nothing is sent.
427
+ */
428
+ async function watch(a, row) {
429
+ let current = row;
430
+ for (;;) {
431
+ if (current.final)
432
+ return answerFinal(a, current);
433
+ if (current.heldUntil <= Date.now()) {
434
+ const read = await readChain(a, current);
435
+ if (read.outcome === "final")
436
+ return byFinalRead(a, read, current.sent, current.payer, current.claimed);
437
+ if (read.answer.state === "pending" && read.answer.reason === "below-mark" && read.answer.transaction !== undefined) {
438
+ return pending(read.answer.transaction, a.network);
439
+ }
440
+ if (current.transaction !== undefined)
441
+ return pending(current.transaction, a.network);
442
+ return unexpectedSettle(log, { ...about(a), event: "claim-unread", reason: read.answer.reason });
443
+ }
444
+ if (performance.now() + WATCH_MS > a.waitUntil) {
445
+ if (current.transaction !== undefined)
446
+ return pending(current.transaction, a.network);
447
+ return unexpectedSettle(log, { ...about(a), event: "settle-deadline-passed", before: "claim-held", settleWaitMs });
448
+ }
449
+ await sleep(WATCH_MS);
450
+ let next;
451
+ try {
452
+ next = await inTime(record.read(a.network, a.key), a.deadline);
453
+ }
454
+ catch (e) {
455
+ log({ ...about(a), event: "store-call-failed", call: "read" }, e);
456
+ next = undefined;
457
+ }
458
+ if (next !== undefined)
459
+ current = next;
460
+ }
461
+ }
462
+ /**
463
+ * A claim the record holds that is not final. Where another settle holds it, this one watches. Otherwise it takes
464
+ * the claim, reads the chain, and submits the identical signed payment again only where the form's nonce is
465
+ * single-use, the read shows the value unconsumed and its validity open (`instrument-live`), the body is the one
466
+ * that claimed the row, and `/verify`'s checks pass for it again.
467
+ */
468
+ async function held(a, row) {
469
+ if (row.heldUntil > Date.now())
470
+ return watch(a, row);
471
+ let took;
472
+ try {
473
+ took = await inTime(record.retake(a.network, a.key, Date.now(), settleWaitMs), a.deadline);
474
+ }
475
+ catch (e) {
476
+ return unread(a, e, "retake");
477
+ }
478
+ if (took === undefined) {
479
+ const again = await inTime(record.read(a.network, a.key), a.deadline).catch(() => undefined);
480
+ return watch(a, again ?? { ...row, heldUntil: Date.now() + settleWaitMs });
481
+ }
482
+ const read = await readChain(a, took);
483
+ if (read.outcome === "final")
484
+ return byFinalRead(a, read, took.sent, took.payer, took.claimed);
485
+ const live = read.answer;
486
+ const search = live.state === "pending" && live.search !== undefined ? { search: live.search } : {};
487
+ if (live.state === "pending" && live.reason === "instrument-live" && resendable(a.instrumented)) {
488
+ if (took.body !== bodyOf(a.payment)) {
489
+ // Another body under the claimed instrument (a copy signed again): never sent in place of the one claimed.
490
+ await release(a, search);
491
+ return failed("invalid_transaction_state", took.transaction ?? "", a.network);
492
+ }
493
+ const v = await settling.verify(a.payment.payload, a.payment.requirements);
494
+ if (!v.isValid) {
495
+ await release(a, search);
496
+ return failed(settleReason(v.invalidReason ?? "invalid_payload"), "", a.network);
497
+ }
498
+ return submit(a, took.payer, took.sent, took.claimed, took.since);
499
+ }
500
+ await release(a, search);
501
+ if (live.state === "pending" && live.reason === "below-mark" && live.transaction !== undefined) {
502
+ return pending(live.transaction, a.network);
503
+ }
504
+ if (took.transaction !== undefined)
505
+ return pending(took.transaction, a.network);
506
+ return unexpectedSettle(log, { ...about(a), event: "claim-unread", reason: live.reason });
507
+ }
508
+ /**
509
+ * Whether a held claim may be sent again: only where the form's nonce is single-use, and never for an instrument
510
+ * named by the digest of its signed payment, which one settler submits once.
511
+ */
512
+ function resendable(i) {
513
+ return i.nonce === "single-use" && i.instrument.by !== "digest";
514
+ }
515
+ /** The transaction an instrument keyed by its transaction id names, which is known before it is sent. */
516
+ function known(i) {
517
+ return i.instrument.by === "transaction" ? i.instrument.transaction : undefined;
518
+ }
519
+ /**
520
+ * The answer where the record could not be read or written: the settler cannot know whether the payment was sent,
521
+ * so it is pending where its transaction is known before it is sent, and the settler's own failure otherwise.
522
+ */
523
+ function unread(a, e, call) {
524
+ const transaction = known(a.instrumented);
525
+ if (transaction !== undefined) {
526
+ log({ ...about(a), event: "store-call-failed", call }, e);
527
+ return pending(transaction, a.network);
528
+ }
529
+ return unexpectedSettle(log, { ...about(a), event: "store-call-failed", call }, e);
530
+ }
531
+ async function verify(body) {
532
+ const r = readShape(body);
533
+ if (typeof r === "string")
534
+ return invalid(r);
535
+ const network = r.paymentRequirements.network;
536
+ const kind = kindAt(r);
537
+ if (typeof kind === "string")
538
+ return invalid(kind);
539
+ const p = paymentOf(r);
540
+ try {
541
+ const m = route(kind.registration, p.payload, p.requirements);
542
+ if (m.descriptor.verifyForbidden === true)
543
+ return invalid("unsupported_scheme");
544
+ const i = await m.record.instrument(p);
545
+ if ("refused" in i)
546
+ return { isValid: false, invalidReason: i.refused, ...(i.message === undefined ? {} : { invalidMessage: i.message }) };
547
+ const landed = m.descriptor.verifiesLanded === true;
548
+ if (!landed) {
549
+ let row;
550
+ try {
551
+ row = await inTime(record.read(network, keyOf(i.instrument)), Infinity);
552
+ }
553
+ catch (e) {
554
+ return invalid(unexpectedVerify(log, { event: "store-call-failed", network, call: "read" }, e));
555
+ }
556
+ if (row !== undefined)
557
+ return invalid("invalid_transaction_state", row.payer);
558
+ }
559
+ const excluded = declared(kind, m, p, i, "verify");
560
+ if (excluded !== undefined)
561
+ return { isValid: false, invalidReason: excluded };
562
+ if (gated(m, p)) {
563
+ let spent;
564
+ try {
565
+ spent = await inTime(fees.spent(network, Date.now()), Infinity);
566
+ }
567
+ catch (e) {
568
+ return invalid(unexpectedVerify(log, { event: "store-call-failed", network, call: "fee" }, e));
569
+ }
570
+ if (spent)
571
+ return invalid("fee_budget_spent");
572
+ }
573
+ const v = await facilitator.verify(p.payload, p.requirements);
574
+ if (!v.isValid || landed)
575
+ return v;
576
+ let read;
577
+ try {
578
+ read = await m.record.read(p, { deadline: performance.now() + settleWaitMs });
579
+ }
580
+ catch (e) {
581
+ log({ event: "read-failed", network, ...(v.payer === undefined ? {} : { payer: v.payer }) }, e);
582
+ return v;
583
+ }
584
+ return read.outcome === "final" ? invalid("invalid_transaction_state", v.payer) : v;
585
+ }
586
+ catch (e) {
587
+ return invalid(unexpectedVerify(log, { event: "verify-error", network }, e));
588
+ }
589
+ }
590
+ async function settle(body) {
591
+ const deadline = performance.now() + settleWaitMs;
592
+ const r = readShape(body);
593
+ if (typeof r === "string")
594
+ return failed(r, "", networkOf(body));
595
+ const network = r.paymentRequirements.network;
596
+ const kind = kindAt(r);
597
+ if (typeof kind === "string")
598
+ return failed(kind, "", network);
599
+ const payment = paymentOf(r);
600
+ try {
601
+ const module = route(kind.registration, payment.payload, payment.requirements);
602
+ // The form's pure checks and the instrument, then the record, before anything reads the chain
603
+ // or the clock, a published class's checks among them.
604
+ const i = await module.record.instrument(payment);
605
+ if ("refused" in i)
606
+ return { ...failed(i.refused, "", network), ...(i.message === undefined ? {} : { errorMessage: i.message }) };
607
+ const a = {
608
+ network,
609
+ key: keyOf(i.instrument),
610
+ kind,
611
+ module,
612
+ payment,
613
+ instrumented: i,
614
+ deadline,
615
+ waitUntil: deadline - answerReserve(settleWaitMs),
616
+ };
617
+ let row;
618
+ try {
619
+ row = await inTime(record.read(network, a.key), deadline);
620
+ }
621
+ catch (e) {
622
+ return unread(a, e, "read");
623
+ }
624
+ if (row?.final === true)
625
+ return answerFinal(a, row);
626
+ // What the kind declares.
627
+ const excluded = declared(kind, module, payment, i, "settle");
628
+ if (excluded !== undefined)
629
+ return failed(excluded, "", network);
630
+ if (row !== undefined)
631
+ return held(a, row);
632
+ // The checks of /verify; where they refuse, the chain's read of the instrument. Only what the chain shows of
633
+ // the signer's value is final here, never a lapse, which the read takes from the payload's own validity, and
634
+ // the payload is not one the checks passed.
635
+ const v = await settling.verify(payment.payload, payment.requirements);
636
+ if (!v.isValid) {
637
+ const read = await readChain(a, {});
638
+ const lapsed = read.answer.state === "failed" && read.answer.reason === "instrument-unused";
639
+ if (read.outcome === "final" && !lapsed)
640
+ return byFinalRead(a, read, [], v.payer, undefined);
641
+ return failed(settleReason(v.invalidReason ?? "invalid_payload"), "", network);
642
+ }
643
+ // The claim, with the chain's position the module reads for it, where its read searches from one.
644
+ let since;
645
+ if (module.record.position !== undefined && a.waitUntil - performance.now() > 0) {
646
+ try {
647
+ since = await module.record.position(payment, { deadline: a.waitUntil });
648
+ }
649
+ catch (e) {
650
+ log({ ...about(a, { ...(v.payer === undefined ? {} : { payer: v.payer }) }), event: "position-unread" }, e);
651
+ }
652
+ }
653
+ const claimed = Date.now();
654
+ const transaction = known(i);
655
+ let won;
656
+ try {
657
+ won = await inTime(record.claim(network, a.key, {
658
+ pairing: i.pairing,
659
+ ...(v.payer === undefined ? {} : { payer: v.payer }),
660
+ ...(transaction === undefined ? {} : { transaction }),
661
+ body: bodyOf(payment),
662
+ ...(since === undefined ? {} : { since }),
663
+ now: claimed,
664
+ holdMs: settleWaitMs,
665
+ }), deadline);
666
+ }
667
+ catch (e) {
668
+ return unread(a, e, "claim");
669
+ }
670
+ if (!won) {
671
+ const now = await inTime(record.read(network, a.key), deadline).catch(() => undefined);
672
+ return watch(a, now ?? { pairing: i.pairing, claimed, heldUntil: claimed + settleWaitMs, final: false, sent: [] });
673
+ }
674
+ // The fee budget, the submission and the answer.
675
+ return await submit(a, v.payer, transaction === undefined ? [] : [transaction], claimed, since);
676
+ }
677
+ catch (e) {
678
+ return unexpectedSettle(log, { event: "settle-error", network }, e);
679
+ }
680
+ }
681
+ /** Answers before the body is read, and closes the connection, so that nothing more of the body is read. */
682
+ function refuseUnread(req, res, status, body, headers = {}) {
683
+ res.setHeader("connection", "close");
684
+ for (const [k, v] of Object.entries(headers))
685
+ res.setHeader(k, v);
686
+ sendJson(res, status, body);
687
+ req.destroy();
688
+ }
689
+ async function handle(req, res) {
690
+ if (credential !== undefined && !presents(req, credential)) {
691
+ return refuseUnread(req, res, 401, { error: "unauthorized" }, { "www-authenticate": "Bearer" });
692
+ }
693
+ const path = (req.url ?? "").split("?")[0];
694
+ if (path === "/supported") {
695
+ if (req.method !== "GET")
696
+ return sendJson(res, 405, { error: "method not allowed" });
697
+ return sendJson(res, 200, supported());
698
+ }
699
+ if (path !== "/verify" && path !== "/settle")
700
+ return sendJson(res, 404, { error: "not found" });
701
+ if (req.method !== "POST")
702
+ return sendJson(res, 405, { error: "method not allowed" });
703
+ const read = await readRequestJson(req, X402_REQUEST_MAX_BYTES);
704
+ if (read !== undefined && "tooLarge" in read) {
705
+ return refuseUnread(req, res, 413, { error: `the body is larger than ${X402_REQUEST_MAX_BYTES} bytes` });
706
+ }
707
+ if (read !== undefined && "left" in read) {
708
+ // The client left before its body was complete: there is no one to answer, and nothing failed here to log.
709
+ res.destroy();
710
+ return;
711
+ }
712
+ if (path === "/verify") {
713
+ if (read === undefined)
714
+ return sendJson(res, 400, { isValid: false, invalidReason: "invalid_payload" });
715
+ return sendJson(res, 200, await verify(read.json));
716
+ }
717
+ if (read === undefined)
718
+ return sendJson(res, 400, failed("invalid_payload", "", ""));
719
+ return sendJson(res, 200, await settle(read.json));
720
+ }
721
+ const server = createServer((req, res) => {
722
+ handle(req, res).catch((e) => {
723
+ log({ event: "request-error", path: (req.url ?? "").split("?")[0] }, e);
724
+ if (!res.headersSent)
725
+ sendJson(res, 500, { error: "internal error" });
726
+ else
727
+ res.destroy();
728
+ });
729
+ });
730
+ server.requestTimeout = settleWaitMs + 60_000;
731
+ await new Promise((resolve, reject) => {
732
+ server.once("error", reject);
733
+ server.listen(port, host, () => {
734
+ server.off("error", reject);
735
+ resolve();
736
+ });
737
+ });
738
+ return {
739
+ async close() {
740
+ await new Promise((resolve) => {
741
+ server.close(() => resolve());
742
+ server.closeAllConnections();
743
+ });
744
+ for (const close of closers.reverse())
745
+ await close();
746
+ stopSweep();
747
+ await pool.end();
748
+ },
749
+ };
750
+ }
751
+ catch (e) {
752
+ for (const close of closers.reverse())
753
+ await close().catch(() => { });
754
+ stopSweep();
755
+ await pool.end();
756
+ throw e;
757
+ }
758
+ }