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