@smoothsend/sdk 1.1.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -922,15 +922,27 @@ class AptosAdapter {
922
922
  }
923
923
  /**
924
924
  * Get Aptos token address from symbol
925
+ * Mirrors aptosrelayer/config/chains.json
925
926
  */
926
927
  getAptosTokenAddress(tokenSymbol) {
927
- // This would typically come from the chain configuration
928
- if (tokenSymbol.toUpperCase() === 'USDC') {
929
- if (this.chain === 'aptos-testnet') {
930
- return '0x3c27315fb69ba6e4b960f1507d1cefcc9a4247869f26a8d59d6b7869d23782c::test_coins::USDC';
931
- }
928
+ const symbol = tokenSymbol.toUpperCase();
929
+ const TESTNET_TOKENS = {
930
+ USDC: '0x3c27315fb69ba6e4b960f1507d1cefcc9a4247869f26a8d59d6b7869d23782c::test_coins::USDC'
931
+ };
932
+ const MAINNET_TOKENS = {
933
+ USDT: '0x357b0b74bc833e95a115ad22604854d6b0fca151cecd94111770e5d6ffc9dc2b',
934
+ USDC: '0xbae207659db88bea0cbead6da0ed00aac12edcdda169e591cd41c94180b46f3b',
935
+ WBTC: '0x68844a0d7f2587e726ad0579f3d640865bb4162c08a4589eeda3f9689ec52a3d',
936
+ USDE: '0xf37a8864fe737eb8ec2c2931047047cbaed1beed3fb0e5b7c5526dafd3b9c2e9',
937
+ USD1: '0x05fabd1b12e39967a3c24e91b7b8f67719a6dacee74f3c8b9fb7d93e855437d2'
938
+ };
939
+ const tokens = this.chain === 'aptos-testnet' ? TESTNET_TOKENS : MAINNET_TOKENS;
940
+ const address = tokens[symbol];
941
+ if (!address) {
942
+ const supported = Object.keys(tokens).join(', ');
943
+ throw new SmoothSendError(`Unsupported token: ${tokenSymbol} on ${this.chain}. Supported: ${supported}`, APTOS_ERROR_CODES.UNSUPPORTED_TOKEN, 400, { chain: this.chain, token: tokenSymbol, supported });
932
944
  }
933
- throw new SmoothSendError(`Unsupported token: ${tokenSymbol} on ${this.chain}`, APTOS_ERROR_CODES.UNSUPPORTED_TOKEN, 400, { chain: this.chain, token: tokenSymbol });
945
+ return address;
934
946
  }
935
947
  /**
936
948
  * Build Aptos explorer URL for transaction
@@ -1047,6 +1059,279 @@ class AptosAdapter {
1047
1059
  }
1048
1060
  }
1049
1061
 
1062
+ /**
1063
+ * Stellar C-Address Adapter — SDK for Soroban Smart Account operations
1064
+ *
1065
+ * Provides a clean interface for:
1066
+ * - Creating C-addresses (smart accounts) from G-addresses
1067
+ * - Looking up existing C-addresses by owner
1068
+ * - Querying token balances (XLM, USDC, EURC)
1069
+ * - Building bridge transfers (G→C)
1070
+ * - Building smart account transfers (C→G, C→C)
1071
+ * - Submitting user-signed transactions via fee-bump
1072
+ * - Getting transaction history
1073
+ *
1074
+ * All transactions are gasless — the relayer covers fees via fee-bump.
1075
+ *
1076
+ * @example
1077
+ * ```typescript
1078
+ * import { SmoothSendSDK } from '@smoothsend/sdk';
1079
+ *
1080
+ * const sdk = new SmoothSendSDK({ apiKey: 'pk_nogas_xxx', network: 'testnet' });
1081
+ *
1082
+ * // Create a C-address for a G-address owner
1083
+ * const { cAddress } = await sdk.stellar.cAddress.create('GABCD...');
1084
+ *
1085
+ * // Get balances
1086
+ * const { balances } = await sdk.stellar.cAddress.getBalances(cAddress);
1087
+ *
1088
+ * // Build a bridge transfer (G→C), user signs, relayer fee-bumps
1089
+ * const { unsignedXDR } = await sdk.stellar.cAddress.buildBridgeTransfer({
1090
+ * from: 'GABCD...',
1091
+ * destination: cAddress,
1092
+ * asset: 'USDC',
1093
+ * amount: '10.5',
1094
+ * });
1095
+ * // Sign with wallet (e.g., Freighter)
1096
+ * const signedXDR = await wallet.signTransaction(unsignedXDR);
1097
+ * // Submit — relayer wraps in fee-bump
1098
+ * const { txHash } = await sdk.stellar.cAddress.submitTransfer(signedXDR);
1099
+ * ```
1100
+ */
1101
+ class StellarCAddressAdapter {
1102
+ constructor(httpClient, network = 'testnet') {
1103
+ this.httpClient = httpClient;
1104
+ // Multi-chain compatible path: /api/v1/relayer/{chain}/c-address
1105
+ this.basePath = '/api/v1/relayer/stellar/c-address';
1106
+ }
1107
+ /**
1108
+ * Create a new C-address (Soroban Smart Account) for a G-address owner.
1109
+ * If the owner already has a C-address, returns the existing one.
1110
+ *
1111
+ * The relayer pays all deployment fees — completely gasless for the user.
1112
+ *
1113
+ * @param ownerGAddress - The G-address that will control this smart account
1114
+ * @returns The new C-address, tx hash, and whether it already existed
1115
+ */
1116
+ async create(ownerGAddress) {
1117
+ this.validateGAddress(ownerGAddress);
1118
+ try {
1119
+ const response = await this.httpClient.post(`${this.basePath}/create`, { ownerGAddress }, { headers: { 'X-Chain': 'stellar' } });
1120
+ const data = response.data;
1121
+ if (!data.success) {
1122
+ throw new SmoothSendError(data.error || 'Failed to create C-address', 'C_ADDRESS_CREATE_FAILED', 500);
1123
+ }
1124
+ return {
1125
+ cAddress: data.cAddress,
1126
+ txHash: data.txHash,
1127
+ alreadyExisted: data.alreadyExisted,
1128
+ explorerUrl: data.explorerUrl,
1129
+ };
1130
+ }
1131
+ catch (error) {
1132
+ if (error instanceof SmoothSendError)
1133
+ throw error;
1134
+ throw new SmoothSendError(`Failed to create C-address: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_CREATE_FAILED', 500);
1135
+ }
1136
+ }
1137
+ /**
1138
+ * Look up the C-address for a given G-address owner.
1139
+ * Returns null if no C-address exists for this owner.
1140
+ *
1141
+ * @param ownerGAddress - The G-address to look up
1142
+ */
1143
+ async lookup(ownerGAddress) {
1144
+ this.validateGAddress(ownerGAddress);
1145
+ try {
1146
+ const response = await this.httpClient.get(`${this.basePath}/lookup/${ownerGAddress}`, { headers: { 'X-Chain': 'stellar' } });
1147
+ const data = response.data;
1148
+ return {
1149
+ ownerGAddress: data.ownerGAddress,
1150
+ cAddress: data.cAddress || null,
1151
+ hasAccount: data.hasAccount,
1152
+ };
1153
+ }
1154
+ catch (error) {
1155
+ if (error instanceof SmoothSendError)
1156
+ throw error;
1157
+ throw new SmoothSendError(`Failed to lookup C-address: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_LOOKUP_FAILED', 500);
1158
+ }
1159
+ }
1160
+ /**
1161
+ * Get token balances for a C-address.
1162
+ * Returns balances for XLM, USDC, and EURC.
1163
+ *
1164
+ * @param cAddress - The C-address to query
1165
+ */
1166
+ async getBalances(cAddress) {
1167
+ this.validateCAddress(cAddress);
1168
+ try {
1169
+ const response = await this.httpClient.get(`${this.basePath}/balance/${cAddress}`, { headers: { 'X-Chain': 'stellar' } });
1170
+ const data = response.data;
1171
+ return {
1172
+ cAddress: data.cAddress,
1173
+ balances: data.balances,
1174
+ };
1175
+ }
1176
+ catch (error) {
1177
+ if (error instanceof SmoothSendError)
1178
+ throw error;
1179
+ throw new SmoothSendError(`Failed to get balances: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_BALANCE_FAILED', 500);
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Build a bridge transfer (G→C) using SAC.transfer.
1184
+ * Returns unsigned XDR for the user to sign with their wallet.
1185
+ * After signing, submit via submitTransfer().
1186
+ *
1187
+ * @param params.from - Sender G-address (signs the tx)
1188
+ * @param params.destination - Recipient C-address (or G-address)
1189
+ * @param params.asset - Asset to transfer: 'XLM', 'USDC', or 'EURC'
1190
+ * @param params.amount - Human-readable amount (e.g., '10.5')
1191
+ */
1192
+ async buildBridgeTransfer(params) {
1193
+ this.validateGAddress(params.from);
1194
+ try {
1195
+ const response = await this.httpClient.post(`${this.basePath}/bridge-transfer`, params, { headers: { 'X-Chain': 'stellar' } });
1196
+ const data = response.data;
1197
+ if (!data.success) {
1198
+ throw new SmoothSendError(data.error || 'Bridge transfer failed', 'BRIDGE_TRANSFER_FAILED', 500);
1199
+ }
1200
+ return {
1201
+ unsignedXDR: data.unsignedXDR,
1202
+ networkPassphrase: data.networkPassphrase,
1203
+ };
1204
+ }
1205
+ catch (error) {
1206
+ if (error instanceof SmoothSendError)
1207
+ throw error;
1208
+ throw new SmoothSendError(`Bridge transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'BRIDGE_TRANSFER_FAILED', 500);
1209
+ }
1210
+ }
1211
+ /**
1212
+ * Build a transfer from a C-address (SmartAccount.send).
1213
+ * Returns unsigned XDR for the owner to sign.
1214
+ * After signing, submit via submitTransfer().
1215
+ *
1216
+ * @param params.from - Owner G-address (signs auth)
1217
+ * @param params.cAddress - Source C-address (holds the funds)
1218
+ * @param params.destination - Recipient (G or C address)
1219
+ * @param params.asset - Asset: 'XLM', 'USDC', or 'EURC'
1220
+ * @param params.amount - Human-readable amount
1221
+ */
1222
+ async buildTransfer(params) {
1223
+ this.validateGAddress(params.from);
1224
+ this.validateCAddress(params.cAddress);
1225
+ try {
1226
+ const response = await this.httpClient.post(`${this.basePath}/build-transfer`, params, { headers: { 'X-Chain': 'stellar' } });
1227
+ const data = response.data;
1228
+ if (!data.success) {
1229
+ throw new SmoothSendError(data.error || 'Build transfer failed', 'BUILD_TRANSFER_FAILED', 500);
1230
+ }
1231
+ return {
1232
+ unsignedXDR: data.unsignedXDR,
1233
+ networkPassphrase: data.networkPassphrase,
1234
+ };
1235
+ }
1236
+ catch (error) {
1237
+ if (error instanceof SmoothSendError)
1238
+ throw error;
1239
+ throw new SmoothSendError(`Build transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'BUILD_TRANSFER_FAILED', 500);
1240
+ }
1241
+ }
1242
+ /**
1243
+ * Submit a user-signed transaction.
1244
+ * The relayer wraps it in a fee-bump transaction and submits to the network.
1245
+ * The user pays zero fees — the relayer covers everything.
1246
+ *
1247
+ * @param signedXDR - The user-signed transaction XDR (base64)
1248
+ */
1249
+ async submitTransfer(signedXDR) {
1250
+ if (!signedXDR) {
1251
+ throw new SmoothSendError('signedXDR is required', 'MISSING_SIGNED_XDR', 400);
1252
+ }
1253
+ try {
1254
+ const response = await this.httpClient.post(`${this.basePath}/submit-transfer`, { signedXDR }, { headers: { 'X-Chain': 'stellar' } });
1255
+ const data = response.data;
1256
+ if (!data.success) {
1257
+ throw new SmoothSendError(data.error || 'Submit failed', 'SUBMIT_TRANSFER_FAILED', 500);
1258
+ }
1259
+ return {
1260
+ txHash: data.txHash,
1261
+ explorerUrl: data.explorerUrl,
1262
+ };
1263
+ }
1264
+ catch (error) {
1265
+ if (error instanceof SmoothSendError)
1266
+ throw error;
1267
+ throw new SmoothSendError(`Submit transfer failed: ${error instanceof Error ? error.message : String(error)}`, 'SUBMIT_TRANSFER_FAILED', 500);
1268
+ }
1269
+ }
1270
+ /**
1271
+ * Get transaction history for a C-address.
1272
+ * Returns recent transfer events (sent/received) across all supported tokens.
1273
+ *
1274
+ * @param cAddress - The C-address to query
1275
+ * @param limit - Maximum number of transactions to return (default: 20)
1276
+ */
1277
+ async getHistory(cAddress, limit = 20) {
1278
+ this.validateCAddress(cAddress);
1279
+ try {
1280
+ const response = await this.httpClient.get(`${this.basePath}/history/${cAddress}?limit=${limit}`, { headers: { 'X-Chain': 'stellar' } });
1281
+ const data = response.data;
1282
+ return {
1283
+ cAddress: data.cAddress,
1284
+ transactions: data.transactions || [],
1285
+ count: data.count || 0,
1286
+ };
1287
+ }
1288
+ catch (error) {
1289
+ if (error instanceof SmoothSendError)
1290
+ throw error;
1291
+ throw new SmoothSendError(`Failed to get history: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_HISTORY_FAILED', 500);
1292
+ }
1293
+ }
1294
+ /**
1295
+ * Health check for the C-address bridge service.
1296
+ */
1297
+ async health() {
1298
+ try {
1299
+ const response = await this.httpClient.get(`${this.basePath}/health`, { headers: { 'X-Chain': 'stellar' } });
1300
+ const data = response.data;
1301
+ return {
1302
+ service: data.service,
1303
+ relayerPublicKey: data.relayerPublicKey,
1304
+ factoryContractId: data.factoryContractId,
1305
+ isReady: data.isReady,
1306
+ network: data.network,
1307
+ };
1308
+ }
1309
+ catch (error) {
1310
+ if (error instanceof SmoothSendError)
1311
+ throw error;
1312
+ throw new SmoothSendError(`C-Address health check failed: ${error instanceof Error ? error.message : String(error)}`, 'C_ADDRESS_HEALTH_FAILED', 500);
1313
+ }
1314
+ }
1315
+ // ─────────────────────────────────────────────────────────
1316
+ // Validation helpers
1317
+ // ─────────────────────────────────────────────────────────
1318
+ validateGAddress(address) {
1319
+ if (!address || !address.startsWith('G') || address.length !== 56) {
1320
+ throw new SmoothSendError('Invalid G-address. Must start with G and be 56 characters.', 'INVALID_G_ADDRESS', 400);
1321
+ }
1322
+ }
1323
+ validateCAddress(address) {
1324
+ if (!address || !address.startsWith('C') || address.length !== 56) {
1325
+ throw new SmoothSendError('Invalid C-address. Must start with C and be 56 characters.', 'INVALID_C_ADDRESS', 400);
1326
+ }
1327
+ }
1328
+ validateAddress(address) {
1329
+ return (typeof address === 'string' &&
1330
+ address.length === 56 &&
1331
+ (address.startsWith('G') || address.startsWith('C')));
1332
+ }
1333
+ }
1334
+
1050
1335
  /** Headers to route requests to Stellar relayer via proxy */
1051
1336
  const STELLAR_HEADERS = { 'X-Chain': 'stellar' };
1052
1337
  /**
@@ -1069,6 +1354,8 @@ class StellarAdapter {
1069
1354
  retries: 3,
1070
1355
  includeOrigin,
1071
1356
  });
1357
+ // Initialize C-Address adapter (Soroban Smart Account)
1358
+ this.cAddress = new StellarCAddressAdapter(this.httpClient, network);
1072
1359
  }
1073
1360
  setNetwork(network) {
1074
1361
  this.network = network;
@@ -1148,7 +1435,8 @@ class StellarAdapter {
1148
1435
  }
1149
1436
  }
1150
1437
  validateAddress(address) {
1151
- return /^G[A-Z2-7]{55}$/.test(address);
1438
+ // Support both G-addresses (classic) and C-addresses (Soroban smart accounts)
1439
+ return /^[GC][A-Z2-7]{55}$/.test(address);
1152
1440
  }
1153
1441
  validateAmount(amount) {
1154
1442
  try {
@@ -1831,6 +2119,7 @@ class SmoothSendTransactionSubmitter {
1831
2119
  this.network = config.network || 'testnet';
1832
2120
  this.gatewayUrl = config.gatewayUrl || 'https://proxy.smoothsend.xyz';
1833
2121
  this.timeout = config.timeout || 30000;
2122
+ this.getCaptchaToken = config.getCaptchaToken;
1834
2123
  this.debug = config.debug || false;
1835
2124
  }
1836
2125
  /**
@@ -1841,26 +2130,34 @@ class SmoothSendTransactionSubmitter {
1841
2130
  * SmoothSend's relayer which sponsors the gas fees.
1842
2131
  */
1843
2132
  async submitTransaction(args) {
1844
- const { transaction, senderAuthenticator, pluginParams } = args;
2133
+ const { aptosConfig, transaction, senderAuthenticator, pluginParams } = args;
2134
+ // Auto-detect network from aptosConfig (source of truth from wallet adapter)
2135
+ // Falls back to constructor value if aptosConfig doesn't have a recognized network
2136
+ const detectedNetwork = this.resolveNetwork(aptosConfig);
1845
2137
  if (this.debug) {
1846
2138
  console.log('[SmoothSend] Submitting gasless transaction:', {
1847
2139
  sender: transaction.rawTransaction?.sender?.toString(),
1848
- network: this.network,
2140
+ configNetwork: this.network,
2141
+ detectedNetwork,
1849
2142
  });
1850
2143
  }
2144
+ if (detectedNetwork !== this.network && this.debug) {
2145
+ console.warn(`[SmoothSend] Network mismatch: constructor=${this.network}, aptosConfig=${detectedNetwork}. ` +
2146
+ `Using aptosConfig network (${detectedNetwork}).`);
2147
+ }
1851
2148
  try {
1852
2149
  // Serialize transaction and authenticator to bytes
1853
2150
  const transactionBytes = Array.from(transaction.bcsToBytes());
1854
2151
  const authenticatorBytes = Array.from(senderAuthenticator.bcsToBytes());
1855
- // Prepare request payload
2152
+ // Prepare request payload — always use the detected network
1856
2153
  const payload = {
1857
2154
  transactionBytes,
1858
2155
  authenticatorBytes,
1859
- network: this.network,
2156
+ network: detectedNetwork,
1860
2157
  functionName: pluginParams?.functionName || 'unknown',
1861
2158
  };
1862
2159
  // Make request to SmoothSend gateway
1863
- const response = await this.makeRequest('/api/v1/relayer/gasless-transaction', payload);
2160
+ const response = await this.makeRequest('/api/v1/relayer/gasless-transaction', payload, detectedNetwork);
1864
2161
  if (!response.success || !response.txnHash) {
1865
2162
  throw new Error(response.error || response.details || 'Transaction submission failed');
1866
2163
  }
@@ -1889,20 +2186,57 @@ class SmoothSendTransactionSubmitter {
1889
2186
  throw new Error(`SmoothSend gasless transaction failed: ${error.message}`);
1890
2187
  }
1891
2188
  }
2189
+ /**
2190
+ * Resolve the effective network from aptosConfig.
2191
+ * aptosConfig.network is the source of truth set by AptosWalletAdapterProvider.
2192
+ */
2193
+ resolveNetwork(aptosConfig) {
2194
+ try {
2195
+ const configNetwork = aptosConfig?.network;
2196
+ if (configNetwork === 'testnet' || configNetwork === 'mainnet') {
2197
+ return configNetwork;
2198
+ }
2199
+ if (typeof configNetwork === 'string') {
2200
+ const normalized = configNetwork.toLowerCase();
2201
+ if (normalized === 'testnet' || normalized === 'mainnet') {
2202
+ return normalized;
2203
+ }
2204
+ }
2205
+ }
2206
+ catch {
2207
+ // fall through
2208
+ }
2209
+ return this.network;
2210
+ }
1892
2211
  /**
1893
2212
  * Make an HTTP request to the SmoothSend gateway
1894
2213
  */
1895
- async makeRequest(endpoint, payload) {
2214
+ async makeRequest(endpoint, payload, network) {
2215
+ const effectiveNetwork = network || this.network;
1896
2216
  const url = `${this.gatewayUrl}${endpoint}`;
1897
2217
  const headers = {
1898
2218
  'Content-Type': 'application/json',
1899
2219
  'X-API-Key': this.apiKey,
1900
- 'X-Chain': `aptos-${this.network}`,
2220
+ 'X-Chain': `aptos-${effectiveNetwork}`,
1901
2221
  };
1902
2222
  // Add Origin header for public keys in browser
1903
2223
  if (this.apiKey.startsWith('pk_nogas_') && typeof window !== 'undefined') {
1904
2224
  headers['Origin'] = window.location.origin;
1905
2225
  }
2226
+ // Add captcha token if the project requires it
2227
+ if (this.getCaptchaToken) {
2228
+ try {
2229
+ const token = await this.getCaptchaToken();
2230
+ if (token) {
2231
+ headers['X-Captcha-Token'] = token;
2232
+ }
2233
+ }
2234
+ catch (e) {
2235
+ if (this.debug) {
2236
+ console.warn('[SmoothSend] Failed to get captcha token:', e);
2237
+ }
2238
+ }
2239
+ }
1906
2240
  const controller = new AbortController();
1907
2241
  const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1908
2242
  try {
@@ -2236,7 +2570,7 @@ function createScriptComposerClient(config) {
2236
2570
  * SDK version
2237
2571
  * @public
2238
2572
  */
2239
- const VERSION = '1.1.0'; // Multi-chain: Aptos + Stellar
2573
+ const VERSION = '2.0.0'; // Multi-chain: Aptos + Stellar + C-Address
2240
2574
 
2241
2575
  exports.APTOS_ERROR_CODES = APTOS_ERROR_CODES;
2242
2576
  exports.AptosAdapter = AptosAdapter;
@@ -2251,6 +2585,7 @@ exports.SmoothSendError = SmoothSendError;
2251
2585
  exports.SmoothSendSDK = SmoothSendSDK;
2252
2586
  exports.SmoothSendTransactionSubmitter = SmoothSendTransactionSubmitter;
2253
2587
  exports.StellarAdapter = StellarAdapter;
2588
+ exports.StellarCAddressAdapter = StellarCAddressAdapter;
2254
2589
  exports.VERSION = VERSION;
2255
2590
  exports.ValidationError = ValidationError;
2256
2591
  exports.createErrorFromResponse = createErrorFromResponse;