@nevermined-io/payments 1.1.18 → 1.3.2

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 (50) hide show
  1. package/dist/a2a/clientRegistry.d.ts.map +1 -1
  2. package/dist/a2a/clientRegistry.js +2 -2
  3. package/dist/a2a/clientRegistry.js.map +1 -1
  4. package/dist/a2a/paymentsClient.d.ts +2 -2
  5. package/dist/a2a/paymentsClient.d.ts.map +1 -1
  6. package/dist/a2a/paymentsClient.js +10 -6
  7. package/dist/a2a/paymentsClient.js.map +1 -1
  8. package/dist/a2a/server.d.ts.map +1 -1
  9. package/dist/a2a/server.js +3 -1
  10. package/dist/a2a/server.js.map +1 -1
  11. package/dist/a2a/types.d.ts +1 -0
  12. package/dist/a2a/types.d.ts.map +1 -1
  13. package/dist/a2a/types.js.map +1 -1
  14. package/dist/api/plans-api.d.ts +12 -2
  15. package/dist/api/plans-api.d.ts.map +1 -1
  16. package/dist/api/plans-api.js +16 -3
  17. package/dist/api/plans-api.js.map +1 -1
  18. package/dist/common/types.d.ts +70 -7
  19. package/dist/common/types.d.ts.map +1 -1
  20. package/dist/common/types.js +16 -0
  21. package/dist/common/types.js.map +1 -1
  22. package/dist/index.d.ts +2 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/plans.d.ts +13 -2
  27. package/dist/plans.d.ts.map +1 -1
  28. package/dist/plans.js +19 -2
  29. package/dist/plans.js.map +1 -1
  30. package/dist/x402/delegation-api.d.ts +92 -19
  31. package/dist/x402/delegation-api.d.ts.map +1 -1
  32. package/dist/x402/delegation-api.js +65 -23
  33. package/dist/x402/delegation-api.js.map +1 -1
  34. package/dist/x402/express/middleware.d.ts +4 -0
  35. package/dist/x402/express/middleware.d.ts.map +1 -1
  36. package/dist/x402/express/middleware.js +7 -4
  37. package/dist/x402/express/middleware.js.map +1 -1
  38. package/dist/x402/facilitator-api.d.ts +9 -0
  39. package/dist/x402/facilitator-api.d.ts.map +1 -1
  40. package/dist/x402/facilitator-api.js +24 -10
  41. package/dist/x402/facilitator-api.js.map +1 -1
  42. package/dist/x402/index.d.ts +3 -3
  43. package/dist/x402/index.d.ts.map +1 -1
  44. package/dist/x402/index.js +2 -2
  45. package/dist/x402/index.js.map +1 -1
  46. package/dist/x402/token.d.ts +17 -17
  47. package/dist/x402/token.d.ts.map +1 -1
  48. package/dist/x402/token.js +27 -37
  49. package/dist/x402/token.js.map +1 -1
  50. package/package.json +1 -1
@@ -72,27 +72,27 @@ import { getDefaultNetwork } from '../common/types.js';
72
72
  * ```
73
73
  */
74
74
  export function buildPaymentRequired(planId, options) {
75
- const { endpoint, agentId, httpVerb, scheme = 'nvm:erc4337', network, description, environment, } = options || {};
75
+ const { endpoint, agentId, httpVerb, scheme = 'nvm:erc4337', network, description, mimeType, environment, } = options || {};
76
76
  const resolvedNetwork = network ?? getDefaultNetwork(scheme, environment);
77
- // Build extra fields if any are provided
78
- const extra = agentId || httpVerb
79
- ? {
80
- ...(agentId && { agentId }),
81
- ...(httpVerb && { httpVerb }),
82
- }
83
- : undefined;
77
+ // Build extra fields always include version for scheme versioning
78
+ const extra = {
79
+ version: '1',
80
+ ...(agentId && { agentId }),
81
+ ...(httpVerb && { httpVerb }),
82
+ };
84
83
  return {
85
84
  x402Version: 2,
86
85
  resource: {
87
86
  url: endpoint || '',
88
87
  ...(description && { description }),
88
+ ...(mimeType && { mimeType }),
89
89
  },
90
90
  accepts: [
91
91
  {
92
92
  scheme,
93
93
  network: resolvedNetwork,
94
94
  planId,
95
- ...(extra && { extra }),
95
+ extra,
96
96
  },
97
97
  ],
98
98
  extensions: {},
@@ -108,14 +108,28 @@ async function fetchPlanMetadata(payments, planId) {
108
108
  try {
109
109
  const plan = await payments.plans.getPlan(planId);
110
110
  const isCrypto = plan.registry?.price?.isCrypto;
111
+ // fiatPaymentProvider is in plan.metadata.plan, not in registry.price
112
+ const fiatProvider = plan.metadata?.plan?.fiatPaymentProvider;
111
113
  const scheme = isCrypto === false ? 'nvm:card-delegation' : 'nvm:erc4337';
112
- planMetadataCache.set(planId, { scheme, cachedAt: Date.now() });
114
+ planMetadataCache.set(planId, { scheme, fiatProvider, cachedAt: Date.now() });
113
115
  return { scheme };
114
116
  }
115
117
  catch {
116
118
  return { scheme: 'nvm:erc4337' };
117
119
  }
118
120
  }
121
+ /**
122
+ * Resolve the network for a plan from its fiatPaymentProvider metadata.
123
+ * For card-delegation plans, returns the provider ('stripe' or 'braintree').
124
+ * Returns undefined for crypto plans.
125
+ */
126
+ export async function resolveNetwork(payments, planId, explicitNetwork) {
127
+ if (explicitNetwork)
128
+ return explicitNetwork;
129
+ await fetchPlanMetadata(payments, planId);
130
+ const cached = planMetadataCache.get(planId);
131
+ return cached?.fiatProvider;
132
+ }
119
133
  /**
120
134
  * Resolve the x402 scheme for a plan by fetching plan metadata (cached).
121
135
  * Used in callsites that don't have a token to extract scheme from
@@ -1 +1 @@
1
- {"version":3,"file":"facilitator-api.js","sourceRoot":"","sources":["../../src/x402/facilitator-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAA;AAC1F,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAAqD,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAuJzG;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAAc,EACd,OAQC;IAED,MAAM,EACJ,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,MAAM,GAAG,aAAa,EACtB,OAAO,EACP,WAAW,EACX,WAAW,GACZ,GAAG,OAAO,IAAI,EAAE,CAAA;IACjB,MAAM,eAAe,G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K,CAAA;YACb,CAAC;YACD,MAAM,aAAa,CAAC,WAAW,CAAC,4CAA4C,EAAE;gBAC5E,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;gBAC/D,IAAI,EAAE,eAAe;aACtB,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The FacilitatorAPI class provides methods to verify and settle AI agent permissions using X402 access tokens.\n * This allows AI agents to act as facilitators, verifying and settling credits on behalf of subscribers.\n *\n * @example\n * ```typescript\n * import { Payments, X402PaymentRequired } from '@nevermined-io/payments'\n *\n * // Initialize the Payments instance\n * const payments = Payments.getInstance({\n * nvmApiKey: 'your-nvm-api-key',\n * environment: 'sandbox'\n * })\n *\n * // The server's 402 PaymentRequired response\n * const paymentRequired: X402PaymentRequired = buildPaymentRequired('123456789', {\n * endpoint: '/api/v1/agents/task',\n * agentId: '987654321',\n * httpVerb: 'POST'\n * })\n *\n * // Get X402 access token from subscriber (x402 v2: payment-signature header)\n * const x402Token = req.headers['payment-signature'] as string\n *\n * // Verify if subscriber has sufficient permissions/credits\n * const verification = await payments.facilitator.verifyPermissions({\n * paymentRequired,\n * x402AccessToken: x402Token,\n * maxAmount: 2n\n * })\n *\n * if (verification.isValid) {\n * // Settle (burn) the credits\n * const settlement = await payments.facilitator.settlePermissions({\n * paymentRequired,\n * x402AccessToken: x402Token,\n * maxAmount: 2n\n * })\n * console.log(`Credits redeemed: ${settlement.creditsRedeemed}`)\n * }\n * ```\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { API_URL_SETTLE_PERMISSIONS, API_URL_VERIFY_PERMISSIONS } from '../api/nvm-api.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { PaymentOptions, StartAgentRequest, X402SchemeType, getDefaultNetwork } from '../common/types.js'\nimport type { EnvironmentName } from '../environments.js'\nimport type { Payments } from '../payments.js'\nimport type { VisaPaymentRequired } from './visa-facilitator-api.js'\n\n/**\n * x402 Resource information\n */\nexport interface X402Resource {\n /** The protected resource URL */\n url: string\n /** Human-readable description */\n description?: string\n /** Expected response MIME type (e.g., \"application/json\") */\n mimeType?: string\n}\n\n/**\n * x402 Scheme extra fields for nvm:erc4337\n */\nexport interface X402SchemeExtra {\n /** Scheme version (e.g., \"1\") */\n version?: string\n /** Agent identifier */\n agentId?: string\n /** HTTP method for the endpoint */\n httpVerb?: string\n}\n\n/**\n * x402 Scheme definition (nvm:erc4337)\n */\nexport interface X402Scheme {\n /** Payment scheme identifier (e.g., \"nvm:erc4337\") */\n scheme: string\n /** Blockchain network in CAIP-2 format (e.g., \"eip155:84532\") */\n network: string\n /** 256-bit plan identifier */\n planId: string\n /** Scheme-specific extra fields */\n extra?: X402SchemeExtra\n}\n\n/**\n * x402 PaymentRequired response (402 response from server)\n */\nexport interface X402PaymentRequired {\n /** x402 protocol version (always 2) */\n x402Version: number\n /** Human-readable error message */\n error?: string\n /** Protected resource information */\n resource: X402Resource\n /** Array of accepted payment schemes */\n accepts: X402Scheme[]\n /** Extensions object (empty object for nvm:erc4337) */\n extensions: Record<string, unknown>\n}\n\n/**\n * x402 PaymentAccepted response (accepted payment scheme)\n */\nexport interface X402PaymentAccepted {\n /** The x402 version */\n x402Version: number\n /** The accepted payment scheme (nvm:erc4337) */\n accepted: X402Scheme\n /** The payload of the payment accepted */\n payload: {\n signature: string\n authorization: {\n from: string\n sessionKeysProvider: string\n sessionKeys: string[]\n }\n }\n extensions: Record<string, unknown>\n}\n\n/**\n * Parameters for verifying permissions\n */\nexport interface VerifyPermissionsParams {\n /** The server's 402 PaymentRequired response (NVM or Visa flavored) */\n paymentRequired: X402PaymentRequired | VisaPaymentRequired\n /** The X402 access token (base64-encoded) */\n x402AccessToken: string\n /** Maximum credits to verify (optional) */\n maxAmount?: bigint\n}\n\n/**\n * x402 Verify Response - per x402 facilitator spec\n * @see https://github.com/coinbase/x402/blob/main/specs/x402-specification-v2.md\n */\nexport interface VerifyPermissionsResult {\n /** Whether the payment authorization is valid */\n isValid: boolean\n /** Reason for invalidity (only present if isValid is false) */\n invalidReason?: string\n /** Address of the payer's wallet */\n payer?: string\n /** Agent request ID for observability tracking (Nevermined extension) */\n agentRequestId?: string\n /** URL pattern that matched the endpoint (Nevermined extension) */\n urlMatching?: string\n /** Agent request context for observability (Nevermined extension) */\n agentRequest?: StartAgentRequest\n}\n\n/**\n * Parameters for settling permissions\n */\nexport interface SettlePermissionsParams {\n /** The server's 402 PaymentRequired response (NVM or Visa flavored) */\n paymentRequired: X402PaymentRequired | VisaPaymentRequired\n /** The X402 access token (base64-encoded) */\n x402AccessToken: string\n /** Number of credits to burn (optional) */\n maxAmount?: bigint\n /** Agent request ID for observability tracking. Returned by verifyPermissions. */\n agentRequestId?: string\n /** Whether this is a batch request (multiple LLM calls under one agentRequestId) */\n batch?: boolean\n /** Margin percentage (0-10) for credit calculation. Mutually exclusive with maxAmount when agentRequestId provided. */\n marginPercent?: number\n}\n\n/**\n * x402 Settle Response - per x402 facilitator spec\n * @see https://github.com/coinbase/x402/blob/main/specs/x402-specification-v2.md\n */\nexport interface SettlePermissionsResult {\n /** Whether settlement was successful */\n success: boolean\n /** Reason for settlement failure (only present if success is false) */\n errorReason?: string\n /** Address of the payer's wallet */\n payer?: string\n /** Blockchain transaction hash (empty string if settlement failed) */\n transaction: string\n /** Blockchain network identifier in CAIP-2 format */\n network: string\n /** Number of credits redeemed (Nevermined extension) */\n creditsRedeemed?: string\n /** Subscriber's remaining balance (Nevermined extension) */\n remainingBalance?: string\n /** Transaction hash of the order operation if auto top-up occurred (Nevermined extension) */\n orderTx?: string\n}\n\n/**\n * Build an X402PaymentRequired object for verify/settle operations.\n *\n * This helper simplifies the creation of payment requirement objects\n * that are needed for the facilitator API.\n *\n * @param planId - The Nevermined plan identifier (required)\n * @param options - Optional configuration with endpoint, agentId, httpVerb, network, description\n * @returns X402PaymentRequired object ready to use with verifyPermissions/settlePermissions\n *\n * @example\n * ```typescript\n * import { buildPaymentRequired } from '@nevermined-io/payments'\n *\n * const paymentRequired = buildPaymentRequired('123456789', {\n * endpoint: '/api/v1/agents/task',\n * agentId: '987654321',\n * httpVerb: 'POST'\n * })\n *\n * const result = await payments.facilitator.verifyPermissions({\n * paymentRequired,\n * x402AccessToken: token,\n * maxAmount: 2n\n * })\n * ```\n */\nexport function buildPaymentRequired(\n planId: string,\n options?: {\n endpoint?: string\n agentId?: string\n httpVerb?: string\n network?: string\n description?: string\n scheme?: X402SchemeType\n environment?: EnvironmentName\n },\n): X402PaymentRequired {\n const {\n endpoint,\n agentId,\n httpVerb,\n scheme = 'nvm:erc4337',\n network,\n description,\n environment,\n } = options || {}\n const resolvedNetwork = network ?? getDefaultNetwork(scheme, environment)\n\n // Build extra fields if any are provided\n const extra: X402SchemeExtra | undefined =\n agentId || httpVerb\n ? {\n ...(agentId && { agentId }),\n ...(httpVerb && { httpVerb }),\n }\n : undefined\n\n return {\n x402Version: 2,\n resource: {\n url: endpoint || '',\n ...(description && { description }),\n },\n accepts: [\n {\n scheme,\n network: resolvedNetwork,\n planId,\n ...(extra && { extra }),\n },\n ],\n extensions: {},\n }\n}\n\ninterface CachedPlanMetadata {\n scheme: X402SchemeType\n cachedAt: number\n}\n\nconst CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\nconst planMetadataCache = new Map<string, CachedPlanMetadata>()\n\nasync function fetchPlanMetadata(\n payments: Payments,\n planId: string,\n): Promise<{ scheme: X402SchemeType }> {\n const cached = planMetadataCache.get(planId)\n if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) {\n return { scheme: cached.scheme }\n }\n try {\n const plan = await payments.plans.getPlan(planId)\n const isCrypto = plan.registry?.price?.isCrypto\n const scheme: X402SchemeType =\n isCrypto === false ? 'nvm:card-delegation' : 'nvm:erc4337'\n planMetadataCache.set(planId, { scheme, cachedAt: Date.now() })\n return { scheme }\n } catch {\n return { scheme: 'nvm:erc4337' }\n }\n}\n\n/**\n * Resolve the x402 scheme for a plan by fetching plan metadata (cached).\n * Used in callsites that don't have a token to extract scheme from\n * (402 responses and token generation).\n *\n * @param payments - The Payments instance for API access\n * @param planId - The plan identifier\n * @param explicitScheme - Optional explicit override; returned immediately if provided\n * @returns The resolved scheme type\n */\nexport async function resolveScheme(\n payments: Payments,\n planId: string,\n explicitScheme?: X402SchemeType,\n): Promise<X402SchemeType> {\n if (explicitScheme) return explicitScheme\n const metadata = await fetchPlanMetadata(payments, planId)\n return metadata.scheme\n}\n\n/**\n * The FacilitatorAPI class provides methods to verify and settle AI agent permissions.\n * It enables AI agents to act as facilitators, managing credit verification and settlement\n * for subscribers using X402 access tokens.\n */\nexport class FacilitatorAPI extends BasePaymentsAPI {\n /**\n * Get a singleton instance of the FacilitatorAPI class.\n *\n * @param options - The options to initialize the payments class\n * @returns The instance of the FacilitatorAPI class\n */\n static getInstance(options: PaymentOptions): FacilitatorAPI {\n return new FacilitatorAPI(options)\n }\n\n /**\n * Verify if a subscriber has permission to use credits from a payment plan.\n * This method simulates the credit usage without actually burning credits,\n * checking if the subscriber has sufficient balance and permissions.\n *\n * The planId and subscriberAddress are extracted from the x402AccessToken.\n *\n * @param params - Verification parameters (see {@link VerifyPermissionsParams}).\n * - paymentRequired: x402 PaymentRequired from 402 response (required, for validation)\n * - x402AccessToken: X402 access token (contains planId, subscriberAddress, agentId)\n * - maxAmount: maximum credits to verify (optional, bigint)\n * @returns A promise that resolves to a verification result with 'isValid' boolean\n *\n * @throws PaymentsError if verification fails\n */\n async verifyPermissions(params: VerifyPermissionsParams): Promise<VerifyPermissionsResult> {\n const { paymentRequired, x402AccessToken, maxAmount } = params\n\n const url = new URL(API_URL_VERIFY_PERMISSIONS, this.environment.backend)\n\n const body: Record<string, unknown> = {\n paymentRequired,\n x402AccessToken,\n }\n\n if (maxAmount !== undefined) {\n body.maxAmount = maxAmount.toString()\n }\n\n const options = this.getPublicHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission verification failed'\n try {\n const errorData = await response.json()\n errorMessage = errorData.message || errorMessage\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: `HTTP ${response.status}`,\n })\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) {\n throw error\n }\n throw PaymentsError.fromBackend('Network error during permission verification', {\n message: error instanceof Error ? error.message : String(error),\n code: 'network_error',\n })\n }\n }\n\n /**\n * Settle (burn) credits from a subscriber's payment plan.\n * This method executes the actual credit consumption, burning the specified\n * number of credits from the subscriber's balance. If the subscriber doesn't\n * have enough credits, it will attempt to order more before settling.\n *\n * The planId and subscriberAddress are extracted from the x402AccessToken.\n *\n * @param params - Settlement parameters (see {@link SettlePermissionsParams}).\n * - paymentRequired: x402 PaymentRequired from 402 response (required, for validation)\n * - x402AccessToken: X402 access token (contains planId, subscriberAddress, agentId)\n * - maxAmount: number of credits to burn (optional, bigint)\n * - agentRequestId: Agent request ID for observability tracking (optional)\n * - batch: Whether this is a batch request (optional)\n * - marginPercent: Margin percentage for credit calculation (optional)\n * @returns A promise that resolves to a settlement result with transaction details\n *\n * @throws PaymentsError if settlement fails\n */\n async settlePermissions(params: SettlePermissionsParams): Promise<SettlePermissionsResult> {\n const { paymentRequired, x402AccessToken, maxAmount, agentRequestId, batch, marginPercent } =\n params\n\n const url = new URL(API_URL_SETTLE_PERMISSIONS, this.environment.backend)\n\n const body: Record<string, unknown> = {\n paymentRequired,\n x402AccessToken,\n }\n\n if (maxAmount !== undefined) {\n body.maxAmount = maxAmount.toString()\n }\n if (agentRequestId !== undefined) {\n body.agentRequestId = agentRequestId\n }\n if (batch !== undefined) {\n body.batch = batch\n }\n if (marginPercent !== undefined) {\n body.marginPercent = marginPercent\n }\n\n const options = this.getPublicHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission settlement failed'\n try {\n const errorData = await response.json()\n errorMessage = errorData.message || errorMessage\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: `HTTP ${response.status}`,\n })\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) {\n throw error\n }\n throw PaymentsError.fromBackend('Network error during permission settlement', {\n message: error instanceof Error ? error.message : String(error),\n code: 'network_error',\n })\n }\n }\n}\n"]}
1
+ {"version":3,"file":"facilitator-api.js","sourceRoot":"","sources":["../../src/x402/facilitator-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAA;AAC1F,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAAqD,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAyJzG;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAAc,EACd,OASC;IAED,MAAM,EACJ,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,MAAM,GAAG,aAAa,EACtB,OAAO,EACP,WAAW,EACX,QAAQ,EACR,WAAW,GACZ,GAAG,OAAO,IAAI,EAAE,CAAA;IACjB,MAAM,eAAe,GAAG,OAAO,IAAI,iBAAiB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IAEzE,oEAAoE;IACpE,MAAM,KAAK,GAAoB;QAC7B,OAAO,EAAE,GAAG;QACZ,GAAG,CAAC,OAAO,IAAI,EAAE,OAAO,EAAE,CAAC;QAC3B,GAAG,CAAC,QAAQ,IAAI,EAAE,QAAQ,EAAE,CAAC;KAC9B,CAAA;IAED,OAAO;QACL,WAAW,EAAE,CAAC;QACd,QAAQ,EAAE;YACR,GAAG,EAAE,QAAQ,IAAI,EAAE;YACnB,GAAG,CAAC,WA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,EAAE,CAAC;gBACnC,MAAM,KAAK,CAAA;YACb,CAAC;YACD,MAAM,aAAa,CAAC,WAAW,CAAC,4CAA4C,EAAE;gBAC5E,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;gBAC/D,IAAI,EAAE,eAAe;aACtB,CAAC,CAAA;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * The FacilitatorAPI class provides methods to verify and settle AI agent permissions using X402 access tokens.\n * This allows AI agents to act as facilitators, verifying and settling credits on behalf of subscribers.\n *\n * @example\n * ```typescript\n * import { Payments, X402PaymentRequired } from '@nevermined-io/payments'\n *\n * // Initialize the Payments instance\n * const payments = Payments.getInstance({\n * nvmApiKey: 'your-nvm-api-key',\n * environment: 'sandbox'\n * })\n *\n * // The server's 402 PaymentRequired response\n * const paymentRequired: X402PaymentRequired = buildPaymentRequired('123456789', {\n * endpoint: '/api/v1/agents/task',\n * agentId: '987654321',\n * httpVerb: 'POST'\n * })\n *\n * // Get X402 access token from subscriber (x402 v2: payment-signature header)\n * const x402Token = req.headers['payment-signature'] as string\n *\n * // Verify if subscriber has sufficient permissions/credits\n * const verification = await payments.facilitator.verifyPermissions({\n * paymentRequired,\n * x402AccessToken: x402Token,\n * maxAmount: 2n\n * })\n *\n * if (verification.isValid) {\n * // Settle (burn) the credits\n * const settlement = await payments.facilitator.settlePermissions({\n * paymentRequired,\n * x402AccessToken: x402Token,\n * maxAmount: 2n\n * })\n * console.log(`Credits redeemed: ${settlement.creditsRedeemed}`)\n * }\n * ```\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { API_URL_SETTLE_PERMISSIONS, API_URL_VERIFY_PERMISSIONS } from '../api/nvm-api.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { PaymentOptions, StartAgentRequest, X402SchemeType, getDefaultNetwork } from '../common/types.js'\nimport type { EnvironmentName } from '../environments.js'\nimport type { Payments } from '../payments.js'\nimport type { VisaPaymentRequired } from './visa-facilitator-api.js'\n\n/**\n * x402 Resource information\n */\nexport interface X402Resource {\n /** The protected resource URL */\n url: string\n /** Human-readable description */\n description?: string\n /** Expected response MIME type (e.g., \"application/json\") */\n mimeType?: string\n}\n\n/**\n * x402 Scheme extra fields for nvm:erc4337\n */\nexport interface X402SchemeExtra {\n /** Scheme version (e.g., \"1\") */\n version?: string\n /** Agent identifier */\n agentId?: string\n /** HTTP method for the endpoint */\n httpVerb?: string\n}\n\n/**\n * x402 Scheme definition (nvm:erc4337)\n */\nexport interface X402Scheme {\n /** Payment scheme identifier (e.g., \"nvm:erc4337\") */\n scheme: string\n /** Blockchain network in CAIP-2 format (e.g., \"eip155:84532\") */\n network: string\n /** 256-bit plan identifier */\n planId: string\n /** Scheme-specific extra fields */\n extra?: X402SchemeExtra\n}\n\n/**\n * x402 PaymentRequired response (402 response from server)\n */\nexport interface X402PaymentRequired {\n /** x402 protocol version (always 2) */\n x402Version: number\n /** Human-readable error message */\n error?: string\n /** Protected resource information */\n resource: X402Resource\n /** Array of accepted payment schemes */\n accepts: X402Scheme[]\n /** Extensions object (empty object for nvm:erc4337) */\n extensions: Record<string, unknown>\n}\n\n/**\n * x402 PaymentAccepted response (accepted payment scheme)\n */\nexport interface X402PaymentAccepted {\n /** The x402 version */\n x402Version: number\n /** The accepted payment scheme (nvm:erc4337) */\n accepted: X402Scheme\n /** The payload of the payment accepted */\n payload: {\n signature: string\n authorization: {\n from: string\n sessionKeysProvider: string\n sessionKeys: string[]\n }\n }\n extensions: Record<string, unknown>\n}\n\n/**\n * Parameters for verifying permissions\n */\nexport interface VerifyPermissionsParams {\n /** The server's 402 PaymentRequired response (NVM or Visa flavored) */\n paymentRequired: X402PaymentRequired | VisaPaymentRequired\n /** The X402 access token (base64-encoded) */\n x402AccessToken: string\n /** Maximum credits to verify (optional) */\n maxAmount?: bigint\n}\n\n/**\n * x402 Verify Response - per x402 facilitator spec\n * @see https://github.com/coinbase/x402/blob/main/specs/x402-specification-v2.md\n */\nexport interface VerifyPermissionsResult {\n /** Whether the payment authorization is valid */\n isValid: boolean\n /** Reason for invalidity (only present if isValid is false) */\n invalidReason?: string\n /** Address of the payer's wallet */\n payer?: string\n /** Network identifier (e.g., 'stripe', 'braintree', 'eip155:84532') */\n network?: string\n /** Agent request ID for observability tracking (Nevermined extension) */\n agentRequestId?: string\n /** URL pattern that matched the endpoint (Nevermined extension) */\n urlMatching?: string\n /** Agent request context for observability (Nevermined extension) */\n agentRequest?: StartAgentRequest\n}\n\n/**\n * Parameters for settling permissions\n */\nexport interface SettlePermissionsParams {\n /** The server's 402 PaymentRequired response (NVM or Visa flavored) */\n paymentRequired: X402PaymentRequired | VisaPaymentRequired\n /** The X402 access token (base64-encoded) */\n x402AccessToken: string\n /** Number of credits to burn (optional) */\n maxAmount?: bigint\n /** Agent request ID for observability tracking. Returned by verifyPermissions. */\n agentRequestId?: string\n /** Whether this is a batch request (multiple LLM calls under one agentRequestId) */\n batch?: boolean\n /** Margin percentage (0-10) for credit calculation. Mutually exclusive with maxAmount when agentRequestId provided. */\n marginPercent?: number\n}\n\n/**\n * x402 Settle Response - per x402 facilitator spec\n * @see https://github.com/coinbase/x402/blob/main/specs/x402-specification-v2.md\n */\nexport interface SettlePermissionsResult {\n /** Whether settlement was successful */\n success: boolean\n /** Reason for settlement failure (only present if success is false) */\n errorReason?: string\n /** Address of the payer's wallet */\n payer?: string\n /** Blockchain transaction hash (empty string if settlement failed) */\n transaction: string\n /** Blockchain network identifier in CAIP-2 format */\n network: string\n /** Number of credits redeemed (Nevermined extension) */\n creditsRedeemed?: string\n /** Subscriber's remaining balance (Nevermined extension) */\n remainingBalance?: string\n /** Transaction hash of the order operation if auto top-up occurred (Nevermined extension) */\n orderTx?: string\n}\n\n/**\n * Build an X402PaymentRequired object for verify/settle operations.\n *\n * This helper simplifies the creation of payment requirement objects\n * that are needed for the facilitator API.\n *\n * @param planId - The Nevermined plan identifier (required)\n * @param options - Optional configuration with endpoint, agentId, httpVerb, network, description\n * @returns X402PaymentRequired object ready to use with verifyPermissions/settlePermissions\n *\n * @example\n * ```typescript\n * import { buildPaymentRequired } from '@nevermined-io/payments'\n *\n * const paymentRequired = buildPaymentRequired('123456789', {\n * endpoint: '/api/v1/agents/task',\n * agentId: '987654321',\n * httpVerb: 'POST'\n * })\n *\n * const result = await payments.facilitator.verifyPermissions({\n * paymentRequired,\n * x402AccessToken: token,\n * maxAmount: 2n\n * })\n * ```\n */\nexport function buildPaymentRequired(\n planId: string,\n options?: {\n endpoint?: string\n agentId?: string\n httpVerb?: string\n network?: string\n description?: string\n mimeType?: string\n scheme?: X402SchemeType\n environment?: EnvironmentName\n },\n): X402PaymentRequired {\n const {\n endpoint,\n agentId,\n httpVerb,\n scheme = 'nvm:erc4337',\n network,\n description,\n mimeType,\n environment,\n } = options || {}\n const resolvedNetwork = network ?? getDefaultNetwork(scheme, environment)\n\n // Build extra fields — always include version for scheme versioning\n const extra: X402SchemeExtra = {\n version: '1',\n ...(agentId && { agentId }),\n ...(httpVerb && { httpVerb }),\n }\n\n return {\n x402Version: 2,\n resource: {\n url: endpoint || '',\n ...(description && { description }),\n ...(mimeType && { mimeType }),\n },\n accepts: [\n {\n scheme,\n network: resolvedNetwork,\n planId,\n extra,\n },\n ],\n extensions: {},\n }\n}\n\ninterface CachedPlanMetadata {\n scheme: X402SchemeType\n fiatProvider?: string\n cachedAt: number\n}\n\nconst CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\nconst planMetadataCache = new Map<string, CachedPlanMetadata>()\n\nasync function fetchPlanMetadata(\n payments: Payments,\n planId: string,\n): Promise<{ scheme: X402SchemeType }> {\n const cached = planMetadataCache.get(planId)\n if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) {\n return { scheme: cached.scheme }\n }\n try {\n const plan = await payments.plans.getPlan(planId)\n const isCrypto = plan.registry?.price?.isCrypto\n // fiatPaymentProvider is in plan.metadata.plan, not in registry.price\n const fiatProvider = (plan as any).metadata?.plan?.fiatPaymentProvider\n const scheme: X402SchemeType =\n isCrypto === false ? 'nvm:card-delegation' : 'nvm:erc4337'\n planMetadataCache.set(planId, { scheme, fiatProvider, cachedAt: Date.now() })\n return { scheme }\n } catch {\n return { scheme: 'nvm:erc4337' }\n }\n}\n\n/**\n * Resolve the network for a plan from its fiatPaymentProvider metadata.\n * For card-delegation plans, returns the provider ('stripe' or 'braintree').\n * Returns undefined for crypto plans.\n */\nexport async function resolveNetwork(\n payments: Payments,\n planId: string,\n explicitNetwork?: string,\n): Promise<string | undefined> {\n if (explicitNetwork) return explicitNetwork\n await fetchPlanMetadata(payments, planId)\n const cached = planMetadataCache.get(planId)\n return cached?.fiatProvider\n}\n\n/**\n * Resolve the x402 scheme for a plan by fetching plan metadata (cached).\n * Used in callsites that don't have a token to extract scheme from\n * (402 responses and token generation).\n *\n * @param payments - The Payments instance for API access\n * @param planId - The plan identifier\n * @param explicitScheme - Optional explicit override; returned immediately if provided\n * @returns The resolved scheme type\n */\nexport async function resolveScheme(\n payments: Payments,\n planId: string,\n explicitScheme?: X402SchemeType,\n): Promise<X402SchemeType> {\n if (explicitScheme) return explicitScheme\n const metadata = await fetchPlanMetadata(payments, planId)\n return metadata.scheme\n}\n\n/**\n * The FacilitatorAPI class provides methods to verify and settle AI agent permissions.\n * It enables AI agents to act as facilitators, managing credit verification and settlement\n * for subscribers using X402 access tokens.\n */\nexport class FacilitatorAPI extends BasePaymentsAPI {\n /**\n * Get a singleton instance of the FacilitatorAPI class.\n *\n * @param options - The options to initialize the payments class\n * @returns The instance of the FacilitatorAPI class\n */\n static getInstance(options: PaymentOptions): FacilitatorAPI {\n return new FacilitatorAPI(options)\n }\n\n /**\n * Verify if a subscriber has permission to use credits from a payment plan.\n * This method simulates the credit usage without actually burning credits,\n * checking if the subscriber has sufficient balance and permissions.\n *\n * The planId and subscriberAddress are extracted from the x402AccessToken.\n *\n * @param params - Verification parameters (see {@link VerifyPermissionsParams}).\n * - paymentRequired: x402 PaymentRequired from 402 response (required, for validation)\n * - x402AccessToken: X402 access token (contains planId, subscriberAddress, agentId)\n * - maxAmount: maximum credits to verify (optional, bigint)\n * @returns A promise that resolves to a verification result with 'isValid' boolean\n *\n * @throws PaymentsError if verification fails\n */\n async verifyPermissions(params: VerifyPermissionsParams): Promise<VerifyPermissionsResult> {\n const { paymentRequired, x402AccessToken, maxAmount } = params\n\n const url = new URL(API_URL_VERIFY_PERMISSIONS, this.environment.backend)\n\n const body: Record<string, unknown> = {\n paymentRequired,\n x402AccessToken,\n }\n\n if (maxAmount !== undefined) {\n body.maxAmount = maxAmount.toString()\n }\n\n const options = this.getPublicHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission verification failed'\n try {\n const errorData = await response.json()\n errorMessage = errorData.message || errorMessage\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: `HTTP ${response.status}`,\n })\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) {\n throw error\n }\n throw PaymentsError.fromBackend('Network error during permission verification', {\n message: error instanceof Error ? error.message : String(error),\n code: 'network_error',\n })\n }\n }\n\n /**\n * Settle (burn) credits from a subscriber's payment plan.\n * This method executes the actual credit consumption, burning the specified\n * number of credits from the subscriber's balance. If the subscriber doesn't\n * have enough credits, it will attempt to order more before settling.\n *\n * The planId and subscriberAddress are extracted from the x402AccessToken.\n *\n * @param params - Settlement parameters (see {@link SettlePermissionsParams}).\n * - paymentRequired: x402 PaymentRequired from 402 response (required, for validation)\n * - x402AccessToken: X402 access token (contains planId, subscriberAddress, agentId)\n * - maxAmount: number of credits to burn (optional, bigint)\n * - agentRequestId: Agent request ID for observability tracking (optional)\n * - batch: Whether this is a batch request (optional)\n * - marginPercent: Margin percentage for credit calculation (optional)\n * @returns A promise that resolves to a settlement result with transaction details\n *\n * @throws PaymentsError if settlement fails\n */\n async settlePermissions(params: SettlePermissionsParams): Promise<SettlePermissionsResult> {\n const { paymentRequired, x402AccessToken, maxAmount, agentRequestId, batch, marginPercent } =\n params\n\n const url = new URL(API_URL_SETTLE_PERMISSIONS, this.environment.backend)\n\n const body: Record<string, unknown> = {\n paymentRequired,\n x402AccessToken,\n }\n\n if (maxAmount !== undefined) {\n body.maxAmount = maxAmount.toString()\n }\n if (agentRequestId !== undefined) {\n body.agentRequestId = agentRequestId\n }\n if (batch !== undefined) {\n body.batch = batch\n }\n if (marginPercent !== undefined) {\n body.marginPercent = marginPercent\n }\n\n const options = this.getPublicHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission settlement failed'\n try {\n const errorData = await response.json()\n errorMessage = errorData.message || errorMessage\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: `HTTP ${response.status}`,\n })\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) {\n throw error\n }\n throw PaymentsError.fromBackend('Network error during permission settlement', {\n message: error instanceof Error ? error.message : String(error),\n code: 'network_error',\n })\n }\n }\n}\n"]}
@@ -2,11 +2,11 @@
2
2
  * X402 API module for token generation and facilitator operations.
3
3
  */
4
4
  export { X402TokenAPI } from './token.js';
5
- export { FacilitatorAPI, buildPaymentRequired, resolveScheme } from './facilitator-api.js';
5
+ export { FacilitatorAPI, buildPaymentRequired, resolveNetwork, resolveScheme } from './facilitator-api.js';
6
6
  export type { X402Resource, X402SchemeExtra, X402Scheme, X402PaymentRequired, X402PaymentAccepted, VerifyPermissionsParams, VerifyPermissionsResult, SettlePermissionsParams, SettlePermissionsResult, } from './facilitator-api.js';
7
7
  export { DelegationAPI } from './delegation-api.js';
8
- export type { PaymentMethodSummary } from './delegation-api.js';
9
- export type { X402SchemeType, CardDelegationConfig, X402TokenOptions } from '../common/types.js';
8
+ export type { PaymentMethodSummary, UpdatePaymentMethodDto, DelegationSummary, DelegationListResponse, PurchasingPower, ListOptions, } from './delegation-api.js';
9
+ export type { X402SchemeType, DelegationConfig, CreateDelegationPayload, CreateDelegationResponse, X402TokenOptions, } from '../common/types.js';
10
10
  export { X402_SCHEME_NETWORKS, getDefaultNetwork, isValidScheme } from '../common/types.js';
11
11
  export { VisaFacilitatorAPI, buildVisaPaymentRequired, VISA_X402_HEADERS } from './visa-facilitator-api.js';
12
12
  export type { VisaPaymentExtra, VisaPaymentRequirements, VisaPaymentRequired, VisaVerifyResponse, VisaSettlementResponse, } from './visa-facilitator-api.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/x402/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAC1F,YAAY,EAEV,YAAY,EACZ,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,mBAAmB,EAEnB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,sBAAsB,CAAA;AAG7B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,YAAY,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAG/D,YAAY,EAAE,cAAc,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAChG,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAG3F,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAA;AAC3G,YAAY,EACV,gBAAgB,EAChB,uBAAuB,EACvB,mBAAmB,EACnB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,YAAY,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/x402/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAC1G,YAAY,EAEV,YAAY,EACZ,eAAe,EACf,UAAU,EACV,mBAAmB,EACnB,mBAAmB,EAEnB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,sBAAsB,CAAA;AAG7B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,YAAY,EACV,oBAAoB,EACpB,sBAAsB,EACtB,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,WAAW,GACZ,MAAM,qBAAqB,CAAA;AAG5B,YAAY,EACV,cAAc,EACd,gBAAgB,EAChB,uBAAuB,EACvB,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAG3F,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAA;AAC3G,YAAY,EACV,gBAAgB,EAChB,uBAAuB,EACvB,mBAAmB,EACnB,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,YAAY,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAA"}
@@ -2,8 +2,8 @@
2
2
  * X402 API module for token generation and facilitator operations.
3
3
  */
4
4
  export { X402TokenAPI } from './token.js';
5
- export { FacilitatorAPI, buildPaymentRequired, resolveScheme } from './facilitator-api.js';
6
- // Card delegation exports
5
+ export { FacilitatorAPI, buildPaymentRequired, resolveNetwork, resolveScheme } from './facilitator-api.js';
6
+ // Delegation exports
7
7
  export { DelegationAPI } from './delegation-api.js';
8
8
  export { X402_SCHEME_NETWORKS, getDefaultNetwork, isValidScheme } from '../common/types.js';
9
9
  // Visa x402 exports
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/x402/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAe1F,0BAA0B;AAC1B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAKnD,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAE3F,oBAAoB;AACpB,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAA;AAQ3G,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA","sourcesContent":["/**\n * X402 API module for token generation and facilitator operations.\n */\n\nexport { X402TokenAPI } from './token.js'\nexport { FacilitatorAPI, buildPaymentRequired, resolveScheme } from './facilitator-api.js'\nexport type {\n // x402 types\n X402Resource,\n X402SchemeExtra,\n X402Scheme,\n X402PaymentRequired,\n X402PaymentAccepted,\n // Facilitator params and results\n VerifyPermissionsParams,\n VerifyPermissionsResult,\n SettlePermissionsParams,\n SettlePermissionsResult,\n} from './facilitator-api.js'\n\n// Card delegation exports\nexport { DelegationAPI } from './delegation-api.js'\nexport type { PaymentMethodSummary } from './delegation-api.js'\n\n// Scheme types\nexport type { X402SchemeType, CardDelegationConfig, X402TokenOptions } from '../common/types.js'\nexport { X402_SCHEME_NETWORKS, getDefaultNetwork, isValidScheme } from '../common/types.js'\n\n// Visa x402 exports\nexport { VisaFacilitatorAPI, buildVisaPaymentRequired, VISA_X402_HEADERS } from './visa-facilitator-api.js'\nexport type {\n VisaPaymentExtra,\n VisaPaymentRequirements,\n VisaPaymentRequired,\n VisaVerifyResponse,\n VisaSettlementResponse,\n} from './visa-facilitator-api.js'\nexport { VisaTokenAPI } from './visa-token-api.js'\nexport type { VisaPaymentPayloadResponse } from './visa-token-api.js'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/x402/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AACzC,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAe1G,qBAAqB;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAkBnD,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAE3F,oBAAoB;AACpB,OAAO,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAA;AAQ3G,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA","sourcesContent":["/**\n * X402 API module for token generation and facilitator operations.\n */\n\nexport { X402TokenAPI } from './token.js'\nexport { FacilitatorAPI, buildPaymentRequired, resolveNetwork, resolveScheme } from './facilitator-api.js'\nexport type {\n // x402 types\n X402Resource,\n X402SchemeExtra,\n X402Scheme,\n X402PaymentRequired,\n X402PaymentAccepted,\n // Facilitator params and results\n VerifyPermissionsParams,\n VerifyPermissionsResult,\n SettlePermissionsParams,\n SettlePermissionsResult,\n} from './facilitator-api.js'\n\n// Delegation exports\nexport { DelegationAPI } from './delegation-api.js'\nexport type {\n PaymentMethodSummary,\n UpdatePaymentMethodDto,\n DelegationSummary,\n DelegationListResponse,\n PurchasingPower,\n ListOptions,\n} from './delegation-api.js'\n\n// Scheme and delegation types\nexport type {\n X402SchemeType,\n DelegationConfig,\n CreateDelegationPayload,\n CreateDelegationResponse,\n X402TokenOptions,\n} from '../common/types.js'\nexport { X402_SCHEME_NETWORKS, getDefaultNetwork, isValidScheme } from '../common/types.js'\n\n// Visa x402 exports\nexport { VisaFacilitatorAPI, buildVisaPaymentRequired, VISA_X402_HEADERS } from './visa-facilitator-api.js'\nexport type {\n VisaPaymentExtra,\n VisaPaymentRequirements,\n VisaPaymentRequired,\n VisaVerifyResponse,\n VisaSettlementResponse,\n} from './visa-facilitator-api.js'\nexport { VisaTokenAPI } from './visa-token-api.js'\nexport type { VisaPaymentPayloadResponse } from './visa-token-api.js'\n"]}
@@ -21,37 +21,37 @@ export declare class X402TokenAPI extends BasePaymentsAPI {
21
21
  */
22
22
  static getInstance(options: PaymentOptions): X402TokenAPI;
23
23
  /**
24
- * Create a permission and get an X402 access token for the given plan.
24
+ * Create a delegation and get an X402 access token for the given plan.
25
25
  *
26
- * This token allows the agent to verify and settle permissions on behalf
27
- * of the subscriber. The token contains cryptographically signed session keys
28
- * that delegate specific permissions (order, burn) to the agent.
26
+ * This token allows the agent to verify and settle delegations on behalf
27
+ * of the subscriber.
28
+ *
29
+ * For erc4337 scheme, you must pass `tokenOptions.delegationConfig` with either:
30
+ * - `delegationId` to reuse an existing delegation, or
31
+ * - `spendingLimitCents` + `durationSecs` to auto-create a new one.
29
32
  *
30
33
  * @param planId - The unique identifier of the payment plan
31
- * @param agentId - The unique identifier of the AI agent (optional). If provided, permissions are restricted to that specific agent.
32
- * @param redemptionLimit - Maximum number of interactions/redemptions allowed (optional)
33
- * @param orderLimit - Maximum spend limit in token units (wei) for ordering (optional)
34
- * @param expiration - Expiration date in ISO 8601 format, e.g. "2025-02-01T10:00:00Z" (optional)
34
+ * @param agentId - The unique identifier of the AI agent (optional)
35
+ * @param tokenOptions - Options controlling scheme and delegation behavior (optional)
35
36
  * @returns A promise that resolves to an object containing:
36
37
  * - accessToken: The X402 access token string
37
- * - Additional metadata about the token
38
38
  *
39
39
  * @throws PaymentsError if the request fails
40
40
  *
41
41
  * @example
42
42
  * ```typescript
43
- * import { Payments } from '@nevermined-io/payments'
44
- *
45
- * const payments = Payments.getInstance({
46
- * nvmApiKey: 'nvm:subscriber-key',
47
- * environment: 'sandbox'
43
+ * // Pattern A auto-create delegation
44
+ * const result = await payments.x402.getX402AccessToken(planId, agentId, {
45
+ * delegationConfig: { spendingLimitCents: 10000, durationSecs: 604800 }
48
46
  * })
49
47
  *
50
- * const result = await payments.x402.getX402AccessToken(planId, agentId)
51
- * const token = result.accessToken
48
+ * // Pattern B reuse existing delegation
49
+ * const result = await payments.x402.getX402AccessToken(planId, agentId, {
50
+ * delegationConfig: { delegationId: 'existing-delegation-uuid' }
51
+ * })
52
52
  * ```
53
53
  */
54
- getX402AccessToken(planId: string, agentId?: string, redemptionLimit?: number, orderLimit?: string, expiration?: string, tokenOptions?: X402TokenOptions): Promise<{
54
+ getX402AccessToken(planId: string, agentId?: string, tokenOptions?: X402TokenOptions): Promise<{
55
55
  accessToken: string;
56
56
  [key: string]: any;
57
57
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/x402/token.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAGzD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAqB,MAAM,oBAAoB,CAAA;AAExF;;;;;GAKG;AACH,qBAAa,YAAa,SAAQ,eAAe;IAC/C;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,YAAY;IAIzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IACG,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,MAAM,EAChB,eAAe,CAAC,EAAE,MAAM,EACxB,UAAU,CAAC,EAAE,MAAM,EACnB,UAAU,CAAC,EAAE,MAAM,EACnB,YAAY,CAAC,EAAE,gBAAgB,GAC9B,OAAO,CAAC;QAAE,WAAW,EAAE,MAAM,CAAC;QAAA,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;CAiEvD"}
1
+ {"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../src/x402/token.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAGzD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAqB,MAAM,oBAAoB,CAAA;AAExF;;;;;GAKG;AACH,qBAAa,YAAa,SAAQ,eAAe;IAC/C;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,YAAY;IAIzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IACG,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,MAAM,EAChB,YAAY,CAAC,EAAE,gBAAgB,GAC9B,OAAO,CAAC;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;CAyDxD"}
@@ -25,41 +25,47 @@ export class X402TokenAPI extends BasePaymentsAPI {
25
25
  return new X402TokenAPI(options);
26
26
  }
27
27
  /**
28
- * Create a permission and get an X402 access token for the given plan.
28
+ * Create a delegation and get an X402 access token for the given plan.
29
29
  *
30
- * This token allows the agent to verify and settle permissions on behalf
31
- * of the subscriber. The token contains cryptographically signed session keys
32
- * that delegate specific permissions (order, burn) to the agent.
30
+ * This token allows the agent to verify and settle delegations on behalf
31
+ * of the subscriber.
32
+ *
33
+ * For erc4337 scheme, you must pass `tokenOptions.delegationConfig` with either:
34
+ * - `delegationId` to reuse an existing delegation, or
35
+ * - `spendingLimitCents` + `durationSecs` to auto-create a new one.
33
36
  *
34
37
  * @param planId - The unique identifier of the payment plan
35
- * @param agentId - The unique identifier of the AI agent (optional). If provided, permissions are restricted to that specific agent.
36
- * @param redemptionLimit - Maximum number of interactions/redemptions allowed (optional)
37
- * @param orderLimit - Maximum spend limit in token units (wei) for ordering (optional)
38
- * @param expiration - Expiration date in ISO 8601 format, e.g. "2025-02-01T10:00:00Z" (optional)
38
+ * @param agentId - The unique identifier of the AI agent (optional)
39
+ * @param tokenOptions - Options controlling scheme and delegation behavior (optional)
39
40
  * @returns A promise that resolves to an object containing:
40
41
  * - accessToken: The X402 access token string
41
- * - Additional metadata about the token
42
42
  *
43
43
  * @throws PaymentsError if the request fails
44
44
  *
45
45
  * @example
46
46
  * ```typescript
47
- * import { Payments } from '@nevermined-io/payments'
48
- *
49
- * const payments = Payments.getInstance({
50
- * nvmApiKey: 'nvm:subscriber-key',
51
- * environment: 'sandbox'
47
+ * // Pattern A auto-create delegation
48
+ * const result = await payments.x402.getX402AccessToken(planId, agentId, {
49
+ * delegationConfig: { spendingLimitCents: 10000, durationSecs: 604800 }
52
50
  * })
53
51
  *
54
- * const result = await payments.x402.getX402AccessToken(planId, agentId)
55
- * const token = result.accessToken
52
+ * // Pattern B reuse existing delegation
53
+ * const result = await payments.x402.getX402AccessToken(planId, agentId, {
54
+ * delegationConfig: { delegationId: 'existing-delegation-uuid' }
55
+ * })
56
56
  * ```
57
57
  */
58
- async getX402AccessToken(planId, agentId, redemptionLimit, orderLimit, expiration, tokenOptions) {
58
+ async getX402AccessToken(planId, agentId, tokenOptions) {
59
59
  const urlPath = API_URL_CREATE_PERMISSION;
60
60
  const url = new URL(urlPath, this.environment.backend);
61
61
  const scheme = tokenOptions?.scheme ?? 'nvm:erc4337';
62
62
  const network = tokenOptions?.network ?? getDefaultNetwork(scheme, this.environmentName);
63
+ // Validate delegationConfig is provided — the backend requires it for token generation
64
+ if (!tokenOptions?.delegationConfig) {
65
+ throw PaymentsError.validation(`delegationConfig is required for ${scheme} token generation. ` +
66
+ 'Provide delegationConfig.delegationId to reuse an existing delegation, ' +
67
+ 'or delegationConfig.spendingLimitCents + durationSecs to auto-create one.');
68
+ }
63
69
  // Build x402-aligned request body
64
70
  const body = {
65
71
  accepted: {
@@ -71,31 +77,15 @@ export class X402TokenAPI extends BasePaymentsAPI {
71
77
  },
72
78
  },
73
79
  };
74
- // Add delegation config for card-delegation scheme
75
- if (scheme === 'nvm:card-delegation' && tokenOptions?.delegationConfig) {
80
+ // Add delegation config for both erc4337 and card-delegation schemes
81
+ if (tokenOptions?.delegationConfig) {
76
82
  body.delegationConfig = tokenOptions.delegationConfig;
77
83
  }
78
- // Add session key config if any options are provided (erc4337 only)
79
- if (scheme === 'nvm:erc4337') {
80
- const sessionKeyConfig = {};
81
- if (redemptionLimit !== undefined) {
82
- sessionKeyConfig.redemptionLimit = redemptionLimit;
83
- }
84
- if (orderLimit !== undefined) {
85
- sessionKeyConfig.orderLimit = orderLimit;
86
- }
87
- if (expiration !== undefined) {
88
- sessionKeyConfig.expiration = expiration;
89
- }
90
- if (Object.keys(sessionKeyConfig).length > 0) {
91
- body.sessionKeyConfig = sessionKeyConfig;
92
- }
93
- }
94
84
  const options = this.getBackendHTTPOptions('POST', body);
95
85
  try {
96
86
  const response = await fetch(url, options);
97
87
  if (!response.ok) {
98
- let errorMessage = 'Failed to create X402 permission';
88
+ let errorMessage = 'Failed to create X402 delegation token';
99
89
  try {
100
90
  const errorData = await response.json();
101
91
  errorMessage = errorData.message || errorMessage;
@@ -111,7 +101,7 @@ export class X402TokenAPI extends BasePaymentsAPI {
111
101
  if (error instanceof PaymentsError) {
112
102
  throw error;
113
103
  }
114
- throw PaymentsError.internal(`Network error while creating X402 permission: ${error instanceof Error ? error.message : String(error)}`);
104
+ throw PaymentsError.internal(`Network error while creating X402 delegation token: ${error instanceof Error ? error.message : String(error)}`);
115
105
  }
116
106
  }
117
107
  }
@@ -1 +1 @@
1
- {"version":3,"file":"token.js","sourceRoot":"","sources":["../../src/x402/token.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,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,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC1G,CAAA;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * X402 Token Generation API.\n *\n * Provides X402 access token generation functionality for subscribers.\n * Tokens are used to authorize payment verification and settlement.\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { API_URL_CREATE_PERMISSION } from '../api/nvm-api.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { PaymentOptions, X402TokenOptions, getDefaultNetwork } from '../common/types.js'\n\n/**\n * X402 Token API for generating access tokens.\n *\n * Handles X402 access token generation for subscribers to authorize\n * payment operations with AI agents.\n */\nexport class X402TokenAPI extends BasePaymentsAPI {\n /**\n * Get a singleton instance of the X402TokenAPI class.\n *\n * @param options - The options to initialize the API\n * @returns The instance of the X402TokenAPI class\n */\n static getInstance(options: PaymentOptions): X402TokenAPI {\n return new X402TokenAPI(options)\n }\n\n /**\n * Create a permission and get an X402 access token for the given plan.\n *\n * This token allows the agent to verify and settle permissions on behalf\n * of the subscriber. The token contains cryptographically signed session keys\n * that delegate specific permissions (order, burn) to the agent.\n *\n * @param planId - The unique identifier of the payment plan\n * @param agentId - The unique identifier of the AI agent (optional). If provided, permissions are restricted to that specific agent.\n * @param redemptionLimit - Maximum number of interactions/redemptions allowed (optional)\n * @param orderLimit - Maximum spend limit in token units (wei) for ordering (optional)\n * @param expiration - Expiration date in ISO 8601 format, e.g. \"2025-02-01T10:00:00Z\" (optional)\n * @returns A promise that resolves to an object containing:\n * - accessToken: The X402 access token string\n * - Additional metadata about the token\n *\n * @throws PaymentsError if the request fails\n *\n * @example\n * ```typescript\n * import { Payments } from '@nevermined-io/payments'\n *\n * const payments = Payments.getInstance({\n * nvmApiKey: 'nvm:subscriber-key',\n * environment: 'sandbox'\n * })\n *\n * const result = await payments.x402.getX402AccessToken(planId, agentId)\n * const token = result.accessToken\n * ```\n */\n async getX402AccessToken(\n planId: string,\n agentId?: string,\n redemptionLimit?: number,\n orderLimit?: string,\n expiration?: string,\n tokenOptions?: X402TokenOptions,\n ): Promise<{ accessToken: string;[key: string]: any }> {\n const urlPath = API_URL_CREATE_PERMISSION\n const url = new URL(urlPath, this.environment.backend)\n\n const scheme = tokenOptions?.scheme ?? 'nvm:erc4337'\n const network = tokenOptions?.network ?? getDefaultNetwork(scheme, this.environmentName)\n\n // Build x402-aligned request body\n const body: Record<string, any> = {\n accepted: {\n scheme,\n network,\n planId,\n extra: {\n ...(agentId && { agentId }),\n },\n },\n }\n\n // Add delegation config for card-delegation scheme\n if (scheme === 'nvm:card-delegation' && tokenOptions?.delegationConfig) {\n body.delegationConfig = tokenOptions.delegationConfig\n }\n\n // Add session key config if any options are provided (erc4337 only)\n if (scheme === 'nvm:erc4337') {\n const sessionKeyConfig: Record<string, any> = {}\n if (redemptionLimit !== undefined) {\n sessionKeyConfig.redemptionLimit = redemptionLimit\n }\n if (orderLimit !== undefined) {\n sessionKeyConfig.orderLimit = orderLimit\n }\n if (expiration !== undefined) {\n sessionKeyConfig.expiration = expiration\n }\n if (Object.keys(sessionKeyConfig).length > 0) {\n body.sessionKeyConfig = sessionKeyConfig\n }\n }\n\n const options = this.getBackendHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Failed to create X402 permission'\n try {\n const errorData = await response.json()\n errorMessage = errorData.message || errorMessage\n } catch {\n // Use default error message\n }\n throw PaymentsError.internal(`${errorMessage} (HTTP ${response.status})`)\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) {\n throw error\n }\n throw PaymentsError.internal(\n `Network error while creating X402 permission: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n"]}
1
+ {"version":3,"file":"token.js","sourceRoot":"","sources":["../../src/x402/token.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,E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AAM,OAAO,GAAG,IAAI,CAAC,qBAAqB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;QAExD,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;YAC1C,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;gBACjB,IAAI,YAAY,GAAG,wCAAwC,CAAA;gBAC3D,IAAI,CAAC;oBACH,MAAM,SAAS,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;oBACvC,YAAY,GAAG,SAAS,CAAC,OAAO,IAAI,YAAY,CAAA;gBAClD,CAAC;gBAAC,MAAM,CAAC;oBACP,4BAA4B;gBAC9B,CAAC;gBACD,MAAM,aAAa,CAAC,QAAQ,CAAC,GAAG,YAAY,UAAU,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAA;YAC3E,CAAC;YACD,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,aAAa,EAAE,CAAC;gBACnC,MAAM,KAAK,CAAA;YACb,CAAC;YACD,MAAM,aAAa,CAAC,QAAQ,CAC1B,uDAAuD,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAChH,CAAA;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * X402 Token Generation API.\n *\n * Provides X402 access token generation functionality for subscribers.\n * Tokens are used to authorize payment verification and settlement.\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { API_URL_CREATE_PERMISSION } from '../api/nvm-api.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { PaymentOptions, X402TokenOptions, getDefaultNetwork } from '../common/types.js'\n\n/**\n * X402 Token API for generating access tokens.\n *\n * Handles X402 access token generation for subscribers to authorize\n * payment operations with AI agents.\n */\nexport class X402TokenAPI extends BasePaymentsAPI {\n /**\n * Get a singleton instance of the X402TokenAPI class.\n *\n * @param options - The options to initialize the API\n * @returns The instance of the X402TokenAPI class\n */\n static getInstance(options: PaymentOptions): X402TokenAPI {\n return new X402TokenAPI(options)\n }\n\n /**\n * Create a delegation and get an X402 access token for the given plan.\n *\n * This token allows the agent to verify and settle delegations on behalf\n * of the subscriber.\n *\n * For erc4337 scheme, you must pass `tokenOptions.delegationConfig` with either:\n * - `delegationId` to reuse an existing delegation, or\n * - `spendingLimitCents` + `durationSecs` to auto-create a new one.\n *\n * @param planId - The unique identifier of the payment plan\n * @param agentId - The unique identifier of the AI agent (optional)\n * @param tokenOptions - Options controlling scheme and delegation behavior (optional)\n * @returns A promise that resolves to an object containing:\n * - accessToken: The X402 access token string\n *\n * @throws PaymentsError if the request fails\n *\n * @example\n * ```typescript\n * // Pattern A auto-create delegation\n * const result = await payments.x402.getX402AccessToken(planId, agentId, {\n * delegationConfig: { spendingLimitCents: 10000, durationSecs: 604800 }\n * })\n *\n * // Pattern B — reuse existing delegation\n * const result = await payments.x402.getX402AccessToken(planId, agentId, {\n * delegationConfig: { delegationId: 'existing-delegation-uuid' }\n * })\n * ```\n */\n async getX402AccessToken(\n planId: string,\n agentId?: string,\n tokenOptions?: X402TokenOptions,\n ): Promise<{ accessToken: string; [key: string]: any }> {\n const urlPath = API_URL_CREATE_PERMISSION\n const url = new URL(urlPath, this.environment.backend)\n\n const scheme = tokenOptions?.scheme ?? 'nvm:erc4337'\n const network = tokenOptions?.network ?? getDefaultNetwork(scheme, this.environmentName)\n\n // Validate delegationConfig is provided — the backend requires it for token generation\n if (!tokenOptions?.delegationConfig) {\n throw PaymentsError.validation(\n `delegationConfig is required for ${scheme} token generation. ` +\n 'Provide delegationConfig.delegationId to reuse an existing delegation, ' +\n 'or delegationConfig.spendingLimitCents + durationSecs to auto-create one.',\n )\n }\n\n // Build x402-aligned request body\n const body: Record<string, any> = {\n accepted: {\n scheme,\n network,\n planId,\n extra: {\n ...(agentId && { agentId }),\n },\n },\n }\n\n // Add delegation config for both erc4337 and card-delegation schemes\n if (tokenOptions?.delegationConfig) {\n body.delegationConfig = tokenOptions.delegationConfig\n }\n\n const options = this.getBackendHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Failed to create X402 delegation token'\n try {\n const errorData = await response.json()\n errorMessage = errorData.message || errorMessage\n } catch {\n // Use default error message\n }\n throw PaymentsError.internal(`${errorMessage} (HTTP ${response.status})`)\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) {\n throw error\n }\n throw PaymentsError.internal(\n `Network error while creating X402 delegation token: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nevermined-io/payments",
3
- "version": "1.1.18",
3
+ "version": "1.3.2",
4
4
  "description": "Typescript SDK to interact with the Nevermined Payments Protocol",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",