@smoothsend/sdk 2.3.6 → 2.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +22 -22
  2. package/README.md +349 -349
  3. package/dist/adapters/evm.d.ts +39 -0
  4. package/dist/adapters/evm.d.ts.map +1 -0
  5. package/dist/config/chains.d.ts +7 -0
  6. package/dist/config/chains.d.ts.map +1 -0
  7. package/dist/index.esm.js +3 -1846
  8. package/dist/index.esm.js.map +1 -1
  9. package/dist/services/chainConfigService.d.ts +49 -0
  10. package/dist/services/chainConfigService.d.ts.map +1 -0
  11. package/package.json +120 -120
  12. package/dist/aptos-privy/index.cjs +0 -40
  13. package/dist/aptos-privy/index.cjs.map +0 -1
  14. package/dist/aptos-privy/index.js +0 -34
  15. package/dist/aptos-privy/index.js.map +0 -1
  16. package/dist/aptos-privy/normalizePrivyAptosWallet.d.ts +0 -4
  17. package/dist/aptos-privy/normalizePrivyAptosWallet.d.ts.map +0 -1
  18. package/dist/aptos-privy/privyAptosSigner.d.ts +0 -32
  19. package/dist/aptos-privy/privyAptosSigner.d.ts.map +0 -1
  20. package/dist/aptos-privy/useSmoothSendAptosPrivy.d.ts +0 -13
  21. package/dist/aptos-privy/useSmoothSendAptosPrivy.d.ts.map +0 -1
  22. package/dist/aptos-privy-entry.d.ts +0 -9
  23. package/dist/aptos-privy-entry.d.ts.map +0 -1
  24. package/dist/chunks/SmoothSendSDK-C_ofuBkk.cjs +0 -1519
  25. package/dist/chunks/SmoothSendSDK-C_ofuBkk.cjs.map +0 -1
  26. package/dist/chunks/SmoothSendSDK-CaV_PCIG.js +0 -1511
  27. package/dist/chunks/SmoothSendSDK-CaV_PCIG.js.map +0 -1
  28. package/dist/chunks/SmoothSendSDK.d-9GBgZONY.d.ts +0 -262
  29. package/dist/chunks/TrueGaslessClient-DThO4Tpb.cjs +0 -1237
  30. package/dist/chunks/TrueGaslessClient-DThO4Tpb.cjs.map +0 -1
  31. package/dist/chunks/TrueGaslessClient-l2uFvNAa.js +0 -1228
  32. package/dist/chunks/TrueGaslessClient-l2uFvNAa.js.map +0 -1
  33. package/dist/chunks/shared-2xx2VLH3.js +0 -453
  34. package/dist/chunks/shared-2xx2VLH3.js.map +0 -1
  35. package/dist/chunks/shared-B8UdyBTN.d.ts +0 -143
  36. package/dist/chunks/shared-BJv1JV1H.cjs +0 -702
  37. package/dist/chunks/shared-BJv1JV1H.cjs.map +0 -1
  38. package/dist/chunks/shared-BXvqbQ6f.d.ts +0 -262
  39. package/dist/chunks/shared-Bh4xtpHv.js +0 -740
  40. package/dist/chunks/shared-Bh4xtpHv.js.map +0 -1
  41. package/dist/chunks/shared-BlIQttCf.d.ts +0 -1279
  42. package/dist/chunks/shared-BoRfHN1w.js +0 -1511
  43. package/dist/chunks/shared-BoRfHN1w.js.map +0 -1
  44. package/dist/chunks/shared-CNF22ESH.js +0 -557
  45. package/dist/chunks/shared-CNF22ESH.js.map +0 -1
  46. package/dist/chunks/shared-CPpb2n9T.d.ts +0 -780
  47. package/dist/chunks/shared-CaQMAGQR.js +0 -1511
  48. package/dist/chunks/shared-CaQMAGQR.js.map +0 -1
  49. package/dist/chunks/shared-Cgb7mhwI.d.ts +0 -471
  50. package/dist/chunks/shared-Cn4duBJT.d.ts +0 -1279
  51. package/dist/chunks/shared-CzR0rIwZ.cjs +0 -635
  52. package/dist/chunks/shared-CzR0rIwZ.cjs.map +0 -1
  53. package/dist/chunks/shared-DEurKmpI.cjs +0 -1519
  54. package/dist/chunks/shared-DEurKmpI.cjs.map +0 -1
  55. package/dist/chunks/shared-DQbEIiTE.cjs +0 -746
  56. package/dist/chunks/shared-DQbEIiTE.cjs.map +0 -1
  57. package/dist/chunks/shared-DYAVFARB.d.ts +0 -472
  58. package/dist/chunks/shared-DzwYUjQn.cjs +0 -457
  59. package/dist/chunks/shared-DzwYUjQn.cjs.map +0 -1
  60. package/dist/chunks/shared-KUvoQkzf.d.ts +0 -471
  61. package/dist/chunks/shared-RVkwmkG7.d.ts +0 -262
  62. package/dist/chunks/shared-XH1iLZjy.js +0 -629
  63. package/dist/chunks/shared-XH1iLZjy.js.map +0 -1
  64. package/dist/chunks/shared-kovW7ATj.js +0 -694
  65. package/dist/chunks/shared-kovW7ATj.js.map +0 -1
  66. package/dist/chunks/shared-viO0MYao.d.ts +0 -459
  67. package/dist/chunks/shared-x1-VC-Li.cjs +0 -568
  68. package/dist/chunks/shared-x1-VC-Li.cjs.map +0 -1
  69. package/dist/chunks/useSmoothSendAvax-BHeW_6x8.cjs +0 -1865
  70. package/dist/chunks/useSmoothSendAvax-BHeW_6x8.cjs.map +0 -1
  71. package/dist/chunks/useSmoothSendAvax-ZuHw1aYi.js +0 -1848
  72. package/dist/chunks/useSmoothSendAvax-ZuHw1aYi.js.map +0 -1
  73. package/dist/chunks/version-CNF22ESH.js +0 -557
  74. package/dist/chunks/version-CNF22ESH.js.map +0 -1
  75. package/dist/chunks/version-x1-VC-Li.cjs +0 -568
  76. package/dist/chunks/version-x1-VC-Li.cjs.map +0 -1
  77. package/dist/chunks/version.d-Cn4duBJT.d.ts +0 -1279
@@ -1,1511 +0,0 @@
1
- import { S as SmoothSendError, H as HttpClient } from './shared-CNF22ESH.js';
2
-
3
- // Export error classes
4
- /**
5
- * Mapping of supported chains to their respective ecosystems
6
- * Used internally for adapter selection and routing
7
- */
8
- const CHAIN_ECOSYSTEM_MAP = {
9
- 'avalanche': 'evm',
10
- 'aptos-testnet': 'aptos',
11
- 'aptos-mainnet': 'aptos',
12
- 'stellar-testnet': 'stellar',
13
- 'stellar-mainnet': 'stellar',
14
- };
15
- /**
16
- * Aptos-specific error codes
17
- * Used for detailed error handling in Aptos adapter
18
- *
19
- * @remarks
20
- * Error codes are prefixed with APTOS_ for easy identification
21
- */
22
- const APTOS_ERROR_CODES = {
23
- // Signature verification errors
24
- /** Missing signature in request */
25
- MISSING_SIGNATURE: 'APTOS_MISSING_SIGNATURE',
26
- /** Missing public key for verification */
27
- MISSING_PUBLIC_KEY: 'APTOS_MISSING_PUBLIC_KEY',
28
- /** Invalid signature format */
29
- INVALID_SIGNATURE_FORMAT: 'APTOS_INVALID_SIGNATURE_FORMAT',
30
- /** Invalid public key format */
31
- INVALID_PUBLIC_KEY_FORMAT: 'APTOS_INVALID_PUBLIC_KEY_FORMAT',
32
- /** Address doesn't match public key */
33
- ADDRESS_MISMATCH: 'APTOS_ADDRESS_MISMATCH',
34
- /** Signature verification failed */
35
- SIGNATURE_VERIFICATION_FAILED: 'APTOS_SIGNATURE_VERIFICATION_FAILED',
36
- // Transaction errors
37
- /** Missing transaction data */
38
- MISSING_TRANSACTION_DATA: 'APTOS_MISSING_TRANSACTION_DATA',
39
- /** Invalid transaction format */
40
- INVALID_TRANSACTION_FORMAT: 'APTOS_INVALID_TRANSACTION_FORMAT',
41
- // Address validation errors
42
- /** Empty address provided */
43
- EMPTY_ADDRESS: 'APTOS_EMPTY_ADDRESS',
44
- /** Invalid address format */
45
- INVALID_ADDRESS_FORMAT: 'APTOS_INVALID_ADDRESS_FORMAT',
46
- // General errors
47
- /** Error fetching quote */
48
- QUOTE_ERROR: 'APTOS_QUOTE_ERROR',
49
- /** Error executing transfer */
50
- EXECUTE_ERROR: 'APTOS_EXECUTE_ERROR',
51
- /** Error fetching balance */
52
- BALANCE_ERROR: 'APTOS_BALANCE_ERROR',
53
- /** Error fetching token info */
54
- TOKEN_INFO_ERROR: 'APTOS_TOKEN_INFO_ERROR',
55
- /** Error checking status */
56
- STATUS_ERROR: 'APTOS_STATUS_ERROR',
57
- /** Error calling Move function */
58
- MOVE_CALL_ERROR: 'APTOS_MOVE_CALL_ERROR',
59
- /** Unsupported token */
60
- UNSUPPORTED_TOKEN: 'APTOS_UNSUPPORTED_TOKEN'
61
- };
62
- /**
63
- * Stellar adapter error codes
64
- */
65
- const STELLAR_ERROR_CODES = {
66
- MISSING_SIGNED_TRANSACTION: 'STELLAR_MISSING_SIGNED_TRANSACTION',
67
- GASLESS_TRANSACTION_ERROR: 'STELLAR_GASLESS_TRANSACTION_ERROR',
68
- STATUS_ERROR: 'STELLAR_STATUS_ERROR',
69
- HEALTH_ERROR: 'STELLAR_HEALTH_ERROR',
70
- INVALID_ADDRESS_FORMAT: 'STELLAR_INVALID_ADDRESS_FORMAT',
71
- };
72
-
73
- /**
74
- * Aptos Multi-Chain Adapter - v2 Proxy Architecture
75
- * Handles all Aptos chains (aptos-testnet, aptos-mainnet)
76
- * Routes all requests through proxy.smoothsend.xyz with API key authentication
77
- * Supports Aptos-specific features like gasless transactions and Move-based contracts
78
- */
79
- class AptosAdapter {
80
- constructor(chain, config, apiKey, network = 'testnet', includeOrigin = false) {
81
- // Validate this is an Aptos chain
82
- if (CHAIN_ECOSYSTEM_MAP[chain] !== 'aptos') {
83
- throw new SmoothSendError(`AptosAdapter can only handle Aptos chains, got: ${chain}`, 'INVALID_CHAIN_FOR_ADAPTER', 400, { chain });
84
- }
85
- this.chain = chain;
86
- this.config = config;
87
- this.apiKey = apiKey;
88
- this.network = network;
89
- // Initialize HTTP client with proxy configuration
90
- this.httpClient = new HttpClient({
91
- apiKey: this.apiKey,
92
- network: this.network,
93
- timeout: 30000,
94
- retries: 3,
95
- includeOrigin
96
- });
97
- }
98
- /**
99
- * Build API path for proxy worker routing to Aptos relayer
100
- * All requests route through /api/v1/relayer/aptos/* endpoints
101
- */
102
- getApiPath(endpoint) {
103
- return `/api/v1/relayer/aptos${endpoint}`;
104
- }
105
- /**
106
- * Update network parameter for subsequent requests
107
- * Network is passed via X-Network header to proxy worker
108
- */
109
- setNetwork(network) {
110
- this.network = network;
111
- this.httpClient.setNetwork(network);
112
- }
113
- /**
114
- * Get current network
115
- */
116
- getNetwork() {
117
- return this.network;
118
- }
119
- /**
120
- * Estimate fee for a transfer (v2 interface method)
121
- * Routes through proxy: POST /api/v1/relayer/aptos/quote
122
- */
123
- async estimateFee(request) {
124
- try {
125
- const response = await this.httpClient.post(this.getApiPath('/quote'), {
126
- fromAddress: request.from,
127
- toAddress: request.to,
128
- amount: request.amount,
129
- coinType: this.getAptosTokenAddress(request.token)
130
- });
131
- const responseData = response.data;
132
- const quote = responseData.quote;
133
- const feeEstimate = {
134
- relayerFee: quote.relayerFee,
135
- feeInUSD: quote.feeInUSD || '0',
136
- coinType: this.getAptosTokenAddress(request.token),
137
- estimatedGas: quote.estimatedGas || '0',
138
- network: this.network
139
- };
140
- // Attach usage metadata from proxy response headers
141
- if (response.metadata) {
142
- feeEstimate.metadata = response.metadata;
143
- }
144
- return feeEstimate;
145
- }
146
- catch (error) {
147
- if (error instanceof SmoothSendError) {
148
- throw error;
149
- }
150
- throw new SmoothSendError(`Failed to estimate Aptos fee: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.QUOTE_ERROR, 500, { chain: this.chain });
151
- }
152
- }
153
- /**
154
- * Execute gasless transfer (v2 interface method)
155
- * Routes through proxy: POST /api/v1/relayer/aptos/execute
156
- */
157
- async executeGaslessTransfer(signedData) {
158
- return this.executeTransfer(signedData);
159
- }
160
- /**
161
- * Get quote for a transfer (legacy method, kept for backward compatibility)
162
- * Routes through proxy: POST /api/v1/relayer/aptos/quote
163
- */
164
- async getQuote(request) {
165
- try {
166
- // Route through proxy: POST /api/v1/relayer/aptos/quote
167
- const response = await this.httpClient.post(this.getApiPath('/quote'), {
168
- fromAddress: request.from,
169
- toAddress: request.to,
170
- amount: request.amount,
171
- coinType: this.getAptosTokenAddress(request.token)
172
- });
173
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
174
- const responseData = response.data;
175
- const quote = responseData.quote;
176
- return {
177
- amount: request.amount,
178
- relayerFee: quote.relayerFee,
179
- total: (BigInt(request.amount) + BigInt(quote.relayerFee)).toString(),
180
- feePercentage: 0, // Aptos uses different fee structure
181
- contractAddress: responseData.transactionData.function.split('::')[0],
182
- // Store Aptos-specific data for later use
183
- aptosTransactionData: responseData.transactionData
184
- };
185
- }
186
- catch (error) {
187
- // Re-throw typed errors from HttpClient, wrap others
188
- if (error instanceof SmoothSendError) {
189
- throw error;
190
- }
191
- throw new SmoothSendError(`Failed to get Aptos quote: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.QUOTE_ERROR, 500, { chain: this.chain });
192
- }
193
- }
194
- async prepareTransfer(request, quote) {
195
- // For Aptos, the transaction data is provided in the quote response
196
- // The user will sign this transaction directly in their wallet
197
- const aptosQuote = quote;
198
- if (!aptosQuote.aptosTransactionData) {
199
- throw new SmoothSendError('Missing Aptos transaction data from quote', APTOS_ERROR_CODES.MISSING_TRANSACTION_DATA, 400, { chain: this.chain });
200
- }
201
- // Return the transaction data that needs to be signed
202
- // NOTE: After signing, you must serialize the transaction and authenticator
203
- // using the Aptos SDK and provide them as transactionBytes and authenticatorBytes
204
- return {
205
- domain: null, // Aptos doesn't use domain separation like EVM
206
- types: null,
207
- message: aptosQuote.aptosTransactionData,
208
- primaryType: 'AptosTransaction',
209
- // Add metadata to help with serialization - using any type for flexibility
210
- metadata: {
211
- requiresSerialization: true,
212
- serializationInstructions: 'After signing, serialize the SimpleTransaction and AccountAuthenticator using Aptos SDK',
213
- expectedFormat: 'transactionBytes and authenticatorBytes as number arrays'
214
- }
215
- };
216
- }
217
- async executeTransfer(signedData) {
218
- try {
219
- // Validate that we have the required serialized transaction data
220
- this.validateSerializedTransactionData(signedData);
221
- // Route through proxy: POST /api/v1/relayer/aptos/execute
222
- const response = await this.httpClient.post(this.getApiPath('/execute'), {
223
- transactionBytes: signedData.transactionBytes,
224
- authenticatorBytes: signedData.authenticatorBytes
225
- });
226
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
227
- const transferData = response.data;
228
- const result = {
229
- success: transferData.success || true,
230
- // Use standardized field names (txHash, transferId)
231
- txHash: transferData.txHash || transferData.hash, // Support both formats
232
- transferId: transferData.transferId || transferData.transactionId, // Support both formats
233
- explorerUrl: this.buildAptosExplorerUrl(transferData.txHash || transferData.hash),
234
- // Standard fields
235
- gasUsed: transferData.gasUsed,
236
- // Aptos-specific fields from enhanced response format
237
- gasFeePaidBy: transferData.gasFeePaidBy || 'relayer',
238
- userPaidAPT: transferData.userPaidAPT || false,
239
- vmStatus: transferData.vmStatus,
240
- sender: transferData.sender,
241
- chain: transferData.chain,
242
- relayerFee: transferData.relayerFee,
243
- message: transferData.message
244
- };
245
- // Attach usage metadata from proxy response headers
246
- if (response.metadata) {
247
- result.metadata = response.metadata;
248
- }
249
- return result;
250
- }
251
- catch (error) {
252
- // Re-throw typed errors from HttpClient, wrap others
253
- if (error instanceof SmoothSendError) {
254
- throw error;
255
- }
256
- throw new SmoothSendError(`Failed to execute Aptos transfer: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.EXECUTE_ERROR, 500, { chain: this.chain });
257
- }
258
- }
259
- async getBalance(address, token) {
260
- try {
261
- // Route through proxy: GET /api/v1/relayer/aptos/balance/:address
262
- const response = await this.httpClient.get(this.getApiPath(`/balance/${address}`));
263
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
264
- const balanceData = response.data;
265
- return [{
266
- token: balanceData?.symbol || token || 'USDC',
267
- balance: balanceData?.balance?.toString() || '0',
268
- decimals: balanceData?.decimals || 6,
269
- symbol: balanceData?.symbol || token || 'USDC',
270
- name: balanceData?.name || 'USD Coin (Testnet)'
271
- }];
272
- }
273
- catch (error) {
274
- // Re-throw typed errors from HttpClient, wrap others
275
- if (error instanceof SmoothSendError) {
276
- throw error;
277
- }
278
- throw new SmoothSendError(`Failed to get Aptos balance: ${error instanceof Error ? error.message : String(error)}`, APTOS_ERROR_CODES.BALANCE_ERROR, 500, { chain: this.chain });
279
- }
280
- }
281
- async getTokenInfo(token) {
282
- try {
283
- // Route through proxy: GET /api/v1/relayer/aptos/tokens
284
- const response = await this.httpClient.get(this.getApiPath('/tokens'));
285
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
286
- const tokens = response.data.tokens || {};
287
- const tokenInfo = tokens[token.toUpperCase()];
288
- if (!tokenInfo) {
289
- throw new Error(`Token ${token} not supported on ${this.chain}`);
290
- }
291
- return {
292
- symbol: tokenInfo.symbol,
293
- address: tokenInfo.address,
294
- decimals: tokenInfo.decimals,
295
- name: tokenInfo.name
296
- };
297
- }
298
- catch (error) {
299
- // Re-throw typed errors from HttpClient, wrap others
300
- if (error instanceof SmoothSendError) {
301
- throw error;
302
- }
303
- 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 });
304
- }
305
- }
306
- async getNonce(address) {
307
- // Aptos uses sequence numbers instead of nonces
308
- // For compatibility, we return a timestamp-based value
309
- // The actual sequence number is managed by the Aptos blockchain
310
- return Date.now().toString();
311
- }
312
- async getTransactionStatus(txHash) {
313
- try {
314
- // Route through proxy: GET /api/v1/relayer/aptos/status/:txHash
315
- const response = await this.httpClient.get(this.getApiPath(`/status/${txHash}`));
316
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
317
- return response.data;
318
- }
319
- catch (error) {
320
- // Re-throw typed errors from HttpClient, wrap others
321
- if (error instanceof SmoothSendError) {
322
- throw error;
323
- }
324
- 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 });
325
- }
326
- }
327
- /**
328
- * Get health status of Aptos relayer through proxy
329
- * Routes through proxy: GET /api/v1/relayer/aptos/health
330
- */
331
- async getHealth() {
332
- try {
333
- const response = await this.httpClient.get(this.getApiPath('/health'));
334
- const healthResponse = {
335
- success: true,
336
- status: response.data.status || 'healthy',
337
- timestamp: response.data.timestamp || new Date().toISOString(),
338
- version: response.data.version || '2.0'
339
- };
340
- // Attach usage metadata from proxy response headers
341
- if (response.metadata) {
342
- healthResponse.metadata = response.metadata;
343
- }
344
- return healthResponse;
345
- }
346
- catch (error) {
347
- if (error instanceof SmoothSendError) {
348
- throw error;
349
- }
350
- throw new SmoothSendError(`Failed to get Aptos health status: ${error instanceof Error ? error.message : String(error)}`, 'HEALTH_CHECK_ERROR', 500, { chain: this.chain });
351
- }
352
- }
353
- validateAddress(address) {
354
- // Aptos address validation (0x prefix, up to 64 hex characters)
355
- // Aptos addresses can be shorter and are automatically padded
356
- return /^0x[a-fA-F0-9]{1,64}$/.test(address);
357
- }
358
- validateAmount(amount) {
359
- try {
360
- const amountBN = BigInt(amount);
361
- return amountBN > 0n;
362
- }
363
- catch {
364
- return false;
365
- }
366
- }
367
- /**
368
- * Get Aptos token address from symbol
369
- * Mirrors aptosrelayer/config/chains.json
370
- */
371
- getAptosTokenAddress(tokenSymbol) {
372
- const symbol = tokenSymbol.toUpperCase();
373
- const TESTNET_TOKENS = {
374
- USDC: '0x3c27315fb69ba6e4b960f1507d1cefcc9a4247869f26a8d59d6b7869d23782c::test_coins::USDC'
375
- };
376
- const MAINNET_TOKENS = {
377
- USDT: '0x357b0b74bc833e95a115ad22604854d6b0fca151cecd94111770e5d6ffc9dc2b',
378
- USDC: '0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b',
379
- WBTC: '0x68844a0d7f2587e726ad0579f3d640865bb4162c08a4589eeda3f9689ec52a3d',
380
- USDE: '0xf37a8864fe737eb8ec2c2931047047cbaed1beed3fb0e5b7c5526dafd3b9c2e9',
381
- USD1: '0x05fabd1b12e39967a3c24e91b7b8f67719a6dacee74f3c8b9fb7d93e855437d2'
382
- };
383
- const tokens = this.chain === 'aptos-testnet' ? TESTNET_TOKENS : MAINNET_TOKENS;
384
- const address = tokens[symbol];
385
- if (!address) {
386
- const supported = Object.keys(tokens).join(', ');
387
- throw new SmoothSendError(`Unsupported token: ${tokenSymbol} on ${this.chain}. Supported: ${supported}`, APTOS_ERROR_CODES.UNSUPPORTED_TOKEN, 400, { chain: this.chain, token: tokenSymbol, supported });
388
- }
389
- return address;
390
- }
391
- /**
392
- * Build Aptos explorer URL for transaction
393
- */
394
- buildAptosExplorerUrl(txHash) {
395
- if (this.chain === 'aptos-testnet') {
396
- return `https://explorer.aptoslabs.com/txn/${txHash}?network=testnet`;
397
- }
398
- return `https://explorer.aptoslabs.com/txn/${txHash}`;
399
- }
400
- /**
401
- * Validate serialized transaction data for proxy worker
402
- * @param signedData The signed transfer data to validate
403
- */
404
- validateSerializedTransactionData(signedData) {
405
- if (!signedData.transactionBytes) {
406
- throw new SmoothSendError('Serialized transaction bytes are required for Aptos transactions', APTOS_ERROR_CODES.MISSING_TRANSACTION_DATA, 400, { chain: this.chain });
407
- }
408
- if (!signedData.authenticatorBytes) {
409
- throw new SmoothSendError('Serialized authenticator bytes are required for Aptos transactions', APTOS_ERROR_CODES.MISSING_SIGNATURE, 400, { chain: this.chain });
410
- }
411
- // Validate that transaction bytes is an array of numbers (0-255)
412
- if (!Array.isArray(signedData.transactionBytes) ||
413
- !signedData.transactionBytes.every((b) => typeof b === 'number' && b >= 0 && b <= 255)) {
414
- throw new SmoothSendError('Invalid transaction bytes format. Expected array of numbers 0-255.', APTOS_ERROR_CODES.INVALID_SIGNATURE_FORMAT, 400, { chain: this.chain });
415
- }
416
- // Validate that authenticator bytes is an array of numbers (0-255)
417
- if (!Array.isArray(signedData.authenticatorBytes) ||
418
- !signedData.authenticatorBytes.every((b) => typeof b === 'number' && b >= 0 && b <= 255)) {
419
- throw new SmoothSendError('Invalid authenticator bytes format. Expected array of numbers 0-255.', APTOS_ERROR_CODES.INVALID_PUBLIC_KEY_FORMAT, 400, { chain: this.chain });
420
- }
421
- }
422
- /**
423
- * Enhanced address validation with detailed error messages
424
- * @param address The address to validate
425
- * @returns true if valid, throws error if invalid
426
- */
427
- validateAddressStrict(address) {
428
- if (!address) {
429
- throw new SmoothSendError('Address cannot be empty', APTOS_ERROR_CODES.EMPTY_ADDRESS, 400, { chain: this.chain });
430
- }
431
- // Aptos address validation (0x prefix, up to 64 hex characters)
432
- if (!/^0x[a-fA-F0-9]{1,64}$/.test(address)) {
433
- 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 });
434
- }
435
- return true;
436
- }
437
- /**
438
- * Verify that a public key corresponds to an expected address
439
- * This mirrors the enhanced verification in the relayer
440
- * @param publicKey The public key to verify
441
- * @param expectedAddress The expected address
442
- * @returns true if they match
443
- */
444
- async verifyPublicKeyAddress(publicKey, expectedAddress) {
445
- try {
446
- // This would typically use the Aptos SDK to derive address from public key
447
- // For now, we'll do basic validation and let the relayer handle the actual verification
448
- this.validateAddressStrict(expectedAddress);
449
- if (!publicKey || !publicKey.startsWith('0x')) {
450
- return false;
451
- }
452
- // The actual verification is done by the relayer using the Aptos SDK
453
- // This is just a preliminary check
454
- return true;
455
- }
456
- catch (error) {
457
- return false;
458
- }
459
- }
460
- /**
461
- * Enhanced transaction preparation with better signature data structure
462
- * @param request Transfer request
463
- * @param quote Transfer quote
464
- * @returns Signature data with enhanced structure
465
- */
466
- async prepareTransferEnhanced(request, quote) {
467
- const baseSignatureData = await this.prepareTransfer(request, quote);
468
- return {
469
- ...baseSignatureData,
470
- metadata: {
471
- chain: this.chain,
472
- fromAddress: request.from,
473
- toAddress: request.to,
474
- amount: request.amount,
475
- token: request.token,
476
- relayerFee: quote.relayerFee,
477
- signatureVersion: '2.0', // Version for tracking signature format changes
478
- requiresPublicKey: true, // Indicates this chain requires public key for verification
479
- verificationMethod: 'ed25519_with_address_derivation' // Indicates verification method used
480
- }
481
- };
482
- }
483
- /**
484
- * Aptos-specific Move contract interaction
485
- */
486
- async callMoveFunction(functionName, args) {
487
- try {
488
- // Route through proxy: POST /api/v1/relayer/aptos/move/call
489
- const response = await this.httpClient.post(this.getApiPath('/move/call'), {
490
- function: functionName,
491
- arguments: args
492
- });
493
- // In proxy mode, errors are thrown by HttpClient, so we only handle success
494
- return response.data;
495
- }
496
- catch (error) {
497
- // Re-throw typed errors from HttpClient, wrap others
498
- if (error instanceof SmoothSendError) {
499
- throw error;
500
- }
501
- 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 });
502
- }
503
- }
504
- }
505
-
506
- /**
507
- * Stellar C-Address Adapter — SDK for Soroban Smart Account operations
508
- *
509
- * Provides a clean interface for:
510
- * - Creating C-addresses (smart accounts) from G-addresses
511
- * - Looking up existing C-addresses by owner
512
- * - Querying token balances (XLM, USDC, EURC)
513
- * - Building bridge transfers (G→C)
514
- * - Building smart account transfers (C→G, C→C)
515
- * - Submitting user-signed transactions via fee-bump
516
- * - Getting transaction history
517
- *
518
- * All transactions are gasless — the relayer covers fees via fee-bump.
519
- *
520
- * @example
521
- * ```typescript
522
- * import { SmoothSendSDK } from '@smoothsend/sdk';
523
- *
524
- * const sdk = new SmoothSendSDK({ apiKey: 'pk_nogas_xxx', network: 'testnet' });
525
- *
526
- * // Create a C-address for a G-address owner
527
- * const { cAddress } = await sdk.stellar.cAddress.create('GABCD...');
528
- *
529
- * // Get balances
530
- * const { balances } = await sdk.stellar.cAddress.getBalances(cAddress);
531
- *
532
- * // Build a bridge transfer (G→C), user signs, relayer fee-bumps
533
- * const { unsignedXDR } = await sdk.stellar.cAddress.buildBridgeTransfer({
534
- * from: 'GABCD...',
535
- * destination: cAddress,
536
- * asset: 'USDC',
537
- * amount: '10.5',
538
- * });
539
- * // Sign with wallet (e.g., Freighter)
540
- * const signedXDR = await wallet.signTransaction(unsignedXDR);
541
- * // Submit — relayer wraps in fee-bump
542
- * const { txHash } = await sdk.stellar.cAddress.submitTransfer(signedXDR);
543
- * ```
544
- */
545
- class StellarCAddressAdapter {
546
- constructor(httpClient, network = 'testnet') {
547
- this.httpClient = httpClient;
548
- // Multi-chain compatible path: /api/v1/relayer/{chain}/c-address
549
- this.basePath = '/api/v1/relayer/stellar/c-address';
550
- }
551
- /**
552
- * Create a new C-address (Soroban Smart Account) for a G-address owner.
553
- * If the owner already has a C-address, returns the existing one.
554
- *
555
- * The relayer pays all deployment fees — completely gasless for the user.
556
- *
557
- * @param ownerGAddress - The G-address that will control this smart account
558
- * @returns The new C-address, tx hash, and whether it already existed
559
- */
560
- async create(ownerGAddress) {
561
- this.validateGAddress(ownerGAddress);
562
- try {
563
- const response = await this.httpClient.post(`${this.basePath}/create`, { ownerGAddress }, { headers: { 'X-Chain': 'stellar' } });
564
- const data = response.data;
565
- if (!data.success) {
566
- throw new SmoothSendError(data.error || 'Failed to create C-address', 'C_ADDRESS_CREATE_FAILED', 500);
567
- }
568
- return {
569
- cAddress: data.cAddress,
570
- txHash: data.txHash,
571
- alreadyExisted: data.alreadyExisted,
572
- explorerUrl: data.explorerUrl,
573
- };
574
- }
575
- catch (error) {
576
- if (error instanceof SmoothSendError)
577
- throw error;
578
- throw new SmoothSendError(`Failed to create C-address: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_CREATE_FAILED', 500);
579
- }
580
- }
581
- /**
582
- * Look up the C-address for a given G-address owner.
583
- * Returns null if no C-address exists for this owner.
584
- *
585
- * @param ownerGAddress - The G-address to look up
586
- */
587
- async lookup(ownerGAddress) {
588
- this.validateGAddress(ownerGAddress);
589
- try {
590
- const response = await this.httpClient.get(`${this.basePath}/lookup/${ownerGAddress}`, { headers: { 'X-Chain': 'stellar' } });
591
- const data = response.data;
592
- return {
593
- ownerGAddress: data.ownerGAddress,
594
- cAddress: data.cAddress || null,
595
- hasAccount: data.hasAccount,
596
- };
597
- }
598
- catch (error) {
599
- if (error instanceof SmoothSendError)
600
- throw error;
601
- throw new SmoothSendError(`Failed to lookup C-address: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_LOOKUP_FAILED', 500);
602
- }
603
- }
604
- /**
605
- * Get token balances for a C-address.
606
- * Returns balances for XLM, USDC, and EURC.
607
- *
608
- * @param cAddress - The C-address to query
609
- */
610
- async getBalances(cAddress) {
611
- this.validateCAddress(cAddress);
612
- try {
613
- const response = await this.httpClient.get(`${this.basePath}/balance/${cAddress}`, { headers: { 'X-Chain': 'stellar' } });
614
- const data = response.data;
615
- return {
616
- cAddress: data.cAddress,
617
- balances: data.balances,
618
- };
619
- }
620
- catch (error) {
621
- if (error instanceof SmoothSendError)
622
- throw error;
623
- throw new SmoothSendError(`Failed to get balances: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_BALANCE_FAILED', 500);
624
- }
625
- }
626
- /**
627
- * Build a bridge transfer (G→C) using SAC.transfer.
628
- * Returns unsigned XDR for the user to sign with their wallet.
629
- * After signing, submit via submitTransfer().
630
- *
631
- * @param params.from - Sender G-address (signs the tx)
632
- * @param params.destination - Recipient C-address (or G-address)
633
- * @param params.asset - Asset to transfer: 'XLM', 'USDC', or 'EURC'
634
- * @param params.amount - Human-readable amount (e.g., '10.5')
635
- */
636
- async buildBridgeTransfer(params) {
637
- this.validateGAddress(params.from);
638
- try {
639
- const response = await this.httpClient.post(`${this.basePath}/bridge-transfer`, params, { headers: { 'X-Chain': 'stellar' } });
640
- const data = response.data;
641
- if (!data.success) {
642
- throw new SmoothSendError(data.error || 'Bridge transfer failed', 'BRIDGE_TRANSFER_FAILED', 500);
643
- }
644
- return {
645
- unsignedXDR: data.unsignedXDR,
646
- networkPassphrase: data.networkPassphrase,
647
- };
648
- }
649
- catch (error) {
650
- if (error instanceof SmoothSendError)
651
- throw error;
652
- throw new SmoothSendError(`Bridge transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'BRIDGE_TRANSFER_FAILED', 500);
653
- }
654
- }
655
- /**
656
- * Build a transfer from a C-address (SmartAccount.send).
657
- * Returns unsigned XDR for the owner to sign.
658
- * After signing, submit via submitTransfer().
659
- *
660
- * @param params.from - Owner G-address (signs auth)
661
- * @param params.cAddress - Source C-address (holds the funds)
662
- * @param params.destination - Recipient (G or C address)
663
- * @param params.asset - Asset: 'XLM', 'USDC', or 'EURC'
664
- * @param params.amount - Human-readable amount
665
- */
666
- async buildTransfer(params) {
667
- this.validateGAddress(params.from);
668
- this.validateCAddress(params.cAddress);
669
- try {
670
- const response = await this.httpClient.post(`${this.basePath}/build-transfer`, params, { headers: { 'X-Chain': 'stellar' } });
671
- const data = response.data;
672
- if (!data.success) {
673
- throw new SmoothSendError(data.error || 'Build transfer failed', 'BUILD_TRANSFER_FAILED', 500);
674
- }
675
- return {
676
- unsignedXDR: data.unsignedXDR,
677
- networkPassphrase: data.networkPassphrase,
678
- };
679
- }
680
- catch (error) {
681
- if (error instanceof SmoothSendError)
682
- throw error;
683
- throw new SmoothSendError(`Build transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'BUILD_TRANSFER_FAILED', 500);
684
- }
685
- }
686
- /**
687
- * Submit a user-signed transaction.
688
- * The relayer wraps it in a fee-bump transaction and submits to the network.
689
- * The user pays zero fees — the relayer covers everything.
690
- *
691
- * @param signedXDR - The user-signed transaction XDR (base64)
692
- */
693
- async submitTransfer(signedXDR) {
694
- if (!signedXDR) {
695
- throw new SmoothSendError('signedXDR is required', 'MISSING_SIGNED_XDR', 400);
696
- }
697
- try {
698
- const response = await this.httpClient.post(`${this.basePath}/submit-transfer`, { signedXDR }, { headers: { 'X-Chain': 'stellar' } });
699
- const data = response.data;
700
- if (!data.success) {
701
- throw new SmoothSendError(data.error || 'Submit failed', 'SUBMIT_TRANSFER_FAILED', 500);
702
- }
703
- return {
704
- txHash: data.txHash,
705
- explorerUrl: data.explorerUrl,
706
- };
707
- }
708
- catch (error) {
709
- if (error instanceof SmoothSendError)
710
- throw error;
711
- throw new SmoothSendError(`Submit transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'SUBMIT_TRANSFER_FAILED', 500);
712
- }
713
- }
714
- /**
715
- * Get transaction history for a C-address.
716
- * Returns recent transfer events (sent/received) across all supported tokens.
717
- *
718
- * @param cAddress - The C-address to query
719
- * @param limit - Maximum number of transactions to return (default: 20)
720
- */
721
- async getHistory(cAddress, limit = 20) {
722
- this.validateCAddress(cAddress);
723
- try {
724
- const response = await this.httpClient.get(`${this.basePath}/history/${cAddress}?limit=${limit}`, { headers: { 'X-Chain': 'stellar' } });
725
- const data = response.data;
726
- return {
727
- cAddress: data.cAddress,
728
- transactions: data.transactions || [],
729
- count: data.count || 0,
730
- };
731
- }
732
- catch (error) {
733
- if (error instanceof SmoothSendError)
734
- throw error;
735
- throw new SmoothSendError(`Failed to get history: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_HISTORY_FAILED', 500);
736
- }
737
- }
738
- /**
739
- * Health check for the C-address bridge service.
740
- */
741
- async health() {
742
- try {
743
- const response = await this.httpClient.get(`${this.basePath}/health`, { headers: { 'X-Chain': 'stellar' } });
744
- const data = response.data;
745
- return {
746
- service: data.service,
747
- relayerPublicKey: data.relayerPublicKey,
748
- factoryContractId: data.factoryContractId,
749
- isReady: data.isReady,
750
- network: data.network,
751
- };
752
- }
753
- catch (error) {
754
- if (error instanceof SmoothSendError)
755
- throw error;
756
- throw new SmoothSendError(`C-Address health check failed: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_HEALTH_FAILED', 500);
757
- }
758
- }
759
- // ─────────────────────────────────────────────────────────
760
- // Validation helpers
761
- // ─────────────────────────────────────────────────────────
762
- validateGAddress(address) {
763
- if (!address || !address.startsWith('G') || address.length !== 56) {
764
- throw new SmoothSendError('Invalid G-address. Must start with G and be 56 characters.', 'INVALID_G_ADDRESS', 400);
765
- }
766
- }
767
- validateCAddress(address) {
768
- if (!address || !address.startsWith('C') || address.length !== 56) {
769
- throw new SmoothSendError('Invalid C-address. Must start with C and be 56 characters.', 'INVALID_C_ADDRESS', 400);
770
- }
771
- }
772
- validateAddress(address) {
773
- return (typeof address === 'string' &&
774
- address.length === 56 &&
775
- (address.startsWith('G') || address.startsWith('C')));
776
- }
777
- }
778
-
779
- /** Headers to route requests to Stellar relayer via proxy */
780
- const STELLAR_HEADERS = { 'X-Chain': 'stellar' };
781
- /**
782
- * Stellar Adapter - Gasless transactions via Fee Bump
783
- * Routes through proxy.smoothsend.xyz with API key authentication
784
- * Supports XLM, USDC, EURC and other Stellar assets
785
- */
786
- class StellarAdapter {
787
- constructor(chain, config, apiKey, network = 'testnet', includeOrigin = false) {
788
- if (CHAIN_ECOSYSTEM_MAP[chain] !== 'stellar') {
789
- throw new SmoothSendError(`StellarAdapter can only handle Stellar chains, got: ${chain}`, 'INVALID_CHAIN_FOR_ADAPTER', 400, { chain });
790
- }
791
- this.chain = chain;
792
- this.config = config;
793
- this.network = network;
794
- this.httpClient = new HttpClient({
795
- apiKey,
796
- network,
797
- timeout: 30000,
798
- retries: 3,
799
- includeOrigin,
800
- });
801
- // Initialize C-Address adapter (Soroban Smart Account)
802
- this.cAddress = new StellarCAddressAdapter(this.httpClient, network);
803
- }
804
- setNetwork(network) {
805
- this.network = network;
806
- this.httpClient.setNetwork(network);
807
- }
808
- getNetwork() {
809
- return this.network;
810
- }
811
- /**
812
- * Stellar gasless: relayer pays fee. Returns 0 for user.
813
- */
814
- async estimateFee(_request) {
815
- return {
816
- relayerFee: '0',
817
- feeInUSD: '0',
818
- coinType: _request.token || 'XLM',
819
- estimatedGas: '0',
820
- network: this.network,
821
- };
822
- }
823
- /**
824
- * Submit signed XDR to relayer for Fee Bump wrapping
825
- */
826
- async executeGaslessTransfer(signedData) {
827
- if (!signedData.signedTransaction) {
828
- throw new SmoothSendError('signedTransaction (XDR) is required for Stellar gasless transfers', STELLAR_ERROR_CODES.MISSING_SIGNED_TRANSACTION, 400, { chain: this.chain });
829
- }
830
- try {
831
- const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', { signedTransaction: signedData.signedTransaction }, { headers: STELLAR_HEADERS });
832
- const data = response.data;
833
- const result = {
834
- success: data.success ?? true,
835
- txHash: data.hash ?? data.txnHash,
836
- transferId: data.hash ?? data.txnHash,
837
- explorerUrl: data.explorerUrl,
838
- gasFeePaidBy: 'relayer',
839
- gasUsed: data.feeStroops,
840
- };
841
- if (response.metadata) {
842
- result.metadata = response.metadata;
843
- }
844
- return result;
845
- }
846
- catch (error) {
847
- if (error instanceof SmoothSendError)
848
- throw error;
849
- throw new SmoothSendError(`Stellar gasless transfer failed: ${error instanceof Error ? error.message : String(error)}`, STELLAR_ERROR_CODES.GASLESS_TRANSACTION_ERROR, 500, { chain: this.chain });
850
- }
851
- }
852
- async getTransactionStatus(txHash) {
853
- try {
854
- const response = await this.httpClient.get(`/api/v1/relayer/stellar/status/${txHash}`, { headers: STELLAR_HEADERS });
855
- return response.data;
856
- }
857
- catch (error) {
858
- if (error instanceof SmoothSendError)
859
- throw error;
860
- 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 });
861
- }
862
- }
863
- async getHealth() {
864
- try {
865
- const response = await this.httpClient.get('/api/v1/relayer/stellar/health', {
866
- headers: STELLAR_HEADERS,
867
- });
868
- return {
869
- success: true,
870
- status: response.data.status ?? 'healthy',
871
- timestamp: response.data.timestamp ?? new Date().toISOString(),
872
- version: '2.0',
873
- };
874
- }
875
- catch (error) {
876
- if (error instanceof SmoothSendError)
877
- throw error;
878
- throw new SmoothSendError(`Stellar health check failed: ${error instanceof Error ? error.message : String(error)}`, STELLAR_ERROR_CODES.HEALTH_ERROR, 500, { chain: this.chain });
879
- }
880
- }
881
- validateAddress(address) {
882
- // Support both G-addresses (classic) and C-addresses (Soroban smart accounts)
883
- return /^[GC][A-Z2-7]{55}$/.test(address);
884
- }
885
- validateAmount(amount) {
886
- try {
887
- const n = parseFloat(amount);
888
- return !isNaN(n) && n > 0;
889
- }
890
- catch {
891
- return false;
892
- }
893
- }
894
- }
895
-
896
- class SmoothSendSDK {
897
- constructor(config) {
898
- this.adapters = new Map();
899
- this.eventListeners = [];
900
- this.hasWarnedAboutSecretKey = false;
901
- // Validate API key is provided
902
- if (!config.apiKey) {
903
- throw new SmoothSendError('API key is required. Get your API key from dashboard.smoothsend.xyz', 'MISSING_API_KEY');
904
- }
905
- // Detect and validate API key type
906
- this.keyType = this.detectKeyType(config.apiKey);
907
- // Warn if secret key is used in browser environment
908
- this.warnIfSecretKeyInBrowser();
909
- // Validate network parameter if provided
910
- if (config.network && config.network !== 'testnet' && config.network !== 'mainnet') {
911
- throw new SmoothSendError('Invalid network parameter. Must be "testnet" or "mainnet"', 'INVALID_NETWORK');
912
- }
913
- // Set configuration with defaults
914
- this.config = {
915
- apiKey: config.apiKey,
916
- network: config.network || 'testnet', // Default to testnet
917
- timeout: config.timeout || 30000,
918
- retries: config.retries || 3,
919
- customHeaders: config.customHeaders || {}
920
- };
921
- }
922
- /**
923
- * Detect key type from API key prefix
924
- * Supports pk_nogas_* (public), sk_nogas_* (secret), and no_gas_* (legacy)
925
- */
926
- detectKeyType(apiKey) {
927
- if (apiKey.startsWith('pk_nogas_')) {
928
- return 'public';
929
- }
930
- if (apiKey.startsWith('sk_nogas_')) {
931
- return 'secret';
932
- }
933
- if (apiKey.startsWith('no_gas_')) {
934
- return 'legacy';
935
- }
936
- throw new SmoothSendError('Invalid API key format. API key must start with "pk_nogas_", "sk_nogas_", or "no_gas_"', 'INVALID_API_KEY_FORMAT');
937
- }
938
- /**
939
- * Check if running in browser environment
940
- * Used for conditional warnings and Origin header logic
941
- */
942
- isBrowserEnvironment() {
943
- return typeof window !== 'undefined' && typeof window.document !== 'undefined';
944
- }
945
- /**
946
- * Warn if secret key is used in browser environment
947
- * Only warns once per SDK instance
948
- */
949
- warnIfSecretKeyInBrowser() {
950
- if (this.hasWarnedAboutSecretKey) {
951
- return;
952
- }
953
- if (this.keyType === 'secret' && this.isBrowserEnvironment()) {
954
- console.warn('⚠️ WARNING: Secret key detected in browser environment.\n' +
955
- 'Secret keys (sk_nogas_*) should only be used in server-side code.\n' +
956
- 'Use public keys (pk_nogas_*) for frontend applications.\n' +
957
- 'Learn more: https://docs.smoothsend.xyz/security/api-keys');
958
- this.hasWarnedAboutSecretKey = true;
959
- }
960
- }
961
- /**
962
- * Determine if Origin header should be included in requests
963
- * Include Origin header only for public keys in browser environment
964
- */
965
- shouldIncludeOrigin() {
966
- return this.keyType === 'public' && this.isBrowserEnvironment();
967
- }
968
- /**
969
- * Get or create adapter for a specific chain on-demand
970
- */
971
- getOrCreateAdapter(chain) {
972
- // Check if adapter already exists
973
- let adapter = this.adapters.get(chain);
974
- if (!adapter) {
975
- // Create adapter on-demand
976
- const ecosystem = CHAIN_ECOSYSTEM_MAP[chain];
977
- if (ecosystem === 'aptos') {
978
- // Create minimal config for adapter (proxy handles actual configuration)
979
- const minimalConfig = {
980
- name: chain,
981
- displayName: chain,
982
- chainId: 0,
983
- rpcUrl: '',
984
- relayerUrl: 'https://proxy.smoothsend.xyz',
985
- explorerUrl: '',
986
- tokens: [],
987
- nativeCurrency: {
988
- name: 'APT',
989
- symbol: 'APT',
990
- decimals: 8
991
- }
992
- };
993
- adapter = new AptosAdapter(chain, minimalConfig, this.config.apiKey, this.config.network || 'testnet', this.shouldIncludeOrigin());
994
- }
995
- else if (ecosystem === 'stellar') {
996
- const minimalConfig = {
997
- name: chain,
998
- displayName: chain,
999
- chainId: 0,
1000
- rpcUrl: '',
1001
- relayerUrl: 'https://proxy.smoothsend.xyz',
1002
- explorerUrl: '',
1003
- tokens: [],
1004
- nativeCurrency: { name: 'XLM', symbol: 'XLM', decimals: 7 },
1005
- };
1006
- adapter = new StellarAdapter(chain, minimalConfig, this.config.apiKey, this.config.network || 'testnet', this.shouldIncludeOrigin());
1007
- }
1008
- else if (ecosystem === 'evm') {
1009
- throw new SmoothSendError(`EVM chains not yet supported in v2. Chain: ${chain}`, 'UNSUPPORTED_CHAIN');
1010
- }
1011
- else {
1012
- throw new SmoothSendError(`Unsupported ecosystem: ${ecosystem}`, 'UNSUPPORTED_ECOSYSTEM');
1013
- }
1014
- // Cache the adapter for future use
1015
- this.adapters.set(chain, adapter);
1016
- }
1017
- return adapter;
1018
- }
1019
- // Event handling
1020
- addEventListener(listener) {
1021
- this.eventListeners.push(listener);
1022
- }
1023
- removeEventListener(listener) {
1024
- const index = this.eventListeners.indexOf(listener);
1025
- if (index > -1) {
1026
- this.eventListeners.splice(index, 1);
1027
- }
1028
- }
1029
- emitEvent(event) {
1030
- this.eventListeners.forEach(listener => {
1031
- try {
1032
- listener(event);
1033
- }
1034
- catch (error) {
1035
- console.error('Error in event listener:', error);
1036
- }
1037
- });
1038
- }
1039
- // Core transfer methods
1040
- async estimateFee(request) {
1041
- const adapter = this.getOrCreateAdapter(request.chain);
1042
- this.emitEvent({
1043
- type: 'transfer_initiated',
1044
- data: { request },
1045
- timestamp: Date.now(),
1046
- chain: request.chain
1047
- });
1048
- try {
1049
- const feeEstimate = await adapter.estimateFee(request);
1050
- // Metadata is already attached by the adapter from HTTP response headers
1051
- return feeEstimate;
1052
- }
1053
- catch (error) {
1054
- this.emitEvent({
1055
- type: 'transfer_failed',
1056
- data: { error: error instanceof Error ? error.message : String(error), step: 'estimate_fee' },
1057
- timestamp: Date.now(),
1058
- chain: request.chain
1059
- });
1060
- throw error;
1061
- }
1062
- }
1063
- /**
1064
- * Submit a signed Stellar transaction (XDR) for gasless relay.
1065
- * Use when you've already built and signed the transaction.
1066
- *
1067
- * @example
1068
- * const signedXdr = await stellarWallet.signTransaction(tx);
1069
- * const result = await sdk.submitStellarTransaction(signedXdr);
1070
- */
1071
- async submitStellarTransaction(signedXdr) {
1072
- const chain = this.config.network === 'mainnet' ? 'stellar-mainnet' : 'stellar-testnet';
1073
- return this.executeGaslessTransfer({
1074
- signedTransaction: signedXdr,
1075
- chain,
1076
- network: this.config.network,
1077
- });
1078
- }
1079
- async executeGaslessTransfer(signedData) {
1080
- const adapter = this.getOrCreateAdapter(signedData.chain);
1081
- this.emitEvent({
1082
- type: 'transfer_submitted',
1083
- data: { signedData },
1084
- timestamp: Date.now(),
1085
- chain: signedData.chain
1086
- });
1087
- try {
1088
- const result = await adapter.executeGaslessTransfer(signedData);
1089
- this.emitEvent({
1090
- type: 'transfer_confirmed',
1091
- data: { result },
1092
- timestamp: Date.now(),
1093
- chain: signedData.chain
1094
- });
1095
- return result;
1096
- }
1097
- catch (error) {
1098
- this.emitEvent({
1099
- type: 'transfer_failed',
1100
- data: { error: error instanceof Error ? error.message : String(error), step: 'execute' },
1101
- timestamp: Date.now(),
1102
- chain: signedData.chain
1103
- });
1104
- throw error;
1105
- }
1106
- }
1107
- /**
1108
- * Convenience method for complete transfer flow
1109
- * Works for both Aptos and Stellar - same 3-line API.
1110
- *
1111
- * @param request Transfer request with from, to, token, amount, chain
1112
- * @param wallet Aptos or Stellar wallet provider
1113
- * @returns Transfer result with transaction hash and usage metadata
1114
- *
1115
- * Aptos wallet: signTransaction returns { transactionBytes, authenticatorBytes }
1116
- * Stellar wallet: signTransaction returns string (signed XDR)
1117
- */
1118
- async transfer(request, wallet) {
1119
- this.emitEvent({
1120
- type: 'transfer_initiated',
1121
- data: { request },
1122
- timestamp: Date.now(),
1123
- chain: request.chain,
1124
- });
1125
- try {
1126
- const ecosystem = CHAIN_ECOSYSTEM_MAP[request.chain];
1127
- if (ecosystem === 'stellar') {
1128
- return this.transferStellar(request, wallet);
1129
- }
1130
- // Aptos flow
1131
- const aptosWallet = wallet;
1132
- const feeEstimate = await this.estimateFee(request);
1133
- const transaction = await aptosWallet.buildTransaction({
1134
- sender: request.from,
1135
- recipient: request.to,
1136
- amount: request.amount,
1137
- coinType: feeEstimate.coinType,
1138
- relayerFee: feeEstimate.relayerFee,
1139
- });
1140
- this.emitEvent({
1141
- type: 'transfer_signed',
1142
- data: { transaction },
1143
- timestamp: Date.now(),
1144
- chain: request.chain,
1145
- });
1146
- const signedTx = await aptosWallet.signTransaction(transaction);
1147
- return this.executeGaslessTransfer({
1148
- transactionBytes: signedTx.transactionBytes,
1149
- authenticatorBytes: signedTx.authenticatorBytes,
1150
- chain: request.chain,
1151
- network: this.config.network,
1152
- });
1153
- }
1154
- catch (error) {
1155
- this.emitEvent({
1156
- type: 'transfer_failed',
1157
- data: {
1158
- error: error instanceof Error ? error.message : String(error),
1159
- step: 'transfer',
1160
- },
1161
- timestamp: Date.now(),
1162
- chain: request.chain,
1163
- });
1164
- throw error;
1165
- }
1166
- }
1167
- async transferStellar(request, wallet) {
1168
- const transaction = await wallet.buildTransaction({
1169
- from: request.from,
1170
- to: request.to,
1171
- amount: request.amount,
1172
- token: request.token,
1173
- });
1174
- this.emitEvent({
1175
- type: 'transfer_signed',
1176
- data: { transaction },
1177
- timestamp: Date.now(),
1178
- chain: request.chain,
1179
- });
1180
- const signedXdr = await wallet.signTransaction(transaction);
1181
- return this.executeGaslessTransfer({
1182
- signedTransaction: signedXdr,
1183
- chain: request.chain,
1184
- network: this.config.network,
1185
- });
1186
- }
1187
- // Note: Batch transfer support will be implemented in a future phase
1188
- // Utility methods
1189
- /**
1190
- * Get transaction status for a specific transaction
1191
- * Routes through proxy to chain-specific status endpoint
1192
- *
1193
- * @param chain Chain where the transaction was executed
1194
- * @param txHash Transaction hash to query
1195
- * @returns Transaction status information
1196
- * @throws SmoothSendError if chain is not supported or status check fails
1197
- *
1198
- * @example
1199
- * ```typescript
1200
- * const status = await sdk.getTransactionStatus('aptos-testnet', '0x123...');
1201
- * console.log('Transaction status:', status);
1202
- * ```
1203
- */
1204
- async getTransactionStatus(chain, txHash) {
1205
- if (!this.isChainSupported(chain)) {
1206
- throw new SmoothSendError(`Chain ${chain} is not supported`, 'UNSUPPORTED_CHAIN', 400, { chain, supportedChains: this.getSupportedChains() });
1207
- }
1208
- if (!txHash || txHash.trim() === '') {
1209
- throw new SmoothSendError('Transaction hash is required', 'MISSING_TX_HASH', 400);
1210
- }
1211
- const adapter = this.getOrCreateAdapter(chain);
1212
- return await adapter.getTransactionStatus(txHash);
1213
- }
1214
- validateAddress(chain, address) {
1215
- const adapter = this.getOrCreateAdapter(chain);
1216
- return adapter.validateAddress(address);
1217
- }
1218
- validateAmount(chain, amount) {
1219
- const adapter = this.getOrCreateAdapter(chain);
1220
- return adapter.validateAmount(amount);
1221
- }
1222
- /**
1223
- * Check proxy worker health status
1224
- * Routes directly to proxy's /health endpoint (not chain-specific)
1225
- *
1226
- * @returns Health response with status, version, and timestamp
1227
- * @throws NetworkError if proxy is unavailable
1228
- * @throws SmoothSendError for other errors
1229
- *
1230
- * @example
1231
- * ```typescript
1232
- * try {
1233
- * const health = await sdk.getHealth();
1234
- * console.log('Proxy status:', health.status);
1235
- * console.log('Version:', health.version);
1236
- * } catch (error) {
1237
- * if (error instanceof NetworkError) {
1238
- * console.error('Proxy unavailable. Please retry later.');
1239
- * }
1240
- * }
1241
- * ```
1242
- */
1243
- async getHealth() {
1244
- // Import HttpClient for direct proxy health check
1245
- const { HttpClient } = await import('./shared-CNF22ESH.js').then(function (n) { return n.h; });
1246
- // Create HTTP client for direct proxy communication
1247
- const httpClient = new HttpClient({
1248
- apiKey: this.config.apiKey,
1249
- network: this.config.network || 'testnet',
1250
- timeout: this.config.timeout,
1251
- retries: this.config.retries,
1252
- includeOrigin: this.shouldIncludeOrigin()
1253
- });
1254
- try {
1255
- // Check proxy's general health endpoint (not chain-specific)
1256
- const response = await httpClient.get('/health');
1257
- const healthResponse = {
1258
- success: true,
1259
- status: response.data.status || 'healthy',
1260
- timestamp: response.data.timestamp || new Date().toISOString(),
1261
- version: response.data.version || '2.0'
1262
- };
1263
- // Attach usage metadata from proxy response headers
1264
- if (response.metadata) {
1265
- healthResponse.metadata = response.metadata;
1266
- }
1267
- return healthResponse;
1268
- }
1269
- catch (error) {
1270
- if (error instanceof SmoothSendError) {
1271
- throw error;
1272
- }
1273
- 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);
1274
- }
1275
- }
1276
- /**
1277
- * Get list of supported chains (static list)
1278
- * For dynamic list from proxy, use getSupportedChainsFromProxy()
1279
- *
1280
- * @returns Array of supported chain identifiers
1281
- *
1282
- * @example
1283
- * ```typescript
1284
- * const chains = sdk.getSupportedChains();
1285
- * console.log('Supported chains:', chains);
1286
- * // Output: ['aptos-testnet', 'aptos-mainnet']
1287
- * ```
1288
- */
1289
- getSupportedChains() {
1290
- return ['aptos-testnet', 'aptos-mainnet', 'stellar-testnet', 'stellar-mainnet'];
1291
- }
1292
- /**
1293
- * Get list of supported chains from proxy worker (dynamic)
1294
- * Queries the proxy for the current list of supported chains
1295
- *
1296
- * @returns Promise with array of chain information including status
1297
- * @throws SmoothSendError if unable to fetch chains from proxy
1298
- *
1299
- * @example
1300
- * ```typescript
1301
- * const chains = await sdk.getSupportedChainsFromProxy();
1302
- * chains.forEach(chain => {
1303
- * console.log(`${chain.name} (${chain.id}): ${chain.status}`);
1304
- * });
1305
- * ```
1306
- */
1307
- async getSupportedChainsFromProxy() {
1308
- const { HttpClient } = await import('./shared-CNF22ESH.js').then(function (n) { return n.h; });
1309
- const httpClient = new HttpClient({
1310
- apiKey: this.config.apiKey,
1311
- network: this.config.network || 'testnet',
1312
- timeout: this.config.timeout,
1313
- retries: this.config.retries,
1314
- includeOrigin: this.shouldIncludeOrigin()
1315
- });
1316
- try {
1317
- const response = await httpClient.get('/api/v1/chains');
1318
- if (!response.data.chains) {
1319
- throw new Error('Invalid response format from proxy');
1320
- }
1321
- return response.data.chains;
1322
- }
1323
- catch (error) {
1324
- if (error instanceof SmoothSendError) {
1325
- throw error;
1326
- }
1327
- throw new SmoothSendError(`Failed to fetch supported chains from proxy: ${error instanceof Error ? error.message : String(error)}`, 'CHAINS_FETCH_ERROR', 500);
1328
- }
1329
- }
1330
- /**
1331
- * Check if a specific chain is currently supported
1332
- *
1333
- * @param chain Chain identifier to check
1334
- * @returns true if chain is supported, false otherwise
1335
- *
1336
- * @example
1337
- * ```typescript
1338
- * if (sdk.isChainSupported('aptos-testnet')) {
1339
- * console.log('Aptos testnet is supported');
1340
- * } else {
1341
- * console.log('Chain not supported');
1342
- * }
1343
- * ```
1344
- */
1345
- isChainSupported(chain) {
1346
- const supportedChains = this.getSupportedChains();
1347
- return supportedChains.includes(chain);
1348
- }
1349
- /**
1350
- * Check health status of a specific chain's relayer
1351
- * Routes through proxy to chain-specific health endpoint
1352
- *
1353
- * @param chain Chain identifier to check
1354
- * @returns Health response for the specific chain
1355
- * @throws SmoothSendError if chain is not supported or health check fails
1356
- *
1357
- * @example
1358
- * ```typescript
1359
- * try {
1360
- * const health = await sdk.getChainHealth('aptos-testnet');
1361
- * console.log('Aptos testnet status:', health.status);
1362
- * } catch (error) {
1363
- * console.error('Chain health check failed:', error.message);
1364
- * }
1365
- * ```
1366
- */
1367
- async getChainHealth(chain) {
1368
- if (!this.isChainSupported(chain)) {
1369
- throw new SmoothSendError(`Chain ${chain} is not supported`, 'UNSUPPORTED_CHAIN', 400, { chain, supportedChains: this.getSupportedChains() });
1370
- }
1371
- const adapter = this.getOrCreateAdapter(chain);
1372
- return await adapter.getHealth();
1373
- }
1374
- /**
1375
- * Get current usage statistics without making a transfer
1376
- * Makes a lightweight health check request to retrieve usage metadata
1377
- *
1378
- * @returns Usage metadata with rate limit and monthly usage information
1379
- * @throws Error if unable to retrieve usage stats
1380
- *
1381
- * @example
1382
- * ```typescript
1383
- * const usage = await sdk.getUsageStats();
1384
- * console.log('Rate limit:', usage.rateLimit);
1385
- * console.log('Monthly usage:', usage.monthly);
1386
- * console.log('Request ID:', usage.requestId);
1387
- *
1388
- * // Check if approaching limits
1389
- * if (parseInt(usage.rateLimit.remaining) < 2) {
1390
- * console.warn('Approaching rate limit!');
1391
- * }
1392
- * ```
1393
- */
1394
- async getUsageStats() {
1395
- try {
1396
- // Make a health check request to get usage metadata from headers
1397
- const health = await this.getHealth();
1398
- // The health response includes metadata from the HTTP client
1399
- const healthWithMetadata = health;
1400
- if (!healthWithMetadata.metadata) {
1401
- throw new SmoothSendError('Usage metadata not available. This may occur if not using proxy mode.', 'METADATA_NOT_AVAILABLE');
1402
- }
1403
- return healthWithMetadata.metadata;
1404
- }
1405
- catch (error) {
1406
- // If health check fails, we can't get usage stats
1407
- if (error instanceof SmoothSendError) {
1408
- throw error;
1409
- }
1410
- throw new SmoothSendError(`Failed to retrieve usage statistics: ${error instanceof Error ? error.message : String(error)}`, 'USAGE_STATS_ERROR');
1411
- }
1412
- }
1413
- /**
1414
- * Extract request ID from a transfer result for debugging and support
1415
- *
1416
- * @param result Transfer result from executeGaslessTransfer or transfer
1417
- * @returns Request ID if available, undefined otherwise
1418
- *
1419
- * @example
1420
- * ```typescript
1421
- * const result = await sdk.executeGaslessTransfer(signedData);
1422
- * const requestId = sdk.getRequestId(result);
1423
- * if (requestId) {
1424
- * console.log('Request ID for support:', requestId);
1425
- * }
1426
- * ```
1427
- */
1428
- getRequestId(result) {
1429
- return result.metadata?.requestId;
1430
- }
1431
- /**
1432
- * Check if approaching rate limit based on transfer result metadata
1433
- *
1434
- * @param result Transfer result with metadata
1435
- * @param threshold Percentage threshold (0-100) to consider as "approaching" (default: 20)
1436
- * @returns true if remaining requests are below threshold percentage
1437
- *
1438
- * @example
1439
- * ```typescript
1440
- * const result = await sdk.transfer(request, wallet);
1441
- * if (sdk.isApproachingRateLimit(result)) {
1442
- * console.warn('Approaching rate limit, consider slowing down requests');
1443
- * }
1444
- * ```
1445
- */
1446
- isApproachingRateLimit(result, threshold = 20) {
1447
- if (!result.metadata?.rateLimit) {
1448
- return false;
1449
- }
1450
- const limit = parseInt(result.metadata.rateLimit.limit);
1451
- const remaining = parseInt(result.metadata.rateLimit.remaining);
1452
- if (isNaN(limit) || isNaN(remaining) || limit === 0) {
1453
- return false;
1454
- }
1455
- const percentageRemaining = (remaining / limit) * 100;
1456
- return percentageRemaining <= threshold;
1457
- }
1458
- /**
1459
- * Check if approaching monthly usage limit based on transfer result metadata
1460
- *
1461
- * @param result Transfer result with metadata
1462
- * @param threshold Percentage threshold (0-100) to consider as "approaching" (default: 90)
1463
- * @returns true if monthly usage is above threshold percentage
1464
- *
1465
- * @example
1466
- * ```typescript
1467
- * const result = await sdk.transfer(request, wallet);
1468
- * if (sdk.isApproachingMonthlyLimit(result)) {
1469
- * console.warn('Approaching monthly limit, consider upgrading plan');
1470
- * }
1471
- * ```
1472
- */
1473
- isApproachingMonthlyLimit(result, threshold = 90) {
1474
- if (!result.metadata?.monthly) {
1475
- return false;
1476
- }
1477
- const limit = parseInt(result.metadata.monthly.limit);
1478
- const usage = parseInt(result.metadata.monthly.usage);
1479
- if (isNaN(limit) || isNaN(usage) || limit === 0) {
1480
- return false;
1481
- }
1482
- const percentageUsed = (usage / limit) * 100;
1483
- return percentageUsed >= threshold;
1484
- }
1485
- // Ecosystem-specific methods for advanced usage
1486
- /**
1487
- * Check if a chain belongs to a specific ecosystem
1488
- */
1489
- getChainEcosystem(chain) {
1490
- return CHAIN_ECOSYSTEM_MAP[chain];
1491
- }
1492
- // Static utility methods
1493
- /**
1494
- * Get list of supported chains (static method)
1495
- * Can be called without instantiating the SDK
1496
- *
1497
- * @returns Array of supported chain identifiers
1498
- *
1499
- * @example
1500
- * ```typescript
1501
- * const chains = SmoothSendSDK.getSupportedChains();
1502
- * console.log('Supported chains:', chains);
1503
- * ```
1504
- */
1505
- static getSupportedChains() {
1506
- return ['aptos-testnet', 'aptos-mainnet', 'stellar-testnet', 'stellar-mainnet'];
1507
- }
1508
- }
1509
-
1510
- export { APTOS_ERROR_CODES as A, CHAIN_ECOSYSTEM_MAP as C, SmoothSendSDK as S, StellarAdapter as a, StellarCAddressAdapter as b, STELLAR_ERROR_CODES as c, AptosAdapter as d };
1511
- //# sourceMappingURL=shared-CaQMAGQR.js.map