@nevermined-io/payments 1.6.0 → 1.8.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 (88) hide show
  1. package/dist/a2a/agent-card.d.ts +26 -0
  2. package/dist/a2a/agent-card.d.ts.map +1 -1
  3. package/dist/a2a/agent-card.js +36 -1
  4. package/dist/a2a/agent-card.js.map +1 -1
  5. package/dist/a2a/paymentsClient.d.ts +41 -1
  6. package/dist/a2a/paymentsClient.d.ts.map +1 -1
  7. package/dist/a2a/paymentsClient.js +120 -8
  8. package/dist/a2a/paymentsClient.js.map +1 -1
  9. package/dist/a2a/paymentsRequestHandler.d.ts +25 -2
  10. package/dist/a2a/paymentsRequestHandler.d.ts.map +1 -1
  11. package/dist/a2a/paymentsRequestHandler.js +240 -20
  12. package/dist/a2a/paymentsRequestHandler.js.map +1 -1
  13. package/dist/a2a/server.d.ts +2 -2
  14. package/dist/a2a/server.d.ts.map +1 -1
  15. package/dist/a2a/server.js +70 -20
  16. package/dist/a2a/server.js.map +1 -1
  17. package/dist/a2a/types.d.ts +31 -1
  18. package/dist/a2a/types.d.ts.map +1 -1
  19. package/dist/a2a/types.js.map +1 -1
  20. package/dist/a2a/x402-a2a.d.ts +142 -0
  21. package/dist/a2a/x402-a2a.d.ts.map +1 -0
  22. package/dist/a2a/x402-a2a.js +254 -0
  23. package/dist/a2a/x402-a2a.js.map +1 -0
  24. package/dist/api/agents-api.d.ts +19 -0
  25. package/dist/api/agents-api.d.ts.map +1 -1
  26. package/dist/api/agents-api.js +30 -3
  27. package/dist/api/agents-api.js.map +1 -1
  28. package/dist/api/base-payments.d.ts +6 -4
  29. package/dist/api/base-payments.d.ts.map +1 -1
  30. package/dist/api/base-payments.js +10 -0
  31. package/dist/api/base-payments.js.map +1 -1
  32. package/dist/api/contracts-api.js +1 -1
  33. package/dist/api/contracts-api.js.map +1 -1
  34. package/dist/api/nvm-api.d.ts +1 -0
  35. package/dist/api/nvm-api.d.ts.map +1 -1
  36. package/dist/api/nvm-api.js +4 -0
  37. package/dist/api/nvm-api.js.map +1 -1
  38. package/dist/api/plans-api.d.ts +12 -2
  39. package/dist/api/plans-api.d.ts.map +1 -1
  40. package/dist/api/plans-api.js +12 -12
  41. package/dist/api/plans-api.js.map +1 -1
  42. package/dist/common/api-version.d.ts +24 -0
  43. package/dist/common/api-version.d.ts.map +1 -0
  44. package/dist/common/api-version.js +24 -0
  45. package/dist/common/api-version.js.map +1 -0
  46. package/dist/common/types.d.ts +73 -18
  47. package/dist/common/types.d.ts.map +1 -1
  48. package/dist/common/types.js.map +1 -1
  49. package/dist/index.d.ts +3 -0
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +4 -0
  52. package/dist/index.js.map +1 -1
  53. package/dist/mcp/core/auth.d.ts +14 -0
  54. package/dist/mcp/core/auth.d.ts.map +1 -1
  55. package/dist/mcp/core/auth.js +56 -23
  56. package/dist/mcp/core/auth.js.map +1 -1
  57. package/dist/mcp/core/paywall.d.ts +6 -0
  58. package/dist/mcp/core/paywall.d.ts.map +1 -1
  59. package/dist/mcp/core/paywall.js +170 -84
  60. package/dist/mcp/core/paywall.js.map +1 -1
  61. package/dist/mcp/utils/errors.d.ts +26 -0
  62. package/dist/mcp/utils/errors.d.ts.map +1 -1
  63. package/dist/mcp/utils/errors.js +32 -0
  64. package/dist/mcp/utils/errors.js.map +1 -1
  65. package/dist/mcp/utils/meta.d.ts +54 -0
  66. package/dist/mcp/utils/meta.d.ts.map +1 -0
  67. package/dist/mcp/utils/meta.js +72 -0
  68. package/dist/mcp/utils/meta.js.map +1 -0
  69. package/dist/payments.d.ts +4 -3
  70. package/dist/payments.d.ts.map +1 -1
  71. package/dist/payments.js +5 -3
  72. package/dist/payments.js.map +1 -1
  73. package/dist/utils.d.ts +27 -0
  74. package/dist/utils.d.ts.map +1 -1
  75. package/dist/utils.js +34 -0
  76. package/dist/utils.js.map +1 -1
  77. package/dist/x402/facilitator-api.d.ts +21 -0
  78. package/dist/x402/facilitator-api.d.ts.map +1 -1
  79. package/dist/x402/facilitator-api.js +39 -0
  80. package/dist/x402/facilitator-api.js.map +1 -1
  81. package/dist/x402/index.d.ts +1 -1
  82. package/dist/x402/index.d.ts.map +1 -1
  83. package/dist/x402/index.js.map +1 -1
  84. package/dist/x402/token.d.ts +13 -10
  85. package/dist/x402/token.d.ts.map +1 -1
  86. package/dist/x402/token.js +46 -16
  87. package/dist/x402/token.js.map +1 -1
  88. package/package.json +2 -2
@@ -220,6 +220,27 @@ export declare function buildPaymentRequired(planId: string, options?: {
220
220
  scheme?: X402SchemeType;
221
221
  environment?: EnvironmentName;
222
222
  }): X402PaymentRequired;
223
+ /**
224
+ * Build an X402PaymentRequired object advertising one or more plans.
225
+ *
226
+ * Like {@link buildPaymentRequired} but produces one `accepts[]` entry per plan
227
+ * id, so a payment-required response can advertise every plan that unlocks the
228
+ * resource. For a single plan this is equivalent to {@link buildPaymentRequired}.
229
+ *
230
+ * @param planIds - The Nevermined plan identifiers (falls back to `['']` if empty)
231
+ * @param options - Same options as {@link buildPaymentRequired}
232
+ * @returns X402PaymentRequired object with one accepts entry per plan
233
+ */
234
+ export declare function buildPaymentRequiredForPlans(planIds: string[], options?: {
235
+ endpoint?: string;
236
+ agentId?: string;
237
+ httpVerb?: string;
238
+ network?: string;
239
+ description?: string;
240
+ mimeType?: string;
241
+ scheme?: X402SchemeType;
242
+ environment?: EnvironmentName;
243
+ }): X402PaymentRequired;
223
244
  /**
224
245
  * Resolve the network for a plan from its fiatPaymentProvider metadata.
225
246
  * For card-delegation plans, returns the provider ('stripe' or 'braintree').
@@ -1 +1 @@
1
- {"version":3,"file":"facilitator-api.d.ts","sourceRoot":"","sources":["../../src/x402/facilitator-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAGzD,OAAO,EACL,cAAc,EAC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AAmB,CAqCrB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,MAAM,EAAE,EACjB,OAAO,CAAC,EAAE;IACR,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE,cAAc,CAAA;IACvB,WAAW,CAAC,EAAE,eAAe,CAAA;CAC9B,GACA,mBAAmB,CAuCrB;AAgCD;;;;GAIG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,EACd,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAK7B;AAED;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CACjC,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,EACd,cAAc,CAAC,EAAE,cAAc,GAC9B,OAAO,CAAC,cAAc,CAAC,CAIzB;AAED;;;;GAIG;AACH,qBAAa,cAAe,SAAQ,eAAe;IACjD;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,cAAc;IAI3D;;;;;;;;;;;;;;OAcG;IACG,iBAAiB,CAAC,MAAM,EAAE,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAkD1F;;;;;;;;;;;;;;;;;;OAkBG;IACG,iBAAiB,CAAC,MAAM,EAAE,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;CA2D3F"}
@@ -98,6 +98,45 @@ export function buildPaymentRequired(planId, options) {
98
98
  extensions: {},
99
99
  };
100
100
  }
101
+ /**
102
+ * Build an X402PaymentRequired object advertising one or more plans.
103
+ *
104
+ * Like {@link buildPaymentRequired} but produces one `accepts[]` entry per plan
105
+ * id, so a payment-required response can advertise every plan that unlocks the
106
+ * resource. For a single plan this is equivalent to {@link buildPaymentRequired}.
107
+ *
108
+ * @param planIds - The Nevermined plan identifiers (falls back to `['']` if empty)
109
+ * @param options - Same options as {@link buildPaymentRequired}
110
+ * @returns X402PaymentRequired object with one accepts entry per plan
111
+ */
112
+ export function buildPaymentRequiredForPlans(planIds, options) {
113
+ const ids = planIds.length > 0 ? planIds : [''];
114
+ if (ids.length === 1) {
115
+ return buildPaymentRequired(ids[0], options);
116
+ }
117
+ const { endpoint, agentId, httpVerb, scheme = 'nvm:erc4337', network, description, mimeType, environment, } = options || {};
118
+ const resolvedNetwork = network ?? getDefaultNetwork(scheme, environment);
119
+ const extra = {
120
+ version: '1',
121
+ ...(agentId && { agentId }),
122
+ ...(httpVerb && { httpVerb }),
123
+ };
124
+ return {
125
+ x402Version: 2,
126
+ resource: {
127
+ url: endpoint || '',
128
+ ...(description && { description }),
129
+ ...(mimeType && { mimeType }),
130
+ },
131
+ accepts: ids.map((planId) => ({
132
+ scheme,
133
+ network: resolvedNetwork,
134
+ planId,
135
+ extra,
136
+ })),
137
+ extensions: {},
138
+ };
139
+ }
101
140
  const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
102
141
  const planMetadataCache = new Map();
103
142
  async function fetchPlanMetadata(payments, planId) {
@@ -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,EAIL,iBAAiB,GAClB,MAAM,oBAAoB,CAAA;AA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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 {\n PaymentOptions,\n StartAgentRequest,\n X402SchemeType,\n getDefaultNetwork,\n} from '../common/types.js'\nimport type { EnvironmentName } from '../environments.js'\nimport type { Payments } from '../payments.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 */\n paymentRequired: X402PaymentRequired\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', 'visa', '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 */\n paymentRequired: X402PaymentRequired\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 = 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 // Send the NVM API-key auth header (Authorization: Bearer <nvmApiKey>).\n // The backend /verify endpoint runs an OPTIONAL guard that tolerates the\n // header's absence today, so this is non-breaking; it pre-positions for\n // the later strict-guard flip. See nevermined-io/nvm-monorepo#1570.\n const options = this.getBackendHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission verification failed'\n let errorCode = `http_${response.status}`\n try {\n const errorData = await response.json()\n if (errorData.message) errorMessage = errorData.message\n if (errorData.code) errorCode = errorData.code\n if (errorData.hint) errorMessage = `${errorMessage} — ${errorData.hint}`\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: errorCode,\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 // Send the NVM API-key auth header (Authorization: Bearer <nvmApiKey>).\n // The backend /settle endpoint runs an OPTIONAL guard that tolerates the\n // header's absence today, so this is non-breaking; it pre-positions for\n // the later strict-guard flip. See nevermined-io/nvm-monorepo#1570.\n const options = this.getBackendHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission settlement failed'\n let errorCode = `http_${response.status}`\n try {\n const errorData = await response.json()\n if (errorData.message) errorMessage = errorData.message\n if (errorData.code) errorCode = errorData.code\n if (errorData.hint) errorMessage = `${errorMessage} — ${errorData.hint}`\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: errorCode,\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,yB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;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,aAAa,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 {\n PaymentOptions,\n StartAgentRequest,\n X402SchemeType,\n getDefaultNetwork,\n} from '../common/types.js'\nimport type { EnvironmentName } from '../environments.js'\nimport type { Payments } from '../payments.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 */\n paymentRequired: X402PaymentRequired\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', 'visa', '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 */\n paymentRequired: X402PaymentRequired\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\n/**\n * Build an X402PaymentRequired object advertising one or more plans.\n *\n * Like {@link buildPaymentRequired} but produces one `accepts[]` entry per plan\n * id, so a payment-required response can advertise every plan that unlocks the\n * resource. For a single plan this is equivalent to {@link buildPaymentRequired}.\n *\n * @param planIds - The Nevermined plan identifiers (falls back to `['']` if empty)\n * @param options - Same options as {@link buildPaymentRequired}\n * @returns X402PaymentRequired object with one accepts entry per plan\n */\nexport function buildPaymentRequiredForPlans(\n planIds: 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 ids = planIds.length > 0 ? planIds : ['']\n if (ids.length === 1) {\n return buildPaymentRequired(ids[0], options)\n }\n\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 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: ids.map((planId) => ({\n scheme,\n network: resolvedNetwork,\n planId,\n extra,\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 = 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 // Send the NVM API-key auth header (Authorization: Bearer <nvmApiKey>).\n // The backend /verify endpoint runs an OPTIONAL guard that tolerates the\n // header's absence today, so this is non-breaking; it pre-positions for\n // the later strict-guard flip. See nevermined-io/nvm-monorepo#1570.\n const options = this.getBackendHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission verification failed'\n let errorCode = `http_${response.status}`\n try {\n const errorData = await response.json()\n if (errorData.message) errorMessage = errorData.message\n if (errorData.code) errorCode = errorData.code\n if (errorData.hint) errorMessage = `${errorMessage} — ${errorData.hint}`\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: errorCode,\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 // Send the NVM API-key auth header (Authorization: Bearer <nvmApiKey>).\n // The backend /settle endpoint runs an OPTIONAL guard that tolerates the\n // header's absence today, so this is non-breaking; it pre-positions for\n // the later strict-guard flip. See nevermined-io/nvm-monorepo#1570.\n const options = this.getBackendHTTPOptions('POST', body)\n\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let errorMessage = 'Permission settlement failed'\n let errorCode = `http_${response.status}`\n try {\n const errorData = await response.json()\n if (errorData.message) errorMessage = errorData.message\n if (errorData.code) errorCode = errorData.code\n if (errorData.hint) errorMessage = `${errorMessage} — ${errorData.hint}`\n } catch {\n // Use default error message\n }\n throw PaymentsError.fromBackend(errorMessage, {\n message: errorMessage,\n code: errorCode,\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"]}
@@ -6,6 +6,6 @@ export { FacilitatorAPI, buildPaymentRequired, resolveNetwork, resolveScheme, }
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
8
  export type { CardProvider, DelegationProvider, PaymentMethodSummary, UpdatePaymentMethodDto, DelegationSummary, DelegationListResponse, PurchasingPower, ListOptions, } from './delegation-api.js';
9
- export type { X402SchemeType, DelegationConfig, CreateDelegationPayload, CreateDelegationResponse, X402TokenOptions, } from '../common/types.js';
9
+ export type { X402SchemeType, DelegationConfig, DelegationCurrency, CreateDelegationPayload, CreateDelegationResponse, X402TokenOptions, } from '../common/types.js';
10
10
  export { X402_SCHEME_NETWORKS, getDefaultNetwork, isValidScheme } from '../common/types.js';
11
11
  //# sourceMappingURL=index.d.ts.map
@@ -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,EACL,cAAc,EACd,oBAAoB,EACpB,cAAc,EACd,aAAa,GACd,MAAM,sBAAsB,CAAA;AAC7B,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,YAAY,EACZ,kBAAkB,EAClB,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"}
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,EACL,cAAc,EACd,oBAAoB,EACpB,cAAc,EACd,aAAa,GACd,MAAM,sBAAsB,CAAA;AAC7B,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,YAAY,EACZ,kBAAkB,EAClB,oBAAoB,EACpB,sBAAsB,EACtB,iBAAiB,EACjB,sBAAsB,EACtB,eAAe,EACf,WAAW,GACZ,MAAM,qBAAqB,CAAA;AAG5B,YAAY,EACV,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,uBAAuB,EACvB,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA"}
@@ -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,EACL,cAAc,EACd,oBAAoB,EACpB,cAAc,EACd,aAAa,GACd,MAAM,sBAAsB,CAAA;AAe7B,qBAAqB;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAoBnD,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA","sourcesContent":["/**\n * X402 API module for token generation and facilitator operations.\n */\n\nexport { X402TokenAPI } from './token.js'\nexport {\n FacilitatorAPI,\n buildPaymentRequired,\n resolveNetwork,\n resolveScheme,\n} 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 CardProvider,\n DelegationProvider,\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"]}
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,EACL,cAAc,EACd,oBAAoB,EACpB,cAAc,EACd,aAAa,GACd,MAAM,sBAAsB,CAAA;AAe7B,qBAAqB;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAqBnD,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA","sourcesContent":["/**\n * X402 API module for token generation and facilitator operations.\n */\n\nexport { X402TokenAPI } from './token.js'\nexport {\n FacilitatorAPI,\n buildPaymentRequired,\n resolveNetwork,\n resolveScheme,\n} 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 CardProvider,\n DelegationProvider,\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 DelegationCurrency,\n CreateDelegationPayload,\n CreateDelegationResponse,\n X402TokenOptions,\n} from '../common/types.js'\nexport { X402_SCHEME_NETWORKS, getDefaultNetwork, isValidScheme } from '../common/types.js'\n"]}
@@ -21,14 +21,16 @@ export declare class X402TokenAPI extends BasePaymentsAPI {
21
21
  */
22
22
  static getInstance(options: PaymentOptions): X402TokenAPI;
23
23
  /**
24
- * Create a delegation and get an X402 access token for the given plan.
24
+ * Get an X402 access token for the given plan, backed by a delegation.
25
25
  *
26
26
  * This token allows the agent to verify and settle delegations on behalf
27
27
  * of the subscriber.
28
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
+ * The supported flow is **create-first**: create the delegation once with
30
+ * {@link DelegationAPI.createDelegation}, then pass its `delegationId` in
31
+ * `tokenOptions.delegationConfig`. Passing inline create-on-the-fly fields
32
+ * (spending limits / `providerPaymentMethodId` / `cardId`, i.e. no
33
+ * `delegationId`) is **deprecated** and emits a runtime warning.
32
34
  *
33
35
  * @param planId - The unique identifier of the payment plan
34
36
  * @param agentId - The unique identifier of the AI agent (optional)
@@ -40,14 +42,15 @@ export declare class X402TokenAPI extends BasePaymentsAPI {
40
42
  *
41
43
  * @example
42
44
  * ```typescript
43
- * // Pattern A auto-create delegation
44
- * const result = await payments.x402.getX402AccessToken(planId, agentId, {
45
- * delegationConfig: { spendingLimitCents: 10000, durationSecs: 604800 }
45
+ * // Supported: create the delegation first, then request the token by id.
46
+ * const { delegationId } = await payments.delegation.createDelegation({
47
+ * provider: 'erc4337',
48
+ * spendingLimitCents: 10000,
49
+ * durationSecs: 604800,
50
+ * currency: 'usdc',
46
51
  * })
47
- *
48
- * // Pattern B — reuse existing delegation
49
52
  * const result = await payments.x402.getX402AccessToken(planId, agentId, {
50
- * delegationConfig: { delegationId: 'existing-delegation-uuid' }
53
+ * delegationConfig: { delegationId },
51
54
  * })
52
55
  * ```
53
56
  */
@@ -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,YAAY,CAAC,EAAE,gBAAgB,GAC9B,OAAO,CAAC;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;CAyDxD"}
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAiCG;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;CA2FxD"}
@@ -25,14 +25,16 @@ export class X402TokenAPI extends BasePaymentsAPI {
25
25
  return new X402TokenAPI(options);
26
26
  }
27
27
  /**
28
- * Create a delegation and get an X402 access token for the given plan.
28
+ * Get an X402 access token for the given plan, backed by a delegation.
29
29
  *
30
30
  * This token allows the agent to verify and settle delegations on behalf
31
31
  * of the subscriber.
32
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
+ * The supported flow is **create-first**: create the delegation once with
34
+ * {@link DelegationAPI.createDelegation}, then pass its `delegationId` in
35
+ * `tokenOptions.delegationConfig`. Passing inline create-on-the-fly fields
36
+ * (spending limits / `providerPaymentMethodId` / `cardId`, i.e. no
37
+ * `delegationId`) is **deprecated** and emits a runtime warning.
36
38
  *
37
39
  * @param planId - The unique identifier of the payment plan
38
40
  * @param agentId - The unique identifier of the AI agent (optional)
@@ -44,14 +46,15 @@ export class X402TokenAPI extends BasePaymentsAPI {
44
46
  *
45
47
  * @example
46
48
  * ```typescript
47
- * // Pattern A auto-create delegation
48
- * const result = await payments.x402.getX402AccessToken(planId, agentId, {
49
- * delegationConfig: { spendingLimitCents: 10000, durationSecs: 604800 }
49
+ * // Supported: create the delegation first, then request the token by id.
50
+ * const { delegationId } = await payments.delegation.createDelegation({
51
+ * provider: 'erc4337',
52
+ * spendingLimitCents: 10000,
53
+ * durationSecs: 604800,
54
+ * currency: 'usdc',
50
55
  * })
51
- *
52
- * // Pattern B — reuse existing delegation
53
56
  * const result = await payments.x402.getX402AccessToken(planId, agentId, {
54
- * delegationConfig: { delegationId: 'existing-delegation-uuid' }
57
+ * delegationConfig: { delegationId },
55
58
  * })
56
59
  * ```
57
60
  */
@@ -63,8 +66,36 @@ export class X402TokenAPI extends BasePaymentsAPI {
63
66
  // Validate delegationConfig is provided — the backend requires it for token generation
64
67
  if (!tokenOptions?.delegationConfig) {
65
68
  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.');
69
+ 'Create a delegation first with payments.delegation.createDelegation(), ' +
70
+ 'then request the token with delegationConfig.delegationId.');
71
+ }
72
+ // Deprecation: the supported flow is create-first — create the delegation
73
+ // with createDelegation(), then request the token with { delegationId }.
74
+ // A delegationConfig that carries an inline-create signal instead of a
75
+ // delegationId triggers inline create-on-the-fly, which the backend has
76
+ // deprecated (auto-select and providerPaymentMethodId/cardId creation).
77
+ // Warn once per call; the { delegationId } (± apiKeyId) path is silent.
78
+ // Predicate mirrors the Python SDK (payments-py#224): no delegationId AND
79
+ // at least one creation field present — a bare/invalid config is left to
80
+ // fail downstream rather than warned.
81
+ const { delegationId, cardId, providerPaymentMethodId, spendingLimitCents, durationSecs } = tokenOptions.delegationConfig;
82
+ // Reject an explicit empty/blank delegationId early — it is neither a valid
83
+ // reuse id nor an inline-create signal, and forwarding `delegationId: ''`
84
+ // would 4xx at the backend. (Symmetric with the Python SDK, payments-py#225.)
85
+ if (delegationId !== undefined && delegationId.trim() === '') {
86
+ throw PaymentsError.validation('delegationConfig.delegationId must not be an empty string. ' +
87
+ 'Pass a valid delegation UUID or omit the field.');
88
+ }
89
+ const isInlineCreate = !delegationId &&
90
+ (cardId !== undefined ||
91
+ providerPaymentMethodId !== undefined ||
92
+ spendingLimitCents !== undefined ||
93
+ durationSecs !== undefined);
94
+ if (isInlineCreate) {
95
+ console.warn('[DEPRECATED] getX402AccessToken: inline create-on-the-fly delegationConfig ' +
96
+ '(no delegationId) is deprecated and will be removed in a future release. ' +
97
+ 'Create the delegation first with payments.delegation.createDelegation(), ' +
98
+ 'then request the token with delegationConfig: { delegationId }.');
68
99
  }
69
100
  // Build x402-aligned request body
70
101
  const body = {
@@ -77,10 +108,9 @@ export class X402TokenAPI extends BasePaymentsAPI {
77
108
  },
78
109
  },
79
110
  };
80
- // Add delegation config for both erc4337 and card-delegation schemes
81
- if (tokenOptions?.delegationConfig) {
82
- body.delegationConfig = tokenOptions.delegationConfig;
83
- }
111
+ // Add delegation config for both erc4337 and card-delegation schemes.
112
+ // delegationConfig is guaranteed present here (the absence check above throws).
113
+ body.delegationConfig = tokenOptions.delegationConfig;
84
114
  const options = this.getBackendHTTPOptions('POST', body);
85
115
  try {
86
116
  const response = await fetch(url, options);
@@ -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,yBAAyB,EAAE,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAAoC,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAExF;;;;;GAKG;AACH,MAAM,OAAO,YAAa,SAAQ,eAAe;IAC/C;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAuB;QACxC,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC,CAAA;IAClC,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IACH,KAAK,CAAC,kBAAkB,CACtB,MAAc,EACd,OAAgB,EAChB,YAA+B;QAE/B,MAAM,OAAO,GAAG,yBAAyB,CAAA;QACzC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;QAEtD,MAAM,MAAM,GAAG,YAAY,EAAE,MAAM,IAAI,aAAa,CAAA;QACpD,MAAM,OAAO,GAAG,YAAY,EAAE,OAAO,IAAI,iBAAiB,CAAC,MAAM,EAAE,IAAI,CAAC,eAAe,CAAC,CAAA;QAExF,uFAAuF;QACvF,IAAI,CAAC,YAAY,EAAE,gBAAgB,EAAE,CAAC;YACpC,MAAM,aAAa,CAAC,UAAU,CAC5B,oCAAoC,MAAM,qBAAqB;gBAC7D,yEAAyE;gBACzE,2EAA2E,CAC9E,CAAA;QACH,CAAC;Q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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"]}
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,yBAAyB,EAAE,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAC3D,OAAO,EAAoC,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAExF;;;;;GAKG;AACH,MAAM,OAAO,YAAa,SAAQ,eAAe;IAC/C;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,OAAuB;QACxC,OAAO,IAAI,YAAY,CAAC,OAAO,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,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 * Get an X402 access token for the given plan, backed by a delegation.\n *\n * This token allows the agent to verify and settle delegations on behalf\n * of the subscriber.\n *\n * The supported flow is **create-first**: create the delegation once with\n * {@link DelegationAPI.createDelegation}, then pass its `delegationId` in\n * `tokenOptions.delegationConfig`. Passing inline create-on-the-fly fields\n * (spending limits / `providerPaymentMethodId` / `cardId`, i.e. no\n * `delegationId`) is **deprecated** and emits a runtime warning.\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 * // Supported: create the delegation first, then request the token by id.\n * const { delegationId } = await payments.delegation.createDelegation({\n * provider: 'erc4337',\n * spendingLimitCents: 10000,\n * durationSecs: 604800,\n * currency: 'usdc',\n * })\n * const result = await payments.x402.getX402AccessToken(planId, agentId, {\n * delegationConfig: { delegationId },\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 'Create a delegation first with payments.delegation.createDelegation(), ' +\n 'then request the token with delegationConfig.delegationId.',\n )\n }\n\n // Deprecation: the supported flow is create-first — create the delegation\n // with createDelegation(), then request the token with { delegationId }.\n // A delegationConfig that carries an inline-create signal instead of a\n // delegationId triggers inline create-on-the-fly, which the backend has\n // deprecated (auto-select and providerPaymentMethodId/cardId creation).\n // Warn once per call; the { delegationId } (± apiKeyId) path is silent.\n // Predicate mirrors the Python SDK (payments-py#224): no delegationId AND\n // at least one creation field present — a bare/invalid config is left to\n // fail downstream rather than warned.\n const { delegationId, cardId, providerPaymentMethodId, spendingLimitCents, durationSecs } =\n tokenOptions.delegationConfig\n // Reject an explicit empty/blank delegationId early — it is neither a valid\n // reuse id nor an inline-create signal, and forwarding `delegationId: ''`\n // would 4xx at the backend. (Symmetric with the Python SDK, payments-py#225.)\n if (delegationId !== undefined && delegationId.trim() === '') {\n throw PaymentsError.validation(\n 'delegationConfig.delegationId must not be an empty string. ' +\n 'Pass a valid delegation UUID or omit the field.',\n )\n }\n const isInlineCreate =\n !delegationId &&\n (cardId !== undefined ||\n providerPaymentMethodId !== undefined ||\n spendingLimitCents !== undefined ||\n durationSecs !== undefined)\n if (isInlineCreate) {\n console.warn(\n '[DEPRECATED] getX402AccessToken: inline create-on-the-fly delegationConfig ' +\n '(no delegationId) is deprecated and will be removed in a future release. ' +\n 'Create the delegation first with payments.delegation.createDelegation(), ' +\n 'then request the token with delegationConfig: { delegationId }.',\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 // delegationConfig is guaranteed present here (the absence check above throws).\n body.delegationConfig = tokenOptions.delegationConfig\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.6.0",
3
+ "version": "1.8.0",
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",
@@ -122,7 +122,7 @@
122
122
  }
123
123
  },
124
124
  "dependencies": {
125
- "@a2a-js/sdk": "^0.3.4",
125
+ "@a2a-js/sdk": "^0.3.13",
126
126
  "@helicone/helpers": "^1.6.0",
127
127
  "@opentelemetry/api": "^1.9.0",
128
128
  "@opentelemetry/exporter-trace-otlp-http": "^0.215.0",