@voyage_ai/v402-web-ts 0.1.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/README.md ADDED
@@ -0,0 +1 @@
1
+ # v402-web-ts
@@ -0,0 +1,523 @@
1
+ import { PaymentRequirements } from 'x402/types';
2
+ export { ExactEvmPayload, ExactSvmPayload, PaymentRequirements, SPLTokenAmount, SettleResponse, VerifyResponse, x402Response } from 'x402/types';
3
+ import { VersionedTransaction } from '@solana/web3.js';
4
+ import { z } from 'zod';
5
+
6
+ /**
7
+ * Common types for x402 SDK
8
+ * Framework-agnostic types that work across different wallet implementations
9
+ */
10
+
11
+ /**
12
+ * Generic wallet adapter interface - works with any wallet provider
13
+ * Compatible with Anza wallet-adapter, Privy, and custom implementations
14
+ */
15
+ interface WalletAdapter {
16
+ publicKey?: {
17
+ toString(): string;
18
+ };
19
+ address?: string;
20
+ signTransaction: (tx: VersionedTransaction) => Promise<VersionedTransaction>;
21
+ }
22
+ /**
23
+ * EVM wallet adapter interface
24
+ */
25
+ interface EvmWalletAdapter {
26
+ address: string;
27
+ signTypedData: (domain: any, types: any, message: any) => Promise<string>;
28
+ switchChain?: (chainId: string) => Promise<void>;
29
+ }
30
+ /**
31
+ * Network type enum - for wallet detection
32
+ */
33
+ declare enum NetworkType {
34
+ EVM = "evm",
35
+ SOLANA = "solana",
36
+ SVM = "svm",// Alias for Solana
37
+ UNKNOWN = "unknown"
38
+ }
39
+
40
+ /**
41
+ * SVM (Solana) specific types
42
+ * Uses x402 official types as base
43
+ */
44
+
45
+ /**
46
+ * Solana network enum
47
+ */
48
+ declare const SolanaNetworkSchema: z.ZodEnum<["solana-devnet", "solana", "solana-mainnet"]>;
49
+ type SolanaNetwork = z.infer<typeof SolanaNetworkSchema>;
50
+ /**
51
+ * Solana payment payload schema (conforms to x402 spec)
52
+ */
53
+ declare const SolanaPaymentPayloadSchema: z.ZodObject<{
54
+ x402Version: z.ZodLiteral<1>;
55
+ scheme: z.ZodLiteral<"exact">;
56
+ network: z.ZodEnum<["solana-devnet", "solana", "solana-mainnet"]>;
57
+ payload: z.ZodObject<{
58
+ transaction: z.ZodString;
59
+ }, "strip", z.ZodTypeAny, {
60
+ transaction: string;
61
+ }, {
62
+ transaction: string;
63
+ }>;
64
+ }, "strip", z.ZodTypeAny, {
65
+ x402Version: 1;
66
+ scheme: "exact";
67
+ network: "solana" | "solana-devnet" | "solana-mainnet";
68
+ payload: {
69
+ transaction: string;
70
+ };
71
+ }, {
72
+ x402Version: 1;
73
+ scheme: "exact";
74
+ network: "solana" | "solana-devnet" | "solana-mainnet";
75
+ payload: {
76
+ transaction: string;
77
+ };
78
+ }>;
79
+ type SolanaPaymentPayload = z.infer<typeof SolanaPaymentPayloadSchema>;
80
+ /**
81
+ * Configuration for Solana payment client
82
+ */
83
+ interface SvmClientConfig {
84
+ wallet: WalletAdapter;
85
+ network: SolanaNetwork;
86
+ rpcUrl?: string;
87
+ maxPaymentAmount?: bigint;
88
+ }
89
+ /**
90
+ * Configuration for creating Solana payment header
91
+ */
92
+ interface CreateSvmPaymentHeaderParams {
93
+ wallet: WalletAdapter;
94
+ paymentRequirements: PaymentRequirements;
95
+ x402Version: number;
96
+ rpcUrl: string;
97
+ }
98
+
99
+ /**
100
+ * EVM specific types
101
+ * Uses x402 official types as base
102
+ */
103
+
104
+ /**
105
+ * EVM network enum (common networks)
106
+ */
107
+ declare const EvmNetworkSchema: z.ZodEnum<["ethereum", "sepolia", "base", "base-sepolia", "polygon", "arbitrum", "optimism"]>;
108
+ type EvmNetwork = z.infer<typeof EvmNetworkSchema>;
109
+ /**
110
+ * EVM payment payload schema (conforms to x402 spec)
111
+ */
112
+ declare const EvmPaymentPayloadSchema: z.ZodObject<{
113
+ x402Version: z.ZodLiteral<1>;
114
+ scheme: z.ZodLiteral<"exact">;
115
+ network: z.ZodEnum<["ethereum", "sepolia", "base", "base-sepolia", "polygon", "arbitrum", "optimism"]>;
116
+ payload: z.ZodObject<{
117
+ signature: z.ZodString;
118
+ authorization: z.ZodObject<{
119
+ from: z.ZodString;
120
+ to: z.ZodString;
121
+ value: z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>;
122
+ validAfter: z.ZodEffects<z.ZodString, string, string>;
123
+ validBefore: z.ZodEffects<z.ZodString, string, string>;
124
+ nonce: z.ZodString;
125
+ }, "strip", z.ZodTypeAny, {
126
+ from: string;
127
+ to: string;
128
+ value: string;
129
+ validAfter: string;
130
+ validBefore: string;
131
+ nonce: string;
132
+ }, {
133
+ from: string;
134
+ to: string;
135
+ value: string;
136
+ validAfter: string;
137
+ validBefore: string;
138
+ nonce: string;
139
+ }>;
140
+ }, "strip", z.ZodTypeAny, {
141
+ signature: string;
142
+ authorization: {
143
+ from: string;
144
+ to: string;
145
+ value: string;
146
+ validAfter: string;
147
+ validBefore: string;
148
+ nonce: string;
149
+ };
150
+ }, {
151
+ signature: string;
152
+ authorization: {
153
+ from: string;
154
+ to: string;
155
+ value: string;
156
+ validAfter: string;
157
+ validBefore: string;
158
+ nonce: string;
159
+ };
160
+ }>;
161
+ }, "strip", z.ZodTypeAny, {
162
+ x402Version: 1;
163
+ scheme: "exact";
164
+ network: "ethereum" | "sepolia" | "base" | "base-sepolia" | "polygon" | "arbitrum" | "optimism";
165
+ payload: {
166
+ signature: string;
167
+ authorization: {
168
+ from: string;
169
+ to: string;
170
+ value: string;
171
+ validAfter: string;
172
+ validBefore: string;
173
+ nonce: string;
174
+ };
175
+ };
176
+ }, {
177
+ x402Version: 1;
178
+ scheme: "exact";
179
+ network: "ethereum" | "sepolia" | "base" | "base-sepolia" | "polygon" | "arbitrum" | "optimism";
180
+ payload: {
181
+ signature: string;
182
+ authorization: {
183
+ from: string;
184
+ to: string;
185
+ value: string;
186
+ validAfter: string;
187
+ validBefore: string;
188
+ nonce: string;
189
+ };
190
+ };
191
+ }>;
192
+ type EvmPaymentPayload = z.infer<typeof EvmPaymentPayloadSchema>;
193
+ /**
194
+ * Configuration for EVM payment client
195
+ */
196
+ interface EvmClientConfig {
197
+ wallet: EvmWalletAdapter;
198
+ network: EvmNetwork;
199
+ maxPaymentAmount?: bigint;
200
+ }
201
+ /**
202
+ * Configuration for creating EVM payment header
203
+ */
204
+ interface CreateEvmPaymentHeaderParams {
205
+ wallet: EvmWalletAdapter;
206
+ paymentRequirements: PaymentRequirements;
207
+ x402Version: number;
208
+ chainId: number;
209
+ }
210
+ /**
211
+ * Network configuration for EVM chains
212
+ */
213
+ interface EvmNetworkConfig {
214
+ chainId: string;
215
+ chainName: string;
216
+ rpcUrls: string[];
217
+ nativeCurrency: {
218
+ name: string;
219
+ symbol: string;
220
+ decimals: number;
221
+ };
222
+ }
223
+ /**
224
+ * Common EVM network configurations
225
+ */
226
+ declare const EVM_NETWORK_CONFIGS: Record<string, EvmNetworkConfig>;
227
+ /**
228
+ * Get chain ID from network name
229
+ */
230
+ declare function getChainId(network: string): number;
231
+
232
+ /**
233
+ * SVM (Solana) Payment Header Builder
234
+ *
235
+ * Low-level API: Creates X-PAYMENT header for Solana transactions
236
+ * Use this when you want to build the payment header yourself and handle fetch separately
237
+ */
238
+
239
+ /**
240
+ * Create X-PAYMENT header for Solana payment
241
+ *
242
+ * @param params - Payment header parameters
243
+ * @returns Base64-encoded X-PAYMENT header string
244
+ *
245
+ * @example
246
+ * ```typescript
247
+ * const paymentHeader = await createSvmPaymentHeader({
248
+ * wallet: phantomWallet,
249
+ * paymentRequirements: requirements,
250
+ * x402Version: 1,
251
+ * rpcUrl: "https://api.devnet.solana.com"
252
+ * });
253
+ *
254
+ * // Use the header in your own fetch
255
+ * const response = await fetch(endpoint, {
256
+ * headers: {
257
+ * "X-PAYMENT": paymentHeader
258
+ * }
259
+ * });
260
+ * ```
261
+ */
262
+ declare function createSvmPaymentHeader(params: CreateSvmPaymentHeaderParams): Promise<string>;
263
+ /**
264
+ * Helper: Get default RPC URL for Solana network
265
+ */
266
+ declare function getDefaultSolanaRpcUrl(network: string): string;
267
+
268
+ /**
269
+ * SVM (Solana) Payment Handler
270
+ *
271
+ * High-level API: Automatically handles the full payment flow
272
+ * Use this for the simplest integration - just provide wallet and endpoint
273
+ */
274
+
275
+ /**
276
+ * Handle SVM payment with automatic x402 flow
277
+ *
278
+ * @param endpoint - API endpoint that requires x402 payment
279
+ * @param config - SVM client configuration
280
+ * @param requestInit - Optional fetch RequestInit options
281
+ * @returns Response from the endpoint after successful payment
282
+ *
283
+ * @example
284
+ * ```typescript
285
+ * // Simple usage with Phantom wallet
286
+ * const response = await handleSvmPayment(
287
+ * "https://api.example.com/protected",
288
+ * {
289
+ * wallet: window.solana,
290
+ * network: "solana-devnet"
291
+ * }
292
+ * );
293
+ * const data = await response.json();
294
+ * ```
295
+ */
296
+ declare function handleSvmPayment(endpoint: string, config: SvmClientConfig, requestInit?: RequestInit): Promise<Response>;
297
+ /**
298
+ * Create a custom fetch function that automatically handles x402 payments for SVM
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * const paymentFetch = createSvmPaymentFetch({
303
+ * wallet: window.solana,
304
+ * network: "solana-devnet",
305
+ * maxPaymentAmount: BigInt(1_000_000) // 1 USDC max
306
+ * });
307
+ *
308
+ * // Use like regular fetch
309
+ * const response = await paymentFetch("https://api.example.com/protected");
310
+ * ```
311
+ */
312
+ declare function createSvmPaymentFetch(config: SvmClientConfig): typeof fetch;
313
+
314
+ /**
315
+ * EVM Payment Header Builder
316
+ *
317
+ * Low-level API: Creates X-PAYMENT header for EVM transactions
318
+ * Use this when you want to build the payment header yourself and handle fetch separately
319
+ */
320
+
321
+ /**
322
+ * Create X-PAYMENT header for EVM payment (EIP-3009 format)
323
+ *
324
+ * @param params - Payment header parameters
325
+ * @returns Base64-encoded X-PAYMENT header string
326
+ *
327
+ * @example
328
+ * ```typescript
329
+ * const paymentHeader = await createEvmPaymentHeader({
330
+ * wallet: metamaskWallet,
331
+ * paymentRequirements: requirements,
332
+ * x402Version: 1,
333
+ * chainId: 84532
334
+ * });
335
+ *
336
+ * // Use the header in your own fetch
337
+ * const response = await fetch(endpoint, {
338
+ * headers: {
339
+ * "X-PAYMENT": paymentHeader
340
+ * }
341
+ * });
342
+ * ```
343
+ */
344
+ declare function createEvmPaymentHeader(params: CreateEvmPaymentHeaderParams): Promise<string>;
345
+ /**
346
+ * Get chain ID from network name
347
+ */
348
+ declare function getChainIdFromNetwork(network: string): number;
349
+
350
+ /**
351
+ * EVM Payment Handler
352
+ *
353
+ * High-level API: Automatically handles the full payment flow
354
+ * Use this for the simplest integration - just provide wallet and endpoint
355
+ */
356
+
357
+ /**
358
+ * Handle EVM payment with automatic x402 flow
359
+ *
360
+ * @param endpoint - API endpoint that requires x402 payment
361
+ * @param config - EVM client configuration
362
+ * @param requestInit - Optional fetch RequestInit options
363
+ * @returns Response from the endpoint after successful payment
364
+ *
365
+ * @example
366
+ * ```typescript
367
+ * // Simple usage with MetaMask
368
+ * const provider = new ethers.BrowserProvider(window.ethereum);
369
+ * const signer = await provider.getSigner();
370
+ *
371
+ * const response = await handleEvmPayment(
372
+ * "https://api.example.com/protected",
373
+ * {
374
+ * wallet: {
375
+ * address: await signer.getAddress(),
376
+ * signTypedData: (domain, types, message) =>
377
+ * signer.signTypedData(domain, types, message)
378
+ * },
379
+ * network: "base-sepolia"
380
+ * }
381
+ * );
382
+ * ```
383
+ */
384
+ declare function handleEvmPayment(endpoint: string, config: EvmClientConfig, requestInit?: RequestInit): Promise<Response>;
385
+ /**
386
+ * Create a custom fetch function that automatically handles x402 payments for EVM
387
+ *
388
+ * @example
389
+ * ```typescript
390
+ * const paymentFetch = createEvmPaymentFetch({
391
+ * wallet: myWallet,
392
+ * network: "base-sepolia",
393
+ * maxPaymentAmount: BigInt(1_000_000) // 1 USDC max
394
+ * });
395
+ *
396
+ * // Use like regular fetch
397
+ * const response = await paymentFetch("https://api.example.com/protected");
398
+ * ```
399
+ */
400
+ declare function createEvmPaymentFetch(config: EvmClientConfig): typeof fetch;
401
+
402
+ /**
403
+ * Wallet utilities
404
+ *
405
+ * Generic wallet connection and management utilities
406
+ * Framework-agnostic and chain-agnostic
407
+ */
408
+
409
+ /**
410
+ * Check if a wallet is installed for a specific network type
411
+ */
412
+ declare function isWalletInstalled(networkType: NetworkType): boolean;
413
+ /**
414
+ * Get wallet provider for a network type
415
+ */
416
+ declare function getWalletProvider(networkType: NetworkType): any;
417
+ /**
418
+ * Format wallet address for display (show first 6 and last 4 characters)
419
+ */
420
+ declare function formatAddress(address: string): string;
421
+ /**
422
+ * Get wallet install URL
423
+ */
424
+ declare function getWalletInstallUrl(networkType: NetworkType): string;
425
+ /**
426
+ * Get wallet display name
427
+ */
428
+ declare function getWalletDisplayName(networkType: NetworkType): string;
429
+
430
+ /**
431
+ * Payment helper utilities for demo/UI
432
+ * Simplified payment handling with callbacks
433
+ */
434
+
435
+ /**
436
+ * Make payment with automatic chain handling
437
+ *
438
+ * This function handles all the chain-specific logic internally.
439
+ * Business logic should be handled via callbacks.
440
+ *
441
+ * @param endpoint - API endpoint
442
+ * @param networkType - Network type (from useWallet)
443
+ * @param merchantId - @see our website to apply
444
+ * @returns Response from the payment
445
+ *
446
+ * @example
447
+ * ```tsx
448
+ * const response = await makePayment('/api/endpoint', networkType);
449
+ * const data = await response.json();
450
+ * ```
451
+ */
452
+ declare function makePayment(networkType: NetworkType, merchantId: string, endpoint?: string): Promise<Response>;
453
+
454
+ /**
455
+ * Network utilities
456
+ *
457
+ * Helper functions for network detection and validation
458
+ */
459
+
460
+ /**
461
+ * Get network type from network name
462
+ */
463
+ declare function getNetworkType(network: string): NetworkType;
464
+ /**
465
+ * Check if network is EVM-based
466
+ */
467
+ declare function isEvmNetwork(network: string): boolean;
468
+ /**
469
+ * Check if network is Solana-based
470
+ */
471
+ declare function isSolanaNetwork(network: string): boolean;
472
+ /**
473
+ * Validate Solana address format (base58)
474
+ */
475
+ declare function isSolanaAddress(address: string): boolean;
476
+ /**
477
+ * Validate EVM address format (0x-prefixed hex)
478
+ */
479
+ declare function isEvmAddress(address: string): boolean;
480
+ /**
481
+ * Get network display name
482
+ */
483
+ declare function getNetworkDisplayName(network: string): string;
484
+
485
+ /**
486
+ * General helper utilities
487
+ *
488
+ * Miscellaneous helper functions for the SDK
489
+ */
490
+ /**
491
+ * Convert human-readable amount to atomic units (smallest unit)
492
+ *
493
+ * @param amount - Human-readable amount (e.g., 2.5 for 2.5 USDC)
494
+ * @param decimals - Token decimals (e.g., 6 for USDC, 18 for ETH)
495
+ * @returns Amount in atomic units as bigint
496
+ *
497
+ * @example
498
+ * ```typescript
499
+ * // 2.5 USDC (6 decimals) = 2,500,000 micro-USDC
500
+ * const atomicUnits = toAtomicUnits(2.5, 6); // 2500000n
501
+ * ```
502
+ */
503
+ declare function toAtomicUnits(amount: number, decimals: number): bigint;
504
+ /**
505
+ * Convert atomic units to human-readable amount
506
+ *
507
+ * @param atomicUnits - Token amount in smallest units
508
+ * @param decimals - Token decimals (e.g., 6 for USDC, 18 for ETH)
509
+ * @returns Human-readable amount as number
510
+ *
511
+ * @example
512
+ * ```typescript
513
+ * // 2,500,000 micro-USDC = 2.5 USDC
514
+ * const amount = fromAtomicUnits(2500000n, 6); // 2.5
515
+ * ```
516
+ */
517
+ declare function fromAtomicUnits(atomicUnits: bigint | number, decimals: number): number;
518
+ /**
519
+ * Parse x402Response to check if it's a 402 payment required
520
+ */
521
+ declare function is402Response(response: any): boolean;
522
+
523
+ export { type CreateEvmPaymentHeaderParams, type CreateSvmPaymentHeaderParams, EVM_NETWORK_CONFIGS, type EvmClientConfig, type EvmNetwork, type EvmNetworkConfig, EvmNetworkSchema, type EvmPaymentPayload, EvmPaymentPayloadSchema, type EvmWalletAdapter, NetworkType, type SolanaNetwork, SolanaNetworkSchema, type SolanaPaymentPayload, SolanaPaymentPayloadSchema, type SvmClientConfig, type WalletAdapter, createEvmPaymentFetch, createEvmPaymentHeader, createSvmPaymentFetch, createSvmPaymentHeader, formatAddress, fromAtomicUnits, getChainId, getChainIdFromNetwork, getDefaultSolanaRpcUrl, getNetworkDisplayName, getNetworkType, getWalletDisplayName, getWalletInstallUrl, getWalletProvider, handleEvmPayment, handleSvmPayment, is402Response, isEvmAddress, isEvmNetwork, isSolanaAddress, isSolanaNetwork, isWalletInstalled, makePayment, toAtomicUnits };