@veridex/agentic-payments 0.1.1-beta.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/MIGRATION.md +307 -0
  3. package/README.md +395 -0
  4. package/dist/index.d.mts +2327 -0
  5. package/dist/index.d.ts +2327 -0
  6. package/dist/index.js +5815 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/index.mjs +5759 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/examples/basic-agent.ts +126 -0
  11. package/examples/mcp-claude.ts +75 -0
  12. package/examples/ucp-checkout.ts +92 -0
  13. package/examples/x402-integration.ts +75 -0
  14. package/package.json +36 -0
  15. package/src/AgentWallet.ts +432 -0
  16. package/src/chains/AptosChainClient.ts +29 -0
  17. package/src/chains/ChainClient.ts +73 -0
  18. package/src/chains/ChainClientFactory.ts +113 -0
  19. package/src/chains/EVMChainClient.ts +39 -0
  20. package/src/chains/SolanaChainClient.ts +37 -0
  21. package/src/chains/StarknetChainClient.ts +36 -0
  22. package/src/chains/SuiChainClient.ts +28 -0
  23. package/src/index.ts +83 -0
  24. package/src/mcp/MCPServer.ts +73 -0
  25. package/src/mcp/schemas.ts +60 -0
  26. package/src/monitoring/AlertManager.ts +258 -0
  27. package/src/monitoring/AuditLogger.ts +86 -0
  28. package/src/monitoring/BalanceCache.ts +44 -0
  29. package/src/monitoring/ComplianceExporter.ts +52 -0
  30. package/src/oracle/PythFeeds.ts +60 -0
  31. package/src/oracle/PythOracle.ts +121 -0
  32. package/src/performance/ConnectionPool.ts +217 -0
  33. package/src/performance/NonceManager.ts +91 -0
  34. package/src/performance/ParallelRouteFinder.ts +438 -0
  35. package/src/performance/TransactionPoller.ts +201 -0
  36. package/src/performance/TransactionQueue.ts +565 -0
  37. package/src/performance/index.ts +46 -0
  38. package/src/react/hooks.ts +298 -0
  39. package/src/routing/BridgeOrchestrator.ts +18 -0
  40. package/src/routing/CrossChainRouter.ts +501 -0
  41. package/src/routing/DEXAggregator.ts +448 -0
  42. package/src/routing/FeeEstimator.ts +43 -0
  43. package/src/session/SessionKeyManager.ts +312 -0
  44. package/src/session/SessionStorage.ts +80 -0
  45. package/src/session/SpendingTracker.ts +71 -0
  46. package/src/types/agent.ts +105 -0
  47. package/src/types/errors.ts +115 -0
  48. package/src/types/mcp.ts +22 -0
  49. package/src/types/ucp.ts +47 -0
  50. package/src/types/x402.ts +170 -0
  51. package/src/ucp/CapabilityNegotiator.ts +44 -0
  52. package/src/ucp/CredentialProvider.ts +73 -0
  53. package/src/ucp/PaymentTokenizer.ts +169 -0
  54. package/src/ucp/TransportAdapter.ts +18 -0
  55. package/src/ucp/UCPClient.ts +143 -0
  56. package/src/x402/NonceManager.ts +26 -0
  57. package/src/x402/PaymentParser.ts +225 -0
  58. package/src/x402/PaymentSigner.ts +305 -0
  59. package/src/x402/X402Client.ts +364 -0
  60. package/src/x402/adapters/CronosFacilitatorAdapter.ts +109 -0
  61. package/tests/alerts.test.ts +208 -0
  62. package/tests/chains.test.ts +242 -0
  63. package/tests/integration.test.ts +315 -0
  64. package/tests/monitoring.test.ts +435 -0
  65. package/tests/performance.test.ts +303 -0
  66. package/tests/property.test.ts +186 -0
  67. package/tests/react-hooks.test.ts +262 -0
  68. package/tests/session.test.ts +376 -0
  69. package/tests/ucp.test.ts +253 -0
  70. package/tests/x402.test.ts +385 -0
  71. package/tsconfig.json +26 -0
  72. package/tsup.config.ts +10 -0
  73. package/vitest.config.ts +16 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,108 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@veridex/agentic-payments` will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-01-20
9
+
10
+ ### Added
11
+
12
+ #### Core Features
13
+ - **Session Key Management**
14
+ - `SessionKeyManager` for creating, validating, and revoking session keys
15
+ - `SpendingTracker` for daily and per-transaction limit enforcement
16
+ - `SessionStorage` for encrypted key persistence
17
+ - Support for 24-hour maximum session duration
18
+ - Automatic daily limit reset with rolling window
19
+
20
+ - **x402 Protocol Support**
21
+ - `X402Client` for automatic HTTP 402 payment handling
22
+ - `PaymentParser` for parsing payment requirement headers
23
+ - `PaymentSigner` with ERC-3009 support (transferWithAuthorization)
24
+ - `NonceManager` for client-side nonce tracking
25
+
26
+ - **UCP Integration**
27
+ - `UCPCredentialProvider` for Universal Credential Protocol support
28
+ - `CapabilityNegotiator` for capability intersection calculation
29
+ - `PaymentTokenizer` for generating and validating payment tokens
30
+ - Token refresh and revocation mechanisms
31
+
32
+ - **MCP Server**
33
+ - `MCPServer` for Model Context Protocol integration
34
+ - Tools: `veridex_create_session_key`, `veridex_pay`, `veridex_check_balance`, `veridex_revoke_session`, `veridex_get_payment_history`
35
+ - JSON Schema validation for all tool parameters
36
+
37
+ - **Multi-Chain Support**
38
+ - `ChainClientFactory` for creating chain-specific clients
39
+ - `EVMChainClient` - Base, Optimism, Arbitrum, Ethereum, Polygon, BSC, Avalanche
40
+ - `SolanaChainClient` - Solana mainnet and devnet
41
+ - `AptosChainClient` - Aptos mainnet and testnet
42
+ - `SuiChainClient` - Sui mainnet and testnet
43
+ - `StarknetChainClient` - Starknet mainnet and testnet
44
+
45
+ - **Oracle Integration**
46
+ - `PythOracle` for real-time price feeds via Hermes API
47
+ - `PythFeeds` registry for price feed IDs
48
+ - Support for ETH, SOL, APT, SUI, STRK native token pricing
49
+
50
+ - **Cross-Chain Routing**
51
+ - `CrossChainRouter` for finding optimal payment routes
52
+ - `FeeEstimator` for gas and bridge fee calculation
53
+ - `BridgeOrchestrator` for Wormhole integration
54
+
55
+ - **Monitoring & Compliance**
56
+ - `AuditLogger` for payment audit trails
57
+ - `AlertManager` with configurable spending thresholds
58
+ - High-value transaction approval workflow (5-minute window)
59
+ - Anomaly detection for unusual transaction patterns
60
+ - Webhook notifications for alerts
61
+ - `ComplianceExporter` for CSV/JSON export
62
+
63
+ - **Performance Optimizations**
64
+ - `NonceManager` - Client-side nonce tracking
65
+ - `TransactionQueue` - Batch transaction support
66
+ - `TransactionPoller` - 2-second confirmation polling
67
+ - `BalanceCache` - 10-second TTL caching
68
+
69
+ - **Error Handling**
70
+ - `AgentPaymentError` with structured error codes
71
+ - Remediation suggestions for all error types
72
+ - Retry flag for transient errors
73
+ - Exponential backoff (2s, 4s, 8s) for retries
74
+
75
+ - **React Hooks**
76
+ - `useAgentWallet` - Wallet state management
77
+ - `usePaymentHistory` - Transaction history with pagination
78
+ - `useSessionStatus` - Real-time session status
79
+
80
+ - **Developer Experience**
81
+ - Full TypeScript support with `.d.ts` generation
82
+ - Dual ESM/CJS builds
83
+ - Comprehensive README documentation
84
+ - Example files for all major use cases
85
+
86
+ ### Test Coverage
87
+ - 136 tests passing
88
+ - Property-based tests with fast-check
89
+ - Integration tests for full payment flows
90
+ - Unit tests for all modules
91
+
92
+ ### Dependencies
93
+ - `@veridex/sdk` - Core SDK integration
94
+ - `ethers` - EVM interactions
95
+ - `@solana/web3.js` - Solana interactions
96
+ - `axios` - HTTP client for Pyth oracle
97
+ - `zod` - Schema validation
98
+
99
+ ## [Unreleased]
100
+
101
+ ### Planned
102
+ - Connection pooling for HTTP requests
103
+ - Parallel route finding optimization
104
+ - React hooks unit tests
105
+ - Cross-browser testing
106
+ - Migration guide from `@veridex/sdk`
107
+ - DEX integration for token swapping
108
+ - Cross-chain recovery mechanisms
package/MIGRATION.md ADDED
@@ -0,0 +1,307 @@
1
+ # Migration Guide: @veridex/sdk to @veridex/agentic-payments
2
+
3
+ This guide helps you migrate from using `@veridex/sdk` directly to using `@veridex/agentic-payments` for agent-based payment workflows.
4
+
5
+ ## Overview
6
+
7
+ `@veridex/agentic-payments` is built on top of `@veridex/sdk` and provides:
8
+ - **Session key management** with spending limits
9
+ - **Automatic x402 payment handling**
10
+ - **UCP credential provider** for payment tokenization
11
+ - **MCP server** for LLM integration
12
+ - **Multi-chain support** with unified interface
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ # Remove direct @veridex/sdk usage (if only used for payments)
18
+ npm uninstall @veridex/sdk
19
+
20
+ # Install the agentic payments SDK
21
+ npm install @veridex/agentic-payments
22
+ ```
23
+
24
+ > Note: `@veridex/agentic-payments` includes `@veridex/sdk` as a dependency, so you still have access to core SDK features.
25
+
26
+ ## Key Differences
27
+
28
+ | Feature | @veridex/sdk | @veridex/agentic-payments |
29
+ |---------|-------------|---------------------------|
30
+ | Authentication | Direct passkey | Session keys with limits |
31
+ | Payments | Manual signing | Automatic with retry |
32
+ | Multi-chain | Chain-specific clients | Unified interface |
33
+ | x402 | Manual handling | Automatic interception |
34
+ | Monitoring | None | Audit logging, alerts |
35
+
36
+ ## Migration Steps
37
+
38
+ ### 1. Replace Direct Wallet Usage
39
+
40
+ **Before (with @veridex/sdk):**
41
+
42
+ ```typescript
43
+ import { VeridexSDK } from '@veridex/sdk';
44
+
45
+ const sdk = await VeridexSDK.create({
46
+ chainPreset: 'base',
47
+ networkType: 'mainnet',
48
+ });
49
+
50
+ // Direct signing with master key
51
+ const tx = await sdk.hub.executePayment({
52
+ recipient: '0x...',
53
+ amount: '10000000', // 10 USDC
54
+ token: '0x...',
55
+ });
56
+ ```
57
+
58
+ **After (with @veridex/agentic-payments):**
59
+
60
+ ```typescript
61
+ import { createAgentWallet } from '@veridex/agentic-payments';
62
+
63
+ const agent = await createAgentWallet({
64
+ masterCredential: {
65
+ credentialId: 'your-passkey-credential',
66
+ publicKeyX: BigInt('...'),
67
+ publicKeyY: BigInt('...'),
68
+ keyHash: '0x...',
69
+ },
70
+ session: {
71
+ dailyLimitUSD: 100,
72
+ perTransactionLimitUSD: 25,
73
+ expiryHours: 8,
74
+ allowedChains: [30], // Base
75
+ },
76
+ });
77
+
78
+ // Payment with automatic limit checking
79
+ const receipt = await agent.pay({
80
+ recipient: '0x...',
81
+ amount: '10.00',
82
+ token: 'USDC',
83
+ chain: 30,
84
+ });
85
+ ```
86
+
87
+ ### 2. Replace Manual x402 Handling
88
+
89
+ **Before:**
90
+
91
+ ```typescript
92
+ async function fetchWithPayment(url: string) {
93
+ let response = await fetch(url);
94
+
95
+ if (response.status === 402) {
96
+ const paymentHeader = response.headers.get('X-Payment-Required');
97
+ const parsed = JSON.parse(atob(paymentHeader));
98
+
99
+ // Manual payment logic
100
+ const tx = await sdk.hub.executePayment({
101
+ recipient: parsed.recipient,
102
+ amount: parsed.amount,
103
+ token: parsed.token,
104
+ });
105
+
106
+ // Retry with proof
107
+ response = await fetch(url, {
108
+ headers: {
109
+ 'X-Payment-Proof': tx.hash,
110
+ },
111
+ });
112
+ }
113
+
114
+ return response;
115
+ }
116
+ ```
117
+
118
+ **After:**
119
+
120
+ ```typescript
121
+ // Automatic handling built-in
122
+ const response = await agent.fetch('https://api.paid-service.com/resource');
123
+ // Payment automatically handled on 402 response
124
+ ```
125
+
126
+ ### 3. Replace Chain-Specific Clients
127
+
128
+ **Before:**
129
+
130
+ ```typescript
131
+ import { EVMClient } from '@veridex/sdk/chains/evm';
132
+ import { SolanaClient } from '@veridex/sdk/chains/solana';
133
+
134
+ const evmClient = new EVMClient({ /* config */ });
135
+ const solanaClient = new SolanaClient({ /* config */ });
136
+
137
+ // Different APIs for each chain
138
+ const evmBalance = await evmClient.getBalance();
139
+ const solBalance = await solanaClient.getBalance();
140
+ ```
141
+
142
+ **After:**
143
+
144
+ ```typescript
145
+ import { ChainClientFactory } from '@veridex/agentic-payments';
146
+
147
+ // Unified interface
148
+ const baseClient = ChainClientFactory.createClient('base', 'mainnet');
149
+ const solanaClient = ChainClientFactory.createClient('solana', 'mainnet');
150
+
151
+ // Same API for all chains
152
+ const baseBalance = await baseClient.getBalance(address);
153
+ const solBalance = await solanaClient.getBalance(address);
154
+
155
+ // Or use multi-chain balance
156
+ const allBalances = await agent.getMultiChainBalance();
157
+ ```
158
+
159
+ ### 4. Add Session Management
160
+
161
+ Sessions are a new concept in `@veridex/agentic-payments`:
162
+
163
+ ```typescript
164
+ // Check session status
165
+ const status = agent.getSessionStatus();
166
+ console.log(`Remaining: $${status.remainingDailyLimitUSD}`);
167
+ console.log(`Expires: ${new Date(status.expiresAt)}`);
168
+
169
+ // Revoke session (requires master key)
170
+ await agent.revokeSession();
171
+ ```
172
+
173
+ ### 5. Add Monitoring
174
+
175
+ **New features not available in @veridex/sdk:**
176
+
177
+ ```typescript
178
+ // Subscribe to spending alerts
179
+ agent.onSpendingAlert((alert) => {
180
+ console.log(`Alert: ${alert.type} - ${alert.message}`);
181
+ });
182
+
183
+ // Get payment history
184
+ const history = await agent.getPaymentHistory({
185
+ limit: 50,
186
+ chain: 30,
187
+ });
188
+
189
+ // Export audit logs
190
+ const csv = await agent.exportAuditLog('csv');
191
+ ```
192
+
193
+ ## React Migration
194
+
195
+ ### Before (manual state management):
196
+
197
+ ```typescript
198
+ import { useState, useEffect } from 'react';
199
+ import { VeridexSDK } from '@veridex/sdk';
200
+
201
+ function PaymentComponent() {
202
+ const [sdk, setSdk] = useState(null);
203
+
204
+ useEffect(() => {
205
+ VeridexSDK.create(config).then(setSdk);
206
+ }, []);
207
+
208
+ // Manual state management...
209
+ }
210
+ ```
211
+
212
+ ### After (with hooks):
213
+
214
+ ```typescript
215
+ import { useAgentWallet, useSessionStatus, usePaymentHistory } from '@veridex/agentic-payments';
216
+
217
+ function PaymentComponent() {
218
+ const { wallet, isLoading, error } = useAgentWallet(config);
219
+ const { status } = useSessionStatus(wallet);
220
+ const { history } = usePaymentHistory(wallet);
221
+
222
+ return (
223
+ <div>
224
+ <p>Remaining: ${status?.remainingDailyLimitUSD}</p>
225
+ <button onClick={() => wallet?.pay(params)}>Pay</button>
226
+ </div>
227
+ );
228
+ }
229
+ ```
230
+
231
+ ## API Changes Summary
232
+
233
+ ### Imports
234
+
235
+ ```typescript
236
+ // Before
237
+ import { VeridexSDK, EVMClient } from '@veridex/sdk';
238
+
239
+ // After
240
+ import {
241
+ createAgentWallet,
242
+ ChainClientFactory,
243
+ SessionKeyManager,
244
+ X402Client,
245
+ } from '@veridex/agentic-payments';
246
+ ```
247
+
248
+ ### Payment Parameters
249
+
250
+ ```typescript
251
+ // Before
252
+ await sdk.hub.executePayment({
253
+ recipient: '0x...',
254
+ amount: '10000000', // Raw units
255
+ token: '0x...', // Address
256
+ });
257
+
258
+ // After
259
+ await agent.pay({
260
+ recipient: '0x...',
261
+ amount: '10.00', // Human-readable
262
+ token: 'USDC', // Symbol
263
+ chain: 30, // Chain ID
264
+ });
265
+ ```
266
+
267
+ ### Error Handling
268
+
269
+ ```typescript
270
+ // Before - generic errors
271
+ try {
272
+ await sdk.hub.executePayment(params);
273
+ } catch (error) {
274
+ console.error(error.message);
275
+ }
276
+
277
+ // After - structured errors with remediation
278
+ import { AgentPaymentError } from '@veridex/agentic-payments';
279
+
280
+ try {
281
+ await agent.pay(params);
282
+ } catch (error) {
283
+ if (error instanceof AgentPaymentError) {
284
+ console.log(`Code: ${error.code}`);
285
+ console.log(`Fix: ${error.remediation}`);
286
+ console.log(`Retryable: ${error.retryable}`);
287
+ }
288
+ }
289
+ ```
290
+
291
+ ## Accessing Core SDK
292
+
293
+ If you need access to the underlying SDK for advanced use cases:
294
+
295
+ ```typescript
296
+ // The core SDK is re-exported
297
+ import { VeridexSDK, EVMClient } from '@veridex/agentic-payments';
298
+
299
+ // Or access via the agent wallet
300
+ const coreClient = agent.getChainClient(30);
301
+ ```
302
+
303
+ ## Need Help?
304
+
305
+ - [Full API Documentation](https://docs.veridex.network/agentic-payments)
306
+ - [GitHub Issues](https://github.com/veridex/agent-payments/issues)
307
+ - [Discord Community](https://discord.gg/veridex)