@t402/core 2.3.1 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/client/index.d.ts +3 -2
- package/dist/cjs/client/index.js +71 -2
- package/dist/cjs/client/index.js.map +1 -1
- package/dist/cjs/facilitator/index.d.ts +2 -1
- package/dist/cjs/http/index.d.ts +13 -6
- package/dist/cjs/http/index.js +76 -5
- package/dist/cjs/http/index.js.map +1 -1
- package/dist/cjs/mechanisms-dYCiYgko.d.ts +1195 -0
- package/dist/cjs/server/index.d.ts +3 -2
- package/dist/cjs/server/index.js +70 -3
- package/dist/cjs/server/index.js.map +1 -1
- package/dist/cjs/{t402HTTPClient-GIweW6nh.d.ts → t402HTTPClient-CHaMMGBY.d.ts} +2 -2
- package/dist/cjs/{t402HTTPResourceServer-CcpZF3af.d.ts → t402HTTPResourceServer-B-aOi0BZ.d.ts} +2 -2
- package/dist/cjs/types/index.d.ts +2 -1
- package/dist/cjs/types/index.js +470 -2
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/v1/index.d.ts +2 -1
- package/dist/cjs/utils/index.d.ts +29 -2
- package/dist/cjs/utils/index.js +53 -0
- package/dist/cjs/utils/index.js.map +1 -1
- package/dist/esm/{chunk-773TNE2Y.mjs → chunk-7RHSIMQL.mjs} +18 -7
- package/dist/esm/chunk-7RHSIMQL.mjs.map +1 -0
- package/dist/esm/{chunk-3IUBYRYG.mjs → chunk-LJ4M5Z5U.mjs} +51 -1
- package/dist/esm/chunk-LJ4M5Z5U.mjs.map +1 -0
- package/dist/esm/chunk-STKQDKUH.mjs +101 -0
- package/dist/esm/chunk-STKQDKUH.mjs.map +1 -0
- package/dist/esm/client/index.d.mts +3 -2
- package/dist/esm/client/index.mjs +3 -2
- package/dist/esm/client/index.mjs.map +1 -1
- package/dist/esm/facilitator/index.d.mts +2 -1
- package/dist/esm/http/index.d.mts +13 -6
- package/dist/esm/http/index.mjs +3 -2
- package/dist/esm/mechanisms-dYCiYgko.d.mts +1195 -0
- package/dist/esm/server/index.d.mts +3 -2
- package/dist/esm/server/index.mjs +3 -2
- package/dist/esm/server/index.mjs.map +1 -1
- package/dist/esm/{t402HTTPClient-DbZqiMSO.d.mts → t402HTTPClient-DbIXpGXL.d.mts} +2 -2
- package/dist/esm/{t402HTTPResourceServer-BbQ6HVBC.d.mts → t402HTTPResourceServer-CstWZOsH.d.mts} +2 -2
- package/dist/esm/types/index.d.mts +2 -1
- package/dist/esm/types/index.mjs +304 -1
- package/dist/esm/types/index.mjs.map +1 -1
- package/dist/esm/types/v1/index.d.mts +2 -1
- package/dist/esm/utils/index.d.mts +29 -2
- package/dist/esm/utils/index.mjs +7 -1
- package/package.json +11 -11
- package/dist/cjs/mechanisms-B-vz5yOj.d.ts +0 -443
- package/dist/esm/chunk-3IUBYRYG.mjs.map +0 -1
- package/dist/esm/chunk-773TNE2Y.mjs.map +0 -1
- package/dist/esm/mechanisms-B-vz5yOj.d.mts +0 -443
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/types/schemes/upto.ts"],"sourcesContent":["/**\n * Up-To Scheme Types\n *\n * The `upto` scheme authorizes transfer of up to a maximum amount,\n * enabling usage-based billing where the final settlement amount\n * is determined by actual usage.\n *\n * @example\n * ```typescript\n * // Client authorizes up to $1.00\n * const requirements: UptoPaymentRequirements = {\n * scheme: 'upto',\n * network: 'eip155:8453',\n * maxAmount: '1000000', // $1.00 in USDC\n * minAmount: '10000', // $0.01 minimum\n * asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n * payTo: '0x...',\n * maxTimeoutSeconds: 300,\n * extra: {\n * unit: 'token',\n * unitPrice: '100',\n * },\n * };\n *\n * // Server settles for actual usage ($0.15)\n * const settlement: UptoSettlement = {\n * settleAmount: '150000',\n * usageDetails: {\n * tokensGenerated: 1500,\n * unitPrice: '100',\n * },\n * };\n * ```\n */\n\nimport type { Network, PaymentRequirements } from \"../\";\n\n/**\n * Extended payment requirements for the upto scheme.\n */\nexport interface UptoPaymentRequirements extends Omit<PaymentRequirements, \"scheme\" | \"amount\"> {\n /** Scheme identifier - always 'upto' */\n scheme: \"upto\";\n\n /** Network identifier (CAIP-2 format) */\n network: Network;\n\n /** Maximum amount the client authorizes (in smallest denomination) */\n maxAmount: string;\n\n /** Minimum settlement amount (prevents dust payments) */\n minAmount?: string;\n\n /** Asset contract address or identifier */\n asset: string;\n\n /** Recipient address */\n payTo: string;\n\n /** Maximum time in seconds before payment expires */\n maxTimeoutSeconds: number;\n\n /** Additional scheme-specific data */\n extra: UptoExtra;\n}\n\n/**\n * Extra fields specific to the upto scheme.\n */\nexport interface UptoExtra extends Record<string, unknown> {\n /** Billing unit (e.g., 'token', 'request', 'second', 'byte') */\n unit?: string;\n\n /** Price per unit in smallest denomination */\n unitPrice?: string;\n\n /** EIP-712 domain name (for EVM) */\n name?: string;\n\n /** EIP-712 domain version (for EVM) */\n version?: string;\n\n /** Router contract address (for EVM) */\n routerAddress?: string;\n}\n\n/**\n * Base payload structure for upto scheme.\n */\nexport interface UptoPayloadBase {\n /** Unique nonce to prevent replay attacks */\n nonce: string;\n}\n\n/**\n * EVM-specific upto payload using EIP-2612 Permit.\n */\nexport interface UptoEvmPayload extends UptoPayloadBase {\n /** EIP-2612 permit signature components */\n signature: {\n v: number;\n r: `0x${string}`;\n s: `0x${string}`;\n };\n\n /** Permit authorization parameters */\n authorization: {\n /** Token owner address */\n owner: `0x${string}`;\n\n /** Spender address (router contract) */\n spender: `0x${string}`;\n\n /** Maximum authorized value */\n value: string;\n\n /** Permit deadline (unix timestamp) */\n deadline: string;\n\n /** Permit nonce (from token contract) */\n nonce: number;\n };\n}\n\n/**\n * Alternative EVM payload with combined signature.\n */\nexport interface UptoEvmPayloadCompact extends UptoPayloadBase {\n /** Combined EIP-2612 permit signature */\n signature: `0x${string}`;\n\n /** Permit authorization parameters */\n authorization: {\n owner: `0x${string}`;\n spender: `0x${string}`;\n value: string;\n deadline: string;\n nonce: number;\n };\n}\n\n/**\n * Settlement request for upto scheme.\n */\nexport interface UptoSettlement {\n /** Actual amount to settle (must be <= maxAmount) */\n settleAmount: string;\n\n /** Optional usage details for auditing */\n usageDetails?: UptoUsageDetails;\n}\n\n/**\n * Usage details for settlement auditing.\n */\nexport interface UptoUsageDetails {\n /** Number of units consumed */\n unitsConsumed?: number;\n\n /** Price per unit used */\n unitPrice?: string;\n\n /** Type of unit */\n unitType?: string;\n\n /** Start timestamp of usage period */\n startTime?: number;\n\n /** End timestamp of usage period */\n endTime?: number;\n\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Settlement response for upto scheme.\n */\nexport interface UptoSettlementResponse {\n /** Whether settlement was successful */\n success: boolean;\n\n /** Transaction hash (if on-chain) */\n transactionHash?: string;\n\n /** Actual amount settled */\n settledAmount: string;\n\n /** Maximum amount that was authorized */\n maxAmount: string;\n\n /** Block number (if on-chain) */\n blockNumber?: number;\n\n /** Gas used (if on-chain) */\n gasUsed?: string;\n\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Validation result for upto payment.\n */\nexport interface UptoValidationResult {\n /** Whether the payment is valid */\n isValid: boolean;\n\n /** Reason if invalid */\n invalidReason?: string;\n\n /** Validated maximum amount */\n validatedMaxAmount?: string;\n\n /** Payer address */\n payer?: string;\n\n /** Expiration timestamp */\n expiresAt?: number;\n}\n\n/**\n * Type guard for UptoPaymentRequirements.\n *\n * @param requirements - The value to check\n * @returns True if the value is UptoPaymentRequirements\n */\nexport function isUptoPaymentRequirements(\n requirements: unknown,\n): requirements is UptoPaymentRequirements {\n if (typeof requirements !== \"object\" || requirements === null) return false;\n const req = requirements as Record<string, unknown>;\n return req.scheme === \"upto\" && \"maxAmount\" in req;\n}\n\n/**\n * Type guard for UptoEvmPayload.\n *\n * @param payload - The value to check\n * @returns True if the value is UptoEvmPayload\n */\nexport function isUptoEvmPayload(payload: unknown): payload is UptoEvmPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return (\n \"signature\" in p &&\n \"authorization\" in p &&\n typeof p.authorization === \"object\" &&\n p.authorization !== null &&\n \"owner\" in (p.authorization as Record<string, unknown>) &&\n \"spender\" in (p.authorization as Record<string, unknown>) &&\n \"value\" in (p.authorization as Record<string, unknown>) &&\n \"deadline\" in (p.authorization as Record<string, unknown>)\n );\n}\n\n/**\n * Constants for upto scheme.\n */\nexport const UPTO_SCHEME = \"upto\" as const;\n\nexport const UPTO_DEFAULTS = {\n /** Default minimum settlement amount (prevents dust) */\n MIN_AMOUNT: \"1000\",\n\n /** Default maximum timeout in seconds (5 minutes) */\n MAX_TIMEOUT_SECONDS: 300,\n\n /** Supported billing units */\n UNITS: [\"token\", \"request\", \"second\", \"minute\", \"byte\", \"kb\", \"mb\"] as const,\n} as const;\n\nexport type UptoUnit = (typeof UPTO_DEFAULTS.UNITS)[number];\n"],"mappings":";;;AAmOO,SAAS,0BACd,cACyC;AACzC,MAAI,OAAO,iBAAiB,YAAY,iBAAiB,KAAM,QAAO;AACtE,QAAM,MAAM;AACZ,SAAO,IAAI,WAAW,UAAU,eAAe;AACjD;AAQO,SAAS,iBAAiB,SAA6C;AAC5E,MAAI,OAAO,YAAY,YAAY,YAAY,KAAM,QAAO;AAC5D,QAAM,IAAI;AACV,SACE,eAAe,KACf,mBAAmB,KACnB,OAAO,EAAE,kBAAkB,YAC3B,EAAE,kBAAkB,QACpB,WAAY,EAAE,iBACd,aAAc,EAAE,iBAChB,WAAY,EAAE,iBACd,cAAe,EAAE;AAErB;AAKO,IAAM,cAAc;AAEpB,IAAM,gBAAgB;AAAA;AAAA,EAE3B,YAAY;AAAA;AAAA,EAGZ,qBAAqB;AAAA;AAAA,EAGrB,OAAO,CAAC,SAAS,WAAW,UAAU,UAAU,QAAQ,MAAM,IAAI;AACpE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/types/a2a.ts","../../../src/types/schemes/upto.ts","../../../src/types/errors.ts"],"sourcesContent":["/**\n * A2A (Agent-to-Agent) Transport Types\n *\n * Implements t402 payment flows over the Agent-to-Agent protocol\n * using JSON-RPC messages and task-based state management.\n *\n * @see https://github.com/google-a2a/a2a-t402/v0.1\n */\n\nimport type { PaymentPayload, PaymentRequired } from \"./payments\";\nimport type { SettleResponse } from \"./facilitator\";\n\n// ============================================================================\n// A2A Payment Status\n// ============================================================================\n\n/**\n * Payment status values used in A2A metadata\n */\nexport type A2APaymentStatus =\n | \"payment-required\" // Payment requirements sent to client\n | \"payment-rejected\" // Client rejected payment requirements\n | \"payment-submitted\" // Payment payload received by server\n | \"payment-verified\" // Payment payload verified by server\n | \"payment-completed\" // Payment settled on-chain successfully\n | \"payment-failed\"; // Payment verification or settlement failed\n\n/**\n * A2A task states that correspond to payment states\n */\nexport type A2ATaskState =\n | \"submitted\"\n | \"working\"\n | \"input-required\"\n | \"completed\"\n | \"canceled\"\n | \"failed\"\n | \"unknown\";\n\n// ============================================================================\n// A2A Message Types\n// ============================================================================\n\n/**\n * A2A message part - text content\n */\nexport interface A2ATextPart {\n kind: \"text\";\n text: string;\n}\n\n/**\n * A2A message part - file content\n */\nexport interface A2AFilePart {\n kind: \"file\";\n file: {\n name?: string;\n mimeType?: string;\n bytes?: string; // base64 encoded\n uri?: string;\n };\n}\n\n/**\n * A2A message part - data content\n */\nexport interface A2ADataPart {\n kind: \"data\";\n data: Record<string, unknown>;\n}\n\nexport type A2AMessagePart = A2ATextPart | A2AFilePart | A2ADataPart;\n\n/**\n * A2A payment metadata fields\n */\nexport interface A2APaymentMetadata {\n /** Current payment status */\n \"t402.payment.status\"?: A2APaymentStatus;\n\n /** Payment requirements (when status is payment-required) */\n \"t402.payment.required\"?: PaymentRequired;\n\n /** Payment payload (when status is payment-submitted) */\n \"t402.payment.payload\"?: PaymentPayload;\n\n /** Settlement receipts (when status is payment-completed or payment-failed) */\n \"t402.payment.receipts\"?: SettleResponse[];\n\n /** Error code (when status is payment-failed) */\n \"t402.payment.error\"?: string;\n}\n\n/**\n * A2A message with payment metadata\n */\nexport interface A2AMessage {\n kind: \"message\";\n messageId?: string;\n role: \"user\" | \"agent\";\n parts: A2AMessagePart[];\n metadata?: A2APaymentMetadata & Record<string, unknown>;\n}\n\n// ============================================================================\n// A2A Task Types\n// ============================================================================\n\n/**\n * A2A artifact (output from completed task)\n */\nexport interface A2AArtifact {\n kind: string;\n name?: string;\n mimeType?: string;\n data?: string; // base64 encoded\n uri?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * A2A task status\n */\nexport interface A2ATaskStatus {\n state: A2ATaskState;\n message?: A2AMessage;\n timestamp?: string;\n}\n\n/**\n * A2A task\n */\nexport interface A2ATask {\n kind: \"task\";\n id: string;\n sessionId?: string;\n status: A2ATaskStatus;\n artifacts?: A2AArtifact[];\n history?: A2AMessage[];\n metadata?: Record<string, unknown>;\n}\n\n// ============================================================================\n// A2A JSON-RPC Types\n// ============================================================================\n\n/**\n * A2A JSON-RPC request\n */\nexport interface A2ARequest<T = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n id: string | number;\n params?: T;\n}\n\n/**\n * A2A JSON-RPC response\n */\nexport interface A2AResponse<T = unknown> {\n jsonrpc: \"2.0\";\n id: string | number;\n result?: T;\n error?: A2AError;\n}\n\n/**\n * A2A JSON-RPC error\n */\nexport interface A2AError {\n code: number;\n message: string;\n data?: unknown;\n}\n\n// ============================================================================\n// A2A Extension Types\n// ============================================================================\n\n/**\n * A2A extension declaration\n */\nexport interface A2AExtension {\n uri: string;\n description?: string;\n required?: boolean;\n}\n\n/**\n * A2A agent capabilities\n */\nexport interface A2ACapabilities {\n streaming?: boolean;\n pushNotifications?: boolean;\n stateTransitionHistory?: boolean;\n extensions?: A2AExtension[];\n}\n\n/**\n * A2A agent card (service advertisement)\n */\nexport interface A2AAgentCard {\n name: string;\n description?: string;\n url: string;\n provider?: {\n organization?: string;\n url?: string;\n };\n version?: string;\n documentationUrl?: string;\n capabilities?: A2ACapabilities;\n authentication?: {\n schemes: string[];\n credentials?: string;\n };\n defaultInputModes?: string[];\n defaultOutputModes?: string[];\n skills?: A2ASkill[];\n}\n\n/**\n * A2A skill definition\n */\nexport interface A2ASkill {\n id: string;\n name: string;\n description?: string;\n tags?: string[];\n examples?: string[];\n inputModes?: string[];\n outputModes?: string[];\n}\n\n// ============================================================================\n// T402-A2A Constants\n// ============================================================================\n\n/**\n * T402 A2A extension URI\n */\nexport const T402_A2A_EXTENSION_URI = \"https://github.com/google-a2a/a2a-t402/v0.1\";\n\n/**\n * HTTP header for A2A extension activation\n */\nexport const A2A_EXTENSIONS_HEADER = \"X-A2A-Extensions\";\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if a task is in a payment-required state\n *\n * @param task - The A2A task to check\n * @returns Whether the task requires payment\n */\nexport function isPaymentRequired(task: A2ATask): boolean {\n return (\n task.status.state === \"input-required\" &&\n task.status.message?.metadata?.[\"t402.payment.status\"] === \"payment-required\"\n );\n}\n\n/**\n * Check if a task has completed payment\n *\n * @param task - The A2A task to check\n * @returns Whether the task has completed payment\n */\nexport function isPaymentCompleted(task: A2ATask): boolean {\n return (\n task.status.state === \"completed\" &&\n task.status.message?.metadata?.[\"t402.payment.status\"] === \"payment-completed\"\n );\n}\n\n/**\n * Check if a task has failed payment\n *\n * @param task - The A2A task to check\n * @returns Whether the task has failed payment\n */\nexport function isPaymentFailed(task: A2ATask): boolean {\n return (\n task.status.state === \"failed\" &&\n task.status.message?.metadata?.[\"t402.payment.status\"] === \"payment-failed\"\n );\n}\n\n/**\n * Extract payment requirements from a task\n *\n * @param task - The A2A task to extract requirements from\n * @returns The payment requirements if the task requires payment\n */\nexport function getPaymentRequired(task: A2ATask): PaymentRequired | undefined {\n if (isPaymentRequired(task)) {\n return task.status.message?.metadata?.[\"t402.payment.required\"];\n }\n return undefined;\n}\n\n/**\n * Extract payment receipts from a task\n *\n * @param task - The A2A task to extract receipts from\n * @returns The settlement receipts if available\n */\nexport function getPaymentReceipts(task: A2ATask): SettleResponse[] | undefined {\n return task.status.message?.metadata?.[\"t402.payment.receipts\"];\n}\n\n/**\n * Create a payment-required message\n *\n * @param paymentRequired - The payment requirements\n * @param text - Optional message text\n * @returns An A2A message with payment-required metadata\n */\nexport function createPaymentRequiredMessage(\n paymentRequired: PaymentRequired,\n text: string = \"Payment is required to complete this request.\",\n): A2AMessage {\n return {\n kind: \"message\",\n role: \"agent\",\n parts: [{ kind: \"text\", text }],\n metadata: {\n \"t402.payment.status\": \"payment-required\",\n \"t402.payment.required\": paymentRequired,\n },\n };\n}\n\n/**\n * Create a payment submission message\n *\n * @param paymentPayload - The payment payload to submit\n * @param text - Optional message text\n * @returns An A2A message with payment-submitted metadata\n */\nexport function createPaymentSubmissionMessage(\n paymentPayload: PaymentPayload,\n text: string = \"Here is the payment authorization.\",\n): A2AMessage {\n return {\n kind: \"message\",\n role: \"user\",\n parts: [{ kind: \"text\", text }],\n metadata: {\n \"t402.payment.status\": \"payment-submitted\",\n \"t402.payment.payload\": paymentPayload,\n },\n };\n}\n\n/**\n * Create a payment completed message\n *\n * @param receipts - The settlement receipts\n * @param text - Optional message text\n * @returns An A2A message with payment-completed metadata\n */\nexport function createPaymentCompletedMessage(\n receipts: SettleResponse[],\n text: string = \"Payment successful.\",\n): A2AMessage {\n return {\n kind: \"message\",\n role: \"agent\",\n parts: [{ kind: \"text\", text }],\n metadata: {\n \"t402.payment.status\": \"payment-completed\",\n \"t402.payment.receipts\": receipts,\n },\n };\n}\n\n/**\n * Create a payment failed message\n *\n * @param receipts - The settlement receipts\n * @param errorCode - The error code\n * @param text - Optional message text\n * @returns An A2A message with payment-failed metadata\n */\nexport function createPaymentFailedMessage(\n receipts: SettleResponse[],\n errorCode: string,\n text: string = \"Payment failed.\",\n): A2AMessage {\n return {\n kind: \"message\",\n role: \"agent\",\n parts: [{ kind: \"text\", text }],\n metadata: {\n \"t402.payment.status\": \"payment-failed\",\n \"t402.payment.error\": errorCode,\n \"t402.payment.receipts\": receipts,\n },\n };\n}\n\n/**\n * Create a T402 extension declaration for agent cards\n *\n * @param required - Whether the extension is required\n * @returns An A2A extension declaration\n */\nexport function createT402Extension(required: boolean = false): A2AExtension {\n return {\n uri: T402_A2A_EXTENSION_URI,\n description: \"Supports payments using the t402 protocol for on-chain settlement.\",\n required,\n };\n}\n","/**\n * Up-To Scheme Types\n *\n * The `upto` scheme authorizes transfer of up to a maximum amount,\n * enabling usage-based billing where the final settlement amount\n * is determined by actual usage.\n *\n * @example\n * ```typescript\n * // Client authorizes up to $1.00\n * const requirements: UptoPaymentRequirements = {\n * scheme: 'upto',\n * network: 'eip155:8453',\n * maxAmount: '1000000', // $1.00 in USDC\n * minAmount: '10000', // $0.01 minimum\n * asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n * payTo: '0x...',\n * maxTimeoutSeconds: 300,\n * extra: {\n * unit: 'token',\n * unitPrice: '100',\n * },\n * };\n *\n * // Server settles for actual usage ($0.15)\n * const settlement: UptoSettlement = {\n * settleAmount: '150000',\n * usageDetails: {\n * tokensGenerated: 1500,\n * unitPrice: '100',\n * },\n * };\n * ```\n */\n\nimport type { Network, PaymentRequirements } from \"../\";\n\n/**\n * Extended payment requirements for the upto scheme.\n */\nexport interface UptoPaymentRequirements extends Omit<PaymentRequirements, \"scheme\" | \"amount\"> {\n /** Scheme identifier - always 'upto' */\n scheme: \"upto\";\n\n /** Network identifier (CAIP-2 format) */\n network: Network;\n\n /** Maximum amount the client authorizes (in smallest denomination) */\n maxAmount: string;\n\n /** Minimum settlement amount (prevents dust payments) */\n minAmount?: string;\n\n /** Asset contract address or identifier */\n asset: string;\n\n /** Recipient address */\n payTo: string;\n\n /** Maximum time in seconds before payment expires */\n maxTimeoutSeconds: number;\n\n /** Additional scheme-specific data */\n extra: UptoExtra;\n}\n\n/**\n * Extra fields specific to the upto scheme.\n */\nexport interface UptoExtra extends Record<string, unknown> {\n /** Billing unit (e.g., 'token', 'request', 'second', 'byte') */\n unit?: string;\n\n /** Price per unit in smallest denomination */\n unitPrice?: string;\n\n /** EIP-712 domain name (for EVM) */\n name?: string;\n\n /** EIP-712 domain version (for EVM) */\n version?: string;\n\n /** Router contract address (for EVM) */\n routerAddress?: string;\n}\n\n/**\n * Base payload structure for upto scheme.\n */\nexport interface UptoPayloadBase {\n /** Unique nonce to prevent replay attacks */\n nonce: string;\n}\n\n/**\n * EVM-specific upto payload using EIP-2612 Permit.\n */\nexport interface UptoEvmPayload extends UptoPayloadBase {\n /** EIP-2612 permit signature components */\n signature: {\n v: number;\n r: `0x${string}`;\n s: `0x${string}`;\n };\n\n /** Permit authorization parameters */\n authorization: {\n /** Token owner address */\n owner: `0x${string}`;\n\n /** Spender address (router contract) */\n spender: `0x${string}`;\n\n /** Maximum authorized value */\n value: string;\n\n /** Permit deadline (unix timestamp) */\n deadline: string;\n\n /** Permit nonce (from token contract) */\n nonce: number;\n };\n}\n\n/**\n * Alternative EVM payload with combined signature.\n */\nexport interface UptoEvmPayloadCompact extends UptoPayloadBase {\n /** Combined EIP-2612 permit signature */\n signature: `0x${string}`;\n\n /** Permit authorization parameters */\n authorization: {\n owner: `0x${string}`;\n spender: `0x${string}`;\n value: string;\n deadline: string;\n nonce: number;\n };\n}\n\n/**\n * Settlement request for upto scheme.\n */\nexport interface UptoSettlement {\n /** Actual amount to settle (must be <= maxAmount) */\n settleAmount: string;\n\n /** Optional usage details for auditing */\n usageDetails?: UptoUsageDetails;\n}\n\n/**\n * Usage details for settlement auditing.\n */\nexport interface UptoUsageDetails {\n /** Number of units consumed */\n unitsConsumed?: number;\n\n /** Price per unit used */\n unitPrice?: string;\n\n /** Type of unit */\n unitType?: string;\n\n /** Start timestamp of usage period */\n startTime?: number;\n\n /** End timestamp of usage period */\n endTime?: number;\n\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Settlement response for upto scheme.\n */\nexport interface UptoSettlementResponse {\n /** Whether settlement was successful */\n success: boolean;\n\n /** Transaction hash (if on-chain) */\n transactionHash?: string;\n\n /** Actual amount settled */\n settledAmount: string;\n\n /** Maximum amount that was authorized */\n maxAmount: string;\n\n /** Block number (if on-chain) */\n blockNumber?: number;\n\n /** Gas used (if on-chain) */\n gasUsed?: string;\n\n /** Error message if failed */\n error?: string;\n}\n\n/**\n * Validation result for upto payment.\n */\nexport interface UptoValidationResult {\n /** Whether the payment is valid */\n isValid: boolean;\n\n /** Reason if invalid */\n invalidReason?: string;\n\n /** Validated maximum amount */\n validatedMaxAmount?: string;\n\n /** Payer address */\n payer?: string;\n\n /** Expiration timestamp */\n expiresAt?: number;\n}\n\n/**\n * Type guard for UptoPaymentRequirements.\n *\n * @param requirements - The value to check\n * @returns True if the value is UptoPaymentRequirements\n */\nexport function isUptoPaymentRequirements(\n requirements: unknown,\n): requirements is UptoPaymentRequirements {\n if (typeof requirements !== \"object\" || requirements === null) return false;\n const req = requirements as Record<string, unknown>;\n return req.scheme === \"upto\" && \"maxAmount\" in req;\n}\n\n/**\n * Type guard for UptoEvmPayload.\n *\n * @param payload - The value to check\n * @returns True if the value is UptoEvmPayload\n */\nexport function isUptoEvmPayload(payload: unknown): payload is UptoEvmPayload {\n if (typeof payload !== \"object\" || payload === null) return false;\n const p = payload as Record<string, unknown>;\n return (\n \"signature\" in p &&\n \"authorization\" in p &&\n typeof p.authorization === \"object\" &&\n p.authorization !== null &&\n \"owner\" in (p.authorization as Record<string, unknown>) &&\n \"spender\" in (p.authorization as Record<string, unknown>) &&\n \"value\" in (p.authorization as Record<string, unknown>) &&\n \"deadline\" in (p.authorization as Record<string, unknown>)\n );\n}\n\n/**\n * Constants for upto scheme.\n */\nexport const UPTO_SCHEME = \"upto\" as const;\n\nexport const UPTO_DEFAULTS = {\n /** Default minimum settlement amount (prevents dust) */\n MIN_AMOUNT: \"1000\",\n\n /** Default maximum timeout in seconds (5 minutes) */\n MAX_TIMEOUT_SECONDS: 300,\n\n /** Supported billing units */\n UNITS: [\"token\", \"request\", \"second\", \"minute\", \"byte\", \"kb\", \"mb\"] as const,\n} as const;\n\nexport type UptoUnit = (typeof UPTO_DEFAULTS.UNITS)[number];\n","/**\n * Standardized T402 error codes returned by the facilitator API.\n * Error codes follow the format T402-XYYY where X is the category (1-8)\n * and YYY is the specific error within that category.\n */\n\n// Client Errors (T402-1xxx): Invalid input, malformed requests\nexport const ERR_INVALID_REQUEST = \"T402-1001\" as const;\nexport const ERR_MISSING_PAYLOAD = \"T402-1002\" as const;\nexport const ERR_MISSING_REQUIREMENTS = \"T402-1003\" as const;\nexport const ERR_INVALID_PAYLOAD = \"T402-1004\" as const;\nexport const ERR_INVALID_REQUIREMENTS = \"T402-1005\" as const;\nexport const ERR_INVALID_SIGNATURE = \"T402-1006\" as const;\nexport const ERR_INVALID_NETWORK = \"T402-1007\" as const;\nexport const ERR_INVALID_SCHEME = \"T402-1008\" as const;\nexport const ERR_INVALID_AMOUNT = \"T402-1009\" as const;\nexport const ERR_INVALID_ADDRESS = \"T402-1010\" as const;\nexport const ERR_EXPIRED_PAYMENT = \"T402-1011\" as const;\nexport const ERR_INVALID_NONCE = \"T402-1012\" as const;\nexport const ERR_INSUFFICIENT_AMOUNT = \"T402-1013\" as const;\nexport const ERR_INVALID_IDEMPOTENCY_KEY = \"T402-1014\" as const;\nexport const ERR_SIGNATURE_EXPIRED = \"T402-1015\" as const;\n\n// Server Errors (T402-2xxx): Internal failures, dependency issues\nexport const ERR_INTERNAL = \"T402-2001\" as const;\nexport const ERR_DATABASE_UNAVAILABLE = \"T402-2002\" as const;\nexport const ERR_CACHE_UNAVAILABLE = \"T402-2003\" as const;\nexport const ERR_RPC_UNAVAILABLE = \"T402-2004\" as const;\nexport const ERR_RATE_LIMITED = \"T402-2005\" as const;\nexport const ERR_SERVICE_UNAVAILABLE = \"T402-2006\" as const;\n\n// Facilitator Errors (T402-3xxx): Verification and settlement failures\nexport const ERR_VERIFICATION_FAILED = \"T402-3001\" as const;\nexport const ERR_SETTLEMENT_FAILED = \"T402-3002\" as const;\nexport const ERR_INSUFFICIENT_BALANCE = \"T402-3003\" as const;\nexport const ERR_ALLOWANCE_INSUFFICIENT = \"T402-3004\" as const;\nexport const ERR_PAYMENT_MISMATCH = \"T402-3005\" as const;\nexport const ERR_DUPLICATE_PAYMENT = \"T402-3006\" as const;\nexport const ERR_SETTLEMENT_PENDING = \"T402-3007\" as const;\nexport const ERR_SETTLEMENT_TIMEOUT = \"T402-3008\" as const;\nexport const ERR_NONCE_REPLAY = \"T402-3009\" as const;\nexport const ERR_IDEMPOTENCY_CONFLICT = \"T402-3010\" as const;\nexport const ERR_IDEMPOTENCY_UNAVAILABLE = \"T402-3011\" as const;\nexport const ERR_PREVIOUS_REQUEST_FAILED = \"T402-3012\" as const;\nexport const ERR_REQUEST_IN_PROGRESS = \"T402-3013\" as const;\n\n// Chain-Specific Errors (T402-4xxx): Network and transaction issues\nexport const ERR_CHAIN_UNAVAILABLE = \"T402-4001\" as const;\nexport const ERR_TRANSACTION_FAILED = \"T402-4002\" as const;\nexport const ERR_TRANSACTION_REVERTED = \"T402-4003\" as const;\nexport const ERR_GAS_ESTIMATION_FAILED = \"T402-4004\" as const;\nexport const ERR_NONCE_CONFLICT = \"T402-4005\" as const;\nexport const ERR_CHAIN_CONGESTED = \"T402-4006\" as const;\nexport const ERR_CONTRACT_ERROR = \"T402-4007\" as const;\n\n// Bridge Errors (T402-5xxx): Cross-chain operation failures\nexport const ERR_BRIDGE_UNAVAILABLE = \"T402-5001\" as const;\nexport const ERR_BRIDGE_QUOTE_FAILED = \"T402-5002\" as const;\nexport const ERR_BRIDGE_TRANSFER_FAILED = \"T402-5003\" as const;\nexport const ERR_BRIDGE_TIMEOUT = \"T402-5004\" as const;\nexport const ERR_UNSUPPORTED_ROUTE = \"T402-5005\" as const;\n\n// Streaming Errors (T402-6xxx): Payment stream issues\nexport const ERR_STREAM_NOT_FOUND = \"T402-6001\" as const;\nexport const ERR_STREAM_ALREADY_CLOSED = \"T402-6002\" as const;\nexport const ERR_STREAM_ALREADY_PAUSED = \"T402-6003\" as const;\nexport const ERR_STREAM_NOT_PAUSED = \"T402-6004\" as const;\nexport const ERR_STREAM_AMOUNT_EXCEEDED = \"T402-6005\" as const;\nexport const ERR_STREAM_EXPIRED = \"T402-6006\" as const;\nexport const ERR_STREAM_INVALID_STATE = \"T402-6007\" as const;\nexport const ERR_STREAM_RATE_LIMITED = \"T402-6008\" as const;\n\n// Intent Errors (T402-7xxx): Payment intent issues\nexport const ERR_INTENT_NOT_FOUND = \"T402-7001\" as const;\nexport const ERR_INTENT_ALREADY_EXECUTED = \"T402-7002\" as const;\nexport const ERR_INTENT_CANCELLED = \"T402-7003\" as const;\nexport const ERR_INTENT_EXPIRED = \"T402-7004\" as const;\nexport const ERR_NO_ROUTES_AVAILABLE = \"T402-7005\" as const;\nexport const ERR_ROUTE_EXPIRED = \"T402-7006\" as const;\nexport const ERR_ROUTE_NOT_SELECTED = \"T402-7007\" as const;\nexport const ERR_INTENT_INVALID_STATE = \"T402-7008\" as const;\n\n// Discovery Errors (T402-8xxx): Resource marketplace issues\nexport const ERR_RESOURCE_NOT_FOUND = \"T402-8001\" as const;\nexport const ERR_RESOURCE_ALREADY_EXISTS = \"T402-8002\" as const;\nexport const ERR_INVALID_PARAMETERS = \"T402-8003\" as const;\nexport const ERR_NOT_AUTHORIZED = \"T402-8004\" as const;\n\n/** Union type of all T402 error codes */\nexport type ErrorCode =\n | typeof ERR_INVALID_REQUEST\n | typeof ERR_MISSING_PAYLOAD\n | typeof ERR_MISSING_REQUIREMENTS\n | typeof ERR_INVALID_PAYLOAD\n | typeof ERR_INVALID_REQUIREMENTS\n | typeof ERR_INVALID_SIGNATURE\n | typeof ERR_INVALID_NETWORK\n | typeof ERR_INVALID_SCHEME\n | typeof ERR_INVALID_AMOUNT\n | typeof ERR_INVALID_ADDRESS\n | typeof ERR_EXPIRED_PAYMENT\n | typeof ERR_INVALID_NONCE\n | typeof ERR_INSUFFICIENT_AMOUNT\n | typeof ERR_INVALID_IDEMPOTENCY_KEY\n | typeof ERR_SIGNATURE_EXPIRED\n | typeof ERR_INTERNAL\n | typeof ERR_DATABASE_UNAVAILABLE\n | typeof ERR_CACHE_UNAVAILABLE\n | typeof ERR_RPC_UNAVAILABLE\n | typeof ERR_RATE_LIMITED\n | typeof ERR_SERVICE_UNAVAILABLE\n | typeof ERR_VERIFICATION_FAILED\n | typeof ERR_SETTLEMENT_FAILED\n | typeof ERR_INSUFFICIENT_BALANCE\n | typeof ERR_ALLOWANCE_INSUFFICIENT\n | typeof ERR_PAYMENT_MISMATCH\n | typeof ERR_DUPLICATE_PAYMENT\n | typeof ERR_SETTLEMENT_PENDING\n | typeof ERR_SETTLEMENT_TIMEOUT\n | typeof ERR_NONCE_REPLAY\n | typeof ERR_IDEMPOTENCY_CONFLICT\n | typeof ERR_IDEMPOTENCY_UNAVAILABLE\n | typeof ERR_PREVIOUS_REQUEST_FAILED\n | typeof ERR_REQUEST_IN_PROGRESS\n | typeof ERR_CHAIN_UNAVAILABLE\n | typeof ERR_TRANSACTION_FAILED\n | typeof ERR_TRANSACTION_REVERTED\n | typeof ERR_GAS_ESTIMATION_FAILED\n | typeof ERR_NONCE_CONFLICT\n | typeof ERR_CHAIN_CONGESTED\n | typeof ERR_CONTRACT_ERROR\n | typeof ERR_BRIDGE_UNAVAILABLE\n | typeof ERR_BRIDGE_QUOTE_FAILED\n | typeof ERR_BRIDGE_TRANSFER_FAILED\n | typeof ERR_BRIDGE_TIMEOUT\n | typeof ERR_UNSUPPORTED_ROUTE\n | typeof ERR_STREAM_NOT_FOUND\n | typeof ERR_STREAM_ALREADY_CLOSED\n | typeof ERR_STREAM_ALREADY_PAUSED\n | typeof ERR_STREAM_NOT_PAUSED\n | typeof ERR_STREAM_AMOUNT_EXCEEDED\n | typeof ERR_STREAM_EXPIRED\n | typeof ERR_STREAM_INVALID_STATE\n | typeof ERR_STREAM_RATE_LIMITED\n | typeof ERR_INTENT_NOT_FOUND\n | typeof ERR_INTENT_ALREADY_EXECUTED\n | typeof ERR_INTENT_CANCELLED\n | typeof ERR_INTENT_EXPIRED\n | typeof ERR_NO_ROUTES_AVAILABLE\n | typeof ERR_ROUTE_EXPIRED\n | typeof ERR_ROUTE_NOT_SELECTED\n | typeof ERR_INTENT_INVALID_STATE\n | typeof ERR_RESOURCE_NOT_FOUND\n | typeof ERR_RESOURCE_ALREADY_EXISTS\n | typeof ERR_INVALID_PARAMETERS\n | typeof ERR_NOT_AUTHORIZED;\n\n/** Structured error response from the facilitator API */\nexport interface APIError {\n code: ErrorCode;\n message: string;\n details?: string;\n retry?: boolean;\n}\n\n/**\n * Returns the HTTP status code for a given error code\n *\n * @param code - The T402 error code\n * @returns The corresponding HTTP status code\n */\nexport function httpStatusForCode(code: ErrorCode): number {\n const category = code.charAt(5);\n switch (category) {\n case \"1\":\n return 400;\n case \"2\":\n if (code === ERR_RATE_LIMITED) return 429;\n return 500;\n case \"3\":\n if (code === ERR_VERIFICATION_FAILED || code === ERR_PAYMENT_MISMATCH) return 422;\n return 500;\n case \"4\":\n return 502;\n case \"5\":\n return 502;\n case \"6\":\n if (code === ERR_STREAM_NOT_FOUND) return 404;\n return 400;\n case \"7\":\n if (code === ERR_INTENT_NOT_FOUND) return 404;\n return 400;\n case \"8\":\n if (code === ERR_RESOURCE_NOT_FOUND) return 404;\n if (code === ERR_RESOURCE_ALREADY_EXISTS) return 409;\n if (code === ERR_NOT_AUTHORIZED) return 403;\n return 400;\n default:\n return 500;\n }\n}\n\n/**\n * Returns true if the error code is a client error (T402-1xxx)\n *\n * @param code - The T402 error code\n * @returns Whether the error is a client error\n */\nexport function isClientError(code: ErrorCode): boolean {\n return code.charAt(5) === \"1\";\n}\n\n/**\n * Returns true if the error code is a server error (T402-2xxx)\n *\n * @param code - The T402 error code\n * @returns Whether the error is a server error\n */\nexport function isServerError(code: ErrorCode): boolean {\n return code.charAt(5) === \"2\";\n}\n\n/**\n * Returns true if the error code is a facilitator error (T402-3xxx)\n *\n * @param code - The T402 error code\n * @returns Whether the error is a facilitator error\n */\nexport function isFacilitatorError(code: ErrorCode): boolean {\n return code.charAt(5) === \"3\";\n}\n\n/**\n * Returns true if the error code is a chain error (T402-4xxx)\n *\n * @param code - The T402 error code\n * @returns Whether the error is a chain error\n */\nexport function isChainError(code: ErrorCode): boolean {\n return code.charAt(5) === \"4\";\n}\n\n/**\n * Returns true if the error code is a bridge error (T402-5xxx)\n *\n * @param code - The T402 error code\n * @returns Whether the error is a bridge error\n */\nexport function isBridgeError(code: ErrorCode): boolean {\n return code.charAt(5) === \"5\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkPO,IAAM,yBAAyB;AAK/B,IAAM,wBAAwB;AAY9B,SAAS,kBAAkB,MAAwB;AACxD,SACE,KAAK,OAAO,UAAU,oBACtB,KAAK,OAAO,SAAS,WAAW,qBAAqB,MAAM;AAE/D;AAQO,SAAS,mBAAmB,MAAwB;AACzD,SACE,KAAK,OAAO,UAAU,eACtB,KAAK,OAAO,SAAS,WAAW,qBAAqB,MAAM;AAE/D;AAQO,SAAS,gBAAgB,MAAwB;AACtD,SACE,KAAK,OAAO,UAAU,YACtB,KAAK,OAAO,SAAS,WAAW,qBAAqB,MAAM;AAE/D;AAQO,SAAS,mBAAmB,MAA4C;AAC7E,MAAI,kBAAkB,IAAI,GAAG;AAC3B,WAAO,KAAK,OAAO,SAAS,WAAW,uBAAuB;AAAA,EAChE;AACA,SAAO;AACT;AAQO,SAAS,mBAAmB,MAA6C;AAC9E,SAAO,KAAK,OAAO,SAAS,WAAW,uBAAuB;AAChE;AASO,SAAS,6BACd,iBACA,OAAe,iDACH;AACZ,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,IACN,OAAO,CAAC,EAAE,MAAM,QAAQ,KAAK,CAAC;AAAA,IAC9B,UAAU;AAAA,MACR,uBAAuB;AAAA,MACvB,yBAAyB;AAAA,IAC3B;AAAA,EACF;AACF;AASO,SAAS,+BACd,gBACA,OAAe,sCACH;AACZ,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAA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V1, j as PaymentRequiredV1, k as PaymentRequirementsV1, l as SettleRequestV1, m as SettleResponseV1, n as SupportedResponseV1, o as VerifyRequestV1 } from '../../mechanisms-dYCiYgko.mjs';
|
|
2
|
+
import 'zod';
|
|
@@ -1,5 +1,32 @@
|
|
|
1
|
-
import { N as Network } from '../mechanisms-
|
|
1
|
+
import { N as Network } from '../mechanisms-dYCiYgko.mjs';
|
|
2
|
+
import 'zod';
|
|
2
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Generate a cryptographically secure random integer in range [0, max)
|
|
6
|
+
*
|
|
7
|
+
* Uses rejection sampling to ensure uniform distribution.
|
|
8
|
+
*
|
|
9
|
+
* @param max - Exclusive upper bound (must be > 0 and <= 2^32)
|
|
10
|
+
* @returns Random integer in [0, max)
|
|
11
|
+
* @throws Error if max is invalid or crypto unavailable
|
|
12
|
+
*/
|
|
13
|
+
declare function cryptoRandomInt(max: number): number;
|
|
14
|
+
/**
|
|
15
|
+
* Generate a cryptographically secure random BigInt
|
|
16
|
+
*
|
|
17
|
+
* @param bits - Number of bits (default 64, max 256)
|
|
18
|
+
* @returns Random BigInt with specified number of bits
|
|
19
|
+
* @throws Error if bits is invalid or crypto unavailable
|
|
20
|
+
*/
|
|
21
|
+
declare function cryptoRandomBigInt(bits?: number): bigint;
|
|
22
|
+
/**
|
|
23
|
+
* Generate a cryptographically secure random hex string
|
|
24
|
+
*
|
|
25
|
+
* @param bytes - Number of random bytes (default 16)
|
|
26
|
+
* @returns Hex-encoded random string
|
|
27
|
+
* @throws Error if bytes is invalid or crypto unavailable
|
|
28
|
+
*/
|
|
29
|
+
declare function cryptoRandomHex(bytes?: number): string;
|
|
3
30
|
/**
|
|
4
31
|
* Scheme data structure for facilitator storage
|
|
5
32
|
*/
|
|
@@ -45,4 +72,4 @@ declare function safeBase64Decode(data: string): string;
|
|
|
45
72
|
*/
|
|
46
73
|
declare function deepEqual(obj1: unknown, obj2: unknown): boolean;
|
|
47
74
|
|
|
48
|
-
export { Base64EncodedRegex, type SchemeData, deepEqual, findByNetworkAndScheme, findFacilitatorBySchemeAndNetwork, findSchemesByNetwork, safeBase64Decode, safeBase64Encode };
|
|
75
|
+
export { Base64EncodedRegex, type SchemeData, cryptoRandomBigInt, cryptoRandomHex, cryptoRandomInt, deepEqual, findByNetworkAndScheme, findFacilitatorBySchemeAndNetwork, findSchemesByNetwork, safeBase64Decode, safeBase64Encode };
|
package/dist/esm/utils/index.mjs
CHANGED
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
import {
|
|
2
2
|
Base64EncodedRegex,
|
|
3
|
+
cryptoRandomBigInt,
|
|
4
|
+
cryptoRandomHex,
|
|
5
|
+
cryptoRandomInt,
|
|
3
6
|
deepEqual,
|
|
4
7
|
findByNetworkAndScheme,
|
|
5
8
|
findFacilitatorBySchemeAndNetwork,
|
|
6
9
|
findSchemesByNetwork,
|
|
7
10
|
safeBase64Decode,
|
|
8
11
|
safeBase64Encode
|
|
9
|
-
} from "../chunk-
|
|
12
|
+
} from "../chunk-LJ4M5Z5U.mjs";
|
|
10
13
|
import "../chunk-4W2Y3RJM.mjs";
|
|
11
14
|
export {
|
|
12
15
|
Base64EncodedRegex,
|
|
16
|
+
cryptoRandomBigInt,
|
|
17
|
+
cryptoRandomHex,
|
|
18
|
+
cryptoRandomInt,
|
|
13
19
|
deepEqual,
|
|
14
20
|
findByNetworkAndScheme,
|
|
15
21
|
findFacilitatorBySchemeAndNetwork,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@t402/core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.0",
|
|
4
4
|
"main": "./dist/cjs/index.js",
|
|
5
5
|
"module": "./dist/esm/index.js",
|
|
6
6
|
"types": "./dist/cjs/index.d.ts",
|
|
@@ -10,21 +10,21 @@
|
|
|
10
10
|
"repository": "https://github.com/t402-io/t402",
|
|
11
11
|
"description": "t402 Payment Protocol",
|
|
12
12
|
"devDependencies": {
|
|
13
|
-
"@eslint/js": "^9.
|
|
14
|
-
"@types/node": "^
|
|
15
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
16
|
-
"@typescript-eslint/parser": "^8.
|
|
13
|
+
"@eslint/js": "^9.39.2",
|
|
14
|
+
"@types/node": "^25.2.2",
|
|
15
|
+
"@typescript-eslint/eslint-plugin": "^8.55.0",
|
|
16
|
+
"@typescript-eslint/parser": "^8.55.0",
|
|
17
17
|
"eslint": "^9.24.0",
|
|
18
18
|
"eslint-plugin-import": "^2.31.0",
|
|
19
|
-
"eslint-plugin-jsdoc": "^
|
|
20
|
-
"eslint-plugin-prettier": "^5.
|
|
19
|
+
"eslint-plugin-jsdoc": "^62.5.4",
|
|
20
|
+
"eslint-plugin-prettier": "^5.5.5",
|
|
21
21
|
"glob": "^13.0.0",
|
|
22
|
-
"prettier": "3.
|
|
23
|
-
"tsup": "^8.
|
|
22
|
+
"prettier": "3.8.1",
|
|
23
|
+
"tsup": "^8.5.1",
|
|
24
24
|
"tsx": "^4.21.0",
|
|
25
|
-
"typescript": "^5.
|
|
25
|
+
"typescript": "^5.9.3",
|
|
26
26
|
"vite": "^7.3.1",
|
|
27
|
-
"vite-tsconfig-paths": "^
|
|
27
|
+
"vite-tsconfig-paths": "^6.1.0",
|
|
28
28
|
"vitest": "^3.2.4"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
@@ -1,443 +0,0 @@
|
|
|
1
|
-
type PaymentRequirementsV1 = {
|
|
2
|
-
scheme: string;
|
|
3
|
-
network: Network;
|
|
4
|
-
maxAmountRequired: string;
|
|
5
|
-
resource: string;
|
|
6
|
-
description: string;
|
|
7
|
-
mimeType: string;
|
|
8
|
-
outputSchema: Record<string, unknown>;
|
|
9
|
-
payTo: string;
|
|
10
|
-
maxTimeoutSeconds: number;
|
|
11
|
-
asset: string;
|
|
12
|
-
extra: Record<string, unknown>;
|
|
13
|
-
};
|
|
14
|
-
type PaymentRequiredV1 = {
|
|
15
|
-
t402Version: 1;
|
|
16
|
-
error?: string;
|
|
17
|
-
accepts: PaymentRequirementsV1[];
|
|
18
|
-
};
|
|
19
|
-
type PaymentPayloadV1 = {
|
|
20
|
-
t402Version: 1;
|
|
21
|
-
scheme: string;
|
|
22
|
-
network: Network;
|
|
23
|
-
payload: Record<string, unknown>;
|
|
24
|
-
};
|
|
25
|
-
type VerifyRequestV1 = {
|
|
26
|
-
paymentPayload: PaymentPayloadV1;
|
|
27
|
-
paymentRequirements: PaymentRequirementsV1;
|
|
28
|
-
};
|
|
29
|
-
type SettleRequestV1 = {
|
|
30
|
-
paymentPayload: PaymentPayloadV1;
|
|
31
|
-
paymentRequirements: PaymentRequirementsV1;
|
|
32
|
-
};
|
|
33
|
-
type SettleResponseV1 = {
|
|
34
|
-
success: boolean;
|
|
35
|
-
errorReason?: string;
|
|
36
|
-
payer?: string;
|
|
37
|
-
transaction: string;
|
|
38
|
-
network: Network;
|
|
39
|
-
};
|
|
40
|
-
type SupportedResponseV1 = {
|
|
41
|
-
kinds: {
|
|
42
|
-
t402Version: number;
|
|
43
|
-
scheme: string;
|
|
44
|
-
network: Network;
|
|
45
|
-
extra?: Record<string, unknown>;
|
|
46
|
-
}[];
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
interface ResourceServerExtension {
|
|
50
|
-
key: string;
|
|
51
|
-
enrichDeclaration?: (declaration: unknown, transportContext: unknown) => unknown;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Up-To Scheme Types
|
|
56
|
-
*
|
|
57
|
-
* The `upto` scheme authorizes transfer of up to a maximum amount,
|
|
58
|
-
* enabling usage-based billing where the final settlement amount
|
|
59
|
-
* is determined by actual usage.
|
|
60
|
-
*
|
|
61
|
-
* @example
|
|
62
|
-
* ```typescript
|
|
63
|
-
* // Client authorizes up to $1.00
|
|
64
|
-
* const requirements: UptoPaymentRequirements = {
|
|
65
|
-
* scheme: 'upto',
|
|
66
|
-
* network: 'eip155:8453',
|
|
67
|
-
* maxAmount: '1000000', // $1.00 in USDC
|
|
68
|
-
* minAmount: '10000', // $0.01 minimum
|
|
69
|
-
* asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
|
|
70
|
-
* payTo: '0x...',
|
|
71
|
-
* maxTimeoutSeconds: 300,
|
|
72
|
-
* extra: {
|
|
73
|
-
* unit: 'token',
|
|
74
|
-
* unitPrice: '100',
|
|
75
|
-
* },
|
|
76
|
-
* };
|
|
77
|
-
*
|
|
78
|
-
* // Server settles for actual usage ($0.15)
|
|
79
|
-
* const settlement: UptoSettlement = {
|
|
80
|
-
* settleAmount: '150000',
|
|
81
|
-
* usageDetails: {
|
|
82
|
-
* tokensGenerated: 1500,
|
|
83
|
-
* unitPrice: '100',
|
|
84
|
-
* },
|
|
85
|
-
* };
|
|
86
|
-
* ```
|
|
87
|
-
*/
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Extended payment requirements for the upto scheme.
|
|
91
|
-
*/
|
|
92
|
-
interface UptoPaymentRequirements extends Omit<PaymentRequirements, "scheme" | "amount"> {
|
|
93
|
-
/** Scheme identifier - always 'upto' */
|
|
94
|
-
scheme: "upto";
|
|
95
|
-
/** Network identifier (CAIP-2 format) */
|
|
96
|
-
network: Network;
|
|
97
|
-
/** Maximum amount the client authorizes (in smallest denomination) */
|
|
98
|
-
maxAmount: string;
|
|
99
|
-
/** Minimum settlement amount (prevents dust payments) */
|
|
100
|
-
minAmount?: string;
|
|
101
|
-
/** Asset contract address or identifier */
|
|
102
|
-
asset: string;
|
|
103
|
-
/** Recipient address */
|
|
104
|
-
payTo: string;
|
|
105
|
-
/** Maximum time in seconds before payment expires */
|
|
106
|
-
maxTimeoutSeconds: number;
|
|
107
|
-
/** Additional scheme-specific data */
|
|
108
|
-
extra: UptoExtra;
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Extra fields specific to the upto scheme.
|
|
112
|
-
*/
|
|
113
|
-
interface UptoExtra extends Record<string, unknown> {
|
|
114
|
-
/** Billing unit (e.g., 'token', 'request', 'second', 'byte') */
|
|
115
|
-
unit?: string;
|
|
116
|
-
/** Price per unit in smallest denomination */
|
|
117
|
-
unitPrice?: string;
|
|
118
|
-
/** EIP-712 domain name (for EVM) */
|
|
119
|
-
name?: string;
|
|
120
|
-
/** EIP-712 domain version (for EVM) */
|
|
121
|
-
version?: string;
|
|
122
|
-
/** Router contract address (for EVM) */
|
|
123
|
-
routerAddress?: string;
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* Base payload structure for upto scheme.
|
|
127
|
-
*/
|
|
128
|
-
interface UptoPayloadBase {
|
|
129
|
-
/** Unique nonce to prevent replay attacks */
|
|
130
|
-
nonce: string;
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* EVM-specific upto payload using EIP-2612 Permit.
|
|
134
|
-
*/
|
|
135
|
-
interface UptoEvmPayload extends UptoPayloadBase {
|
|
136
|
-
/** EIP-2612 permit signature components */
|
|
137
|
-
signature: {
|
|
138
|
-
v: number;
|
|
139
|
-
r: `0x${string}`;
|
|
140
|
-
s: `0x${string}`;
|
|
141
|
-
};
|
|
142
|
-
/** Permit authorization parameters */
|
|
143
|
-
authorization: {
|
|
144
|
-
/** Token owner address */
|
|
145
|
-
owner: `0x${string}`;
|
|
146
|
-
/** Spender address (router contract) */
|
|
147
|
-
spender: `0x${string}`;
|
|
148
|
-
/** Maximum authorized value */
|
|
149
|
-
value: string;
|
|
150
|
-
/** Permit deadline (unix timestamp) */
|
|
151
|
-
deadline: string;
|
|
152
|
-
/** Permit nonce (from token contract) */
|
|
153
|
-
nonce: number;
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
|
-
* Alternative EVM payload with combined signature.
|
|
158
|
-
*/
|
|
159
|
-
interface UptoEvmPayloadCompact extends UptoPayloadBase {
|
|
160
|
-
/** Combined EIP-2612 permit signature */
|
|
161
|
-
signature: `0x${string}`;
|
|
162
|
-
/** Permit authorization parameters */
|
|
163
|
-
authorization: {
|
|
164
|
-
owner: `0x${string}`;
|
|
165
|
-
spender: `0x${string}`;
|
|
166
|
-
value: string;
|
|
167
|
-
deadline: string;
|
|
168
|
-
nonce: number;
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Settlement request for upto scheme.
|
|
173
|
-
*/
|
|
174
|
-
interface UptoSettlement {
|
|
175
|
-
/** Actual amount to settle (must be <= maxAmount) */
|
|
176
|
-
settleAmount: string;
|
|
177
|
-
/** Optional usage details for auditing */
|
|
178
|
-
usageDetails?: UptoUsageDetails;
|
|
179
|
-
}
|
|
180
|
-
/**
|
|
181
|
-
* Usage details for settlement auditing.
|
|
182
|
-
*/
|
|
183
|
-
interface UptoUsageDetails {
|
|
184
|
-
/** Number of units consumed */
|
|
185
|
-
unitsConsumed?: number;
|
|
186
|
-
/** Price per unit used */
|
|
187
|
-
unitPrice?: string;
|
|
188
|
-
/** Type of unit */
|
|
189
|
-
unitType?: string;
|
|
190
|
-
/** Start timestamp of usage period */
|
|
191
|
-
startTime?: number;
|
|
192
|
-
/** End timestamp of usage period */
|
|
193
|
-
endTime?: number;
|
|
194
|
-
/** Additional metadata */
|
|
195
|
-
metadata?: Record<string, unknown>;
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Settlement response for upto scheme.
|
|
199
|
-
*/
|
|
200
|
-
interface UptoSettlementResponse {
|
|
201
|
-
/** Whether settlement was successful */
|
|
202
|
-
success: boolean;
|
|
203
|
-
/** Transaction hash (if on-chain) */
|
|
204
|
-
transactionHash?: string;
|
|
205
|
-
/** Actual amount settled */
|
|
206
|
-
settledAmount: string;
|
|
207
|
-
/** Maximum amount that was authorized */
|
|
208
|
-
maxAmount: string;
|
|
209
|
-
/** Block number (if on-chain) */
|
|
210
|
-
blockNumber?: number;
|
|
211
|
-
/** Gas used (if on-chain) */
|
|
212
|
-
gasUsed?: string;
|
|
213
|
-
/** Error message if failed */
|
|
214
|
-
error?: string;
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Validation result for upto payment.
|
|
218
|
-
*/
|
|
219
|
-
interface UptoValidationResult {
|
|
220
|
-
/** Whether the payment is valid */
|
|
221
|
-
isValid: boolean;
|
|
222
|
-
/** Reason if invalid */
|
|
223
|
-
invalidReason?: string;
|
|
224
|
-
/** Validated maximum amount */
|
|
225
|
-
validatedMaxAmount?: string;
|
|
226
|
-
/** Payer address */
|
|
227
|
-
payer?: string;
|
|
228
|
-
/** Expiration timestamp */
|
|
229
|
-
expiresAt?: number;
|
|
230
|
-
}
|
|
231
|
-
/**
|
|
232
|
-
* Type guard for UptoPaymentRequirements.
|
|
233
|
-
*
|
|
234
|
-
* @param requirements - The value to check
|
|
235
|
-
* @returns True if the value is UptoPaymentRequirements
|
|
236
|
-
*/
|
|
237
|
-
declare function isUptoPaymentRequirements(requirements: unknown): requirements is UptoPaymentRequirements;
|
|
238
|
-
/**
|
|
239
|
-
* Type guard for UptoEvmPayload.
|
|
240
|
-
*
|
|
241
|
-
* @param payload - The value to check
|
|
242
|
-
* @returns True if the value is UptoEvmPayload
|
|
243
|
-
*/
|
|
244
|
-
declare function isUptoEvmPayload(payload: unknown): payload is UptoEvmPayload;
|
|
245
|
-
/**
|
|
246
|
-
* Constants for upto scheme.
|
|
247
|
-
*/
|
|
248
|
-
declare const UPTO_SCHEME: "upto";
|
|
249
|
-
declare const UPTO_DEFAULTS: {
|
|
250
|
-
/** Default minimum settlement amount (prevents dust) */
|
|
251
|
-
readonly MIN_AMOUNT: "1000";
|
|
252
|
-
/** Default maximum timeout in seconds (5 minutes) */
|
|
253
|
-
readonly MAX_TIMEOUT_SECONDS: 300;
|
|
254
|
-
/** Supported billing units */
|
|
255
|
-
readonly UNITS: readonly ["token", "request", "second", "minute", "byte", "kb", "mb"];
|
|
256
|
-
};
|
|
257
|
-
type UptoUnit = (typeof UPTO_DEFAULTS.UNITS)[number];
|
|
258
|
-
|
|
259
|
-
type Network = `${string}:${string}`;
|
|
260
|
-
type Money = string | number;
|
|
261
|
-
type AssetAmount = {
|
|
262
|
-
asset: string;
|
|
263
|
-
amount: string;
|
|
264
|
-
extra?: Record<string, unknown>;
|
|
265
|
-
};
|
|
266
|
-
type Price = Money | AssetAmount;
|
|
267
|
-
|
|
268
|
-
interface ResourceInfo {
|
|
269
|
-
url: string;
|
|
270
|
-
description?: string;
|
|
271
|
-
mimeType?: string;
|
|
272
|
-
}
|
|
273
|
-
type PaymentRequirements = {
|
|
274
|
-
scheme: string;
|
|
275
|
-
network: Network;
|
|
276
|
-
asset: string;
|
|
277
|
-
amount: string;
|
|
278
|
-
payTo: string;
|
|
279
|
-
maxTimeoutSeconds: number;
|
|
280
|
-
extra: Record<string, unknown>;
|
|
281
|
-
};
|
|
282
|
-
type PaymentRequired = {
|
|
283
|
-
t402Version: number;
|
|
284
|
-
error?: string;
|
|
285
|
-
resource: ResourceInfo;
|
|
286
|
-
accepts: PaymentRequirements[];
|
|
287
|
-
extensions?: Record<string, unknown>;
|
|
288
|
-
};
|
|
289
|
-
type PaymentPayload = {
|
|
290
|
-
t402Version: number;
|
|
291
|
-
resource?: ResourceInfo;
|
|
292
|
-
accepted: PaymentRequirements;
|
|
293
|
-
payload: Record<string, unknown>;
|
|
294
|
-
extensions?: Record<string, unknown>;
|
|
295
|
-
};
|
|
296
|
-
|
|
297
|
-
type VerifyRequest = {
|
|
298
|
-
paymentPayload: PaymentPayload;
|
|
299
|
-
paymentRequirements: PaymentRequirements;
|
|
300
|
-
};
|
|
301
|
-
type VerifyResponse = {
|
|
302
|
-
isValid: boolean;
|
|
303
|
-
invalidReason?: string;
|
|
304
|
-
payer?: string;
|
|
305
|
-
};
|
|
306
|
-
type SettleRequest = {
|
|
307
|
-
paymentPayload: PaymentPayload;
|
|
308
|
-
paymentRequirements: PaymentRequirements;
|
|
309
|
-
};
|
|
310
|
-
type SettleResponse = {
|
|
311
|
-
success: boolean;
|
|
312
|
-
errorReason?: string;
|
|
313
|
-
payer?: string;
|
|
314
|
-
transaction: string;
|
|
315
|
-
network: Network;
|
|
316
|
-
};
|
|
317
|
-
type SupportedKind = {
|
|
318
|
-
t402Version: number;
|
|
319
|
-
scheme: string;
|
|
320
|
-
network: Network;
|
|
321
|
-
extra?: Record<string, unknown>;
|
|
322
|
-
};
|
|
323
|
-
type SupportedResponse = {
|
|
324
|
-
kinds: SupportedKind[];
|
|
325
|
-
extensions: string[];
|
|
326
|
-
signers: Record<string, string[]>;
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
/**
|
|
330
|
-
* Money parser function that converts a numeric amount to an AssetAmount
|
|
331
|
-
* Receives the amount as a decimal number (e.g., 1.50 for $1.50)
|
|
332
|
-
* Returns null to indicate "cannot handle this amount", causing fallback to next parser
|
|
333
|
-
* Always returns a Promise for consistency - use async/await
|
|
334
|
-
*
|
|
335
|
-
* @param amount - The decimal amount (e.g., 1.50)
|
|
336
|
-
* @param network - The network identifier for context
|
|
337
|
-
* @returns AssetAmount or null to try next parser
|
|
338
|
-
*/
|
|
339
|
-
type MoneyParser = (amount: number, network: Network) => Promise<AssetAmount | null>;
|
|
340
|
-
interface SchemeNetworkClient {
|
|
341
|
-
readonly scheme: string;
|
|
342
|
-
createPaymentPayload(t402Version: number, paymentRequirements: PaymentRequirements): Promise<Pick<PaymentPayload, "t402Version" | "payload">>;
|
|
343
|
-
}
|
|
344
|
-
interface SchemeNetworkFacilitator {
|
|
345
|
-
readonly scheme: string;
|
|
346
|
-
/**
|
|
347
|
-
* CAIP family pattern that this facilitator supports.
|
|
348
|
-
* Used to group signers by blockchain family in the supported response.
|
|
349
|
-
*
|
|
350
|
-
* @example
|
|
351
|
-
* // EVM facilitators
|
|
352
|
-
* readonly caipFamily = "eip155:*";
|
|
353
|
-
*
|
|
354
|
-
* @example
|
|
355
|
-
* // SVM facilitators
|
|
356
|
-
* readonly caipFamily = "solana:*";
|
|
357
|
-
*/
|
|
358
|
-
readonly caipFamily: string;
|
|
359
|
-
/**
|
|
360
|
-
* Get mechanism-specific extra data needed for the supported kinds endpoint.
|
|
361
|
-
* This method is called when building the facilitator's supported response.
|
|
362
|
-
*
|
|
363
|
-
* @param network - The network identifier for context
|
|
364
|
-
* @returns Extra data object or undefined if no extra data is needed
|
|
365
|
-
*
|
|
366
|
-
* @example
|
|
367
|
-
* // EVM schemes return undefined (no extra data needed)
|
|
368
|
-
* getExtra(network: Network): undefined {
|
|
369
|
-
* return undefined;
|
|
370
|
-
* }
|
|
371
|
-
*
|
|
372
|
-
* @example
|
|
373
|
-
* // SVM schemes return feePayer address
|
|
374
|
-
* getExtra(network: Network): Record<string, unknown> | undefined {
|
|
375
|
-
* return { feePayer: this.signer.address };
|
|
376
|
-
* }
|
|
377
|
-
*/
|
|
378
|
-
getExtra(network: Network): Record<string, unknown> | undefined;
|
|
379
|
-
/**
|
|
380
|
-
* Get signer addresses used by this facilitator for a given network.
|
|
381
|
-
* These are included in the supported response to help clients understand
|
|
382
|
-
* which addresses might sign/pay for transactions.
|
|
383
|
-
*
|
|
384
|
-
* Supports multiple addresses for load balancing, key rotation, and high availability.
|
|
385
|
-
*
|
|
386
|
-
* @param network - The network identifier
|
|
387
|
-
* @returns Array of signer addresses (wallet addresses, fee payer addresses, etc.)
|
|
388
|
-
*
|
|
389
|
-
* @example
|
|
390
|
-
* // EVM facilitator
|
|
391
|
-
* getSigners(network: string): string[] {
|
|
392
|
-
* return [...this.signer.getAddresses()];
|
|
393
|
-
* }
|
|
394
|
-
*
|
|
395
|
-
* @example
|
|
396
|
-
* // SVM facilitator
|
|
397
|
-
* getSigners(network: string): string[] {
|
|
398
|
-
* return [...this.signer.getAddresses()];
|
|
399
|
-
* }
|
|
400
|
-
*/
|
|
401
|
-
getSigners(network: string): string[];
|
|
402
|
-
verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
|
|
403
|
-
settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;
|
|
404
|
-
}
|
|
405
|
-
interface SchemeNetworkServer {
|
|
406
|
-
readonly scheme: string;
|
|
407
|
-
/**
|
|
408
|
-
* Convert a user-friendly price to the scheme's specific amount and asset format
|
|
409
|
-
* Always returns a Promise for consistency
|
|
410
|
-
*
|
|
411
|
-
* @param price - User-friendly price (e.g., "$0.10", "0.10", { amount: "100000", asset: "USDC" })
|
|
412
|
-
* @param network - The network identifier for context
|
|
413
|
-
* @returns Promise that resolves to the converted amount, asset identifier, and any extra metadata
|
|
414
|
-
*
|
|
415
|
-
* @example
|
|
416
|
-
* // For EVM networks with USDC:
|
|
417
|
-
* await parsePrice("$0.10", "eip155:8453") => { amount: "100000", asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
|
|
418
|
-
*
|
|
419
|
-
* // For custom schemes:
|
|
420
|
-
* await parsePrice("10 points", "custom:network") => { amount: "10", asset: "points" }
|
|
421
|
-
*/
|
|
422
|
-
parsePrice(price: Price, network: Network): Promise<AssetAmount>;
|
|
423
|
-
/**
|
|
424
|
-
* Build payment requirements for this scheme/network combination
|
|
425
|
-
*
|
|
426
|
-
* @param paymentRequirements - Base payment requirements with amount/asset already set
|
|
427
|
-
* @param supportedKind - The supported kind from facilitator's /supported endpoint
|
|
428
|
-
* @param supportedKind.t402Version - The t402 version
|
|
429
|
-
* @param supportedKind.scheme - The payment scheme
|
|
430
|
-
* @param supportedKind.network - The network identifier
|
|
431
|
-
* @param supportedKind.extra - Optional extra metadata
|
|
432
|
-
* @param facilitatorExtensions - Extensions supported by the facilitator
|
|
433
|
-
* @returns Enhanced payment requirements ready to be sent to clients
|
|
434
|
-
*/
|
|
435
|
-
enhancePaymentRequirements(paymentRequirements: PaymentRequirements, supportedKind: {
|
|
436
|
-
t402Version: number;
|
|
437
|
-
scheme: string;
|
|
438
|
-
network: Network;
|
|
439
|
-
extra?: Record<string, unknown>;
|
|
440
|
-
}, facilitatorExtensions: string[]): Promise<PaymentRequirements>;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
export { type AssetAmount as A, type UptoUnit as B, isUptoPaymentRequirements as C, isUptoEvmPayload as D, UPTO_SCHEME as E, UPTO_DEFAULTS as F, type Money as M, type Network as N, type PaymentRequirements as P, type ResourceServerExtension as R, type SettleResponse as S, type UptoPaymentRequirements as U, type VerifyResponse as V, type PaymentPayload as a, type SchemeNetworkFacilitator as b, type PaymentRequired as c, type SchemeNetworkClient as d, type SupportedResponse as e, type SchemeNetworkServer as f, type SupportedKind as g, type Price as h, type PaymentRequirementsV1 as i, type PaymentRequiredV1 as j, type PaymentPayloadV1 as k, type VerifyRequestV1 as l, type SettleRequestV1 as m, type SettleResponseV1 as n, type SupportedResponseV1 as o, type VerifyRequest as p, type SettleRequest as q, type MoneyParser as r, type UptoExtra as s, type UptoPayloadBase as t, type UptoEvmPayload as u, type UptoEvmPayloadCompact as v, type UptoSettlement as w, type UptoUsageDetails as x, type UptoSettlementResponse as y, type UptoValidationResult as z };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["import { Network } from \"../types\";\n\n/**\n * Scheme data structure for facilitator storage\n */\nexport interface SchemeData<T> {\n facilitator: T;\n networks: Set<Network>;\n pattern: Network;\n}\n\nexport const findSchemesByNetwork = <T>(\n map: Map<string, Map<string, T>>,\n network: Network,\n): Map<string, T> | undefined => {\n // Direct match first\n let implementationsByScheme = map.get(network);\n\n if (!implementationsByScheme) {\n // Try pattern matching for registered network patterns\n for (const [registeredNetworkPattern, implementations] of map.entries()) {\n // Convert the registered network pattern to a regex\n // e.g., \"eip155:*\" becomes /^eip155:.*$/\n const pattern = registeredNetworkPattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") // Escape special regex chars except *\n .replace(/\\\\\\*/g, \".*\"); // Replace escaped * with .*\n\n const regex = new RegExp(`^${pattern}$`);\n\n if (regex.test(network)) {\n implementationsByScheme = implementations;\n break;\n }\n }\n }\n\n return implementationsByScheme;\n};\n\nexport const findByNetworkAndScheme = <T>(\n map: Map<string, Map<string, T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n return findSchemesByNetwork(map, network)?.get(scheme);\n};\n\n/**\n * Finds a facilitator by scheme and network using pattern matching.\n * Works with new SchemeData storage structure.\n *\n * @param schemeMap - Map of scheme names to SchemeData\n * @param scheme - The scheme to find\n * @param network - The network to match against\n * @returns The facilitator if found, undefined otherwise\n */\nexport const findFacilitatorBySchemeAndNetwork = <T>(\n schemeMap: Map<string, SchemeData<T>>,\n scheme: string,\n network: Network,\n): T | undefined => {\n const schemeData = schemeMap.get(scheme);\n if (!schemeData) return undefined;\n\n // Check if network is in the stored networks set\n if (schemeData.networks.has(network)) {\n return schemeData.facilitator;\n }\n\n // Try pattern matching\n const patternRegex = new RegExp(\"^\" + schemeData.pattern.replace(\"*\", \".*\") + \"$\");\n if (patternRegex.test(network)) {\n return schemeData.facilitator;\n }\n\n return undefined;\n};\n\nexport const Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * Encodes a string to base64 format\n *\n * @param data - The string to be encoded to base64\n * @returns The base64 encoded string\n */\nexport function safeBase64Encode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.btoa === \"function\") {\n return globalThis.btoa(data);\n }\n return Buffer.from(data).toString(\"base64\");\n}\n\n/**\n * Decodes a base64 string back to its original format\n *\n * @param data - The base64 encoded string to be decoded\n * @returns The decoded string in UTF-8 format\n */\nexport function safeBase64Decode(data: string): string {\n if (typeof globalThis !== \"undefined\" && typeof globalThis.atob === \"function\") {\n return globalThis.atob(data);\n }\n return Buffer.from(data, \"base64\").toString(\"utf-8\");\n}\n\n/**\n * Deep equality comparison for payment requirements\n * Uses a normalized JSON.stringify for consistent comparison\n *\n * @param obj1 - First object to compare\n * @param obj2 - Second object to compare\n * @returns True if objects are deeply equal\n */\nexport function deepEqual(obj1: unknown, obj2: unknown): boolean {\n // Normalize and stringify both objects for comparison\n // This handles nested objects, arrays, and different property orders\n const normalize = (obj: unknown): string => {\n // Handle primitives and null/undefined\n if (obj === null || obj === undefined) return JSON.stringify(obj);\n if (typeof obj !== \"object\") return JSON.stringify(obj);\n\n // Handle arrays\n if (Array.isArray(obj)) {\n return JSON.stringify(\n obj.map(item =>\n typeof item === \"object\" && item !== null ? JSON.parse(normalize(item)) : item,\n ),\n );\n }\n\n // Handle objects - sort keys and recursively normalize values\n const sorted: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach(key => {\n const value = (obj as Record<string, unknown>)[key];\n sorted[key] =\n typeof value === \"object\" && value !== null ? JSON.parse(normalize(value)) : value;\n });\n return JSON.stringify(sorted);\n };\n\n try {\n return normalize(obj1) === normalize(obj2);\n } catch {\n // Fallback to simple comparison if normalization fails\n return JSON.stringify(obj1) === JSON.stringify(obj2);\n }\n}\n"],"mappings":";AAWO,IAAM,uBAAuB,CAClC,KACA,YAC+B;AAE/B,MAAI,0BAA0B,IAAI,IAAI,OAAO;AAE7C,MAAI,CAAC,yBAAyB;AAE5B,eAAW,CAAC,0BAA0B,eAAe,KAAK,IAAI,QAAQ,GAAG;AAGvE,YAAM,UAAU,yBACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,YAAM,QAAQ,IAAI,OAAO,IAAI,OAAO,GAAG;AAEvC,UAAI,MAAM,KAAK,OAAO,GAAG;AACvB,kCAA0B;AAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,yBAAyB,CACpC,KACA,QACA,YACkB;AAClB,SAAO,qBAAqB,KAAK,OAAO,GAAG,IAAI,MAAM;AACvD;AAWO,IAAM,oCAAoC,CAC/C,WACA,QACA,YACkB;AAClB,QAAM,aAAa,UAAU,IAAI,MAAM;AACvC,MAAI,CAAC,WAAY,QAAO;AAGxB,MAAI,WAAW,SAAS,IAAI,OAAO,GAAG;AACpC,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,eAAe,IAAI,OAAO,MAAM,WAAW,QAAQ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