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