@useopentab/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1398 @@
1
+ import "./chunk-EKJH2AJS.js";
2
+ import "./chunk-4R3NAR3C.js";
3
+ import {
4
+ KeyFileAccountSigner,
5
+ KeydClient,
6
+ TAB_AUTH_HEADER,
7
+ encodeTabAuthHeader,
8
+ encodeTabStatusRequestV1
9
+ } from "./chunk-IRXOU25X.js";
10
+ import "./chunk-HZHOKJIM.js";
11
+ import "./chunk-S5IAH7CT.js";
12
+ import {
13
+ CliError
14
+ } from "./chunk-MOZ4BFSB.js";
15
+ import {
16
+ BUREAU_CONTRACT_NAME,
17
+ CloseAckV1Codec,
18
+ MAX_LANES,
19
+ ReceiptV1Codec,
20
+ TESTNET_GENESIS_HEX,
21
+ TabAgreementV1Codec,
22
+ U64_MAX,
23
+ VoucherV1Codec,
24
+ bureauErrorName,
25
+ bytesEqual,
26
+ caip2FromGenesis,
27
+ closeAckFor,
28
+ contractAddressEqual,
29
+ decodeLineOfResult,
30
+ decodeReceiptV1,
31
+ decodeTabOfResult,
32
+ decodeVoucherV1,
33
+ ed25519Verify,
34
+ encodeCloseAckV1,
35
+ encodeCloseVoucherV1,
36
+ encodeLineOfParams,
37
+ encodeSettleTabParams,
38
+ encodeTabOfParams,
39
+ encodeVoucherV1,
40
+ fromHex,
41
+ isAccountAddress,
42
+ receiptHash,
43
+ requestHash,
44
+ responseHash,
45
+ sha256,
46
+ toHex,
47
+ zeroHash
48
+ } from "./chunk-D3C7KAMJ.js";
49
+
50
+ // packages/client/src/errors.ts
51
+ var ClientError = class extends Error {
52
+ name = "ClientError";
53
+ code;
54
+ /** HTTP status of the remote answer that caused it, when there was one. */
55
+ status;
56
+ details;
57
+ constructor(code, message, opts = {}) {
58
+ super(message, opts.cause === void 0 ? void 0 : { cause: opts.cause });
59
+ this.code = code;
60
+ this.status = opts.status ?? null;
61
+ this.details = opts.details ?? {};
62
+ }
63
+ };
64
+
65
+ // packages/client/src/wire.ts
66
+ import { z } from "zod";
67
+ var PAYMENT_SIGNATURE_HEADER = "PAYMENT-SIGNATURE";
68
+ var PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE";
69
+ var BATCH_SETTLEMENT_SCHEME = "batch-settlement";
70
+ var CCD_TAB_BINDING = "ccd-tab/v1";
71
+ var MAX_HEADER_CHARS = 8192;
72
+ var MAX_CONTROL_BODY_BYTES = 64 * 1024;
73
+ var U64_RE = /^(0|[1-9][0-9]{0,19})$/;
74
+ var U64_MAX2 = (1n << 64n) - 1n;
75
+ var u64 = z.string().regex(U64_RE, "a u64 decimal string").transform((s) => BigInt(s)).refine((v) => v <= U64_MAX2, "out of u64 range");
76
+ function hexOf(bytes) {
77
+ return z.string().regex(new RegExp(`^[0-9a-f]{${bytes * 2}}$`), `${bytes} bytes of lowercase hex`);
78
+ }
79
+ var RECEIPT_HEX = hexOf(ReceiptV1Codec.size ?? 0);
80
+ var SIG_HEX = hexOf(64);
81
+ function issues(e) {
82
+ return e.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
83
+ }
84
+ function base64Json(value, what) {
85
+ const trimmed = value.trim();
86
+ if (trimmed.length === 0 || trimmed.length > MAX_HEADER_CHARS || trimmed.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(trimmed)) {
87
+ throw new ClientError("malformed_response", `${what} is not bounded base64`);
88
+ }
89
+ try {
90
+ return JSON.parse(Buffer.from(trimmed, "base64").toString("utf8"));
91
+ } catch {
92
+ throw new ClientError("malformed_response", `${what} is not base64 JSON`);
93
+ }
94
+ }
95
+ function encodePaymentSignature(network, tabId, lane, voucher, sig) {
96
+ const json = {
97
+ x402Version: 2,
98
+ scheme: BATCH_SETTLEMENT_SCHEME,
99
+ network,
100
+ payload: { tabId: tabId.toString(), lane, voucher: toHex(voucher), sig: toHex(sig) }
101
+ };
102
+ return Buffer.from(JSON.stringify(json), "utf8").toString("base64");
103
+ }
104
+ var paymentResponseSchema = z.object({ commitmentId: hexOf(32), charged: u64, receipt: RECEIPT_HEX, sig: SIG_HEX }).strict();
105
+ function parsePaymentResponse(value) {
106
+ const parsed = paymentResponseSchema.safeParse(base64Json(value, PAYMENT_RESPONSE_HEADER));
107
+ if (!parsed.success) throw new ClientError("malformed_response", `PAYMENT-RESPONSE: ${issues(parsed.error)}`);
108
+ const p = parsed.data;
109
+ return { commitmentId: fromHex(p.commitmentId), charged: p.charged, receipt: fromHex(p.receipt), sig: fromHex(p.sig) };
110
+ }
111
+ var laneReceiptSchema = z.object({
112
+ lane: z.number().int().min(0).max(MAX_LANES - 1),
113
+ seq: u64,
114
+ receipt: RECEIPT_HEX,
115
+ sig: SIG_HEX,
116
+ voucher: hexOf(VoucherV1Codec.size ?? 0).optional(),
117
+ voucherSig: SIG_HEX.optional()
118
+ }).strict();
119
+ function parseLaneSnapshot(body) {
120
+ const parsed = z.object({ lanes: z.array(laneReceiptSchema).max(MAX_LANES) }).loose().safeParse(body);
121
+ if (!parsed.success) throw new ClientError("malformed_response", `lane snapshot: ${issues(parsed.error)}`);
122
+ return parsed.data.lanes.map((l) => ({
123
+ lane: l.lane,
124
+ seq: l.seq,
125
+ receipt: fromHex(l.receipt),
126
+ sig: fromHex(l.sig),
127
+ ...l.voucher === void 0 || l.voucherSig === void 0 ? {} : { voucher: fromHex(l.voucher), voucherSig: fromHex(l.voucherSig) }
128
+ }));
129
+ }
130
+ var closeAckSchema = z.object({ ack: hexOf(CloseAckV1Codec.size ?? 0), sig: SIG_HEX }).strict();
131
+ function parseCloseAck(body) {
132
+ const parsed = closeAckSchema.safeParse(body);
133
+ if (!parsed.success) throw new ClientError("malformed_response", `close ack: ${issues(parsed.error)}`);
134
+ return { ack: fromHex(parsed.data.ack), sig: fromHex(parsed.data.sig) };
135
+ }
136
+ function errorCodeOf(body) {
137
+ const parsed = z.object({ error: z.string().max(128), message: z.string().max(4096).optional() }).loose().safeParse(body);
138
+ return parsed.success ? { error: parsed.data.error, message: parsed.data.message ?? "" } : null;
139
+ }
140
+ var acceptSchema = z.object({
141
+ scheme: z.string().max(64),
142
+ network: z.string().max(128),
143
+ amount: z.string().max(40).optional(),
144
+ asset: z.string().max(256).optional(),
145
+ payTo: z.string().max(128).optional(),
146
+ extra: z.record(z.string().max(64), z.unknown()).optional()
147
+ }).loose();
148
+ var paymentRequiredSchema = z.object({ x402Version: z.literal(2), error: z.string().max(256).optional(), accepts: z.array(acceptSchema).max(16) }).loose();
149
+ var batchExtraSchema = z.object({
150
+ binding: z.literal(CCD_TAB_BINDING),
151
+ bureau: z.object({ index: u64, subindex: u64 }).strict(),
152
+ sellerToken: u64,
153
+ termsUrl: z.string().max(2048),
154
+ maxPricePerCall: u64
155
+ }).loose();
156
+ async function readBody(res, limit) {
157
+ if (res.body === null) return new Uint8Array();
158
+ const reader = res.body.getReader();
159
+ const chunks = [];
160
+ let total = 0;
161
+ for (; ; ) {
162
+ const { done, value } = await reader.read();
163
+ if (done) break;
164
+ total += value.byteLength;
165
+ if (total > limit) {
166
+ await reader.cancel().catch(() => void 0);
167
+ return null;
168
+ }
169
+ chunks.push(value);
170
+ }
171
+ const out = new Uint8Array(total);
172
+ let offset = 0;
173
+ for (const c of chunks) {
174
+ out.set(c, offset);
175
+ offset += c.byteLength;
176
+ }
177
+ return out;
178
+ }
179
+ async function readJson(res) {
180
+ const bytes = await readBody(res, MAX_CONTROL_BODY_BYTES);
181
+ if (bytes === null) throw new ClientError("malformed_response", `the ${res.status} body exceeds ${MAX_CONTROL_BODY_BYTES} bytes`);
182
+ try {
183
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
184
+ } catch {
185
+ return null;
186
+ }
187
+ }
188
+
189
+ // packages/client/src/receipts.ts
190
+ var STRICT = { strict: true };
191
+ function signedByAny(sig, message, keys) {
192
+ return keys.some((k) => ed25519Verify(sig, message, k, STRICT));
193
+ }
194
+ function fail(field) {
195
+ throw new ClientError("bad_receipt", `the receipt does not match the voucher (${field})`, { details: { field } });
196
+ }
197
+ function verifyReceipt(c) {
198
+ let r;
199
+ try {
200
+ r = decodeReceiptV1(c.receipt);
201
+ } catch (e) {
202
+ throw new ClientError("bad_receipt", `not a ReceiptV1: ${e.message}`);
203
+ }
204
+ const v = c.voucher;
205
+ if (!bytesEqual(r.genesis, v.genesis) || !contractAddressEqual(r.bureau, v.bureau)) fail("domain");
206
+ if (r.tabId !== v.tabId || r.lane !== v.lane || r.seq !== v.seq) fail("position");
207
+ if (!bytesEqual(r.voucherHash, c.commitmentId)) fail("voucher_hash");
208
+ if (r.charged > v.maxPrice) fail("charged");
209
+ if (r.chargedCumulative !== v.ackedCumulative + r.charged) fail("charged_cumulative");
210
+ if (c.body !== void 0 && !bytesEqual(r.responseHash, responseHash(c.body))) fail("response_hash");
211
+ if (!signedByAny(c.sig, c.receipt, c.sellerKeys)) {
212
+ throw new ClientError("bad_receipt", "the receipt is not signed by the tab's seller key");
213
+ }
214
+ return r;
215
+ }
216
+ function verifySnapshotReceipt(scope, lane, receipt, sig) {
217
+ let r;
218
+ try {
219
+ r = decodeReceiptV1(receipt);
220
+ } catch (e) {
221
+ throw new ClientError("bad_receipt", `not a ReceiptV1: ${e.message}`);
222
+ }
223
+ if (!bytesEqual(r.genesis, scope.genesis) || !contractAddressEqual(r.bureau, scope.bureau)) fail("domain");
224
+ if (r.tabId !== scope.tabId || r.lane !== lane || lane >= scope.maxLanes || r.seq < 1n) fail("position");
225
+ if (r.chargedCumulative < r.charged) fail("charged_cumulative");
226
+ if (!signedByAny(sig, receipt, scope.sellerKeys)) throw new ClientError("bad_receipt", "the receipt is not signed by the tab's seller key");
227
+ return r;
228
+ }
229
+ function snapshotVoucherTime(r, voucher, sig, buyerKey) {
230
+ if (voucher === void 0 || sig === void 0) return null;
231
+ let v;
232
+ try {
233
+ v = decodeVoucherV1(voucher);
234
+ } catch {
235
+ return null;
236
+ }
237
+ const ok = bytesEqual(sha256(voucher), r.voucherHash) && v.tabId === r.tabId && v.lane === r.lane && v.seq === r.seq && ed25519Verify(sig, voucher, buyerKey, STRICT);
238
+ return ok ? v.issuedAt : null;
239
+ }
240
+ function verifyCloseAck(close, ack, sig, sellerKeys) {
241
+ if (!bytesEqual(ack, encodeCloseAckV1(closeAckFor(close)))) {
242
+ throw new ClientError("bad_ack", "the close ack is not the ack of this close");
243
+ }
244
+ if (!signedByAny(sig, ack, sellerKeys)) throw new ClientError("bad_ack", "the close ack is not signed by the tab's seller key");
245
+ }
246
+
247
+ // packages/client/src/lanes.ts
248
+ var FRESH_LANE = Object.freeze({
249
+ seq: 0n,
250
+ cumulative: 0n,
251
+ receiptHash: zeroHash(),
252
+ issuedAt: 0n,
253
+ voucherIssuedAt: null,
254
+ last: null
255
+ });
256
+ function headOf(receipt, sig, voucherIssuedAt = null) {
257
+ return {
258
+ seq: receipt.seq,
259
+ cumulative: receipt.chargedCumulative,
260
+ receiptHash: receiptHash(receipt),
261
+ issuedAt: receipt.issuedAt,
262
+ voucherIssuedAt,
263
+ last: { receipt, sig: Uint8Array.from(sig) }
264
+ };
265
+ }
266
+ var Lanes = class {
267
+ count;
268
+ #heads;
269
+ #free;
270
+ /** Lanes that cannot be used until resynced from a seller receipt. */
271
+ #blocked = /* @__PURE__ */ new Set();
272
+ #waiters = [];
273
+ constructor(count) {
274
+ if (!Number.isInteger(count) || count < 1) throw new RangeError("a tab has at least one lane");
275
+ this.count = count;
276
+ this.#heads = Array.from({ length: count }, () => FRESH_LANE);
277
+ this.#free = Array.from({ length: count }, (_, i) => i);
278
+ }
279
+ head(lane) {
280
+ const h = this.#heads[lane];
281
+ if (h === void 0) throw new RangeError(`lane ${lane} is out of range`);
282
+ return h;
283
+ }
284
+ heads() {
285
+ return [...this.#heads];
286
+ }
287
+ /** Moves a lane to a verified receipt (never back) and unblocks it. */
288
+ advance(lane, head) {
289
+ if (head.seq >= this.head(lane).seq) this.#heads[lane] = head;
290
+ this.#blocked.delete(lane);
291
+ }
292
+ /** Sets a lane to the seller's signed snapshot (a corrective resync may move it back) and unblocks it. */
293
+ reset(lane, head) {
294
+ this.head(lane);
295
+ this.#heads[lane] = head;
296
+ this.#blocked.delete(lane);
297
+ }
298
+ /** Marks a lane unusable until a receipt resyncs it (keyd holds a voucher the seller never saw). */
299
+ block(lane) {
300
+ this.head(lane);
301
+ this.#blocked.add(lane);
302
+ if (this.usable() === 0) {
303
+ for (const w of this.#waiters.splice(0)) w.reject(noLane());
304
+ }
305
+ }
306
+ /** Makes a blocked lane usable again without moving it (keyd can sign its next voucher). */
307
+ unblock(lane) {
308
+ this.head(lane);
309
+ this.#blocked.delete(lane);
310
+ }
311
+ isBlocked(lane) {
312
+ return this.#blocked.has(lane);
313
+ }
314
+ /** Number of lanes not blocked. */
315
+ usable() {
316
+ return this.count - this.#blocked.size;
317
+ }
318
+ /** Waits for a free, usable lane. */
319
+ acquire() {
320
+ if (this.usable() === 0) return Promise.reject(noLane());
321
+ let best = -1;
322
+ for (const [i, l] of this.#free.entries()) {
323
+ if (!this.#blocked.has(l) && (best < 0 || l < this.#free[best])) best = i;
324
+ }
325
+ if (best >= 0) return Promise.resolve(this.#free.splice(best, 1)[0]);
326
+ return new Promise((resolve, reject) => this.#waiters.push({ resolve, reject }));
327
+ }
328
+ /** Returns a lane to the pool, handing it to the next waiter when it is usable. */
329
+ release(lane) {
330
+ if (!this.#blocked.has(lane)) {
331
+ const next = this.#waiters.shift();
332
+ if (next !== void 0) {
333
+ next.resolve(lane);
334
+ return;
335
+ }
336
+ }
337
+ this.#free.push(lane);
338
+ }
339
+ };
340
+ function noLane() {
341
+ return new ClientError("no_usable_lane", "every lane of the tab waits for a resync from the seller");
342
+ }
343
+
344
+ // packages/client/src/tx.ts
345
+ import {
346
+ AccountAddress,
347
+ AccountTransactionV1,
348
+ CcdAmount,
349
+ ContractAddress as SdkContractAddress,
350
+ Energy,
351
+ Parameter,
352
+ ReceiveName,
353
+ SequenceNumber,
354
+ Transaction,
355
+ TransactionExpiry
356
+ } from "@concordium/web-sdk";
357
+ function arrayBuffer(bytes) {
358
+ const copy = new Uint8Array(bytes.length);
359
+ copy.set(bytes);
360
+ return copy.buffer;
361
+ }
362
+ async function signSponsoredUpdate(u) {
363
+ const signable = Transaction.updateContract(
364
+ {
365
+ amount: CcdAmount.fromMicroCcd(u.amount),
366
+ address: SdkContractAddress.create(u.bureau.index, u.bureau.subindex),
367
+ receiveName: ReceiveName.fromString(`${BUREAU_CONTRACT_NAME}.${u.entrypoint}`),
368
+ message: Parameter.fromBuffer(arrayBuffer(u.parameter))
369
+ },
370
+ Energy.create(u.executionEnergy)
371
+ ).addMetadata({
372
+ sender: AccountAddress.fromBase58(u.sender.address),
373
+ nonce: SequenceNumber.create(u.nonce),
374
+ expiry: TransactionExpiry.fromEpochSeconds(u.expiry)
375
+ }).addSponsor(AccountAddress.fromBase58(u.sponsor)).build();
376
+ const signature = await u.sender.signAsSender(signable);
377
+ const finalized = Transaction.finalize(Transaction.addSignature(signable, signature));
378
+ return toHex(AccountTransactionV1.serialize(finalized));
379
+ }
380
+ function sponsoredRequestKey(transactionHex) {
381
+ const tx = AccountTransactionV1.deserialize(arrayBuffer(fromHex(transactionHex)));
382
+ return toHex(sha256(AccountTransactionV1.serializeBlockItem(tx)));
383
+ }
384
+ function energyWithMargin(used, marginPct) {
385
+ const pct = BigInt(100 + marginPct);
386
+ return (used * pct + 99n) / 100n;
387
+ }
388
+
389
+ // packages/client/src/sponsored.ts
390
+ var UNRESOLVED_CODES = /* @__PURE__ */ new Set(["submitted_unconfirmed", "facilitator_unreachable"]);
391
+ var EXPIRY_MARGIN_SECONDS = 30n;
392
+ var MAX_UNANSWERED = 64;
393
+ function lostAnswer(e) {
394
+ return e.code === "facilitator_unreachable" || e.code === "facilitator_error" && e.status !== null && e.status >= 502 && e.status <= 504;
395
+ }
396
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
397
+ var SponsoredSender = class {
398
+ #o;
399
+ #tails = /* @__PURE__ */ new Map();
400
+ #unanswered = /* @__PURE__ */ new Map();
401
+ #info;
402
+ constructor(opts) {
403
+ this.#o = opts;
404
+ }
405
+ /** The facilitator's `/supported` answer (cached; a failure is retried next time). */
406
+ info() {
407
+ this.#info ??= this.#o.facilitator.supported().then((info) => {
408
+ const b = this.#o.bureau;
409
+ if (info.bureau.index !== b.index || info.bureau.subindex !== b.subindex) {
410
+ throw new ClientError("wrong_facilitator", "the facilitator sponsors another bureau instance");
411
+ }
412
+ return info;
413
+ }).catch((e) => {
414
+ this.#info = void 0;
415
+ throw e;
416
+ });
417
+ return this.#info;
418
+ }
419
+ /** `POST /sponsor/submit` of an `openTab` or `closeTab` sent by `wallet`. */
420
+ submit(wallet, entrypoint, parameter) {
421
+ return this.#serial(wallet.address, () => this.#send(wallet, entrypoint, parameter, 0n, (hex2) => this.#o.facilitator.submit(hex2)));
422
+ }
423
+ /** `POST /redeem` of a `settleTab` attaching `amount`, sent by `wallet`. */
424
+ redeem(wallet, tabId, parameter, amount) {
425
+ const post = (hex2) => this.#o.facilitator.redeem(tabId, hex2);
426
+ return this.#serial(wallet.address, () => this.#send(wallet, "settleTab", parameter, amount, post, (tx) => this.#remember(tx, post)));
427
+ }
428
+ /**
429
+ * Sends a redemption whose outcome was left open (`submitted_unconfirmed` or
430
+ * `facilitator_unreachable` with `details.requestKey`) again: the same signed transaction, in its
431
+ * payer's queue, reconciled as the first time. Throws `unknown_request` when this sender holds no
432
+ * such request (it was answered since, or this is another process).
433
+ */
434
+ resendRedeem(requestKey) {
435
+ const held = this.#unanswered.get(requestKey);
436
+ if (held === void 0) return Promise.reject(new ClientError("unknown_request", `no unanswered redemption ${requestKey} is held here`));
437
+ return this.#serial(held.tx.sender, async () => {
438
+ try {
439
+ const result = await this.#deliver(held.tx, held.post);
440
+ this.#unanswered.delete(requestKey);
441
+ return result;
442
+ } catch (e) {
443
+ if (!(e instanceof ClientError && UNRESOLVED_CODES.has(e.code))) this.#unanswered.delete(requestKey);
444
+ throw e;
445
+ }
446
+ });
447
+ }
448
+ /**
449
+ * Runs `task` in `payer`'s queue, after its earlier sponsored updates and before later ones (x402
450
+ * exact payments use this: they spend the same wallet nonce).
451
+ */
452
+ exclusive(payer, task) {
453
+ return this.#serial(payer, task);
454
+ }
455
+ async #send(wallet, entrypoint, parameter, amount, post, unresolved) {
456
+ const { chain, now } = this.#o;
457
+ const { sponsor } = await this.info();
458
+ const maxRebuilds = this.#o.maxRebuilds ?? 3;
459
+ for (let build = 0; ; build++) {
460
+ const nonce = await chain.nextNonce(wallet.address);
461
+ const used = await chain.dryRun({ invoker: wallet.address, entrypoint, parameter, amount });
462
+ const expiry = BigInt(Math.floor(now() / 1e3) + (this.#o.expirySeconds ?? 300));
463
+ const hex2 = await signSponsoredUpdate({
464
+ sender: wallet,
465
+ sponsor,
466
+ bureau: this.#o.bureau,
467
+ entrypoint,
468
+ parameter,
469
+ amount,
470
+ executionEnergy: energyWithMargin(used, this.#o.energyMarginPct ?? 20),
471
+ nonce,
472
+ expiry
473
+ });
474
+ const tx = { hex: hex2, requestKey: sponsoredRequestKey(hex2), sender: wallet.address, nonce, expiry };
475
+ try {
476
+ return await this.#deliver(tx, post);
477
+ } catch (e) {
478
+ if (!(e instanceof ClientError)) throw e;
479
+ if (e.code === "nonce_mismatch" && build < maxRebuilds) continue;
480
+ if (UNRESOLVED_CODES.has(e.code)) unresolved?.(tx);
481
+ throw e;
482
+ }
483
+ }
484
+ }
485
+ /**
486
+ * Posts one signed transaction until it has an answer: resends it after `finalization_timeout`,
487
+ * and reconciles a lost answer (see the module comment).
488
+ */
489
+ async #deliver(tx, post) {
490
+ const maxResends = this.#o.maxResends ?? 5;
491
+ const attempts = this.#o.reconcile?.attempts ?? 10;
492
+ const maxDelay = this.#o.reconcile?.maxDelayMs ?? 15e3;
493
+ let delay = this.#o.reconcile?.delayMs ?? 1e3;
494
+ const budget = this.#o.reconcile?.budgetMs ?? 18e4;
495
+ const sleep = this.#o.sleep ?? defaultSleep;
496
+ let resends = 0;
497
+ let lost = 0;
498
+ let lostSince = null;
499
+ for (; ; ) {
500
+ try {
501
+ return await post(tx.hex);
502
+ } catch (e) {
503
+ if (!(e instanceof ClientError)) throw e;
504
+ if (e.code === "finalization_timeout" && resends < maxResends) {
505
+ resends++;
506
+ continue;
507
+ }
508
+ if (!lostAnswer(e)) throw e;
509
+ const chain = await this.#chainState(tx);
510
+ lostSince ??= performance.now();
511
+ const outOfTime = performance.now() + delay - lostSince > budget;
512
+ if (chain === "expired" || lost >= attempts || outOfTime) throw this.#outcome(tx, chain, lost, e);
513
+ lost++;
514
+ await sleep(delay);
515
+ delay = Math.min(delay * 2, maxDelay);
516
+ }
517
+ }
518
+ }
519
+ /** What the chain says of the transaction's nonce. */
520
+ async #chainState(tx) {
521
+ let next;
522
+ try {
523
+ next = await this.#o.chain.nextNonce(tx.sender);
524
+ } catch {
525
+ return "unknown";
526
+ }
527
+ if (next > tx.nonce) return "used";
528
+ return BigInt(Math.floor(this.#o.now() / 1e3)) > tx.expiry + EXPIRY_MARGIN_SECONDS ? "expired" : "unused";
529
+ }
530
+ /** The error that reports a lost answer's outcome, as far as the chain can tell it. */
531
+ #outcome(tx, chain, resent, cause) {
532
+ const details = {
533
+ requestKey: tx.requestKey,
534
+ sender: tx.sender,
535
+ nonce: tx.nonce.toString(),
536
+ expiry: tx.expiry.toString(),
537
+ chain,
538
+ resent
539
+ };
540
+ if (chain === "expired") {
541
+ return new ClientError(
542
+ "not_submitted",
543
+ `the facilitator did not answer, and the transaction never reached the chain: nonce ${tx.nonce} is unused and the transaction expired; nothing was sent, a new request is safe`,
544
+ { details, cause }
545
+ );
546
+ }
547
+ if (chain === "used") {
548
+ return new ClientError(
549
+ "submitted_unconfirmed",
550
+ `the facilitator did not answer after ${resent} resends, but nonce ${tx.nonce} of the wallet is used on chain (this sender sends one transaction per wallet at a time, so it is this one): send the same request again for its hash and outcome`,
551
+ { details, cause }
552
+ );
553
+ }
554
+ return new ClientError(
555
+ "facilitator_unreachable",
556
+ `the facilitator did not answer after ${resent} resends; the transaction is not on chain${chain === "unknown" ? " as far as the chain could be read" : ""} and stays valid until ${tx.expiry}: send the same request again`,
557
+ { ...cause.status === null ? {} : { status: cause.status }, details, cause }
558
+ );
559
+ }
560
+ #remember(tx, post) {
561
+ this.#unanswered.delete(tx.requestKey);
562
+ this.#unanswered.set(tx.requestKey, { tx, post });
563
+ while (this.#unanswered.size > MAX_UNANSWERED) {
564
+ const oldest = this.#unanswered.keys().next().value;
565
+ if (oldest === void 0) break;
566
+ this.#unanswered.delete(oldest);
567
+ }
568
+ }
569
+ /** Runs `task` after every earlier task of the same payer has finished. */
570
+ #serial(payer, task) {
571
+ const previous = this.#tails.get(payer) ?? Promise.resolve();
572
+ const run = previous.then(task, task);
573
+ const tail = run.then(
574
+ () => void 0,
575
+ () => void 0
576
+ );
577
+ this.#tails.set(payer, tail);
578
+ void tail.then(() => {
579
+ if (this.#tails.get(payer) === tail) this.#tails.delete(payer);
580
+ });
581
+ return run;
582
+ }
583
+ };
584
+
585
+ // packages/client/src/tab.ts
586
+ var SETTLE_ANEW = /* @__PURE__ */ new Set(["not_submitted", "unknown_request", "nonce_mismatch", "transaction_expired"]);
587
+ function tabPath(tabId, suffix = "") {
588
+ return `/tab/${tabId}${suffix}`;
589
+ }
590
+ var Tab = class {
591
+ tabId;
592
+ #d;
593
+ #lanes;
594
+ #sellerKeys;
595
+ #view;
596
+ #calls = 0;
597
+ /** Calls in flight: id → when they started (ms). */
598
+ #active = /* @__PURE__ */ new Map();
599
+ #nextCall = 0;
600
+ /** Woken whenever a call ends. */
601
+ #ended = [];
602
+ /** Set while a `current` settlement holds new calls. */
603
+ #hold = null;
604
+ /** Settlements run one at a time. */
605
+ #settleQueue = Promise.resolve();
606
+ /** A redemption whose outcome is still open; the next settle() sends it again first. */
607
+ #unanswered = null;
608
+ /**
609
+ * Per lane, the last receipt of its previous cycle segment and the cycle of the voucher after
610
+ * it: the lane's last receipt of every cycle before `before` (from the receipt's own cycle on).
611
+ */
612
+ #boundaries = /* @__PURE__ */ new Map();
613
+ #buyerKey = null;
614
+ /** The issued_at of the last voucher signed per lane: each voucher gets a later one, so no two are alike. */
615
+ #lastIssued = /* @__PURE__ */ new Map();
616
+ constructor(deps) {
617
+ this.#d = deps;
618
+ this.tabId = deps.tabId;
619
+ this.#view = deps.view;
620
+ this.#lanes = new Lanes(deps.view.maxLanes);
621
+ this.#sellerKeys = [Uint8Array.from(deps.view.sellerKey)];
622
+ }
623
+ /** The tab as last read from the chain. */
624
+ get view() {
625
+ return this.#view;
626
+ }
627
+ /**
628
+ * A fetch that pays with the tab. Requests must go to the seller's origin. Returns the seller's
629
+ * answer: a paid response (its receipt verified), or the seller's refusal (402, 403, ...).
630
+ */
631
+ fetch = async (input, init) => {
632
+ const req = new Request(input, init);
633
+ const url = new URL(req.url);
634
+ if (url.origin !== this.#d.origin) throw new ClientError("wrong_origin", `tab ${this.tabId} pays ${this.#d.origin}, not ${url.origin}`);
635
+ const body = new Uint8Array(await req.arrayBuffer());
636
+ const call = await this.#enter();
637
+ let lane;
638
+ try {
639
+ lane = await this.#lanes.acquire();
640
+ for (let attempt = 0; ; attempt++) {
641
+ const out = await this.#callOnLane(lane, req, url, body, attempt > 0);
642
+ if (out.kind === "done") return out.response;
643
+ }
644
+ } finally {
645
+ if (lane !== void 0) this.#lanes.release(lane);
646
+ this.#leave(call);
647
+ }
648
+ };
649
+ /** One voucher on `lane`. `last` stops a second corrective retry. */
650
+ async #callOnLane(lane, req, url, body, last) {
651
+ const d = this.#d;
652
+ const head = this.#lanes.head(lane);
653
+ const previous = this.#lastIssued.get(lane);
654
+ let issuedAt = BigInt(d.now());
655
+ if (previous !== void 0 && issuedAt <= previous) issuedAt = previous + 1n;
656
+ this.#lastIssued.set(lane, issuedAt);
657
+ const voucher = {
658
+ genesis: d.genesis,
659
+ bureau: d.bureau,
660
+ tabId: this.tabId,
661
+ lane,
662
+ seq: head.seq + 1n,
663
+ ackedCumulative: head.cumulative,
664
+ maxPrice: d.maxPricePerCall,
665
+ requestHash: requestHash(req.method, url.pathname + url.search, body),
666
+ prevReceiptHash: head.receiptHash,
667
+ issuedAt
668
+ };
669
+ const sig = await d.signer.signVoucher(voucher, this.#policy());
670
+ const voucherBytes = encodeVoucherV1(voucher);
671
+ const headers = new Headers(req.headers);
672
+ headers.set(PAYMENT_SIGNATURE_HEADER, encodePaymentSignature(d.network, this.tabId, lane, voucherBytes, sig));
673
+ headers.set("accept-encoding", "identity");
674
+ const maxBytes = d.maxResponseBytes ?? 8 << 20;
675
+ let res = await this.#send(lane, url, req.method, headers, body);
676
+ let bytes = await readBody(res, maxBytes);
677
+ const retries = d.inFlightRetries ?? 5;
678
+ for (let attempt = 0; isInFlight(res, bytes) && attempt < retries; attempt++) {
679
+ await new Promise((r) => setTimeout(r, (d.inFlightDelayMs ?? 250) * 2 ** attempt));
680
+ res = await this.#send(lane, url, req.method, headers, body);
681
+ bytes = await readBody(res, maxBytes);
682
+ }
683
+ const paid = res.headers.get(PAYMENT_RESPONSE_HEADER);
684
+ if (paid !== null) {
685
+ let receipt;
686
+ let receiptSig;
687
+ try {
688
+ const pr = parsePaymentResponse(paid);
689
+ const commitment = sha256(voucherBytes);
690
+ const retained = !(res.status === 409 && errorCodeOf(jsonOf(bytes))?.error === "response_not_retained");
691
+ if (bytes === null && retained) throw new ClientError("response_too_large", "the paid response exceeds maxResponseBytes");
692
+ receipt = verifyReceipt({
693
+ voucher,
694
+ commitmentId: commitment,
695
+ receipt: pr.receipt,
696
+ sig: pr.sig,
697
+ sellerKeys: this.#sellerKeys,
698
+ ...retained && bytes !== null ? { body: bytes } : {}
699
+ });
700
+ if (toHex(pr.commitmentId) !== toHex(commitment) || pr.charged !== receipt.charged) {
701
+ throw new ClientError("bad_receipt", "PAYMENT-RESPONSE disagrees with its receipt");
702
+ }
703
+ receiptSig = pr.sig;
704
+ } catch (e) {
705
+ this.#lanes.block(lane);
706
+ throw e;
707
+ }
708
+ this.#moveTo(lane, headOf(receipt, receiptSig, voucher.issuedAt), false);
709
+ this.#calls++;
710
+ return { kind: "done", response: new Response(nullBody(res.status, bytes), { status: res.status, statusText: res.statusText, headers: res.headers }) };
711
+ }
712
+ if (isInFlight(res, bytes)) {
713
+ this.#lanes.block(lane);
714
+ return { kind: "done", response: new Response(nullBody(res.status, bytes), { status: res.status, statusText: res.statusText, headers: res.headers }) };
715
+ }
716
+ const json = jsonOf(bytes);
717
+ if (res.status === 402 && errorCodeOf(json)?.error === "lane_out_of_sync" && !last) {
718
+ await this.#resyncFrom(parseLaneSnapshot(json), { onlyLane: lane });
719
+ if (!this.#lanes.isBlocked(lane)) return { kind: "retry" };
720
+ } else {
721
+ await this.#rewind(lane);
722
+ }
723
+ return { kind: "done", response: new Response(nullBody(res.status, bytes), { status: res.status, statusText: res.statusText, headers: res.headers }) };
724
+ }
725
+ /** Sends one voucher; a network failure resends the same bytes once (the seller replays it idempotently). */
726
+ async #send(lane, url, method, headers, body) {
727
+ const init = { method, headers, redirect: "manual", ...method === "GET" || method === "HEAD" ? {} : { body } };
728
+ try {
729
+ return await this.#d.fetch(url, init);
730
+ } catch {
731
+ try {
732
+ return await this.#d.fetch(url, init);
733
+ } catch (e) {
734
+ this.#lanes.block(lane);
735
+ throw new ClientError("seller_unreachable", `the call on lane ${lane} did not reach the seller; resync the tab`, { cause: e });
736
+ }
737
+ }
738
+ }
739
+ /** keyd's voucher policy: exposure within the on-chain limit above what is settled, and the cycle budget. */
740
+ #policy() {
741
+ const tabLimit = this.#view.settledTotal + this.#view.limit;
742
+ return this.#d.cycleBudget === void 0 ? { tabLimit } : { tabLimit, cycleBudget: this.#d.cycleBudget };
743
+ }
744
+ /**
745
+ * Puts keyd's lane back on the last verified receipt after a refused voucher. A lane with no
746
+ * receipt yet needs nothing: keyd signs its seq 1 again (acked 0, it proves no debt).
747
+ */
748
+ async #rewind(lane) {
749
+ const last = this.#lanes.head(lane).last;
750
+ if (last === null) return;
751
+ const resync = this.#d.signer.resyncLane;
752
+ if (resync === void 0) {
753
+ this.#lanes.block(lane);
754
+ return;
755
+ }
756
+ try {
757
+ await resync.call(this.#d.signer, last.receipt, last.sig);
758
+ } catch {
759
+ this.#lanes.block(lane);
760
+ }
761
+ }
762
+ /**
763
+ * Resyncs `onlyLane` (or every lane) from a seller-signed lane snapshot. With `aheadOnly`, only
764
+ * lanes where the seller holds a later receipt than the buyer move (a close mismatch carries the
765
+ * seller's view of a finished cycle, which is behind lanes that went on in the current one).
766
+ */
767
+ async #resyncFrom(snapshot, opts = {}) {
768
+ const scope = { genesis: this.#d.genesis, bureau: this.#d.bureau, tabId: this.tabId, maxLanes: this.#lanes.count, sellerKeys: this.#sellerKeys };
769
+ const resync = this.#d.signer.resyncLane;
770
+ const buyerKey = await this.#ownKey();
771
+ let moved = false;
772
+ for (const entry of snapshot) {
773
+ if (opts.onlyLane !== void 0 && entry.lane !== opts.onlyLane) continue;
774
+ const receipt = verifySnapshotReceipt(scope, entry.lane, entry.receipt, entry.sig);
775
+ if (opts.aheadOnly === true && receipt.seq <= this.#lanes.head(entry.lane).seq) continue;
776
+ if (resync === void 0) {
777
+ this.#lanes.block(entry.lane);
778
+ continue;
779
+ }
780
+ try {
781
+ await resync.call(this.#d.signer, receipt, entry.sig);
782
+ this.#moveTo(entry.lane, headOf(receipt, entry.sig, snapshotVoucherTime(receipt, entry.voucher, entry.voucherSig, buyerKey)), true);
783
+ moved = true;
784
+ } catch {
785
+ this.#lanes.block(entry.lane);
786
+ }
787
+ }
788
+ if (opts.onlyLane !== void 0 && !snapshot.some((e) => e.lane === opts.onlyLane)) {
789
+ if (this.#lanes.head(opts.onlyLane).seq === 0n) this.#lanes.unblock(opts.onlyLane);
790
+ else this.#lanes.block(opts.onlyLane);
791
+ }
792
+ return moved;
793
+ }
794
+ /**
795
+ * Reads the seller's lane snapshot (`GET /tab/:id`) and resyncs every lane from it. The request
796
+ * carries `CCD-TAB-AUTH`, a TabStatusRequestV1 signed by the line key (only the buyer may read
797
+ * its tab's receipts and amounts).
798
+ */
799
+ async resync() {
800
+ const headers = { accept: "application/json" };
801
+ const signStatus = this.#d.signer.signStatusRequest;
802
+ if (signStatus !== void 0) {
803
+ const request = { genesis: this.#d.genesis, bureau: this.#d.bureau, tabId: this.tabId, issuedAt: BigInt(this.#d.now()) };
804
+ headers[TAB_AUTH_HEADER] = encodeTabAuthHeader(encodeTabStatusRequestV1(request), await signStatus.call(this.#d.signer, request));
805
+ }
806
+ const res = await this.#d.fetch(new URL(tabPath(this.tabId), this.#d.origin), { headers, redirect: "manual" });
807
+ const json = await readJson(res);
808
+ if (!res.ok) throw new ClientError(errorCodeOf(json)?.error ?? "seller_error", `GET ${tabPath(this.tabId)}: ${res.status}`, { status: res.status });
809
+ const snapshot = parseLaneSnapshot(json);
810
+ await this.#resyncFrom(snapshot);
811
+ for (let lane = 0; lane < this.#lanes.count; lane++) {
812
+ if (this.#lanes.isBlocked(lane) && this.#lanes.head(lane).seq === 0n && !snapshot.some((e) => e.lane === lane)) this.#lanes.unblock(lane);
813
+ }
814
+ }
815
+ /** The line's session public key (the buyer's own vouchers in a snapshot verify against it). */
816
+ async #ownKey() {
817
+ this.#buyerKey ??= Uint8Array.from(await this.#d.signer.publicKey());
818
+ return this.#buyerKey;
819
+ }
820
+ /** The cycle of a voucher time, or null when it is unknown. */
821
+ #cycleOf(t) {
822
+ return t === null ? null : cycleAt(this.#view, t);
823
+ }
824
+ /**
825
+ * Moves a lane to `next` (forward with `advance`, or as a snapshot says with `reset`) and keeps
826
+ * its cycle boundary as keyd does: when the lane's voucher cycle moves on, the previous head is
827
+ * the lane's last receipt of the cycles before.
828
+ */
829
+ #moveTo(lane, next, reset) {
830
+ const prev = this.#lanes.head(lane);
831
+ if (next.seq > prev.seq && prev.seq > 0n) {
832
+ const pc = this.#cycleOf(prev.voucherIssuedAt);
833
+ const nc = this.#cycleOf(next.voucherIssuedAt);
834
+ if (nc !== null && (pc === null || pc < nc)) this.#boundaries.set(lane, { head: prev, before: nc });
835
+ } else if (next.seq < prev.seq) {
836
+ const b = this.#boundaries.get(lane);
837
+ if (b !== void 0 && b.head.seq >= next.seq) this.#boundaries.delete(lane);
838
+ }
839
+ if (reset) this.#lanes.reset(lane, next);
840
+ else this.#lanes.advance(lane, next);
841
+ }
842
+ /** The lane's last receipt of cycle `c` (by voucher issued_at), or null when it has none. */
843
+ #tailAt(lane, c) {
844
+ const h = this.#lanes.head(lane);
845
+ if (h.seq === 0n) return null;
846
+ const hc = this.#cycleOf(h.voucherIssuedAt);
847
+ if (hc === null || hc <= c) return h;
848
+ const b = this.#boundaries.get(lane);
849
+ if (b === void 0 || b.before <= c) return null;
850
+ const bc = this.#cycleOf(b.head.voucherIssuedAt);
851
+ return bc === null || bc <= c ? b.head : null;
852
+ }
853
+ /** Re-reads the tab from the chain. */
854
+ async refresh() {
855
+ const view = await this.#d.chain.tabOf(this.tabId);
856
+ if (view === null) throw new ClientError("unknown_tab", `tab ${this.tabId} does not exist`);
857
+ this.#view = view;
858
+ return view;
859
+ }
860
+ /**
861
+ * Settles a cycle (see {@link SettleOptions}): signs a CloseVoucherV1 that names it and states each
862
+ * lane at its last receipt of that cycle, collects the seller's CloseAckV1, and redeems a
863
+ * sponsored `settleTab` attaching exactly the amount due. Returns null when nothing is due.
864
+ * Settlements run one at a time. Settling the previous cycle (the default from cycle 1 on) lets
865
+ * calls go on meanwhile; it only waits for calls that started before the current cycle.
866
+ *
867
+ * When an earlier settle() ended with its redemption's outcome open (`submitted_unconfirmed` or
868
+ * `facilitator_unreachable`), this one first sends that redemption again and returns its
869
+ * settlement once the facilitator answers; if that transaction never reached the chain and never
870
+ * can (`not_submitted`, or the facilitator has no record of it and answers `nonce_mismatch` or
871
+ * `transaction_expired`), it settles anew.
872
+ */
873
+ async settle(opts = {}) {
874
+ const prior = this.#settleQueue;
875
+ let done;
876
+ this.#settleQueue = new Promise((r) => {
877
+ done = r;
878
+ });
879
+ try {
880
+ await prior;
881
+ const resent = await this.#resendUnanswered();
882
+ if (resent !== null) return resent;
883
+ let through = opts.through ?? "auto";
884
+ if (through === "auto") through = cycleAt(this.#view, BigInt(this.#d.now())) === 0 ? "current" : "previous";
885
+ if (through === "current") {
886
+ let release;
887
+ this.#hold = new Promise((r) => {
888
+ release = r;
889
+ });
890
+ try {
891
+ await this.#drain(null);
892
+ return await this.#settle("current", true);
893
+ } finally {
894
+ this.#hold = null;
895
+ release();
896
+ }
897
+ }
898
+ const view = await this.refresh();
899
+ const start = view.openedAt + BigInt(cycleAt(view, BigInt(this.#d.now()))) * view.cycleMs;
900
+ await this.#drain(start);
901
+ return await this.#settle("previous", true);
902
+ } finally {
903
+ done();
904
+ }
905
+ }
906
+ async #settle(through, mayResync) {
907
+ const d = this.#d;
908
+ const tab = await this.refresh();
909
+ const now = BigInt(d.now());
910
+ const current = cycleAt(tab, now);
911
+ const cycle = through === "current" ? current : current - 1;
912
+ if (cycle < 0 || cycle < (tab.lastSettledCycle ?? 0)) return null;
913
+ const lanes = [];
914
+ let total = 0n;
915
+ for (let lane = 0; lane < this.#lanes.count; lane++) {
916
+ const recorded = tab.lanes[lane] ?? { seq: 0n, chargedCumulative: 0n };
917
+ const t = this.#tailAt(lane, cycle);
918
+ if (t === null) {
919
+ total += recorded.chargedCumulative;
920
+ continue;
921
+ }
922
+ if (t.seq < recorded.seq || t.cumulative < recorded.chargedCumulative) {
923
+ throw new ClientError("lane_behind_chain", `lane ${lane}: the chain records seq ${recorded.seq}; resync the tab`);
924
+ }
925
+ lanes.push({ lane, seq: t.seq, chargedCumulative: t.cumulative, lastReceiptHash: t.receiptHash });
926
+ total += t.cumulative;
927
+ }
928
+ const amount = total - tab.settledTotal;
929
+ if (lanes.length === 0 || amount <= 0n) return null;
930
+ const close = { genesis: d.genesis, bureau: d.bureau, tabId: this.tabId, cycle, lanes, total, issuedAt: now };
931
+ const closeSig = await d.signer.signClose(close);
932
+ const ack = await this.#collectAck(close, closeSig);
933
+ if (ack === "resynced" && mayResync) return this.#settle(through, false);
934
+ const ackSig = ack instanceof Uint8Array ? ack : null;
935
+ const parameter = encodeSettleTabParams({ close, buyerSig: closeSig, ackSig });
936
+ const settling = { cycle, total, amount, close, closeSig, ackSig };
937
+ let sent;
938
+ try {
939
+ sent = await d.sender.redeem(d.wallet, this.tabId, parameter, amount);
940
+ } catch (e) {
941
+ const requestKey = e instanceof ClientError && UNRESOLVED_CODES.has(e.code) ? e.details["requestKey"] : void 0;
942
+ if (typeof requestKey === "string") {
943
+ this.#unanswered = { requestKey, ...settling };
944
+ await this.refresh().catch(() => void 0);
945
+ }
946
+ throw e;
947
+ }
948
+ return this.#settled(settling, sent);
949
+ }
950
+ /** Checks the facilitator's answer, reads the tab again and builds the {@link Settlement}. */
951
+ async #settled(s, sent) {
952
+ if (sent.amount !== s.amount) throw new ClientError("amount_mismatch", `the facilitator redeemed ${sent.amount}, not ${s.amount}`);
953
+ await this.refresh();
954
+ return { ...s, acked: s.ackSig !== null, txHash: sent.txHash, blockHash: sent.blockHash };
955
+ }
956
+ /**
957
+ * Sends the redemption an earlier settle() left open again: its settlement once the facilitator
958
+ * answers, null when there is none or it never reached the chain (`not_submitted`, or the sender no
959
+ * longer holds it). An outcome that is still open is thrown and kept.
960
+ */
961
+ async #resendUnanswered() {
962
+ const u = this.#unanswered;
963
+ if (u === null) return null;
964
+ let sent;
965
+ try {
966
+ sent = await this.#d.sender.resendRedeem(u.requestKey);
967
+ } catch (e) {
968
+ if (e instanceof ClientError && UNRESOLVED_CODES.has(e.code)) {
969
+ await this.refresh().catch(() => void 0);
970
+ throw e;
971
+ }
972
+ this.#unanswered = null;
973
+ if (e instanceof ClientError && SETTLE_ANEW.has(e.code)) return null;
974
+ throw e;
975
+ }
976
+ this.#unanswered = null;
977
+ return this.#settled({ cycle: u.cycle, total: u.total, amount: u.amount, close: u.close, closeSig: u.closeSig, ackSig: u.ackSig }, sent);
978
+ }
979
+ /**
980
+ * `POST /tab/:id/close`: the verified ack signature, `resynced` after a corrective snapshot, or
981
+ * null when the seller gives no ack (the payment never depends on it).
982
+ */
983
+ async #collectAck(close, closeSig) {
984
+ let res;
985
+ try {
986
+ res = await this.#d.fetch(new URL(tabPath(this.tabId, "/close"), this.#d.origin), {
987
+ method: "POST",
988
+ headers: { "content-type": "application/json", accept: "application/json" },
989
+ body: JSON.stringify({ close: toHex(encodeCloseVoucherV1(close)), sig: toHex(closeSig) }),
990
+ redirect: "manual"
991
+ });
992
+ } catch {
993
+ return null;
994
+ }
995
+ const json = await readJson(res);
996
+ if (res.status === 200) {
997
+ const { ack, sig } = parseCloseAck(json);
998
+ verifyCloseAck(close, ack, sig, this.#sellerKeys);
999
+ return sig;
1000
+ }
1001
+ if (res.status === 409 && errorCodeOf(json)?.error === "close_mismatch") {
1002
+ await this.#resyncFrom(parseLaneSnapshot(json), { aheadOnly: true });
1003
+ return "resynced";
1004
+ }
1005
+ return null;
1006
+ }
1007
+ /** The buyer's view of the tab. */
1008
+ status() {
1009
+ const heads = this.#lanes.heads();
1010
+ const receiptedTotal = heads.reduce((s, h) => s + h.cumulative, 0n);
1011
+ const settledTotal = this.#view.settledTotal;
1012
+ return {
1013
+ tabId: this.tabId,
1014
+ limit: this.#view.limit,
1015
+ settledTotal,
1016
+ receiptedTotal,
1017
+ outstanding: receiptedTotal > settledTotal ? receiptedTotal - settledTotal : 0n,
1018
+ calls: this.#calls,
1019
+ lanes: heads.map((h, lane) => ({ lane, seq: h.seq, cumulative: h.cumulative, blocked: this.#lanes.isBlocked(lane) }))
1020
+ };
1021
+ }
1022
+ /** The verified head of `lane`. */
1023
+ laneHead(lane) {
1024
+ return this.#lanes.head(lane);
1025
+ }
1026
+ async #enter() {
1027
+ while (this.#hold !== null) await this.#hold;
1028
+ const id = this.#nextCall++;
1029
+ this.#active.set(id, BigInt(this.#d.now()));
1030
+ return id;
1031
+ }
1032
+ #leave(id) {
1033
+ this.#active.delete(id);
1034
+ for (const wake of this.#ended.splice(0)) wake();
1035
+ }
1036
+ /** Waits until no call that started before `before` (any call, when null) is in flight. */
1037
+ async #drain(before) {
1038
+ while ([...this.#active.values()].some((t) => before === null || t < before)) {
1039
+ await new Promise((r) => this.#ended.push(r));
1040
+ }
1041
+ }
1042
+ };
1043
+ function cycleAt(tab, t) {
1044
+ return t <= tab.openedAt ? 0 : Number((t - tab.openedAt) / tab.cycleMs);
1045
+ }
1046
+ function isInFlight(res, bytes) {
1047
+ return res.status === 409 && res.headers.get(PAYMENT_RESPONSE_HEADER) === null && errorCodeOf(jsonOf(bytes))?.error === "voucher_in_flight";
1048
+ }
1049
+ function jsonOf(bytes) {
1050
+ if (bytes === null) return null;
1051
+ try {
1052
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1053
+ } catch {
1054
+ return null;
1055
+ }
1056
+ }
1057
+ function nullBody(status, bytes) {
1058
+ return status === 204 || status === 205 || status === 304 || bytes === null ? null : bytes;
1059
+ }
1060
+
1061
+ // packages/handshake/src/adapters/registry.ts
1062
+ import {
1063
+ ContractAddress as SdkContractAddress2,
1064
+ Energy as Energy2,
1065
+ isKnown,
1066
+ Parameter as Parameter2,
1067
+ ReceiveName as ReceiveName2,
1068
+ RejectReasonTag,
1069
+ ReturnValue
1070
+ } from "@concordium/web-sdk";
1071
+
1072
+ // packages/handshake/src/wire.ts
1073
+ import { z as z2 } from "zod";
1074
+ var DEFAULT_MAX_BODY_BYTES = 8 * 1024;
1075
+ var DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024;
1076
+ var AGREEMENT_HEX_LENGTH = 2 * (TabAgreementV1Codec.size ?? 0);
1077
+ var hex = (bytes) => z2.string().regex(new RegExp(`^[0-9a-f]{${2 * bytes}}$`), `must be ${bytes} bytes of lowercase hex`);
1078
+ var u64Decimal = z2.string().regex(/^(0|[1-9][0-9]{0,19})$/, "must be a canonical decimal u64").refine((s) => BigInt(s) <= U64_MAX, "exceeds u64");
1079
+ var badge = z2.string().regex(/^[1-9A-HJ-NP-Za-km-z]{6,64}$/, "must be a CIS-2 token address");
1080
+ var unixSeconds = z2.int().min(0);
1081
+ var helloSchema = z2.strictObject({
1082
+ iss: z2.strictObject({ badge, lineId: u64Decimal, sessionKey: hex(32) }),
1083
+ aud: z2.strictObject({ badge, url: z2.string().min(1).max(2048) }),
1084
+ terms: z2.strictObject({
1085
+ limit: u64Decimal,
1086
+ cycleMs: z2.int().min(1),
1087
+ maxLanes: z2.int().min(1).max(65535)
1088
+ }),
1089
+ /** 16 to 128 base64url characters (at least 96 bits when random). */
1090
+ nonce: z2.string().regex(/^[A-Za-z0-9_-]{16,128}$/, "must be 16 to 128 base64url characters"),
1091
+ iat: unixSeconds,
1092
+ exp: unixSeconds
1093
+ });
1094
+ var helloEnvelopeSchema = z2.strictObject({ hello: helloSchema, sig: hex(64) });
1095
+ var acceptSchema2 = z2.strictObject({
1096
+ helloHash: hex(32),
1097
+ agreement: z2.string().regex(new RegExp(`^[0-9a-f]{${AGREEMENT_HEX_LENGTH}}$`), "must be a hex TabAgreementV1"),
1098
+ sellerSig: hex(64),
1099
+ iat: unixSeconds
1100
+ });
1101
+ var acceptEnvelopeSchema = z2.strictObject({ accept: acceptSchema2, sig: hex(64) });
1102
+ var errorBodySchema = z2.strictObject({
1103
+ error: z2.string().regex(/^[a-z0-9_]{1,64}$/),
1104
+ message: z2.string().max(2048),
1105
+ explain: z2.string().max(2048).optional()
1106
+ });
1107
+
1108
+ // packages/handshake/src/checks.ts
1109
+ var DAY_MS = 86400000n;
1110
+ var MAX_CYCLE_MS = 366n * DAY_MS;
1111
+
1112
+ // packages/handshake/src/errors.ts
1113
+ var RESPONDER_ERRORS = Object.freeze({
1114
+ method_not_allowed: 405,
1115
+ unsupported_media_type: 415,
1116
+ body_too_large: 413,
1117
+ rate_limited: 429,
1118
+ malformed_json: 400,
1119
+ non_canonical_json: 400,
1120
+ invalid_hello: 400,
1121
+ invalid_window: 400,
1122
+ expired: 401,
1123
+ iat_in_future: 401,
1124
+ bad_signature: 401,
1125
+ wrong_audience_badge: 403,
1126
+ wrong_audience_url: 403,
1127
+ replayed_nonce: 409,
1128
+ line_not_found: 403,
1129
+ key_mismatch: 403,
1130
+ badge_line_mismatch: 403,
1131
+ line_not_active: 403,
1132
+ line_expired: 403,
1133
+ owner_defaulted: 403,
1134
+ agent_revoked: 403,
1135
+ owner_changed: 403,
1136
+ key_revoked_or_displaced: 403,
1137
+ badge_invalid: 403,
1138
+ owner_credential_expired: 403,
1139
+ url_not_in_card: 403,
1140
+ same_owner: 403,
1141
+ tier_too_low: 403,
1142
+ standing_too_low: 403,
1143
+ lanes_out_of_range: 422,
1144
+ cycle_out_of_range: 422,
1145
+ limit_out_of_range: 422,
1146
+ line_full: 422,
1147
+ daily_budget_exhausted: 429,
1148
+ replay_cache_full: 503,
1149
+ replay_store_unavailable: 503,
1150
+ chain_unavailable: 503,
1151
+ registry_changed: 503,
1152
+ card_unavailable: 503,
1153
+ seller_not_registered: 503,
1154
+ seller_key_mismatch: 503,
1155
+ seller_key_not_bound: 503,
1156
+ seller_not_active: 503,
1157
+ seller_owner_changed: 503,
1158
+ seller_wallet_changed: 503,
1159
+ internal_error: 500
1160
+ });
1161
+ var INITIATOR_ERROR_CODES = Object.freeze([
1162
+ "invalid_request",
1163
+ "invalid_url",
1164
+ "signer_key_invalid",
1165
+ "signer_failed",
1166
+ "seller_key_invalid",
1167
+ "seller_agent_not_active",
1168
+ "pay_to_mismatch",
1169
+ "transport_error",
1170
+ "seller_rejected",
1171
+ "invalid_accept",
1172
+ "hello_hash_mismatch",
1173
+ "bad_accept_signature",
1174
+ "accept_time_invalid",
1175
+ "invalid_agreement",
1176
+ "bad_agreement_signature",
1177
+ "agreement_mismatch"
1178
+ ]);
1179
+
1180
+ // packages/handshake/src/hono.ts
1181
+ import { Hono } from "hono";
1182
+
1183
+ // packages/handshake/src/http.ts
1184
+ var JSON_HEADERS = Object.freeze({ "content-type": "application/json", "cache-control": "no-store" });
1185
+
1186
+ // packages/client/src/exact.ts
1187
+ import { AccountAddress as AccountAddress2, AccountTransactionType, SequenceNumber as SequenceNumber2, Transaction as Transaction2 } from "@concordium/web-sdk";
1188
+ import { ExactConcordiumScheme } from "@x402/concordium/exact/client";
1189
+ import { x402Client } from "@x402/core/client";
1190
+ import { decodePaymentRequiredHeader, decodePaymentResponseHeader, encodePaymentSignatureHeader } from "@x402/core/http";
1191
+ import {
1192
+ appendPaymentIdentifierToExtensions,
1193
+ extractPaymentIdentifier,
1194
+ generatePaymentId,
1195
+ isPaymentIdentifierExtension,
1196
+ isValidPaymentId,
1197
+ PAYMENT_IDENTIFIER
1198
+ } from "@x402/extensions/payment-identifier";
1199
+ import { z as z3 } from "zod";
1200
+ var MAX_HEADER_CHARS2 = 16 * 1024;
1201
+ var acceptSchema3 = z3.object({
1202
+ scheme: z3.string().max(64),
1203
+ network: z3.string().max(128),
1204
+ asset: z3.string().max(256),
1205
+ amount: z3.string().max(40),
1206
+ payTo: z3.string().max(128),
1207
+ maxTimeoutSeconds: z3.number().int(),
1208
+ extra: z3.record(z3.string().max(64), z3.unknown())
1209
+ }).loose();
1210
+ var paymentRequiredSchema2 = z3.object({
1211
+ x402Version: z3.literal(2),
1212
+ error: z3.string().max(256).optional(),
1213
+ resource: z3.object({ url: z3.string().max(2048) }).loose(),
1214
+ accepts: z3.array(z3.unknown()).max(16),
1215
+ extensions: z3.record(z3.string().max(64), z3.unknown()).optional()
1216
+ }).loose();
1217
+
1218
+ // packages/client/src/client.ts
1219
+ var MAX_TERMS_BYTES = 256 * 1024;
1220
+
1221
+ // packages/client/src/adapters/grpc.ts
1222
+ import {
1223
+ AccountAddress as AccountAddress3,
1224
+ CcdAmount as CcdAmount2,
1225
+ ContractAddress as SdkContractAddress3,
1226
+ Energy as Energy3,
1227
+ isKnown as isKnown2,
1228
+ Parameter as Parameter3,
1229
+ ReceiveName as ReceiveName3,
1230
+ RejectReasonTag as RejectReasonTag2,
1231
+ ReturnValue as ReturnValue2
1232
+ } from "@concordium/web-sdk";
1233
+ function arrayBuffer2(bytes) {
1234
+ const copy = new Uint8Array(bytes.length);
1235
+ copy.set(bytes);
1236
+ return copy.buffer;
1237
+ }
1238
+ var GrpcClientChain = class {
1239
+ #client;
1240
+ #bureau;
1241
+ #energy;
1242
+ constructor(client, opts) {
1243
+ this.#client = client;
1244
+ this.#bureau = opts.bureau;
1245
+ this.#energy = opts.energy ?? 500000n;
1246
+ }
1247
+ async #view(entrypoint, parameter, decode) {
1248
+ const res = await this.#client.invokeContract({
1249
+ contract: SdkContractAddress3.create(this.#bureau.index, this.#bureau.subindex),
1250
+ method: ReceiveName3.fromString(`${BUREAU_CONTRACT_NAME}.${entrypoint}`),
1251
+ parameter: Parameter3.fromBuffer(arrayBuffer2(parameter)),
1252
+ energy: Energy3.create(this.#energy)
1253
+ });
1254
+ if (res.tag === "failure") throw new ClientError("chain_unavailable", `${entrypoint} could not be read`);
1255
+ if (res.returnValue === void 0) throw new ClientError("chain_unavailable", `${entrypoint} returned nothing`);
1256
+ return decode(Uint8Array.from(ReturnValue2.toBuffer(res.returnValue)));
1257
+ }
1258
+ tabOf(tabId) {
1259
+ return this.#view("tabOf", encodeTabOfParams(tabId), decodeTabOfResult);
1260
+ }
1261
+ lineOf(lineId) {
1262
+ return this.#view("lineOf", encodeLineOfParams(lineId), decodeLineOfResult);
1263
+ }
1264
+ async nextNonce(address2) {
1265
+ return (await this.#client.getNextAccountNonce(AccountAddress3.fromBase58(address2))).nonce.value;
1266
+ }
1267
+ async dryRun(input) {
1268
+ const res = await this.#client.invokeContract({
1269
+ invoker: AccountAddress3.fromBase58(input.invoker),
1270
+ contract: SdkContractAddress3.create(this.#bureau.index, this.#bureau.subindex),
1271
+ method: ReceiveName3.fromString(`${BUREAU_CONTRACT_NAME}.${input.entrypoint}`),
1272
+ parameter: Parameter3.fromBuffer(arrayBuffer2(input.parameter)),
1273
+ amount: CcdAmount2.fromMicroCcd(input.amount),
1274
+ energy: Energy3.create(this.#energy)
1275
+ });
1276
+ if (res.tag === "success") return res.usedEnergy.value;
1277
+ const reason = res.reason;
1278
+ const rejectCode = isKnown2(reason) && reason.tag === RejectReasonTag2.RejectedReceive ? reason.rejectReason : null;
1279
+ const bureauError = rejectCode === null ? null : bureauErrorName(rejectCode);
1280
+ throw new ClientError("dry_run_failed", `${input.entrypoint} would be rejected (${bureauError ?? (isKnown2(reason) ? reason.tag : "unknown")})`, {
1281
+ details: { rejectCode, bureauError }
1282
+ });
1283
+ }
1284
+ };
1285
+
1286
+ // packages/client/src/adapters/facilitator.ts
1287
+ import { z as z4 } from "zod";
1288
+ var MAX_RESPONSE_BYTES = 64 * 1024;
1289
+ var u642 = z4.string().regex(/^(0|[1-9][0-9]{0,19})$/).transform(BigInt).refine((v) => v < 1n << 64n);
1290
+ var hash = z4.string().regex(/^[0-9a-f]{64}$/);
1291
+ var address = z4.string().max(64).refine(isAccountAddress, "an account address");
1292
+ var supportedSchema = z4.object({
1293
+ kinds: z4.array(
1294
+ z4.object({
1295
+ scheme: z4.string().max(64),
1296
+ network: z4.string().max(128),
1297
+ extra: z4.object({ sponsor: address, relay: address, bureau: z4.object({ index: u642, subindex: u642 }).strict() }).loose()
1298
+ }).loose()
1299
+ ).min(1).max(16)
1300
+ }).loose();
1301
+ var submitSchema = z4.object({ txHash: hash, blockHash: hash }).strict();
1302
+ var redeemSchema = z4.object({ txHash: hash, blockHash: hash, amount: u642 }).strict();
1303
+ var HttpFacilitator = class {
1304
+ #base;
1305
+ #fetch;
1306
+ #timeoutMs;
1307
+ constructor(opts) {
1308
+ this.#base = opts.baseUrl.replace(/\/+$/, "");
1309
+ this.#fetch = opts.fetch ?? fetch;
1310
+ this.#timeoutMs = opts.timeoutMs ?? 9e4;
1311
+ }
1312
+ async supported() {
1313
+ const body = await this.#request("GET", "/supported");
1314
+ const parsed = supportedSchema.safeParse(body);
1315
+ const kind = parsed.success ? parsed.data.kinds[0] : void 0;
1316
+ if (kind === void 0) throw new ClientError("malformed_response", "GET /supported is not a facilitator answer");
1317
+ const bureau = { index: kind.extra.bureau.index, subindex: kind.extra.bureau.subindex };
1318
+ return { sponsor: kind.extra.sponsor, relay: kind.extra.relay, bureau, network: kind.network };
1319
+ }
1320
+ async submit(transaction) {
1321
+ const parsed = submitSchema.safeParse(await this.#request("POST", "/sponsor/submit", { transaction }));
1322
+ if (!parsed.success) throw new ClientError("malformed_response", "POST /sponsor/submit returned an unexpected body");
1323
+ return parsed.data;
1324
+ }
1325
+ async redeem(tabId, transaction) {
1326
+ const parsed = redeemSchema.safeParse(await this.#request("POST", "/redeem", { tabId: tabId.toString(), transaction }));
1327
+ if (!parsed.success) throw new ClientError("malformed_response", "POST /redeem returned an unexpected body");
1328
+ return parsed.data;
1329
+ }
1330
+ async #request(method, path, body) {
1331
+ let res;
1332
+ try {
1333
+ res = await this.#fetch(`${this.#base}${path}`, {
1334
+ method,
1335
+ headers: body === void 0 ? { accept: "application/json" } : { "content-type": "application/json", accept: "application/json" },
1336
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
1337
+ redirect: "error",
1338
+ signal: AbortSignal.timeout(this.#timeoutMs)
1339
+ });
1340
+ } catch (e) {
1341
+ throw new ClientError("facilitator_unreachable", `${method} ${path} failed: ${e.message}`, { cause: e });
1342
+ }
1343
+ const bytes = await readBody(res, MAX_RESPONSE_BYTES);
1344
+ if (bytes === null) throw new ClientError("malformed_response", `${method} ${path}: the answer is too large`, { status: res.status });
1345
+ let json = null;
1346
+ try {
1347
+ json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1348
+ } catch {
1349
+ }
1350
+ if (res.ok) return json;
1351
+ const err = errorCodeOf(json);
1352
+ const details = json !== null && typeof json === "object" && !Array.isArray(json) ? json : {};
1353
+ throw new ClientError(err?.error ?? "facilitator_error", `${method} ${path}: ${res.status} ${err?.message ?? ""}`.trim(), {
1354
+ status: res.status,
1355
+ details
1356
+ });
1357
+ }
1358
+ };
1359
+
1360
+ // packages/cli/src/liveSettle.ts
1361
+ async function settleLive({ config, io, grpc }, req) {
1362
+ if (config.facilitatorUrl === null) throw new CliError("usage", "set FACILITATOR_URL");
1363
+ const chain = new GrpcClientChain(grpc, { bureau: config.bureau });
1364
+ const facilitator = new HttpFacilitator({ baseUrl: config.facilitatorUrl, fetch: io.fetch });
1365
+ const now = () => io.now();
1366
+ const sender = new SponsoredSender({ chain, facilitator, bureau: config.bureau, now });
1367
+ const view = await chain.tabOf(req.tabId);
1368
+ if (view === null) throw new CliError("not_found", `tab ${req.tabId} does not exist`);
1369
+ const keyd = new KeydClient({ socketPath: config.keydSocket });
1370
+ const wallet = await KeyFileAccountSigner.fromFile(req.walletKeyFile);
1371
+ try {
1372
+ const genesis = fromHex(TESTNET_GENESIS_HEX, 32);
1373
+ const tab = new Tab({
1374
+ tabId: req.tabId,
1375
+ view,
1376
+ genesis,
1377
+ bureau: config.bureau,
1378
+ network: caip2FromGenesis(genesis),
1379
+ origin: new URL(req.origin).origin,
1380
+ signer: keyd.buyer(req.keyName),
1381
+ wallet,
1382
+ chain,
1383
+ sender,
1384
+ fetch: io.fetch,
1385
+ now,
1386
+ maxPricePerCall: req.maxPricePerCall
1387
+ });
1388
+ await tab.resync();
1389
+ const s = await tab.settle({ through: req.through });
1390
+ return s === null ? null : { cycle: s.cycle, total: s.total, amount: s.amount, acked: s.acked, txHash: s.txHash };
1391
+ } finally {
1392
+ wallet.destroy();
1393
+ keyd.close();
1394
+ }
1395
+ }
1396
+ export {
1397
+ settleLive
1398
+ };