uvd-x402-sdk 2.75.0 → 2.77.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.
- package/README.md +145 -1
- package/dist/backend/index.d.mts +348 -52
- package/dist/backend/index.d.ts +348 -52
- package/dist/backend/index.js +470 -235
- package/dist/backend/index.js.map +1 -1
- package/dist/backend/index.mjs +459 -236
- package/dist/backend/index.mjs.map +1 -1
- package/dist/index.d.mts +44 -6
- package/dist/index.d.ts +44 -6
- package/dist/index.js +244 -39
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +234 -40
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/backend/facilitator-error.ts +355 -0
- package/src/backend/index.ts +536 -263
- package/src/dx402.ts +130 -10
- package/src/index.ts +17 -0
package/dist/index.d.mts
CHANGED
|
@@ -4,7 +4,7 @@ export { A as AlgorandPaymentPayload, C as CAIP2_IDENTIFIERS, a as CAIP2_TO_CHAI
|
|
|
4
4
|
import { S as SigningWalletAdapter } from './wallet-0cX9Pw2F.mjs';
|
|
5
5
|
export { E as EIP3009Authorization, a as EIP3009Params } from './wallet-0cX9Pw2F.mjs';
|
|
6
6
|
export { E as EnvKeyAdapter, O as OWSWallet, a as OWSWalletAdapter } from './ows-CYIVd4xO.mjs';
|
|
7
|
-
export { FacilitatorClient, FacilitatorClientOptions, HonoMiddlewareOptions, PaymentAcceptance, PaymentMiddlewareOptions, PaymentPayloadV2, PaymentRequirementsV2, ResourceInfoV2, SettleRequestV2, VerifiedPaymentState, VerifyRequestV2, X402_CORS_HEADERS, X402_HEADER_NAMES, buildPaymentRequirements, buildSettleRequest, buildSettleRequestV2, buildVerifyRequest, buildVerifyRequestV2, create402Response, createHonoMiddleware, createPaymentMiddleware, extractPaymentFromHeaders, getCorsHeaders } from './backend/index.mjs';
|
|
7
|
+
export { AMBIGUOUS_LEASE_REASONS, DEFAULT_FACILITATOR_RETRIES, DEFAULT_RETRY_AFTER_SECONDS, FacilitatorClient, FacilitatorClientOptions, FacilitatorErrorInfo, FacilitatorFailureFields, FacilitatorFetchOptions, HonoMiddlewareOptions, MAX_RETRY_AFTER_SECONDS, PaymentAcceptance, PaymentMiddlewareOptions, PaymentPayloadV2, PaymentRequirementsV2, REPLAYABLE_LEASE_REASONS, ResourceInfoV2, SettleRequestV2, VerifiedPaymentState, VerifyRequestV2, WRITER_LEASE_REASONS, WriterLeaseReason, X402_CORS_HEADERS, X402_HEADER_NAMES, buildPaymentRequirements, buildSettleRequest, buildSettleRequestV2, buildVerifyRequest, buildVerifyRequestV2, create402Response, createHonoMiddleware, createPaymentMiddleware, extractPaymentFromHeaders, facilitatorFetch, getCorsHeaders, isAmbiguousLeaseReason, isReplayableLeaseReason, parseRetryAfterSeconds, readFacilitatorError } from './backend/index.mjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* DX402 `durable-evidence`: recover a paid response after the fact.
|
|
@@ -303,6 +303,41 @@ interface AnchorOptions {
|
|
|
303
303
|
* anchor for the same payment supersedes it.
|
|
304
304
|
*/
|
|
305
305
|
sign?: (digest: Uint8Array) => string | Promise<string>;
|
|
306
|
+
/**
|
|
307
|
+
* `(sealedBytes) => pointer`. Bring your own storage.
|
|
308
|
+
*
|
|
309
|
+
* Without this the sealed envelope travels **inside** the anchor request and
|
|
310
|
+
* the facilitator hosts it, which is the easy path and stays the default. With
|
|
311
|
+
* it, the SDK still seals exactly as before -- the buyer has to be able to
|
|
312
|
+
* decrypt, so the sealing is not optional -- then hands you the ciphertext,
|
|
313
|
+
* you write it wherever you keep durable bytes, and you return the pointer
|
|
314
|
+
* that addresses it. The request then carries only that pointer, so the
|
|
315
|
+
* ciphertext never travels through the anchor call and
|
|
316
|
+
* {@link ANCHOR_MAX_REQUEST_BYTES} does not apply to your body.
|
|
317
|
+
*
|
|
318
|
+
* A callable rather than a precomputed pointer, for the same reason
|
|
319
|
+
* {@link AnchorOptions.sign} is one: the SDK must seal first, and only then
|
|
320
|
+
* can anything be uploaded. Handing in a pointer computed in advance would
|
|
321
|
+
* mean addressing bytes that do not exist yet.
|
|
322
|
+
*
|
|
323
|
+
* The returned pointer is what the buyer will dereference, so it must be
|
|
324
|
+
* readable by them -- see {@link dereferencePointer} for the schemes the SDK
|
|
325
|
+
* resolves out of the box. It is also bound into the seller signature.
|
|
326
|
+
*
|
|
327
|
+
* **It is never allowed to break the sale.** If it throws or returns
|
|
328
|
+
* something unusable, the anchor degrades to a skip and the payment is
|
|
329
|
+
* untouched.
|
|
330
|
+
*/
|
|
331
|
+
upload?: (sealed: Uint8Array) => string | Promise<string>;
|
|
332
|
+
/**
|
|
333
|
+
* Which storage family the pointer belongs to: `s3`, `ipfs` or `arweave`.
|
|
334
|
+
*
|
|
335
|
+
* Defaults to `s3`, and in {@link AnchorOptions.upload} mode it is inferred
|
|
336
|
+
* from the pointer's scheme when you do not say. Distinct from `storage`,
|
|
337
|
+
* which names one of the FACILITATOR's own offers and is meaningless when you
|
|
338
|
+
* supply the bytes yourself.
|
|
339
|
+
*/
|
|
340
|
+
backend?: 's3' | 'ipfs' | 'arweave';
|
|
306
341
|
retention?: string;
|
|
307
342
|
facilitator?: string;
|
|
308
343
|
fetch?: typeof fetch;
|
|
@@ -322,15 +357,18 @@ interface AnchorOptions {
|
|
|
322
357
|
* identical, the ed25519 form was refused (`409 dx402_already_anchored`) and the
|
|
323
358
|
* EVM form superseded the provisional.
|
|
324
359
|
*
|
|
325
|
-
* `pointer`
|
|
326
|
-
* facilitator issues the pointer and you cannot sign what you have not seen.
|
|
360
|
+
* `pointer` defaults to the empty string, which is right when you send `sealed`:
|
|
361
|
+
* the facilitator issues the pointer and you cannot sign what you have not seen.
|
|
362
|
+
* When you supply your OWN pointer it must be passed here **verbatim** -- the
|
|
363
|
+
* facilitator verifies against `req.pointer` when one is present and against
|
|
364
|
+
* `""` when it is absent (x402-rs `dx402/service.rs`, `signed_pointer`), so
|
|
365
|
+
* signing the empty string alongside a pointer produces a signature that never
|
|
366
|
+
* verifies and an anchor that silently stays provisional.
|
|
327
367
|
*/
|
|
328
|
-
declare function sellerDigestFor(paymentId: string, contentHash: string, payee: string, network: string): Uint8Array | undefined;
|
|
368
|
+
declare function sellerDigestFor(paymentId: string, contentHash: string, payee: string, network: string, pointer?: string): Uint8Array | undefined;
|
|
329
369
|
/**
|
|
330
370
|
* Largest `POST /dx402/anchor` request the facilitator accepts, mirroring its
|
|
331
371
|
* `MAX_REQUEST_BODY_BYTES` (default 64 KiB, an anti-OOM bound on every route).
|
|
332
|
-
* After base64 inflation and ~600 bytes of metadata this leaves ~47 KB of
|
|
333
|
-
* plaintext.
|
|
334
372
|
*/
|
|
335
373
|
declare const ANCHOR_MAX_REQUEST_BYTES: number;
|
|
336
374
|
declare function anchorEvidence(body: Uint8Array, opts: AnchorOptions): Promise<Record<string, unknown>>;
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { A as AlgorandPaymentPayload, C as CAIP2_IDENTIFIERS, a as CAIP2_TO_CHAI
|
|
|
4
4
|
import { S as SigningWalletAdapter } from './wallet-0cX9Pw2F.js';
|
|
5
5
|
export { E as EIP3009Authorization, a as EIP3009Params } from './wallet-0cX9Pw2F.js';
|
|
6
6
|
export { E as EnvKeyAdapter, O as OWSWallet, a as OWSWalletAdapter } from './ows-DTDixPzO.js';
|
|
7
|
-
export { FacilitatorClient, FacilitatorClientOptions, HonoMiddlewareOptions, PaymentAcceptance, PaymentMiddlewareOptions, PaymentPayloadV2, PaymentRequirementsV2, ResourceInfoV2, SettleRequestV2, VerifiedPaymentState, VerifyRequestV2, X402_CORS_HEADERS, X402_HEADER_NAMES, buildPaymentRequirements, buildSettleRequest, buildSettleRequestV2, buildVerifyRequest, buildVerifyRequestV2, create402Response, createHonoMiddleware, createPaymentMiddleware, extractPaymentFromHeaders, getCorsHeaders } from './backend/index.js';
|
|
7
|
+
export { AMBIGUOUS_LEASE_REASONS, DEFAULT_FACILITATOR_RETRIES, DEFAULT_RETRY_AFTER_SECONDS, FacilitatorClient, FacilitatorClientOptions, FacilitatorErrorInfo, FacilitatorFailureFields, FacilitatorFetchOptions, HonoMiddlewareOptions, MAX_RETRY_AFTER_SECONDS, PaymentAcceptance, PaymentMiddlewareOptions, PaymentPayloadV2, PaymentRequirementsV2, REPLAYABLE_LEASE_REASONS, ResourceInfoV2, SettleRequestV2, VerifiedPaymentState, VerifyRequestV2, WRITER_LEASE_REASONS, WriterLeaseReason, X402_CORS_HEADERS, X402_HEADER_NAMES, buildPaymentRequirements, buildSettleRequest, buildSettleRequestV2, buildVerifyRequest, buildVerifyRequestV2, create402Response, createHonoMiddleware, createPaymentMiddleware, extractPaymentFromHeaders, facilitatorFetch, getCorsHeaders, isAmbiguousLeaseReason, isReplayableLeaseReason, parseRetryAfterSeconds, readFacilitatorError } from './backend/index.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* DX402 `durable-evidence`: recover a paid response after the fact.
|
|
@@ -303,6 +303,41 @@ interface AnchorOptions {
|
|
|
303
303
|
* anchor for the same payment supersedes it.
|
|
304
304
|
*/
|
|
305
305
|
sign?: (digest: Uint8Array) => string | Promise<string>;
|
|
306
|
+
/**
|
|
307
|
+
* `(sealedBytes) => pointer`. Bring your own storage.
|
|
308
|
+
*
|
|
309
|
+
* Without this the sealed envelope travels **inside** the anchor request and
|
|
310
|
+
* the facilitator hosts it, which is the easy path and stays the default. With
|
|
311
|
+
* it, the SDK still seals exactly as before -- the buyer has to be able to
|
|
312
|
+
* decrypt, so the sealing is not optional -- then hands you the ciphertext,
|
|
313
|
+
* you write it wherever you keep durable bytes, and you return the pointer
|
|
314
|
+
* that addresses it. The request then carries only that pointer, so the
|
|
315
|
+
* ciphertext never travels through the anchor call and
|
|
316
|
+
* {@link ANCHOR_MAX_REQUEST_BYTES} does not apply to your body.
|
|
317
|
+
*
|
|
318
|
+
* A callable rather than a precomputed pointer, for the same reason
|
|
319
|
+
* {@link AnchorOptions.sign} is one: the SDK must seal first, and only then
|
|
320
|
+
* can anything be uploaded. Handing in a pointer computed in advance would
|
|
321
|
+
* mean addressing bytes that do not exist yet.
|
|
322
|
+
*
|
|
323
|
+
* The returned pointer is what the buyer will dereference, so it must be
|
|
324
|
+
* readable by them -- see {@link dereferencePointer} for the schemes the SDK
|
|
325
|
+
* resolves out of the box. It is also bound into the seller signature.
|
|
326
|
+
*
|
|
327
|
+
* **It is never allowed to break the sale.** If it throws or returns
|
|
328
|
+
* something unusable, the anchor degrades to a skip and the payment is
|
|
329
|
+
* untouched.
|
|
330
|
+
*/
|
|
331
|
+
upload?: (sealed: Uint8Array) => string | Promise<string>;
|
|
332
|
+
/**
|
|
333
|
+
* Which storage family the pointer belongs to: `s3`, `ipfs` or `arweave`.
|
|
334
|
+
*
|
|
335
|
+
* Defaults to `s3`, and in {@link AnchorOptions.upload} mode it is inferred
|
|
336
|
+
* from the pointer's scheme when you do not say. Distinct from `storage`,
|
|
337
|
+
* which names one of the FACILITATOR's own offers and is meaningless when you
|
|
338
|
+
* supply the bytes yourself.
|
|
339
|
+
*/
|
|
340
|
+
backend?: 's3' | 'ipfs' | 'arweave';
|
|
306
341
|
retention?: string;
|
|
307
342
|
facilitator?: string;
|
|
308
343
|
fetch?: typeof fetch;
|
|
@@ -322,15 +357,18 @@ interface AnchorOptions {
|
|
|
322
357
|
* identical, the ed25519 form was refused (`409 dx402_already_anchored`) and the
|
|
323
358
|
* EVM form superseded the provisional.
|
|
324
359
|
*
|
|
325
|
-
* `pointer`
|
|
326
|
-
* facilitator issues the pointer and you cannot sign what you have not seen.
|
|
360
|
+
* `pointer` defaults to the empty string, which is right when you send `sealed`:
|
|
361
|
+
* the facilitator issues the pointer and you cannot sign what you have not seen.
|
|
362
|
+
* When you supply your OWN pointer it must be passed here **verbatim** -- the
|
|
363
|
+
* facilitator verifies against `req.pointer` when one is present and against
|
|
364
|
+
* `""` when it is absent (x402-rs `dx402/service.rs`, `signed_pointer`), so
|
|
365
|
+
* signing the empty string alongside a pointer produces a signature that never
|
|
366
|
+
* verifies and an anchor that silently stays provisional.
|
|
327
367
|
*/
|
|
328
|
-
declare function sellerDigestFor(paymentId: string, contentHash: string, payee: string, network: string): Uint8Array | undefined;
|
|
368
|
+
declare function sellerDigestFor(paymentId: string, contentHash: string, payee: string, network: string, pointer?: string): Uint8Array | undefined;
|
|
329
369
|
/**
|
|
330
370
|
* Largest `POST /dx402/anchor` request the facilitator accepts, mirroring its
|
|
331
371
|
* `MAX_REQUEST_BODY_BYTES` (default 64 KiB, an anti-OOM bound on every route).
|
|
332
|
-
* After base64 inflation and ~600 bytes of metadata this leaves ~47 KB of
|
|
333
|
-
* plaintext.
|
|
334
372
|
*/
|
|
335
373
|
declare const ANCHOR_MAX_REQUEST_BYTES: number;
|
|
336
374
|
declare function anchorEvidence(body: Uint8Array, opts: AnchorOptions): Promise<Record<string, unknown>>;
|
package/dist/index.js
CHANGED
|
@@ -1584,13 +1584,13 @@ function chainIdFor(network) {
|
|
|
1584
1584
|
if (Number.isFinite(byId) && byId > 0) return getChainById(byId)?.chainId;
|
|
1585
1585
|
return getChainByName(name)?.chainId;
|
|
1586
1586
|
}
|
|
1587
|
-
function sellerDigestFor(paymentId2, contentHash2, payee, network) {
|
|
1587
|
+
function sellerDigestFor(paymentId2, contentHash2, payee, network, pointer = "") {
|
|
1588
1588
|
if (isEvmAddress(payee)) {
|
|
1589
1589
|
const chainId = chainIdFor(network);
|
|
1590
1590
|
if (!chainId) return void 0;
|
|
1591
|
-
return anchorDigest(paymentId2, contentHash2,
|
|
1591
|
+
return anchorDigest(paymentId2, contentHash2, pointer, payee, chainId);
|
|
1592
1592
|
}
|
|
1593
|
-
return anchorDigest(paymentId2, contentHash2,
|
|
1593
|
+
return anchorDigest(paymentId2, contentHash2, pointer, ZERO_ADDRESS, 0);
|
|
1594
1594
|
}
|
|
1595
1595
|
var ANCHOR_MAX_REQUEST_BYTES = 64 * 1024;
|
|
1596
1596
|
function toBase64(bytes) {
|
|
@@ -1601,6 +1601,11 @@ function toBase64(bytes) {
|
|
|
1601
1601
|
}
|
|
1602
1602
|
return btoa(out);
|
|
1603
1603
|
}
|
|
1604
|
+
function backendForPointer(pointer) {
|
|
1605
|
+
if (pointer.startsWith("ipfs://")) return "ipfs";
|
|
1606
|
+
if (pointer.startsWith("ar://")) return "arweave";
|
|
1607
|
+
return "s3";
|
|
1608
|
+
}
|
|
1604
1609
|
async function anchorEvidence(body, opts) {
|
|
1605
1610
|
try {
|
|
1606
1611
|
const recipients = [
|
|
@@ -1611,14 +1616,35 @@ async function anchorEvidence(body, opts) {
|
|
|
1611
1616
|
}
|
|
1612
1617
|
const blob = sealEvidenceTo(body, recipients, opts.paymentId);
|
|
1613
1618
|
const hash = contentHash(body);
|
|
1619
|
+
let pointer;
|
|
1620
|
+
if (opts.upload) {
|
|
1621
|
+
try {
|
|
1622
|
+
pointer = await opts.upload(blob);
|
|
1623
|
+
} catch {
|
|
1624
|
+
return { v: 1, skipped: "anchor_failed", stage: "upload" };
|
|
1625
|
+
}
|
|
1626
|
+
if (typeof pointer !== "string" || pointer.trim() === "") {
|
|
1627
|
+
return { v: 1, skipped: "anchor_failed", stage: "upload" };
|
|
1628
|
+
}
|
|
1629
|
+
pointer = pointer.trim();
|
|
1630
|
+
}
|
|
1614
1631
|
const payload = {
|
|
1615
1632
|
paymentId: opts.paymentId,
|
|
1616
1633
|
network: opts.network,
|
|
1617
1634
|
txHash: opts.txHash,
|
|
1618
1635
|
payer: opts.payer,
|
|
1619
1636
|
payee: opts.payee,
|
|
1620
|
-
|
|
1621
|
-
|
|
1637
|
+
// Exactly one of these. The facilitator dispatches on their presence:
|
|
1638
|
+
// `sealed` -> it hosts and derives the pointer; `pointer` alone -> it uses
|
|
1639
|
+
// yours; neither -> error (x402-rs `dx402/service.rs`).
|
|
1640
|
+
...pointer !== void 0 ? { pointer } : { sealed: toBase64(blob) },
|
|
1641
|
+
// Declared, not measured. Since x402-rs 2.3.0 the facilitator records
|
|
1642
|
+
// the store that ACTUALLY took the bytes and returns that, so a response
|
|
1643
|
+
// may name a different backend than the request did -- `ipfs` where you
|
|
1644
|
+
// said `s3`, because a deployment whose primary is Pinata wrote there.
|
|
1645
|
+
// That is the facilitator correcting the record, not a mismatch to
|
|
1646
|
+
// assert on.
|
|
1647
|
+
backend: opts.backend ?? (pointer !== void 0 ? backendForPointer(pointer) : "s3"),
|
|
1622
1648
|
contentHash: hash,
|
|
1623
1649
|
keyAlg: opts.payerKey.length === 32 ? "ECIES-X25519" : "ECIES-secp256k1",
|
|
1624
1650
|
mode: "direct",
|
|
@@ -1632,7 +1658,7 @@ async function anchorEvidence(body, opts) {
|
|
|
1632
1658
|
payload.storage = opts.storage;
|
|
1633
1659
|
}
|
|
1634
1660
|
if (opts.sign) {
|
|
1635
|
-
const digest = sellerDigestFor(opts.paymentId, hash, opts.payee, opts.network);
|
|
1661
|
+
const digest = sellerDigestFor(opts.paymentId, hash, opts.payee, opts.network, pointer ?? "");
|
|
1636
1662
|
if (digest === void 0) {
|
|
1637
1663
|
unsigned = "unknown_chain_id";
|
|
1638
1664
|
} else {
|
|
@@ -1640,7 +1666,7 @@ async function anchorEvidence(body, opts) {
|
|
|
1640
1666
|
}
|
|
1641
1667
|
}
|
|
1642
1668
|
const wire = JSON.stringify(payload);
|
|
1643
|
-
if (new TextEncoder().encode(wire).length > ANCHOR_MAX_REQUEST_BYTES) {
|
|
1669
|
+
if (pointer === void 0 && new TextEncoder().encode(wire).length > ANCHOR_MAX_REQUEST_BYTES) {
|
|
1644
1670
|
return { v: 1, skipped: "too_large" };
|
|
1645
1671
|
}
|
|
1646
1672
|
const base = (opts.facilitator ?? "https://facilitator.ultravioletadao.xyz").replace(
|
|
@@ -3723,6 +3749,118 @@ async function buildEscrowPreAuth(wallet, params) {
|
|
|
3723
3749
|
});
|
|
3724
3750
|
}
|
|
3725
3751
|
|
|
3752
|
+
// src/backend/facilitator-error.ts
|
|
3753
|
+
var WRITER_LEASE_REASONS = [
|
|
3754
|
+
"holder_unknown",
|
|
3755
|
+
"forwarding_disabled",
|
|
3756
|
+
"forwarded_but_not_writer",
|
|
3757
|
+
"body_unreadable",
|
|
3758
|
+
"forward_failed"
|
|
3759
|
+
];
|
|
3760
|
+
var REPLAYABLE_LEASE_REASONS = [
|
|
3761
|
+
"holder_unknown",
|
|
3762
|
+
"forwarding_disabled",
|
|
3763
|
+
"forwarded_but_not_writer",
|
|
3764
|
+
"body_unreadable"
|
|
3765
|
+
];
|
|
3766
|
+
var AMBIGUOUS_LEASE_REASONS = ["forward_failed"];
|
|
3767
|
+
var MAX_RETRY_AFTER_SECONDS = 15;
|
|
3768
|
+
var DEFAULT_RETRY_AFTER_SECONDS = 5;
|
|
3769
|
+
var DEFAULT_FACILITATOR_RETRIES = 2;
|
|
3770
|
+
function isReplayableLeaseReason(reason) {
|
|
3771
|
+
return REPLAYABLE_LEASE_REASONS.includes(reason);
|
|
3772
|
+
}
|
|
3773
|
+
function isAmbiguousLeaseReason(reason) {
|
|
3774
|
+
return AMBIGUOUS_LEASE_REASONS.includes(reason);
|
|
3775
|
+
}
|
|
3776
|
+
function parseRetryAfterSeconds(response) {
|
|
3777
|
+
let raw;
|
|
3778
|
+
try {
|
|
3779
|
+
raw = response?.headers?.get?.("retry-after");
|
|
3780
|
+
} catch {
|
|
3781
|
+
return void 0;
|
|
3782
|
+
}
|
|
3783
|
+
if (raw === null || raw === void 0 || raw === "") return void 0;
|
|
3784
|
+
const seconds = Number(raw);
|
|
3785
|
+
if (!Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
3786
|
+
return Math.min(seconds, MAX_RETRY_AFTER_SECONDS);
|
|
3787
|
+
}
|
|
3788
|
+
function reasonFrom(body) {
|
|
3789
|
+
try {
|
|
3790
|
+
const parsed = JSON.parse(body);
|
|
3791
|
+
if (parsed && typeof parsed === "object" && typeof parsed.reason === "string") {
|
|
3792
|
+
return parsed.reason;
|
|
3793
|
+
}
|
|
3794
|
+
} catch {
|
|
3795
|
+
}
|
|
3796
|
+
return void 0;
|
|
3797
|
+
}
|
|
3798
|
+
async function readFacilitatorError(response) {
|
|
3799
|
+
let body = "";
|
|
3800
|
+
try {
|
|
3801
|
+
body = await response.text();
|
|
3802
|
+
} catch {
|
|
3803
|
+
body = "";
|
|
3804
|
+
}
|
|
3805
|
+
const status = response.status;
|
|
3806
|
+
const reason = reasonFrom(body);
|
|
3807
|
+
const retryable = status === 429 || status === 502 || status === 503 || status === 504;
|
|
3808
|
+
const retryAfterSeconds = retryable ? parseRetryAfterSeconds(response) ?? DEFAULT_RETRY_AFTER_SECONDS : void 0;
|
|
3809
|
+
const safeToReplay = status === 429 || status === 503 && isReplayableLeaseReason(reason);
|
|
3810
|
+
return {
|
|
3811
|
+
error: `Facilitator error: ${status} - ${body}`,
|
|
3812
|
+
status,
|
|
3813
|
+
reason,
|
|
3814
|
+
retryAfterSeconds,
|
|
3815
|
+
retryable,
|
|
3816
|
+
safeToReplay,
|
|
3817
|
+
body
|
|
3818
|
+
};
|
|
3819
|
+
}
|
|
3820
|
+
function failureFields(info) {
|
|
3821
|
+
return {
|
|
3822
|
+
status: info.status,
|
|
3823
|
+
retryable: info.retryable,
|
|
3824
|
+
safeToReplay: info.safeToReplay,
|
|
3825
|
+
...info.reason !== void 0 ? { reason: info.reason } : {},
|
|
3826
|
+
...info.retryAfterSeconds !== void 0 ? { retryAfterSeconds: info.retryAfterSeconds } : {}
|
|
3827
|
+
};
|
|
3828
|
+
}
|
|
3829
|
+
function carryFailureFields(source) {
|
|
3830
|
+
return {
|
|
3831
|
+
...source.status !== void 0 ? { status: source.status } : {},
|
|
3832
|
+
...source.reason !== void 0 ? { reason: source.reason } : {},
|
|
3833
|
+
...source.retryable !== void 0 ? { retryable: source.retryable } : {},
|
|
3834
|
+
...source.retryAfterSeconds !== void 0 ? { retryAfterSeconds: source.retryAfterSeconds } : {},
|
|
3835
|
+
...source.safeToReplay !== void 0 ? { safeToReplay: source.safeToReplay } : {}
|
|
3836
|
+
};
|
|
3837
|
+
}
|
|
3838
|
+
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
3839
|
+
async function facilitatorFetch(url, init, options) {
|
|
3840
|
+
const retries = options.retries ?? DEFAULT_FACILITATOR_RETRIES;
|
|
3841
|
+
const canReplay = options.canReplay ?? ((info) => info.safeToReplay);
|
|
3842
|
+
const doFetch = options.fetchImpl ?? fetch;
|
|
3843
|
+
const sleep = options.sleepImpl ?? defaultSleep;
|
|
3844
|
+
let attempt = 0;
|
|
3845
|
+
for (; ; ) {
|
|
3846
|
+
const controller = new AbortController();
|
|
3847
|
+
const timeoutId = setTimeout(() => controller.abort(), options.timeoutMs);
|
|
3848
|
+
let response;
|
|
3849
|
+
try {
|
|
3850
|
+
response = await doFetch(url, { ...init, signal: controller.signal });
|
|
3851
|
+
} finally {
|
|
3852
|
+
clearTimeout(timeoutId);
|
|
3853
|
+
}
|
|
3854
|
+
if (response.ok) return { response };
|
|
3855
|
+
const error = await readFacilitatorError(response);
|
|
3856
|
+
if (attempt >= retries || !error.retryable || !canReplay(error)) {
|
|
3857
|
+
return { response, error };
|
|
3858
|
+
}
|
|
3859
|
+
attempt += 1;
|
|
3860
|
+
await sleep((error.retryAfterSeconds ?? DEFAULT_RETRY_AFTER_SECONDS) * 1e3);
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
|
|
3726
3864
|
// src/backend/index.ts
|
|
3727
3865
|
function parsePaymentHeader(headerValue) {
|
|
3728
3866
|
if (!headerValue) {
|
|
@@ -3829,10 +3967,12 @@ var FacilitatorClient = class {
|
|
|
3829
3967
|
baseUrl;
|
|
3830
3968
|
timeout;
|
|
3831
3969
|
explicitTimeout;
|
|
3970
|
+
retries;
|
|
3832
3971
|
constructor(options = {}) {
|
|
3833
3972
|
this.baseUrl = options.baseUrl || "https://facilitator.ultravioletadao.xyz";
|
|
3834
3973
|
this.explicitTimeout = options.timeout !== void 0;
|
|
3835
3974
|
this.timeout = options.timeout || 3e4;
|
|
3975
|
+
this.retries = options.retries;
|
|
3836
3976
|
}
|
|
3837
3977
|
/**
|
|
3838
3978
|
* Get timeout for a specific network, using per-chain defaults when no explicit timeout was set.
|
|
@@ -3859,29 +3999,31 @@ var FacilitatorClient = class {
|
|
|
3859
3999
|
*/
|
|
3860
4000
|
async verify(paymentHeader, requirements) {
|
|
3861
4001
|
const body = buildVerifyRequest(paymentHeader, requirements);
|
|
3862
|
-
const controller = new AbortController();
|
|
3863
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
3864
4002
|
try {
|
|
3865
|
-
const response = await
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
3870
|
-
|
|
3871
|
-
|
|
3872
|
-
|
|
3873
|
-
|
|
4003
|
+
const { response, error } = await facilitatorFetch(
|
|
4004
|
+
`${this.baseUrl}/verify`,
|
|
4005
|
+
{
|
|
4006
|
+
method: "POST",
|
|
4007
|
+
headers: { "Content-Type": "application/json" },
|
|
4008
|
+
body: JSON.stringify(body)
|
|
4009
|
+
},
|
|
4010
|
+
{ timeoutMs: this.timeout, retries: this.retries }
|
|
4011
|
+
);
|
|
4012
|
+
if (error) {
|
|
3874
4013
|
return {
|
|
3875
4014
|
isValid: false,
|
|
3876
|
-
invalidReason:
|
|
4015
|
+
invalidReason: error.error,
|
|
4016
|
+
...failureFields(error)
|
|
3877
4017
|
};
|
|
3878
4018
|
}
|
|
3879
4019
|
return await response.json();
|
|
3880
4020
|
} catch (error) {
|
|
3881
|
-
clearTimeout(timeoutId);
|
|
3882
4021
|
return {
|
|
3883
4022
|
isValid: false,
|
|
3884
|
-
invalidReason: error instanceof Error ? error.message : "Unknown error"
|
|
4023
|
+
invalidReason: error instanceof Error ? error.message : "Unknown error",
|
|
4024
|
+
retryable: true,
|
|
4025
|
+
safeToReplay: false,
|
|
4026
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS
|
|
3885
4027
|
};
|
|
3886
4028
|
}
|
|
3887
4029
|
}
|
|
@@ -3897,21 +4039,21 @@ var FacilitatorClient = class {
|
|
|
3897
4039
|
async settle(paymentHeader, requirements) {
|
|
3898
4040
|
const body = buildSettleRequest(paymentHeader, requirements);
|
|
3899
4041
|
const settleTimeout = this.getTimeout(requirements.network);
|
|
3900
|
-
const controller = new AbortController();
|
|
3901
|
-
const timeoutId = setTimeout(() => controller.abort(), settleTimeout);
|
|
3902
4042
|
try {
|
|
3903
|
-
const response = await
|
|
3904
|
-
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
|
|
3911
|
-
|
|
4043
|
+
const { response, error } = await facilitatorFetch(
|
|
4044
|
+
`${this.baseUrl}/settle`,
|
|
4045
|
+
{
|
|
4046
|
+
method: "POST",
|
|
4047
|
+
headers: { "Content-Type": "application/json" },
|
|
4048
|
+
body: JSON.stringify(body)
|
|
4049
|
+
},
|
|
4050
|
+
{ timeoutMs: settleTimeout, retries: this.retries }
|
|
4051
|
+
);
|
|
4052
|
+
if (error) {
|
|
3912
4053
|
return {
|
|
3913
4054
|
success: false,
|
|
3914
|
-
error:
|
|
4055
|
+
error: error.error,
|
|
4056
|
+
...failureFields(error)
|
|
3915
4057
|
};
|
|
3916
4058
|
}
|
|
3917
4059
|
const result = await response.json();
|
|
@@ -3952,10 +4094,12 @@ var FacilitatorClient = class {
|
|
|
3952
4094
|
payer: result.payer
|
|
3953
4095
|
};
|
|
3954
4096
|
} catch (error) {
|
|
3955
|
-
clearTimeout(timeoutId);
|
|
3956
4097
|
return {
|
|
3957
4098
|
success: false,
|
|
3958
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
4099
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
4100
|
+
retryable: true,
|
|
4101
|
+
safeToReplay: false,
|
|
4102
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS
|
|
3959
4103
|
};
|
|
3960
4104
|
}
|
|
3961
4105
|
}
|
|
@@ -3975,7 +4119,8 @@ var FacilitatorClient = class {
|
|
|
3975
4119
|
return {
|
|
3976
4120
|
verified: false,
|
|
3977
4121
|
settled: false,
|
|
3978
|
-
error: verifyResult.invalidReason
|
|
4122
|
+
error: verifyResult.invalidReason,
|
|
4123
|
+
...carryFailureFields(verifyResult)
|
|
3979
4124
|
};
|
|
3980
4125
|
}
|
|
3981
4126
|
const settleResult = await this.settle(paymentHeader, requirements);
|
|
@@ -3983,7 +4128,8 @@ var FacilitatorClient = class {
|
|
|
3983
4128
|
verified: true,
|
|
3984
4129
|
settled: settleResult.success,
|
|
3985
4130
|
transactionHash: settleResult.transactionHash,
|
|
3986
|
-
error: settleResult.error
|
|
4131
|
+
error: settleResult.error,
|
|
4132
|
+
...carryFailureFields(settleResult)
|
|
3987
4133
|
};
|
|
3988
4134
|
}
|
|
3989
4135
|
/**
|
|
@@ -4385,10 +4531,29 @@ function createVerifiedPaymentState(client, payment, requirements, verifyResult)
|
|
|
4385
4531
|
}
|
|
4386
4532
|
};
|
|
4387
4533
|
}
|
|
4534
|
+
function respondUnavailable(res, message, failure) {
|
|
4535
|
+
const seconds = Math.max(1, Math.ceil(failure.retryAfterSeconds ?? DEFAULT_RETRY_AFTER_SECONDS));
|
|
4536
|
+
const body = {
|
|
4537
|
+
error: message,
|
|
4538
|
+
reason: failure.reason ?? failure.invalidReason ?? failure.error,
|
|
4539
|
+
retryable: true,
|
|
4540
|
+
retryAfterSeconds: seconds,
|
|
4541
|
+
// False for `forward_failed` and for a bare timeout: the write may already
|
|
4542
|
+
// have landed, so the caller must reconcile before resending.
|
|
4543
|
+
safeToReplay: failure.safeToReplay === true
|
|
4544
|
+
};
|
|
4545
|
+
const staged = res.status(503);
|
|
4546
|
+
if (typeof staged.set === "function") {
|
|
4547
|
+
staged.set({ "Retry-After": String(seconds) }).json(body);
|
|
4548
|
+
return;
|
|
4549
|
+
}
|
|
4550
|
+
staged.json(body);
|
|
4551
|
+
}
|
|
4388
4552
|
function createPaymentMiddleware(getRequirements, options = {}) {
|
|
4389
4553
|
const client = new FacilitatorClient({
|
|
4390
4554
|
baseUrl: options.facilitatorUrl || options.baseUrl,
|
|
4391
|
-
timeout: options.timeout
|
|
4555
|
+
timeout: options.timeout,
|
|
4556
|
+
retries: options.retries
|
|
4392
4557
|
});
|
|
4393
4558
|
const settlementStrategy = options.settlementStrategy || "before-handler";
|
|
4394
4559
|
return async (req, res, next) => {
|
|
@@ -4403,6 +4568,10 @@ function createPaymentMiddleware(getRequirements, options = {}) {
|
|
|
4403
4568
|
const requirements = buildPaymentRequirements(reqOptions);
|
|
4404
4569
|
const verifyResult = await client.verify(payment, requirements);
|
|
4405
4570
|
if (!verifyResult.isValid) {
|
|
4571
|
+
if (verifyResult.retryable) {
|
|
4572
|
+
respondUnavailable(res, "Payment verification unavailable", verifyResult);
|
|
4573
|
+
return;
|
|
4574
|
+
}
|
|
4406
4575
|
res.status(402).json({
|
|
4407
4576
|
error: "Payment verification failed",
|
|
4408
4577
|
reason: verifyResult.invalidReason
|
|
@@ -4413,6 +4582,10 @@ function createPaymentMiddleware(getRequirements, options = {}) {
|
|
|
4413
4582
|
if (settlementStrategy === "before-handler") {
|
|
4414
4583
|
const settleResult = await req.x402.settle();
|
|
4415
4584
|
if (!settleResult.success) {
|
|
4585
|
+
if (settleResult.retryable) {
|
|
4586
|
+
respondUnavailable(res, "Payment settlement unavailable", settleResult);
|
|
4587
|
+
return;
|
|
4588
|
+
}
|
|
4416
4589
|
res.status(500).json({
|
|
4417
4590
|
error: "Payment settlement failed",
|
|
4418
4591
|
reason: settleResult.error || "Unknown settlement error"
|
|
@@ -4423,10 +4596,25 @@ function createPaymentMiddleware(getRequirements, options = {}) {
|
|
|
4423
4596
|
next();
|
|
4424
4597
|
};
|
|
4425
4598
|
}
|
|
4599
|
+
function honoUnavailable(c, message, failure) {
|
|
4600
|
+
const seconds = Math.max(1, Math.ceil(failure.retryAfterSeconds ?? DEFAULT_RETRY_AFTER_SECONDS));
|
|
4601
|
+
c.header?.("Retry-After", String(seconds));
|
|
4602
|
+
return c.json(
|
|
4603
|
+
{
|
|
4604
|
+
error: message,
|
|
4605
|
+
reason: failure.reason ?? failure.invalidReason ?? failure.error,
|
|
4606
|
+
retryable: true,
|
|
4607
|
+
retryAfterSeconds: seconds,
|
|
4608
|
+
safeToReplay: failure.safeToReplay === true
|
|
4609
|
+
},
|
|
4610
|
+
503
|
|
4611
|
+
);
|
|
4612
|
+
}
|
|
4426
4613
|
function createHonoMiddleware(options) {
|
|
4427
4614
|
const client = new FacilitatorClient({
|
|
4428
4615
|
baseUrl: options.facilitatorUrl || options.baseUrl,
|
|
4429
|
-
timeout: options.timeout
|
|
4616
|
+
timeout: options.timeout,
|
|
4617
|
+
retries: options.retries
|
|
4430
4618
|
});
|
|
4431
4619
|
const settlementStrategy = options.settlementStrategy || "before-handler";
|
|
4432
4620
|
if (!options.accepts[0]) {
|
|
@@ -4466,6 +4654,9 @@ function createHonoMiddleware(options) {
|
|
|
4466
4654
|
}
|
|
4467
4655
|
const verifyResult = await client.verify(parsed, requirement);
|
|
4468
4656
|
if (!verifyResult.isValid) {
|
|
4657
|
+
if (verifyResult.retryable) {
|
|
4658
|
+
return honoUnavailable(c, "Payment verification unavailable", verifyResult);
|
|
4659
|
+
}
|
|
4469
4660
|
return c.json({
|
|
4470
4661
|
error: "Payment verification failed",
|
|
4471
4662
|
reason: verifyResult.invalidReason
|
|
@@ -4476,6 +4667,9 @@ function createHonoMiddleware(options) {
|
|
|
4476
4667
|
if (settlementStrategy === "before-handler") {
|
|
4477
4668
|
const settleResult = await verifiedPayment.settle();
|
|
4478
4669
|
if (!settleResult.success) {
|
|
4670
|
+
if (settleResult.retryable) {
|
|
4671
|
+
return honoUnavailable(c, "Payment settlement unavailable", settleResult);
|
|
4672
|
+
}
|
|
4479
4673
|
return c.json({
|
|
4480
4674
|
error: "Payment settlement failed",
|
|
4481
4675
|
reason: settleResult.error || "Unknown error"
|
|
@@ -4508,14 +4702,17 @@ var ESCROW_TIMEOUT_MS = {
|
|
|
4508
4702
|
// Monad: 90s
|
|
4509
4703
|
};
|
|
4510
4704
|
|
|
4705
|
+
exports.AMBIGUOUS_LEASE_REASONS = AMBIGUOUS_LEASE_REASONS;
|
|
4511
4706
|
exports.ANCHOR_MAX_REQUEST_BYTES = ANCHOR_MAX_REQUEST_BYTES;
|
|
4512
4707
|
exports.CAIP2_IDENTIFIERS = CAIP2_IDENTIFIERS;
|
|
4513
4708
|
exports.CAIP2_TO_CHAIN = CAIP2_TO_CHAIN;
|
|
4514
4709
|
exports.ContentHashMismatch = ContentHashMismatch;
|
|
4515
4710
|
exports.DEFAULT_CHAIN = DEFAULT_CHAIN;
|
|
4516
4711
|
exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
|
|
4712
|
+
exports.DEFAULT_FACILITATOR_RETRIES = DEFAULT_FACILITATOR_RETRIES;
|
|
4517
4713
|
exports.DEFAULT_FACILITATOR_URL = DEFAULT_FACILITATOR_URL;
|
|
4518
4714
|
exports.DEFAULT_PAYMENT_HEADER = DEFAULT_PAYMENT_HEADER;
|
|
4715
|
+
exports.DEFAULT_RETRY_AFTER_SECONDS = DEFAULT_RETRY_AFTER_SECONDS;
|
|
4519
4716
|
exports.DELEGATE_PREFIX = DELEGATE_PREFIX;
|
|
4520
4717
|
exports.DX402Error = DX402Error;
|
|
4521
4718
|
exports.ESCROW_DEPOSIT_LIMIT_USD = ESCROW_DEPOSIT_LIMIT_USD;
|
|
@@ -4527,13 +4724,16 @@ exports.EvidenceSkipped = EvidenceSkipped;
|
|
|
4527
4724
|
exports.FACILITATOR_ADDRESSES = FACILITATOR_ADDRESSES;
|
|
4528
4725
|
exports.FacilitatorClient = FacilitatorClient;
|
|
4529
4726
|
exports.KEEPALIVE_INTERVAL_MS = KEEPALIVE_INTERVAL_MS;
|
|
4727
|
+
exports.MAX_RETRY_AFTER_SECONDS = MAX_RETRY_AFTER_SECONDS;
|
|
4530
4728
|
exports.OPERATOR_FEE_BPS = OPERATOR_FEE_BPS;
|
|
4531
4729
|
exports.OWSWalletAdapter = OWSWalletAdapter;
|
|
4532
4730
|
exports.PAYMENT_HEADER_NAMES = PAYMENT_HEADER_NAMES;
|
|
4731
|
+
exports.REPLAYABLE_LEASE_REASONS = REPLAYABLE_LEASE_REASONS;
|
|
4533
4732
|
exports.SMA_WRAP_TARGETS = SMA_WRAP_TARGETS;
|
|
4534
4733
|
exports.SSEParser = SSEParser;
|
|
4535
4734
|
exports.SUPPORTED_CHAINS = SUPPORTED_CHAINS;
|
|
4536
4735
|
exports.TrafficStreamError = TrafficStreamError;
|
|
4736
|
+
exports.WRITER_LEASE_REASONS = WRITER_LEASE_REASONS;
|
|
4537
4737
|
exports.X402Client = X402Client;
|
|
4538
4738
|
exports.X402Error = X402Error;
|
|
4539
4739
|
exports.X402_CORS_HEADERS = X402_CORS_HEADERS;
|
|
@@ -4577,6 +4777,7 @@ exports.encodeX402Header = encodeX402Header;
|
|
|
4577
4777
|
exports.evidenceFromHeaders = evidenceFromHeaders;
|
|
4578
4778
|
exports.evidenceHeader = evidenceHeader;
|
|
4579
4779
|
exports.extractPaymentFromHeaders = extractPaymentFromHeaders;
|
|
4780
|
+
exports.facilitatorFetch = facilitatorFetch;
|
|
4580
4781
|
exports.fetchNonce = fetchNonce;
|
|
4581
4782
|
exports.generatePaymentOptions = generatePaymentOptions;
|
|
4582
4783
|
exports.getAlgorandChains = getAlgorandChains;
|
|
@@ -4599,10 +4800,12 @@ exports.getTokenByAddress = getTokenByAddress;
|
|
|
4599
4800
|
exports.getTokenConfig = getTokenConfig;
|
|
4600
4801
|
exports.getXRPLChains = getXRPLChains;
|
|
4601
4802
|
exports.isAlgorandChain = isAlgorandChain;
|
|
4803
|
+
exports.isAmbiguousLeaseReason = isAmbiguousLeaseReason;
|
|
4602
4804
|
exports.isCAIP2Format = isCAIP2Format;
|
|
4603
4805
|
exports.isChainSupported = isChainSupported;
|
|
4604
4806
|
exports.isDelegated = isDelegated;
|
|
4605
4807
|
exports.isEndToEnd = isEndToEnd;
|
|
4808
|
+
exports.isReplayableLeaseReason = isReplayableLeaseReason;
|
|
4606
4809
|
exports.isSVMChain = isSVMChain;
|
|
4607
4810
|
exports.isSuiChain = isSuiChain;
|
|
4608
4811
|
exports.isTokenSupported = isTokenSupported;
|
|
@@ -4611,11 +4814,13 @@ exports.matchesFilters = matchesFilters;
|
|
|
4611
4814
|
exports.needsAccountWrap = needsAccountWrap;
|
|
4612
4815
|
exports.parseEvidenceHeader = parseEvidenceHeader;
|
|
4613
4816
|
exports.parseNetworkIdentifier = parseNetworkIdentifier;
|
|
4817
|
+
exports.parseRetryAfterSeconds = parseRetryAfterSeconds;
|
|
4614
4818
|
exports.parseSealed = parseSealed;
|
|
4615
4819
|
exports.parseTrafficEvent = parseTrafficEvent;
|
|
4616
4820
|
exports.payerKeyFromEvmSignature = payerKeyFromEvmSignature;
|
|
4617
4821
|
exports.payerKeyFromSolanaAddress = payerKeyFromSolanaAddress;
|
|
4618
4822
|
exports.paymentChallengeFrom = paymentChallengeFrom;
|
|
4823
|
+
exports.readFacilitatorError = readFacilitatorError;
|
|
4619
4824
|
exports.recoverEvidence = recoverEvidence;
|
|
4620
4825
|
exports.replaySafeTypedData = replaySafeTypedData;
|
|
4621
4826
|
exports.resolveDelegation = resolveDelegation;
|