kawasekit 0.1.0-beta.2 → 0.1.0-beta.3
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.
- package/README.md +56 -18
- package/dist/{chunk-ZES4UYIQ.js → chunk-2V3W4B64.js} +47 -7
- package/dist/chunk-2V3W4B64.js.map +1 -0
- package/dist/{chunk-DLH2O4MU.js → chunk-6G345P2I.js} +3 -3
- package/dist/{chunk-DLH2O4MU.js.map → chunk-6G345P2I.js.map} +1 -1
- package/dist/{chunk-ZY6RT2DB.js → chunk-CD6SQBZN.js} +211 -30
- package/dist/chunk-CD6SQBZN.js.map +1 -0
- package/dist/chunk-WMFCI6KC.js +333 -0
- package/dist/chunk-WMFCI6KC.js.map +1 -0
- package/dist/cli/index.cjs +3 -3
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +7 -6
- package/dist/cli/index.js.map +1 -1
- package/dist/idempotency/index.cjs +353 -0
- package/dist/idempotency/index.cjs.map +1 -0
- package/dist/idempotency/index.d.cts +203 -0
- package/dist/idempotency/index.d.ts +203 -0
- package/dist/idempotency/index.js +5 -0
- package/dist/idempotency/index.js.map +1 -0
- package/dist/index-NdNKNnZP.d.cts +808 -0
- package/dist/index-kqH78Yms.d.ts +808 -0
- package/dist/index.cjs +575 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +40 -4
- package/dist/index.d.ts +40 -4
- package/dist/index.js +4 -3
- package/dist/observability/index.d.cts +203 -2
- package/dist/observability/index.d.ts +203 -2
- package/dist/observability/otlp/index.d.cts +2 -1
- package/dist/observability/otlp/index.d.ts +2 -1
- package/dist/observability/prometheus/index.d.cts +2 -1
- package/dist/observability/prometheus/index.d.ts +2 -1
- package/dist/{server-t1qVFVnJ.d.ts → server-BMeg_hNB.d.cts} +30 -2
- package/dist/{server-C3XkkTIP.d.cts → server-CSpATNiH.d.ts} +30 -2
- package/dist/store-BY16tCbe.d.cts +166 -0
- package/dist/store-Bd-91QL0.d.ts +166 -0
- package/dist/{index-Bf78wMqn.d.cts → types-A_WwFpcv.d.cts} +1 -200
- package/dist/{index-WQ_Hq4_Z.d.ts → types-DwFfT4E7.d.ts} +1 -200
- package/dist/x402/hono/index.cjs +335 -4
- package/dist/x402/hono/index.cjs.map +1 -1
- package/dist/x402/hono/index.d.cts +4 -2
- package/dist/x402/hono/index.d.ts +4 -2
- package/dist/x402/hono/index.js +2 -1
- package/dist/x402/hono/index.js.map +1 -1
- package/dist/x402/index.cjs +373 -3
- package/dist/x402/index.cjs.map +1 -1
- package/dist/x402/index.d.cts +7 -768
- package/dist/x402/index.d.ts +7 -768
- package/dist/x402/index.js +3 -2
- package/package.json +11 -1
- package/dist/chunk-ZES4UYIQ.js.map +0 -1
- package/dist/chunk-ZY6RT2DB.js.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { chainIdToX402Network, X402_VERSION, createInMemoryIdempotencyStore, KAWASEKIT_IDEMPOTENCY_RECORD_VERSION } from './chunk-WMFCI6KC.js';
|
|
2
|
+
import { polygonAmoy, polygon } from './chunk-SA7LMQFG.js';
|
|
2
3
|
import { invokeHookSafely, extractAcceptedNetworks } from './chunk-LEHWRDVS.js';
|
|
3
4
|
import { isAddress, getAddress } from 'viem';
|
|
4
5
|
|
|
@@ -226,35 +227,11 @@ var X402InvalidConfigError = class extends Error {
|
|
|
226
227
|
}
|
|
227
228
|
};
|
|
228
229
|
|
|
229
|
-
// src/x402/types.ts
|
|
230
|
-
var X402_VERSION = 2;
|
|
231
|
-
var EIP155_PREFIX = "eip155:";
|
|
232
|
-
function chainIdToX402Network(chainId) {
|
|
233
|
-
return `${EIP155_PREFIX}${chainId}`;
|
|
234
|
-
}
|
|
235
|
-
function isX402Network(value) {
|
|
236
|
-
if (!value.startsWith(EIP155_PREFIX)) {
|
|
237
|
-
return false;
|
|
238
|
-
}
|
|
239
|
-
const rest = value.slice(EIP155_PREFIX.length);
|
|
240
|
-
if (rest.length === 0 || /^0\d/.test(rest)) {
|
|
241
|
-
return false;
|
|
242
|
-
}
|
|
243
|
-
const parsed = Number(rest);
|
|
244
|
-
if (!Number.isInteger(parsed) || parsed < 0) {
|
|
245
|
-
return false;
|
|
246
|
-
}
|
|
247
|
-
return isSupportedChainId(parsed);
|
|
248
|
-
}
|
|
249
|
-
function x402NetworkToChainId(network) {
|
|
250
|
-
const rest = network.slice(EIP155_PREFIX.length);
|
|
251
|
-
return Number(rest);
|
|
252
|
-
}
|
|
253
|
-
|
|
254
230
|
// src/x402/encoding.ts
|
|
255
231
|
var X402_HEADER_PAYMENT_REQUIRED = "PAYMENT-REQUIRED";
|
|
256
232
|
var X402_HEADER_PAYMENT_SIGNATURE = "PAYMENT-SIGNATURE";
|
|
257
233
|
var X402_HEADER_PAYMENT_RESPONSE = "PAYMENT-RESPONSE";
|
|
234
|
+
var X402_HEADER_IDEMPOTENCY_KEY = "Idempotency-Key";
|
|
258
235
|
var BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})?$/;
|
|
259
236
|
function bigIntReplacer(_key, value) {
|
|
260
237
|
return typeof value === "bigint" ? value.toString() : value;
|
|
@@ -460,8 +437,168 @@ function withPaymentResponseHeader(innerResponse, settlement) {
|
|
|
460
437
|
headers
|
|
461
438
|
});
|
|
462
439
|
}
|
|
440
|
+
var SNAPSHOT_HEADER_ALLOWLIST = ["content-type", X402_HEADER_PAYMENT_RESPONSE];
|
|
441
|
+
var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
|
|
442
|
+
var DEFAULT_MAX_SNAPSHOT_BYTES = 64 * 1024;
|
|
443
|
+
var DEFAULT_FALLBACK_TTL_SECONDS = 86400;
|
|
444
|
+
function resolveIdempotency(config) {
|
|
445
|
+
if (config?.store === "none") {
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
return {
|
|
449
|
+
store: config?.store ?? createInMemoryIdempotencyStore(),
|
|
450
|
+
inFlight: config?.inFlight ?? "reject",
|
|
451
|
+
maxSnapshotBytes: config?.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES,
|
|
452
|
+
fallbackTtlSeconds: config?.fallbackTtlSeconds ?? DEFAULT_FALLBACK_TTL_SECONDS
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
function bytesToBase64(bytes) {
|
|
456
|
+
let binary = "";
|
|
457
|
+
for (const b of bytes) {
|
|
458
|
+
binary += String.fromCharCode(b);
|
|
459
|
+
}
|
|
460
|
+
return btoa(binary);
|
|
461
|
+
}
|
|
462
|
+
function base64ToBytes(b64) {
|
|
463
|
+
const binary = atob(b64);
|
|
464
|
+
const bytes = new Uint8Array(binary.length);
|
|
465
|
+
for (let i = 0; i < binary.length; i += 1) {
|
|
466
|
+
bytes[i] = binary.charCodeAt(i);
|
|
467
|
+
}
|
|
468
|
+
return bytes;
|
|
469
|
+
}
|
|
470
|
+
function readAuthorization(payload) {
|
|
471
|
+
const inner = payload.payload;
|
|
472
|
+
if (typeof inner !== "object" || inner === null) {
|
|
473
|
+
return null;
|
|
474
|
+
}
|
|
475
|
+
const auth = inner.authorization;
|
|
476
|
+
if (typeof auth !== "object" || auth === null) {
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
479
|
+
const a = auth;
|
|
480
|
+
if (typeof a.nonce !== "string" || a.nonce === "") {
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
const validBefore = typeof a.validBefore === "string" && /^[0-9]+$/.test(a.validBefore) ? BigInt(a.validBefore) : 0n;
|
|
484
|
+
return { nonce: a.nonce, validBefore };
|
|
485
|
+
}
|
|
486
|
+
function computeServerKey(request, requirements, auth) {
|
|
487
|
+
const header = request.headers.get(X402_HEADER_IDEMPOTENCY_KEY);
|
|
488
|
+
let material;
|
|
489
|
+
if (header !== null && header !== "") {
|
|
490
|
+
material = `hdr:${header}`;
|
|
491
|
+
} else if (auth !== null) {
|
|
492
|
+
material = `nonce:${auth.nonce}`;
|
|
493
|
+
} else {
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
return JSON.stringify([
|
|
497
|
+
requirements.network,
|
|
498
|
+
getAddress(requirements.payTo),
|
|
499
|
+
getAddress(requirements.asset),
|
|
500
|
+
material
|
|
501
|
+
]);
|
|
502
|
+
}
|
|
503
|
+
async function snapshotResponse(response, maxBytes) {
|
|
504
|
+
const contentLength = response.headers.get("content-length");
|
|
505
|
+
if (contentLength !== null && Number(contentLength) > maxBytes) {
|
|
506
|
+
return void 0;
|
|
507
|
+
}
|
|
508
|
+
const buffer = await response.clone().arrayBuffer();
|
|
509
|
+
if (buffer.byteLength > maxBytes) {
|
|
510
|
+
return void 0;
|
|
511
|
+
}
|
|
512
|
+
const headers = [];
|
|
513
|
+
for (const name of SNAPSHOT_HEADER_ALLOWLIST) {
|
|
514
|
+
const value = response.headers.get(name);
|
|
515
|
+
if (value !== null) {
|
|
516
|
+
headers.push([name, value]);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return { status: response.status, headers, bodyBase64: bytesToBase64(new Uint8Array(buffer)) };
|
|
520
|
+
}
|
|
521
|
+
function replayResponse(record) {
|
|
522
|
+
const snapshot = record.responseSnapshot;
|
|
523
|
+
if (snapshot !== void 0) {
|
|
524
|
+
const headers2 = new Headers();
|
|
525
|
+
for (const [name, value] of snapshot.headers) {
|
|
526
|
+
headers2.set(name, value);
|
|
527
|
+
}
|
|
528
|
+
headers2.set(IDEMPOTENCY_REPLAYED_HEADER, "true");
|
|
529
|
+
return new Response(base64ToBytes(snapshot.bodyBase64), { status: snapshot.status, headers: headers2 });
|
|
530
|
+
}
|
|
531
|
+
const headers = new Headers({ [IDEMPOTENCY_REPLAYED_HEADER]: "true" });
|
|
532
|
+
headers.set(
|
|
533
|
+
X402_HEADER_PAYMENT_RESPONSE,
|
|
534
|
+
encodePaymentResponseHeader({
|
|
535
|
+
success: true,
|
|
536
|
+
transaction: record.txHash,
|
|
537
|
+
network: record.network,
|
|
538
|
+
payer: record.payer,
|
|
539
|
+
amount: record.amount
|
|
540
|
+
})
|
|
541
|
+
);
|
|
542
|
+
return new Response(null, { status: 200, headers });
|
|
543
|
+
}
|
|
544
|
+
function buildRecord(key, settlement, requirements, validBefore, fallbackTtlSeconds, snapshot) {
|
|
545
|
+
if (settlement.transaction === "" || settlement.payer === void 0) {
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
const nowSec = BigInt(Math.floor(Date.now() / 1e3));
|
|
549
|
+
const expiresAt = validBefore > nowSec ? validBefore : nowSec + BigInt(fallbackTtlSeconds);
|
|
550
|
+
return {
|
|
551
|
+
kawasekitVersion: KAWASEKIT_IDEMPOTENCY_RECORD_VERSION,
|
|
552
|
+
key,
|
|
553
|
+
// settlement.transaction is the on-chain tx hash (0x-hex) the facilitator broadcast.
|
|
554
|
+
txHash: settlement.transaction,
|
|
555
|
+
payer: settlement.payer,
|
|
556
|
+
amount: settlement.amount ?? requirements.amount,
|
|
557
|
+
network: requirements.network,
|
|
558
|
+
...snapshot !== void 0 ? { responseSnapshot: snapshot } : {},
|
|
559
|
+
expiresAt
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
function sleep(ms) {
|
|
563
|
+
return new Promise((resolve) => {
|
|
564
|
+
setTimeout(resolve, ms);
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
var IN_FLIGHT_POLL_MS = 100;
|
|
568
|
+
var IN_FLIGHT_MAX_POLLS = 50;
|
|
569
|
+
async function releaseLease(idem, key, lease) {
|
|
570
|
+
if (idem !== null && key !== null && lease !== null) {
|
|
571
|
+
try {
|
|
572
|
+
await idem.store.abandon(key, lease);
|
|
573
|
+
} catch {
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
async function resolveInFlight(idem, key) {
|
|
578
|
+
if (idem.inFlight !== "await") {
|
|
579
|
+
return null;
|
|
580
|
+
}
|
|
581
|
+
for (let i = 0; i < IN_FLIGHT_MAX_POLLS; i += 1) {
|
|
582
|
+
await sleep(IN_FLIGHT_POLL_MS);
|
|
583
|
+
let lookup;
|
|
584
|
+
try {
|
|
585
|
+
lookup = await idem.store.begin(key);
|
|
586
|
+
} catch {
|
|
587
|
+
return null;
|
|
588
|
+
}
|
|
589
|
+
if (lookup.status === "completed") {
|
|
590
|
+
return lookup.record;
|
|
591
|
+
}
|
|
592
|
+
if (lookup.status === "fresh") {
|
|
593
|
+
await releaseLease(idem, key, lookup.lease);
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
463
599
|
function createX402Handler(params) {
|
|
464
600
|
const { facilitator, requirementsFor, handler, resourceFor, hooks } = params;
|
|
601
|
+
const idempotency = resolveIdempotency(params.idempotency);
|
|
465
602
|
return async function x402Handler(request) {
|
|
466
603
|
const startedAtMs = Date.now();
|
|
467
604
|
const emitPaymentRequired = (reqs, error) => {
|
|
@@ -517,6 +654,28 @@ function createX402Handler(params) {
|
|
|
517
654
|
if (!verifyResult.isValid) {
|
|
518
655
|
return emitPaymentRequired(requirements, verifyResult.invalidReason ?? "verify failed");
|
|
519
656
|
}
|
|
657
|
+
const auth = readAuthorization(paymentPayload);
|
|
658
|
+
const idemKey = idempotency !== null ? computeServerKey(request, matchedRequirements, auth) : null;
|
|
659
|
+
let lease = null;
|
|
660
|
+
if (idempotency !== null && idemKey !== null) {
|
|
661
|
+
let lookup;
|
|
662
|
+
try {
|
|
663
|
+
lookup = await idempotency.store.begin(idemKey);
|
|
664
|
+
} catch (cause) {
|
|
665
|
+
return internalError("idempotency_store_failed", cause);
|
|
666
|
+
}
|
|
667
|
+
if (lookup.status === "completed") {
|
|
668
|
+
return replayResponse(lookup.record);
|
|
669
|
+
}
|
|
670
|
+
if (lookup.status === "in_flight") {
|
|
671
|
+
const awaited = await resolveInFlight(idempotency, idemKey);
|
|
672
|
+
if (awaited !== null) {
|
|
673
|
+
return replayResponse(awaited);
|
|
674
|
+
}
|
|
675
|
+
return emitPaymentRequired(requirements, "payment_in_progress");
|
|
676
|
+
}
|
|
677
|
+
lease = lookup.lease;
|
|
678
|
+
}
|
|
520
679
|
let settleResult;
|
|
521
680
|
try {
|
|
522
681
|
settleResult = await facilitator.settle({
|
|
@@ -525,9 +684,11 @@ function createX402Handler(params) {
|
|
|
525
684
|
paymentRequirements: matchedRequirements
|
|
526
685
|
});
|
|
527
686
|
} catch (cause) {
|
|
687
|
+
await releaseLease(idempotency, idemKey, lease);
|
|
528
688
|
return internalError("facilitator_settle_failed", cause);
|
|
529
689
|
}
|
|
530
690
|
if (!settleResult.success) {
|
|
691
|
+
await releaseLease(idempotency, idemKey, lease);
|
|
531
692
|
return emitPaymentRequired(requirements, settleResult.errorReason ?? "settle failed");
|
|
532
693
|
}
|
|
533
694
|
if (settleResult.payer !== void 0) {
|
|
@@ -549,10 +710,30 @@ function createX402Handler(params) {
|
|
|
549
710
|
settlement: settleResult
|
|
550
711
|
};
|
|
551
712
|
const innerResponse = await handler(request, context);
|
|
552
|
-
|
|
713
|
+
const finalResponse = withPaymentResponseHeader(innerResponse, settleResult);
|
|
714
|
+
if (idempotency !== null && idemKey !== null && lease !== null) {
|
|
715
|
+
const snapshot = await snapshotResponse(finalResponse, idempotency.maxSnapshotBytes);
|
|
716
|
+
const record = buildRecord(
|
|
717
|
+
idemKey,
|
|
718
|
+
settleResult,
|
|
719
|
+
matchedRequirements,
|
|
720
|
+
auth?.validBefore ?? 0n,
|
|
721
|
+
idempotency.fallbackTtlSeconds,
|
|
722
|
+
snapshot
|
|
723
|
+
);
|
|
724
|
+
if (record !== null) {
|
|
725
|
+
try {
|
|
726
|
+
await idempotency.store.complete(idemKey, record, lease);
|
|
727
|
+
} catch {
|
|
728
|
+
}
|
|
729
|
+
} else {
|
|
730
|
+
await releaseLease(idempotency, idemKey, lease);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
return finalResponse;
|
|
553
734
|
};
|
|
554
735
|
}
|
|
555
736
|
|
|
556
|
-
export { JPYC_DECIMALS, JPYC_EIP712_DOMAIN_HINT, JPYC_V2_ADDRESS, JpycNotAvailableError, X402InvalidConfigError, X402InvalidPayloadError, X402_DEFAULT_MAX_TIMEOUT_SECONDS, X402_HEADER_PAYMENT_REQUIRED, X402_HEADER_PAYMENT_RESPONSE, X402_HEADER_PAYMENT_SIGNATURE,
|
|
557
|
-
//# sourceMappingURL=chunk-
|
|
558
|
-
//# sourceMappingURL=chunk-
|
|
737
|
+
export { JPYC_DECIMALS, JPYC_EIP712_DOMAIN_HINT, JPYC_V2_ADDRESS, JpycNotAvailableError, X402InvalidConfigError, X402InvalidPayloadError, X402_DEFAULT_MAX_TIMEOUT_SECONDS, X402_HEADER_IDEMPOTENCY_KEY, X402_HEADER_PAYMENT_REQUIRED, X402_HEADER_PAYMENT_RESPONSE, X402_HEADER_PAYMENT_SIGNATURE, buildPaymentRequiredResponse, buildPaymentRequirements, createX402Handler, decodePaymentRequiredHeader, decodePaymentResponseHeader, decodePaymentSignatureHeader, encodePaymentRequiredHeader, encodePaymentResponseHeader, encodePaymentSignatureHeader, getJpycAddress, jpycAbi, jpycDeployments };
|
|
738
|
+
//# sourceMappingURL=chunk-CD6SQBZN.js.map
|
|
739
|
+
//# sourceMappingURL=chunk-CD6SQBZN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tokens/jpyc.ts","../src/x402/errors.ts","../src/x402/encoding.ts","../src/x402/payment-requirements.ts","../src/x402/server.ts"],"names":["getAddress","headers"],"mappings":";;;;;;AAgBO,IAAM,aAAA,GAAgB;AAatB,IAAM,uBAAA,GAA0B;AAAA,EACtC,IAAA,EAAM,UAAA;AAAA,EACN,OAAA,EAAS;AACV;AAaO,IAAM,eAAA,GAA2B;AAgBjC,IAAM,eAAA,GAA8E;AAAA,EAC1F,CAAC,OAAA,CAAQ,EAAE,GAAG,EAAE,OAAA,EAAS,OAAA,C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,SAAS,mBAAA,CAAoB,OAAA;AAAA,QAC7B,aAAa,YAAA,CAAa;AAAA,OAC3B;AACA,MAAA,gBAAA,CAAiB,KAAA,EAAO,mBAAmB,aAAa,CAAA;AAAA,IACzD;AAGA,IAAA,MAAM,OAAA,GAA8B;AAAA,MACnC,cAAA;AAAA,MACA,mBAAA;AAAA,MACA,UAAA,EAAY;AAAA,KACb;AACA,IAAA,MAAM,aAAA,GAAgB,MAAM,OAAA,CAAQ,OAAA,EAAS,OAAO,CAAA;AACpD,IAAA,MAAM,aAAA,GAAgB,yBAAA,CAA0B,aAAA,EAAe,YAAY,CAAA;AAI3E,IAAA,IAAI,WAAA,KAAgB,IAAA,IAAQ,OAAA,KAAY,IAAA,IAAQ,UAAU,IAAA,EAAM;AAC/D,MAAA,MAAM,QAAA,GAAW,MAAM,gBAAA,CAAiB,aAAA,EAAe,YAAY,gBAAgB,CAAA;AACnF,MAAA,MAAM,MAAA,GAAS,WAAA;AAAA,QACd,OAAA;AAAA,QACA,YAAA;AAAA,QACA,mBAAA;AAAA,QACA,MAAM,WAAA,IAAe,EAAA;AAAA,QACrB,WAAA,CAAY,kBAAA;AAAA,QACZ;AAAA,OACD;AACA,MAAA,IAAI,WAAW,IAAA,EAAM;AACpB,QAAA,IAAI;AACH,UAAA,MAAM,WAAA,CAAY,KAAA,CAAM,QAAA,CAAS,OAAA,EAAS,QAAQ,KAAK,CAAA;AAAA,QACxD,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACD,CAAA,MAAO;AACN,QAAA,MAAM,YAAA,CAAa,WAAA,EAAa,OAAA,EAAS,KAAK,CAAA;AAAA,MAC/C;AAAA,IACD;AACA,IAAA,OAAO,aAAA;AAAA,EACR,CAAA;AACD","file":"chunk-CD6SQBZN.js","sourcesContent":["/**\n * JPYC stablecoin metadata, deployments, and ABI.\n *\n * JPYC is a Japanese yen-pegged stablecoin issued by JPYC Inc. under the\n * revised Payment Services Act as 電子決済手段 (electronic payment\n * instrument). The new (\"v2\") JPYC, launched 2025-10, lives at the same\n * address on every chain where it is deployed.\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport { polygon, polygonAmoy } from \"../chains\";\n\n/** ERC-20 decimals for JPYC. Constant across every chain. */\nexport const JPYC_DECIMALS = 18;\n\n/**\n * EIP-712 domain hint for off-chain authorization signing (EIP-3009, EIP-2612).\n *\n * The real JPYC contract does not expose `version()` publicly — it lives in an\n * `internal VERSION` state variable set during proxy initialization. The\n * canonical value is `\"1\"`, matching the FiatToken lineage; the\n * {@link signTransferWithAuthorization} helper accepts an override if a future\n * deployment changes this.\n *\n * `name` is \"JPY Coin\" — the on-chain `name()` value on every live deployment.\n */\nexport const JPYC_EIP712_DOMAIN_HINT = {\n\tname: \"JPY Coin\",\n\tversion: \"1\",\n} as const;\n\n/**\n * Address shared by every live JPYC deployment.\n *\n * Verified on:\n * - Ethereum : https://etherscan.io/token/0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n * - Polygon : https://polygonscan.com/token/0xe7c3d8c9a439fede00d2600032d5db0be71c3c29\n * - Polygon Amoy : https://amoy.polygonscan.com/token/0xe7c3d8c9a439fede00d2600032d5db0be71c3c29\n * - Avalanche : https://snowtrace.io/token/0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n *\n * Do NOT confuse with the legacy 前払式支払手段 JPYC at `0x431D5dFF...`.\n */\nexport const JPYC_V2_ADDRESS: Address = \"0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\";\n\n/** A JPYC deployment on a single chain. */\nexport interface JpycDeployment {\n\treadonly chainId: SupportedChainId;\n\treadonly address: Address;\n\t/** `true` if the token is live on this chain right now. */\n\treadonly isLive: boolean;\n}\n\n/**\n * JPYC deployments keyed by chain.\n *\n * Only chains in {@link SupportedChainId} appear here — adding Avalanche /\n * Ethereum requires first adding them to `src/chains/`.\n */\nexport const jpycDeployments: { readonly [chainId in SupportedChainId]: JpycDeployment } = {\n\t[polygon.id]: { chainId: polygon.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[polygonAmoy.id]: { chainId: polygonAmoy.id, address: JPYC_V2_ADDRESS, isLive: true },\n};\n\n/**\n * Thrown when JPYC is not deployed on the requested chain.\n *\n * Today this is unreachable (every {@link SupportedChainId} has a live\n * deployment), but the error class is exported for future chains (Kaia) where\n * JPYC is still in development.\n */\nexport class JpycNotAvailableError extends Error {\n\tconstructor(chainId: number) {\n\t\tsuper(`JPYC is not yet deployed on chain ID ${chainId}.`);\n\t\tthis.name = \"JpycNotAvailableError\";\n\t}\n}\n\n/**\n * Returns the JPYC contract address for a kawasekit-supported chain.\n *\n * @param chainId - A {@link SupportedChainId}.\n * @returns The JPYC contract address on that chain.\n * @throws {JpycNotAvailableError} If JPYC is not live on the chain.\n *\n * @example\n * ```ts\n * import { getJpycAddress, polygonAmoy } from \"kawasekit\";\n *\n * const address = getJpycAddress(polygonAmoy.id);\n * ```\n */\nexport function getJpycAddress(chainId: SupportedChainId): Address {\n\tconst deployment = jpycDeployments[chainId];\n\tif (!deployment.isLive) {\n\t\tthrow new JpycNotAvailableError(chainId);\n\t}\n\treturn deployment.address;\n}\n\n/**\n * Minimal JPYC ABI: ERC-20 + EIP-3009 surface that kawasekit needs.\n *\n * Excludes permit / mint / blocklist / pause — kawasekit only reads balance,\n * sends `transfer()` via UserOp, and constructs / submits EIP-3009\n * authorizations. Bringing in the full FiatTokenV1 ABI would be wasted bytes.\n */\nexport const jpycAbi = [\n\t// ----- ERC-20 read -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"name\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"string\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"symbol\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"string\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"decimals\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"uint8\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"totalSupply\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"balanceOf\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [{ name: \"account\", type: \"address\" }],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"allowance\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [\n\t\t\t{ name: \"owner\", type: \"address\" },\n\t\t\t{ name: \"spender\", type: \"address\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t// ----- ERC-20 write -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transfer\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transferFrom\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"approve\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"spender\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t// ----- EIP-3009 -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transferWithAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"receiveWithAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"cancelAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"authorizationState\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t// ----- Events kawasekit needs to decode -----\n\t{\n\t\ttype: \"event\",\n\t\tname: \"Transfer\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\", indexed: true },\n\t\t\t{ name: \"to\", type: \"address\", indexed: true },\n\t\t\t{ name: \"value\", type: \"uint256\", indexed: false },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"Approval\",\n\t\tinputs: [\n\t\t\t{ name: \"owner\", type: \"address\", indexed: true },\n\t\t\t{ name: \"spender\", type: \"address\", indexed: true },\n\t\t\t{ name: \"value\", type: \"uint256\", indexed: false },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"AuthorizationUsed\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\", indexed: true },\n\t\t\t{ name: \"nonce\", type: \"bytes32\", indexed: true },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"AuthorizationCanceled\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\", indexed: true },\n\t\t\t{ name: \"nonce\", type: \"bytes32\", indexed: true },\n\t\t],\n\t},\n] as const;\n","/**\n * Typed errors thrown by the `kawasekit/x402` modules.\n *\n * Centralised so that consumers can `instanceof`-discriminate without importing\n * deep paths. Additional error classes are added here as the corresponding\n * modules come online (server, facilitator, …).\n *\n * @packageDocumentation\n */\n\n/**\n * Thrown when an x402 wire-format payload is malformed: invalid base64, invalid\n * JSON, or a value that cannot represent the expected schema.\n *\n * Carries the offending header / context name so callers can produce actionable\n * log lines without re-parsing the message string.\n *\n * @example\n * ```ts\n * import { decodePaymentSignatureHeader, X402InvalidPayloadError } from \"kawasekit\";\n *\n * try {\n * decodePaymentSignatureHeader(headerValue);\n * } catch (error) {\n * if (error instanceof X402InvalidPayloadError) {\n * console.warn(`reject ${error.context}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402InvalidPayloadError extends Error {\n\t/** Logical name of the payload that failed (e.g. `\"PAYMENT-SIGNATURE\"`). */\n\treadonly context: string;\n\t/** Short machine-readable reason code. */\n\treadonly reason: string;\n\n\tconstructor(context: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid ${context} payload: ${reason}`, options);\n\t\tthis.name = \"X402InvalidPayloadError\";\n\t\tthis.context = context;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown when an x402 SDK construction-time configuration is invalid: an\n * unknown `asset.kind`, a known asset id that kawasekit does not ship a\n * domain for, missing required fields on an `unsafeOverride`, etc.\n *\n * Distinct from {@link X402InvalidPayloadError} (which describes wire-format\n * problems): config errors are integrator bugs, not adversarial inputs.\n *\n * @example\n * ```ts\n * import { createX402PaymentSigner, X402InvalidConfigError } from \"kawasekit\";\n *\n * try {\n * createX402PaymentSigner({\n * network: \"testnet\",\n * account,\n * // @ts-expect-error — kind: \"foo\" is not a known kind\n * asset: { kind: \"foo\" },\n * });\n * } catch (error) {\n * if (error instanceof X402InvalidConfigError) {\n * console.error(`${error.field}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402InvalidConfigError extends Error {\n\t/** Logical name of the config field that failed (e.g. `\"asset\"`). */\n\treadonly field: string;\n\t/** Short machine-readable reason code. */\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid ${field} config: ${reason}`, options);\n\t\tthis.name = \"X402InvalidConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n","/**\n * Wire-format encoding for x402 v2 headers.\n *\n * Three pairs of `encode*` / `decode*` helpers, one per x402 v2 HTTP header:\n *\n * | Direction | Header | Payload type |\n * | ---------------- | ------------------- | -------------------------------- |\n * | server → client | `PAYMENT-REQUIRED` | {@link X402PaymentRequiredResponse} |\n * | client → server | `PAYMENT-SIGNATURE` | {@link X402PaymentPayload} |\n * | server → client | `PAYMENT-RESPONSE` | {@link X402SettlementResponse} |\n *\n * Encoding rules (match `@x402/core@2.13.0` byte-for-byte so kawasekit payloads\n * decode in any spec-compliant client / facilitator):\n *\n * - The payload is JSON-stringified, then UTF-8 → base64 encoded.\n * - **Standard base64** with `+` / `/` and `=` padding, **not** URL-safe base64.\n * (Header values flow through `Authorization`-style positions where `+` is\n * acceptable in the v2 spec.)\n * - The replacer used by `JSON.stringify` rewrites any stray `bigint` value to\n * its decimal string form, so kawasekit callers can hand a payload whose\n * `value` / `validAfter` / `validBefore` are bigints by mistake and the\n * encoder still produces a spec-conformant string — silent corruption\n * surfaces as a type error in `tsc`, not a runtime crash.\n *\n * Decoders are intentionally minimal: base64 syntax check + `JSON.parse` + a\n * \"must be a plain object\" sanity check. Schema-level validation lives one\n * layer up (in `server.ts` and `client.ts`) so that this module stays a small,\n * dependency-free wire codec.\n *\n * @packageDocumentation\n */\n\nimport { X402InvalidPayloadError } from \"./errors\";\nimport type {\n\tX402PaymentPayload,\n\tX402PaymentRequiredResponse,\n\tX402SettlementResponse,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// HTTP header names (x402 v2 transport spec)\n// ---------------------------------------------------------------------------\n\n/**\n * Name of the response header that carries the base64-encoded\n * {@link X402PaymentRequiredResponse} alongside the HTTP 402 status.\n */\nexport const X402_HEADER_PAYMENT_REQUIRED = \"PAYMENT-REQUIRED\" as const;\n\n/**\n * Name of the request header that carries the client's base64-encoded\n * {@link X402PaymentPayload}.\n *\n * Note: x402 v1 used `X-PAYMENT`. v2 drops the `X-` prefix. Servers may accept\n * both during transition; clients should send only this v2 name.\n */\nexport const X402_HEADER_PAYMENT_SIGNATURE = \"PAYMENT-SIGNATURE\" as const;\n\n/**\n * Name of the response header that carries the base64-encoded\n * {@link X402SettlementResponse} after a successful settlement.\n */\nexport const X402_HEADER_PAYMENT_RESPONSE = \"PAYMENT-RESPONSE\" as const;\n\n/**\n * Name of the optional request header that carries a reasoning-step idempotency\n * key (M5-1). Standard `Idempotency-Key` (IETF draft / Stripe-compatible). When\n * present, the x402 server deduplicates on this logical key; the EIP-3009 nonce\n * remains the on-chain fund backstop. See `docs/rfc/m5-1-reasoning-step-idempotency.md`.\n */\nexport const X402_HEADER_IDEMPOTENCY_KEY = \"Idempotency-Key\" as const;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n// Canonical base64 per RFC 4648 §4: encoded length is a multiple of 4 and the\n// only legal trailing forms are `XX==`, `XXX=`, or `XXXX` (no padding). The\n// outer prefix is zero or more 4-char groups; the optional inner alternation\n// matches a single final group of 4 chars or a properly padded 2-or-3 char\n// group. This shape rejects the non-canonical forms an adversary could try\n// to smuggle past the decoder — overlong padding (`X===`), misplaced padding\n// (`X=XX`), short tails (`XXX` with no `=`), or non-mod-4 lengths.\n//\n// See `docs/THREAT_MODEL.md` §6.7 for the M4 review trail and\n// `src/x402/encoding.test.ts` \"RFC 4648 canonical enforcement\" for the\n// adversarial corpus.\n/**\n * Strict RFC 4648 §4 canonical base64 matcher. Exported for the\n * property-based test in `encoding.test.ts` (Threat 1.7 / §6.7\n * regex-vs-decoder agreement); not intended as part of the public API.\n *\n * @internal\n */\nexport const BASE64_REGEX =\n\t/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})?$/;\n\nfunction bigIntReplacer(_key: string, value: unknown): unknown {\n\treturn typeof value === \"bigint\" ? value.toString() : value;\n}\n\nfunction stringifyBigIntSafe(value: unknown): string {\n\treturn JSON.stringify(value, bigIntReplacer);\n}\n\nfunction utf8ToBase64(input: string): string {\n\t// Cross-env: prefer `btoa` (browsers, Workers, Bun, modern Node 18+) and\n\t// fall back to `Buffer` for older Node where `btoa` was Latin-1-only.\n\tif (typeof globalThis.btoa === \"function\") {\n\t\tconst bytes = new TextEncoder().encode(input);\n\t\tlet binary = \"\";\n\t\tfor (const byte of bytes) {\n\t\t\tbinary += String.fromCharCode(byte);\n\t\t}\n\t\treturn globalThis.btoa(binary);\n\t}\n\treturn Buffer.from(input, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Internal helper exported for the regex-vs-decoder property-based test.\n * Not part of the public API.\n *\n * @internal\n */\nexport function base64ToUtf8(input: string): string {\n\tif (typeof globalThis.atob === \"function\") {\n\t\tconst binary = globalThis.atob(input);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i);\n\t\t}\n\t\treturn new TextDecoder(\"utf-8\").decode(bytes);\n\t}\n\treturn Buffer.from(input, \"base64\").toString(\"utf8\");\n}\n\nfunction decodeHeader<T>(headerName: string, headerValue: string): T {\n\tif (!BASE64_REGEX.test(headerValue)) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"header is not valid base64\");\n\t}\n\tlet json: string;\n\ttry {\n\t\tjson = base64ToUtf8(headerValue);\n\t} catch (cause) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"base64 decode failed\", { cause });\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(json);\n\t} catch (cause) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"decoded value is not valid JSON\", { cause });\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"decoded value is not a JSON object\");\n\t}\n\treturn parsed as T;\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-REQUIRED\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402PaymentRequiredResponse} as a base64 string suitable\n * for the `PAYMENT-REQUIRED` response header.\n *\n * @example\n * ```ts\n * import { encodePaymentRequiredHeader } from \"kawasekit\";\n *\n * const headerValue = encodePaymentRequiredHeader({\n * x402Version: 2,\n * resource: { url: \"https://api.example.com/data\" },\n * accepts: [],\n * });\n * res.setHeader(\"PAYMENT-REQUIRED\", headerValue);\n * ```\n */\nexport function encodePaymentRequiredHeader(payload: X402PaymentRequiredResponse): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-REQUIRED` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentRequiredHeader(headerValue: string): X402PaymentRequiredResponse {\n\treturn decodeHeader<X402PaymentRequiredResponse>(X402_HEADER_PAYMENT_REQUIRED, headerValue);\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-SIGNATURE\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402PaymentPayload} as a base64 string suitable for the\n * `PAYMENT-SIGNATURE` request header.\n *\n * @example\n * ```ts\n * import { encodePaymentSignatureHeader } from \"kawasekit\";\n *\n * const headerValue = encodePaymentSignatureHeader(paymentPayload);\n * await fetch(url, { headers: { \"PAYMENT-SIGNATURE\": headerValue } });\n * ```\n */\nexport function encodePaymentSignatureHeader(payload: X402PaymentPayload): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-SIGNATURE` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentSignatureHeader(headerValue: string): X402PaymentPayload {\n\treturn decodeHeader<X402PaymentPayload>(X402_HEADER_PAYMENT_SIGNATURE, headerValue);\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-RESPONSE\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402SettlementResponse} as a base64 string suitable for\n * the `PAYMENT-RESPONSE` response header.\n */\nexport function encodePaymentResponseHeader(payload: X402SettlementResponse): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-RESPONSE` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentResponseHeader(headerValue: string): X402SettlementResponse {\n\treturn decodeHeader<X402SettlementResponse>(X402_HEADER_PAYMENT_RESPONSE, headerValue);\n}\n","/**\n * Server-side builders for x402 v2 `PAYMENT-REQUIRED` payloads.\n *\n * `buildPaymentRequirements()` produces one accepted-payment entry; servers\n * call it once per (chain × asset) they want to advertise. `buildPaymentRequiredResponse()`\n * wraps a list of those entries into the full body the server returns alongside\n * an HTTP 402 status (typically also encoded into the `PAYMENT-REQUIRED`\n * header — see `src/x402/encoding.ts`).\n *\n * These factories live on the **server** side. The mirror-image client-side\n * factory is `createX402PaymentSigner()` in `client.ts`.\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport { JPYC_V2_ADDRESS } from \"../tokens/jpyc\";\nimport { X402InvalidPayloadError } from \"./errors\";\nimport type {\n\tX402PaymentRequiredResponse,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n} from \"./types\";\nimport { chainIdToX402Network, X402_VERSION } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Default value for `maxTimeoutSeconds` when {@link BuildPaymentRequirementsParams.maxTimeoutSeconds}\n * is not supplied. Matches the x402 spec example for short-lived authorizations.\n *\n * Increase to 300 (the client-side default) when targeting Polygon Amoy in the\n * M3 demo — bundler inclusion latency can spike above 60 s on testnet.\n */\nexport const X402_DEFAULT_MAX_TIMEOUT_SECONDS = 60;\n\n/** Default `extra` payload kawasekit injects when the asset is JPYC. */\nconst JPYC_EXACT_EVM_EXTRA = {\n\tassetTransferMethod: \"eip3009\",\n\tname: \"JPY Coin\",\n\tversion: \"1\",\n} as const;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Parameters for {@link buildPaymentRequirements}. */\nexport interface BuildPaymentRequirementsParams {\n\t/** Numeric chain ID; converted to the CAIP-2 `eip155:{chainId}` form. */\n\treadonly chainId: SupportedChainId;\n\t/** ERC-20 contract address of the token to be transferred. */\n\treadonly asset: Address;\n\t/** Recipient wallet address. */\n\treadonly payTo: Address;\n\t/** Atomic-unit amount. Accepts `bigint` (preferred) or a decimal `string`. */\n\treadonly amount: bigint | string;\n\t/**\n\t * Optional. Defaults to {@link X402_DEFAULT_MAX_TIMEOUT_SECONDS}.\n\t *\n\t * The maximum wall-clock time the client may take to produce a signed\n\t * payload after receiving this 402 response.\n\t */\n\treadonly maxTimeoutSeconds?: number;\n\t/**\n\t * Optional explicit `extra` payload. When omitted and `asset` is JPYC,\n\t * kawasekit injects a default `{ assetTransferMethod: \"eip3009\", name: \"JPY Coin\", version: \"1\" }`.\n\t * For non-JPYC assets `extra` is required (the client needs at least\n\t * `name` / `version` to reconstruct the EIP-712 domain).\n\t */\n\treadonly extra?: Record<string, unknown>;\n}\n\n/** Parameters for {@link buildPaymentRequiredResponse}. */\nexport interface BuildPaymentRequiredResponseParams {\n\t/** The protected resource the client is being asked to pay for. */\n\treadonly resource: X402ResourceInfo;\n\t/** One or more acceptable payment methods. */\n\treadonly accepts: readonly X402PaymentRequirements[];\n\t/** Optional human-readable reason for the 402, echoed in the response body. */\n\treadonly error?: string;\n\t/** Optional protocol extensions (advanced; rarely set). */\n\treadonly extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst UINT256_DECIMAL = /^(0|[1-9][0-9]*)$/;\n\nfunction coerceAmount(amount: bigint | string): string {\n\tif (typeof amount === \"bigint\") {\n\t\tif (amount <= 0n) {\n\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t`\\`amount\\` must be positive, got ${amount}`,\n\t\t\t);\n\t\t}\n\t\tif (amount > UINT256_MAX) {\n\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t`\\`amount\\` exceeds uint256, got ${amount}`,\n\t\t\t);\n\t\t}\n\t\treturn amount.toString();\n\t}\n\tif (!UINT256_DECIMAL.test(amount)) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`amount\\` must be a non-negative decimal string, got ${JSON.stringify(amount)}`,\n\t\t);\n\t}\n\tconst parsed = BigInt(amount);\n\tif (parsed === 0n) {\n\t\tthrow new X402InvalidPayloadError(\"PaymentRequirements\", \"`amount` must be positive\");\n\t}\n\tif (parsed > UINT256_MAX) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`amount\\` exceeds uint256, got ${amount}`,\n\t\t);\n\t}\n\treturn amount;\n}\n\nfunction assertAddress(value: string, field: string): Address {\n\tif (!isAddress(value, { strict: false })) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` is not a valid address: ${value}`,\n\t\t);\n\t}\n\treturn value as Address;\n}\n\nfunction resolveExtra(\n\tasset: Address,\n\texplicit: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (explicit) {\n\t\treturn explicit;\n\t}\n\tif (getAddress(asset) === getAddress(JPYC_V2_ADDRESS)) {\n\t\treturn { ...JPYC_EXACT_EVM_EXTRA };\n\t}\n\tthrow new X402InvalidPayloadError(\n\t\t\"PaymentRequirements\",\n\t\t\"`extra` is required for non-JPYC assets (clients need at least `name` and `version` for EIP-712 domain reconstruction)\",\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Builds one {@link X402PaymentRequirements} entry suitable for the `accepts`\n * array of a `PAYMENT-REQUIRED` response.\n *\n * @example Single-chain JPYC (defaults extra automatically)\n * ```ts\n * import { parseUnits } from \"viem\";\n * import {\n * buildPaymentRequirements,\n * JPYC_DECIMALS,\n * JPYC_V2_ADDRESS,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const requirements = buildPaymentRequirements({\n * chainId: polygonAmoy.id,\n * asset: JPYC_V2_ADDRESS,\n * payTo: \"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\",\n * amount: parseUnits(\"0.001\", JPYC_DECIMALS),\n * });\n * ```\n */\nexport function buildPaymentRequirements(\n\tparams: BuildPaymentRequirementsParams,\n): X402PaymentRequirements {\n\tconst asset = assertAddress(params.asset, \"asset\");\n\tconst payTo = assertAddress(params.payTo, \"payTo\");\n\tconst amount = coerceAmount(params.amount);\n\tconst maxTimeoutSeconds = params.maxTimeoutSeconds ?? X402_DEFAULT_MAX_TIMEOUT_SECONDS;\n\tif (maxTimeoutSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`maxTimeoutSeconds\\` must be positive, got ${maxTimeoutSeconds}`,\n\t\t);\n\t}\n\tconst extra = resolveExtra(asset, params.extra);\n\n\treturn {\n\t\tscheme: \"exact\",\n\t\tnetwork: chainIdToX402Network(params.chainId),\n\t\tamount,\n\t\tasset,\n\t\tpayTo,\n\t\tmaxTimeoutSeconds,\n\t\textra,\n\t};\n}\n\n/**\n * Builds the full {@link X402PaymentRequiredResponse} body the server returns\n * alongside HTTP 402.\n *\n * @example\n * ```ts\n * import {\n * buildPaymentRequiredResponse,\n * buildPaymentRequirements,\n * encodePaymentRequiredHeader,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const response = buildPaymentRequiredResponse({\n * resource: { url: \"https://api.example.com/weather\", description: \"Real-time weather\" },\n * accepts: [\n * buildPaymentRequirements({ chainId: polygonAmoy.id, ... }),\n * ],\n * error: \"PAYMENT-SIGNATURE header is required\",\n * });\n *\n * res.statusCode = 402;\n * res.setHeader(\"PAYMENT-REQUIRED\", encodePaymentRequiredHeader(response));\n * res.setHeader(\"content-type\", \"application/json\");\n * res.end(JSON.stringify(response));\n * ```\n */\nexport function buildPaymentRequiredResponse(\n\tparams: BuildPaymentRequiredResponseParams,\n): X402PaymentRequiredResponse {\n\tif (params.accepts.length === 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequired\",\n\t\t\t\"`accepts` must contain at least one PaymentRequirements entry\",\n\t\t);\n\t}\n\t// Object literal is built conditionally so optional fields are *absent* (not\n\t// `undefined`) when not provided — required by `exactOptionalPropertyTypes`.\n\tconst base: Pick<X402PaymentRequiredResponse, \"x402Version\" | \"resource\" | \"accepts\"> = {\n\t\tx402Version: X402_VERSION,\n\t\tresource: params.resource,\n\t\taccepts: params.accepts,\n\t};\n\tif (params.error !== undefined && params.extensions !== undefined) {\n\t\treturn { ...base, error: params.error, extensions: params.extensions };\n\t}\n\tif (params.error !== undefined) {\n\t\treturn { ...base, error: params.error };\n\t}\n\tif (params.extensions !== undefined) {\n\t\treturn { ...base, extensions: params.extensions };\n\t}\n\treturn base;\n}\n","/**\n * `createX402Handler()` — framework-agnostic x402 v2 resource-server adapter.\n *\n * The returned function maps any WHATWG `Request` to a `Response`, gating the\n * caller-supplied inner handler behind an x402 payment flow:\n *\n * 1. Compute requirements for the request (via `requirementsFor`).\n * `null` / empty array → no payment, pass through to inner handler.\n * 2. Look for the `PAYMENT-SIGNATURE` header. If missing or malformed →\n * `402 Payment Required` with a `PAYMENT-REQUIRED` header carrying the\n * encoded {@link X402PaymentRequiredResponse}.\n * 3. The client's `paymentPayload.accepted` must match one entry in our\n * requirements list (scheme / network / amount / asset / payTo).\n * 4. Call `facilitator.verify`. On failure → 402 with a reason.\n * 5. Call `facilitator.settle`. On failure → 402 with a reason. On success →\n * invoke the inner handler, attach the `PAYMENT-RESPONSE` header, return.\n *\n * Because the contract is `Request → Response`, the handler runs unchanged on\n * Node (via `@hono/node-server` or a hand-rolled adapter), Bun, Deno, Cloudflare\n * Workers, and Vercel Edge.\n *\n * @packageDocumentation\n */\n\nimport type { Hex } from \"viem\";\nimport { getAddress } from \"viem\";\nimport {\n\tcreateInMemoryIdempotencyStore,\n\ttype IdempotencyLease,\n\ttype IdempotencyLookupResult,\n\ttype IdempotencyRecord,\n\ttype IdempotencyResponseSnapshot,\n\ttype IdempotencyStore,\n\tKAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n} from \"../idempotency\";\nimport {\n\textractAcceptedNetworks,\n\tinvokeHookSafely,\n\ttype ObservabilityHooks,\n\ttype PaymentAcceptedEvent,\n\ttype PaymentRequiredEvent,\n} from \"../observability/hooks\";\nimport {\n\tdecodePaymentSignatureHeader,\n\tencodePaymentRequiredHeader,\n\tencodePaymentResponseHeader,\n\tX402_HEADER_IDEMPOTENCY_KEY,\n\tX402_HEADER_PAYMENT_REQUIRED,\n\tX402_HEADER_PAYMENT_RESPONSE,\n\tX402_HEADER_PAYMENT_SIGNATURE,\n} from \"./encoding\";\nimport { X402InvalidPayloadError } from \"./errors\";\nimport { buildPaymentRequiredResponse } from \"./payment-requirements\";\nimport type {\n\tFacilitator,\n\tX402PaymentPayload,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n\tX402SettlementResponse,\n} from \"./types\";\nimport { X402_VERSION } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Context passed to the inner handler **after** a payment has been verified\n * and settled. `null` when the request bypassed the payment flow because\n * `requirementsFor` returned `null` / `[]`.\n */\nexport interface X402HandlerContext {\n\t/** The client's signed payment payload. */\n\treadonly paymentPayload: X402PaymentPayload;\n\t/** The matching requirements entry the client targeted. */\n\treadonly matchedRequirements: X402PaymentRequirements;\n\t/** Facilitator's settlement response (broadcast already happened). */\n\treadonly settlement: X402SettlementResponse;\n}\n\n/**\n * The inner business-logic handler. Receives the same `Request` plus a context\n * that is present when a payment was made for this request, and `null`\n * otherwise (pass-through case).\n */\nexport type X402InnerHandler = (\n\trequest: Request,\n\tcontext: X402HandlerContext | null,\n) => Promise<Response> | Response;\n\n/** Parameters for {@link createX402Handler}. */\nexport interface CreateX402HandlerParams {\n\t/** Facilitator that performs verify and settle (self or HTTP-proxied). */\n\treadonly facilitator: Facilitator;\n\t/**\n\t * Returns the {@link X402PaymentRequirements} that apply to this request.\n\t *\n\t * - Return one or more entries to require payment (client picks one).\n\t * - Return `null` or `[]` to skip the payment flow entirely for this\n\t * request — the inner handler is invoked with `context = null`.\n\t */\n\treadonly requirementsFor: (\n\t\trequest: Request,\n\t) =>\n\t\t| Promise<readonly X402PaymentRequirements[] | null>\n\t\t| readonly X402PaymentRequirements[]\n\t\t| null;\n\t/** The protected business-logic handler. Invoked after settlement. */\n\treadonly handler: X402InnerHandler;\n\t/**\n\t * Optional builder for the {@link X402ResourceInfo} echoed in the 402\n\t * response. Defaults to `{ url: request.url }`.\n\t */\n\treadonly resourceFor?: (request: Request) => Promise<X402ResourceInfo> | X402ResourceInfo;\n\t/**\n\t * Optional observability callbacks. The handler emits `onPaymentRequired`\n\t * each time it returns a 402, and `onPaymentAccepted` after a settled\n\t * payment unlocks the inner handler. Hooks are fire-and-forget — see\n\t * {@link ObservabilityHooks}.\n\t */\n\treadonly hooks?: ObservabilityHooks;\n\t/**\n\t * Reasoning-step idempotency (M5-1, Half A). **Default-on**: when omitted, an\n\t * in-memory store deduplicates re-sent / concurrent paid requests — replaying\n\t * the cached response and closing the verify→settle TOCTOU. Pass\n\t * `{ store: \"none\" }` to disable, or a shared store (Redis/SQL adapter) for\n\t * multi-replica deployments (the in-memory default is single-process).\n\t * Fund-correctness never depends on this store — the on-chain EIP-3009 nonce\n\t * is the backstop.\n\t */\n\treadonly idempotency?: IdempotencyServerConfig;\n}\n\n/** Server-side idempotency configuration (M5-1). See {@link CreateX402HandlerParams.idempotency}. */\nexport interface IdempotencyServerConfig {\n\t/** The store, or `\"none\"` to disable. Default: a fresh in-memory bounded LRU. */\n\treadonly store?: IdempotencyStore | \"none\";\n\t/**\n\t * What to do when a concurrent request holds the in-flight lease for the same\n\t * key. `\"reject\"` (default) returns a `payment_in_progress` 402 (the client\n\t * retries and gets the cached result); `\"await\"` polls briefly for the twin\n\t * to complete, then replays its response.\n\t */\n\treadonly inFlight?: \"await\" | \"reject\";\n\t/** Max captured response body size for replay, in bytes. Default 65536 (64 KiB). */\n\treadonly maxSnapshotBytes?: number;\n\t/** Fallback record TTL in seconds when the authorization `validBefore` is unreadable. Default 86400. */\n\treadonly fallbackTtlSeconds?: number;\n}\n\n/** The function returned by {@link createX402Handler}. */\nexport type X402RequestHandler = (request: Request) => Promise<Response>;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultResource(request: Request): X402ResourceInfo {\n\treturn { url: request.url };\n}\n\nfunction isSameRequirements(\n\toffered: X402PaymentRequirements,\n\tchosen: X402PaymentRequirements,\n): boolean {\n\treturn (\n\t\toffered.scheme === chosen.scheme &&\n\t\toffered.network === chosen.network &&\n\t\toffered.amount === chosen.amount &&\n\t\tgetAddress(offered.asset) === getAddress(chosen.asset) &&\n\t\tgetAddress(offered.payTo) === getAddress(chosen.payTo)\n\t);\n}\n\nasync function paymentRequired(\n\trequest: Request,\n\trequirements: readonly X402PaymentRequirements[],\n\tresourceFor: ((r: Request) => Promise<X402ResourceInfo> | X402ResourceInfo) | undefined,\n\terror: string,\n): Promise<Response> {\n\tconst resource = resourceFor ? await resourceFor(request) : defaultResource(request);\n\tconst body = buildPaymentRequiredResponse({ resource, accepts: requirements, error });\n\tconst headers = new Headers({ \"content-type\": \"application/json\" });\n\theaders.set(X402_HEADER_PAYMENT_REQUIRED, encodePaymentRequiredHeader(body));\n\treturn new Response(JSON.stringify(body), { status: 402, headers });\n}\n\nfunction internalError(reason: string, cause: unknown): Response {\n\tconst message = cause instanceof Error ? cause.message : String(cause);\n\treturn new Response(JSON.stringify({ error: reason, message }), {\n\t\tstatus: 500,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t});\n}\n\nfunction withPaymentResponseHeader(\n\tinnerResponse: Response,\n\tsettlement: X402SettlementResponse,\n): Response {\n\tconst headers = new Headers(innerResponse.headers);\n\theaders.set(X402_HEADER_PAYMENT_RESPONSE, encodePaymentResponseHeader(settlement));\n\treturn new Response(innerResponse.body, {\n\t\tstatus: innerResponse.status,\n\t\tstatusText: innerResponse.statusText,\n\t\theaders,\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Idempotency (M5-1) helpers\n// ---------------------------------------------------------------------------\n\n/** Credential-safe header allowlist preserved in a replayed response. */\nconst SNAPSHOT_HEADER_ALLOWLIST = [\"content-type\", X402_HEADER_PAYMENT_RESPONSE];\nconst IDEMPOTENCY_REPLAYED_HEADER = \"Idempotency-Replayed\";\nconst DEFAULT_MAX_SNAPSHOT_BYTES = 64 * 1024;\nconst DEFAULT_FALLBACK_TTL_SECONDS = 86_400;\n\ninterface ResolvedIdempotency {\n\treadonly store: IdempotencyStore;\n\treadonly inFlight: \"await\" | \"reject\";\n\treadonly maxSnapshotBytes: number;\n\treadonly fallbackTtlSeconds: number;\n}\n\n/** Resolve the (default-on) idempotency config once per handler construction. */\nfunction resolveIdempotency(\n\tconfig: IdempotencyServerConfig | undefined,\n): ResolvedIdempotency | null {\n\tif (config?.store === \"none\") {\n\t\treturn null;\n\t}\n\treturn {\n\t\tstore: config?.store ?? createInMemoryIdempotencyStore(),\n\t\tinFlight: config?.inFlight ?? \"reject\",\n\t\tmaxSnapshotBytes: config?.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES,\n\t\tfallbackTtlSeconds: config?.fallbackTtlSeconds ?? DEFAULT_FALLBACK_TTL_SECONDS,\n\t};\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const b of bytes) {\n\t\tbinary += String.fromCharCode(b);\n\t}\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n\tconst binary = atob(b64);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i += 1) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n\n/** Defensively read the EIP-3009 nonce + validBefore from an opaque payload. */\nfunction readAuthorization(\n\tpayload: X402PaymentPayload,\n): { readonly nonce: string; readonly validBefore: bigint } | null {\n\tconst inner = payload.payload;\n\tif (typeof inner !== \"object\" || inner === null) {\n\t\treturn null;\n\t}\n\tconst auth = (inner as { authorization?: unknown }).authorization;\n\tif (typeof auth !== \"object\" || auth === null) {\n\t\treturn null;\n\t}\n\tconst a = auth as { nonce?: unknown; validBefore?: unknown };\n\tif (typeof a.nonce !== \"string\" || a.nonce === \"\") {\n\t\treturn null;\n\t}\n\tconst validBefore =\n\t\ttypeof a.validBefore === \"string\" && /^[0-9]+$/.test(a.validBefore)\n\t\t\t? BigInt(a.validBefore)\n\t\t\t: 0n;\n\treturn { nonce: a.nonce, validBefore };\n}\n\n/**\n * The server dedup key: the client `Idempotency-Key` header when present (the\n * logical reasoning-step key, working even for signers that cannot derive a\n * nonce), else the EIP-3009 nonce — both namespaced by (network, payTo, asset)\n * for cross-tenant isolation. `null` ⇒ no key can be formed; dedup is skipped\n * (the on-chain nonce still backstops fund-correctness).\n */\nfunction computeServerKey(\n\trequest: Request,\n\trequirements: X402PaymentRequirements,\n\tauth: { readonly nonce: string } | null,\n): string | null {\n\tconst header = request.headers.get(X402_HEADER_IDEMPOTENCY_KEY);\n\tlet material: string;\n\tif (header !== null && header !== \"\") {\n\t\tmaterial = `hdr:${header}`;\n\t} else if (auth !== null) {\n\t\tmaterial = `nonce:${auth.nonce}`;\n\t} else {\n\t\treturn null;\n\t}\n\treturn JSON.stringify([\n\t\trequirements.network,\n\t\tgetAddress(requirements.payTo),\n\t\tgetAddress(requirements.asset),\n\t\tmaterial,\n\t]);\n}\n\n/**\n * Snapshot a response for replay, reading from a clone so the original body\n * stays intact. `undefined` if the body exceeds `maxBytes` (the record then\n * stores only the settlement for a minimal replay).\n */\nasync function snapshotResponse(\n\tresponse: Response,\n\tmaxBytes: number,\n): Promise<IdempotencyResponseSnapshot | undefined> {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength !== null && Number(contentLength) > maxBytes) {\n\t\treturn undefined;\n\t}\n\tconst buffer = await response.clone().arrayBuffer();\n\tif (buffer.byteLength > maxBytes) {\n\t\treturn undefined;\n\t}\n\tconst headers: Array<readonly [string, string]> = [];\n\tfor (const name of SNAPSHOT_HEADER_ALLOWLIST) {\n\t\tconst value = response.headers.get(name);\n\t\tif (value !== null) {\n\t\t\theaders.push([name, value]);\n\t\t}\n\t}\n\treturn { status: response.status, headers, bodyBase64: bytesToBase64(new Uint8Array(buffer)) };\n}\n\n/** Rebuild a response from a completed record (replay path), tagged for clients. */\nfunction replayResponse(record: IdempotencyRecord): Response {\n\tconst snapshot = record.responseSnapshot;\n\tif (snapshot !== undefined) {\n\t\tconst headers = new Headers();\n\t\tfor (const [name, value] of snapshot.headers) {\n\t\t\theaders.set(name, value);\n\t\t}\n\t\theaders.set(IDEMPOTENCY_REPLAYED_HEADER, \"true\");\n\t\treturn new Response(base64ToBytes(snapshot.bodyBase64), { status: snapshot.status, headers });\n\t}\n\tconst headers = new Headers({ [IDEMPOTENCY_REPLAYED_HEADER]: \"true\" });\n\theaders.set(\n\t\tX402_HEADER_PAYMENT_RESPONSE,\n\t\tencodePaymentResponseHeader({\n\t\t\tsuccess: true,\n\t\t\ttransaction: record.txHash,\n\t\t\tnetwork: record.network,\n\t\t\tpayer: record.payer,\n\t\t\tamount: record.amount,\n\t\t}),\n\t);\n\treturn new Response(null, { status: 200, headers });\n}\n\nfunction buildRecord(\n\tkey: string,\n\tsettlement: X402SettlementResponse,\n\trequirements: X402PaymentRequirements,\n\tvalidBefore: bigint,\n\tfallbackTtlSeconds: number,\n\tsnapshot: IdempotencyResponseSnapshot | undefined,\n): IdempotencyRecord | null {\n\tif (settlement.transaction === \"\" || settlement.payer === undefined) {\n\t\treturn null;\n\t}\n\tconst nowSec = BigInt(Math.floor(Date.now() / 1000));\n\tconst expiresAt = validBefore > nowSec ? validBefore : nowSec + BigInt(fallbackTtlSeconds);\n\treturn {\n\t\tkawasekitVersion: KAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n\t\tkey,\n\t\t// settlement.transaction is the on-chain tx hash (0x-hex) the facilitator broadcast.\n\t\ttxHash: settlement.transaction as Hex,\n\t\tpayer: settlement.payer,\n\t\tamount: settlement.amount ?? requirements.amount,\n\t\tnetwork: requirements.network,\n\t\t...(snapshot !== undefined ? { responseSnapshot: snapshot } : {}),\n\t\texpiresAt,\n\t};\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tsetTimeout(resolve, ms);\n\t});\n}\n\nconst IN_FLIGHT_POLL_MS = 100;\nconst IN_FLIGHT_MAX_POLLS = 50; // ~5s bounded wait for the \"await\" policy\n\n/** Release an owned in-flight lease so the step can be retried (best-effort). */\nasync function releaseLease(\n\tidem: ResolvedIdempotency | null,\n\tkey: string | null,\n\tlease: IdempotencyLease | null,\n): Promise<void> {\n\tif (idem !== null && key !== null && lease !== null) {\n\t\ttry {\n\t\t\tawait idem.store.abandon(key, lease);\n\t\t} catch {\n\t\t\t// best-effort: the lease will also expire on its own (crash-recovery TTL).\n\t\t}\n\t}\n}\n\n/**\n * For the `\"await\"` in-flight policy, poll briefly for a concurrent twin to\n * complete. Returns its record to replay, or `null` to fall back to the reject\n * path (twin still running past the budget, or it died and freed the slot).\n */\nasync function resolveInFlight(\n\tidem: ResolvedIdempotency,\n\tkey: string,\n): Promise<IdempotencyRecord | null> {\n\tif (idem.inFlight !== \"await\") {\n\t\treturn null;\n\t}\n\tfor (let i = 0; i < IN_FLIGHT_MAX_POLLS; i += 1) {\n\t\tawait sleep(IN_FLIGHT_POLL_MS);\n\t\tlet lookup: IdempotencyLookupResult;\n\t\ttry {\n\t\t\tlookup = await idem.store.begin(key);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tif (lookup.status === \"completed\") {\n\t\t\treturn lookup.record;\n\t\t}\n\t\tif (lookup.status === \"fresh\") {\n\t\t\t// The twin died and we now hold the lease; release it and let the\n\t\t\t// caller reject (the client retries and settles cleanly).\n\t\t\tawait releaseLease(idem, key, lookup.lease);\n\t\t\treturn null;\n\t\t}\n\t\t// still in_flight → keep polling\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Builds an {@link X402RequestHandler} that wraps `params.handler` with the\n * x402 payment flow.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { parseUnits } from \"viem\";\n * import {\n * buildPaymentRequirements,\n * createSelfFacilitator,\n * createX402Handler,\n * JPYC_DECIMALS,\n * JPYC_V2_ADDRESS,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const handler = createX402Handler({\n * facilitator: createSelfFacilitator({ walletClient, publicClient }),\n * requirementsFor: (req) =>\n * new URL(req.url).pathname.startsWith(\"/weather\")\n * ? [buildPaymentRequirements({\n * chainId: polygonAmoy.id,\n * asset: JPYC_V2_ADDRESS,\n * payTo: \"0x...\",\n * amount: parseUnits(\"0.001\", JPYC_DECIMALS),\n * })]\n * : null,\n * handler: async (req) => new Response(JSON.stringify({ weather: \"sunny\" }), {\n * headers: { \"content-type\": \"application/json\" },\n * }),\n * });\n *\n * // Mount on any framework that exposes WHATWG Request → Response.\n * ```\n */\nexport function createX402Handler(params: CreateX402HandlerParams): X402RequestHandler {\n\tconst { facilitator, requirementsFor, handler, resourceFor, hooks } = params;\n\t// Resolved ONCE so the in-memory store persists across requests (the Hono\n\t// adapter rebuilds the handler per request, so this must live in the closure).\n\tconst idempotency = resolveIdempotency(params.idempotency);\n\n\treturn async function x402Handler(request: Request): Promise<Response> {\n\t\tconst startedAtMs = Date.now();\n\n\t\tconst emitPaymentRequired = (\n\t\t\treqs: readonly X402PaymentRequirements[],\n\t\t\terror: string,\n\t\t): Promise<Response> => {\n\t\t\tconst event: PaymentRequiredEvent = {\n\t\t\t\tkind: \"payment_required\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl: request.url,\n\t\t\t\tacceptedNetworks: extractAcceptedNetworks(reqs),\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onPaymentRequired, event);\n\t\t\treturn paymentRequired(request, reqs, resourceFor, error);\n\t\t};\n\n\t\t// 1. Resolve requirements (or pass through)\n\t\tlet requirements: readonly X402PaymentRequirements[] | null;\n\t\ttry {\n\t\t\trequirements = await requirementsFor(request);\n\t\t} catch (cause) {\n\t\t\treturn internalError(\"requirements_resolution_failed\", cause);\n\t\t}\n\t\tif (requirements === null || requirements.length === 0) {\n\t\t\treturn handler(request, null);\n\t\t}\n\n\t\t// 2. Read the PAYMENT-SIGNATURE header\n\t\tconst headerValue = request.headers.get(X402_HEADER_PAYMENT_SIGNATURE);\n\t\tif (headerValue === null || headerValue === \"\") {\n\t\t\treturn emitPaymentRequired(requirements, \"PAYMENT-SIGNATURE header is required\");\n\t\t}\n\n\t\t// 3. Decode the payment payload\n\t\tlet paymentPayload: X402PaymentPayload;\n\t\ttry {\n\t\t\tpaymentPayload = decodePaymentSignatureHeader(headerValue);\n\t\t} catch (cause) {\n\t\t\tconst reason =\n\t\t\t\tcause instanceof X402InvalidPayloadError\n\t\t\t\t\t? cause.reason\n\t\t\t\t\t: \"invalid PAYMENT-SIGNATURE header\";\n\t\t\treturn emitPaymentRequired(requirements, reason);\n\t\t}\n\n\t\t// 4. Match chosen requirements to an offered entry\n\t\tconst matchedRequirements = requirements.find((offered) =>\n\t\t\tisSameRequirements(offered, paymentPayload.accepted),\n\t\t);\n\t\tif (!matchedRequirements) {\n\t\t\treturn emitPaymentRequired(\n\t\t\t\trequirements,\n\t\t\t\t\"paymentPayload.accepted does not match any offered requirements\",\n\t\t\t);\n\t\t}\n\n\t\t// 5. Verify\n\t\tlet verifyResult: Awaited<ReturnType<Facilitator[\"verify\"]>>;\n\t\ttry {\n\t\t\tverifyResult = await facilitator.verify({\n\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\tpaymentPayload,\n\t\t\t\tpaymentRequirements: matchedRequirements,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\treturn internalError(\"facilitator_verify_failed\", cause);\n\t\t}\n\t\tif (!verifyResult.isValid) {\n\t\t\treturn emitPaymentRequired(requirements, verifyResult.invalidReason ?? \"verify failed\");\n\t\t}\n\n\t\t// 5b. Reasoning-step idempotency gate (M5-1, Half A). Runs AFTER verify so a\n\t\t// cached response is only released against a re-verified authorization.\n\t\tconst auth = readAuthorization(paymentPayload);\n\t\tconst idemKey =\n\t\t\tidempotency !== null ? computeServerKey(request, matchedRequirements, auth) : null;\n\t\tlet lease: IdempotencyLease | null = null;\n\t\tif (idempotency !== null && idemKey !== null) {\n\t\t\tlet lookup: IdempotencyLookupResult;\n\t\t\ttry {\n\t\t\t\tlookup = await idempotency.store.begin(idemKey);\n\t\t\t} catch (cause) {\n\t\t\t\treturn internalError(\"idempotency_store_failed\", cause);\n\t\t\t}\n\t\t\tif (lookup.status === \"completed\") {\n\t\t\t\treturn replayResponse(lookup.record);\n\t\t\t}\n\t\t\tif (lookup.status === \"in_flight\") {\n\t\t\t\tconst awaited = await resolveInFlight(idempotency, idemKey);\n\t\t\t\tif (awaited !== null) {\n\t\t\t\t\treturn replayResponse(awaited);\n\t\t\t\t}\n\t\t\t\treturn emitPaymentRequired(requirements, \"payment_in_progress\");\n\t\t\t}\n\t\t\tlease = lookup.lease;\n\t\t}\n\n\t\t// 6. Settle\n\t\tlet settleResult: Awaited<ReturnType<Facilitator[\"settle\"]>>;\n\t\ttry {\n\t\t\tsettleResult = await facilitator.settle({\n\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\tpaymentPayload,\n\t\t\t\tpaymentRequirements: matchedRequirements,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\treturn internalError(\"facilitator_settle_failed\", cause);\n\t\t}\n\t\tif (!settleResult.success) {\n\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\treturn emitPaymentRequired(requirements, settleResult.errorReason ?? \"settle failed\");\n\t\t}\n\n\t\t// 7. Settled — emit onPaymentAccepted then invoke inner handler.\n\t\tif (settleResult.payer !== undefined) {\n\t\t\tconst acceptedEvent: PaymentAcceptedEvent = {\n\t\t\t\tkind: \"payment_accepted\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl: request.url,\n\t\t\t\tpayer: settleResult.payer,\n\t\t\t\tamount: settleResult.amount ?? matchedRequirements.amount,\n\t\t\t\tnetwork: matchedRequirements.network,\n\t\t\t\ttransaction: settleResult.transaction as Hex,\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onPaymentAccepted, acceptedEvent);\n\t\t}\n\n\t\t// Inner handler errors propagate — settlement has already happened.\n\t\tconst context: X402HandlerContext = {\n\t\t\tpaymentPayload,\n\t\t\tmatchedRequirements,\n\t\t\tsettlement: settleResult,\n\t\t};\n\t\tconst innerResponse = await handler(request, context);\n\t\tconst finalResponse = withPaymentResponseHeader(innerResponse, settleResult);\n\n\t\t// 7b. Record the settled response for replay-on-duplicate (best-effort —\n\t\t// fund-correctness is guaranteed on-chain regardless of the store).\n\t\tif (idempotency !== null && idemKey !== null && lease !== null) {\n\t\t\tconst snapshot = await snapshotResponse(finalResponse, idempotency.maxSnapshotBytes);\n\t\t\tconst record = buildRecord(\n\t\t\t\tidemKey,\n\t\t\t\tsettleResult,\n\t\t\t\tmatchedRequirements,\n\t\t\t\tauth?.validBefore ?? 0n,\n\t\t\t\tidempotency.fallbackTtlSeconds,\n\t\t\t\tsnapshot,\n\t\t\t);\n\t\t\tif (record !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tawait idempotency.store.complete(idemKey, record, lease);\n\t\t\t\t} catch {\n\t\t\t\t\t// Completing the cache is best-effort; on-chain nonce is the backstop.\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\t}\n\t\t}\n\t\treturn finalResponse;\n\t};\n}\n"]}
|