uvd-x402-sdk 2.29.0 → 2.31.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 CHANGED
@@ -526,23 +526,32 @@ app.post('/api/premium', async (req, res) => {
526
526
  return res.status(status).set(headers).json(body);
527
527
  }
528
528
 
529
- // Verify and settle
529
+ // Verify first, then settle when you're ready to fulfill the request
530
530
  const client = new FacilitatorClient();
531
531
  const requirements = buildPaymentRequirements({
532
532
  amount: '1.00',
533
533
  recipient: process.env.RECIPIENT,
534
+ resource: 'https://api.example.com/premium',
535
+ chainName: 'base',
536
+ x402Version: payment.x402Version,
534
537
  });
535
538
 
536
- const result = await client.verifyAndSettle(payment, requirements);
539
+ const verifyResult = await client.verify(payment, requirements);
540
+ if (!verifyResult.isValid) {
541
+ return res.status(402).json({ error: verifyResult.invalidReason });
542
+ }
537
543
 
538
- if (!result.verified) {
539
- return res.status(402).json({ error: result.error });
544
+ const settleResult = await client.settle(payment, requirements);
545
+ if (!settleResult.success) {
546
+ return res.status(500).json({ error: settleResult.error });
540
547
  }
541
548
 
542
- res.json({ data: 'premium content', txHash: result.transactionHash });
549
+ res.json({ data: 'premium content', txHash: settleResult.transactionHash });
543
550
  });
544
551
  ```
545
552
 
553
+ `createPaymentMiddleware()` and `createHonoMiddleware()` verify by default and attach settlement context for manual control. Use `settlementStrategy: 'before-handler'` only if you intentionally want eager settlement before your handler runs.
554
+
546
555
  ## React
547
556
 
548
557
  ```tsx
@@ -149,6 +149,52 @@ interface PaymentRequirementsOptions {
149
149
  /** x402 version to use */
150
150
  x402Version?: X402Version;
151
151
  }
152
+ /**
153
+ * x402 payment option advertised in a 402 response.
154
+ *
155
+ * The SDK keeps the response shape richer than the minimal protocol fields so
156
+ * servers can preserve settlement-critical metadata such as payTo and extra.
157
+ */
158
+ interface PaymentAcceptance {
159
+ network: string;
160
+ asset: string;
161
+ amount: string;
162
+ payTo?: string;
163
+ facilitator?: string;
164
+ resource?: string;
165
+ description?: string;
166
+ mimeType?: string;
167
+ maxTimeoutSeconds?: number;
168
+ outputSchema?: unknown;
169
+ extra?: unknown;
170
+ }
171
+ /**
172
+ * Verified payment context attached by server middleware.
173
+ */
174
+ interface VerifiedPaymentState {
175
+ payment: X402Header;
176
+ requirements: PaymentRequirements;
177
+ verifyResult: VerifyResponse;
178
+ settle: () => Promise<SettleResponse>;
179
+ }
180
+ /**
181
+ * Shared server middleware options.
182
+ */
183
+ interface PaymentMiddlewareOptions extends FacilitatorClientOptions {
184
+ /** Alias for baseUrl to keep middleware options ergonomic */
185
+ facilitatorUrl?: string;
186
+ /**
187
+ * Settlement behavior after verification.
188
+ * - manual: verify only; caller settles explicitly
189
+ * - before-handler: settle immediately before calling next()
190
+ */
191
+ settlementStrategy?: 'manual' | 'before-handler';
192
+ }
193
+ /**
194
+ * Custom resolver for selecting the correct payment requirement when multiple
195
+ * accepts are advertised.
196
+ */
197
+ type PaymentRequirementResolver = (payment: X402Header, requirements: PaymentRequirements[]) => PaymentRequirements | null | Promise<PaymentRequirements | null>;
152
198
  /**
153
199
  * Parse X-PAYMENT or PAYMENT-SIGNATURE header value
154
200
  *
@@ -448,11 +494,7 @@ declare class FacilitatorClient {
448
494
  * ```
449
495
  */
450
496
  declare function create402Response(requirements: PaymentRequirementsOptions, options?: {
451
- accepts?: Array<{
452
- network: string;
453
- asset: string;
454
- amount: string;
455
- }>;
497
+ accepts?: PaymentAcceptance[];
456
498
  }): {
457
499
  status: 402;
458
500
  headers: Record<string, string>;
@@ -476,15 +518,21 @@ declare function create402Response(requirements: PaymentRequirementsOptions, opt
476
518
  * { facilitatorUrl: 'https://facilitator.uvd.xyz' }
477
519
  * );
478
520
  *
479
- * app.get('/premium/*', paymentMiddleware, (req, res) => {
521
+ * app.get('/premium/*', paymentMiddleware, async (req, res) => {
522
+ * const settleResult = await req.x402?.settle();
523
+ * if (!settleResult?.success) {
524
+ * return res.status(500).json({ error: settleResult?.error });
525
+ * }
526
+ *
480
527
  * res.json({ premium: 'data' });
481
528
  * });
482
529
  * ```
483
530
  */
484
531
  declare function createPaymentMiddleware(getRequirements: (req: {
485
532
  headers: Record<string, string | string[] | undefined>;
486
- }) => PaymentRequirementsOptions, options?: FacilitatorClientOptions): (req: {
533
+ }) => PaymentRequirementsOptions, options?: PaymentMiddlewareOptions): (req: {
487
534
  headers: Record<string, string | string[] | undefined>;
535
+ x402?: VerifiedPaymentState;
488
536
  }, res: {
489
537
  status: (code: number) => {
490
538
  json: (body: unknown) => void;
@@ -493,6 +541,56 @@ declare function createPaymentMiddleware(getRequirements: (req: {
493
541
  };
494
542
  };
495
543
  }, next: () => void) => Promise<void>;
544
+ /**
545
+ * Options for creating a Hono x402 payment middleware
546
+ */
547
+ interface HonoMiddlewareOptions extends PaymentMiddlewareOptions {
548
+ /** Payment requirements to advertise */
549
+ accepts: PaymentAcceptance[];
550
+ /** Response version to advertise (defaults to auto) */
551
+ x402Version?: X402Version | 'auto';
552
+ /** Custom requirement resolver for ambiguous multi-accept flows */
553
+ resolveRequirement?: PaymentRequirementResolver;
554
+ }
555
+ /**
556
+ * Create a Hono-compatible middleware for x402 payments.
557
+ *
558
+ * Handles the x402 payment flow:
559
+ * 1. Returns 402 with payment requirements if no X-PAYMENT header
560
+ * 2. Verifies the payment with the facilitator
561
+ * 3. Optionally settles before the handler when settlementStrategy is set
562
+ * 4. Passes control to the next handler on success
563
+ *
564
+ * @param options - Middleware options with facilitator URL and payment accepts
565
+ * @returns Hono middleware function
566
+ *
567
+ * @example
568
+ * ```ts
569
+ * import { createHonoMiddleware } from 'uvd-x402-sdk';
570
+ *
571
+ * const paywall = createHonoMiddleware({
572
+ * accepts: [{
573
+ * network: 'skale-base',
574
+ * asset: '0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20',
575
+ * amount: '1000000',
576
+ * payTo: '0xYourWallet',
577
+ * extra: { name: 'Bridged USDC (SKALE Bridge)', version: '2' },
578
+ * }],
579
+ * });
580
+ *
581
+ * app.get('/api/premium', paywall, (c) => {
582
+ * return c.json({ message: 'Premium content!' });
583
+ * });
584
+ * ```
585
+ */
586
+ declare function createHonoMiddleware(options: HonoMiddlewareOptions): (c: {
587
+ req: {
588
+ header: (name: string) => string | undefined;
589
+ url: string;
590
+ };
591
+ json: (body: unknown, status?: number) => unknown;
592
+ set?: (key: string, value: unknown) => void;
593
+ }, next: () => Promise<void>) => Promise<unknown>;
496
594
  /**
497
595
  * Resource category for discovery
498
596
  */
@@ -2035,4 +2133,4 @@ declare class AdvancedEscrowClient {
2035
2133
  refundPostEscrow(paymentInfo: AdvancedPaymentInfo, amount?: string, tokenCollector?: string, collectorData?: string): Promise<AdvancedTransactionResult>;
2036
2134
  }
2037
2135
 
2038
- export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentId, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, ESCROW_TIMEOUT_MS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStateResponse, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };
2136
+ export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentId, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, ESCROW_TIMEOUT_MS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStateResponse, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type HonoMiddlewareOptions, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentAcceptance, type PaymentMiddlewareOptions, type PaymentRequirementResolver, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifiedPaymentState, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createHonoMiddleware, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };
@@ -149,6 +149,52 @@ interface PaymentRequirementsOptions {
149
149
  /** x402 version to use */
150
150
  x402Version?: X402Version;
151
151
  }
152
+ /**
153
+ * x402 payment option advertised in a 402 response.
154
+ *
155
+ * The SDK keeps the response shape richer than the minimal protocol fields so
156
+ * servers can preserve settlement-critical metadata such as payTo and extra.
157
+ */
158
+ interface PaymentAcceptance {
159
+ network: string;
160
+ asset: string;
161
+ amount: string;
162
+ payTo?: string;
163
+ facilitator?: string;
164
+ resource?: string;
165
+ description?: string;
166
+ mimeType?: string;
167
+ maxTimeoutSeconds?: number;
168
+ outputSchema?: unknown;
169
+ extra?: unknown;
170
+ }
171
+ /**
172
+ * Verified payment context attached by server middleware.
173
+ */
174
+ interface VerifiedPaymentState {
175
+ payment: X402Header;
176
+ requirements: PaymentRequirements;
177
+ verifyResult: VerifyResponse;
178
+ settle: () => Promise<SettleResponse>;
179
+ }
180
+ /**
181
+ * Shared server middleware options.
182
+ */
183
+ interface PaymentMiddlewareOptions extends FacilitatorClientOptions {
184
+ /** Alias for baseUrl to keep middleware options ergonomic */
185
+ facilitatorUrl?: string;
186
+ /**
187
+ * Settlement behavior after verification.
188
+ * - manual: verify only; caller settles explicitly
189
+ * - before-handler: settle immediately before calling next()
190
+ */
191
+ settlementStrategy?: 'manual' | 'before-handler';
192
+ }
193
+ /**
194
+ * Custom resolver for selecting the correct payment requirement when multiple
195
+ * accepts are advertised.
196
+ */
197
+ type PaymentRequirementResolver = (payment: X402Header, requirements: PaymentRequirements[]) => PaymentRequirements | null | Promise<PaymentRequirements | null>;
152
198
  /**
153
199
  * Parse X-PAYMENT or PAYMENT-SIGNATURE header value
154
200
  *
@@ -448,11 +494,7 @@ declare class FacilitatorClient {
448
494
  * ```
449
495
  */
450
496
  declare function create402Response(requirements: PaymentRequirementsOptions, options?: {
451
- accepts?: Array<{
452
- network: string;
453
- asset: string;
454
- amount: string;
455
- }>;
497
+ accepts?: PaymentAcceptance[];
456
498
  }): {
457
499
  status: 402;
458
500
  headers: Record<string, string>;
@@ -476,15 +518,21 @@ declare function create402Response(requirements: PaymentRequirementsOptions, opt
476
518
  * { facilitatorUrl: 'https://facilitator.uvd.xyz' }
477
519
  * );
478
520
  *
479
- * app.get('/premium/*', paymentMiddleware, (req, res) => {
521
+ * app.get('/premium/*', paymentMiddleware, async (req, res) => {
522
+ * const settleResult = await req.x402?.settle();
523
+ * if (!settleResult?.success) {
524
+ * return res.status(500).json({ error: settleResult?.error });
525
+ * }
526
+ *
480
527
  * res.json({ premium: 'data' });
481
528
  * });
482
529
  * ```
483
530
  */
484
531
  declare function createPaymentMiddleware(getRequirements: (req: {
485
532
  headers: Record<string, string | string[] | undefined>;
486
- }) => PaymentRequirementsOptions, options?: FacilitatorClientOptions): (req: {
533
+ }) => PaymentRequirementsOptions, options?: PaymentMiddlewareOptions): (req: {
487
534
  headers: Record<string, string | string[] | undefined>;
535
+ x402?: VerifiedPaymentState;
488
536
  }, res: {
489
537
  status: (code: number) => {
490
538
  json: (body: unknown) => void;
@@ -493,6 +541,56 @@ declare function createPaymentMiddleware(getRequirements: (req: {
493
541
  };
494
542
  };
495
543
  }, next: () => void) => Promise<void>;
544
+ /**
545
+ * Options for creating a Hono x402 payment middleware
546
+ */
547
+ interface HonoMiddlewareOptions extends PaymentMiddlewareOptions {
548
+ /** Payment requirements to advertise */
549
+ accepts: PaymentAcceptance[];
550
+ /** Response version to advertise (defaults to auto) */
551
+ x402Version?: X402Version | 'auto';
552
+ /** Custom requirement resolver for ambiguous multi-accept flows */
553
+ resolveRequirement?: PaymentRequirementResolver;
554
+ }
555
+ /**
556
+ * Create a Hono-compatible middleware for x402 payments.
557
+ *
558
+ * Handles the x402 payment flow:
559
+ * 1. Returns 402 with payment requirements if no X-PAYMENT header
560
+ * 2. Verifies the payment with the facilitator
561
+ * 3. Optionally settles before the handler when settlementStrategy is set
562
+ * 4. Passes control to the next handler on success
563
+ *
564
+ * @param options - Middleware options with facilitator URL and payment accepts
565
+ * @returns Hono middleware function
566
+ *
567
+ * @example
568
+ * ```ts
569
+ * import { createHonoMiddleware } from 'uvd-x402-sdk';
570
+ *
571
+ * const paywall = createHonoMiddleware({
572
+ * accepts: [{
573
+ * network: 'skale-base',
574
+ * asset: '0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20',
575
+ * amount: '1000000',
576
+ * payTo: '0xYourWallet',
577
+ * extra: { name: 'Bridged USDC (SKALE Bridge)', version: '2' },
578
+ * }],
579
+ * });
580
+ *
581
+ * app.get('/api/premium', paywall, (c) => {
582
+ * return c.json({ message: 'Premium content!' });
583
+ * });
584
+ * ```
585
+ */
586
+ declare function createHonoMiddleware(options: HonoMiddlewareOptions): (c: {
587
+ req: {
588
+ header: (name: string) => string | undefined;
589
+ url: string;
590
+ };
591
+ json: (body: unknown, status?: number) => unknown;
592
+ set?: (key: string, value: unknown) => void;
593
+ }, next: () => Promise<void>) => Promise<unknown>;
496
594
  /**
497
595
  * Resource category for discovery
498
596
  */
@@ -2035,4 +2133,4 @@ declare class AdvancedEscrowClient {
2035
2133
  refundPostEscrow(paymentInfo: AdvancedPaymentInfo, amount?: string, tokenCollector?: string, collectorData?: string): Promise<AdvancedTransactionResult>;
2036
2134
  }
2037
2135
 
2038
- export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentId, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, ESCROW_TIMEOUT_MS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStateResponse, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };
2136
+ export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentId, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, ESCROW_TIMEOUT_MS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStateResponse, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type HonoMiddlewareOptions, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentAcceptance, type PaymentMiddlewareOptions, type PaymentRequirementResolver, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifiedPaymentState, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createHonoMiddleware, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };