uvd-x402-sdk 2.95.0 → 2.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +9 -0
  2. package/dist/adapters/index.d.mts +1 -1
  3. package/dist/adapters/index.d.ts +1 -1
  4. package/dist/backend/index.d.mts +3 -2
  5. package/dist/backend/index.d.ts +3 -2
  6. package/dist/backend/index.js +255 -17
  7. package/dist/backend/index.js.map +1 -1
  8. package/dist/backend/index.mjs +243 -18
  9. package/dist/backend/index.mjs.map +1 -1
  10. package/dist/{index-DTbVW7EU.d.ts → index-AGj6ViCS.d.ts} +19 -5
  11. package/dist/{index-DnxubrYX.d.mts → index-BsKsZzP3.d.mts} +1 -1
  12. package/dist/{index-DnxubrYX.d.ts → index-BsKsZzP3.d.ts} +1 -1
  13. package/dist/{index-CkHu2s9r.d.ts → index-CtxLKroV.d.mts} +3 -1
  14. package/dist/{index-CIUGPbu8.d.mts → index-DMSZJyZ9.d.mts} +19 -5
  15. package/dist/{index-CF2HBEAJ.d.mts → index-DRDWlAcU.d.ts} +3 -1
  16. package/dist/index.d.mts +5 -4
  17. package/dist/index.d.ts +5 -4
  18. package/dist/index.js +269 -30
  19. package/dist/index.js.map +1 -1
  20. package/dist/index.mjs +257 -31
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/providers/algorand/index.d.mts +1 -1
  23. package/dist/providers/algorand/index.d.ts +1 -1
  24. package/dist/providers/evm/index.d.mts +1 -1
  25. package/dist/providers/evm/index.d.ts +1 -1
  26. package/dist/providers/hedera/index.d.mts +1 -1
  27. package/dist/providers/hedera/index.d.ts +1 -1
  28. package/dist/providers/near/index.d.mts +1 -1
  29. package/dist/providers/near/index.d.ts +1 -1
  30. package/dist/providers/solana/index.d.mts +1 -1
  31. package/dist/providers/solana/index.d.ts +1 -1
  32. package/dist/providers/stellar/index.d.mts +1 -1
  33. package/dist/providers/stellar/index.d.ts +1 -1
  34. package/dist/providers/sui/index.d.mts +1 -1
  35. package/dist/providers/sui/index.d.ts +1 -1
  36. package/dist/providers/xrpl/index.d.mts +1 -1
  37. package/dist/providers/xrpl/index.d.ts +1 -1
  38. package/dist/react/index.d.mts +4 -3
  39. package/dist/react/index.d.ts +4 -3
  40. package/dist/react/index.js +151 -0
  41. package/dist/react/index.js.map +1 -1
  42. package/dist/react/index.mjs +151 -0
  43. package/dist/react/index.mjs.map +1 -1
  44. package/dist/react/picker/index.d.mts +1 -1
  45. package/dist/react/picker/index.d.ts +1 -1
  46. package/dist/receipts-CwaG8BpU.d.ts +99 -0
  47. package/dist/receipts-sEYlpK10.d.mts +99 -0
  48. package/dist/utils/index.d.mts +2 -2
  49. package/dist/utils/index.d.ts +2 -2
  50. package/dist/{validity-SD6nwegA.d.mts → validity-BcPTzuK8.d.mts} +1 -1
  51. package/dist/{validity-BrvXzCEF.d.ts → validity-CoCrj9pZ.d.ts} +1 -1
  52. package/package.json +1 -1
  53. package/src/backend/index.ts +57 -16
  54. package/src/client/X402Client.ts +5 -0
  55. package/src/fixtures/facilitator-receipts-v1.json +299 -0
  56. package/src/index.ts +2 -0
  57. package/src/receipts.ts +209 -0
package/README.md CHANGED
@@ -1978,3 +1978,12 @@ Three things worth knowing:
1978
1978
  that payment, so `signed: true` is the honest maximum.
1979
1979
 
1980
1980
  Full guide: [DX402.md](https://github.com/UltravioletaDAO/x402-rs/blob/main/docs/DX402.md)
1981
+
1982
+ ## Portable facilitator receipts
1983
+
1984
+ Arc mainnet/testnet exact USDC/EURC and native Hedera USDC v2 support additive
1985
+ facilitator receipts: network, asset, atomic amount, payTo, request hash,
1986
+ settlement ID, status and refusal reason. Persist purchase context before sending
1987
+ the authorization and reuse it after uncertainty. Payment confirmation does not
1988
+ prove merchant delivery. See [the receipt guide](docs/facilitator-receipts.md).
1989
+ Live EURC acceptance remains pending.
@@ -1,4 +1,4 @@
1
- import { X as X402Version, a as PaymentResult } from '../index-DnxubrYX.mjs';
1
+ import { X as X402Version, a as PaymentResult } from '../index-BsKsZzP3.mjs';
2
2
  export { E as EnvKeyAdapter, O as OWSWallet, a as OWSWalletAdapter } from '../ows-Z9v4GxOZ.mjs';
3
3
  import '../wallet-w7BnImDG.mjs';
4
4
 
@@ -1,4 +1,4 @@
1
- import { X as X402Version, a as PaymentResult } from '../index-DnxubrYX.js';
1
+ import { X as X402Version, a as PaymentResult } from '../index-BsKsZzP3.js';
2
2
  export { E as EnvKeyAdapter, O as OWSWallet, a as OWSWalletAdapter } from '../ows-C-KmORG9.js';
3
3
  import '../wallet-w7BnImDG.js';
4
4
 
@@ -1,3 +1,4 @@
1
1
  import '../wallet-w7BnImDG.mjs';
2
- import '../index-DnxubrYX.mjs';
3
- export { A as AMBIGUOUS_LEASE_REASONS, ab as AdvancedAuthorizationResult, ac as AdvancedEscrowClient, ad as AdvancedEscrowClientOptions, ae as AdvancedEscrowContracts, af as AdvancedEscrowTaskTier, ag as AdvancedPaymentInfo, ah as AdvancedTransactionResult, ai as AgentId, aj as AgentIdentity, ak as AgentRegistration, al as AgentRegistrationFile, am as AgentService, an as AtomStats, ao as BASE_MAINNET_CONTRACTS, ap as BazaarClient, aq as BazaarClientOptions, ar as BazaarDiscoverOptions, as as BazaarDiscoverResponse, at as BazaarRegisterOptions, au as BazaarResource, av as CreateEscrowOptions, D as DEFAULT_FACILITATOR_RETRIES, a as DEFAULT_RETRY_AFTER_SECONDS, aw as DEPOSIT_LIMIT_USDC, ax as DiscoveryAccepts, ay as DiscoveryCuration, az as DiscoveryHealth, aA as DiscoveryHealthStatus, aB as DiscoveryListOptions, aC as DiscoveryPagination, aD as DiscoveryRegisterOptions, aE as DiscoveryResource, aF as DiscoveryResponse, aG as DiscoverySource, aH as DiscoveryStats, aI as DiscoveryTier, aJ as Dispute, aK as DisputeOutcome, aL as ERC8004_CONTRACTS, aM as ERC8004_EXTENSION_ID, aN as ESCROW_CONTRACTS, aO as ESCROW_TIMEOUT_MS, aP as Erc8004Client, aQ as Erc8004ClientOptions, aR as Erc8004LookupError, aS as Erc8004Network, aT as EscrowClient, aU as EscrowClientOptions, aV as EscrowPayment, aW as EscrowStateResponse, aX as EscrowStatus, F as FacilitatorClient, b as FacilitatorClientOptions, c as FacilitatorErrorInfo, d as FacilitatorFailureFields, e as FacilitatorFetchOptions, aY as FeedbackEntry, aZ as FeedbackParams, a_ as FeedbackRequest, a$ as FeedbackResponse, b0 as HEALTH_FILTERS, H as HonoMiddlewareOptions, b1 as IdentityByOwnerResponse, b2 as IdentityMetadataResponse, b3 as IdentityTotalSupplyResponse, b4 as LifecycleAuthOptions, M as MAX_RETRY_AFTER_SECONDS, b5 as MAX_SEARCH_LEN, b6 as MetadataEntryParam, b7 as OPERATOR_ABI, b8 as OPERATOR_ABI_CREATE3, b9 as PAYMENT_INFO_TYPEHASH, P as ParsedFacilitatorErrorBody, q as PaymentAcceptance, r as PaymentMiddlewareOptions, s as PaymentPayloadV2, ba as PaymentRequirementResolver, bb as PaymentRequirements, bc as PaymentRequirementsOptions, t as PaymentRequirementsV2, bd as PrepareRelayFeedbackRequest, be as PrepareRelayFeedbackResponse, bf as PrepareRelayResponseRequest, bg as PrepareSolanaFeedbackRequest, bh as PrepareSolanaFeedbackResponse, bi as ProofOfPayment, bj as RELAYED_FEEDBACK_NETWORKS, R as REPLAYABLE_LEASE_REASONS, bk as RefundRequest, bl as RefundStatus, bm as RegisterAgentRequest, bn as RegisterAgentResponse, bo as RegisterJobResponse, bp as RegisterJobStatus, bq as RegistrationPendingError, br as RelayAuthorizationParams, bs as ReputationResponse, bt as ReputationSummary, bu as RequestRefundOptions, u as ResourceInfoV2, S as SETTLEMENT_UNCONFIRMED, bv as SOLANA_FEEDBACK_NETWORKS, bw as SettleRequest, v as SettleRequestV2, bx as SettleResponse, by as SettleResponseWithProof, bz as SubmitRelayFeedbackRequest, bA as SubmitRelayResponseRequest, bB as SubmitSolanaFeedbackRequest, bC as TIER_FILTERS, bD as TIER_TIMINGS, bE as USDC_DOMAIN_NAME, bF as UnavailableBody, bG as UnavailableResponse, V as VerifiedPaymentState, bH as VerifyRequest, w as VerifyRequestV2, bI as VerifyResponse, W as WRITER_LEASE_REASONS, y as WriterLeaseReason, X as X402_CORS_HEADERS, z as X402_HEADER_NAMES, bJ as ZERO_ADDRESS, bK as buildErc8004PaymentRequirements, G as buildPaymentRequirements, I as buildSettleRequest, J as buildSettleRequestForVersion, K as buildSettleRequestV2, bL as buildUnavailableResponse, N as buildVerifyRequest, O as buildVerifyRequestForVersion, Q as buildVerifyRequestV2, bM as canRefundEscrow, bN as canReleaseEscrow, bO as carryFailureFields, T as create402Response, U as createHonoMiddleware, Y as createPaymentMiddleware, bP as epochToDate, bQ as escrowTimeRemaining, Z as extractPaymentFromHeaders, _ as facilitatorFetch, $ as getCorsHeaders, bR as getEscrowContractsByChainId, bS as getEscrowSupportedChainIds, bT as isAlive, a0 as isAmbiguousLeaseReason, bU as isEscrowExpired, bV as isEscrowSupportedOnChain, bW as isRegisterJobTerminal, a1 as isReplayableLeaseReason, a2 as isSettlementUnconfirmed, a4 as parseFacilitatorErrorBody, bX as parsePaymentHeader, a5 as parseRetryAfterSeconds, a6 as readFacilitatorError, a7 as resolveEnvelopeVersion, bY as supportsRelayedFeedback, bZ as supportsSolanaFeedback, a8 as toPaymentRequirementsV2, a9 as toResourceInfoV2, b_ as wireNetwork } from '../index-CIUGPbu8.mjs';
2
+ export { a as FacilitatorReceipt, F as FetchReceiptResult, P as PaymentState, b as PurchaseContext, c as RECEIPT_ISSUER, R as ReceiptFetchOptions, d as ReceiptKeys, e as canonicalReceiptJson, f as createPurchaseContext, g as fetchWithReceipt, h as getFacilitatorReceipt, p as parseFacilitatorReceipt, i as paymentResponseHeaders, j as purchaseContextHeader, r as receiptCommitment, k as receiptFromErrorBody, l as receiptFromResponse, v as validatePurchaseContext, m as verifyFacilitatorReceipt } from '../receipts-sEYlpK10.mjs';
3
+ import '../index-BsKsZzP3.mjs';
4
+ export { A as AMBIGUOUS_LEASE_REASONS, ab as AdvancedAuthorizationResult, ac as AdvancedEscrowClient, ad as AdvancedEscrowClientOptions, ae as AdvancedEscrowContracts, af as AdvancedEscrowTaskTier, ag as AdvancedPaymentInfo, ah as AdvancedTransactionResult, ai as AgentId, aj as AgentIdentity, ak as AgentRegistration, al as AgentRegistrationFile, am as AgentService, an as AtomStats, ao as BASE_MAINNET_CONTRACTS, ap as BazaarClient, aq as BazaarClientOptions, ar as BazaarDiscoverOptions, as as BazaarDiscoverResponse, at as BazaarRegisterOptions, au as BazaarResource, av as CreateEscrowOptions, D as DEFAULT_FACILITATOR_RETRIES, a as DEFAULT_RETRY_AFTER_SECONDS, aw as DEPOSIT_LIMIT_USDC, ax as DiscoveryAccepts, ay as DiscoveryCuration, az as DiscoveryHealth, aA as DiscoveryHealthStatus, aB as DiscoveryListOptions, aC as DiscoveryPagination, aD as DiscoveryRegisterOptions, aE as DiscoveryResource, aF as DiscoveryResponse, aG as DiscoverySource, aH as DiscoveryStats, aI as DiscoveryTier, aJ as Dispute, aK as DisputeOutcome, aL as ERC8004_CONTRACTS, aM as ERC8004_EXTENSION_ID, aN as ESCROW_CONTRACTS, aO as ESCROW_TIMEOUT_MS, aP as Erc8004Client, aQ as Erc8004ClientOptions, aR as Erc8004LookupError, aS as Erc8004Network, aT as EscrowClient, aU as EscrowClientOptions, aV as EscrowPayment, aW as EscrowStateResponse, aX as EscrowStatus, F as FacilitatorClient, b as FacilitatorClientOptions, c as FacilitatorErrorInfo, d as FacilitatorFailureFields, e as FacilitatorFetchOptions, aY as FeedbackEntry, aZ as FeedbackParams, a_ as FeedbackRequest, a$ as FeedbackResponse, b0 as HEALTH_FILTERS, H as HonoMiddlewareOptions, b1 as IdentityByOwnerResponse, b2 as IdentityMetadataResponse, b3 as IdentityTotalSupplyResponse, b4 as LifecycleAuthOptions, M as MAX_RETRY_AFTER_SECONDS, b5 as MAX_SEARCH_LEN, b6 as MetadataEntryParam, b7 as OPERATOR_ABI, b8 as OPERATOR_ABI_CREATE3, b9 as PAYMENT_INFO_TYPEHASH, P as ParsedFacilitatorErrorBody, q as PaymentAcceptance, r as PaymentMiddlewareOptions, s as PaymentPayloadV2, ba as PaymentRequirementResolver, bb as PaymentRequirements, bc as PaymentRequirementsOptions, t as PaymentRequirementsV2, bd as PrepareRelayFeedbackRequest, be as PrepareRelayFeedbackResponse, bf as PrepareRelayResponseRequest, bg as PrepareSolanaFeedbackRequest, bh as PrepareSolanaFeedbackResponse, bi as ProofOfPayment, bj as RELAYED_FEEDBACK_NETWORKS, R as REPLAYABLE_LEASE_REASONS, bk as RefundRequest, bl as RefundStatus, bm as RegisterAgentRequest, bn as RegisterAgentResponse, bo as RegisterJobResponse, bp as RegisterJobStatus, bq as RegistrationPendingError, br as RelayAuthorizationParams, bs as ReputationResponse, bt as ReputationSummary, bu as RequestRefundOptions, u as ResourceInfoV2, S as SETTLEMENT_UNCONFIRMED, bv as SOLANA_FEEDBACK_NETWORKS, bw as SettleRequest, v as SettleRequestV2, bx as SettleResponse, by as SettleResponseWithProof, bz as SubmitRelayFeedbackRequest, bA as SubmitRelayResponseRequest, bB as SubmitSolanaFeedbackRequest, bC as TIER_FILTERS, bD as TIER_TIMINGS, bE as USDC_DOMAIN_NAME, bF as UnavailableBody, bG as UnavailableResponse, V as VerifiedPaymentState, bH as VerifyRequest, w as VerifyRequestV2, bI as VerifyResponse, W as WRITER_LEASE_REASONS, y as WriterLeaseReason, X as X402_CORS_HEADERS, z as X402_HEADER_NAMES, bJ as ZERO_ADDRESS, bK as buildErc8004PaymentRequirements, G as buildPaymentRequirements, I as buildSettleRequest, J as buildSettleRequestForVersion, K as buildSettleRequestV2, bL as buildUnavailableResponse, N as buildVerifyRequest, O as buildVerifyRequestForVersion, Q as buildVerifyRequestV2, bM as canRefundEscrow, bN as canReleaseEscrow, bO as carryFailureFields, T as create402Response, U as createHonoMiddleware, Y as createPaymentMiddleware, bP as epochToDate, bQ as escrowTimeRemaining, Z as extractPaymentFromHeaders, _ as facilitatorFetch, $ as getCorsHeaders, bR as getEscrowContractsByChainId, bS as getEscrowSupportedChainIds, bT as isAlive, a0 as isAmbiguousLeaseReason, bU as isEscrowExpired, bV as isEscrowSupportedOnChain, bW as isRegisterJobTerminal, a1 as isReplayableLeaseReason, a2 as isSettlementUnconfirmed, a4 as parseFacilitatorErrorBody, bX as parsePaymentHeader, a5 as parseRetryAfterSeconds, a6 as readFacilitatorError, a7 as resolveEnvelopeVersion, bY as supportsRelayedFeedback, bZ as supportsSolanaFeedback, a8 as toPaymentRequirementsV2, a9 as toResourceInfoV2, b_ as wireNetwork } from '../index-DMSZJyZ9.mjs';
@@ -1,3 +1,4 @@
1
1
  import '../wallet-w7BnImDG.js';
2
- import '../index-DnxubrYX.js';
3
- export { A as AMBIGUOUS_LEASE_REASONS, ab as AdvancedAuthorizationResult, ac as AdvancedEscrowClient, ad as AdvancedEscrowClientOptions, ae as AdvancedEscrowContracts, af as AdvancedEscrowTaskTier, ag as AdvancedPaymentInfo, ah as AdvancedTransactionResult, ai as AgentId, aj as AgentIdentity, ak as AgentRegistration, al as AgentRegistrationFile, am as AgentService, an as AtomStats, ao as BASE_MAINNET_CONTRACTS, ap as BazaarClient, aq as BazaarClientOptions, ar as BazaarDiscoverOptions, as as BazaarDiscoverResponse, at as BazaarRegisterOptions, au as BazaarResource, av as CreateEscrowOptions, D as DEFAULT_FACILITATOR_RETRIES, a as DEFAULT_RETRY_AFTER_SECONDS, aw as DEPOSIT_LIMIT_USDC, ax as DiscoveryAccepts, ay as DiscoveryCuration, az as DiscoveryHealth, aA as DiscoveryHealthStatus, aB as DiscoveryListOptions, aC as DiscoveryPagination, aD as DiscoveryRegisterOptions, aE as DiscoveryResource, aF as DiscoveryResponse, aG as DiscoverySource, aH as DiscoveryStats, aI as DiscoveryTier, aJ as Dispute, aK as DisputeOutcome, aL as ERC8004_CONTRACTS, aM as ERC8004_EXTENSION_ID, aN as ESCROW_CONTRACTS, aO as ESCROW_TIMEOUT_MS, aP as Erc8004Client, aQ as Erc8004ClientOptions, aR as Erc8004LookupError, aS as Erc8004Network, aT as EscrowClient, aU as EscrowClientOptions, aV as EscrowPayment, aW as EscrowStateResponse, aX as EscrowStatus, F as FacilitatorClient, b as FacilitatorClientOptions, c as FacilitatorErrorInfo, d as FacilitatorFailureFields, e as FacilitatorFetchOptions, aY as FeedbackEntry, aZ as FeedbackParams, a_ as FeedbackRequest, a$ as FeedbackResponse, b0 as HEALTH_FILTERS, H as HonoMiddlewareOptions, b1 as IdentityByOwnerResponse, b2 as IdentityMetadataResponse, b3 as IdentityTotalSupplyResponse, b4 as LifecycleAuthOptions, M as MAX_RETRY_AFTER_SECONDS, b5 as MAX_SEARCH_LEN, b6 as MetadataEntryParam, b7 as OPERATOR_ABI, b8 as OPERATOR_ABI_CREATE3, b9 as PAYMENT_INFO_TYPEHASH, P as ParsedFacilitatorErrorBody, q as PaymentAcceptance, r as PaymentMiddlewareOptions, s as PaymentPayloadV2, ba as PaymentRequirementResolver, bb as PaymentRequirements, bc as PaymentRequirementsOptions, t as PaymentRequirementsV2, bd as PrepareRelayFeedbackRequest, be as PrepareRelayFeedbackResponse, bf as PrepareRelayResponseRequest, bg as PrepareSolanaFeedbackRequest, bh as PrepareSolanaFeedbackResponse, bi as ProofOfPayment, bj as RELAYED_FEEDBACK_NETWORKS, R as REPLAYABLE_LEASE_REASONS, bk as RefundRequest, bl as RefundStatus, bm as RegisterAgentRequest, bn as RegisterAgentResponse, bo as RegisterJobResponse, bp as RegisterJobStatus, bq as RegistrationPendingError, br as RelayAuthorizationParams, bs as ReputationResponse, bt as ReputationSummary, bu as RequestRefundOptions, u as ResourceInfoV2, S as SETTLEMENT_UNCONFIRMED, bv as SOLANA_FEEDBACK_NETWORKS, bw as SettleRequest, v as SettleRequestV2, bx as SettleResponse, by as SettleResponseWithProof, bz as SubmitRelayFeedbackRequest, bA as SubmitRelayResponseRequest, bB as SubmitSolanaFeedbackRequest, bC as TIER_FILTERS, bD as TIER_TIMINGS, bE as USDC_DOMAIN_NAME, bF as UnavailableBody, bG as UnavailableResponse, V as VerifiedPaymentState, bH as VerifyRequest, w as VerifyRequestV2, bI as VerifyResponse, W as WRITER_LEASE_REASONS, y as WriterLeaseReason, X as X402_CORS_HEADERS, z as X402_HEADER_NAMES, bJ as ZERO_ADDRESS, bK as buildErc8004PaymentRequirements, G as buildPaymentRequirements, I as buildSettleRequest, J as buildSettleRequestForVersion, K as buildSettleRequestV2, bL as buildUnavailableResponse, N as buildVerifyRequest, O as buildVerifyRequestForVersion, Q as buildVerifyRequestV2, bM as canRefundEscrow, bN as canReleaseEscrow, bO as carryFailureFields, T as create402Response, U as createHonoMiddleware, Y as createPaymentMiddleware, bP as epochToDate, bQ as escrowTimeRemaining, Z as extractPaymentFromHeaders, _ as facilitatorFetch, $ as getCorsHeaders, bR as getEscrowContractsByChainId, bS as getEscrowSupportedChainIds, bT as isAlive, a0 as isAmbiguousLeaseReason, bU as isEscrowExpired, bV as isEscrowSupportedOnChain, bW as isRegisterJobTerminal, a1 as isReplayableLeaseReason, a2 as isSettlementUnconfirmed, a4 as parseFacilitatorErrorBody, bX as parsePaymentHeader, a5 as parseRetryAfterSeconds, a6 as readFacilitatorError, a7 as resolveEnvelopeVersion, bY as supportsRelayedFeedback, bZ as supportsSolanaFeedback, a8 as toPaymentRequirementsV2, a9 as toResourceInfoV2, b_ as wireNetwork } from '../index-DTbVW7EU.js';
2
+ export { a as FacilitatorReceipt, F as FetchReceiptResult, P as PaymentState, b as PurchaseContext, c as RECEIPT_ISSUER, R as ReceiptFetchOptions, d as ReceiptKeys, e as canonicalReceiptJson, f as createPurchaseContext, g as fetchWithReceipt, h as getFacilitatorReceipt, p as parseFacilitatorReceipt, i as paymentResponseHeaders, j as purchaseContextHeader, r as receiptCommitment, k as receiptFromErrorBody, l as receiptFromResponse, v as validatePurchaseContext, m as verifyFacilitatorReceipt } from '../receipts-CwaG8BpU.js';
3
+ import '../index-BsKsZzP3.js';
4
+ export { A as AMBIGUOUS_LEASE_REASONS, ab as AdvancedAuthorizationResult, ac as AdvancedEscrowClient, ad as AdvancedEscrowClientOptions, ae as AdvancedEscrowContracts, af as AdvancedEscrowTaskTier, ag as AdvancedPaymentInfo, ah as AdvancedTransactionResult, ai as AgentId, aj as AgentIdentity, ak as AgentRegistration, al as AgentRegistrationFile, am as AgentService, an as AtomStats, ao as BASE_MAINNET_CONTRACTS, ap as BazaarClient, aq as BazaarClientOptions, ar as BazaarDiscoverOptions, as as BazaarDiscoverResponse, at as BazaarRegisterOptions, au as BazaarResource, av as CreateEscrowOptions, D as DEFAULT_FACILITATOR_RETRIES, a as DEFAULT_RETRY_AFTER_SECONDS, aw as DEPOSIT_LIMIT_USDC, ax as DiscoveryAccepts, ay as DiscoveryCuration, az as DiscoveryHealth, aA as DiscoveryHealthStatus, aB as DiscoveryListOptions, aC as DiscoveryPagination, aD as DiscoveryRegisterOptions, aE as DiscoveryResource, aF as DiscoveryResponse, aG as DiscoverySource, aH as DiscoveryStats, aI as DiscoveryTier, aJ as Dispute, aK as DisputeOutcome, aL as ERC8004_CONTRACTS, aM as ERC8004_EXTENSION_ID, aN as ESCROW_CONTRACTS, aO as ESCROW_TIMEOUT_MS, aP as Erc8004Client, aQ as Erc8004ClientOptions, aR as Erc8004LookupError, aS as Erc8004Network, aT as EscrowClient, aU as EscrowClientOptions, aV as EscrowPayment, aW as EscrowStateResponse, aX as EscrowStatus, F as FacilitatorClient, b as FacilitatorClientOptions, c as FacilitatorErrorInfo, d as FacilitatorFailureFields, e as FacilitatorFetchOptions, aY as FeedbackEntry, aZ as FeedbackParams, a_ as FeedbackRequest, a$ as FeedbackResponse, b0 as HEALTH_FILTERS, H as HonoMiddlewareOptions, b1 as IdentityByOwnerResponse, b2 as IdentityMetadataResponse, b3 as IdentityTotalSupplyResponse, b4 as LifecycleAuthOptions, M as MAX_RETRY_AFTER_SECONDS, b5 as MAX_SEARCH_LEN, b6 as MetadataEntryParam, b7 as OPERATOR_ABI, b8 as OPERATOR_ABI_CREATE3, b9 as PAYMENT_INFO_TYPEHASH, P as ParsedFacilitatorErrorBody, q as PaymentAcceptance, r as PaymentMiddlewareOptions, s as PaymentPayloadV2, ba as PaymentRequirementResolver, bb as PaymentRequirements, bc as PaymentRequirementsOptions, t as PaymentRequirementsV2, bd as PrepareRelayFeedbackRequest, be as PrepareRelayFeedbackResponse, bf as PrepareRelayResponseRequest, bg as PrepareSolanaFeedbackRequest, bh as PrepareSolanaFeedbackResponse, bi as ProofOfPayment, bj as RELAYED_FEEDBACK_NETWORKS, R as REPLAYABLE_LEASE_REASONS, bk as RefundRequest, bl as RefundStatus, bm as RegisterAgentRequest, bn as RegisterAgentResponse, bo as RegisterJobResponse, bp as RegisterJobStatus, bq as RegistrationPendingError, br as RelayAuthorizationParams, bs as ReputationResponse, bt as ReputationSummary, bu as RequestRefundOptions, u as ResourceInfoV2, S as SETTLEMENT_UNCONFIRMED, bv as SOLANA_FEEDBACK_NETWORKS, bw as SettleRequest, v as SettleRequestV2, bx as SettleResponse, by as SettleResponseWithProof, bz as SubmitRelayFeedbackRequest, bA as SubmitRelayResponseRequest, bB as SubmitSolanaFeedbackRequest, bC as TIER_FILTERS, bD as TIER_TIMINGS, bE as USDC_DOMAIN_NAME, bF as UnavailableBody, bG as UnavailableResponse, V as VerifiedPaymentState, bH as VerifyRequest, w as VerifyRequestV2, bI as VerifyResponse, W as WRITER_LEASE_REASONS, y as WriterLeaseReason, X as X402_CORS_HEADERS, z as X402_HEADER_NAMES, bJ as ZERO_ADDRESS, bK as buildErc8004PaymentRequirements, G as buildPaymentRequirements, I as buildSettleRequest, J as buildSettleRequestForVersion, K as buildSettleRequestV2, bL as buildUnavailableResponse, N as buildVerifyRequest, O as buildVerifyRequestForVersion, Q as buildVerifyRequestV2, bM as canRefundEscrow, bN as canReleaseEscrow, bO as carryFailureFields, T as create402Response, U as createHonoMiddleware, Y as createPaymentMiddleware, bP as epochToDate, bQ as escrowTimeRemaining, Z as extractPaymentFromHeaders, _ as facilitatorFetch, $ as getCorsHeaders, bR as getEscrowContractsByChainId, bS as getEscrowSupportedChainIds, bT as isAlive, a0 as isAmbiguousLeaseReason, bU as isEscrowExpired, bV as isEscrowSupportedOnChain, bW as isRegisterJobTerminal, a1 as isReplayableLeaseReason, a2 as isSettlementUnconfirmed, a4 as parseFacilitatorErrorBody, bX as parsePaymentHeader, a5 as parseRetryAfterSeconds, a6 as readFacilitatorError, a7 as resolveEnvelopeVersion, bY as supportsRelayedFeedback, bZ as supportsSolanaFeedback, a8 as toPaymentRequirementsV2, a9 as toResourceInfoV2, b_ as wireNetwork } from '../index-AGj6ViCS.js';
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ var ed25519 = require('@noble/curves/ed25519');
4
+ var sha256 = require('@noble/hashes/sha256');
5
+ var utils = require('@noble/hashes/utils');
3
6
  var ethers = require('ethers');
4
7
 
5
8
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -8,6 +11,187 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
11
  if (typeof require !== "undefined") return require.apply(this, arguments);
9
12
  throw Error('Dynamic require of "' + x + '" is not supported');
10
13
  });
14
+ var RECEIPT_ISSUER = "https://facilitator.ultravioletadao.xyz";
15
+ var encoder = new TextEncoder();
16
+ var decoder = new TextDecoder("utf-8", { fatal: true });
17
+ var digest = (value) => utils.bytesToHex(sha256.sha256(value));
18
+ function canonicalReceiptJson(value) {
19
+ if (value === null || typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
20
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return String(value);
21
+ if (Array.isArray(value)) return `[${value.map(canonicalReceiptJson).join(",")}]`;
22
+ if (typeof value === "object" && value) {
23
+ const object = value;
24
+ const keys = Object.keys(object).sort();
25
+ if (keys.some((key) => !/^[\x00-\x7f]*$/.test(key))) throw new Error("non-ASCII canonical key");
26
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalReceiptJson(object[key])}`).join(",")}}`;
27
+ }
28
+ throw new Error("unsupported canonical value");
29
+ }
30
+ function receiptCommitment(domain, value) {
31
+ return digest(encoder.encode(`${domain}
32
+ ${canonicalReceiptJson(value)}`));
33
+ }
34
+ function encode64(bytes) {
35
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
36
+ return btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join(""));
37
+ }
38
+ function decode64(value) {
39
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(value) || value.length % 4 !== 0) throw new Error("invalid base64");
40
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(value, "base64"));
41
+ return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
42
+ }
43
+ function decodeUrl64(value) {
44
+ const padded = value.replace(/-/g, "+").replace(/_/g, "/");
45
+ return decode64(padded + "=".repeat((4 - padded.length % 4) % 4));
46
+ }
47
+ function parseFacilitatorReceipt(value) {
48
+ if (value === null || value === void 0) return null;
49
+ const r = value;
50
+ if (r.schemaVersion !== 1 || !["verified", "pending", "confirmed", "rejected", "unknown"].includes(r.status)) throw new Error("unsupported receipt version or state");
51
+ for (const key of ["receiptId", "issuer", "operation", "network", "scheme", "asset", "amount", "payTo", "paymentRequestHash", "authorizationId"]) {
52
+ if (typeof r[key] !== "string" || !r[key]) throw new Error(`invalid receipt ${key}`);
53
+ }
54
+ if (!Number.isSafeInteger(r.revision) || r.revision < 1 || !r.request || !r.retry) throw new Error("incomplete receipt");
55
+ if (r.requestHashVersion !== "uvd-x402-request-v1" || r.requestHash !== receiptCommitment(r.requestHashVersion, r.request)) throw new Error("receipt request hash mismatch");
56
+ for (const key of ["network", "scheme", "asset", "amount", "payTo", "purchaseId"]) {
57
+ if (r[key] !== r.request[key]) throw new Error("receipt terms mismatch");
58
+ }
59
+ if (!/^[0-9]+$/.test(r.amount)) throw new Error("receipt amount must be an atomic integer string");
60
+ if (r.status === "confirmed" && (r.operation !== "settle" || !r.settlement?.id)) throw new Error("confirmation has no settlement");
61
+ return r;
62
+ }
63
+ function verifyFacilitatorReceipt(receipt, jwks, issuer = RECEIPT_ISSUER) {
64
+ try {
65
+ parseFacilitatorReceipt(receipt);
66
+ if (receipt.issuer !== issuer || receipt.proof?.type !== "jws" || !receipt.proof.jws) return false;
67
+ const parts = receipt.proof.jws.split(".");
68
+ if (parts.length !== 3) return false;
69
+ const [protectedHeader, payload, signature] = parts;
70
+ const header = JSON.parse(decoder.decode(decodeUrl64(protectedHeader)));
71
+ if (header.alg !== "EdDSA" || header.typ !== "uvd-facilitator-receipt+jws") return false;
72
+ const keys = jwks.keys.filter((k) => k.kid === header.kid && k.kty === "OKP" && k.crv === "Ed25519");
73
+ if (keys.length !== 1 || !keys[0].x) return false;
74
+ if (decoder.decode(decodeUrl64(payload)) !== canonicalReceiptJson({ ...receipt, proof: null })) return false;
75
+ return ed25519.ed25519.verify(decodeUrl64(signature), encoder.encode(`${protectedHeader}.${payload}`), decodeUrl64(keys[0].x));
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+ function createPurchaseContext() {
81
+ return { purchaseId: utils.bytesToHex(utils.randomBytes(16)), accessToken: utils.bytesToHex(utils.randomBytes(32)) };
82
+ }
83
+ function purchaseContextHeader(context) {
84
+ return encode64(encoder.encode(canonicalReceiptJson({
85
+ purchaseId: context.purchaseId,
86
+ accessToken: context.accessToken,
87
+ method: context.method,
88
+ url: context.url,
89
+ bodySha256: context.bodySha256
90
+ })));
91
+ }
92
+ function validatePurchaseContext(header, method, url, body) {
93
+ if (!header) return void 0;
94
+ if (header.length > 8192) throw new Error("invalid purchase context");
95
+ const context = JSON.parse(decoder.decode(decode64(header)));
96
+ if (typeof context.purchaseId !== "string" || !context.purchaseId || context.purchaseId.length > 128 || typeof context.accessToken !== "string" || !/^[0-9a-f]{64}$/.test(context.accessToken) || context.method !== method.toUpperCase() || context.url !== new URL(url).toString() || context.bodySha256 !== digest(body)) throw new Error("purchase context does not match the HTTP request");
97
+ return header;
98
+ }
99
+ function paymentResponseHeaders(result) {
100
+ const encoded = encode64(encoder.encode(JSON.stringify(result)));
101
+ if (encoded.length > 32768) throw new Error("payment response too large");
102
+ return {
103
+ "PAYMENT-RESPONSE": encoded,
104
+ "X-PAYMENT-RESPONSE": encoded,
105
+ "Access-Control-Expose-Headers": "PAYMENT-RESPONSE, X-PAYMENT-RESPONSE",
106
+ "Cache-Control": "no-store"
107
+ };
108
+ }
109
+ function receiptFromResponse(response) {
110
+ const values = [response.headers.get("PAYMENT-RESPONSE"), response.headers.get("X-PAYMENT-RESPONSE")].filter((v) => v !== null);
111
+ if (!values.length) return null;
112
+ if (new Set(values).size !== 1 || values[0].includes(",") || values[0].length > 32768) throw new Error("ambiguous or oversized payment response header");
113
+ return parseFacilitatorReceipt(JSON.parse(decoder.decode(decode64(values[0]))).receipt);
114
+ }
115
+ function receiptFromErrorBody(body) {
116
+ try {
117
+ return parseFacilitatorReceipt(JSON.parse(body).receipt);
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+ async function fetchWithReceipt(fetchClient, url, options) {
123
+ const { context, persist, trustedKeys, issuer = RECEIPT_ISSUER } = options;
124
+ const transport = options.fetchImpl || globalThis.fetch;
125
+ const method = (options.method || "GET").toUpperCase();
126
+ const request = new Request(url, { ...options.init, method });
127
+ const bytes = new Uint8Array(await request.arrayBuffer());
128
+ const bodyHash = digest(bytes);
129
+ if (context.method && (context.method !== method || context.url !== request.url || context.bodySha256 !== bodyHash)) throw new Error("purchase context cannot be reused for another HTTP request");
130
+ context.method = method;
131
+ context.url = request.url;
132
+ context.bodySha256 = bodyHash;
133
+ const init = { ...options.init, method, headers: new Headers(request.headers), body: ["GET", "HEAD"].includes(method) ? void 0 : bytes };
134
+ let receipt = parseFacilitatorReceipt(context.receipt);
135
+ let transportError;
136
+ const persistCopy = async () => {
137
+ await persist(JSON.parse(JSON.stringify(context)));
138
+ };
139
+ const send = async (input, sendOptions) => {
140
+ const headers = new Headers(sendOptions?.headers);
141
+ const paid = headers.get("X-PAYMENT") || headers.get("PAYMENT-SIGNATURE");
142
+ if (paid) {
143
+ const paymentHeaders = {};
144
+ for (const name of ["X-PAYMENT", "PAYMENT-SIGNATURE"]) {
145
+ const value = headers.get(name);
146
+ if (value) paymentHeaders[name] = value;
147
+ }
148
+ if (context.paymentHeaders && JSON.stringify(context.paymentHeaders) !== JSON.stringify(paymentHeaders)) throw new Error("refusing a new authorization for an existing purchase");
149
+ context.paymentHeaders = paymentHeaders;
150
+ headers.set("X-UVD-Purchase", purchaseContextHeader(context));
151
+ await persistCopy();
152
+ }
153
+ try {
154
+ return await transport(input, { ...sendOptions, headers });
155
+ } catch (error) {
156
+ transportError = error;
157
+ throw error;
158
+ }
159
+ };
160
+ try {
161
+ let response;
162
+ if (context.paymentHeaders) {
163
+ const headers = new Headers(init.headers);
164
+ for (const [name, value] of Object.entries(context.paymentHeaders)) headers.set(name, value);
165
+ response = await send(request.url, { ...init, headers });
166
+ } else {
167
+ response = await fetchClient(request.url, { ...options, method, init, fetchImpl: send });
168
+ }
169
+ const incoming = receiptFromResponse(response);
170
+ if (incoming) {
171
+ if (incoming.issuer !== issuer || Object.entries({ purchaseId: context.purchaseId, method, url: context.url, bodySha256: bodyHash }).some(([key, value]) => incoming.request[key] !== value)) throw new Error("receipt does not bind this purchase");
172
+ if (receipt?.operation === "settle" && (incoming.receiptId !== receipt.receiptId || incoming.revision < receipt.revision)) throw new Error("receipt revision conflict");
173
+ if (trustedKeys && !verifyFacilitatorReceipt(incoming, trustedKeys, issuer)) throw new Error("receipt signature verification failed");
174
+ receipt = incoming;
175
+ context.receipt = incoming;
176
+ await persistCopy();
177
+ }
178
+ const proofVerified = !!(receipt && trustedKeys && verifyFacilitatorReceipt(receipt, trustedKeys, issuer));
179
+ if (receipt && trustedKeys && !proofVerified) throw new Error("receipt signature verification failed");
180
+ return { response, receipt, paymentState: receipt ? receipt.status : context.paymentHeaders ? "unknown" : "not_required", context, proofVerified };
181
+ } catch (error) {
182
+ if (!transportError) throw error;
183
+ return { response: null, receipt, paymentState: "unknown", context, proofVerified: false, error };
184
+ }
185
+ }
186
+ async function getFacilitatorReceipt(receiptId, context, options = {}) {
187
+ if (!/^[0-9a-f-]{36}$/.test(receiptId)) throw new Error("invalid receipt ID");
188
+ const issuer = options.issuer || RECEIPT_ISSUER;
189
+ const response = await (options.fetchImpl || globalThis.fetch)(`${issuer}/receipts/${receiptId}`, { headers: { Authorization: `Bearer ${context.accessToken}` } });
190
+ if (!response.ok) throw new Error(`receipt lookup failed: ${response.status}`);
191
+ const receipt = parseFacilitatorReceipt((await response.json()).receipt);
192
+ if (!receipt || receipt.issuer !== issuer || receipt.purchaseId !== context.purchaseId) throw new Error("receipt lookup mismatch");
193
+ return receipt;
194
+ }
11
195
 
12
196
  // src/utils/base64.ts
13
197
  function decodeBase64Utf8(encoded) {
@@ -1853,7 +2037,7 @@ function buildSettleRequestForVersion(paymentHeader, requirements, version) {
1853
2037
  return buildSettleRequest(paymentHeader, requirements);
1854
2038
  }
1855
2039
  var X402_CORS_HEADERS = {
1856
- "Access-Control-Allow-Headers": "Content-Type, X-PAYMENT, PAYMENT-SIGNATURE, Authorization",
2040
+ "Access-Control-Allow-Headers": "Content-Type, X-PAYMENT, PAYMENT-SIGNATURE, X-UVD-Purchase, Authorization",
1857
2041
  "Access-Control-Expose-Headers": "X-PAYMENT-RESPONSE, PAYMENT-RESPONSE, PAYMENT-REQUIRED",
1858
2042
  "Access-Control-Allow-Methods": "GET, POST, OPTIONS"
1859
2043
  };
@@ -1862,7 +2046,8 @@ var X402_HEADER_NAMES = [
1862
2046
  "PAYMENT-SIGNATURE",
1863
2047
  "X-PAYMENT-RESPONSE",
1864
2048
  "PAYMENT-RESPONSE",
1865
- "PAYMENT-REQUIRED"
2049
+ "PAYMENT-REQUIRED",
2050
+ "X-UVD-Purchase"
1866
2051
  ];
1867
2052
  function getCorsHeaders(origin = "*") {
1868
2053
  return {
@@ -1906,7 +2091,7 @@ var FacilitatorClient = class {
1906
2091
  * @param requirements - Payment requirements
1907
2092
  * @returns Verification result
1908
2093
  */
1909
- async verify(paymentHeader, requirements) {
2094
+ async verify(paymentHeader, requirements, options = {}) {
1910
2095
  const body = buildVerifyRequestForVersion(
1911
2096
  paymentHeader,
1912
2097
  requirements,
@@ -1917,7 +2102,7 @@ var FacilitatorClient = class {
1917
2102
  `${this.baseUrl}/verify`,
1918
2103
  {
1919
2104
  method: "POST",
1920
- headers: { "Content-Type": "application/json" },
2105
+ headers: { "Content-Type": "application/json", ...options.receiptContext ? { "X-UVD-Purchase": options.receiptContext } : {} },
1921
2106
  body: JSON.stringify(body)
1922
2107
  },
1923
2108
  { timeoutMs: this.timeout, retries: this.retries }
@@ -1926,10 +2111,12 @@ var FacilitatorClient = class {
1926
2111
  return {
1927
2112
  isValid: false,
1928
2113
  invalidReason: error.error,
1929
- ...failureFields(error)
2114
+ ...failureFields(error),
2115
+ receipt: receiptFromErrorBody(error.body)
1930
2116
  };
1931
2117
  }
1932
- return await response.json();
2118
+ const result = await response.json();
2119
+ return { ...result, receipt: parseFacilitatorReceipt(result.receipt) };
1933
2120
  } catch (error) {
1934
2121
  return {
1935
2122
  isValid: false,
@@ -1949,7 +2136,7 @@ var FacilitatorClient = class {
1949
2136
  * @param requirements - Payment requirements
1950
2137
  * @returns Settlement result with transaction hash
1951
2138
  */
1952
- async settle(paymentHeader, requirements) {
2139
+ async settle(paymentHeader, requirements, options = {}) {
1953
2140
  const body = buildSettleRequestForVersion(
1954
2141
  paymentHeader,
1955
2142
  requirements,
@@ -1961,7 +2148,7 @@ var FacilitatorClient = class {
1961
2148
  `${this.baseUrl}/settle`,
1962
2149
  {
1963
2150
  method: "POST",
1964
- headers: { "Content-Type": "application/json" },
2151
+ headers: { "Content-Type": "application/json", ...options.receiptContext ? { "X-UVD-Purchase": options.receiptContext } : {} },
1965
2152
  body: JSON.stringify(body)
1966
2153
  },
1967
2154
  { timeoutMs: settleTimeout, retries: this.retries }
@@ -1970,7 +2157,8 @@ var FacilitatorClient = class {
1970
2157
  return {
1971
2158
  success: false,
1972
2159
  error: error.error,
1973
- ...failureFields(error)
2160
+ ...failureFields(error),
2161
+ receipt: receiptFromErrorBody(error.body)
1974
2162
  };
1975
2163
  }
1976
2164
  const result = await response.json();
@@ -2008,7 +2196,10 @@ var FacilitatorClient = class {
2008
2196
  // facilitator returns it, and this method threw it away — so a seller
2009
2197
  // using the SDK end to end could only ever produce provisional anchors.
2010
2198
  proofOfPayment: result.proofOfPayment ?? result.proof_of_payment,
2011
- payer: result.payer
2199
+ payer: result.payer,
2200
+ receipt: parseFacilitatorReceipt(result.receipt),
2201
+ paymentId: result.paymentId,
2202
+ ...result.receipt?.status === "unknown" || result.receipt?.status === "pending" ? { retryable: true, safeToReplay: false } : {}
2012
2203
  };
2013
2204
  } catch (error) {
2014
2205
  return {
@@ -2434,7 +2625,7 @@ async function resolvePaymentRequirement(payment, requirements, resolver) {
2434
2625
  }
2435
2626
  return { requirement: matches[0] };
2436
2627
  }
2437
- function createVerifiedPaymentState(client, payment, requirements, verifyResult) {
2628
+ function createVerifiedPaymentState(client, payment, requirements, verifyResult, receiptContext, onSettled) {
2438
2629
  let settlePromise = null;
2439
2630
  return {
2440
2631
  payment,
@@ -2442,7 +2633,10 @@ function createVerifiedPaymentState(client, payment, requirements, verifyResult)
2442
2633
  verifyResult,
2443
2634
  settle: () => {
2444
2635
  if (!settlePromise) {
2445
- settlePromise = client.settle(payment, requirements);
2636
+ settlePromise = client.settle(payment, requirements, { receiptContext }).then((result) => {
2637
+ onSettled?.(result);
2638
+ return result;
2639
+ });
2446
2640
  }
2447
2641
  return settlePromise;
2448
2642
  }
@@ -2489,7 +2683,21 @@ function createPaymentMiddleware(getRequirements, options = {}) {
2489
2683
  }
2490
2684
  const reqOptions = getRequirements(req);
2491
2685
  const requirements = buildPaymentRequirements(reqOptions);
2492
- const verifyResult = await client.verify(payment, requirements);
2686
+ let receiptContext;
2687
+ try {
2688
+ const entry = Object.entries(req.headers).find(([name]) => name.toLowerCase() === "x-uvd-purchase")?.[1];
2689
+ if (entry !== void 0) {
2690
+ if (typeof entry !== "string" || !req.method || !["GET", "HEAD"].includes(req.method.toUpperCase()) && !req.rawBody) throw new Error("receipt context requires method and exact raw body");
2691
+ const actualUrl = new URL(req.originalUrl || req.url || reqOptions.resource, reqOptions.resource).toString();
2692
+ receiptContext = validatePurchaseContext(entry, req.method, actualUrl, req.rawBody || new Uint8Array());
2693
+ requirements.resource = actualUrl;
2694
+ }
2695
+ } catch {
2696
+ res.status(400).json({ error: "receipt_context_mismatch" });
2697
+ return;
2698
+ }
2699
+ const verifyResult = await client.verify(payment, requirements, { receiptContext });
2700
+ if (verifyResult.receipt) res.set?.(paymentResponseHeaders({ ...verifyResult }));
2493
2701
  if (!verifyResult.isValid) {
2494
2702
  if (verifyResult.retryable) {
2495
2703
  respondUnavailable(res, "Payment verification unavailable", verifyResult);
@@ -2501,7 +2709,9 @@ function createPaymentMiddleware(getRequirements, options = {}) {
2501
2709
  });
2502
2710
  return;
2503
2711
  }
2504
- req.x402 = createVerifiedPaymentState(client, payment, requirements, verifyResult);
2712
+ req.x402 = createVerifiedPaymentState(client, payment, requirements, verifyResult, receiptContext, (result) => {
2713
+ if (result.receipt) res.set?.(paymentResponseHeaders({ ...result }));
2714
+ });
2505
2715
  if (settlementStrategy === "before-handler") {
2506
2716
  const settleResult = await req.x402.settle();
2507
2717
  if (!settleResult.success) {
@@ -2544,7 +2754,7 @@ function createHonoMiddleware(options) {
2544
2754
  throw new Error("At least one accept entry is required");
2545
2755
  }
2546
2756
  return async (c, next) => {
2547
- const paymentHeader = c.req.header("X-PAYMENT") || c.req.header("x-payment");
2757
+ const paymentHeader = c.req.header("PAYMENT-SIGNATURE") || c.req.header("X-PAYMENT") || c.req.header("x-payment");
2548
2758
  const advertisedVersion = resolveAdvertisedVersion(options.accepts, options.x402Version);
2549
2759
  const advertisedRequirements = options.accepts.map(
2550
2760
  (accept) => buildRequirementFromAcceptance(accept, c.req.url, advertisedVersion)
@@ -2575,7 +2785,20 @@ function createHonoMiddleware(options) {
2575
2785
  reason
2576
2786
  }, 402);
2577
2787
  }
2578
- const verifyResult = await client.verify(parsed, requirement);
2788
+ let receiptContext;
2789
+ try {
2790
+ const header = c.req.header("X-UVD-Purchase");
2791
+ if (header) {
2792
+ const method = c.req.method || c.req.raw?.method;
2793
+ if (!method || !["GET", "HEAD"].includes(method) && !c.req.raw) throw new Error("raw request required");
2794
+ const bytes = c.req.raw ? new Uint8Array(await c.req.raw.clone().arrayBuffer()) : new Uint8Array();
2795
+ receiptContext = validatePurchaseContext(header, method, c.req.url, bytes);
2796
+ }
2797
+ } catch {
2798
+ return c.json({ error: "receipt_context_mismatch" }, 400);
2799
+ }
2800
+ const verifyResult = await client.verify(parsed, requirement, { receiptContext });
2801
+ if (verifyResult.receipt) for (const [name, value] of Object.entries(paymentResponseHeaders({ ...verifyResult }))) c.header?.(name, value);
2579
2802
  if (!verifyResult.isValid) {
2580
2803
  if (verifyResult.retryable) {
2581
2804
  return honoUnavailable(c, "Payment verification unavailable", verifyResult);
@@ -2585,7 +2808,9 @@ function createHonoMiddleware(options) {
2585
2808
  reason: verifyResult.invalidReason
2586
2809
  }, 402);
2587
2810
  }
2588
- const verifiedPayment = createVerifiedPaymentState(client, parsed, requirement, verifyResult);
2811
+ const verifiedPayment = createVerifiedPaymentState(client, parsed, requirement, verifyResult, receiptContext, (result) => {
2812
+ if (result.receipt) for (const [name, value] of Object.entries(paymentResponseHeaders({ ...result }))) c.header?.(name, value);
2813
+ });
2589
2814
  c.set?.("x402", verifiedPayment);
2590
2815
  if (settlementStrategy === "before-handler") {
2591
2816
  const settleResult = await verifiedPayment.settle();
@@ -5501,6 +5726,7 @@ exports.MAX_SEARCH_LEN = MAX_SEARCH_LEN;
5501
5726
  exports.OPERATOR_ABI = OPERATOR_ABI;
5502
5727
  exports.OPERATOR_ABI_CREATE3 = OPERATOR_ABI_CREATE3;
5503
5728
  exports.PAYMENT_INFO_TYPEHASH = PAYMENT_INFO_TYPEHASH;
5729
+ exports.RECEIPT_ISSUER = RECEIPT_ISSUER;
5504
5730
  exports.RELAYED_FEEDBACK_NETWORKS = RELAYED_FEEDBACK_NETWORKS;
5505
5731
  exports.REPLAYABLE_LEASE_REASONS = REPLAYABLE_LEASE_REASONS;
5506
5732
  exports.RegistrationPendingError = RegistrationPendingError;
@@ -5524,17 +5750,21 @@ exports.buildVerifyRequestForVersion = buildVerifyRequestForVersion;
5524
5750
  exports.buildVerifyRequestV2 = buildVerifyRequestV2;
5525
5751
  exports.canRefundEscrow = canRefundEscrow;
5526
5752
  exports.canReleaseEscrow = canReleaseEscrow;
5753
+ exports.canonicalReceiptJson = canonicalReceiptJson;
5527
5754
  exports.carryFailureFields = carryFailureFields;
5528
5755
  exports.create402Response = create402Response;
5529
5756
  exports.createHonoMiddleware = createHonoMiddleware;
5530
5757
  exports.createPaymentMiddleware = createPaymentMiddleware;
5758
+ exports.createPurchaseContext = createPurchaseContext;
5531
5759
  exports.epochToDate = epochToDate;
5532
5760
  exports.escrowTimeRemaining = escrowTimeRemaining;
5533
5761
  exports.extractPaymentFromHeaders = extractPaymentFromHeaders;
5534
5762
  exports.facilitatorFetch = facilitatorFetch;
5763
+ exports.fetchWithReceipt = fetchWithReceipt;
5535
5764
  exports.getCorsHeaders = getCorsHeaders;
5536
5765
  exports.getEscrowContractsByChainId = getEscrowContractsByChainId;
5537
5766
  exports.getEscrowSupportedChainIds = getEscrowSupportedChainIds;
5767
+ exports.getFacilitatorReceipt = getFacilitatorReceipt;
5538
5768
  exports.isAlive = isAlive;
5539
5769
  exports.isAmbiguousLeaseReason = isAmbiguousLeaseReason;
5540
5770
  exports.isEscrowExpired = isEscrowExpired;
@@ -5543,14 +5773,22 @@ exports.isRegisterJobTerminal = isRegisterJobTerminal;
5543
5773
  exports.isReplayableLeaseReason = isReplayableLeaseReason;
5544
5774
  exports.isSettlementUnconfirmed = isSettlementUnconfirmed;
5545
5775
  exports.parseFacilitatorErrorBody = parseFacilitatorErrorBody;
5776
+ exports.parseFacilitatorReceipt = parseFacilitatorReceipt;
5546
5777
  exports.parsePaymentHeader = parsePaymentHeader;
5547
5778
  exports.parseRetryAfterSeconds = parseRetryAfterSeconds;
5779
+ exports.paymentResponseHeaders = paymentResponseHeaders;
5780
+ exports.purchaseContextHeader = purchaseContextHeader;
5548
5781
  exports.readFacilitatorError = readFacilitatorError;
5782
+ exports.receiptCommitment = receiptCommitment;
5783
+ exports.receiptFromErrorBody = receiptFromErrorBody;
5784
+ exports.receiptFromResponse = receiptFromResponse;
5549
5785
  exports.resolveEnvelopeVersion = resolveEnvelopeVersion;
5550
5786
  exports.supportsRelayedFeedback = supportsRelayedFeedback;
5551
5787
  exports.supportsSolanaFeedback = supportsSolanaFeedback;
5552
5788
  exports.toPaymentRequirementsV2 = toPaymentRequirementsV2;
5553
5789
  exports.toResourceInfoV2 = toResourceInfoV2;
5790
+ exports.validatePurchaseContext = validatePurchaseContext;
5791
+ exports.verifyFacilitatorReceipt = verifyFacilitatorReceipt;
5554
5792
  exports.wireNetwork = wireNetwork;
5555
5793
  //# sourceMappingURL=index.js.map
5556
5794
  //# sourceMappingURL=index.js.map