@nevermined-io/payments 1.3.2 → 1.4.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 (54) hide show
  1. package/README.md +5 -3
  2. package/dist/api/base-payments.d.ts.map +1 -1
  3. package/dist/api/base-payments.js +12 -10
  4. package/dist/api/base-payments.js.map +1 -1
  5. package/dist/api/nvm-api.d.ts +0 -1
  6. package/dist/api/nvm-api.d.ts.map +1 -1
  7. package/dist/api/nvm-api.js +0 -1
  8. package/dist/api/nvm-api.js.map +1 -1
  9. package/dist/api/plans-api.d.ts +9 -30
  10. package/dist/api/plans-api.d.ts.map +1 -1
  11. package/dist/api/plans-api.js +11 -46
  12. package/dist/api/plans-api.js.map +1 -1
  13. package/dist/common/types.d.ts +23 -15
  14. package/dist/common/types.d.ts.map +1 -1
  15. package/dist/common/types.js.map +1 -1
  16. package/dist/environments.d.ts +0 -7
  17. package/dist/environments.d.ts.map +1 -1
  18. package/dist/environments.js +0 -13
  19. package/dist/environments.js.map +1 -1
  20. package/dist/index.d.ts +0 -3
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +0 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/mcp/http/session-manager.d.ts.map +1 -1
  25. package/dist/mcp/http/session-manager.js +15 -1
  26. package/dist/mcp/http/session-manager.js.map +1 -1
  27. package/dist/payments.d.ts +17 -1
  28. package/dist/payments.d.ts.map +1 -1
  29. package/dist/payments.js +2 -10
  30. package/dist/payments.js.map +1 -1
  31. package/dist/plans.d.ts +1 -1
  32. package/dist/plans.js +6 -6
  33. package/dist/plans.js.map +1 -1
  34. package/dist/x402/delegation-api.d.ts +34 -7
  35. package/dist/x402/delegation-api.d.ts.map +1 -1
  36. package/dist/x402/delegation-api.js +15 -3
  37. package/dist/x402/delegation-api.js.map +1 -1
  38. package/dist/x402/facilitator-api.d.ts +5 -6
  39. package/dist/x402/facilitator-api.d.ts.map +1 -1
  40. package/dist/x402/facilitator-api.js +17 -5
  41. package/dist/x402/facilitator-api.js.map +1 -1
  42. package/dist/x402/index.d.ts +2 -6
  43. package/dist/x402/index.d.ts.map +1 -1
  44. package/dist/x402/index.js +1 -4
  45. package/dist/x402/index.js.map +1 -1
  46. package/package.json +23 -21
  47. package/dist/x402/visa-facilitator-api.d.ts +0 -150
  48. package/dist/x402/visa-facilitator-api.d.ts.map +0 -1
  49. package/dist/x402/visa-facilitator-api.js +0 -206
  50. package/dist/x402/visa-facilitator-api.js.map +0 -1
  51. package/dist/x402/visa-token-api.d.ts +0 -60
  52. package/dist/x402/visa-token-api.d.ts.map +0 -1
  53. package/dist/x402/visa-token-api.js +0 -99
  54. package/dist/x402/visa-token-api.js.map +0 -1
package/dist/plans.js CHANGED
@@ -72,7 +72,7 @@ export const getExpirableDurationConfig = (durationOfPlan) => {
72
72
  return {
73
73
  isRedemptionAmountFixed: false,
74
74
  redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,
75
- proofRequired: false,
75
+ onchainMirror: false,
76
76
  durationSecs: durationOfPlan,
77
77
  amount: 1n,
78
78
  minAmount: 1n,
@@ -86,7 +86,7 @@ export const getFixedCreditsConfig = (creditsGranted, creditsPerRequest = 1n) =>
86
86
  return {
87
87
  isRedemptionAmountFixed: true,
88
88
  redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,
89
- proofRequired: false,
89
+ onchainMirror: false,
90
90
  durationSecs: 0n,
91
91
  amount: creditsGranted,
92
92
  minAmount: creditsPerRequest,
@@ -97,7 +97,7 @@ export const getDynamicCreditsConfig = (creditsGranted, minCreditsPerRequest = 1
97
97
  return {
98
98
  isRedemptionAmountFixed: false,
99
99
  redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,
100
- proofRequired: false,
100
+ onchainMirror: false,
101
101
  durationSecs: 0n,
102
102
  amount: creditsGranted,
103
103
  minAmount: minCreditsPerRequest,
@@ -110,10 +110,10 @@ export const setRedemptionType = (creditsConfig, redemptionType) => {
110
110
  redemptionType,
111
111
  };
112
112
  };
113
- export const setProofRequired = (creditsConfig, proofRequired = true) => {
113
+ export const setOnchainMirror = (creditsConfig, onchainMirror = true) => {
114
114
  return {
115
115
  ...creditsConfig,
116
- proofRequired,
116
+ onchainMirror,
117
117
  };
118
118
  };
119
119
  /**
@@ -147,7 +147,7 @@ export const getPayAsYouGoCreditsConfig = () => {
147
147
  return {
148
148
  isRedemptionAmountFixed: false,
149
149
  redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,
150
- proofRequired: false,
150
+ onchainMirror: false,
151
151
  durationSecs: 0n,
152
152
  amount: 1n,
153
153
  minAmount: 1n,
package/dist/plans.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plans.js","sourceRoot":"","sources":["../src/plans.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,QAAQ,EACR,kBAAkB,EAGlB,kBAAkB,GACnB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAE9C,MAAM,CAAC,MAAM,gBAAgB,GAAG,MAAO,CAAA,CAAC,uBAAuB;AAC/D,MAAM,CAAC,MAAM,iBAAiB,GAAG,OAAQ,CAAA,CAAC,2BAA2B;AACrE,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAU,CAAA,CAAC,yEAAyE;AACtH,MAAM,CAAC,MAAM,iBAAiB,GAAG,SAAW,CAAA,CAAC,gCAAgC;AAE7E,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAChC,MAAc,EACd,QAAiB,EACjB,WAA8B,QAAQ,CAAC,GAAG,EACzB,EAAE;IACnB,IAAI,CAAC,iBAAiB,CAAC,QAAQ,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,kCAAkC,CAAC,CAAA;IACjF,OAAO;QACL,YAAY,EAAE,WAAW;QACzB,OAAO,EAAE,CAAC,MAAM,CAAC;QACjB,SAA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AAE,EAAE;QACb,SAAS,EAAE,EAAE;KACd,CAAA;AACH,CAAC,CAAA","sourcesContent":["import {\n Address,\n Currency,\n EURC_TOKEN_ADDRESS,\n PlanCreditsConfig,\n PlanPriceConfig,\n PlanRedemptionType,\n} from './common/types.js'\nimport { ZeroAddress } from './environments.js'\nimport { isEthereumAddress } from './utils.js'\n\nexport const ONE_DAY_DURATION = 86_400n // 24 * 60 * 60 seconds\nexport const ONE_WEEK_DURATION = 604_800n // 7 * 24 * 60 * 60 seconds\nexport const ONE_MONTH_DURATION = 2_629_746n // (365.25 days/year ÷ 12 months/year) × 24 × 60 × 60 ≈ 2,629,746 seconds\nexport const ONE_YEAR_DURATION = 31_557_600n // 365.25 * 24 * 60 * 60 seconds\n\nexport const getFiatPriceConfig = (\n amount: bigint,\n receiver: Address,\n currency: Currency | string = Currency.USD,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress: ZeroAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: false,\n currency,\n }\n}\n\nexport const getCryptoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getERC20PriceConfig = (\n amount: bigint,\n tokenAddress: Address,\n receiver: Address,\n): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, tokenAddress)\n}\n\n/**\n * Builds a price configuration for EURC (Euro stablecoin) payments.\n *\n * EURC uses 6 decimal places. To charge €29.00, pass `29_000_000n`.\n *\n * @param amount - Amount in the token's smallest unit (6 decimals for EURC).\n * @param receiver - Wallet address that will receive the payment.\n * @param eurcAddress - Optional EURC token address. Defaults to Base Mainnet EURC.\n * @returns The PlanPriceConfig representing an EURC price.\n */\nexport const getEURCPriceConfig = (\n amount: bigint,\n receiver: Address,\n eurcAddress: Address = EURC_TOKEN_ADDRESS,\n): PlanPriceConfig => {\n return {\n ...getERC20PriceConfig(amount, eurcAddress, receiver),\n currency: Currency.EURC,\n }\n}\n\nexport const getFreePriceConfig = (): PlanPriceConfig => {\n return {\n tokenAddress: ZeroAddress,\n amounts: [],\n receivers: [],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getNativeTokenPriceConfig = (amount: bigint, receiver: Address): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, ZeroAddress)\n}\n\nexport const getExpirableDurationConfig = (durationOfPlan: bigint): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: durationOfPlan,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n\nexport const getNonExpirableDurationConfig = (): PlanCreditsConfig => {\n return getExpirableDurationConfig(0n)\n}\n\nexport const getFixedCreditsConfig = (\n creditsGranted: bigint,\n creditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: true,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: creditsPerRequest,\n maxAmount: creditsPerRequest,\n }\n}\n\nexport const getDynamicCreditsConfig = (\n creditsGranted: bigint,\n minCreditsPerRequest = 1n,\n maxCreditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: minCreditsPerRequest,\n maxAmount: maxCreditsPerRequest,\n }\n}\n\nexport const setRedemptionType = (\n creditsConfig: PlanCreditsConfig,\n redemptionType: PlanRedemptionType,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n redemptionType,\n }\n}\n\nexport const setProofRequired = (\n creditsConfig: PlanCreditsConfig,\n proofRequired = true,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n proofRequired,\n }\n}\n\n/**\n * Build a pay-as-you-go price configuration.\n *\n * For pay-as-you-go plans, the template address must come from the API deployment info.\n */\nexport const getPayAsYouGoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n templateAddress?: Address,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n\n if (!templateAddress) {\n throw new Error(\n 'templateAddress is required. Use ContractsAPI.getPayAsYouGoTemplateAddress() or Payments.plans.getPayAsYouGoPriceConfig()',\n )\n }\n\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress,\n isCrypto: true,\n }\n}\n\n/**\n * Build a pay-as-you-go credits configuration.\n *\n * Credits are not minted upfront; these values are required for validation only.\n */\nexport const getPayAsYouGoCreditsConfig = (): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n proofRequired: false,\n durationSecs: 0n,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n"]}
1
+ {"version":3,"file":"plans.js","sourceRoot":"","sources":["../src/plans.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,QAAQ,EACR,kBAAkB,EAGlB,kBAAkB,GACnB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,WAAW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AC,QAAQ,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,QAAQ,kCAAkC,CAAC,CAAA;IAEjF,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CACb,2HAA2H,CAC5H,CAAA;IACH,CAAC;IAED,OAAO;QACL,YAAY;QACZ,OAAO,EAAE,CAAC,MAAM,CAAC;QACjB,SAAS,EAAE,CAAC,QAAQ,CAAC;QACrB,eAAe,EAAE,WAAW;QAC5B,aAAa,EAAE,WAAW;QAC1B,oBAAoB,EAAE,WAAW;QACjC,eAAe;QACf,QAAQ,EAAE,IAAI;KACf,CAAA;AACH,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,GAAsB,EAAE;IAChE,OAAO;QACL,uBAAuB,EAAE,KAAK;QAC9B,cAAc,EAAE,kBAAkB,CAAC,eAAe;QAClD,aAAa,EAAE,KAAK;QACpB,YAAY,EAAE,EAAE;QAChB,MAAM,EAAE,EAAE;QACV,SAAS,EAAE,EAAE;QACb,SAAS,EAAE,EAAE;KACd,CAAA;AACH,CAAC,CAAA","sourcesContent":["import {\n Address,\n Currency,\n EURC_TOKEN_ADDRESS,\n PlanCreditsConfig,\n PlanPriceConfig,\n PlanRedemptionType,\n} from './common/types.js'\nimport { ZeroAddress } from './environments.js'\nimport { isEthereumAddress } from './utils.js'\n\nexport const ONE_DAY_DURATION = 86_400n // 24 * 60 * 60 seconds\nexport const ONE_WEEK_DURATION = 604_800n // 7 * 24 * 60 * 60 seconds\nexport const ONE_MONTH_DURATION = 2_629_746n // (365.25 days/year ÷ 12 months/year) × 24 × 60 × 60 ≈ 2,629,746 seconds\nexport const ONE_YEAR_DURATION = 31_557_600n // 365.25 * 24 * 60 * 60 seconds\n\nexport const getFiatPriceConfig = (\n amount: bigint,\n receiver: Address,\n currency: Currency | string = Currency.USD,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress: ZeroAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: false,\n currency,\n }\n}\n\nexport const getCryptoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getERC20PriceConfig = (\n amount: bigint,\n tokenAddress: Address,\n receiver: Address,\n): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, tokenAddress)\n}\n\n/**\n * Builds a price configuration for EURC (Euro stablecoin) payments.\n *\n * EURC uses 6 decimal places. To charge €29.00, pass `29_000_000n`.\n *\n * @param amount - Amount in the token's smallest unit (6 decimals for EURC).\n * @param receiver - Wallet address that will receive the payment.\n * @param eurcAddress - Optional EURC token address. Defaults to Base Mainnet EURC.\n * @returns The PlanPriceConfig representing an EURC price.\n */\nexport const getEURCPriceConfig = (\n amount: bigint,\n receiver: Address,\n eurcAddress: Address = EURC_TOKEN_ADDRESS,\n): PlanPriceConfig => {\n return {\n ...getERC20PriceConfig(amount, eurcAddress, receiver),\n currency: Currency.EURC,\n }\n}\n\nexport const getFreePriceConfig = (): PlanPriceConfig => {\n return {\n tokenAddress: ZeroAddress,\n amounts: [],\n receivers: [],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress: ZeroAddress,\n isCrypto: true,\n }\n}\n\nexport const getNativeTokenPriceConfig = (amount: bigint, receiver: Address): PlanPriceConfig => {\n return getCryptoPriceConfig(amount, receiver, ZeroAddress)\n}\n\nexport const getExpirableDurationConfig = (durationOfPlan: bigint): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n onchainMirror: false,\n durationSecs: durationOfPlan,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n\nexport const getNonExpirableDurationConfig = (): PlanCreditsConfig => {\n return getExpirableDurationConfig(0n)\n}\n\nexport const getFixedCreditsConfig = (\n creditsGranted: bigint,\n creditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: true,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n onchainMirror: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: creditsPerRequest,\n maxAmount: creditsPerRequest,\n }\n}\n\nexport const getDynamicCreditsConfig = (\n creditsGranted: bigint,\n minCreditsPerRequest = 1n,\n maxCreditsPerRequest = 1n,\n): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n onchainMirror: false,\n durationSecs: 0n,\n amount: creditsGranted,\n minAmount: minCreditsPerRequest,\n maxAmount: maxCreditsPerRequest,\n }\n}\n\nexport const setRedemptionType = (\n creditsConfig: PlanCreditsConfig,\n redemptionType: PlanRedemptionType,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n redemptionType,\n }\n}\n\nexport const setOnchainMirror = (\n creditsConfig: PlanCreditsConfig,\n onchainMirror = true,\n): PlanCreditsConfig => {\n return {\n ...creditsConfig,\n onchainMirror,\n }\n}\n\n/**\n * Build a pay-as-you-go price configuration.\n *\n * For pay-as-you-go plans, the template address must come from the API deployment info.\n */\nexport const getPayAsYouGoPriceConfig = (\n amount: bigint,\n receiver: Address,\n tokenAddress: Address = ZeroAddress,\n templateAddress?: Address,\n): PlanPriceConfig => {\n if (!isEthereumAddress(receiver))\n throw new Error(`Receiver address ${receiver} is not a valid Ethereum address`)\n\n if (!templateAddress) {\n throw new Error(\n 'templateAddress is required. Use ContractsAPI.getPayAsYouGoTemplateAddress() or Payments.plans.getPayAsYouGoPriceConfig()',\n )\n }\n\n return {\n tokenAddress,\n amounts: [amount],\n receivers: [receiver],\n contractAddress: ZeroAddress,\n feeController: ZeroAddress,\n externalPriceAddress: ZeroAddress,\n templateAddress,\n isCrypto: true,\n }\n}\n\n/**\n * Build a pay-as-you-go credits configuration.\n *\n * Credits are not minted upfront; these values are required for validation only.\n */\nexport const getPayAsYouGoCreditsConfig = (): PlanCreditsConfig => {\n return {\n isRedemptionAmountFixed: false,\n redemptionType: PlanRedemptionType.ONLY_SUBSCRIBER,\n onchainMirror: false,\n durationSecs: 0n,\n amount: 1n,\n minAmount: 1n,\n maxAmount: 1n,\n }\n}\n"]}
@@ -6,17 +6,38 @@
6
6
  */
7
7
  import { BasePaymentsAPI } from '../api/base-payments.js';
8
8
  import { CreateDelegationPayload, CreateDelegationResponse, PaymentOptions } from '../common/types.js';
9
+ /**
10
+ * Card-delegation providers exposed by the SDK. Use this when you want to
11
+ * restrict to card-shape entries only (e.g., filtering the heterogeneous
12
+ * list returned by {@link DelegationAPI.listPaymentMethods}).
13
+ */
14
+ export type CardProvider = 'stripe' | 'braintree' | 'visa';
15
+ /**
16
+ * All delegation providers, including the crypto path. Matches the
17
+ * server-side union and aligns with {@link CreateDelegationPayload.provider}.
18
+ */
19
+ export type DelegationProvider = CardProvider | 'erc4337';
9
20
  /**
10
21
  * Summary of a user's enrolled payment method.
22
+ *
23
+ * The list returned by {@link DelegationAPI.listPaymentMethods} is
24
+ * heterogeneous: it includes enrolled cards (`provider` in
25
+ * `stripe` / `braintree` / `visa`) AND, when the user has a smart account
26
+ * configured, an entry for the user's ERC-4337 wallet
27
+ * (`provider: 'erc4337'`, `type: 'crypto_wallet'`, `brand: 'ethereum'`).
28
+ * Filter on `provider` when callers only want one shape.
11
29
  */
12
30
  export interface PaymentMethodSummary {
13
- /** Payment method ID (Stripe 'pm_...' or Braintree vault token) */
31
+ /** Payment method ID (Stripe 'pm_...', Braintree vault token, Visa Agentic
32
+ * token id, or — for the erc4337 entry — the smart-account address) */
14
33
  id: string;
15
- /** Payment method type (e.g., 'card', 'paypal') */
34
+ /** Payment method type ('card' | 'crypto_wallet' | 'paypal' | …) */
16
35
  type: string;
17
- /** Card brand (e.g., 'visa', 'mastercard') or payment method type ('paypal', 'venmo') */
36
+ /** Card brand (e.g., 'visa', 'mastercard'), 'ethereum' for the erc4337
37
+ * entry, or payment method type ('paypal', 'venmo') */
18
38
  brand: string;
19
- /** Last 4 digits (cards) or email/username (PayPal/Venmo) */
39
+ /** Last 4 digits (cards), trailing 4 chars of the wallet address
40
+ * (erc4337), or email/username (PayPal/Venmo) */
20
41
  last4: string;
21
42
  /** Expiration month (0 for non-card methods) */
22
43
  expMonth: number;
@@ -24,8 +45,8 @@ export interface PaymentMethodSummary {
24
45
  expYear: number;
25
46
  /** Human-readable alias, if set */
26
47
  alias?: string | null;
27
- /** Payment provider: 'stripe' or 'braintree' */
28
- provider?: string;
48
+ /** One of 'stripe' | 'braintree' | 'visa' | 'erc4337' */
49
+ provider?: DelegationProvider;
29
50
  /** Current status ('Active' or 'Revoked') */
30
51
  status?: string;
31
52
  /** NVM API Key IDs allowed to use this payment method, or null if unrestricted */
@@ -101,7 +122,13 @@ export declare class DelegationAPI extends BasePaymentsAPI {
101
122
  */
102
123
  getPurchasingPower(): Promise<PurchasingPower>;
103
124
  /**
104
- * Create a new delegation for either stripe or erc4337 provider.
125
+ * Create a new delegation for any supported provider (stripe, braintree,
126
+ * visa, or erc4337).
127
+ *
128
+ * Note: Visa delegations require a per-delegation device-binding ceremony
129
+ * (FIDO/passkey + assuranceData) that must be performed in the browser
130
+ * via the Nevermined webapp. The SDK can list and consume an already-
131
+ * created Visa delegation but cannot create one programmatically.
105
132
  *
106
133
  * @param payload - The delegation creation parameters
107
134
  * @returns The created delegation ID (and token for card delegations)
@@ -1 +1 @@
1
- {"version":3,"file":"delegation-api.d.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
53
53
  }
54
54
  /**
55
- * Create a new delegation for either stripe or erc4337 provider.
55
+ * Create a new delegation for any supported provider (stripe, braintree,
56
+ * visa, or erc4337).
57
+ *
58
+ * Note: Visa delegations require a per-delegation device-binding ceremony
59
+ * (FIDO/passkey + assuranceData) that must be performed in the browser
60
+ * via the Nevermined webapp. The SDK can list and consume an already-
61
+ * created Visa delegation but cannot create one programmatically.
56
62
  *
57
63
  * @param payload - The delegation creation parameters
58
64
  * @returns The created delegation ID (and token for card delegations)
@@ -75,14 +81,20 @@ export class DelegationAPI extends BasePaymentsAPI {
75
81
  const response = await fetch(url, options);
76
82
  if (!response.ok) {
77
83
  let msg = `Failed to ${action}`;
84
+ let code = `http_${response.status}`;
78
85
  try {
79
86
  const err = await response.json();
80
- msg = err.message || msg;
87
+ if (err.message)
88
+ msg = err.message;
89
+ if (err.code)
90
+ code = err.code;
91
+ if (err.hint)
92
+ msg = `${msg} — ${err.hint}`;
81
93
  }
82
94
  catch {
83
95
  // use default
84
96
  }
85
- throw PaymentsError.internal(`${msg} (HTTP ${response.status})`);
97
+ throw new PaymentsError(`${msg} (HTTP ${response.status})`, code);
86
98
  }
87
99
  return await response.json();
88
100
  }
@@ -1 +1 @@
1
- {"version":3,"file":"delegation-api.js","sourceRoot":"","sources":["../../src/x402/delegation-api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AAmF3D;;GAEG;AACH,MAAM,OAAO,aAAc,SAAQ,eAAe;IAChD,MAAM,CAAC,WAAW,CAAC,OAAuB;QACxC,OAAO,IAAI,aAAa,CAAC,OAAO,CAAC,CAAA;IACnC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,kBAAkB,CAAC,OAAqB;QAC5C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,yBAAyB,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO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,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,aAAa;gBAAE,MAAM,KAAK,CAAA;YAC/C,MAAM,aAAa,CAAC,QAAQ,CAC1B,uBAAuB,MAAM,KAAK,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC3F,CAAA;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Delegation API for managing payment delegations (crypto and card schemes).\n *\n * Provides access to the user's enrolled payment methods and delegations\n * for use with the nvm:erc4337 and nvm:card-delegation x402 schemes.\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport { CreateDelegationPayload, CreateDelegationResponse, PaymentOptions } from '../common/types.js'\n\n/**\n * Summary of a user's enrolled payment method.\n */\nexport interface PaymentMethodSummary {\n /** Payment method ID (Stripe 'pm_...' or Braintree vault token) */\n id: string\n /** Payment method type (e.g., 'card', 'paypal') */\n type: string\n /** Card brand (e.g., 'visa', 'mastercard') or payment method type ('paypal', 'venmo') */\n brand: string\n /** Last 4 digits (cards) or email/username (PayPal/Venmo) */\n last4: string\n /** Expiration month (0 for non-card methods) */\n expMonth: number\n /** Expiration year (0 for non-card methods) */\n expYear: number\n /** Human-readable alias, if set */\n alias?: string | null\n /** Payment provider: 'stripe' or 'braintree' */\n provider?: string\n /** Current status ('Active' or 'Revoked') */\n status?: string\n /** NVM API Key IDs allowed to use this payment method, or null if unrestricted */\n allowedApiKeyIds?: string[] | null\n}\n\n/**\n * Summary of a delegation (card or crypto spending).\n */\nexport interface DelegationSummary {\n delegationId: string\n provider: string\n providerPaymentMethodId: string\n status: string\n spendingLimitCents: string\n amountSpentCents: string\n remainingBudgetCents: string\n currency: string\n transactionCount: number\n expiresAt: string\n createdAt: string\n apiKeyId: string | null\n}\n\n/**\n * Paginated list of delegations returned by the API.\n */\nexport interface DelegationListResponse {\n delegations: DelegationSummary[]\n totalResults: number\n page: number\n offset: number\n}\n\n/**\n * Summary of an agent's purchasing power via card delegations.\n */\nexport interface PurchasingPower {\n cards: PaymentMethodSummary[]\n delegations: DelegationSummary[]\n totalRemainingBudgetCents: number\n currency: string\n}\n\n/**\n * DTO for updating a payment method's alias and allowed API keys.\n */\nexport interface UpdatePaymentMethodDto {\n alias?: string\n allowedApiKeyIds?: string[] | null\n}\n\n/**\n * Options for listing payment methods or delegations.\n */\nexport interface ListOptions {\n /** When true, return only items accessible to the requesting API key */\n accessible?: boolean\n}\n\n/**\n * API for managing payment methods and delegations (card and crypto).\n */\nexport class DelegationAPI extends BasePaymentsAPI {\n static getInstance(options: PaymentOptions): DelegationAPI {\n return new DelegationAPI(options)\n }\n\n /**\n * List the user's enrolled payment methods for card delegation.\n * When `accessible: true`, only cards accessible to the requesting API key are returned.\n */\n async listPaymentMethods(options?: ListOptions): Promise<PaymentMethodSummary[]> {\n const url = new URL('/api/v1/payment-methods', this.environment.backend)\n if (options?.accessible) url.searchParams.set('accessible', 'true')\n return this.fetchJSON(url, 'GET', 'list payment methods')\n }\n\n /**\n * List the user's existing delegations.\n * When `accessible: true`, only usable delegations (Active, non-expired, with budget) are returned.\n */\n async listDelegations(options?: ListOptions): Promise<DelegationListResponse> {\n const url = new URL('/api/v1/delegation', this.environment.backend)\n if (options?.accessible) url.searchParams.set('accessible', 'true')\n return this.fetchJSON(url, 'GET', 'list delegations')\n }\n\n /**\n * Get the agent's purchasing power — accessible cards, active delegations,\n * and combined remaining budget.\n */\n async getPurchasingPower(): Promise<PurchasingPower> {\n const accessible = { accessible: true } satisfies ListOptions\n const [cards, { delegations }] = await Promise.all([\n this.listPaymentMethods(accessible),\n this.listDelegations(accessible),\n ])\n\n const totalRemainingBudgetCents = delegations.reduce(\n (sum, d) => sum + (parseInt(d.remainingBudgetCents, 10) || 0),\n 0,\n )\n\n return {\n cards,\n delegations,\n totalRemainingBudgetCents,\n currency: delegations[0]?.currency ?? 'usd',\n }\n }\n\n /**\n * Create a new delegation for either stripe or erc4337 provider.\n *\n * @param payload - The delegation creation parameters\n * @returns The created delegation ID (and token for card delegations)\n */\n async createDelegation(payload: CreateDelegationPayload): Promise<CreateDelegationResponse> {\n const url = new URL('/api/v1/delegation/create', this.environment.backend)\n return this.fetchJSON(url, 'POST', 'create delegation', payload)\n }\n\n /**\n * Update a payment method's alias and/or allowed API keys.\n */\n async updatePaymentMethod(\n paymentMethodId: string,\n dto: UpdatePaymentMethodDto,\n ): Promise<PaymentMethodSummary> {\n const url = new URL(`/api/v1/payment-methods/${paymentMethodId}`, this.environment.backend)\n return this.fetchJSON(url, 'PATCH', 'update payment method', dto)\n }\n\n // --- Private helpers ---\n\n private async fetchJSON<T>(\n url: URL,\n method: string,\n action: string,\n body?: unknown,\n ): Promise<T> {\n const options = this.getBackendHTTPOptions(method, body)\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let msg = `Failed to ${action}`\n try {\n const err = await response.json()\n msg = err.message || msg\n } catch {\n // use default\n }\n throw PaymentsError.internal(`${msg} (HTTP ${response.status})`)\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) throw error\n throw PaymentsError.internal(\n `Network error while ${action}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n"]}
1
+ {"version":3,"file":"delegation-api.js","sourceRoot":"","sources":["../../src/x402/delegation-api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AA8G3D;;GAEG;AACH,MAAM,OAAO,aAAc,SAAQ,eAAe;IAChD,MAAM,CAAC,WAAW,CAAC,OAAuB;QACxC,OAAO,IAAI,aAAa,CAAC,OAAO,CAAC,CAAA;IACnC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,kBAAkB,CAAC,OAAqB;QAC5C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,yBAAyB,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,GAAG,GAAG,GAAG,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAA;gBAC5C,CAAC;gBAAC,MAAM,CAAC;oBACP,cAAc;gBAChB,CAAC;gBACD,MAAM,IAAI,aAAa,CAAC,GAAG,GAAG,UAAU,QAAQ,CAAC,MAAM,GAAG,EAAE,IAAI,CAAC,CAAA;YACnE,CAAC;YACD,OAAO,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,aAAa;gBAAE,MAAM,KAAK,CAAA;YAC/C,MAAM,aAAa,CAAC,QAAQ,CAC1B,uBAAuB,MAAM,KAAK,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAC3F,CAAA;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Delegation API for managing payment delegations (crypto and card schemes).\n *\n * Provides access to the user's enrolled payment methods and delegations\n * for use with the nvm:erc4337 and nvm:card-delegation x402 schemes.\n */\n\nimport { BasePaymentsAPI } from '../api/base-payments.js'\nimport { PaymentsError } from '../common/payments.error.js'\nimport {\n CreateDelegationPayload,\n CreateDelegationResponse,\n PaymentOptions,\n} from '../common/types.js'\n\n/**\n * Card-delegation providers exposed by the SDK. Use this when you want to\n * restrict to card-shape entries only (e.g., filtering the heterogeneous\n * list returned by {@link DelegationAPI.listPaymentMethods}).\n */\nexport type CardProvider = 'stripe' | 'braintree' | 'visa'\n\n/**\n * All delegation providers, including the crypto path. Matches the\n * server-side union and aligns with {@link CreateDelegationPayload.provider}.\n */\nexport type DelegationProvider = CardProvider | 'erc4337'\n\n/**\n * Summary of a user's enrolled payment method.\n *\n * The list returned by {@link DelegationAPI.listPaymentMethods} is\n * heterogeneous: it includes enrolled cards (`provider` in\n * `stripe` / `braintree` / `visa`) AND, when the user has a smart account\n * configured, an entry for the user's ERC-4337 wallet\n * (`provider: 'erc4337'`, `type: 'crypto_wallet'`, `brand: 'ethereum'`).\n * Filter on `provider` when callers only want one shape.\n */\nexport interface PaymentMethodSummary {\n /** Payment method ID (Stripe 'pm_...', Braintree vault token, Visa Agentic\n * token id, or — for the erc4337 entry — the smart-account address) */\n id: string\n /** Payment method type ('card' | 'crypto_wallet' | 'paypal' | …) */\n type: string\n /** Card brand (e.g., 'visa', 'mastercard'), 'ethereum' for the erc4337\n * entry, or payment method type ('paypal', 'venmo') */\n brand: string\n /** Last 4 digits (cards), trailing 4 chars of the wallet address\n * (erc4337), or email/username (PayPal/Venmo) */\n last4: string\n /** Expiration month (0 for non-card methods) */\n expMonth: number\n /** Expiration year (0 for non-card methods) */\n expYear: number\n /** Human-readable alias, if set */\n alias?: string | null\n /** One of 'stripe' | 'braintree' | 'visa' | 'erc4337' */\n provider?: DelegationProvider\n /** Current status ('Active' or 'Revoked') */\n status?: string\n /** NVM API Key IDs allowed to use this payment method, or null if unrestricted */\n allowedApiKeyIds?: string[] | null\n}\n\n/**\n * Summary of a delegation (card or crypto spending).\n */\nexport interface DelegationSummary {\n delegationId: string\n provider: string\n providerPaymentMethodId: string\n status: string\n spendingLimitCents: string\n amountSpentCents: string\n remainingBudgetCents: string\n currency: string\n transactionCount: number\n expiresAt: string\n createdAt: string\n apiKeyId: string | null\n}\n\n/**\n * Paginated list of delegations returned by the API.\n */\nexport interface DelegationListResponse {\n delegations: DelegationSummary[]\n totalResults: number\n page: number\n offset: number\n}\n\n/**\n * Summary of an agent's purchasing power via card delegations.\n */\nexport interface PurchasingPower {\n cards: PaymentMethodSummary[]\n delegations: DelegationSummary[]\n totalRemainingBudgetCents: number\n currency: string\n}\n\n/**\n * DTO for updating a payment method's alias and allowed API keys.\n */\nexport interface UpdatePaymentMethodDto {\n alias?: string\n allowedApiKeyIds?: string[] | null\n}\n\n/**\n * Options for listing payment methods or delegations.\n */\nexport interface ListOptions {\n /** When true, return only items accessible to the requesting API key */\n accessible?: boolean\n}\n\n/**\n * API for managing payment methods and delegations (card and crypto).\n */\nexport class DelegationAPI extends BasePaymentsAPI {\n static getInstance(options: PaymentOptions): DelegationAPI {\n return new DelegationAPI(options)\n }\n\n /**\n * List the user's enrolled payment methods for card delegation.\n * When `accessible: true`, only cards accessible to the requesting API key are returned.\n */\n async listPaymentMethods(options?: ListOptions): Promise<PaymentMethodSummary[]> {\n const url = new URL('/api/v1/payment-methods', this.environment.backend)\n if (options?.accessible) url.searchParams.set('accessible', 'true')\n return this.fetchJSON(url, 'GET', 'list payment methods')\n }\n\n /**\n * List the user's existing delegations.\n * When `accessible: true`, only usable delegations (Active, non-expired, with budget) are returned.\n */\n async listDelegations(options?: ListOptions): Promise<DelegationListResponse> {\n const url = new URL('/api/v1/delegation', this.environment.backend)\n if (options?.accessible) url.searchParams.set('accessible', 'true')\n return this.fetchJSON(url, 'GET', 'list delegations')\n }\n\n /**\n * Get the agent's purchasing power — accessible cards, active delegations,\n * and combined remaining budget.\n */\n async getPurchasingPower(): Promise<PurchasingPower> {\n const accessible = { accessible: true } satisfies ListOptions\n const [cards, { delegations }] = await Promise.all([\n this.listPaymentMethods(accessible),\n this.listDelegations(accessible),\n ])\n\n const totalRemainingBudgetCents = delegations.reduce(\n (sum, d) => sum + (parseInt(d.remainingBudgetCents, 10) || 0),\n 0,\n )\n\n return {\n cards,\n delegations,\n totalRemainingBudgetCents,\n currency: delegations[0]?.currency ?? 'usd',\n }\n }\n\n /**\n * Create a new delegation for any supported provider (stripe, braintree,\n * visa, or erc4337).\n *\n * Note: Visa delegations require a per-delegation device-binding ceremony\n * (FIDO/passkey + assuranceData) that must be performed in the browser\n * via the Nevermined webapp. The SDK can list and consume an already-\n * created Visa delegation but cannot create one programmatically.\n *\n * @param payload - The delegation creation parameters\n * @returns The created delegation ID (and token for card delegations)\n */\n async createDelegation(payload: CreateDelegationPayload): Promise<CreateDelegationResponse> {\n const url = new URL('/api/v1/delegation/create', this.environment.backend)\n return this.fetchJSON(url, 'POST', 'create delegation', payload)\n }\n\n /**\n * Update a payment method's alias and/or allowed API keys.\n */\n async updatePaymentMethod(\n paymentMethodId: string,\n dto: UpdatePaymentMethodDto,\n ): Promise<PaymentMethodSummary> {\n const url = new URL(`/api/v1/payment-methods/${paymentMethodId}`, this.environment.backend)\n return this.fetchJSON(url, 'PATCH', 'update payment method', dto)\n }\n\n // --- Private helpers ---\n\n private async fetchJSON<T>(url: URL, method: string, action: string, body?: unknown): Promise<T> {\n const options = this.getBackendHTTPOptions(method, body)\n try {\n const response = await fetch(url, options)\n if (!response.ok) {\n let msg = `Failed to ${action}`\n let code = `http_${response.status}`\n try {\n const err = await response.json()\n if (err.message) msg = err.message\n if (err.code) code = err.code\n if (err.hint) msg = `${msg} — ${err.hint}`\n } catch {\n // use default\n }\n throw new PaymentsError(`${msg} (HTTP ${response.status})`, code)\n }\n return await response.json()\n } catch (error) {\n if (error instanceof PaymentsError) throw error\n throw PaymentsError.internal(\n `Network error while ${action}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n}\n"]}
@@ -44,7 +44,6 @@ import { BasePaymentsAPI } from '../api/base-payments.js';
44
44
  import { PaymentOptions, StartAgentRequest, X402SchemeType } from '../common/types.js';
45
45
  import type { EnvironmentName } from '../environments.js';
46
46
  import type { Payments } from '../payments.js';
47
- import type { VisaPaymentRequired } from './visa-facilitator-api.js';
48
47
  /**
49
48
  * x402 Resource information
50
49
  */
@@ -118,8 +117,8 @@ export interface X402PaymentAccepted {
118
117
  * Parameters for verifying permissions
119
118
  */
120
119
  export interface VerifyPermissionsParams {
121
- /** The server's 402 PaymentRequired response (NVM or Visa flavored) */
122
- paymentRequired: X402PaymentRequired | VisaPaymentRequired;
120
+ /** The server's 402 PaymentRequired response */
121
+ paymentRequired: X402PaymentRequired;
123
122
  /** The X402 access token (base64-encoded) */
124
123
  x402AccessToken: string;
125
124
  /** Maximum credits to verify (optional) */
@@ -136,7 +135,7 @@ export interface VerifyPermissionsResult {
136
135
  invalidReason?: string;
137
136
  /** Address of the payer's wallet */
138
137
  payer?: string;
139
- /** Network identifier (e.g., 'stripe', 'braintree', 'eip155:84532') */
138
+ /** Network identifier (e.g., 'stripe', 'braintree', 'visa', 'eip155:84532') */
140
139
  network?: string;
141
140
  /** Agent request ID for observability tracking (Nevermined extension) */
142
141
  agentRequestId?: string;
@@ -149,8 +148,8 @@ export interface VerifyPermissionsResult {
149
148
  * Parameters for settling permissions
150
149
  */
151
150
  export interface SettlePermissionsParams {
152
- /** The server's 402 PaymentRequired response (NVM or Visa flavored) */
153
- paymentRequired: X402PaymentRequired | VisaPaymentRequired;
151
+ /** The server's 402 PaymentRequired response */
152
+ paymentRequired: X402PaymentRequired;
154
153
  /** The X402 access token (base64-encoded) */
155
154
  x402AccessToken: string;
156
155
  /** Number of credits to burn (optional) */
@@ -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,EAAE,cAAc,EAAE,iBAAiB,EAAE,cAAc,EAAqB,MAAM,oBAAoB,CAAA;AACzG,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAC9C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAA;AAEpE;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,iCAAiC;IACjC,GAAG,EAAE,MAAM,CAAA;IACX,iCAAiC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,iCAAiC;IACjC,OAAO,CAAC,EAAE,MAA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AAM,CAAC,WAAW,CAAC,OAAO,EAAE,cAAc,GAAG,cAAc;IAI3D;;;;;;;;;;;;;;OAcG;IACG,iBAAiB,CAAC,MAAM,EAAE,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IA8C1F;;;;;;;;;;;;;;;;;;OAkBG;IACG,iBAAiB,CAAC,MAAM,EAAE,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC;CAuD3F"}
@@ -43,7 +43,7 @@
43
43
  import { BasePaymentsAPI } from '../api/base-payments.js';
44
44
  import { API_URL_SETTLE_PERMISSIONS, API_URL_VERIFY_PERMISSIONS } from '../api/nvm-api.js';
45
45
  import { PaymentsError } from '../common/payments.error.js';
46
- import { getDefaultNetwork } from '../common/types.js';
46
+ import { getDefaultNetwork, } from '../common/types.js';
47
47
  /**
48
48
  * Build an X402PaymentRequired object for verify/settle operations.
49
49
  *
@@ -191,16 +191,22 @@ export class FacilitatorAPI extends BasePaymentsAPI {
191
191
  const response = await fetch(url, options);
192
192
  if (!response.ok) {
193
193
  let errorMessage = 'Permission verification failed';
194
+ let errorCode = `http_${response.status}`;
194
195
  try {
195
196
  const errorData = await response.json();
196
- errorMessage = errorData.message || errorMessage;
197
+ if (errorData.message)
198
+ errorMessage = errorData.message;
199
+ if (errorData.code)
200
+ errorCode = errorData.code;
201
+ if (errorData.hint)
202
+ errorMessage = `${errorMessage} — ${errorData.hint}`;
197
203
  }
198
204
  catch {
199
205
  // Use default error message
200
206
  }
201
207
  throw PaymentsError.fromBackend(errorMessage, {
202
208
  message: errorMessage,
203
- code: `HTTP ${response.status}`,
209
+ code: errorCode,
204
210
  });
205
211
  }
206
212
  return await response.json();
@@ -258,16 +264,22 @@ export class FacilitatorAPI extends BasePaymentsAPI {
258
264
  const response = await fetch(url, options);
259
265
  if (!response.ok) {
260
266
  let errorMessage = 'Permission settlement failed';
267
+ let errorCode = `http_${response.status}`;
261
268
  try {
262
269
  const errorData = await response.json();
263
- errorMessage = errorData.message || errorMessage;
270
+ if (errorData.message)
271
+ errorMessage = errorData.message;
272
+ if (errorData.code)
273
+ errorCode = errorData.code;
274
+ if (errorData.hint)
275
+ errorMessage = `${errorMessage} — ${errorData.hint}`;
264
276
  }
265
277
  catch {
266
278
  // Use default error message
267
279
  }
268
280
  throw PaymentsError.fromBackend(errorMessage, {
269
281
  message: errorMessage,
270
- code: `HTTP ${response.status}`,
282
+ code: errorCode,
271
283
  });
272
284
  }
273
285
  return await response.json();
@@ -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;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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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 { 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"]}
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;AAwJ3B;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,UAAU,oBAAoB,CAClC,MAAc,EACd,OASC;IAED,MAAM,EACJ,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C,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 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 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 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 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"]}
@@ -2,14 +2,10 @@
2
2
  * X402 API module for token generation and facilitator operations.
3
3
  */
4
4
  export { X402TokenAPI } from './token.js';
5
- export { FacilitatorAPI, buildPaymentRequired, resolveNetwork, 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, UpdatePaymentMethodDto, DelegationSummary, DelegationListResponse, PurchasingPower, ListOptions, } from './delegation-api.js';
8
+ export type { CardProvider, DelegationProvider, PaymentMethodSummary, UpdatePaymentMethodDto, DelegationSummary, DelegationListResponse, PurchasingPower, ListOptions, } from './delegation-api.js';
9
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
- export { VisaFacilitatorAPI, buildVisaPaymentRequired, VISA_X402_HEADERS } from './visa-facilitator-api.js';
12
- export type { VisaPaymentExtra, VisaPaymentRequirements, VisaPaymentRequired, VisaVerifyResponse, VisaSettlementResponse, } from './visa-facilitator-api.js';
13
- export { VisaTokenAPI } from './visa-token-api.js';
14
- export type { VisaPaymentPayloadResponse } from './visa-token-api.js';
15
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,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"}
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"}
@@ -2,11 +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, resolveNetwork, resolveScheme } from './facilitator-api.js';
5
+ export { FacilitatorAPI, buildPaymentRequired, resolveNetwork, resolveScheme, } from './facilitator-api.js';
6
6
  // Delegation exports
7
7
  export { DelegationAPI } from './delegation-api.js';
8
8
  export { X402_SCHEME_NETWORKS, getDefaultNetwork, isValidScheme } from '../common/types.js';
9
- // Visa x402 exports
10
- export { VisaFacilitatorAPI, buildVisaPaymentRequired, VISA_X402_HEADERS } from './visa-facilitator-api.js';
11
- export { VisaTokenAPI } from './visa-token-api.js';
12
9
  //# sourceMappingURL=index.js.map
@@ -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,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"]}
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"]}