@nevermined-io/payments 1.3.2 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/api/agents-api.d.ts +4 -3
- package/dist/api/agents-api.d.ts.map +1 -1
- package/dist/api/agents-api.js +5 -5
- package/dist/api/agents-api.js.map +1 -1
- package/dist/api/base-payments.d.ts +49 -1
- package/dist/api/base-payments.d.ts.map +1 -1
- package/dist/api/base-payments.js +82 -16
- package/dist/api/base-payments.js.map +1 -1
- package/dist/api/nvm-api.d.ts +2 -1
- package/dist/api/nvm-api.d.ts.map +1 -1
- package/dist/api/nvm-api.js +2 -1
- package/dist/api/nvm-api.js.map +1 -1
- package/dist/api/organizations-api/organizations-api.d.ts +42 -1
- package/dist/api/organizations-api/organizations-api.d.ts.map +1 -1
- package/dist/api/organizations-api/organizations-api.js +91 -3
- package/dist/api/organizations-api/organizations-api.js.map +1 -1
- package/dist/api/organizations-api/types.d.ts +134 -0
- package/dist/api/organizations-api/types.d.ts.map +1 -1
- package/dist/api/organizations-api/types.js +52 -0
- package/dist/api/organizations-api/types.js.map +1 -1
- package/dist/api/plans-api.d.ts +15 -36
- package/dist/api/plans-api.d.ts.map +1 -1
- package/dist/api/plans-api.js +22 -57
- package/dist/api/plans-api.js.map +1 -1
- package/dist/common/types.d.ts +38 -15
- package/dist/common/types.d.ts.map +1 -1
- package/dist/common/types.js.map +1 -1
- package/dist/environments.d.ts +0 -7
- package/dist/environments.d.ts.map +1 -1
- package/dist/environments.js +0 -13
- package/dist/environments.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp/http/session-manager.d.ts.map +1 -1
- package/dist/mcp/http/session-manager.js +15 -1
- package/dist/mcp/http/session-manager.js.map +1 -1
- package/dist/payments.d.ts +26 -1
- package/dist/payments.d.ts.map +1 -1
- package/dist/payments.js +43 -11
- package/dist/payments.js.map +1 -1
- package/dist/plans.d.ts +1 -1
- package/dist/plans.js +6 -6
- package/dist/plans.js.map +1 -1
- package/dist/x402/delegation-api.d.ts +34 -7
- package/dist/x402/delegation-api.d.ts.map +1 -1
- package/dist/x402/delegation-api.js +15 -3
- package/dist/x402/delegation-api.js.map +1 -1
- package/dist/x402/facilitator-api.d.ts +5 -6
- package/dist/x402/facilitator-api.d.ts.map +1 -1
- package/dist/x402/facilitator-api.js +17 -5
- package/dist/x402/facilitator-api.js.map +1 -1
- package/dist/x402/index.d.ts +2 -6
- package/dist/x402/index.d.ts.map +1 -1
- package/dist/x402/index.js +1 -4
- package/dist/x402/index.js.map +1 -1
- package/package.json +23 -21
- package/dist/x402/visa-facilitator-api.d.ts +0 -150
- package/dist/x402/visa-facilitator-api.d.ts.map +0 -1
- package/dist/x402/visa-facilitator-api.js +0 -206
- package/dist/x402/visa-facilitator-api.js.map +0 -1
- package/dist/x402/visa-token-api.d.ts +0 -60
- package/dist/x402/visa-token-api.d.ts.map +0 -1
- package/dist/x402/visa-token-api.js +0 -99
- package/dist/x402/visa-token-api.js.map +0 -1
|
@@ -52,7 +52,13 @@ export class DelegationAPI extends BasePaymentsAPI {
|
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
54
|
/**
|
|
55
|
-
* Create a new delegation for
|
|
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
|
-
|
|
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
|
|
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,CAAC,CAAA;QACxE,IAAI,OAAO,EAAE,UAAU;YAAE,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,EAAE,MAAM,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,sBAAsB,CAAC,CAAA;IAC3D,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,eAAe,CAAC,OAAqB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,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,EAAE,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;QACxE,IAAI,OAAO,EAAE,UAAU;YAAE,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,EAAE,MAAM,CAAC,CAAA;QACnE,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,sBAAsB,CAAC,CAAA;IAC3D,CAAC;IAED;;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Q,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
|
|
122
|
-
paymentRequired: X402PaymentRequired
|
|
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
|
|
153
|
-
paymentRequired: X402PaymentRequired
|
|
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,
|
|
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,EACd,iBAAiB,EACjB,cAAc,EAEf,MAAM,oBAAoB,CAAA;AAC3B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAE9C;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,iCAAiC;IACjC,GAAG,EAAE,MAAM,CAAA;IACX,iCAAiC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,6DAA6D;I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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
|
-
|
|
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:
|
|
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
|
-
|
|
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:
|
|
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;YACR,GAAG,EAAE,QAAQ,IA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C;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,QAAQ,EACR,OAAO,EAC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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"]}
|
package/dist/x402/index.d.ts
CHANGED
|
@@ -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
|
package/dist/x402/index.d.ts.map
CHANGED
|
@@ -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,
|
|
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"}
|
package/dist/x402/index.js
CHANGED
|
@@ -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
|
package/dist/x402/index.js.map
CHANGED
|
@@ -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,
|
|
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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nevermined-io/payments",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.1",
|
|
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",
|
|
@@ -40,22 +40,22 @@
|
|
|
40
40
|
"scripts": {
|
|
41
41
|
"clean": "rm -rf ./dist/ ./doc/ ./.nyc_output",
|
|
42
42
|
"build": "tsc",
|
|
43
|
-
"build:all": "
|
|
43
|
+
"build:all": "pnpm build && pnpm cli:build",
|
|
44
44
|
"lint": "eslint ./src",
|
|
45
45
|
"test": "jest --verbose --config ./tests/jest.config.json",
|
|
46
46
|
"test:unit": "jest --verbose --config ./tests/jest.config.json --testPathPattern=tests/unit",
|
|
47
47
|
"test:integration": "jest --verbose --config ./tests/jest.config.json --testPathPattern=tests/integration",
|
|
48
|
-
"test:e2e": "jest --verbose --config ./tests/jest.config.
|
|
48
|
+
"test:e2e": "jest --verbose --config ./tests/jest.e2e.config.cjs --testPathPattern=tests/e2e --runInBand",
|
|
49
49
|
"format": "prettier --check ./src",
|
|
50
|
-
"prepublishOnly": "
|
|
50
|
+
"prepublishOnly": "pnpm build",
|
|
51
51
|
"doc": "typedoc --out docs ./src",
|
|
52
|
-
"cli:build": "cd cli &&
|
|
53
|
-
"cli:dev": "cd cli &&
|
|
54
|
-
"cli:test": "cd cli &&
|
|
55
|
-
"cli:install": "cd cli &&
|
|
52
|
+
"cli:build": "cd cli && pnpm build",
|
|
53
|
+
"cli:dev": "cd cli && pnpm dev",
|
|
54
|
+
"cli:test": "cd cli && pnpm test",
|
|
55
|
+
"cli:install": "cd cli && pnpm install"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
-
"@anthropic-ai/sdk": "^0.
|
|
58
|
+
"@anthropic-ai/sdk": "^0.91.1",
|
|
59
59
|
"@aws-sdk/client-bedrock-runtime": "^3.972.0",
|
|
60
60
|
"@babel/core": "^7.27.4",
|
|
61
61
|
"@babel/preset-env": "^7.27.2",
|
|
@@ -76,19 +76,19 @@
|
|
|
76
76
|
"eslint-config-nevermined": "^0.3.0",
|
|
77
77
|
"eslint-config-next": "^15.1.5",
|
|
78
78
|
"eslint-config-prettier": "^9.1.0",
|
|
79
|
-
"eslint-plugin-tsdoc": "^0.2
|
|
79
|
+
"eslint-plugin-tsdoc": "^0.5.2",
|
|
80
80
|
"jest": "^29.7.0",
|
|
81
81
|
"langchain": "^0.3.37",
|
|
82
82
|
"openai": "^6.2.0",
|
|
83
83
|
"prettier": "^3.2.5",
|
|
84
84
|
"source-map-support": "^0.5.21",
|
|
85
85
|
"supertest": "^7.1.4",
|
|
86
|
-
"together-ai": "^0.
|
|
86
|
+
"together-ai": "^0.39.0",
|
|
87
87
|
"ts-jest": "^29.2.5",
|
|
88
88
|
"ts-node": "^10.9.2",
|
|
89
89
|
"tsconfig-paths": "^4.2.0",
|
|
90
90
|
"tslib": "^2.6.2",
|
|
91
|
-
"typedoc": "0.
|
|
91
|
+
"typedoc": "0.28.19",
|
|
92
92
|
"typescript": "^5.3.3"
|
|
93
93
|
},
|
|
94
94
|
"peerDependencies": {
|
|
@@ -111,8 +111,8 @@
|
|
|
111
111
|
"@a2a-js/sdk": "^0.3.4",
|
|
112
112
|
"@helicone/helpers": "^1.6.0",
|
|
113
113
|
"@opentelemetry/api": "^1.9.0",
|
|
114
|
-
"@opentelemetry/exporter-trace-otlp-http": "^0.
|
|
115
|
-
"@traceloop/node-server-sdk": "^0.
|
|
114
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.215.0",
|
|
115
|
+
"@traceloop/node-server-sdk": "^0.26.0",
|
|
116
116
|
"axios": "^1.13.1",
|
|
117
117
|
"express": "4.21.2",
|
|
118
118
|
"jose": "^5.2.4",
|
|
@@ -121,12 +121,14 @@
|
|
|
121
121
|
"zod": "^4.0.17",
|
|
122
122
|
"zod-to-json-schema": "^3.25.0"
|
|
123
123
|
},
|
|
124
|
-
"packageManager": "
|
|
125
|
-
"
|
|
126
|
-
"
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
124
|
+
"packageManager": "pnpm@10.33.0",
|
|
125
|
+
"pnpm": {
|
|
126
|
+
"overrides": {
|
|
127
|
+
"qs": ">=6.14.1",
|
|
128
|
+
"jws": ">=4.0.1",
|
|
129
|
+
"js-yaml": ">=4.1.1",
|
|
130
|
+
"@langchain/core": ">=0.3.80",
|
|
131
|
+
"@smithy/config-resolver": ">=4.4.0"
|
|
132
|
+
}
|
|
131
133
|
}
|
|
132
134
|
}
|
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Visa Facilitator API — verifies and settles payments via the Visa x402 backend.
|
|
3
|
-
*
|
|
4
|
-
* Unlike the base FacilitatorAPI (which sends JSON bodies to the NVM backend),
|
|
5
|
-
* the Visa flow uses the PAYMENT-SIGNATURE HTTP header to transport a base64-encoded
|
|
6
|
-
* PaymentPayload to the Visa backend's /verify and /settle endpoints.
|
|
7
|
-
*
|
|
8
|
-
* @example
|
|
9
|
-
* ```typescript
|
|
10
|
-
* import { Payments } from '@nevermined-io/payments'
|
|
11
|
-
*
|
|
12
|
-
* const payments = Payments.getInstance({
|
|
13
|
-
* nvmApiKey: 'your-nvm-api-key',
|
|
14
|
-
* environment: 'sandbox',
|
|
15
|
-
* scheme: 'visa',
|
|
16
|
-
* })
|
|
17
|
-
*
|
|
18
|
-
* const paymentRequired = buildVisaPaymentRequired({
|
|
19
|
-
* amount: '2.00',
|
|
20
|
-
* asset: 'USD',
|
|
21
|
-
* payTo: 'merchant-id',
|
|
22
|
-
* endpoint: '/tools/random-article',
|
|
23
|
-
* })
|
|
24
|
-
*
|
|
25
|
-
* // The PAYMENT-SIGNATURE header from the client request
|
|
26
|
-
* const paymentSignature = req.headers['payment-signature'] as string
|
|
27
|
-
*
|
|
28
|
-
* const verification = await payments.facilitator.verifyPermissions({
|
|
29
|
-
* paymentRequired,
|
|
30
|
-
* x402AccessToken: paymentSignature,
|
|
31
|
-
* })
|
|
32
|
-
*
|
|
33
|
-
* if (verification.isValid) {
|
|
34
|
-
* const settlement = await payments.facilitator.settlePermissions({
|
|
35
|
-
* paymentRequired,
|
|
36
|
-
* x402AccessToken: paymentSignature,
|
|
37
|
-
* })
|
|
38
|
-
* }
|
|
39
|
-
* ```
|
|
40
|
-
*/
|
|
41
|
-
import { FacilitatorAPI } from './facilitator-api.js';
|
|
42
|
-
import type { VerifyPermissionsParams, VerifyPermissionsResult, SettlePermissionsParams, SettlePermissionsResult, X402Resource } from './facilitator-api.js';
|
|
43
|
-
import { PaymentOptions } from '../common/types.js';
|
|
44
|
-
/**
|
|
45
|
-
* Visa-specific extra fields in PaymentRequirements
|
|
46
|
-
*/
|
|
47
|
-
export interface VisaPaymentExtra {
|
|
48
|
-
/** Visa Token Service provisioned token ID */
|
|
49
|
-
vProvisionedTokenID: string;
|
|
50
|
-
/** VIC instruction ID from mandate creation */
|
|
51
|
-
instructionId: string;
|
|
52
|
-
/** Maximum number of times this payment can be used */
|
|
53
|
-
maxUsage: number;
|
|
54
|
-
/** Merchant name */
|
|
55
|
-
merchantName?: string;
|
|
56
|
-
/** Merchant URL */
|
|
57
|
-
merchantUrl?: string;
|
|
58
|
-
/** Merchant country code */
|
|
59
|
-
merchantCountryCode?: string;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Visa payment requirements (x402 v2 with scheme: "visa")
|
|
63
|
-
*/
|
|
64
|
-
export interface VisaPaymentRequirements {
|
|
65
|
-
scheme: 'visa';
|
|
66
|
-
network: 'visa:vts';
|
|
67
|
-
amount: string;
|
|
68
|
-
asset: string;
|
|
69
|
-
payTo: string;
|
|
70
|
-
maxTimeoutSeconds: number;
|
|
71
|
-
extra: VisaPaymentExtra;
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* Visa-specific PaymentRequired response
|
|
75
|
-
*/
|
|
76
|
-
export interface VisaPaymentRequired {
|
|
77
|
-
x402Version: 2;
|
|
78
|
-
error?: string;
|
|
79
|
-
resource: X402Resource;
|
|
80
|
-
accepts: VisaPaymentRequirements[];
|
|
81
|
-
extensions?: Record<string, unknown>;
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* Visa verify response
|
|
85
|
-
*/
|
|
86
|
-
export interface VisaVerifyResponse {
|
|
87
|
-
isValid: boolean;
|
|
88
|
-
payer?: string;
|
|
89
|
-
invalidReason?: string;
|
|
90
|
-
remainingUsage?: number;
|
|
91
|
-
}
|
|
92
|
-
/**
|
|
93
|
-
* Visa settlement response
|
|
94
|
-
*/
|
|
95
|
-
export interface VisaSettlementResponse {
|
|
96
|
-
success: boolean;
|
|
97
|
-
transaction: string;
|
|
98
|
-
network: 'visa:vts';
|
|
99
|
-
payer?: string;
|
|
100
|
-
errorReason?: string;
|
|
101
|
-
}
|
|
102
|
-
export declare const VISA_X402_HEADERS: {
|
|
103
|
-
readonly PAYMENT_REQUIRED: "PAYMENT-REQUIRED";
|
|
104
|
-
readonly PAYMENT_SIGNATURE: "PAYMENT-SIGNATURE";
|
|
105
|
-
readonly PAYMENT_RESPONSE: "PAYMENT-RESPONSE";
|
|
106
|
-
};
|
|
107
|
-
/**
|
|
108
|
-
* Build a Visa-flavored X402PaymentRequired object.
|
|
109
|
-
*
|
|
110
|
-
* This is the Visa counterpart of `buildPaymentRequired` (which builds NVM-flavored ones).
|
|
111
|
-
*/
|
|
112
|
-
export declare function buildVisaPaymentRequired(options: {
|
|
113
|
-
amount: string;
|
|
114
|
-
asset?: string;
|
|
115
|
-
payTo: string;
|
|
116
|
-
endpoint?: string;
|
|
117
|
-
description?: string;
|
|
118
|
-
maxTimeoutSeconds?: number;
|
|
119
|
-
merchantName?: string;
|
|
120
|
-
merchantUrl?: string;
|
|
121
|
-
merchantCountryCode?: string;
|
|
122
|
-
}): VisaPaymentRequired;
|
|
123
|
-
/**
|
|
124
|
-
* Visa Facilitator API — sends PAYMENT-SIGNATURE header to the Visa backend
|
|
125
|
-
* for verify and settle operations.
|
|
126
|
-
*/
|
|
127
|
-
export declare class VisaFacilitatorAPI extends FacilitatorAPI {
|
|
128
|
-
protected visaBackendUrl: string;
|
|
129
|
-
constructor(options: PaymentOptions);
|
|
130
|
-
static getInstance(options: PaymentOptions): VisaFacilitatorAPI;
|
|
131
|
-
/**
|
|
132
|
-
* Verify a Visa payment authorization.
|
|
133
|
-
*
|
|
134
|
-
* Sends the base64-encoded PaymentPayload as a PAYMENT-SIGNATURE header
|
|
135
|
-
* to the Visa backend's POST /verify endpoint.
|
|
136
|
-
*
|
|
137
|
-
* @param params - contains x402AccessToken, the base64-encoded PaymentPayload from the client
|
|
138
|
-
*/
|
|
139
|
-
verifyPermissions(params: VerifyPermissionsParams): Promise<VerifyPermissionsResult>;
|
|
140
|
-
/**
|
|
141
|
-
* Settle a Visa payment transaction.
|
|
142
|
-
*
|
|
143
|
-
* Sends the base64-encoded PaymentPayload as a PAYMENT-SIGNATURE header
|
|
144
|
-
* to the Visa backend's POST /settle endpoint.
|
|
145
|
-
*
|
|
146
|
-
* @param params - contains x402AccessToken, the base64-encoded PaymentPayload from the client
|
|
147
|
-
*/
|
|
148
|
-
settlePermissions(params: SettlePermissionsParams): Promise<SettlePermissionsResult>;
|
|
149
|
-
}
|
|
150
|
-
//# sourceMappingURL=visa-facilitator-api.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"visa-facilitator-api.d.ts","sourceRoot":"","sources":["../../src/x402/visa-facilitator-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACrD,OAAO,KAAK,EACV,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,uBAAuB,EACvB,YAAY,EACb,MAAM,sBAAsB,CAAA;AAE7B,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAA;AAOnD;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,8CAA8C;IAC9C,mBAAmB,EAAE,MAAM,CAAA;IAC3B,+CAA+C;IAC/C,aAAa,EAAE,MAAM,CAAA;IACrB,uDAAuD;IACvD,QAAQ,EAAE,MAAM,CAAA;IAChB,oBAAoB;IACpB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,mBAAmB;IACnB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,4BAA4B;IAC5B,mBAAmB,CAAC,EAAE,MAAM,CAAA;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,UAAU,CAAA;IACnB,MAAM,EAAE,MA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