@smoothsend/sdk 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import axios from 'axios';
2
- import { useEffect, useCallback } from 'react';
3
- import { useWallet } from '@aptos-labs/wallet-adapter-react';
4
2
  import { Network, Aptos, AptosConfig, Account, MoveVector, AccountAddress, AbstractedAccount } from '@aptos-labs/ts-sdk';
3
+ import { useState, useEffect, useCallback } from 'react';
4
+ import { useWallet } from '@aptos-labs/wallet-adapter-react';
5
5
 
6
6
  /**
7
7
  * Error handling system for SmoothSend SDK v2
@@ -402,7 +402,7 @@ class HttpClient {
402
402
  this.apiKey = config.apiKey;
403
403
  this.network = config.network || 'testnet';
404
404
  this.maxRetries = config.retries || 3;
405
- this.baseURL = 'https://proxy.smoothsend.xyz';
405
+ this.baseURL = config.baseUrl || 'https://proxy.smoothsend.xyz';
406
406
  this.isProxyMode = true;
407
407
  this.includeOrigin = config.includeOrigin || false;
408
408
  const headers = {
@@ -411,10 +411,9 @@ class HttpClient {
411
411
  'X-Network': this.network,
412
412
  ...config.customHeaders,
413
413
  };
414
- // Add Origin header if in browser and includeOrigin is true
415
- if (this.includeOrigin && typeof window !== 'undefined' && window.location) {
416
- headers['Origin'] = window.location.origin;
417
- }
414
+ // Browsers forbid setting the `Origin` header manually ("unsafe header").
415
+ // The browser will set it automatically on cross-origin requests.
416
+ // If callers need the origin explicitly, they can pass a custom header (e.g. `X-Origin`).
418
417
  this.client = axios.create({
419
418
  baseURL: this.baseURL,
420
419
  timeout: config.timeout || 30000,
@@ -2062,6 +2061,24 @@ class SmoothSendSDK {
2062
2061
  }
2063
2062
  }
2064
2063
 
2064
+ /**
2065
+ * Pre-compiled Move script bytecode for add_permissioned_handle
2066
+ *
2067
+ * This bytecode is used to register session keys on-chain via the
2068
+ * `0x1::permissioned_delegation::add_permissioned_handle` function.
2069
+ *
2070
+ * The function cannot be called as an entry function directly — only via a Move script.
2071
+ * This bytecode handles:
2072
+ * - Takes the session public key bytes (vector<u8>) as input
2073
+ * - Constructs DelegationKey from the bytes
2074
+ * - Passes option::none() for rate limiter
2075
+ * - Hardcodes u64::MAX for expiration (on-chain handle never expires)
2076
+ *
2077
+ * Source: aptos-labs/aptos-ts-sdk tests/e2e/transaction/helper.ts
2078
+ */
2079
+ const ADD_PERMISSIONED_HANDLE_BYTECODE = 'a11ceb0b0700000a0801001002101603262c04520405563d079301d70208ea034010aa041f0103010401060109010d010e011201140002080002080700030b0700040c0f0005100701000001050301010001020704050001030a05060001050f01080100010311090a000106130b01000107150b0100010002030702060c0a020001080001060c010a02010801010802010803010b0401090004060c08020b0401080303010c03060c060c03050802030b04010803060c0c083c53454c463e5f30046d61696e094170746f73436f696e0a6170746f735f636f696e04636f696e196d6967726174655f746f5f66756e6769626c655f73746f72650765643235353139256e65775f756e76616c6964617465645f7075626c69635f6b65795f66726f6d5f627974657314556e76616c6964617465645075626c69634b657917' +
2080
+ '7065726d697373696f6e65645f64656c65676174696f6e0f67656e5f656432353531395f6b65790d44656c65676174696f6e4b65790b526174654c696d697465720c726174655f6c696d69746572066f7074696f6e046e6f6e65064f7074696f6e176164645f7065726d697373696f6e65645f68616e646c65167072696d6172795f66756e6769626c655f73746f7265146772616e745f6170745f7065726d697373696f6e167472616e73616374696f6e5f76616c69646174696f6e146772616e745f6761735f7065726d697373696f6effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000114636f6d70696c6174696f6e5f6d65746164617461090003322e3003322e3100000c170a0038000b01110111020c020a0038010c040b020b040600a0724e1809000011040c060a000e060600e1f5050000000011050b000e060600e1f50500000000110602';
2081
+
2065
2082
  /**
2066
2083
  * SmoothSend Transaction Submitter
2067
2084
  *
@@ -2099,6 +2116,7 @@ class SmoothSendSDK {
2099
2116
  */
2100
2117
  class SmoothSendTransactionSubmitter {
2101
2118
  constructor(config) {
2119
+ this._session = null;
2102
2120
  this.sponsoredFunctionsCache = null;
2103
2121
  this.sponsoredFunctionsCacheAt = 0;
2104
2122
  this.SPONSORED_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
@@ -2123,7 +2141,177 @@ class SmoothSendTransactionSubmitter {
2123
2141
  this.timeout = config.timeout || 30000;
2124
2142
  this.getCaptchaToken = config.getCaptchaToken;
2125
2143
  this.debug = config.debug || false;
2144
+ this.sessionEnabled = config.session || false;
2145
+ this.sessionDuration = config.sessionDuration || '24h';
2146
+ }
2147
+ // ─── Session key methods ────────────────────────────────────────────────────
2148
+ /**
2149
+ * Whether a valid session is currently active.
2150
+ */
2151
+ hasSession() {
2152
+ return this._session !== null && Date.now() < this._session.expiresAtMs;
2153
+ }
2154
+ /**
2155
+ * Create a session key for the given master account.
2156
+ * Called once by useSmoothSend when session: true and no session exists.
2157
+ * SmoothSend pays gas for the setup transaction.
2158
+ *
2159
+ * @param masterAccount - The user's wallet account (from wallet adapter)
2160
+ */
2161
+ async createSession(masterAccount) {
2162
+ const network = this.network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2163
+ const aptosClient = new Aptos(new AptosConfig({ network }));
2164
+ // Generate fresh in-memory session keypair
2165
+ const sessionAccount = Account.generate();
2166
+ const expiresAtMs = Date.now() + this._parseDuration(this.sessionDuration);
2167
+ // Step 1: Register session key on-chain via pre-compiled Move script
2168
+ const setupTx = await aptosClient.transaction.build.simple({
2169
+ sender: masterAccount.accountAddress,
2170
+ withFeePayer: true,
2171
+ data: {
2172
+ bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
2173
+ functionArguments: [MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
2174
+ },
2175
+ options: {
2176
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2177
+ },
2178
+ });
2179
+ const senderAuth = await this.signSenderAuthenticator(masterAccount, setupTx, aptosClient);
2180
+ const setupResult = await this.submitTransaction({
2181
+ aptosConfig: aptosClient.config,
2182
+ transaction: setupTx,
2183
+ senderAuthenticator: senderAuth,
2184
+ });
2185
+ await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
2186
+ if (this.debug) {
2187
+ console.log('[SmoothSend] Session key registered on-chain:', setupResult.hash);
2188
+ }
2189
+ // Step 2: Enable account abstraction (idempotent — skip if already on)
2190
+ const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
2191
+ accountAddress: masterAccount.accountAddress,
2192
+ authenticationFunction: '0x1::permissioned_delegation::authenticate',
2193
+ });
2194
+ if (!aaEnabled) {
2195
+ const aaTx = await aptosClient.transaction.build.simple({
2196
+ sender: masterAccount.accountAddress,
2197
+ withFeePayer: true,
2198
+ data: {
2199
+ function: '0x1::account_abstraction::add_authentication_function',
2200
+ functionArguments: [
2201
+ AccountAddress.fromString('0x1'),
2202
+ 'permissioned_delegation',
2203
+ 'authenticate',
2204
+ ],
2205
+ },
2206
+ options: {
2207
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2208
+ },
2209
+ });
2210
+ const aaAuth = await this.signSenderAuthenticator(masterAccount, aaTx, aptosClient);
2211
+ const aaResult = await this.submitTransaction({
2212
+ aptosConfig: aptosClient.config,
2213
+ transaction: aaTx,
2214
+ senderAuthenticator: aaAuth,
2215
+ });
2216
+ await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
2217
+ if (this.debug) {
2218
+ console.log('[SmoothSend] Account abstraction enabled:', aaResult.hash);
2219
+ }
2220
+ }
2221
+ // Build AbstractedAccount — signs future txs with session key,
2222
+ // sender on-chain = master address, chain validates via permissioned_delegation
2223
+ const abstractedAccount = AbstractedAccount.fromPermissionedSigner({
2224
+ signer: sessionAccount,
2225
+ accountAddress: masterAccount.accountAddress,
2226
+ });
2227
+ this._session = {
2228
+ sessionAccount,
2229
+ abstractedAccount,
2230
+ masterAddress: masterAccount.accountAddress,
2231
+ expiresAtMs,
2232
+ aptosClient,
2233
+ };
2234
+ }
2235
+ async isPermissionedSignerEnabled(aptosClient) {
2236
+ try {
2237
+ const result = await aptosClient.view({
2238
+ payload: {
2239
+ function: '0x1::features::is_permissioned_signer_enabled',
2240
+ functionArguments: [],
2241
+ },
2242
+ });
2243
+ return Array.isArray(result) && result[0] === true;
2244
+ }
2245
+ catch (error) {
2246
+ if (this.debug) {
2247
+ console.warn('[SmoothSend] Failed to probe permissioned signer feature:', error);
2248
+ }
2249
+ return false;
2250
+ }
2251
+ }
2252
+ async signSenderAuthenticator(signer, transaction, aptosClient) {
2253
+ const walletLikeSigner = signer;
2254
+ // Wallet-adapter compatible path (returns { authenticator, rawTransaction } in v8)
2255
+ if (typeof walletLikeSigner?.signTransactionWithAuthenticator === 'function') {
2256
+ const result = await walletLikeSigner.signTransactionWithAuthenticator(transaction);
2257
+ return (result?.authenticator ?? result);
2258
+ }
2259
+ // Native ts-sdk account path
2260
+ return aptosClient.transaction.sign({
2261
+ signer,
2262
+ transaction,
2263
+ });
2264
+ }
2265
+ /**
2266
+ * Submit a transaction using the active session key — no wallet popup.
2267
+ * Called by useSmoothSend after session is established.
2268
+ */
2269
+ async submitWithSession(functionName, functionArguments = [], typeArguments = []) {
2270
+ if (!this._session || !this.hasSession()) {
2271
+ throw new Error('[SmoothSend] No active session. Call createSession() first.');
2272
+ }
2273
+ const { abstractedAccount, masterAddress, aptosClient } = this._session;
2274
+ const tx = await aptosClient.transaction.build.simple({
2275
+ sender: masterAddress,
2276
+ withFeePayer: true,
2277
+ data: {
2278
+ function: functionName,
2279
+ functionArguments,
2280
+ ...(typeArguments.length > 0 ? { typeArguments } : {}),
2281
+ },
2282
+ options: {
2283
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2284
+ },
2285
+ });
2286
+ const senderAuth = aptosClient.transaction.sign({
2287
+ signer: abstractedAccount,
2288
+ transaction: tx,
2289
+ });
2290
+ return this.submitTransaction({
2291
+ aptosConfig: aptosClient.config,
2292
+ transaction: tx,
2293
+ senderAuthenticator: senderAuth,
2294
+ });
2126
2295
  }
2296
+ _parseDuration(duration) {
2297
+ if (duration === 'never') {
2298
+ // Client-side "never expires" mode; on-chain handle already uses u64::MAX.
2299
+ return Number.MAX_SAFE_INTEGER;
2300
+ }
2301
+ const n = parseInt(duration, 10);
2302
+ if (isNaN(n))
2303
+ throw new Error(`Invalid sessionDuration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
2304
+ if (duration.endsWith('s'))
2305
+ return n * 1000;
2306
+ if (duration.endsWith('m'))
2307
+ return n * 60 * 1000;
2308
+ if (duration.endsWith('h'))
2309
+ return n * 3600 * 1000;
2310
+ if (duration.endsWith('d'))
2311
+ return n * 86400 * 1000;
2312
+ throw new Error(`Unknown unit in "${duration}". Supported: s, m, h, d, or "never".`);
2313
+ }
2314
+ // ─── Transaction submission ──────────────────────────────────────────────────
2127
2315
  /**
2128
2316
  * Submit a transaction through SmoothSend's gasless relayer
2129
2317
  *
@@ -2331,6 +2519,10 @@ function createSmoothSendSubmitter(apiKey, options) {
2331
2519
  * - Function in allowlist → fee-payer gasless path via SmoothSend
2332
2520
  * - Function not in allowlist → regular wallet submission (user pays gas)
2333
2521
  *
2522
+ * When submitter has session: true, the first transaction triggers a one-time
2523
+ * wallet sign to register a session key on-chain. Every transaction after that
2524
+ * is signed silently — zero wallet popups.
2525
+ *
2334
2526
  * Requires: react >=17, @aptos-labs/wallet-adapter-react >=3, @aptos-labs/ts-sdk >=1
2335
2527
  *
2336
2528
  * @example
@@ -2342,13 +2534,11 @@ function createSmoothSendSubmitter(apiKey, options) {
2342
2534
  * await signAndSubmitTransaction({ data: { function: '0x1::coin::transfer', functionArguments: [to, amount] } });
2343
2535
  * ```
2344
2536
  */
2345
- /**
2346
- * useSmoothSend
2347
- *
2348
- * @param submitter - A SmoothSendTransactionSubmitter instance (created once, e.g. at module scope)
2349
- */
2350
2537
  function useSmoothSend(submitter) {
2351
2538
  const { account, signTransaction, signAndSubmitTransaction: walletSignAndSubmit, } = useWallet();
2539
+ // Track session state reactively so UI updates when session is created/expires
2540
+ const initialHasSession = submitter?.hasSession?.() ?? false;
2541
+ const [hasSessionState, setHasSessionState] = useState(initialHasSession);
2352
2542
  // Prefetch the sponsored-functions list on mount so the first transaction
2353
2543
  // benefits from an already-populated cache with no added latency.
2354
2544
  useEffect(() => {
@@ -2356,11 +2546,85 @@ function useSmoothSend(submitter) {
2356
2546
  // Fail-open: getSponsoredFunctions already handles errors internally
2357
2547
  });
2358
2548
  }, [submitter]);
2549
+ useEffect(() => {
2550
+ if (!submitter)
2551
+ return;
2552
+ const refresh = () => {
2553
+ const hasSession = submitter.hasSession?.() ?? false;
2554
+ setHasSessionState(hasSession);
2555
+ };
2556
+ refresh();
2557
+ const timer = setInterval(refresh, 1000);
2558
+ return () => clearInterval(timer);
2559
+ }, [submitter]);
2359
2560
  const signAndSubmitTransaction = useCallback(async (input) => {
2360
2561
  if (!account?.address) {
2361
2562
  throw new Error('[SmoothSend] Wallet not connected');
2362
2563
  }
2363
2564
  const functionName = input?.data?.function ?? '';
2565
+ console.log('[SmoothSend] signAndSubmitTransaction called:', {
2566
+ functionName,
2567
+ sessionEnabled: submitter.sessionEnabled,
2568
+ hasSession: submitter.hasSession(),
2569
+ });
2570
+ // ── Session key path ────────────────────────────────────────────────────
2571
+ // When session: true, bypass wallet signing entirely after first setup.
2572
+ // Still respects the per-function allowlist — non-sponsored functions
2573
+ // fall through to regular wallet submission (user pays gas).
2574
+ if (submitter.sessionEnabled) {
2575
+ console.log('[SmoothSend] Session mode enabled');
2576
+ // Check allowlist first — no point setting up a session for a non-sponsored function
2577
+ const canGoGasless = typeof signTransaction === 'function';
2578
+ const sponsored = canGoGasless && (await submitter.isSponsored(functionName));
2579
+ console.log('[SmoothSend] Sponsored check:', { sponsored, canGoGasless });
2580
+ if (sponsored) {
2581
+ // If no active session, do the one-time setup
2582
+ if (!submitter.hasSession()) {
2583
+ console.log('[SmoothSend] No session, creating one...');
2584
+ if (!signTransaction) {
2585
+ console.warn('[SmoothSend] session: true requires signTransaction support. Falling back to regular submission.');
2586
+ }
2587
+ else {
2588
+ try {
2589
+ // Adapter object only needs accountAddress + signTransactionWithAuthenticator.
2590
+ // The submitter handles both wallet-adapter and native signer shapes.
2591
+ const walletAccount = {
2592
+ accountAddress: account.address,
2593
+ signTransactionWithAuthenticator: async (tx) => {
2594
+ const rawResult = await signTransaction({
2595
+ transactionOrPayload: tx,
2596
+ asFeePayer: false,
2597
+ });
2598
+ return rawResult?.authenticator ?? rawResult;
2599
+ },
2600
+ };
2601
+ await submitter.createSession(walletAccount);
2602
+ console.log('[SmoothSend] Session created successfully');
2603
+ setHasSessionState(submitter.hasSession?.() ?? false);
2604
+ }
2605
+ catch (err) {
2606
+ console.warn('[SmoothSend] Session setup failed, falling back to regular gasless:', err.message);
2607
+ // Fall through to normal gasless path below
2608
+ }
2609
+ }
2610
+ }
2611
+ // If session is now active, submit silently — no wallet popup
2612
+ if (submitter.hasSession()) {
2613
+ console.log('[SmoothSend] Session is active, using submitWithSession');
2614
+ try {
2615
+ return await submitter.submitWithSession(functionName, input.data?.functionArguments ?? [], input.data?.typeArguments ?? []);
2616
+ }
2617
+ catch (err) {
2618
+ // Session may have expired mid-flight — clear it and fall through
2619
+ console.warn('[SmoothSend] Session submit failed, will re-auth on next call:', err.message);
2620
+ setHasSessionState(false);
2621
+ // Fall through to regular gasless path for this call
2622
+ }
2623
+ }
2624
+ }
2625
+ // Non-sponsored function → fall through to walletSignAndSubmit below
2626
+ }
2627
+ // ── Regular gasless path (TransactionSubmitter) ─────────────────────────
2364
2628
  // signTransaction (sign-only) must be available for the gasless path.
2365
2629
  // Most modern wallets (Petra, Nightly) support it. If absent, fall through.
2366
2630
  const canGoGasless = typeof signTransaction === 'function';
@@ -2416,21 +2680,21 @@ function useSmoothSend(submitter) {
2416
2680
  // Not sponsored or signTransaction unavailable → regular wallet submission
2417
2681
  return walletSignAndSubmit(input);
2418
2682
  }, [account, signTransaction, walletSignAndSubmit, submitter]);
2419
- return { signAndSubmitTransaction };
2683
+ return {
2684
+ signAndSubmitTransaction,
2685
+ hasSession: hasSessionState,
2686
+ };
2420
2687
  }
2421
2688
 
2422
- // ─── Pre-compiled Move script bytecode ───────────────────────────────────────
2423
- // Source: aptos-labs/aptos-ts-sdk tests/e2e/transaction/helper.ts
2424
- // This script calls permissioned_delegation::add_permissioned_handle, which is
2425
- // NOT an entry function and cannot be called directly — only via a Move script.
2426
- // Takes one argument: the session public key bytes (vector<u8>).
2427
- const ADD_PERMISSIONED_HANDLE_BYTECODE = 'a11ceb0b0700000a0801001002101603262c04520405563d079301d70208ea034010aa041f0103010401060109010d010e011201140002080002080700030b0700040c0f0005100701000001050301010001020704050001030a05060001050f01080100010311090a000106130b01000107150b0100010002030702060c0a020001080001060c010a02010801010802010803010b0401090004060c08020b0401080303010c03060c060c03050802030b04010803060c0c083c53454c463e5f30046d61696e094170746f73436f696e0a6170746f735f636f696e04636f696e196d6967726174655f746f5f66756e6769626c655f73746f72650765643235353139256e65775f756e76616c6964617465645f7075626c69635f6b65795f66726f6d5f627974657314556e76616c6964617465645075626c69634b657917' +
2428
- '7065726d697373696f6e65645f64656c65676174696f6e0f67656e5f656432353531395f6b65790d44656c65676174696f6e4b65790b526174654c696d697465720c726174655f6c696d69746572066f7074696f6e046e6f6e65064f7074696f6e176164645f7065726d697373696f6e65645f68616e646c65167072696d6172795f66756e6769626c655f73746f7265146772616e745f6170745f7065726d697373696f6e167472616e73616374696f6e5f76616c69646174696f6e146772616e745f6761735f7065726d697373696f6effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000114636f6d70696c6174696f6e5f6d65746164617461090003322e3003322e3100000c170a0038000b01110111020c020a0038010c040b020b040600a0724e1809000011040c060a000e060600e1f5050000000011050b000e060600e1f50500000000110602';
2429
2689
  // ─── helpers ────────────────────────────────────────────────────────────────
2430
2690
  function parseDurationToSeconds(duration) {
2691
+ if (duration === 'never') {
2692
+ // Client-side "never expires" mode; on-chain handle already uses u64::MAX.
2693
+ return Math.floor(Number.MAX_SAFE_INTEGER / 1000);
2694
+ }
2431
2695
  const n = parseInt(duration, 10);
2432
2696
  if (isNaN(n))
2433
- throw new Error(`Invalid duration "${duration}". Use e.g. "2h", "24h", "7d".`);
2697
+ throw new Error(`Invalid duration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
2434
2698
  if (duration.endsWith('s'))
2435
2699
  return n;
2436
2700
  if (duration.endsWith('m'))
@@ -2439,15 +2703,10 @@ function parseDurationToSeconds(duration) {
2439
2703
  return n * 3600;
2440
2704
  if (duration.endsWith('d'))
2441
2705
  return n * 86400;
2442
- throw new Error(`Unknown duration unit in "${duration}". Supported: s, m, h, d.`);
2706
+ throw new Error(`Unknown duration unit in "${duration}". Supported: s, m, h, d, or "never".`);
2443
2707
  }
2444
2708
  // ─── SmoothSendSession ───────────────────────────────────────────────────────
2445
2709
  /**
2446
- * @experimental
2447
- * Session keys require ACCOUNT_ABSTRACTION (feature 85) and PERMISSIONED_SIGNER (feature 84)
2448
- * to be enabled on the Aptos network. As of now these features are only live on devnet/local node.
2449
- * This will be fully released when the features are activated on testnet and mainnet.
2450
- *
2451
2710
  * A session that lets your app submit transactions on behalf of a user
2452
2711
  * without any wallet popup after the initial one-time setup.
2453
2712
  *
@@ -2490,6 +2749,15 @@ class SmoothSendSession {
2490
2749
  const network = options.network ?? submitter.getConfig().network ?? 'testnet';
2491
2750
  const aptosNetwork = network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2492
2751
  const aptosClient = new Aptos(new AptosConfig({ network: aptosNetwork }));
2752
+ const feature = await aptosClient.view({
2753
+ payload: {
2754
+ function: '0x1::features::is_permissioned_signer_enabled',
2755
+ functionArguments: [],
2756
+ },
2757
+ }).catch(() => [false]);
2758
+ if (!Array.isArray(feature) || feature[0] !== true) {
2759
+ throw new Error('[SmoothSend] Session keys unavailable on this network (permissioned signer feature disabled).');
2760
+ }
2493
2761
  // Generate a fresh Ed25519 session keypair (lives in memory, never persisted)
2494
2762
  const sessionAccount = Account.generate();
2495
2763
  // Client-side expiry tracking (the bytecode script doesn't take an expiry arg)
@@ -2886,6 +3154,134 @@ function createScriptComposerClient(config) {
2886
3154
  return new ScriptComposerClient(config);
2887
3155
  }
2888
3156
 
3157
+ /**
3158
+ * True Gasless Client
3159
+ *
3160
+ * Designed for server-side (backend) environments to securely build, sign,
3161
+ * and submit 100% sponsored gasless transactions using a Secret Key.
3162
+ *
3163
+ * @example
3164
+ * ```typescript
3165
+ * import { TrueGaslessClient } from '@smoothsend/sdk';
3166
+ * import { Account } from '@aptos-labs/ts-sdk';
3167
+ *
3168
+ * const backendWallet = Account.fromPrivateKey({ privateKey: '...' });
3169
+ * const client = new TrueGaslessClient({ apiKey: 'sk_nogas_...', network: 'mainnet' });
3170
+ *
3171
+ * const result = await client.execute({
3172
+ * senderAccount: backendWallet,
3173
+ * payload: {
3174
+ * function: "0x123::my_module::mint_nft",
3175
+ * functionArguments: []
3176
+ * }
3177
+ * });
3178
+ *
3179
+ * console.log("Gasless NFT Minted!", result.txHash);
3180
+ * ```
3181
+ */
3182
+ class TrueGaslessClient {
3183
+ constructor(config) {
3184
+ if (!config.apiKey) {
3185
+ throw new SmoothSendError('API key is required', 'MISSING_API_KEY', 400);
3186
+ }
3187
+ if (!config.apiKey.startsWith('sk_nogas_')) {
3188
+ console.warn('⚠️ WARNING: TrueGaslessClient is intended for backend use with a Secret Key (sk_nogas_*).\n' +
3189
+ 'Using a Public Key may result in CORS errors if ran in a browser environment.');
3190
+ }
3191
+ if (!config.network) {
3192
+ throw new SmoothSendError('Network is required (testnet or mainnet)', 'MISSING_NETWORK', 400);
3193
+ }
3194
+ this.config = {
3195
+ apiKey: config.apiKey,
3196
+ network: config.network,
3197
+ proxyUrl: config.proxyUrl,
3198
+ timeout: config.timeout || 30000,
3199
+ debug: config.debug || false,
3200
+ };
3201
+ this.httpClient = new HttpClient({
3202
+ apiKey: this.config.apiKey,
3203
+ network: this.config.network,
3204
+ timeout: this.config.timeout,
3205
+ retries: 3,
3206
+ includeOrigin: false, // Backend client should not send Origin header
3207
+ baseUrl: this.config.proxyUrl, // Use custom proxy URL if provided
3208
+ });
3209
+ const networkMap = {
3210
+ testnet: Network.TESTNET,
3211
+ mainnet: Network.MAINNET,
3212
+ };
3213
+ this.aptos = new Aptos(new AptosConfig({ network: networkMap[this.config.network] }));
3214
+ }
3215
+ log(message, data) {
3216
+ if (this.config.debug) {
3217
+ console.log(`[TrueGaslessClient] ${message}`, data || '');
3218
+ }
3219
+ }
3220
+ /**
3221
+ * Builds, signs (as sender), and relays an arbitrary payload for complete sponsorship.
3222
+ */
3223
+ async execute(params) {
3224
+ this.log('Starting gasless execution', { sender: params.senderAccount.accountAddress.toString(), payload: params.payload });
3225
+ if (!params.senderAccount || !params.payload) {
3226
+ throw new SmoothSendError('Missing required parameters: senderAccount and payload', 'INVALID_PARAMETERS', 400);
3227
+ }
3228
+ try {
3229
+ this.log('Building simple transaction with fee payer enabled');
3230
+ // Build the transaction and flag it requires a remote fee payer
3231
+ const transaction = await this.aptos.transaction.build.simple({
3232
+ sender: params.senderAccount.accountAddress,
3233
+ data: params.payload,
3234
+ withFeePayer: true,
3235
+ });
3236
+ this.log('Signing transaction locally with senderAccount');
3237
+ // Sign locally over the transaction hash
3238
+ const senderAuthenticator = this.aptos.transaction.sign({
3239
+ signer: params.senderAccount,
3240
+ transaction,
3241
+ });
3242
+ this.log('Serializing to bytes for relayer transmission');
3243
+ // Convert to BCS bytes expected by the proxy
3244
+ const transactionBytes = Array.from(transaction.bcsToBytes());
3245
+ const authenticatorBytes = Array.from(senderAuthenticator.bcsToBytes());
3246
+ this.log('Sending to relayer...');
3247
+ const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
3248
+ transactionBytes,
3249
+ authenticatorBytes,
3250
+ network: this.config.network,
3251
+ functionName: 'function' in params.payload ? params.payload.function : 'unknown',
3252
+ });
3253
+ this.log('Relayer submission successful', response.data);
3254
+ return {
3255
+ success: response.data.success ?? true,
3256
+ requestId: response.data.requestId,
3257
+ txHash: response.data.txnHash || response.data.txHash,
3258
+ gasUsed: response.data.gasUsed,
3259
+ vmStatus: response.data.vmStatus,
3260
+ sender: response.data.sender || params.senderAccount.accountAddress.toString(),
3261
+ };
3262
+ }
3263
+ catch (error) {
3264
+ this.log('Gasless execution failed', error);
3265
+ if (error instanceof SmoothSendError) {
3266
+ throw error;
3267
+ }
3268
+ throw new SmoothSendError(`Failed to execute gasless transaction: ${error.message}`, 'EXECUTION_FAILED', 500, { originalError: error.message });
3269
+ }
3270
+ }
3271
+ /**
3272
+ * Expose the core Aptos instance to allow backend developers to access chain state if needed
3273
+ */
3274
+ getAptosClient() {
3275
+ return this.aptos;
3276
+ }
3277
+ }
3278
+ /**
3279
+ * Helper to initialize TrueGaslessClient
3280
+ */
3281
+ function createTrueGaslessClient(config) {
3282
+ return new TrueGaslessClient(config);
3283
+ }
3284
+
2889
3285
  /**
2890
3286
  * SmoothSend SDK v2.0
2891
3287
  *
@@ -2917,7 +3313,7 @@ function createScriptComposerClient(config) {
2917
3313
  * SDK version
2918
3314
  * @public
2919
3315
  */
2920
- const VERSION = '2.2.0';
3316
+ const VERSION = '2.2.1';
2921
3317
 
2922
- export { APTOS_ERROR_CODES, AptosAdapter, AuthenticationError, CHAIN_ECOSYSTEM_MAP, HttpClient, NetworkError, RateLimitError, STELLAR_ERROR_CODES, ScriptComposerClient, SmoothSendError, SmoothSendSDK, SmoothSendSession, SmoothSendTransactionSubmitter, StellarAdapter, StellarCAddressAdapter, VERSION, ValidationError, createErrorFromResponse, createNetworkError, createScriptComposerClient, createSmoothSendSubmitter, SmoothSendSDK as default, useSmoothSend };
3318
+ export { APTOS_ERROR_CODES, AptosAdapter, AuthenticationError, CHAIN_ECOSYSTEM_MAP, HttpClient, NetworkError, RateLimitError, STELLAR_ERROR_CODES, ScriptComposerClient, SmoothSendError, SmoothSendSDK, SmoothSendSession, SmoothSendTransactionSubmitter, StellarAdapter, StellarCAddressAdapter, TrueGaslessClient, VERSION, ValidationError, createErrorFromResponse, createNetworkError, createScriptComposerClient, createSmoothSendSubmitter, createTrueGaslessClient, SmoothSendSDK as default, useSmoothSend };
2923
3319
  //# sourceMappingURL=index.esm.js.map