@smoothsend/sdk 2.3.7 → 2.3.9

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/index.esm.js DELETED
@@ -1,3319 +0,0 @@
1
- import axios from 'axios';
2
- import { Network, Aptos, AptosConfig, Account, MoveVector, AccountAddress, AbstractedAccount } from '@aptos-labs/ts-sdk';
3
- import { useState, useEffect, useCallback } from 'react';
4
- import { useWallet } from '@aptos-labs/wallet-adapter-react';
5
-
6
- /**
7
- * Error handling system for SmoothSend SDK v2
8
- * Provides typed error classes for different failure scenarios
9
- *
10
- * @remarks
11
- * All SDK errors extend SmoothSendError for consistent error handling
12
- * Use instanceof checks to handle specific error types
13
- *
14
- * @example
15
- * ```typescript
16
- * try {
17
- * await sdk.transfer(request, wallet);
18
- * } catch (error) {
19
- * if (error instanceof AuthenticationError) {
20
- * console.error('Invalid API key');
21
- * } else if (error instanceof RateLimitError) {
22
- * console.error('Rate limit exceeded');
23
- * }
24
- * }
25
- * ```
26
- */
27
- /**
28
- * Base error class for all SmoothSend SDK errors
29
- *
30
- * @remarks
31
- * All SDK-specific errors extend this class
32
- * Contains error code, HTTP status code, and additional details
33
- *
34
- * @example
35
- * ```typescript
36
- * throw new SmoothSendError(
37
- * 'Something went wrong',
38
- * 'CUSTOM_ERROR',
39
- * 500,
40
- * { additionalInfo: 'details' }
41
- * );
42
- * ```
43
- */
44
- class SmoothSendError extends Error {
45
- /**
46
- * Creates a new SmoothSendError
47
- *
48
- * @param message - Human-readable error message
49
- * @param code - Error code for programmatic handling
50
- * @param statusCode - HTTP status code (if applicable)
51
- * @param details - Additional error details
52
- */
53
- constructor(message, code, statusCode, details) {
54
- super(message);
55
- this.code = code;
56
- this.statusCode = statusCode;
57
- this.details = details;
58
- this.name = 'SmoothSendError';
59
- // Maintains proper stack trace for where our error was thrown (only available on V8)
60
- if (Error.captureStackTrace) {
61
- Error.captureStackTrace(this, this.constructor);
62
- }
63
- }
64
- }
65
- /**
66
- * Authentication error - thrown when API key is invalid, missing, or expired
67
- *
68
- * @remarks
69
- * HTTP Status Code: 401
70
- * Indicates authentication failure with the proxy worker
71
- *
72
- * @example
73
- * ```typescript
74
- * try {
75
- * await sdk.transfer(request, wallet);
76
- * } catch (error) {
77
- * if (error instanceof AuthenticationError) {
78
- * console.error('Invalid API key:', error.message);
79
- * console.log('Get a new key at:', error.details.suggestion);
80
- * }
81
- * }
82
- * ```
83
- */
84
- class AuthenticationError extends SmoothSendError {
85
- /**
86
- * Creates a new AuthenticationError
87
- *
88
- * @param message - Human-readable error message
89
- * @param details - Additional error details
90
- */
91
- constructor(message, details) {
92
- super(message, 'AUTHENTICATION_ERROR', 401, {
93
- ...details,
94
- docs: 'https://docs.smoothsend.xyz/api-keys',
95
- suggestion: 'Check your API key at dashboard.smoothsend.xyz'
96
- });
97
- this.name = 'AuthenticationError';
98
- }
99
- }
100
- /**
101
- * Rate limit error - thrown when request rate limit is exceeded
102
- *
103
- * @remarks
104
- * HTTP Status Code: 429
105
- * Contains rate limit details including reset time
106
- *
107
- * @example
108
- * ```typescript
109
- * try {
110
- * await sdk.transfer(request, wallet);
111
- * } catch (error) {
112
- * if (error instanceof RateLimitError) {
113
- * console.error('Rate limit exceeded');
114
- * console.log(`Limit: ${error.limit}`);
115
- * console.log(`Remaining: ${error.remaining}`);
116
- * console.log(`Resets at: ${error.resetTime}`);
117
- * }
118
- * }
119
- * ```
120
- */
121
- class RateLimitError extends SmoothSendError {
122
- /**
123
- * Creates a new RateLimitError
124
- *
125
- * @param message - Human-readable error message
126
- * @param limit - Maximum requests allowed per period
127
- * @param remaining - Remaining requests in current period
128
- * @param resetTime - When the rate limit resets (ISO 8601 timestamp)
129
- */
130
- constructor(message, limit, remaining, resetTime) {
131
- super(message, 'RATE_LIMIT_EXCEEDED', 429, {
132
- limit,
133
- remaining,
134
- resetTime,
135
- docs: 'https://docs.smoothsend.xyz/rate-limits',
136
- suggestion: 'Wait until rate limit resets or upgrade your tier'
137
- });
138
- this.limit = limit;
139
- this.remaining = remaining;
140
- this.resetTime = resetTime;
141
- this.name = 'RateLimitError';
142
- }
143
- }
144
- /**
145
- * Validation error - thrown when request parameters are invalid
146
- *
147
- * @remarks
148
- * HTTP Status Code: 400
149
- * Contains field name that failed validation
150
- *
151
- * @example
152
- * ```typescript
153
- * try {
154
- * await sdk.transfer(request, wallet);
155
- * } catch (error) {
156
- * if (error instanceof ValidationError) {
157
- * console.error(`Invalid ${error.field}:`, error.message);
158
- * }
159
- * }
160
- * ```
161
- */
162
- class ValidationError extends SmoothSendError {
163
- /**
164
- * Creates a new ValidationError
165
- *
166
- * @param message - Human-readable error message
167
- * @param field - Name of the field that failed validation
168
- * @param details - Additional error details
169
- */
170
- constructor(message, field, details) {
171
- super(message, 'VALIDATION_ERROR', 400, {
172
- field,
173
- ...details,
174
- suggestion: `Check the '${field}' parameter and try again`
175
- });
176
- this.field = field;
177
- this.name = 'ValidationError';
178
- }
179
- }
180
- /**
181
- * Network error - thrown when network connectivity issues occur
182
- *
183
- * @remarks
184
- * HTTP Status Code: 0 (no HTTP response)
185
- * Indicates network connectivity problems
186
- *
187
- * @example
188
- * ```typescript
189
- * try {
190
- * await sdk.transfer(request, wallet);
191
- * } catch (error) {
192
- * if (error instanceof NetworkError) {
193
- * console.error('Network error:', error.message);
194
- * console.log('Original error:', error.originalError);
195
- * }
196
- * }
197
- * ```
198
- */
199
- class NetworkError extends SmoothSendError {
200
- /**
201
- * Creates a new NetworkError
202
- *
203
- * @param message - Human-readable error message
204
- * @param originalError - Original error that caused the network failure
205
- */
206
- constructor(message, originalError) {
207
- super(message, 'NETWORK_ERROR', 0, {
208
- originalError: originalError?.message,
209
- suggestion: 'Check your internet connection and try again'
210
- });
211
- this.originalError = originalError;
212
- this.name = 'NetworkError';
213
- }
214
- }
215
- /**
216
- * Helper function to create appropriate error from HTTP response
217
- *
218
- * @remarks
219
- * Parses HTTP error response and creates typed error object
220
- * Used internally by HTTP client
221
- *
222
- * @param statusCode - HTTP status code
223
- * @param errorData - Error response data from API
224
- * @param defaultMessage - Default message if none provided in response
225
- * @returns Typed error object
226
- *
227
- * @example
228
- * ```typescript
229
- * const error = createErrorFromResponse(401, {
230
- * error: 'Invalid API key',
231
- * details: { field: 'apiKey' }
232
- * });
233
- * throw error;
234
- * ```
235
- */
236
- function createErrorFromResponse(statusCode, errorData, defaultMessage = 'An error occurred') {
237
- const message = errorData?.error || errorData?.message || defaultMessage;
238
- const details = errorData?.details || {};
239
- switch (statusCode) {
240
- case 401:
241
- return new AuthenticationError(message, details);
242
- case 429:
243
- return new RateLimitError(message, parseInt(details.limit || '0'), parseInt(details.remaining || '0'), details.reset || details.resetTime || '');
244
- case 400:
245
- return new ValidationError(message, details.field || 'unknown', details);
246
- default:
247
- return new SmoothSendError(message, errorData?.errorCode || 'UNKNOWN_ERROR', statusCode, details);
248
- }
249
- }
250
- /**
251
- * Helper function to create network error from exception
252
- *
253
- * @remarks
254
- * Wraps generic exceptions in NetworkError for consistent error handling
255
- * Used internally by HTTP client
256
- *
257
- * @param error - Original error or exception
258
- * @returns NetworkError instance
259
- *
260
- * @example
261
- * ```typescript
262
- * try {
263
- * await fetch(url);
264
- * } catch (error) {
265
- * throw createNetworkError(error);
266
- * }
267
- * ```
268
- */
269
- function createNetworkError(error) {
270
- const message = error?.message || 'Network request failed';
271
- return new NetworkError(message, error instanceof Error ? error : undefined);
272
- }
273
-
274
- // Export error classes
275
- /**
276
- * Mapping of supported chains to their respective ecosystems
277
- * Used internally for adapter selection and routing
278
- */
279
- const CHAIN_ECOSYSTEM_MAP = {
280
- 'avalanche': 'evm',
281
- 'aptos-testnet': 'aptos',
282
- 'aptos-mainnet': 'aptos',
283
- 'stellar-testnet': 'stellar',
284
- 'stellar-mainnet': 'stellar',
285
- };
286
- /**
287
- * Aptos-specific error codes
288
- * Used for detailed error handling in Aptos adapter
289
- *
290
- * @remarks
291
- * Error codes are prefixed with APTOS_ for easy identification
292
- */
293
- const APTOS_ERROR_CODES = {
294
- // Signature verification errors
295
- /** Missing signature in request */
296
- MISSING_SIGNATURE: 'APTOS_MISSING_SIGNATURE',
297
- /** Missing public key for verification */
298
- MISSING_PUBLIC_KEY: 'APTOS_MISSING_PUBLIC_KEY',
299
- /** Invalid signature format */
300
- INVALID_SIGNATURE_FORMAT: 'APTOS_INVALID_SIGNATURE_FORMAT',
301
- /** Invalid public key format */
302
- INVALID_PUBLIC_KEY_FORMAT: 'APTOS_INVALID_PUBLIC_KEY_FORMAT',
303
- /** Address doesn't match public key */
304
- ADDRESS_MISMATCH: 'APTOS_ADDRESS_MISMATCH',
305
- /** Signature verification failed */
306
- SIGNATURE_VERIFICATION_FAILED: 'APTOS_SIGNATURE_VERIFICATION_FAILED',
307
- // Transaction errors
308
- /** Missing transaction data */
309
- MISSING_TRANSACTION_DATA: 'APTOS_MISSING_TRANSACTION_DATA',
310
- /** Invalid transaction format */
311
- INVALID_TRANSACTION_FORMAT: 'APTOS_INVALID_TRANSACTION_FORMAT',
312
- // Address validation errors
313
- /** Empty address provided */
314
- EMPTY_ADDRESS: 'APTOS_EMPTY_ADDRESS',
315
- /** Invalid address format */
316
- INVALID_ADDRESS_FORMAT: 'APTOS_INVALID_ADDRESS_FORMAT',
317
- // General errors
318
- /** Error fetching quote */
319
- QUOTE_ERROR: 'APTOS_QUOTE_ERROR',
320
- /** Error executing transfer */
321
- EXECUTE_ERROR: 'APTOS_EXECUTE_ERROR',
322
- /** Error fetching balance */
323
- BALANCE_ERROR: 'APTOS_BALANCE_ERROR',
324
- /** Error fetching token info */
325
- TOKEN_INFO_ERROR: 'APTOS_TOKEN_INFO_ERROR',
326
- /** Error checking status */
327
- STATUS_ERROR: 'APTOS_STATUS_ERROR',
328
- /** Error calling Move function */
329
- MOVE_CALL_ERROR: 'APTOS_MOVE_CALL_ERROR',
330
- /** Unsupported token */
331
- UNSUPPORTED_TOKEN: 'APTOS_UNSUPPORTED_TOKEN'
332
- };
333
- /**
334
- * Stellar adapter error codes
335
- */
336
- const STELLAR_ERROR_CODES = {
337
- MISSING_SIGNED_TRANSACTION: 'STELLAR_MISSING_SIGNED_TRANSACTION',
338
- GASLESS_TRANSACTION_ERROR: 'STELLAR_GASLESS_TRANSACTION_ERROR',
339
- STATUS_ERROR: 'STELLAR_STATUS_ERROR',
340
- HEALTH_ERROR: 'STELLAR_HEALTH_ERROR',
341
- INVALID_ADDRESS_FORMAT: 'STELLAR_INVALID_ADDRESS_FORMAT',
342
- };
343
-
344
- /**
345
- * Shared Constants for SmoothSend Platform
346
- *
347
- * IMPORTANT: This file must be kept in sync across all repositories:
348
- * - smoothsend-worker-proxy/src/shared-constants.ts
349
- * - smoothsend-dev-console/src/lib/shared-constants.ts
350
- * - smoothsend-sdk/src/shared-constants.ts
351
- *
352
- * Any changes to these constants must be replicated to all three locations.
353
- */
354
- /**
355
- * API Key Prefixes
356
- * Used to identify key types from their prefix
357
- */
358
- /**
359
- * Usage Response Headers
360
- * Headers sent by worker and read by SDK/Console
361
- *
362
- * IMPORTANT: Header names must match exactly
363
- */
364
- const USAGE_HEADERS = {
365
- RATE_LIMIT: 'X-Rate-Limit-Limit',
366
- RATE_REMAINING: 'X-Rate-Limit-Remaining',
367
- RATE_RESET: 'X-Rate-Limit-Reset',
368
- MONTHLY_LIMIT: 'X-Monthly-Limit',
369
- MONTHLY_USAGE: 'X-Monthly-Usage',
370
- MONTHLY_REMAINING: 'X-Monthly-Remaining',
371
- REQUEST_ID: 'X-Request-ID'};
372
-
373
- /**
374
- * HTTP Client for proxy worker integration
375
- * Handles authentication, rate limiting, usage tracking, and retry logic
376
- */
377
- class HttpClient {
378
- /**
379
- * Constructor supports both old (baseURL, timeout) and new (config object) patterns
380
- * for backward compatibility during migration
381
- */
382
- constructor(configOrBaseURL, timeout) {
383
- // Determine if using new config object or old baseURL pattern
384
- if (typeof configOrBaseURL === 'string') {
385
- // Old pattern: constructor(baseURL, timeout)
386
- this.baseURL = configOrBaseURL;
387
- this.network = 'testnet';
388
- this.maxRetries = 3;
389
- this.isProxyMode = false;
390
- this.includeOrigin = false;
391
- this.client = axios.create({
392
- baseURL: this.baseURL,
393
- timeout: timeout || 30000,
394
- headers: {
395
- 'Content-Type': 'application/json',
396
- },
397
- });
398
- }
399
- else {
400
- // New pattern: constructor(config)
401
- const config = configOrBaseURL;
402
- this.apiKey = config.apiKey;
403
- this.network = config.network || 'testnet';
404
- this.maxRetries = config.retries || 3;
405
- this.baseURL = config.baseUrl || 'https://proxy.smoothsend.xyz';
406
- this.isProxyMode = true;
407
- this.includeOrigin = config.includeOrigin || false;
408
- const headers = {
409
- 'Content-Type': 'application/json',
410
- 'Authorization': `Bearer ${this.apiKey}`,
411
- 'X-Network': this.network,
412
- ...config.customHeaders,
413
- };
414
- // Browsers forbid setting the `Origin` header manually ("unsafe header").
415
- // The browser will set it automatically on cross-origin requests.
416
- // If callers need the origin explicitly, they can pass a custom header (e.g. `X-Origin`).
417
- this.client = axios.create({
418
- baseURL: this.baseURL,
419
- timeout: config.timeout || 30000,
420
- headers,
421
- });
422
- }
423
- // Request interceptor - add timestamp to prevent caching
424
- this.client.interceptors.request.use((config) => {
425
- config.params = { ...config.params, _t: Date.now() };
426
- return config;
427
- }, (error) => Promise.reject(error));
428
- // Response interceptor - handle errors but don't transform responses
429
- this.client.interceptors.response.use((response) => response, (error) => {
430
- // Let the request methods handle errors for proper retry logic
431
- return Promise.reject(error);
432
- });
433
- }
434
- /**
435
- * Extract usage metadata from response headers (proxy mode only)
436
- * Uses USAGE_HEADERS constants for consistency across systems
437
- */
438
- extractMetadata(response) {
439
- if (!this.isProxyMode) {
440
- return undefined;
441
- }
442
- // Convert header names to lowercase for case-insensitive lookup
443
- const headers = response.headers;
444
- return {
445
- rateLimit: {
446
- limit: headers[USAGE_HEADERS.RATE_LIMIT.toLowerCase()] || '0',
447
- remaining: headers[USAGE_HEADERS.RATE_REMAINING.toLowerCase()] || '0',
448
- reset: headers[USAGE_HEADERS.RATE_RESET.toLowerCase()] || '',
449
- },
450
- monthly: {
451
- limit: headers[USAGE_HEADERS.MONTHLY_LIMIT.toLowerCase()] || '0',
452
- usage: headers[USAGE_HEADERS.MONTHLY_USAGE.toLowerCase()] || '0',
453
- remaining: headers[USAGE_HEADERS.MONTHLY_REMAINING.toLowerCase()] || '0',
454
- },
455
- requestId: headers[USAGE_HEADERS.REQUEST_ID.toLowerCase()] || '',
456
- };
457
- }
458
- /**
459
- * Determine if an error should be retried
460
- */
461
- shouldRetry(error, attempt) {
462
- // Don't retry if we've exceeded max retries
463
- if (attempt >= this.maxRetries) {
464
- return false;
465
- }
466
- // Only retry in proxy mode (legacy mode doesn't have retry logic)
467
- if (!this.isProxyMode) {
468
- return false;
469
- }
470
- // Network errors - retry
471
- if (!error.response) {
472
- return true;
473
- }
474
- const status = error.response.status;
475
- // 5xx server errors - retry
476
- if (status >= 500 && status < 600) {
477
- return true;
478
- }
479
- // 4xx client errors - don't retry (including 429 rate limit)
480
- if (status >= 400 && status < 500) {
481
- return false;
482
- }
483
- return false;
484
- }
485
- /**
486
- * Calculate exponential backoff delay with jitter
487
- */
488
- calculateBackoff(attempt) {
489
- const baseDelay = 1000; // 1 second
490
- const maxDelay = 10000; // 10 seconds
491
- const exponentialDelay = baseDelay * Math.pow(2, attempt);
492
- const delay = Math.min(exponentialDelay, maxDelay);
493
- // Add jitter (±20%)
494
- const jitter = delay * 0.2 * (Math.random() * 2 - 1);
495
- return Math.floor(delay + jitter);
496
- }
497
- /**
498
- * Execute request with retry logic (proxy mode) or single attempt (legacy mode)
499
- */
500
- async executeWithRetry(operation) {
501
- let lastError;
502
- const maxAttempts = this.isProxyMode ? this.maxRetries : 0;
503
- for (let attempt = 0; attempt <= maxAttempts; attempt++) {
504
- try {
505
- const response = await operation();
506
- // Success - extract metadata (if proxy mode) and return
507
- const result = {
508
- success: true,
509
- data: response.data,
510
- };
511
- const metadata = this.extractMetadata(response);
512
- if (metadata) {
513
- result.metadata = metadata;
514
- }
515
- return result;
516
- }
517
- catch (error) {
518
- lastError = error;
519
- // Check if we should retry
520
- if (!this.shouldRetry(error, attempt)) {
521
- break;
522
- }
523
- // Wait before retrying (except on last attempt)
524
- if (attempt < maxAttempts) {
525
- const delay = this.calculateBackoff(attempt);
526
- await new Promise(resolve => setTimeout(resolve, delay));
527
- }
528
- }
529
- }
530
- // All retries failed - handle error
531
- return this.handleError(lastError);
532
- }
533
- /**
534
- * Handle errors and create appropriate error responses
535
- */
536
- handleError(error) {
537
- if (this.isProxyMode) {
538
- // Proxy mode: use typed errors
539
- if (error.response) {
540
- // Server responded with error status
541
- const { status, data } = error.response;
542
- const sdkError = createErrorFromResponse(status, data);
543
- throw sdkError;
544
- }
545
- else if (error.request) {
546
- // Network error - no response received
547
- const networkError = createNetworkError(error);
548
- throw networkError;
549
- }
550
- else {
551
- // Other error (request setup, etc.)
552
- const networkError = createNetworkError(error);
553
- throw networkError;
554
- }
555
- }
556
- else {
557
- // Legacy mode: return error response without throwing
558
- if (error.response) {
559
- const { status, data } = error.response;
560
- return {
561
- success: false,
562
- error: data?.error || `HTTP Error ${status}`,
563
- details: data?.details,
564
- errorCode: data?.errorCode || `HTTP_${status}`,
565
- };
566
- }
567
- else if (error.request) {
568
- return {
569
- success: false,
570
- error: 'Network error - unable to connect to server',
571
- errorCode: 'NETWORK_ERROR',
572
- };
573
- }
574
- else {
575
- return {
576
- success: false,
577
- error: error.message || 'Unknown error occurred',
578
- errorCode: 'UNKNOWN_ERROR',
579
- };
580
- }
581
- }
582
- }
583
- /**
584
- * GET request
585
- */
586
- async get(url, config) {
587
- return this.executeWithRetry(() => this.client.get(url, config));
588
- }
589
- /**
590
- * POST request
591
- */
592
- async post(url, data, config) {
593
- return this.executeWithRetry(() => this.client.post(url, data, config));
594
- }
595
- /**
596
- * PUT request
597
- */
598
- async put(url, data, config) {
599
- return this.executeWithRetry(() => this.client.put(url, data, config));
600
- }
601
- /**
602
- * DELETE request
603
- */
604
- async delete(url, config) {
605
- return this.executeWithRetry(() => this.client.delete(url, config));
606
- }
607
- /**
608
- * Update network parameter for subsequent requests
609
- */
610
- setNetwork(network) {
611
- this.network = network;
612
- this.client.defaults.headers['X-Network'] = network;
613
- }
614
- /**
615
- * Get current network
616
- */
617
- getNetwork() {
618
- return this.network;
619
- }
620
- }
621
-
622
- var http = /*#__PURE__*/Object.freeze({
623
- __proto__: null,
624
- HttpClient: HttpClient
625
- });
626
-
627
- /**
628
- * Aptos Multi-Chain Adapter - v2 Proxy Architecture
629
- * Handles all Aptos chains (aptos-testnet, aptos-mainnet)
630
- * Routes all requests through proxy.smoothsend.xyz with API key authentication
631
- * Supports Aptos-specific features like gasless transactions and Move-based contracts
632
- */
633
- class AptosAdapter {
634
- constructor(chain, config, apiKey, network = 'testnet', includeOrigin = false) {
635
- // Validate this is an Aptos chain
636
- if (CHAIN_ECOSYSTEM_MAP[chain] !== 'aptos') {
637
- throw new SmoothSendError(`AptosAdapter can only handle Aptos chains, got: ${chain}`, 'INVALID_CHAIN_FOR_ADAPTER', 400, { chain });
638
- }
639
- this.chain = chain;
640
- this.config = config;
641
- this.apiKey = apiKey;
642
- this.network = network;
643
- // Initialize HTTP client with proxy configuration
644
- this.httpClient = new HttpClient({
645
- apiKey: this.apiKey,
646
- network: this.network,
647
- timeout: 30000,
648
- retries: 3,
649
- includeOrigin
650
- });
651
- }
652
- /**
653
- * Build API path for proxy worker routing to Aptos relayer
654
- * All requests route through /api/v1/relayer/aptos/* endpoints
655
- */
656
- getApiPath(endpoint) {
657
- return `/api/v1/relayer/aptos${endpoint}`;
658
- }
659
- /**
660
- * Update network parameter for subsequent requests
661
- * Network is passed via X-Network header to proxy worker
662
- */
663
- setNetwork(network) {
664
- this.network = network;
665
- this.httpClient.setNetwork(network);
666
- }
667
- /**
668
- * Get current network
669
- */
670
- getNetwork() {
671
- return this.network;
672
- }
673
- /**
674
- * Estimate fee for a transfer (v2 interface method)
675
- * Routes through proxy: POST /api/v1/relayer/aptos/quote
676
- */
677
- async estimateFee(request) {
678
- try {
679
- const response = await this.httpClient.post(this.getApiPath('/quote'), {
680
- fromAddress: request.from,
681
- toAddress: request.to,
682
- amount: request.amount,
683
- coinType: this.getAptosTokenAddress(request.token)
684
- });
685
- const responseData = response.data;
686
- const quote = responseData.quote;
687
- const feeEstimate = {
688
- relayerFee: quote.relayerFee,
689
- feeInUSD: quote.feeInUSD || '0',
690
- coinType: this.getAptosTokenAddress(request.token),
691
- estimatedGas: quote.estimatedGas || '0',
692
- network: this.network
693
- };
694
- // Attach usage metadata from proxy response headers
695
- if (response.metadata) {
696
- feeEstimate.metadata = response.metadata;
697
- }
698
- return feeEstimate;
699
- }
700
- catch (error) {
701
- if (error instanceof SmoothSendError) {
702
- throw error;
703
- }
704
- throw new SmoothSendError(`Failed to estimate Aptos fee: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.QUOTE_ERROR, 500, { chain: this.chain });
705
- }
706
- }
707
- /**
708
- * Execute gasless transfer (v2 interface method)
709
- * Routes through proxy: POST /api/v1/relayer/aptos/execute
710
- */
711
- async executeGaslessTransfer(signedData) {
712
- return this.executeTransfer(signedData);
713
- }
714
- /**
715
- * Get quote for a transfer (legacy method, kept for backward compatibility)
716
- * Routes through proxy: POST /api/v1/relayer/aptos/quote
717
- */
718
- async getQuote(request) {
719
- try {
720
- // Route through proxy: POST /api/v1/relayer/aptos/quote
721
- const response = await this.httpClient.post(this.getApiPath('/quote'), {
722
- fromAddress: request.from,
723
- toAddress: request.to,
724
- amount: request.amount,
725
- coinType: this.getAptosTokenAddress(request.token)
726
- });
727
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
728
- const responseData = response.data;
729
- const quote = responseData.quote;
730
- return {
731
- amount: request.amount,
732
- relayerFee: quote.relayerFee,
733
- total: (BigInt(request.amount) + BigInt(quote.relayerFee)).toString(),
734
- feePercentage: 0, // Aptos uses different fee structure
735
- contractAddress: responseData.transactionData.function.split('::')[0],
736
- // Store Aptos-specific data for later use
737
- aptosTransactionData: responseData.transactionData
738
- };
739
- }
740
- catch (error) {
741
- // Re-throw typed errors from HttpClient, wrap others
742
- if (error instanceof SmoothSendError) {
743
- throw error;
744
- }
745
- throw new SmoothSendError(`Failed to get Aptos quote: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.QUOTE_ERROR, 500, { chain: this.chain });
746
- }
747
- }
748
- async prepareTransfer(request, quote) {
749
- // For Aptos, the transaction data is provided in the quote response
750
- // The user will sign this transaction directly in their wallet
751
- const aptosQuote = quote;
752
- if (!aptosQuote.aptosTransactionData) {
753
- throw new SmoothSendError('Missing Aptos transaction data from quote', APTOS_ERROR_CODES.MISSING_TRANSACTION_DATA, 400, { chain: this.chain });
754
- }
755
- // Return the transaction data that needs to be signed
756
- // NOTE: After signing, you must serialize the transaction and authenticator
757
- // using the Aptos SDK and provide them as transactionBytes and authenticatorBytes
758
- return {
759
- domain: null, // Aptos doesn't use domain separation like EVM
760
- types: null,
761
- message: aptosQuote.aptosTransactionData,
762
- primaryType: 'AptosTransaction',
763
- // Add metadata to help with serialization - using any type for flexibility
764
- metadata: {
765
- requiresSerialization: true,
766
- serializationInstructions: 'After signing, serialize the SimpleTransaction and AccountAuthenticator using Aptos SDK',
767
- expectedFormat: 'transactionBytes and authenticatorBytes as number arrays'
768
- }
769
- };
770
- }
771
- async executeTransfer(signedData) {
772
- try {
773
- // Validate that we have the required serialized transaction data
774
- this.validateSerializedTransactionData(signedData);
775
- // Route through proxy: POST /api/v1/relayer/aptos/execute
776
- const response = await this.httpClient.post(this.getApiPath('/execute'), {
777
- transactionBytes: signedData.transactionBytes,
778
- authenticatorBytes: signedData.authenticatorBytes
779
- });
780
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
781
- const transferData = response.data;
782
- const result = {
783
- success: transferData.success || true,
784
- // Use standardized field names (txHash, transferId)
785
- txHash: transferData.txHash || transferData.hash, // Support both formats
786
- transferId: transferData.transferId || transferData.transactionId, // Support both formats
787
- explorerUrl: this.buildAptosExplorerUrl(transferData.txHash || transferData.hash),
788
- // Standard fields
789
- gasUsed: transferData.gasUsed,
790
- // Aptos-specific fields from enhanced response format
791
- gasFeePaidBy: transferData.gasFeePaidBy || 'relayer',
792
- userPaidAPT: transferData.userPaidAPT || false,
793
- vmStatus: transferData.vmStatus,
794
- sender: transferData.sender,
795
- chain: transferData.chain,
796
- relayerFee: transferData.relayerFee,
797
- message: transferData.message
798
- };
799
- // Attach usage metadata from proxy response headers
800
- if (response.metadata) {
801
- result.metadata = response.metadata;
802
- }
803
- return result;
804
- }
805
- catch (error) {
806
- // Re-throw typed errors from HttpClient, wrap others
807
- if (error instanceof SmoothSendError) {
808
- throw error;
809
- }
810
- throw new SmoothSendError(`Failed to execute Aptos transfer: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.EXECUTE_ERROR, 500, { chain: this.chain });
811
- }
812
- }
813
- async getBalance(address, token) {
814
- try {
815
- // Route through proxy: GET /api/v1/relayer/aptos/balance/:address
816
- const response = await this.httpClient.get(this.getApiPath(`/balance/${address}`));
817
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
818
- const balanceData = response.data;
819
- return [{
820
- token: balanceData?.symbol || token || 'USDC',
821
- balance: balanceData?.balance?.toString() || '0',
822
- decimals: balanceData?.decimals || 6,
823
- symbol: balanceData?.symbol || token || 'USDC',
824
- name: balanceData?.name || 'USD Coin (Testnet)'
825
- }];
826
- }
827
- catch (error) {
828
- // Re-throw typed errors from HttpClient, wrap others
829
- if (error instanceof SmoothSendError) {
830
- throw error;
831
- }
832
- throw new SmoothSendError(`Failed to get Aptos balance: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.BALANCE_ERROR, 500, { chain: this.chain });
833
- }
834
- }
835
- async getTokenInfo(token) {
836
- try {
837
- // Route through proxy: GET /api/v1/relayer/aptos/tokens
838
- const response = await this.httpClient.get(this.getApiPath('/tokens'));
839
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
840
- const tokens = response.data.tokens || {};
841
- const tokenInfo = tokens[token.toUpperCase()];
842
- if (!tokenInfo) {
843
- throw new Error(`Token ${token} not supported on ${this.chain}`);
844
- }
845
- return {
846
- symbol: tokenInfo.symbol,
847
- address: tokenInfo.address,
848
- decimals: tokenInfo.decimals,
849
- name: tokenInfo.name
850
- };
851
- }
852
- catch (error) {
853
- // Re-throw typed errors from HttpClient, wrap others
854
- if (error instanceof SmoothSendError) {
855
- throw error;
856
- }
857
- throw new SmoothSendError(`Failed to get Aptos token info: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.TOKEN_INFO_ERROR, 500, { chain: this.chain });
858
- }
859
- }
860
- async getNonce(address) {
861
- // Aptos uses sequence numbers instead of nonces
862
- // For compatibility, we return a timestamp-based value
863
- // The actual sequence number is managed by the Aptos blockchain
864
- return Date.now().toString();
865
- }
866
- async getTransactionStatus(txHash) {
867
- try {
868
- // Route through proxy: GET /api/v1/relayer/aptos/status/:txHash
869
- const response = await this.httpClient.get(this.getApiPath(`/status/${txHash}`));
870
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
871
- return response.data;
872
- }
873
- catch (error) {
874
- // Re-throw typed errors from HttpClient, wrap others
875
- if (error instanceof SmoothSendError) {
876
- throw error;
877
- }
878
- throw new SmoothSendError(`Failed to get Aptos transaction status: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.STATUS_ERROR, 500, { chain: this.chain });
879
- }
880
- }
881
- /**
882
- * Get health status of Aptos relayer through proxy
883
- * Routes through proxy: GET /api/v1/relayer/aptos/health
884
- */
885
- async getHealth() {
886
- try {
887
- const response = await this.httpClient.get(this.getApiPath('/health'));
888
- const healthResponse = {
889
- success: true,
890
- status: response.data.status || 'healthy',
891
- timestamp: response.data.timestamp || new Date().toISOString(),
892
- version: response.data.version || '2.0'
893
- };
894
- // Attach usage metadata from proxy response headers
895
- if (response.metadata) {
896
- healthResponse.metadata = response.metadata;
897
- }
898
- return healthResponse;
899
- }
900
- catch (error) {
901
- if (error instanceof SmoothSendError) {
902
- throw error;
903
- }
904
- throw new SmoothSendError(`Failed to get Aptos health status: ${error instanceof Error ? error.message : String(error)}`, 'HEALTH_CHECK_ERROR', 500, { chain: this.chain });
905
- }
906
- }
907
- validateAddress(address) {
908
- // Aptos address validation (0x prefix, up to 64 hex characters)
909
- // Aptos addresses can be shorter and are automatically padded
910
- return /^0x[a-fA-F0-9]{1,64}$/.test(address);
911
- }
912
- validateAmount(amount) {
913
- try {
914
- const amountBN = BigInt(amount);
915
- return amountBN > 0n;
916
- }
917
- catch {
918
- return false;
919
- }
920
- }
921
- /**
922
- * Get Aptos token address from symbol
923
- * Mirrors aptosrelayer/config/chains.json
924
- */
925
- getAptosTokenAddress(tokenSymbol) {
926
- const symbol = tokenSymbol.toUpperCase();
927
- const TESTNET_TOKENS = {
928
- USDC: '0x3c27315fb69ba6e4b960f1507d1cefcc9a4247869f26a8d59d6b7869d23782c::test_coins::USDC'
929
- };
930
- const MAINNET_TOKENS = {
931
- USDT: '0x357b0b74bc833e95a115ad22604854d6b0fca151cecd94111770e5d6ffc9dc2b',
932
- USDC: '0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b',
933
- WBTC: '0x68844a0d7f2587e726ad0579f3d640865bb4162c08a4589eeda3f9689ec52a3d',
934
- USDE: '0xf37a8864fe737eb8ec2c2931047047cbaed1beed3fb0e5b7c5526dafd3b9c2e9',
935
- USD1: '0x05fabd1b12e39967a3c24e91b7b8f67719a6dacee74f3c8b9fb7d93e855437d2'
936
- };
937
- const tokens = this.chain === 'aptos-testnet' ? TESTNET_TOKENS : MAINNET_TOKENS;
938
- const address = tokens[symbol];
939
- if (!address) {
940
- const supported = Object.keys(tokens).join(', ');
941
- throw new SmoothSendError(`Unsupported token: ${tokenSymbol} on ${this.chain}. Supported: ${supported}`, APTOS_ERROR_CODES.UNSUPPORTED_TOKEN, 400, { chain: this.chain, token: tokenSymbol, supported });
942
- }
943
- return address;
944
- }
945
- /**
946
- * Build Aptos explorer URL for transaction
947
- */
948
- buildAptosExplorerUrl(txHash) {
949
- if (this.chain === 'aptos-testnet') {
950
- return `https://explorer.aptoslabs.com/txn/${txHash}?network=testnet`;
951
- }
952
- return `https://explorer.aptoslabs.com/txn/${txHash}`;
953
- }
954
- /**
955
- * Validate serialized transaction data for proxy worker
956
- * @param signedData The signed transfer data to validate
957
- */
958
- validateSerializedTransactionData(signedData) {
959
- if (!signedData.transactionBytes) {
960
- throw new SmoothSendError('Serialized transaction bytes are required for Aptos transactions', APTOS_ERROR_CODES.MISSING_TRANSACTION_DATA, 400, { chain: this.chain });
961
- }
962
- if (!signedData.authenticatorBytes) {
963
- throw new SmoothSendError('Serialized authenticator bytes are required for Aptos transactions', APTOS_ERROR_CODES.MISSING_SIGNATURE, 400, { chain: this.chain });
964
- }
965
- // Validate that transaction bytes is an array of numbers (0-255)
966
- if (!Array.isArray(signedData.transactionBytes) ||
967
- !signedData.transactionBytes.every((b) => typeof b === 'number' && b >= 0 && b <= 255)) {
968
- throw new SmoothSendError('Invalid transaction bytes format. Expected array of numbers 0-255.', APTOS_ERROR_CODES.INVALID_SIGNATURE_FORMAT, 400, { chain: this.chain });
969
- }
970
- // Validate that authenticator bytes is an array of numbers (0-255)
971
- if (!Array.isArray(signedData.authenticatorBytes) ||
972
- !signedData.authenticatorBytes.every((b) => typeof b === 'number' && b >= 0 && b <= 255)) {
973
- throw new SmoothSendError('Invalid authenticator bytes format. Expected array of numbers 0-255.', APTOS_ERROR_CODES.INVALID_PUBLIC_KEY_FORMAT, 400, { chain: this.chain });
974
- }
975
- }
976
- /**
977
- * Enhanced address validation with detailed error messages
978
- * @param address The address to validate
979
- * @returns true if valid, throws error if invalid
980
- */
981
- validateAddressStrict(address) {
982
- if (!address) {
983
- throw new SmoothSendError('Address cannot be empty', APTOS_ERROR_CODES.EMPTY_ADDRESS, 400, { chain: this.chain });
984
- }
985
- // Aptos address validation (0x prefix, up to 64 hex characters)
986
- if (!/^0x[a-fA-F0-9]{1,64}$/.test(address)) {
987
- throw new SmoothSendError('Invalid Aptos address format. Must start with 0x and contain 1-64 hex characters.', APTOS_ERROR_CODES.INVALID_ADDRESS_FORMAT, 400, { chain: this.chain });
988
- }
989
- return true;
990
- }
991
- /**
992
- * Verify that a public key corresponds to an expected address
993
- * This mirrors the enhanced verification in the relayer
994
- * @param publicKey The public key to verify
995
- * @param expectedAddress The expected address
996
- * @returns true if they match
997
- */
998
- async verifyPublicKeyAddress(publicKey, expectedAddress) {
999
- try {
1000
- // This would typically use the Aptos SDK to derive address from public key
1001
- // For now, we'll do basic validation and let the relayer handle the actual verification
1002
- this.validateAddressStrict(expectedAddress);
1003
- if (!publicKey || !publicKey.startsWith('0x')) {
1004
- return false;
1005
- }
1006
- // The actual verification is done by the relayer using the Aptos SDK
1007
- // This is just a preliminary check
1008
- return true;
1009
- }
1010
- catch (error) {
1011
- return false;
1012
- }
1013
- }
1014
- /**
1015
- * Enhanced transaction preparation with better signature data structure
1016
- * @param request Transfer request
1017
- * @param quote Transfer quote
1018
- * @returns Signature data with enhanced structure
1019
- */
1020
- async prepareTransferEnhanced(request, quote) {
1021
- const baseSignatureData = await this.prepareTransfer(request, quote);
1022
- return {
1023
- ...baseSignatureData,
1024
- metadata: {
1025
- chain: this.chain,
1026
- fromAddress: request.from,
1027
- toAddress: request.to,
1028
- amount: request.amount,
1029
- token: request.token,
1030
- relayerFee: quote.relayerFee,
1031
- signatureVersion: '2.0', // Version for tracking signature format changes
1032
- requiresPublicKey: true, // Indicates this chain requires public key for verification
1033
- verificationMethod: 'ed25519_with_address_derivation' // Indicates verification method used
1034
- }
1035
- };
1036
- }
1037
- /**
1038
- * Aptos-specific Move contract interaction
1039
- */
1040
- async callMoveFunction(functionName, args) {
1041
- try {
1042
- // Route through proxy: POST /api/v1/relayer/aptos/move/call
1043
- const response = await this.httpClient.post(this.getApiPath('/move/call'), {
1044
- function: functionName,
1045
- arguments: args
1046
- });
1047
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
1048
- return response.data;
1049
- }
1050
- catch (error) {
1051
- // Re-throw typed errors from HttpClient, wrap others
1052
- if (error instanceof SmoothSendError) {
1053
- throw error;
1054
- }
1055
- throw new SmoothSendError(`Failed to call Move function: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.MOVE_CALL_ERROR, 500, { chain: this.chain });
1056
- }
1057
- }
1058
- }
1059
-
1060
- /**
1061
- * Stellar C-Address Adapter — SDK for Soroban Smart Account operations
1062
- *
1063
- * Provides a clean interface for:
1064
- * - Creating C-addresses (smart accounts) from G-addresses
1065
- * - Looking up existing C-addresses by owner
1066
- * - Querying token balances (XLM, USDC, EURC)
1067
- * - Building bridge transfers (G→C)
1068
- * - Building smart account transfers (C→G, C→C)
1069
- * - Submitting user-signed transactions via fee-bump
1070
- * - Getting transaction history
1071
- *
1072
- * All transactions are gasless — the relayer covers fees via fee-bump.
1073
- *
1074
- * @example
1075
- * ```typescript
1076
- * import { SmoothSendSDK } from '@smoothsend/sdk';
1077
- *
1078
- * const sdk = new SmoothSendSDK({ apiKey: 'pk_nogas_xxx', network: 'testnet' });
1079
- *
1080
- * // Create a C-address for a G-address owner
1081
- * const { cAddress } = await sdk.stellar.cAddress.create('GABCD...');
1082
- *
1083
- * // Get balances
1084
- * const { balances } = await sdk.stellar.cAddress.getBalances(cAddress);
1085
- *
1086
- * // Build a bridge transfer (G→C), user signs, relayer fee-bumps
1087
- * const { unsignedXDR } = await sdk.stellar.cAddress.buildBridgeTransfer({
1088
- * from: 'GABCD...',
1089
- * destination: cAddress,
1090
- * asset: 'USDC',
1091
- * amount: '10.5',
1092
- * });
1093
- * // Sign with wallet (e.g., Freighter)
1094
- * const signedXDR = await wallet.signTransaction(unsignedXDR);
1095
- * // Submit — relayer wraps in fee-bump
1096
- * const { txHash } = await sdk.stellar.cAddress.submitTransfer(signedXDR);
1097
- * ```
1098
- */
1099
- class StellarCAddressAdapter {
1100
- constructor(httpClient, network = 'testnet') {
1101
- this.httpClient = httpClient;
1102
- // Multi-chain compatible path: /api/v1/relayer/{chain}/c-address
1103
- this.basePath = '/api/v1/relayer/stellar/c-address';
1104
- }
1105
- /**
1106
- * Create a new C-address (Soroban Smart Account) for a G-address owner.
1107
- * If the owner already has a C-address, returns the existing one.
1108
- *
1109
- * The relayer pays all deployment fees — completely gasless for the user.
1110
- *
1111
- * @param ownerGAddress - The G-address that will control this smart account
1112
- * @returns The new C-address, tx hash, and whether it already existed
1113
- */
1114
- async create(ownerGAddress) {
1115
- this.validateGAddress(ownerGAddress);
1116
- try {
1117
- const response = await this.httpClient.post(`${this.basePath}/create`, { ownerGAddress }, { headers: { 'X-Chain': 'stellar' } });
1118
- const data = response.data;
1119
- if (!data.success) {
1120
- throw new SmoothSendError(data.error || 'Failed to create C-address', 'C_ADDRESS_CREATE_FAILED', 500);
1121
- }
1122
- return {
1123
- cAddress: data.cAddress,
1124
- txHash: data.txHash,
1125
- alreadyExisted: data.alreadyExisted,
1126
- explorerUrl: data.explorerUrl,
1127
- };
1128
- }
1129
- catch (error) {
1130
- if (error instanceof SmoothSendError)
1131
- throw error;
1132
- throw new SmoothSendError(`Failed to create C-address: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_CREATE_FAILED', 500);
1133
- }
1134
- }
1135
- /**
1136
- * Look up the C-address for a given G-address owner.
1137
- * Returns null if no C-address exists for this owner.
1138
- *
1139
- * @param ownerGAddress - The G-address to look up
1140
- */
1141
- async lookup(ownerGAddress) {
1142
- this.validateGAddress(ownerGAddress);
1143
- try {
1144
- const response = await this.httpClient.get(`${this.basePath}/lookup/${ownerGAddress}`, { headers: { 'X-Chain': 'stellar' } });
1145
- const data = response.data;
1146
- return {
1147
- ownerGAddress: data.ownerGAddress,
1148
- cAddress: data.cAddress || null,
1149
- hasAccount: data.hasAccount,
1150
- };
1151
- }
1152
- catch (error) {
1153
- if (error instanceof SmoothSendError)
1154
- throw error;
1155
- throw new SmoothSendError(`Failed to lookup C-address: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_LOOKUP_FAILED', 500);
1156
- }
1157
- }
1158
- /**
1159
- * Get token balances for a C-address.
1160
- * Returns balances for XLM, USDC, and EURC.
1161
- *
1162
- * @param cAddress - The C-address to query
1163
- */
1164
- async getBalances(cAddress) {
1165
- this.validateCAddress(cAddress);
1166
- try {
1167
- const response = await this.httpClient.get(`${this.basePath}/balance/${cAddress}`, { headers: { 'X-Chain': 'stellar' } });
1168
- const data = response.data;
1169
- return {
1170
- cAddress: data.cAddress,
1171
- balances: data.balances,
1172
- };
1173
- }
1174
- catch (error) {
1175
- if (error instanceof SmoothSendError)
1176
- throw error;
1177
- throw new SmoothSendError(`Failed to get balances: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_BALANCE_FAILED', 500);
1178
- }
1179
- }
1180
- /**
1181
- * Build a bridge transfer (G→C) using SAC.transfer.
1182
- * Returns unsigned XDR for the user to sign with their wallet.
1183
- * After signing, submit via submitTransfer().
1184
- *
1185
- * @param params.from - Sender G-address (signs the tx)
1186
- * @param params.destination - Recipient C-address (or G-address)
1187
- * @param params.asset - Asset to transfer: 'XLM', 'USDC', or 'EURC'
1188
- * @param params.amount - Human-readable amount (e.g., '10.5')
1189
- */
1190
- async buildBridgeTransfer(params) {
1191
- this.validateGAddress(params.from);
1192
- try {
1193
- const response = await this.httpClient.post(`${this.basePath}/bridge-transfer`, params, { headers: { 'X-Chain': 'stellar' } });
1194
- const data = response.data;
1195
- if (!data.success) {
1196
- throw new SmoothSendError(data.error || 'Bridge transfer failed', 'BRIDGE_TRANSFER_FAILED', 500);
1197
- }
1198
- return {
1199
- unsignedXDR: data.unsignedXDR,
1200
- networkPassphrase: data.networkPassphrase,
1201
- };
1202
- }
1203
- catch (error) {
1204
- if (error instanceof SmoothSendError)
1205
- throw error;
1206
- throw new SmoothSendError(`Bridge transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'BRIDGE_TRANSFER_FAILED', 500);
1207
- }
1208
- }
1209
- /**
1210
- * Build a transfer from a C-address (SmartAccount.send).
1211
- * Returns unsigned XDR for the owner to sign.
1212
- * After signing, submit via submitTransfer().
1213
- *
1214
- * @param params.from - Owner G-address (signs auth)
1215
- * @param params.cAddress - Source C-address (holds the funds)
1216
- * @param params.destination - Recipient (G or C address)
1217
- * @param params.asset - Asset: 'XLM', 'USDC', or 'EURC'
1218
- * @param params.amount - Human-readable amount
1219
- */
1220
- async buildTransfer(params) {
1221
- this.validateGAddress(params.from);
1222
- this.validateCAddress(params.cAddress);
1223
- try {
1224
- const response = await this.httpClient.post(`${this.basePath}/build-transfer`, params, { headers: { 'X-Chain': 'stellar' } });
1225
- const data = response.data;
1226
- if (!data.success) {
1227
- throw new SmoothSendError(data.error || 'Build transfer failed', 'BUILD_TRANSFER_FAILED', 500);
1228
- }
1229
- return {
1230
- unsignedXDR: data.unsignedXDR,
1231
- networkPassphrase: data.networkPassphrase,
1232
- };
1233
- }
1234
- catch (error) {
1235
- if (error instanceof SmoothSendError)
1236
- throw error;
1237
- throw new SmoothSendError(`Build transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'BUILD_TRANSFER_FAILED', 500);
1238
- }
1239
- }
1240
- /**
1241
- * Submit a user-signed transaction.
1242
- * The relayer wraps it in a fee-bump transaction and submits to the network.
1243
- * The user pays zero fees — the relayer covers everything.
1244
- *
1245
- * @param signedXDR - The user-signed transaction XDR (base64)
1246
- */
1247
- async submitTransfer(signedXDR) {
1248
- if (!signedXDR) {
1249
- throw new SmoothSendError('signedXDR is required', 'MISSING_SIGNED_XDR', 400);
1250
- }
1251
- try {
1252
- const response = await this.httpClient.post(`${this.basePath}/submit-transfer`, { signedXDR }, { headers: { 'X-Chain': 'stellar' } });
1253
- const data = response.data;
1254
- if (!data.success) {
1255
- throw new SmoothSendError(data.error || 'Submit failed', 'SUBMIT_TRANSFER_FAILED', 500);
1256
- }
1257
- return {
1258
- txHash: data.txHash,
1259
- explorerUrl: data.explorerUrl,
1260
- };
1261
- }
1262
- catch (error) {
1263
- if (error instanceof SmoothSendError)
1264
- throw error;
1265
- throw new SmoothSendError(`Submit transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'SUBMIT_TRANSFER_FAILED', 500);
1266
- }
1267
- }
1268
- /**
1269
- * Get transaction history for a C-address.
1270
- * Returns recent transfer events (sent/received) across all supported tokens.
1271
- *
1272
- * @param cAddress - The C-address to query
1273
- * @param limit - Maximum number of transactions to return (default: 20)
1274
- */
1275
- async getHistory(cAddress, limit = 20) {
1276
- this.validateCAddress(cAddress);
1277
- try {
1278
- const response = await this.httpClient.get(`${this.basePath}/history/${cAddress}?limit=${limit}`, { headers: { 'X-Chain': 'stellar' } });
1279
- const data = response.data;
1280
- return {
1281
- cAddress: data.cAddress,
1282
- transactions: data.transactions || [],
1283
- count: data.count || 0,
1284
- };
1285
- }
1286
- catch (error) {
1287
- if (error instanceof SmoothSendError)
1288
- throw error;
1289
- throw new SmoothSendError(`Failed to get history: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_HISTORY_FAILED', 500);
1290
- }
1291
- }
1292
- /**
1293
- * Health check for the C-address bridge service.
1294
- */
1295
- async health() {
1296
- try {
1297
- const response = await this.httpClient.get(`${this.basePath}/health`, { headers: { 'X-Chain': 'stellar' } });
1298
- const data = response.data;
1299
- return {
1300
- service: data.service,
1301
- relayerPublicKey: data.relayerPublicKey,
1302
- factoryContractId: data.factoryContractId,
1303
- isReady: data.isReady,
1304
- network: data.network,
1305
- };
1306
- }
1307
- catch (error) {
1308
- if (error instanceof SmoothSendError)
1309
- throw error;
1310
- throw new SmoothSendError(`C-Address health check failed: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_HEALTH_FAILED', 500);
1311
- }
1312
- }
1313
- // ─────────────────────────────────────────────────────────
1314
- // Validation helpers
1315
- // ─────────────────────────────────────────────────────────
1316
- validateGAddress(address) {
1317
- if (!address || !address.startsWith('G') || address.length !== 56) {
1318
- throw new SmoothSendError('Invalid G-address. Must start with G and be 56 characters.', 'INVALID_G_ADDRESS', 400);
1319
- }
1320
- }
1321
- validateCAddress(address) {
1322
- if (!address || !address.startsWith('C') || address.length !== 56) {
1323
- throw new SmoothSendError('Invalid C-address. Must start with C and be 56 characters.', 'INVALID_C_ADDRESS', 400);
1324
- }
1325
- }
1326
- validateAddress(address) {
1327
- return (typeof address === 'string' &&
1328
- address.length === 56 &&
1329
- (address.startsWith('G') || address.startsWith('C')));
1330
- }
1331
- }
1332
-
1333
- /** Headers to route requests to Stellar relayer via proxy */
1334
- const STELLAR_HEADERS = { 'X-Chain': 'stellar' };
1335
- /**
1336
- * Stellar Adapter - Gasless transactions via Fee Bump
1337
- * Routes through proxy.smoothsend.xyz with API key authentication
1338
- * Supports XLM, USDC, EURC and other Stellar assets
1339
- */
1340
- class StellarAdapter {
1341
- constructor(chain, config, apiKey, network = 'testnet', includeOrigin = false) {
1342
- if (CHAIN_ECOSYSTEM_MAP[chain] !== 'stellar') {
1343
- throw new SmoothSendError(`StellarAdapter can only handle Stellar chains, got: ${chain}`, 'INVALID_CHAIN_FOR_ADAPTER', 400, { chain });
1344
- }
1345
- this.chain = chain;
1346
- this.config = config;
1347
- this.network = network;
1348
- this.httpClient = new HttpClient({
1349
- apiKey,
1350
- network,
1351
- timeout: 30000,
1352
- retries: 3,
1353
- includeOrigin,
1354
- });
1355
- // Initialize C-Address adapter (Soroban Smart Account)
1356
- this.cAddress = new StellarCAddressAdapter(this.httpClient, network);
1357
- }
1358
- setNetwork(network) {
1359
- this.network = network;
1360
- this.httpClient.setNetwork(network);
1361
- }
1362
- getNetwork() {
1363
- return this.network;
1364
- }
1365
- /**
1366
- * Stellar gasless: relayer pays fee. Returns 0 for user.
1367
- */
1368
- async estimateFee(_request) {
1369
- return {
1370
- relayerFee: '0',
1371
- feeInUSD: '0',
1372
- coinType: _request.token || 'XLM',
1373
- estimatedGas: '0',
1374
- network: this.network,
1375
- };
1376
- }
1377
- /**
1378
- * Submit signed XDR to relayer for Fee Bump wrapping
1379
- */
1380
- async executeGaslessTransfer(signedData) {
1381
- if (!signedData.signedTransaction) {
1382
- throw new SmoothSendError('signedTransaction (XDR) is required for Stellar gasless transfers', STELLAR_ERROR_CODES.MISSING_SIGNED_TRANSACTION, 400, { chain: this.chain });
1383
- }
1384
- try {
1385
- const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', { signedTransaction: signedData.signedTransaction }, { headers: STELLAR_HEADERS });
1386
- const data = response.data;
1387
- const result = {
1388
- success: data.success ?? true,
1389
- txHash: data.hash ?? data.txnHash,
1390
- transferId: data.hash ?? data.txnHash,
1391
- explorerUrl: data.explorerUrl,
1392
- gasFeePaidBy: 'relayer',
1393
- gasUsed: data.feeStroops,
1394
- };
1395
- if (response.metadata) {
1396
- result.metadata = response.metadata;
1397
- }
1398
- return result;
1399
- }
1400
- catch (error) {
1401
- if (error instanceof SmoothSendError)
1402
- throw error;
1403
- throw new SmoothSendError(`Stellar gasless transfer failed: ${error instanceof Error ? error.message : String(error)}`, STELLAR_ERROR_CODES.GASLESS_TRANSACTION_ERROR, 500, { chain: this.chain });
1404
- }
1405
- }
1406
- async getTransactionStatus(txHash) {
1407
- try {
1408
- const response = await this.httpClient.get(`/api/v1/relayer/stellar/status/${txHash}`, { headers: STELLAR_HEADERS });
1409
- return response.data;
1410
- }
1411
- catch (error) {
1412
- if (error instanceof SmoothSendError)
1413
- throw error;
1414
- throw new SmoothSendError(`Failed to get Stellar transaction status: ${error instanceof Error ? error.message : String(error)}`, STELLAR_ERROR_CODES.STATUS_ERROR, 500, { chain: this.chain });
1415
- }
1416
- }
1417
- async getHealth() {
1418
- try {
1419
- const response = await this.httpClient.get('/api/v1/relayer/stellar/health', {
1420
- headers: STELLAR_HEADERS,
1421
- });
1422
- return {
1423
- success: true,
1424
- status: response.data.status ?? 'healthy',
1425
- timestamp: response.data.timestamp ?? new Date().toISOString(),
1426
- version: '2.0',
1427
- };
1428
- }
1429
- catch (error) {
1430
- if (error instanceof SmoothSendError)
1431
- throw error;
1432
- throw new SmoothSendError(`Stellar health check failed: ${error instanceof Error ? error.message : String(error)}`, STELLAR_ERROR_CODES.HEALTH_ERROR, 500, { chain: this.chain });
1433
- }
1434
- }
1435
- validateAddress(address) {
1436
- // Support both G-addresses (classic) and C-addresses (Soroban smart accounts)
1437
- return /^[GC][A-Z2-7]{55}$/.test(address);
1438
- }
1439
- validateAmount(amount) {
1440
- try {
1441
- const n = parseFloat(amount);
1442
- return !isNaN(n) && n > 0;
1443
- }
1444
- catch {
1445
- return false;
1446
- }
1447
- }
1448
- }
1449
-
1450
- class SmoothSendSDK {
1451
- constructor(config) {
1452
- this.adapters = new Map();
1453
- this.eventListeners = [];
1454
- this.hasWarnedAboutSecretKey = false;
1455
- // Validate API key is provided
1456
- if (!config.apiKey) {
1457
- throw new SmoothSendError('API key is required. Get your API key from dashboard.smoothsend.xyz', 'MISSING_API_KEY');
1458
- }
1459
- // Detect and validate API key type
1460
- this.keyType = this.detectKeyType(config.apiKey);
1461
- // Warn if secret key is used in browser environment
1462
- this.warnIfSecretKeyInBrowser();
1463
- // Validate network parameter if provided
1464
- if (config.network && config.network !== 'testnet' && config.network !== 'mainnet') {
1465
- throw new SmoothSendError('Invalid network parameter. Must be "testnet" or "mainnet"', 'INVALID_NETWORK');
1466
- }
1467
- // Set configuration with defaults
1468
- this.config = {
1469
- apiKey: config.apiKey,
1470
- network: config.network || 'testnet', // Default to testnet
1471
- timeout: config.timeout || 30000,
1472
- retries: config.retries || 3,
1473
- customHeaders: config.customHeaders || {}
1474
- };
1475
- }
1476
- /**
1477
- * Detect key type from API key prefix
1478
- * Supports pk_nogas_* (public), sk_nogas_* (secret), and no_gas_* (legacy)
1479
- */
1480
- detectKeyType(apiKey) {
1481
- if (apiKey.startsWith('pk_nogas_')) {
1482
- return 'public';
1483
- }
1484
- if (apiKey.startsWith('sk_nogas_')) {
1485
- return 'secret';
1486
- }
1487
- if (apiKey.startsWith('no_gas_')) {
1488
- return 'legacy';
1489
- }
1490
- throw new SmoothSendError('Invalid API key format. API key must start with "pk_nogas_", "sk_nogas_", or "no_gas_"', 'INVALID_API_KEY_FORMAT');
1491
- }
1492
- /**
1493
- * Check if running in browser environment
1494
- * Used for conditional warnings and Origin header logic
1495
- */
1496
- isBrowserEnvironment() {
1497
- return typeof window !== 'undefined' && typeof window.document !== 'undefined';
1498
- }
1499
- /**
1500
- * Warn if secret key is used in browser environment
1501
- * Only warns once per SDK instance
1502
- */
1503
- warnIfSecretKeyInBrowser() {
1504
- if (this.hasWarnedAboutSecretKey) {
1505
- return;
1506
- }
1507
- if (this.keyType === 'secret' && this.isBrowserEnvironment()) {
1508
- console.warn('⚠️ WARNING: Secret key detected in browser environment.\n' +
1509
- 'Secret keys (sk_nogas_*) should only be used in server-side code.\n' +
1510
- 'Use public keys (pk_nogas_*) for frontend applications.\n' +
1511
- 'Learn more: https://docs.smoothsend.xyz/security/api-keys');
1512
- this.hasWarnedAboutSecretKey = true;
1513
- }
1514
- }
1515
- /**
1516
- * Determine if Origin header should be included in requests
1517
- * Include Origin header only for public keys in browser environment
1518
- */
1519
- shouldIncludeOrigin() {
1520
- return this.keyType === 'public' && this.isBrowserEnvironment();
1521
- }
1522
- /**
1523
- * Get or create adapter for a specific chain on-demand
1524
- */
1525
- getOrCreateAdapter(chain) {
1526
- // Check if adapter already exists
1527
- let adapter = this.adapters.get(chain);
1528
- if (!adapter) {
1529
- // Create adapter on-demand
1530
- const ecosystem = CHAIN_ECOSYSTEM_MAP[chain];
1531
- if (ecosystem === 'aptos') {
1532
- // Create minimal config for adapter (proxy handles actual configuration)
1533
- const minimalConfig = {
1534
- name: chain,
1535
- displayName: chain,
1536
- chainId: 0,
1537
- rpcUrl: '',
1538
- relayerUrl: 'https://proxy.smoothsend.xyz',
1539
- explorerUrl: '',
1540
- tokens: [],
1541
- nativeCurrency: {
1542
- name: 'APT',
1543
- symbol: 'APT',
1544
- decimals: 8
1545
- }
1546
- };
1547
- adapter = new AptosAdapter(chain, minimalConfig, this.config.apiKey, this.config.network || 'testnet', this.shouldIncludeOrigin());
1548
- }
1549
- else if (ecosystem === 'stellar') {
1550
- const minimalConfig = {
1551
- name: chain,
1552
- displayName: chain,
1553
- chainId: 0,
1554
- rpcUrl: '',
1555
- relayerUrl: 'https://proxy.smoothsend.xyz',
1556
- explorerUrl: '',
1557
- tokens: [],
1558
- nativeCurrency: { name: 'XLM', symbol: 'XLM', decimals: 7 },
1559
- };
1560
- adapter = new StellarAdapter(chain, minimalConfig, this.config.apiKey, this.config.network || 'testnet', this.shouldIncludeOrigin());
1561
- }
1562
- else if (ecosystem === 'evm') {
1563
- throw new SmoothSendError(`EVM chains not yet supported in v2. Chain: ${chain}`, 'UNSUPPORTED_CHAIN');
1564
- }
1565
- else {
1566
- throw new SmoothSendError(`Unsupported ecosystem: ${ecosystem}`, 'UNSUPPORTED_ECOSYSTEM');
1567
- }
1568
- // Cache the adapter for future use
1569
- this.adapters.set(chain, adapter);
1570
- }
1571
- return adapter;
1572
- }
1573
- // Event handling
1574
- addEventListener(listener) {
1575
- this.eventListeners.push(listener);
1576
- }
1577
- removeEventListener(listener) {
1578
- const index = this.eventListeners.indexOf(listener);
1579
- if (index > -1) {
1580
- this.eventListeners.splice(index, 1);
1581
- }
1582
- }
1583
- emitEvent(event) {
1584
- this.eventListeners.forEach(listener => {
1585
- try {
1586
- listener(event);
1587
- }
1588
- catch (error) {
1589
- console.error('Error in event listener:', error);
1590
- }
1591
- });
1592
- }
1593
- // Core transfer methods
1594
- async estimateFee(request) {
1595
- const adapter = this.getOrCreateAdapter(request.chain);
1596
- this.emitEvent({
1597
- type: 'transfer_initiated',
1598
- data: { request },
1599
- timestamp: Date.now(),
1600
- chain: request.chain
1601
- });
1602
- try {
1603
- const feeEstimate = await adapter.estimateFee(request);
1604
- // Metadata is already attached by the adapter from HTTP response headers
1605
- return feeEstimate;
1606
- }
1607
- catch (error) {
1608
- this.emitEvent({
1609
- type: 'transfer_failed',
1610
- data: { error: error instanceof Error ? error.message : String(error), step: 'estimate_fee' },
1611
- timestamp: Date.now(),
1612
- chain: request.chain
1613
- });
1614
- throw error;
1615
- }
1616
- }
1617
- /**
1618
- * Submit a signed Stellar transaction (XDR) for gasless relay.
1619
- * Use when you've already built and signed the transaction.
1620
- *
1621
- * @example
1622
- * const signedXdr = await stellarWallet.signTransaction(tx);
1623
- * const result = await sdk.submitStellarTransaction(signedXdr);
1624
- */
1625
- async submitStellarTransaction(signedXdr) {
1626
- const chain = this.config.network === 'mainnet' ? 'stellar-mainnet' : 'stellar-testnet';
1627
- return this.executeGaslessTransfer({
1628
- signedTransaction: signedXdr,
1629
- chain,
1630
- network: this.config.network,
1631
- });
1632
- }
1633
- async executeGaslessTransfer(signedData) {
1634
- const adapter = this.getOrCreateAdapter(signedData.chain);
1635
- this.emitEvent({
1636
- type: 'transfer_submitted',
1637
- data: { signedData },
1638
- timestamp: Date.now(),
1639
- chain: signedData.chain
1640
- });
1641
- try {
1642
- const result = await adapter.executeGaslessTransfer(signedData);
1643
- this.emitEvent({
1644
- type: 'transfer_confirmed',
1645
- data: { result },
1646
- timestamp: Date.now(),
1647
- chain: signedData.chain
1648
- });
1649
- return result;
1650
- }
1651
- catch (error) {
1652
- this.emitEvent({
1653
- type: 'transfer_failed',
1654
- data: { error: error instanceof Error ? error.message : String(error), step: 'execute' },
1655
- timestamp: Date.now(),
1656
- chain: signedData.chain
1657
- });
1658
- throw error;
1659
- }
1660
- }
1661
- /**
1662
- * Convenience method for complete transfer flow
1663
- * Works for both Aptos and Stellar - same 3-line API.
1664
- *
1665
- * @param request Transfer request with from, to, token, amount, chain
1666
- * @param wallet Aptos or Stellar wallet provider
1667
- * @returns Transfer result with transaction hash and usage metadata
1668
- *
1669
- * Aptos wallet: signTransaction returns { transactionBytes, authenticatorBytes }
1670
- * Stellar wallet: signTransaction returns string (signed XDR)
1671
- */
1672
- async transfer(request, wallet) {
1673
- this.emitEvent({
1674
- type: 'transfer_initiated',
1675
- data: { request },
1676
- timestamp: Date.now(),
1677
- chain: request.chain,
1678
- });
1679
- try {
1680
- const ecosystem = CHAIN_ECOSYSTEM_MAP[request.chain];
1681
- if (ecosystem === 'stellar') {
1682
- return this.transferStellar(request, wallet);
1683
- }
1684
- // Aptos flow
1685
- const aptosWallet = wallet;
1686
- const feeEstimate = await this.estimateFee(request);
1687
- const transaction = await aptosWallet.buildTransaction({
1688
- sender: request.from,
1689
- recipient: request.to,
1690
- amount: request.amount,
1691
- coinType: feeEstimate.coinType,
1692
- relayerFee: feeEstimate.relayerFee,
1693
- });
1694
- this.emitEvent({
1695
- type: 'transfer_signed',
1696
- data: { transaction },
1697
- timestamp: Date.now(),
1698
- chain: request.chain,
1699
- });
1700
- const signedTx = await aptosWallet.signTransaction(transaction);
1701
- return this.executeGaslessTransfer({
1702
- transactionBytes: signedTx.transactionBytes,
1703
- authenticatorBytes: signedTx.authenticatorBytes,
1704
- chain: request.chain,
1705
- network: this.config.network,
1706
- });
1707
- }
1708
- catch (error) {
1709
- this.emitEvent({
1710
- type: 'transfer_failed',
1711
- data: {
1712
- error: error instanceof Error ? error.message : String(error),
1713
- step: 'transfer',
1714
- },
1715
- timestamp: Date.now(),
1716
- chain: request.chain,
1717
- });
1718
- throw error;
1719
- }
1720
- }
1721
- async transferStellar(request, wallet) {
1722
- const transaction = await wallet.buildTransaction({
1723
- from: request.from,
1724
- to: request.to,
1725
- amount: request.amount,
1726
- token: request.token,
1727
- });
1728
- this.emitEvent({
1729
- type: 'transfer_signed',
1730
- data: { transaction },
1731
- timestamp: Date.now(),
1732
- chain: request.chain,
1733
- });
1734
- const signedXdr = await wallet.signTransaction(transaction);
1735
- return this.executeGaslessTransfer({
1736
- signedTransaction: signedXdr,
1737
- chain: request.chain,
1738
- network: this.config.network,
1739
- });
1740
- }
1741
- // Note: Batch transfer support will be implemented in a future phase
1742
- // Utility methods
1743
- /**
1744
- * Get transaction status for a specific transaction
1745
- * Routes through proxy to chain-specific status endpoint
1746
- *
1747
- * @param chain Chain where the transaction was executed
1748
- * @param txHash Transaction hash to query
1749
- * @returns Transaction status information
1750
- * @throws SmoothSendError if chain is not supported or status check fails
1751
- *
1752
- * @example
1753
- * ```typescript
1754
- * const status = await sdk.getTransactionStatus('aptos-testnet', '0x123...');
1755
- * console.log('Transaction status:', status);
1756
- * ```
1757
- */
1758
- async getTransactionStatus(chain, txHash) {
1759
- if (!this.isChainSupported(chain)) {
1760
- throw new SmoothSendError(`Chain ${chain} is not supported`, 'UNSUPPORTED_CHAIN', 400, { chain, supportedChains: this.getSupportedChains() });
1761
- }
1762
- if (!txHash || txHash.trim() === '') {
1763
- throw new SmoothSendError('Transaction hash is required', 'MISSING_TX_HASH', 400);
1764
- }
1765
- const adapter = this.getOrCreateAdapter(chain);
1766
- return await adapter.getTransactionStatus(txHash);
1767
- }
1768
- validateAddress(chain, address) {
1769
- const adapter = this.getOrCreateAdapter(chain);
1770
- return adapter.validateAddress(address);
1771
- }
1772
- validateAmount(chain, amount) {
1773
- const adapter = this.getOrCreateAdapter(chain);
1774
- return adapter.validateAmount(amount);
1775
- }
1776
- /**
1777
- * Check proxy worker health status
1778
- * Routes directly to proxy's /health endpoint (not chain-specific)
1779
- *
1780
- * @returns Health response with status, version, and timestamp
1781
- * @throws NetworkError if proxy is unavailable
1782
- * @throws SmoothSendError for other errors
1783
- *
1784
- * @example
1785
- * ```typescript
1786
- * try {
1787
- * const health = await sdk.getHealth();
1788
- * console.log('Proxy status:', health.status);
1789
- * console.log('Version:', health.version);
1790
- * } catch (error) {
1791
- * if (error instanceof NetworkError) {
1792
- * console.error('Proxy unavailable. Please retry later.');
1793
- * }
1794
- * }
1795
- * ```
1796
- */
1797
- async getHealth() {
1798
- // Import HttpClient for direct proxy health check
1799
- const { HttpClient } = await Promise.resolve().then(function () { return http; });
1800
- // Create HTTP client for direct proxy communication
1801
- const httpClient = new HttpClient({
1802
- apiKey: this.config.apiKey,
1803
- network: this.config.network || 'testnet',
1804
- timeout: this.config.timeout,
1805
- retries: this.config.retries,
1806
- includeOrigin: this.shouldIncludeOrigin()
1807
- });
1808
- try {
1809
- // Check proxy's general health endpoint (not chain-specific)
1810
- const response = await httpClient.get('/health');
1811
- const healthResponse = {
1812
- success: true,
1813
- status: response.data.status || 'healthy',
1814
- timestamp: response.data.timestamp || new Date().toISOString(),
1815
- version: response.data.version || '2.0'
1816
- };
1817
- // Attach usage metadata from proxy response headers
1818
- if (response.metadata) {
1819
- healthResponse.metadata = response.metadata;
1820
- }
1821
- return healthResponse;
1822
- }
1823
- catch (error) {
1824
- if (error instanceof SmoothSendError) {
1825
- throw error;
1826
- }
1827
- throw new SmoothSendError(`Failed to check proxy health: ${error instanceof Error ? error.message : String(error)}. Please check your connection and retry.`, 'HEALTH_CHECK_ERROR', 500);
1828
- }
1829
- }
1830
- /**
1831
- * Get list of supported chains (static list)
1832
- * For dynamic list from proxy, use getSupportedChainsFromProxy()
1833
- *
1834
- * @returns Array of supported chain identifiers
1835
- *
1836
- * @example
1837
- * ```typescript
1838
- * const chains = sdk.getSupportedChains();
1839
- * console.log('Supported chains:', chains);
1840
- * // Output: ['aptos-testnet', 'aptos-mainnet']
1841
- * ```
1842
- */
1843
- getSupportedChains() {
1844
- return ['aptos-testnet', 'aptos-mainnet', 'stellar-testnet', 'stellar-mainnet'];
1845
- }
1846
- /**
1847
- * Get list of supported chains from proxy worker (dynamic)
1848
- * Queries the proxy for the current list of supported chains
1849
- *
1850
- * @returns Promise with array of chain information including status
1851
- * @throws SmoothSendError if unable to fetch chains from proxy
1852
- *
1853
- * @example
1854
- * ```typescript
1855
- * const chains = await sdk.getSupportedChainsFromProxy();
1856
- * chains.forEach(chain => {
1857
- * console.log(`${chain.name} (${chain.id}): ${chain.status}`);
1858
- * });
1859
- * ```
1860
- */
1861
- async getSupportedChainsFromProxy() {
1862
- const { HttpClient } = await Promise.resolve().then(function () { return http; });
1863
- const httpClient = new HttpClient({
1864
- apiKey: this.config.apiKey,
1865
- network: this.config.network || 'testnet',
1866
- timeout: this.config.timeout,
1867
- retries: this.config.retries,
1868
- includeOrigin: this.shouldIncludeOrigin()
1869
- });
1870
- try {
1871
- const response = await httpClient.get('/api/v1/chains');
1872
- if (!response.data.chains) {
1873
- throw new Error('Invalid response format from proxy');
1874
- }
1875
- return response.data.chains;
1876
- }
1877
- catch (error) {
1878
- if (error instanceof SmoothSendError) {
1879
- throw error;
1880
- }
1881
- throw new SmoothSendError(`Failed to fetch supported chains from proxy: ${error instanceof Error ? error.message : String(error)}`, 'CHAINS_FETCH_ERROR', 500);
1882
- }
1883
- }
1884
- /**
1885
- * Check if a specific chain is currently supported
1886
- *
1887
- * @param chain Chain identifier to check
1888
- * @returns true if chain is supported, false otherwise
1889
- *
1890
- * @example
1891
- * ```typescript
1892
- * if (sdk.isChainSupported('aptos-testnet')) {
1893
- * console.log('Aptos testnet is supported');
1894
- * } else {
1895
- * console.log('Chain not supported');
1896
- * }
1897
- * ```
1898
- */
1899
- isChainSupported(chain) {
1900
- const supportedChains = this.getSupportedChains();
1901
- return supportedChains.includes(chain);
1902
- }
1903
- /**
1904
- * Check health status of a specific chain's relayer
1905
- * Routes through proxy to chain-specific health endpoint
1906
- *
1907
- * @param chain Chain identifier to check
1908
- * @returns Health response for the specific chain
1909
- * @throws SmoothSendError if chain is not supported or health check fails
1910
- *
1911
- * @example
1912
- * ```typescript
1913
- * try {
1914
- * const health = await sdk.getChainHealth('aptos-testnet');
1915
- * console.log('Aptos testnet status:', health.status);
1916
- * } catch (error) {
1917
- * console.error('Chain health check failed:', error.message);
1918
- * }
1919
- * ```
1920
- */
1921
- async getChainHealth(chain) {
1922
- if (!this.isChainSupported(chain)) {
1923
- throw new SmoothSendError(`Chain ${chain} is not supported`, 'UNSUPPORTED_CHAIN', 400, { chain, supportedChains: this.getSupportedChains() });
1924
- }
1925
- const adapter = this.getOrCreateAdapter(chain);
1926
- return await adapter.getHealth();
1927
- }
1928
- /**
1929
- * Get current usage statistics without making a transfer
1930
- * Makes a lightweight health check request to retrieve usage metadata
1931
- *
1932
- * @returns Usage metadata with rate limit and monthly usage information
1933
- * @throws Error if unable to retrieve usage stats
1934
- *
1935
- * @example
1936
- * ```typescript
1937
- * const usage = await sdk.getUsageStats();
1938
- * console.log('Rate limit:', usage.rateLimit);
1939
- * console.log('Monthly usage:', usage.monthly);
1940
- * console.log('Request ID:', usage.requestId);
1941
- *
1942
- * // Check if approaching limits
1943
- * if (parseInt(usage.rateLimit.remaining) < 2) {
1944
- * console.warn('Approaching rate limit!');
1945
- * }
1946
- * ```
1947
- */
1948
- async getUsageStats() {
1949
- try {
1950
- // Make a health check request to get usage metadata from headers
1951
- const health = await this.getHealth();
1952
- // The health response includes metadata from the HTTP client
1953
- const healthWithMetadata = health;
1954
- if (!healthWithMetadata.metadata) {
1955
- throw new SmoothSendError('Usage metadata not available. This may occur if not using proxy mode.', 'METADATA_NOT_AVAILABLE');
1956
- }
1957
- return healthWithMetadata.metadata;
1958
- }
1959
- catch (error) {
1960
- // If health check fails, we can't get usage stats
1961
- if (error instanceof SmoothSendError) {
1962
- throw error;
1963
- }
1964
- throw new SmoothSendError(`Failed to retrieve usage statistics: ${error instanceof Error ? error.message : String(error)}`, 'USAGE_STATS_ERROR');
1965
- }
1966
- }
1967
- /**
1968
- * Extract request ID from a transfer result for debugging and support
1969
- *
1970
- * @param result Transfer result from executeGaslessTransfer or transfer
1971
- * @returns Request ID if available, undefined otherwise
1972
- *
1973
- * @example
1974
- * ```typescript
1975
- * const result = await sdk.executeGaslessTransfer(signedData);
1976
- * const requestId = sdk.getRequestId(result);
1977
- * if (requestId) {
1978
- * console.log('Request ID for support:', requestId);
1979
- * }
1980
- * ```
1981
- */
1982
- getRequestId(result) {
1983
- return result.metadata?.requestId;
1984
- }
1985
- /**
1986
- * Check if approaching rate limit based on transfer result metadata
1987
- *
1988
- * @param result Transfer result with metadata
1989
- * @param threshold Percentage threshold (0-100) to consider as "approaching" (default: 20)
1990
- * @returns true if remaining requests are below threshold percentage
1991
- *
1992
- * @example
1993
- * ```typescript
1994
- * const result = await sdk.transfer(request, wallet);
1995
- * if (sdk.isApproachingRateLimit(result)) {
1996
- * console.warn('Approaching rate limit, consider slowing down requests');
1997
- * }
1998
- * ```
1999
- */
2000
- isApproachingRateLimit(result, threshold = 20) {
2001
- if (!result.metadata?.rateLimit) {
2002
- return false;
2003
- }
2004
- const limit = parseInt(result.metadata.rateLimit.limit);
2005
- const remaining = parseInt(result.metadata.rateLimit.remaining);
2006
- if (isNaN(limit) || isNaN(remaining) || limit === 0) {
2007
- return false;
2008
- }
2009
- const percentageRemaining = (remaining / limit) * 100;
2010
- return percentageRemaining <= threshold;
2011
- }
2012
- /**
2013
- * Check if approaching monthly usage limit based on transfer result metadata
2014
- *
2015
- * @param result Transfer result with metadata
2016
- * @param threshold Percentage threshold (0-100) to consider as "approaching" (default: 90)
2017
- * @returns true if monthly usage is above threshold percentage
2018
- *
2019
- * @example
2020
- * ```typescript
2021
- * const result = await sdk.transfer(request, wallet);
2022
- * if (sdk.isApproachingMonthlyLimit(result)) {
2023
- * console.warn('Approaching monthly limit, consider upgrading plan');
2024
- * }
2025
- * ```
2026
- */
2027
- isApproachingMonthlyLimit(result, threshold = 90) {
2028
- if (!result.metadata?.monthly) {
2029
- return false;
2030
- }
2031
- const limit = parseInt(result.metadata.monthly.limit);
2032
- const usage = parseInt(result.metadata.monthly.usage);
2033
- if (isNaN(limit) || isNaN(usage) || limit === 0) {
2034
- return false;
2035
- }
2036
- const percentageUsed = (usage / limit) * 100;
2037
- return percentageUsed >= threshold;
2038
- }
2039
- // Ecosystem-specific methods for advanced usage
2040
- /**
2041
- * Check if a chain belongs to a specific ecosystem
2042
- */
2043
- getChainEcosystem(chain) {
2044
- return CHAIN_ECOSYSTEM_MAP[chain];
2045
- }
2046
- // Static utility methods
2047
- /**
2048
- * Get list of supported chains (static method)
2049
- * Can be called without instantiating the SDK
2050
- *
2051
- * @returns Array of supported chain identifiers
2052
- *
2053
- * @example
2054
- * ```typescript
2055
- * const chains = SmoothSendSDK.getSupportedChains();
2056
- * console.log('Supported chains:', chains);
2057
- * ```
2058
- */
2059
- static getSupportedChains() {
2060
- return ['aptos-testnet', 'aptos-mainnet', 'stellar-testnet', 'stellar-mainnet'];
2061
- }
2062
- }
2063
-
2064
- /**
2065
- * Pre-compiled Move script bytecode for add_permissioned_handle
2066
- *
2067
- * This bytecode is used to register session keys on-chain via the
2068
- * `0x1::permissioned_delegation::add_permissioned_handle` function.
2069
- *
2070
- * The function cannot be called as an entry function directly — only via a Move script.
2071
- * This bytecode handles:
2072
- * - Takes the session public key bytes (vector<u8>) as input
2073
- * - Constructs DelegationKey from the bytes
2074
- * - Passes option::none() for rate limiter
2075
- * - Hardcodes u64::MAX for expiration (on-chain handle never expires)
2076
- *
2077
- * Source: aptos-labs/aptos-ts-sdk tests/e2e/transaction/helper.ts
2078
- */
2079
- const ADD_PERMISSIONED_HANDLE_BYTECODE = 'a11ceb0b0700000a0801001002101603262c04520405563d079301d70208ea034010aa041f0103010401060109010d010e011201140002080002080700030b0700040c0f0005100701000001050301010001020704050001030a05060001050f01080100010311090a000106130b01000107150b0100010002030702060c0a020001080001060c010a02010801010802010803010b0401090004060c08020b0401080303010c03060c060c03050802030b04010803060c0c083c53454c463e5f30046d61696e094170746f73436f696e0a6170746f735f636f696e04636f696e196d6967726174655f746f5f66756e6769626c655f73746f72650765643235353139256e65775f756e76616c6964617465645f7075626c69635f6b65795f66726f6d5f627974657314556e76616c6964617465645075626c69634b657917' +
2080
- '7065726d697373696f6e65645f64656c65676174696f6e0f67656e5f656432353531395f6b65790d44656c65676174696f6e4b65790b526174654c696d697465720c726174655f6c696d69746572066f7074696f6e046e6f6e65064f7074696f6e176164645f7065726d697373696f6e65645f68616e646c65167072696d6172795f66756e6769626c655f73746f7265146772616e745f6170745f7065726d697373696f6e167472616e73616374696f6e5f76616c69646174696f6e146772616e745f6761735f7065726d697373696f6effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000114636f6d70696c6174696f6e5f6d65746164617461090003322e3003322e3100000c170a0038000b01110111020c020a0038010c040b020b040600a0724e1809000011040c060a000e060600e1f5050000000011050b000e060600e1f50500000000110602';
2081
-
2082
- /**
2083
- * SmoothSend Transaction Submitter
2084
- *
2085
- * A TransactionSubmitter implementation that integrates with the Aptos Wallet Adapter
2086
- * to enable gasless transactions via SmoothSend's relayer network.
2087
- *
2088
- * @example
2089
- * ```typescript
2090
- * import { SmoothSendTransactionSubmitter } from '@smoothsend/sdk';
2091
- * import { AptosWalletAdapterProvider } from '@aptos-labs/wallet-adapter-react';
2092
- *
2093
- * // Create the transaction submitter
2094
- * const transactionSubmitter = new SmoothSendTransactionSubmitter({
2095
- * apiKey: 'pk_nogas_your_api_key_here',
2096
- * network: 'testnet'
2097
- * });
2098
- *
2099
- * // Use in your wallet provider - that's it!
2100
- * <AptosWalletAdapterProvider
2101
- * dappConfig={{
2102
- * network: Network.TESTNET,
2103
- * transactionSubmitter: transactionSubmitter
2104
- * }}
2105
- * >
2106
- * <App />
2107
- * </AptosWalletAdapterProvider>
2108
- * ```
2109
- */
2110
- /**
2111
- * SmoothSend Transaction Submitter
2112
- *
2113
- * Implements the TransactionSubmitter interface to enable gasless transactions
2114
- * through the Aptos Wallet Adapter. Simply pass this to your AptosWalletAdapterProvider
2115
- * and all transactions will automatically be submitted as gasless through SmoothSend.
2116
- */
2117
- class SmoothSendTransactionSubmitter {
2118
- constructor(config) {
2119
- this._session = null;
2120
- this.sponsoredFunctionsCache = null;
2121
- this.sponsoredFunctionsCacheAt = 0;
2122
- this.SPONSORED_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
2123
- if (!config.apiKey) {
2124
- throw new Error('SmoothSend API key is required. Get your key at dashboard.smoothsend.xyz');
2125
- }
2126
- // Validate API key format
2127
- if (!config.apiKey.startsWith('pk_nogas_') &&
2128
- !config.apiKey.startsWith('sk_nogas_') &&
2129
- !config.apiKey.startsWith('no_gas_')) {
2130
- throw new Error('Invalid API key format. Key must start with pk_nogas_, sk_nogas_, or no_gas_');
2131
- }
2132
- // Warn if using secret key in browser
2133
- if (config.apiKey.startsWith('sk_nogas_') && typeof window !== 'undefined') {
2134
- console.warn('⚠️ WARNING: Secret key detected in browser environment.\n' +
2135
- 'Secret keys (sk_nogas_*) should only be used in server-side code.\n' +
2136
- 'Use public keys (pk_nogas_*) for frontend applications.');
2137
- }
2138
- this.apiKey = config.apiKey;
2139
- this.network = config.network || 'testnet';
2140
- this.gatewayUrl = config.gatewayUrl || 'https://proxy.smoothsend.xyz';
2141
- this.timeout = config.timeout || 30000;
2142
- this.getCaptchaToken = config.getCaptchaToken;
2143
- this.debug = config.debug || false;
2144
- this.sessionEnabled = config.session || false;
2145
- this.sessionDuration = config.sessionDuration || '24h';
2146
- }
2147
- // ─── Session key methods ────────────────────────────────────────────────────
2148
- /**
2149
- * Whether a valid session is currently active.
2150
- */
2151
- hasSession() {
2152
- return this._session !== null && Date.now() < this._session.expiresAtMs;
2153
- }
2154
- /**
2155
- * Create a session key for the given master account.
2156
- * Called once by useSmoothSend when session: true and no session exists.
2157
- * SmoothSend pays gas for the setup transaction.
2158
- *
2159
- * @param masterAccount - The user's wallet account (from wallet adapter)
2160
- */
2161
- async createSession(masterAccount) {
2162
- const network = this.network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2163
- const aptosClient = new Aptos(new AptosConfig({ network }));
2164
- // Generate fresh in-memory session keypair
2165
- const sessionAccount = Account.generate();
2166
- const expiresAtMs = Date.now() + this._parseDuration(this.sessionDuration);
2167
- // Step 1: Register session key on-chain via pre-compiled Move script
2168
- const setupTx = await aptosClient.transaction.build.simple({
2169
- sender: masterAccount.accountAddress,
2170
- withFeePayer: true,
2171
- data: {
2172
- bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
2173
- functionArguments: [MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
2174
- },
2175
- options: {
2176
- replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2177
- },
2178
- });
2179
- const senderAuth = await this.signSenderAuthenticator(masterAccount, setupTx, aptosClient);
2180
- const setupResult = await this.submitTransaction({
2181
- aptosConfig: aptosClient.config,
2182
- transaction: setupTx,
2183
- senderAuthenticator: senderAuth,
2184
- });
2185
- await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
2186
- if (this.debug) {
2187
- console.log('[SmoothSend] Session key registered on-chain:', setupResult.hash);
2188
- }
2189
- // Step 2: Enable account abstraction (idempotent — skip if already on)
2190
- const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
2191
- accountAddress: masterAccount.accountAddress,
2192
- authenticationFunction: '0x1::permissioned_delegation::authenticate',
2193
- });
2194
- if (!aaEnabled) {
2195
- const aaTx = await aptosClient.transaction.build.simple({
2196
- sender: masterAccount.accountAddress,
2197
- withFeePayer: true,
2198
- data: {
2199
- function: '0x1::account_abstraction::add_authentication_function',
2200
- functionArguments: [
2201
- AccountAddress.fromString('0x1'),
2202
- 'permissioned_delegation',
2203
- 'authenticate',
2204
- ],
2205
- },
2206
- options: {
2207
- replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2208
- },
2209
- });
2210
- const aaAuth = await this.signSenderAuthenticator(masterAccount, aaTx, aptosClient);
2211
- const aaResult = await this.submitTransaction({
2212
- aptosConfig: aptosClient.config,
2213
- transaction: aaTx,
2214
- senderAuthenticator: aaAuth,
2215
- });
2216
- await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
2217
- if (this.debug) {
2218
- console.log('[SmoothSend] Account abstraction enabled:', aaResult.hash);
2219
- }
2220
- }
2221
- // Build AbstractedAccount — signs future txs with session key,
2222
- // sender on-chain = master address, chain validates via permissioned_delegation
2223
- const abstractedAccount = AbstractedAccount.fromPermissionedSigner({
2224
- signer: sessionAccount,
2225
- accountAddress: masterAccount.accountAddress,
2226
- });
2227
- this._session = {
2228
- sessionAccount,
2229
- abstractedAccount,
2230
- masterAddress: masterAccount.accountAddress,
2231
- expiresAtMs,
2232
- aptosClient,
2233
- };
2234
- }
2235
- async isPermissionedSignerEnabled(aptosClient) {
2236
- try {
2237
- const result = await aptosClient.view({
2238
- payload: {
2239
- function: '0x1::features::is_permissioned_signer_enabled',
2240
- functionArguments: [],
2241
- },
2242
- });
2243
- return Array.isArray(result) && result[0] === true;
2244
- }
2245
- catch (error) {
2246
- if (this.debug) {
2247
- console.warn('[SmoothSend] Failed to probe permissioned signer feature:', error);
2248
- }
2249
- return false;
2250
- }
2251
- }
2252
- async signSenderAuthenticator(signer, transaction, aptosClient) {
2253
- const walletLikeSigner = signer;
2254
- // Wallet-adapter compatible path (returns { authenticator, rawTransaction } in v8)
2255
- if (typeof walletLikeSigner?.signTransactionWithAuthenticator === 'function') {
2256
- const result = await walletLikeSigner.signTransactionWithAuthenticator(transaction);
2257
- return (result?.authenticator ?? result);
2258
- }
2259
- // Native ts-sdk account path
2260
- return aptosClient.transaction.sign({
2261
- signer,
2262
- transaction,
2263
- });
2264
- }
2265
- /**
2266
- * Submit a transaction using the active session key — no wallet popup.
2267
- * Called by useSmoothSend after session is established.
2268
- */
2269
- async submitWithSession(functionName, functionArguments = [], typeArguments = []) {
2270
- if (!this._session || !this.hasSession()) {
2271
- throw new Error('[SmoothSend] No active session. Call createSession() first.');
2272
- }
2273
- const { abstractedAccount, masterAddress, aptosClient } = this._session;
2274
- const tx = await aptosClient.transaction.build.simple({
2275
- sender: masterAddress,
2276
- withFeePayer: true,
2277
- data: {
2278
- function: functionName,
2279
- functionArguments,
2280
- ...(typeArguments.length > 0 ? { typeArguments } : {}),
2281
- },
2282
- options: {
2283
- replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2284
- },
2285
- });
2286
- const senderAuth = aptosClient.transaction.sign({
2287
- signer: abstractedAccount,
2288
- transaction: tx,
2289
- });
2290
- return this.submitTransaction({
2291
- aptosConfig: aptosClient.config,
2292
- transaction: tx,
2293
- senderAuthenticator: senderAuth,
2294
- });
2295
- }
2296
- _parseDuration(duration) {
2297
- if (duration === 'never') {
2298
- // Client-side "never expires" mode; on-chain handle already uses u64::MAX.
2299
- return Number.MAX_SAFE_INTEGER;
2300
- }
2301
- const n = parseInt(duration, 10);
2302
- if (isNaN(n))
2303
- throw new Error(`Invalid sessionDuration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
2304
- if (duration.endsWith('s'))
2305
- return n * 1000;
2306
- if (duration.endsWith('m'))
2307
- return n * 60 * 1000;
2308
- if (duration.endsWith('h'))
2309
- return n * 3600 * 1000;
2310
- if (duration.endsWith('d'))
2311
- return n * 86400 * 1000;
2312
- throw new Error(`Unknown unit in "${duration}". Supported: s, m, h, d, or "never".`);
2313
- }
2314
- // ─── Transaction submission ──────────────────────────────────────────────────
2315
- /**
2316
- * Submit a transaction through SmoothSend's gasless relayer
2317
- *
2318
- * This method is called automatically by the Aptos Wallet Adapter when
2319
- * you use signAndSubmitTransaction. The transaction is submitted to
2320
- * SmoothSend's relayer which sponsors the gas fees.
2321
- */
2322
- async submitTransaction(args) {
2323
- const { aptosConfig, transaction, senderAuthenticator, pluginParams } = args;
2324
- // Auto-detect network from aptosConfig (source of truth from wallet adapter)
2325
- // Falls back to constructor value if aptosConfig doesn't have a recognized network
2326
- const detectedNetwork = this.resolveNetwork(aptosConfig);
2327
- if (this.debug) {
2328
- console.log('[SmoothSend] Submitting gasless transaction:', {
2329
- sender: transaction.rawTransaction?.sender?.toString(),
2330
- configNetwork: this.network,
2331
- detectedNetwork,
2332
- });
2333
- }
2334
- if (detectedNetwork !== this.network && this.debug) {
2335
- console.warn(`[SmoothSend] Network mismatch: constructor=${this.network}, aptosConfig=${detectedNetwork}. ` +
2336
- `Using aptosConfig network (${detectedNetwork}).`);
2337
- }
2338
- try {
2339
- // Serialize transaction and authenticator to bytes
2340
- const transactionBytes = Array.from(transaction.bcsToBytes());
2341
- const authenticatorBytes = Array.from(senderAuthenticator.bcsToBytes());
2342
- // Prepare request payload — always use the detected network
2343
- const payload = {
2344
- transactionBytes,
2345
- authenticatorBytes,
2346
- network: detectedNetwork,
2347
- functionName: pluginParams?.functionName || 'unknown',
2348
- };
2349
- // Make request to SmoothSend gateway
2350
- const response = await this.makeRequest('/api/v1/relayer/gasless-transaction', payload, detectedNetwork);
2351
- if (!response.success || !response.txnHash) {
2352
- throw new Error(response.error || response.details || 'Transaction submission failed');
2353
- }
2354
- if (this.debug) {
2355
- console.log('[SmoothSend] Transaction successful:', {
2356
- hash: response.txnHash,
2357
- gasUsed: response.gasUsed,
2358
- });
2359
- }
2360
- // Return in the format expected by Aptos SDK
2361
- return {
2362
- hash: response.txnHash,
2363
- sender: response.sender || transaction.rawTransaction?.sender?.toString() || '',
2364
- sequence_number: transaction.rawTransaction?.sequence_number?.toString() || '0',
2365
- max_gas_amount: transaction.rawTransaction?.max_gas_amount?.toString() || '0',
2366
- gas_unit_price: transaction.rawTransaction?.gas_unit_price?.toString() || '0',
2367
- expiration_timestamp_secs: transaction.rawTransaction?.expiration_timestamp_secs?.toString() || '0',
2368
- payload: {},
2369
- signature: undefined,
2370
- };
2371
- }
2372
- catch (error) {
2373
- if (this.debug) {
2374
- console.error('[SmoothSend] Transaction failed:', error);
2375
- }
2376
- throw new Error(`SmoothSend gasless transaction failed: ${error.message}`);
2377
- }
2378
- }
2379
- /**
2380
- * Resolve the effective network from aptosConfig.
2381
- * aptosConfig.network is the source of truth set by AptosWalletAdapterProvider.
2382
- */
2383
- resolveNetwork(aptosConfig) {
2384
- try {
2385
- const configNetwork = aptosConfig?.network;
2386
- if (configNetwork === 'testnet' || configNetwork === 'mainnet') {
2387
- return configNetwork;
2388
- }
2389
- if (typeof configNetwork === 'string') {
2390
- const normalized = configNetwork.toLowerCase();
2391
- if (normalized === 'testnet' || normalized === 'mainnet') {
2392
- return normalized;
2393
- }
2394
- }
2395
- }
2396
- catch {
2397
- // fall through
2398
- }
2399
- return this.network;
2400
- }
2401
- /**
2402
- * Make an HTTP request to the SmoothSend gateway
2403
- */
2404
- async makeRequest(endpoint, payload, network, method = 'POST') {
2405
- const effectiveNetwork = network || this.network;
2406
- const url = `${this.gatewayUrl}${endpoint}`;
2407
- const headers = {
2408
- 'Content-Type': 'application/json',
2409
- 'X-API-Key': this.apiKey,
2410
- 'X-Chain': `aptos-${effectiveNetwork}`,
2411
- };
2412
- // Add Origin header for public keys in browser
2413
- if (this.apiKey.startsWith('pk_nogas_') && typeof window !== 'undefined') {
2414
- headers['Origin'] = window.location.origin;
2415
- }
2416
- // Add captcha token if the project requires it
2417
- if (this.getCaptchaToken) {
2418
- try {
2419
- const token = await this.getCaptchaToken();
2420
- if (token) {
2421
- headers['X-Captcha-Token'] = token;
2422
- }
2423
- }
2424
- catch (e) {
2425
- if (this.debug) {
2426
- console.warn('[SmoothSend] Failed to get captcha token:', e);
2427
- }
2428
- }
2429
- }
2430
- const controller = new AbortController();
2431
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
2432
- try {
2433
- const response = await fetch(url, {
2434
- method,
2435
- headers,
2436
- body: method === 'GET' ? undefined : JSON.stringify(payload),
2437
- signal: controller.signal,
2438
- });
2439
- clearTimeout(timeoutId);
2440
- if (!response.ok) {
2441
- const errorData = await response.json().catch(() => ({}));
2442
- throw new Error(errorData.error || errorData.message || `HTTP ${response.status}`);
2443
- }
2444
- return await response.json();
2445
- }
2446
- catch (error) {
2447
- clearTimeout(timeoutId);
2448
- if (error.name === 'AbortError') {
2449
- throw new Error('Request timed out');
2450
- }
2451
- throw error;
2452
- }
2453
- }
2454
- /**
2455
- * Fetch the list of sponsored functions for this API key's project.
2456
- * Results are cached for 5 minutes. Returns ['*'] if all functions are sponsored.
2457
- */
2458
- async getSponsoredFunctions() {
2459
- const now = Date.now();
2460
- if (this.sponsoredFunctionsCache !== null && now - this.sponsoredFunctionsCacheAt < this.SPONSORED_CACHE_TTL) {
2461
- return this.sponsoredFunctionsCache;
2462
- }
2463
- try {
2464
- const response = await this.makeRequest('/api/v1/sponsorship', {}, undefined, 'GET');
2465
- const fns = response.sponsoredFunctions;
2466
- this.sponsoredFunctionsCache = Array.isArray(fns) ? fns : ['*'];
2467
- }
2468
- catch {
2469
- this.sponsoredFunctionsCache = ['*']; // fail-open: assume all sponsored
2470
- }
2471
- this.sponsoredFunctionsCacheAt = now;
2472
- return this.sponsoredFunctionsCache;
2473
- }
2474
- /**
2475
- * Check if a specific function is sponsored for gasless execution.
2476
- * @param functionName - Full function identifier, e.g. "0x123::module::function"
2477
- */
2478
- async isSponsored(functionName) {
2479
- const fns = await this.getSponsoredFunctions();
2480
- if (fns.includes('*'))
2481
- return true;
2482
- const normalize = (id) => id.replace(/^(0x)0+([1-9a-f][0-9a-f]*)(::.+)$/i, '$1$2$3').toLowerCase();
2483
- const normalized = normalize(functionName);
2484
- return fns.some(f => normalize(f) === normalized);
2485
- }
2486
- /**
2487
- */
2488
- getConfig() {
2489
- return {
2490
- apiKey: this.apiKey.substring(0, 15) + '...', // Don't expose full key
2491
- network: this.network,
2492
- gatewayUrl: this.gatewayUrl,
2493
- timeout: this.timeout,
2494
- debug: this.debug,
2495
- };
2496
- }
2497
- }
2498
- /**
2499
- * Create a SmoothSend transaction submitter with minimal configuration
2500
- *
2501
- * @example
2502
- * ```typescript
2503
- * const submitter = createSmoothSendSubmitter('pk_nogas_your_key');
2504
- * ```
2505
- */
2506
- function createSmoothSendSubmitter(apiKey, options) {
2507
- return new SmoothSendTransactionSubmitter({
2508
- apiKey,
2509
- ...options,
2510
- });
2511
- }
2512
-
2513
- /**
2514
- * useSmoothSend — React hook for automatic gasless / user-pays-gas routing
2515
- *
2516
- * Drop-in replacement for useWallet()'s signAndSubmitTransaction.
2517
- * Fetches the project's sponsored-functions list from the gateway on mount
2518
- * and routes each transaction automatically:
2519
- * - Function in allowlist → fee-payer gasless path via SmoothSend
2520
- * - Function not in allowlist → regular wallet submission (user pays gas)
2521
- *
2522
- * When submitter has session: true, the first transaction triggers a one-time
2523
- * wallet sign to register a session key on-chain. Every transaction after that
2524
- * is signed silently — zero wallet popups.
2525
- *
2526
- * Requires: react >=17, @aptos-labs/wallet-adapter-react >=3, @aptos-labs/ts-sdk >=1
2527
- *
2528
- * @example
2529
- * ```tsx
2530
- * // Replace useWallet() with useSmoothSend() where you submit transactions.
2531
- * // No other changes needed.
2532
- *
2533
- * const { signAndSubmitTransaction } = useSmoothSend(submitter);
2534
- * await signAndSubmitTransaction({ data: { function: '0x1::coin::transfer', functionArguments: [to, amount] } });
2535
- * ```
2536
- */
2537
- function useSmoothSend(submitter) {
2538
- const { account, signTransaction, signAndSubmitTransaction: walletSignAndSubmit, } = useWallet();
2539
- // Track session state reactively so UI updates when session is created/expires
2540
- const initialHasSession = submitter?.hasSession?.() ?? false;
2541
- const [hasSessionState, setHasSessionState] = useState(initialHasSession);
2542
- // Prefetch the sponsored-functions list on mount so the first transaction
2543
- // benefits from an already-populated cache with no added latency.
2544
- useEffect(() => {
2545
- submitter.getSponsoredFunctions().catch(() => {
2546
- // Fail-open: getSponsoredFunctions already handles errors internally
2547
- });
2548
- }, [submitter]);
2549
- useEffect(() => {
2550
- if (!submitter)
2551
- return;
2552
- const refresh = () => {
2553
- const hasSession = submitter.hasSession?.() ?? false;
2554
- setHasSessionState(hasSession);
2555
- };
2556
- refresh();
2557
- const timer = setInterval(refresh, 1000);
2558
- return () => clearInterval(timer);
2559
- }, [submitter]);
2560
- const signAndSubmitTransaction = useCallback(async (input) => {
2561
- if (!account?.address) {
2562
- throw new Error('[SmoothSend] Wallet not connected');
2563
- }
2564
- const functionName = input?.data?.function ?? '';
2565
- console.log('[SmoothSend] signAndSubmitTransaction called:', {
2566
- functionName,
2567
- sessionEnabled: submitter.sessionEnabled,
2568
- hasSession: submitter.hasSession(),
2569
- });
2570
- // ── Session key path ────────────────────────────────────────────────────
2571
- // When session: true, bypass wallet signing entirely after first setup.
2572
- // Still respects the per-function allowlist — non-sponsored functions
2573
- // fall through to regular wallet submission (user pays gas).
2574
- if (submitter.sessionEnabled) {
2575
- console.log('[SmoothSend] Session mode enabled');
2576
- // Check allowlist first — no point setting up a session for a non-sponsored function
2577
- const canGoGasless = typeof signTransaction === 'function';
2578
- const sponsored = canGoGasless && (await submitter.isSponsored(functionName));
2579
- console.log('[SmoothSend] Sponsored check:', { sponsored, canGoGasless });
2580
- if (sponsored) {
2581
- // If no active session, do the one-time setup
2582
- if (!submitter.hasSession()) {
2583
- console.log('[SmoothSend] No session, creating one...');
2584
- if (!signTransaction) {
2585
- console.warn('[SmoothSend] session: true requires signTransaction support. Falling back to regular submission.');
2586
- }
2587
- else {
2588
- try {
2589
- // Adapter object only needs accountAddress + signTransactionWithAuthenticator.
2590
- // The submitter handles both wallet-adapter and native signer shapes.
2591
- const walletAccount = {
2592
- accountAddress: account.address,
2593
- signTransactionWithAuthenticator: async (tx) => {
2594
- const rawResult = await signTransaction({
2595
- transactionOrPayload: tx,
2596
- asFeePayer: false,
2597
- });
2598
- return rawResult?.authenticator ?? rawResult;
2599
- },
2600
- };
2601
- await submitter.createSession(walletAccount);
2602
- console.log('[SmoothSend] Session created successfully');
2603
- setHasSessionState(submitter.hasSession?.() ?? false);
2604
- }
2605
- catch (err) {
2606
- console.warn('[SmoothSend] Session setup failed, falling back to regular gasless:', err.message);
2607
- // Fall through to normal gasless path below
2608
- }
2609
- }
2610
- }
2611
- // If session is now active, submit silently — no wallet popup
2612
- if (submitter.hasSession()) {
2613
- console.log('[SmoothSend] Session is active, using submitWithSession');
2614
- try {
2615
- return await submitter.submitWithSession(functionName, input.data?.functionArguments ?? [], input.data?.typeArguments ?? []);
2616
- }
2617
- catch (err) {
2618
- // Session may have expired mid-flight — clear it and fall through
2619
- console.warn('[SmoothSend] Session submit failed, will re-auth on next call:', err.message);
2620
- setHasSessionState(false);
2621
- // Fall through to regular gasless path for this call
2622
- }
2623
- }
2624
- }
2625
- // Non-sponsored function → fall through to walletSignAndSubmit below
2626
- }
2627
- // ── Regular gasless path (TransactionSubmitter) ─────────────────────────
2628
- // signTransaction (sign-only) must be available for the gasless path.
2629
- // Most modern wallets (Petra, Nightly) support it. If absent, fall through.
2630
- const canGoGasless = typeof signTransaction === 'function';
2631
- const sponsored = canGoGasless && (await submitter.isSponsored(functionName));
2632
- if (sponsored && signTransaction) {
2633
- try {
2634
- const config = submitter.getConfig();
2635
- const network = config.network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2636
- const aptos = new Aptos(new AptosConfig({ network }));
2637
- // Build transaction with fee-payer placeholder (AccountAddress.ZERO).
2638
- // replayProtectionNonce (AIP-123): random nonce instead of sequence number
2639
- // so concurrent gasless calls from many users never conflict.
2640
- const transaction = await aptos.transaction.build.simple({
2641
- sender: account.address.toString(),
2642
- data: input.data,
2643
- options: {
2644
- ...input.options,
2645
- replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2646
- },
2647
- withFeePayer: true,
2648
- });
2649
- // Wallet signs sender portion only (no gas required from user).
2650
- // wallet-adapter v8 changed signTransaction to accept { transactionOrPayload, asFeePayer }
2651
- // and returns { authenticator, rawTransaction }.
2652
- // Cast to any to bridge the type mismatch between SDK devDep version and runtime v8.
2653
- const rawResult = await signTransaction({
2654
- transactionOrPayload: transaction,
2655
- asFeePayer: false,
2656
- });
2657
- // Handle both old API (returns AccountAuthenticator directly) and
2658
- // new v8 API (returns { authenticator, rawTransaction })
2659
- const senderAuthenticator = rawResult?.authenticator ?? rawResult;
2660
- // Relayer signs as fee payer and submits
2661
- return await submitter.submitTransaction({
2662
- aptosConfig: aptos.config,
2663
- transaction: transaction,
2664
- senderAuthenticator: senderAuthenticator,
2665
- });
2666
- }
2667
- catch (err) {
2668
- // If the relayer rejects (e.g. function not in allowlist after a config change),
2669
- // fall through to user-pays-gas path rather than surfacing a hard error.
2670
- if (err?.message?.includes('SPONSORSHIP') ||
2671
- err?.message?.includes('not allowed') ||
2672
- err?.message?.includes('403') ||
2673
- err?.message?.includes('gasless')) {
2674
- console.warn('[SmoothSend] Sponsorship rejected, falling back to user-pays-gas:', err.message);
2675
- return walletSignAndSubmit(input);
2676
- }
2677
- throw err;
2678
- }
2679
- }
2680
- // Not sponsored or signTransaction unavailable → regular wallet submission
2681
- return walletSignAndSubmit(input);
2682
- }, [account, signTransaction, walletSignAndSubmit, submitter]);
2683
- return {
2684
- signAndSubmitTransaction,
2685
- hasSession: hasSessionState,
2686
- };
2687
- }
2688
-
2689
- // ─── helpers ────────────────────────────────────────────────────────────────
2690
- function parseDurationToSeconds(duration) {
2691
- if (duration === 'never') {
2692
- // Client-side "never expires" mode; on-chain handle already uses u64::MAX.
2693
- return Math.floor(Number.MAX_SAFE_INTEGER / 1000);
2694
- }
2695
- const n = parseInt(duration, 10);
2696
- if (isNaN(n))
2697
- throw new Error(`Invalid duration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
2698
- if (duration.endsWith('s'))
2699
- return n;
2700
- if (duration.endsWith('m'))
2701
- return n * 60;
2702
- if (duration.endsWith('h'))
2703
- return n * 3600;
2704
- if (duration.endsWith('d'))
2705
- return n * 86400;
2706
- throw new Error(`Unknown duration unit in "${duration}". Supported: s, m, h, d, or "never".`);
2707
- }
2708
- // ─── SmoothSendSession ───────────────────────────────────────────────────────
2709
- /**
2710
- * A session that lets your app submit transactions on behalf of a user
2711
- * without any wallet popup after the initial one-time setup.
2712
- *
2713
- * Uses Aptos AIP-103 Permissioned Signers — authorization is enforced
2714
- * on-chain by `0x1::permissioned_delegation`. No custom Move contract needed.
2715
- *
2716
- * @example
2717
- * // 1. One-time setup (user signs once — can be keyless/Google login)
2718
- * const session = await SmoothSendSession.create({
2719
- * signer: keylessAccount,
2720
- * expiresIn: '24h',
2721
- * }, submitter)
2722
- *
2723
- * // 2. Every action after — zero popups, zero gas
2724
- * await session.submit('0xgame::player::move', ['north'])
2725
- * await session.submit('0xgame::player::attack', [enemyId])
2726
- */
2727
- class SmoothSendSession {
2728
- constructor(args) {
2729
- this.sessionAccount = args.sessionAccount;
2730
- this.abstractedAccount = args.abstractedAccount;
2731
- this.masterAddress = args.masterAddress;
2732
- this.expiresAtMs = args.expiresAtMs;
2733
- this.submitter = args.submitter;
2734
- this.aptosClient = args.aptosClient;
2735
- this._network = args.network;
2736
- }
2737
- /**
2738
- * Create a new session.
2739
- *
2740
- * Registers the session key on-chain via
2741
- * `0x1::permissioned_delegation::add_permissioned_handle`.
2742
- * SmoothSend pays the gas for this setup transaction too.
2743
- *
2744
- * After this returns, the user never needs to approve anything again
2745
- * until the session expires or is revoked.
2746
- */
2747
- static async create(options, submitter) {
2748
- // Resolve network from options or submitter config
2749
- const network = options.network ?? submitter.getConfig().network ?? 'testnet';
2750
- const aptosNetwork = network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2751
- const aptosClient = new Aptos(new AptosConfig({ network: aptosNetwork }));
2752
- const feature = await aptosClient.view({
2753
- payload: {
2754
- function: '0x1::features::is_permissioned_signer_enabled',
2755
- functionArguments: [],
2756
- },
2757
- }).catch(() => [false]);
2758
- if (!Array.isArray(feature) || feature[0] !== true) {
2759
- throw new Error('[SmoothSend] Session keys unavailable on this network (permissioned signer feature disabled).');
2760
- }
2761
- // Generate a fresh Ed25519 session keypair (lives in memory, never persisted)
2762
- const sessionAccount = Account.generate();
2763
- // Client-side expiry tracking (the bytecode script doesn't take an expiry arg)
2764
- const nowSecs = Math.floor(Date.now() / 1000);
2765
- const expirationTimeSecs = nowSecs + parseDurationToSeconds(options.expiresIn);
2766
- // Step 1: Register the session key on-chain via a pre-compiled Move script.
2767
- // add_permissioned_handle is NOT an entry function — only callable from a Move script.
2768
- // Must happen BEFORE enabling account abstraction.
2769
- const setupTx = await aptosClient.transaction.build.simple({
2770
- sender: options.signer.accountAddress,
2771
- withFeePayer: true,
2772
- data: {
2773
- bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
2774
- functionArguments: [MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
2775
- },
2776
- options: {
2777
- replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2778
- },
2779
- });
2780
- const senderAuth = aptosClient.transaction.sign({
2781
- signer: options.signer,
2782
- transaction: setupTx,
2783
- });
2784
- const setupResult = await submitter.submitTransaction({
2785
- aptosConfig: aptosClient.config,
2786
- transaction: setupTx,
2787
- senderAuthenticator: senderAuth,
2788
- });
2789
- await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
2790
- // Step 2: Enable account abstraction — tells the chain to use
2791
- // 0x1::permissioned_delegation::authenticate for this account.
2792
- // Idempotent — skip if already enabled.
2793
- const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
2794
- accountAddress: options.signer.accountAddress,
2795
- authenticationFunction: '0x1::permissioned_delegation::authenticate',
2796
- });
2797
- if (!aaEnabled) {
2798
- const aaTx = await aptosClient.transaction.build.simple({
2799
- sender: options.signer.accountAddress,
2800
- withFeePayer: true,
2801
- data: {
2802
- function: '0x1::account_abstraction::add_authentication_function',
2803
- functionArguments: [
2804
- AccountAddress.fromString('0x1'),
2805
- 'permissioned_delegation',
2806
- 'authenticate',
2807
- ],
2808
- },
2809
- });
2810
- const aaAuth = aptosClient.transaction.sign({ signer: options.signer, transaction: aaTx });
2811
- const aaResult = await submitter.submitTransaction({
2812
- aptosConfig: aptosClient.config,
2813
- transaction: aaTx,
2814
- senderAuthenticator: aaAuth,
2815
- });
2816
- await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
2817
- }
2818
- // Build AbstractedAccount — signs future txs with session key but
2819
- // sender on-chain = master address. Chain validates via permissioned_delegation.
2820
- const abstractedAccount = AbstractedAccount.fromPermissionedSigner({
2821
- signer: sessionAccount,
2822
- accountAddress: options.signer.accountAddress,
2823
- });
2824
- return new SmoothSendSession({
2825
- sessionAccount,
2826
- abstractedAccount,
2827
- masterAddress: options.signer.accountAddress,
2828
- expiresAtMs: expirationTimeSecs * 1000,
2829
- submitter,
2830
- aptosClient,
2831
- network,
2832
- });
2833
- }
2834
- /**
2835
- * Submit a transaction silently — no wallet popup, zero gas.
2836
- *
2837
- * The transaction sender on-chain is still the user's main address.
2838
- * The session key signs it, and `permissioned_delegation::authenticate`
2839
- * validates the authorization at the VM level.
2840
- *
2841
- * @param functionName Full Move function identifier e.g. '0xgame::player::move'
2842
- * @param functionArguments Arguments matching the Move function signature
2843
- * @param typeArguments Optional type arguments for generic functions
2844
- *
2845
- * @example
2846
- * await session.submit('0xgame::player::move', ['north'])
2847
- * await session.submit('0x1::coin::transfer', [recipientAddr, 1000000n])
2848
- */
2849
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2850
- async submit(functionName, functionArguments = [], typeArguments = []) {
2851
- if (!this.isValid()) {
2852
- throw new Error(`Session expired at ${new Date(this.expiresAtMs).toISOString()}. ` +
2853
- `Call SmoothSendSession.create() to start a new session.`);
2854
- }
2855
- // replayProtectionNonce: orderless transaction (AIP-123).
2856
- // Lets users submit multiple session.submit() calls in parallel without
2857
- // sequence number conflicts — critical for games, agents, rapid-fire actions.
2858
- const tx = await this.aptosClient.transaction.build.simple({
2859
- sender: this.masterAddress,
2860
- withFeePayer: true,
2861
- data: {
2862
- function: functionName,
2863
- functionArguments,
2864
- ...(typeArguments.length > 0 ? { typeArguments } : {}),
2865
- },
2866
- options: {
2867
- replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2868
- },
2869
- });
2870
- // Session key signs on behalf of master address
2871
- const senderAuth = this.aptosClient.transaction.sign({
2872
- signer: this.abstractedAccount,
2873
- transaction: tx,
2874
- });
2875
- const result = await this.submitter.submitTransaction({
2876
- aptosConfig: this.aptosClient.config,
2877
- transaction: tx,
2878
- senderAuthenticator: senderAuth,
2879
- });
2880
- return { hash: result.hash };
2881
- }
2882
- /**
2883
- * Whether this session is still valid (not yet expired).
2884
- */
2885
- isValid() {
2886
- return Date.now() < this.expiresAtMs;
2887
- }
2888
- /**
2889
- * Milliseconds until this session expires. Returns 0 if already expired.
2890
- */
2891
- expiresInMs() {
2892
- return Math.max(0, this.expiresAtMs - Date.now());
2893
- }
2894
- /**
2895
- * Session metadata — useful for display or debugging.
2896
- */
2897
- get info() {
2898
- return {
2899
- masterAddress: this.masterAddress.toString(),
2900
- sessionKeyAddress: this.sessionAccount.accountAddress.toString(),
2901
- expiresAt: this.expiresAtMs,
2902
- network: this._network,
2903
- };
2904
- }
2905
- }
2906
-
2907
- /**
2908
- * Script Composer Client
2909
- *
2910
- * Wrapper for Script Composer gasless transactions.
2911
- * Use this for token transfers on mainnet with free tier (fee deducted from token).
2912
- *
2913
- * @remarks
2914
- * Script Composer builds a batched transaction that:
2915
- * 1. Withdraws (amount + fee) from sender
2916
- * 2. Deposits amount to recipient
2917
- * 3. Deposits fee to treasury
2918
- *
2919
- * This allows gasless transactions where the fee is paid in the token being transferred.
2920
- *
2921
- * @example
2922
- * ```typescript
2923
- * import { ScriptComposerClient } from '@smoothsend/aptos-sdk';
2924
- *
2925
- * const client = new ScriptComposerClient({
2926
- * apiKey: 'pk_nogas_xxx',
2927
- * network: 'mainnet'
2928
- * });
2929
- *
2930
- * // Step 1: Build transaction (fee calculated automatically)
2931
- * const { transactionBytes, fee, totalAmount } = await client.buildTransfer({
2932
- * sender: wallet.address,
2933
- * recipient: '0x123...',
2934
- * amount: '1000000', // 1 USDC (6 decimals)
2935
- * assetType: '0x...::usdc::USDC',
2936
- * decimals: 6,
2937
- * symbol: 'USDC'
2938
- * });
2939
- *
2940
- * // Step 2: Sign with wallet
2941
- * const signedTx = await wallet.signTransaction(transactionBytes);
2942
- *
2943
- * // Step 3: Submit
2944
- * const result = await client.submitSignedTransaction({
2945
- * transactionBytes: signedTx.transactionBytes,
2946
- * authenticatorBytes: signedTx.authenticatorBytes
2947
- * });
2948
- *
2949
- * console.log('Tx:', result.txHash);
2950
- * ```
2951
- */
2952
- /**
2953
- * Script Composer Client
2954
- *
2955
- * For gasless token transfers with fee deducted from the token.
2956
- * Use this on mainnet with free tier, or anytime you want fee-in-token.
2957
- */
2958
- class ScriptComposerClient {
2959
- constructor(config) {
2960
- if (!config.apiKey) {
2961
- throw new SmoothSendError('API key is required', 'MISSING_API_KEY', 400);
2962
- }
2963
- if (!config.network) {
2964
- throw new SmoothSendError('Network is required (testnet or mainnet)', 'MISSING_NETWORK', 400);
2965
- }
2966
- this.config = {
2967
- apiKey: config.apiKey,
2968
- network: config.network,
2969
- proxyUrl: config.proxyUrl,
2970
- timeout: config.timeout || 30000,
2971
- debug: config.debug || false,
2972
- };
2973
- this.httpClient = new HttpClient({
2974
- apiKey: this.config.apiKey,
2975
- network: this.config.network,
2976
- timeout: this.config.timeout,
2977
- retries: 3,
2978
- includeOrigin: this.isBrowser(),
2979
- });
2980
- }
2981
- isBrowser() {
2982
- return typeof window !== 'undefined' && typeof window.document !== 'undefined';
2983
- }
2984
- log(message, data) {
2985
- if (this.config.debug) {
2986
- console.log(`[ScriptComposer] ${message}`, data || '');
2987
- }
2988
- }
2989
- /**
2990
- * Estimate fee for a transfer without building the transaction
2991
- *
2992
- * @param params Transfer parameters
2993
- * @returns Fee estimation with pricing details
2994
- */
2995
- async estimateFee(params) {
2996
- this.log('Estimating fee', params);
2997
- try {
2998
- const response = await this.httpClient.post('/api/v1/relayer/estimate-fee', {
2999
- sender: params.sender,
3000
- recipient: params.recipient,
3001
- amount: params.amount,
3002
- assetType: params.assetType,
3003
- decimals: params.decimals,
3004
- symbol: params.symbol,
3005
- network: this.config.network,
3006
- apiKey: this.config.apiKey,
3007
- });
3008
- this.log('Fee estimate received', response.data);
3009
- return response.data;
3010
- }
3011
- catch (error) {
3012
- this.log('Fee estimation failed', error);
3013
- if (error instanceof SmoothSendError) {
3014
- throw error;
3015
- }
3016
- throw new SmoothSendError(`Failed to estimate fee: ${error.message}`, 'FEE_ESTIMATION_FAILED', 500, { originalError: error.message });
3017
- }
3018
- }
3019
- /**
3020
- * Build a gasless transfer transaction
3021
- *
3022
- * Returns unsigned transaction bytes that must be signed by the user's wallet.
3023
- * The fee will be deducted from the token being transferred.
3024
- *
3025
- * @param params Transfer parameters
3026
- * @returns Transaction bytes for signing and fee details
3027
- */
3028
- async buildTransfer(params) {
3029
- this.log('Building transfer', params);
3030
- // Validate parameters
3031
- if (!params.sender || !params.recipient || !params.amount) {
3032
- throw new SmoothSendError('Missing required parameters: sender, recipient, amount', 'INVALID_PARAMETERS', 400);
3033
- }
3034
- if (!params.assetType || params.decimals === undefined || !params.symbol) {
3035
- throw new SmoothSendError('Missing token parameters: assetType, decimals, symbol', 'INVALID_PARAMETERS', 400);
3036
- }
3037
- try {
3038
- // Call the gasless-transaction endpoint in Script Composer mode
3039
- const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
3040
- sender: params.sender,
3041
- recipient: params.recipient,
3042
- amount: params.amount,
3043
- assetType: params.assetType,
3044
- decimals: params.decimals,
3045
- symbol: params.symbol,
3046
- network: this.config.network,
3047
- });
3048
- this.log('Transaction built', response.data);
3049
- return response.data;
3050
- }
3051
- catch (error) {
3052
- this.log('Build transfer failed', error);
3053
- if (error instanceof SmoothSendError) {
3054
- throw error;
3055
- }
3056
- throw new SmoothSendError(`Failed to build transfer: ${error.message}`, 'BUILD_TRANSFER_FAILED', 500, { originalError: error.message });
3057
- }
3058
- }
3059
- /**
3060
- * Submit a signed transaction
3061
- *
3062
- * After the user signs the transaction bytes returned by buildTransfer(),
3063
- * use this method to submit the signed transaction.
3064
- *
3065
- * @param params Signed transaction bytes
3066
- * @returns Transaction result with hash
3067
- */
3068
- async submitSignedTransaction(params) {
3069
- this.log('Submitting signed transaction');
3070
- if (!params.transactionBytes || !params.authenticatorBytes) {
3071
- throw new SmoothSendError('Missing required parameters: transactionBytes, authenticatorBytes', 'INVALID_PARAMETERS', 400);
3072
- }
3073
- try {
3074
- // Call the gasless-transaction endpoint in Legacy mode (with signed tx)
3075
- const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
3076
- transactionBytes: params.transactionBytes,
3077
- authenticatorBytes: params.authenticatorBytes,
3078
- network: this.config.network,
3079
- });
3080
- this.log('Transaction submitted', response.data);
3081
- return {
3082
- success: response.data.success,
3083
- requestId: response.data.requestId,
3084
- txHash: response.data.txnHash || response.data.txHash,
3085
- gasUsed: response.data.gasUsed,
3086
- vmStatus: response.data.vmStatus,
3087
- sender: response.data.sender,
3088
- };
3089
- }
3090
- catch (error) {
3091
- this.log('Submit transaction failed', error);
3092
- if (error instanceof SmoothSendError) {
3093
- throw error;
3094
- }
3095
- throw new SmoothSendError(`Failed to submit transaction: ${error.message}`, 'SUBMIT_FAILED', 500, { originalError: error.message });
3096
- }
3097
- }
3098
- /**
3099
- * Complete transfer flow: build, sign, and submit
3100
- *
3101
- * Convenience method that handles the entire flow.
3102
- * Requires a wallet that can sign transactions.
3103
- *
3104
- * @param params Transfer parameters
3105
- * @param wallet Wallet with signTransaction method
3106
- * @returns Transaction result
3107
- *
3108
- * @example
3109
- * ```typescript
3110
- * const result = await client.transfer({
3111
- * sender: wallet.address,
3112
- * recipient: '0x123...',
3113
- * amount: '1000000',
3114
- * assetType: USDC_ADDRESS,
3115
- * decimals: 6,
3116
- * symbol: 'USDC'
3117
- * }, wallet);
3118
- * ```
3119
- */
3120
- async transfer(params, wallet) {
3121
- this.log('Starting complete transfer flow');
3122
- // Step 1: Build transaction
3123
- const buildResult = await this.buildTransfer(params);
3124
- this.log('Transaction built, fee:', buildResult.fee);
3125
- // Step 2: Sign with wallet
3126
- const signedTx = await wallet.signTransaction(buildResult.transactionBytes);
3127
- this.log('Transaction signed');
3128
- // Step 3: Submit
3129
- const result = await this.submitSignedTransaction({
3130
- transactionBytes: signedTx.transactionBytes,
3131
- authenticatorBytes: signedTx.authenticatorBytes,
3132
- });
3133
- this.log('Transfer complete', result);
3134
- return result;
3135
- }
3136
- /**
3137
- * Get current network
3138
- */
3139
- getNetwork() {
3140
- return this.config.network;
3141
- }
3142
- /**
3143
- * Set network
3144
- */
3145
- setNetwork(network) {
3146
- this.config.network = network;
3147
- this.httpClient.setNetwork(network);
3148
- }
3149
- }
3150
- /**
3151
- * Create a Script Composer client (convenience function)
3152
- */
3153
- function createScriptComposerClient(config) {
3154
- return new ScriptComposerClient(config);
3155
- }
3156
-
3157
- /**
3158
- * True Gasless Client
3159
- *
3160
- * Designed for server-side (backend) environments to securely build, sign,
3161
- * and submit 100% sponsored gasless transactions using a Secret Key.
3162
- *
3163
- * @example
3164
- * ```typescript
3165
- * import { TrueGaslessClient } from '@smoothsend/sdk';
3166
- * import { Account } from '@aptos-labs/ts-sdk';
3167
- *
3168
- * const backendWallet = Account.fromPrivateKey({ privateKey: '...' });
3169
- * const client = new TrueGaslessClient({ apiKey: 'sk_nogas_...', network: 'mainnet' });
3170
- *
3171
- * const result = await client.execute({
3172
- * senderAccount: backendWallet,
3173
- * payload: {
3174
- * function: "0x123::my_module::mint_nft",
3175
- * functionArguments: []
3176
- * }
3177
- * });
3178
- *
3179
- * console.log("Gasless NFT Minted!", result.txHash);
3180
- * ```
3181
- */
3182
- class TrueGaslessClient {
3183
- constructor(config) {
3184
- if (!config.apiKey) {
3185
- throw new SmoothSendError('API key is required', 'MISSING_API_KEY', 400);
3186
- }
3187
- if (!config.apiKey.startsWith('sk_nogas_')) {
3188
- console.warn('⚠️ WARNING: TrueGaslessClient is intended for backend use with a Secret Key (sk_nogas_*).\n' +
3189
- 'Using a Public Key may result in CORS errors if ran in a browser environment.');
3190
- }
3191
- if (!config.network) {
3192
- throw new SmoothSendError('Network is required (testnet or mainnet)', 'MISSING_NETWORK', 400);
3193
- }
3194
- this.config = {
3195
- apiKey: config.apiKey,
3196
- network: config.network,
3197
- proxyUrl: config.proxyUrl,
3198
- timeout: config.timeout || 30000,
3199
- debug: config.debug || false,
3200
- };
3201
- this.httpClient = new HttpClient({
3202
- apiKey: this.config.apiKey,
3203
- network: this.config.network,
3204
- timeout: this.config.timeout,
3205
- retries: 3,
3206
- includeOrigin: false, // Backend client should not send Origin header
3207
- baseUrl: this.config.proxyUrl, // Use custom proxy URL if provided
3208
- });
3209
- const networkMap = {
3210
- testnet: Network.TESTNET,
3211
- mainnet: Network.MAINNET,
3212
- };
3213
- this.aptos = new Aptos(new AptosConfig({ network: networkMap[this.config.network] }));
3214
- }
3215
- log(message, data) {
3216
- if (this.config.debug) {
3217
- console.log(`[TrueGaslessClient] ${message}`, data || '');
3218
- }
3219
- }
3220
- /**
3221
- * Builds, signs (as sender), and relays an arbitrary payload for complete sponsorship.
3222
- */
3223
- async execute(params) {
3224
- this.log('Starting gasless execution', { sender: params.senderAccount.accountAddress.toString(), payload: params.payload });
3225
- if (!params.senderAccount || !params.payload) {
3226
- throw new SmoothSendError('Missing required parameters: senderAccount and payload', 'INVALID_PARAMETERS', 400);
3227
- }
3228
- try {
3229
- this.log('Building simple transaction with fee payer enabled');
3230
- // Build the transaction and flag it requires a remote fee payer
3231
- const transaction = await this.aptos.transaction.build.simple({
3232
- sender: params.senderAccount.accountAddress,
3233
- data: params.payload,
3234
- withFeePayer: true,
3235
- });
3236
- this.log('Signing transaction locally with senderAccount');
3237
- // Sign locally over the transaction hash
3238
- const senderAuthenticator = this.aptos.transaction.sign({
3239
- signer: params.senderAccount,
3240
- transaction,
3241
- });
3242
- this.log('Serializing to bytes for relayer transmission');
3243
- // Convert to BCS bytes expected by the proxy
3244
- const transactionBytes = Array.from(transaction.bcsToBytes());
3245
- const authenticatorBytes = Array.from(senderAuthenticator.bcsToBytes());
3246
- this.log('Sending to relayer...');
3247
- const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
3248
- transactionBytes,
3249
- authenticatorBytes,
3250
- network: this.config.network,
3251
- functionName: 'function' in params.payload ? params.payload.function : 'unknown',
3252
- });
3253
- this.log('Relayer submission successful', response.data);
3254
- return {
3255
- success: response.data.success ?? true,
3256
- requestId: response.data.requestId,
3257
- txHash: response.data.txnHash || response.data.txHash,
3258
- gasUsed: response.data.gasUsed,
3259
- vmStatus: response.data.vmStatus,
3260
- sender: response.data.sender || params.senderAccount.accountAddress.toString(),
3261
- };
3262
- }
3263
- catch (error) {
3264
- this.log('Gasless execution failed', error);
3265
- if (error instanceof SmoothSendError) {
3266
- throw error;
3267
- }
3268
- throw new SmoothSendError(`Failed to execute gasless transaction: ${error.message}`, 'EXECUTION_FAILED', 500, { originalError: error.message });
3269
- }
3270
- }
3271
- /**
3272
- * Expose the core Aptos instance to allow backend developers to access chain state if needed
3273
- */
3274
- getAptosClient() {
3275
- return this.aptos;
3276
- }
3277
- }
3278
- /**
3279
- * Helper to initialize TrueGaslessClient
3280
- */
3281
- function createTrueGaslessClient(config) {
3282
- return new TrueGaslessClient(config);
3283
- }
3284
-
3285
- /**
3286
- * SmoothSend SDK v2.0
3287
- *
3288
- * Multi-chain gasless transaction SDK for seamless dApp integration
3289
- *
3290
- * @remarks
3291
- * The SDK provides a simple interface for executing gasless token transfers
3292
- * across multiple blockchain networks. All requests route through the proxy
3293
- * worker at proxy.smoothsend.xyz with API key authentication.
3294
- *
3295
- * @packageDocumentation
3296
- *
3297
- * @example
3298
- * Aptos:
3299
- * ```typescript
3300
- * const sdk = new SmoothSendSDK({ apiKey: 'pk_nogas_xxx', network: 'testnet' });
3301
- * const result = await sdk.transfer({ from, to, token: 'USDC', amount: '1000000', chain: 'aptos-testnet' }, aptosWallet);
3302
- * ```
3303
- *
3304
- * @example
3305
- * Stellar (same API):
3306
- * ```typescript
3307
- * const sdk = new SmoothSendSDK({ apiKey: 'pk_nogas_xxx', network: 'testnet' });
3308
- * const result = await sdk.transfer({ from, to, token: 'XLM', amount: '100', chain: 'stellar-testnet' }, stellarWallet);
3309
- * ```
3310
- */
3311
- // Main SDK export
3312
- /**
3313
- * SDK version
3314
- * @public
3315
- */
3316
- const VERSION = '2.2.1';
3317
-
3318
- export { APTOS_ERROR_CODES, AptosAdapter, AuthenticationError, CHAIN_ECOSYSTEM_MAP, HttpClient, NetworkError, RateLimitError, STELLAR_ERROR_CODES, ScriptComposerClient, SmoothSendError, SmoothSendSDK, SmoothSendSession, SmoothSendTransactionSubmitter, StellarAdapter, StellarCAddressAdapter, TrueGaslessClient, VERSION, ValidationError, createErrorFromResponse, createNetworkError, createScriptComposerClient, createSmoothSendSubmitter, createTrueGaslessClient, SmoothSendSDK as default, useSmoothSend };
3319
- //# sourceMappingURL=index.esm.js.map