@smoothsend/sdk 2.1.3 → 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.js CHANGED
@@ -3,9 +3,9 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var axios = require('axios');
6
+ var tsSdk = require('@aptos-labs/ts-sdk');
6
7
  var react = require('react');
7
8
  var walletAdapterReact = require('@aptos-labs/wallet-adapter-react');
8
- var tsSdk = require('@aptos-labs/ts-sdk');
9
9
 
10
10
  /**
11
11
  * Error handling system for SmoothSend SDK v2
@@ -406,7 +406,7 @@ class HttpClient {
406
406
  this.apiKey = config.apiKey;
407
407
  this.network = config.network || 'testnet';
408
408
  this.maxRetries = config.retries || 3;
409
- this.baseURL = 'https://proxy.smoothsend.xyz';
409
+ this.baseURL = config.baseUrl || 'https://proxy.smoothsend.xyz';
410
410
  this.isProxyMode = true;
411
411
  this.includeOrigin = config.includeOrigin || false;
412
412
  const headers = {
@@ -415,10 +415,9 @@ class HttpClient {
415
415
  'X-Network': this.network,
416
416
  ...config.customHeaders,
417
417
  };
418
- // Add Origin header if in browser and includeOrigin is true
419
- if (this.includeOrigin && typeof window !== 'undefined' && window.location) {
420
- headers['Origin'] = window.location.origin;
421
- }
418
+ // Browsers forbid setting the `Origin` header manually ("unsafe header").
419
+ // The browser will set it automatically on cross-origin requests.
420
+ // If callers need the origin explicitly, they can pass a custom header (e.g. `X-Origin`).
422
421
  this.client = axios.create({
423
422
  baseURL: this.baseURL,
424
423
  timeout: config.timeout || 30000,
@@ -2066,6 +2065,24 @@ class SmoothSendSDK {
2066
2065
  }
2067
2066
  }
2068
2067
 
2068
+ /**
2069
+ * Pre-compiled Move script bytecode for add_permissioned_handle
2070
+ *
2071
+ * This bytecode is used to register session keys on-chain via the
2072
+ * `0x1::permissioned_delegation::add_permissioned_handle` function.
2073
+ *
2074
+ * The function cannot be called as an entry function directly — only via a Move script.
2075
+ * This bytecode handles:
2076
+ * - Takes the session public key bytes (vector<u8>) as input
2077
+ * - Constructs DelegationKey from the bytes
2078
+ * - Passes option::none() for rate limiter
2079
+ * - Hardcodes u64::MAX for expiration (on-chain handle never expires)
2080
+ *
2081
+ * Source: aptos-labs/aptos-ts-sdk tests/e2e/transaction/helper.ts
2082
+ */
2083
+ const ADD_PERMISSIONED_HANDLE_BYTECODE = 'a11ceb0b0700000a0801001002101603262c04520405563d079301d70208ea034010aa041f0103010401060109010d010e011201140002080002080700030b0700040c0f0005100701000001050301010001020704050001030a05060001050f01080100010311090a000106130b01000107150b0100010002030702060c0a020001080001060c010a02010801010802010803010b0401090004060c08020b0401080303010c03060c060c03050802030b04010803060c0c083c53454c463e5f30046d61696e094170746f73436f696e0a6170746f735f636f696e04636f696e196d6967726174655f746f5f66756e6769626c655f73746f72650765643235353139256e65775f756e76616c6964617465645f7075626c69635f6b65795f66726f6d5f627974657314556e76616c6964617465645075626c69634b657917' +
2084
+ '7065726d697373696f6e65645f64656c65676174696f6e0f67656e5f656432353531395f6b65790d44656c65676174696f6e4b65790b526174654c696d697465720c726174655f6c696d69746572066f7074696f6e046e6f6e65064f7074696f6e176164645f7065726d697373696f6e65645f68616e646c65167072696d6172795f66756e6769626c655f73746f7265146772616e745f6170745f7065726d697373696f6e167472616e73616374696f6e5f76616c69646174696f6e146772616e745f6761735f7065726d697373696f6effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000114636f6d70696c6174696f6e5f6d65746164617461090003322e3003322e3100000c170a0038000b01110111020c020a0038010c040b020b040600a0724e1809000011040c060a000e060600e1f5050000000011050b000e060600e1f50500000000110602';
2085
+
2069
2086
  /**
2070
2087
  * SmoothSend Transaction Submitter
2071
2088
  *
@@ -2103,6 +2120,7 @@ class SmoothSendSDK {
2103
2120
  */
2104
2121
  class SmoothSendTransactionSubmitter {
2105
2122
  constructor(config) {
2123
+ this._session = null;
2106
2124
  this.sponsoredFunctionsCache = null;
2107
2125
  this.sponsoredFunctionsCacheAt = 0;
2108
2126
  this.SPONSORED_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
@@ -2127,7 +2145,177 @@ class SmoothSendTransactionSubmitter {
2127
2145
  this.timeout = config.timeout || 30000;
2128
2146
  this.getCaptchaToken = config.getCaptchaToken;
2129
2147
  this.debug = config.debug || false;
2148
+ this.sessionEnabled = config.session || false;
2149
+ this.sessionDuration = config.sessionDuration || '24h';
2150
+ }
2151
+ // ─── Session key methods ────────────────────────────────────────────────────
2152
+ /**
2153
+ * Whether a valid session is currently active.
2154
+ */
2155
+ hasSession() {
2156
+ return this._session !== null && Date.now() < this._session.expiresAtMs;
2157
+ }
2158
+ /**
2159
+ * Create a session key for the given master account.
2160
+ * Called once by useSmoothSend when session: true and no session exists.
2161
+ * SmoothSend pays gas for the setup transaction.
2162
+ *
2163
+ * @param masterAccount - The user's wallet account (from wallet adapter)
2164
+ */
2165
+ async createSession(masterAccount) {
2166
+ const network = this.network === 'mainnet' ? tsSdk.Network.MAINNET : tsSdk.Network.TESTNET;
2167
+ const aptosClient = new tsSdk.Aptos(new tsSdk.AptosConfig({ network }));
2168
+ // Generate fresh in-memory session keypair
2169
+ const sessionAccount = tsSdk.Account.generate();
2170
+ const expiresAtMs = Date.now() + this._parseDuration(this.sessionDuration);
2171
+ // Step 1: Register session key on-chain via pre-compiled Move script
2172
+ const setupTx = await aptosClient.transaction.build.simple({
2173
+ sender: masterAccount.accountAddress,
2174
+ withFeePayer: true,
2175
+ data: {
2176
+ bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
2177
+ functionArguments: [tsSdk.MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
2178
+ },
2179
+ options: {
2180
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2181
+ },
2182
+ });
2183
+ const senderAuth = await this.signSenderAuthenticator(masterAccount, setupTx, aptosClient);
2184
+ const setupResult = await this.submitTransaction({
2185
+ aptosConfig: aptosClient.config,
2186
+ transaction: setupTx,
2187
+ senderAuthenticator: senderAuth,
2188
+ });
2189
+ await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
2190
+ if (this.debug) {
2191
+ console.log('[SmoothSend] Session key registered on-chain:', setupResult.hash);
2192
+ }
2193
+ // Step 2: Enable account abstraction (idempotent — skip if already on)
2194
+ const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
2195
+ accountAddress: masterAccount.accountAddress,
2196
+ authenticationFunction: '0x1::permissioned_delegation::authenticate',
2197
+ });
2198
+ if (!aaEnabled) {
2199
+ const aaTx = await aptosClient.transaction.build.simple({
2200
+ sender: masterAccount.accountAddress,
2201
+ withFeePayer: true,
2202
+ data: {
2203
+ function: '0x1::account_abstraction::add_authentication_function',
2204
+ functionArguments: [
2205
+ tsSdk.AccountAddress.fromString('0x1'),
2206
+ 'permissioned_delegation',
2207
+ 'authenticate',
2208
+ ],
2209
+ },
2210
+ options: {
2211
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2212
+ },
2213
+ });
2214
+ const aaAuth = await this.signSenderAuthenticator(masterAccount, aaTx, aptosClient);
2215
+ const aaResult = await this.submitTransaction({
2216
+ aptosConfig: aptosClient.config,
2217
+ transaction: aaTx,
2218
+ senderAuthenticator: aaAuth,
2219
+ });
2220
+ await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
2221
+ if (this.debug) {
2222
+ console.log('[SmoothSend] Account abstraction enabled:', aaResult.hash);
2223
+ }
2224
+ }
2225
+ // Build AbstractedAccount — signs future txs with session key,
2226
+ // sender on-chain = master address, chain validates via permissioned_delegation
2227
+ const abstractedAccount = tsSdk.AbstractedAccount.fromPermissionedSigner({
2228
+ signer: sessionAccount,
2229
+ accountAddress: masterAccount.accountAddress,
2230
+ });
2231
+ this._session = {
2232
+ sessionAccount,
2233
+ abstractedAccount,
2234
+ masterAddress: masterAccount.accountAddress,
2235
+ expiresAtMs,
2236
+ aptosClient,
2237
+ };
2238
+ }
2239
+ async isPermissionedSignerEnabled(aptosClient) {
2240
+ try {
2241
+ const result = await aptosClient.view({
2242
+ payload: {
2243
+ function: '0x1::features::is_permissioned_signer_enabled',
2244
+ functionArguments: [],
2245
+ },
2246
+ });
2247
+ return Array.isArray(result) && result[0] === true;
2248
+ }
2249
+ catch (error) {
2250
+ if (this.debug) {
2251
+ console.warn('[SmoothSend] Failed to probe permissioned signer feature:', error);
2252
+ }
2253
+ return false;
2254
+ }
2255
+ }
2256
+ async signSenderAuthenticator(signer, transaction, aptosClient) {
2257
+ const walletLikeSigner = signer;
2258
+ // Wallet-adapter compatible path (returns { authenticator, rawTransaction } in v8)
2259
+ if (typeof walletLikeSigner?.signTransactionWithAuthenticator === 'function') {
2260
+ const result = await walletLikeSigner.signTransactionWithAuthenticator(transaction);
2261
+ return (result?.authenticator ?? result);
2262
+ }
2263
+ // Native ts-sdk account path
2264
+ return aptosClient.transaction.sign({
2265
+ signer,
2266
+ transaction,
2267
+ });
2268
+ }
2269
+ /**
2270
+ * Submit a transaction using the active session key — no wallet popup.
2271
+ * Called by useSmoothSend after session is established.
2272
+ */
2273
+ async submitWithSession(functionName, functionArguments = [], typeArguments = []) {
2274
+ if (!this._session || !this.hasSession()) {
2275
+ throw new Error('[SmoothSend] No active session. Call createSession() first.');
2276
+ }
2277
+ const { abstractedAccount, masterAddress, aptosClient } = this._session;
2278
+ const tx = await aptosClient.transaction.build.simple({
2279
+ sender: masterAddress,
2280
+ withFeePayer: true,
2281
+ data: {
2282
+ function: functionName,
2283
+ functionArguments,
2284
+ ...(typeArguments.length > 0 ? { typeArguments } : {}),
2285
+ },
2286
+ options: {
2287
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2288
+ },
2289
+ });
2290
+ const senderAuth = aptosClient.transaction.sign({
2291
+ signer: abstractedAccount,
2292
+ transaction: tx,
2293
+ });
2294
+ return this.submitTransaction({
2295
+ aptosConfig: aptosClient.config,
2296
+ transaction: tx,
2297
+ senderAuthenticator: senderAuth,
2298
+ });
2130
2299
  }
2300
+ _parseDuration(duration) {
2301
+ if (duration === 'never') {
2302
+ // Client-side "never expires" mode; on-chain handle already uses u64::MAX.
2303
+ return Number.MAX_SAFE_INTEGER;
2304
+ }
2305
+ const n = parseInt(duration, 10);
2306
+ if (isNaN(n))
2307
+ throw new Error(`Invalid sessionDuration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
2308
+ if (duration.endsWith('s'))
2309
+ return n * 1000;
2310
+ if (duration.endsWith('m'))
2311
+ return n * 60 * 1000;
2312
+ if (duration.endsWith('h'))
2313
+ return n * 3600 * 1000;
2314
+ if (duration.endsWith('d'))
2315
+ return n * 86400 * 1000;
2316
+ throw new Error(`Unknown unit in "${duration}". Supported: s, m, h, d, or "never".`);
2317
+ }
2318
+ // ─── Transaction submission ──────────────────────────────────────────────────
2131
2319
  /**
2132
2320
  * Submit a transaction through SmoothSend's gasless relayer
2133
2321
  *
@@ -2335,6 +2523,10 @@ function createSmoothSendSubmitter(apiKey, options) {
2335
2523
  * - Function in allowlist → fee-payer gasless path via SmoothSend
2336
2524
  * - Function not in allowlist → regular wallet submission (user pays gas)
2337
2525
  *
2526
+ * When submitter has session: true, the first transaction triggers a one-time
2527
+ * wallet sign to register a session key on-chain. Every transaction after that
2528
+ * is signed silently — zero wallet popups.
2529
+ *
2338
2530
  * Requires: react >=17, @aptos-labs/wallet-adapter-react >=3, @aptos-labs/ts-sdk >=1
2339
2531
  *
2340
2532
  * @example
@@ -2346,13 +2538,11 @@ function createSmoothSendSubmitter(apiKey, options) {
2346
2538
  * await signAndSubmitTransaction({ data: { function: '0x1::coin::transfer', functionArguments: [to, amount] } });
2347
2539
  * ```
2348
2540
  */
2349
- /**
2350
- * useSmoothSend
2351
- *
2352
- * @param submitter - A SmoothSendTransactionSubmitter instance (created once, e.g. at module scope)
2353
- */
2354
2541
  function useSmoothSend(submitter) {
2355
2542
  const { account, signTransaction, signAndSubmitTransaction: walletSignAndSubmit, } = walletAdapterReact.useWallet();
2543
+ // Track session state reactively so UI updates when session is created/expires
2544
+ const initialHasSession = submitter?.hasSession?.() ?? false;
2545
+ const [hasSessionState, setHasSessionState] = react.useState(initialHasSession);
2356
2546
  // Prefetch the sponsored-functions list on mount so the first transaction
2357
2547
  // benefits from an already-populated cache with no added latency.
2358
2548
  react.useEffect(() => {
@@ -2360,11 +2550,85 @@ function useSmoothSend(submitter) {
2360
2550
  // Fail-open: getSponsoredFunctions already handles errors internally
2361
2551
  });
2362
2552
  }, [submitter]);
2553
+ react.useEffect(() => {
2554
+ if (!submitter)
2555
+ return;
2556
+ const refresh = () => {
2557
+ const hasSession = submitter.hasSession?.() ?? false;
2558
+ setHasSessionState(hasSession);
2559
+ };
2560
+ refresh();
2561
+ const timer = setInterval(refresh, 1000);
2562
+ return () => clearInterval(timer);
2563
+ }, [submitter]);
2363
2564
  const signAndSubmitTransaction = react.useCallback(async (input) => {
2364
2565
  if (!account?.address) {
2365
2566
  throw new Error('[SmoothSend] Wallet not connected');
2366
2567
  }
2367
2568
  const functionName = input?.data?.function ?? '';
2569
+ console.log('[SmoothSend] signAndSubmitTransaction called:', {
2570
+ functionName,
2571
+ sessionEnabled: submitter.sessionEnabled,
2572
+ hasSession: submitter.hasSession(),
2573
+ });
2574
+ // ── Session key path ────────────────────────────────────────────────────
2575
+ // When session: true, bypass wallet signing entirely after first setup.
2576
+ // Still respects the per-function allowlist — non-sponsored functions
2577
+ // fall through to regular wallet submission (user pays gas).
2578
+ if (submitter.sessionEnabled) {
2579
+ console.log('[SmoothSend] Session mode enabled');
2580
+ // Check allowlist first — no point setting up a session for a non-sponsored function
2581
+ const canGoGasless = typeof signTransaction === 'function';
2582
+ const sponsored = canGoGasless && (await submitter.isSponsored(functionName));
2583
+ console.log('[SmoothSend] Sponsored check:', { sponsored, canGoGasless });
2584
+ if (sponsored) {
2585
+ // If no active session, do the one-time setup
2586
+ if (!submitter.hasSession()) {
2587
+ console.log('[SmoothSend] No session, creating one...');
2588
+ if (!signTransaction) {
2589
+ console.warn('[SmoothSend] session: true requires signTransaction support. Falling back to regular submission.');
2590
+ }
2591
+ else {
2592
+ try {
2593
+ // Adapter object only needs accountAddress + signTransactionWithAuthenticator.
2594
+ // The submitter handles both wallet-adapter and native signer shapes.
2595
+ const walletAccount = {
2596
+ accountAddress: account.address,
2597
+ signTransactionWithAuthenticator: async (tx) => {
2598
+ const rawResult = await signTransaction({
2599
+ transactionOrPayload: tx,
2600
+ asFeePayer: false,
2601
+ });
2602
+ return rawResult?.authenticator ?? rawResult;
2603
+ },
2604
+ };
2605
+ await submitter.createSession(walletAccount);
2606
+ console.log('[SmoothSend] Session created successfully');
2607
+ setHasSessionState(submitter.hasSession?.() ?? false);
2608
+ }
2609
+ catch (err) {
2610
+ console.warn('[SmoothSend] Session setup failed, falling back to regular gasless:', err.message);
2611
+ // Fall through to normal gasless path below
2612
+ }
2613
+ }
2614
+ }
2615
+ // If session is now active, submit silently — no wallet popup
2616
+ if (submitter.hasSession()) {
2617
+ console.log('[SmoothSend] Session is active, using submitWithSession');
2618
+ try {
2619
+ return await submitter.submitWithSession(functionName, input.data?.functionArguments ?? [], input.data?.typeArguments ?? []);
2620
+ }
2621
+ catch (err) {
2622
+ // Session may have expired mid-flight — clear it and fall through
2623
+ console.warn('[SmoothSend] Session submit failed, will re-auth on next call:', err.message);
2624
+ setHasSessionState(false);
2625
+ // Fall through to regular gasless path for this call
2626
+ }
2627
+ }
2628
+ }
2629
+ // Non-sponsored function → fall through to walletSignAndSubmit below
2630
+ }
2631
+ // ── Regular gasless path (TransactionSubmitter) ─────────────────────────
2368
2632
  // signTransaction (sign-only) must be available for the gasless path.
2369
2633
  // Most modern wallets (Petra, Nightly) support it. If absent, fall through.
2370
2634
  const canGoGasless = typeof signTransaction === 'function';
@@ -2374,11 +2638,16 @@ function useSmoothSend(submitter) {
2374
2638
  const config = submitter.getConfig();
2375
2639
  const network = config.network === 'mainnet' ? tsSdk.Network.MAINNET : tsSdk.Network.TESTNET;
2376
2640
  const aptos = new tsSdk.Aptos(new tsSdk.AptosConfig({ network }));
2377
- // Build transaction with fee-payer placeholder (AccountAddress.ZERO)
2641
+ // Build transaction with fee-payer placeholder (AccountAddress.ZERO).
2642
+ // replayProtectionNonce (AIP-123): random nonce instead of sequence number
2643
+ // so concurrent gasless calls from many users never conflict.
2378
2644
  const transaction = await aptos.transaction.build.simple({
2379
2645
  sender: account.address.toString(),
2380
2646
  data: input.data,
2381
- options: input.options,
2647
+ options: {
2648
+ ...input.options,
2649
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2650
+ },
2382
2651
  withFeePayer: true,
2383
2652
  });
2384
2653
  // Wallet signs sender portion only (no gas required from user).
@@ -2415,7 +2684,228 @@ function useSmoothSend(submitter) {
2415
2684
  // Not sponsored or signTransaction unavailable → regular wallet submission
2416
2685
  return walletSignAndSubmit(input);
2417
2686
  }, [account, signTransaction, walletSignAndSubmit, submitter]);
2418
- return { signAndSubmitTransaction };
2687
+ return {
2688
+ signAndSubmitTransaction,
2689
+ hasSession: hasSessionState,
2690
+ };
2691
+ }
2692
+
2693
+ // ─── helpers ────────────────────────────────────────────────────────────────
2694
+ function parseDurationToSeconds(duration) {
2695
+ if (duration === 'never') {
2696
+ // Client-side "never expires" mode; on-chain handle already uses u64::MAX.
2697
+ return Math.floor(Number.MAX_SAFE_INTEGER / 1000);
2698
+ }
2699
+ const n = parseInt(duration, 10);
2700
+ if (isNaN(n))
2701
+ throw new Error(`Invalid duration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
2702
+ if (duration.endsWith('s'))
2703
+ return n;
2704
+ if (duration.endsWith('m'))
2705
+ return n * 60;
2706
+ if (duration.endsWith('h'))
2707
+ return n * 3600;
2708
+ if (duration.endsWith('d'))
2709
+ return n * 86400;
2710
+ throw new Error(`Unknown duration unit in "${duration}". Supported: s, m, h, d, or "never".`);
2711
+ }
2712
+ // ─── SmoothSendSession ───────────────────────────────────────────────────────
2713
+ /**
2714
+ * A session that lets your app submit transactions on behalf of a user
2715
+ * without any wallet popup after the initial one-time setup.
2716
+ *
2717
+ * Uses Aptos AIP-103 Permissioned Signers — authorization is enforced
2718
+ * on-chain by `0x1::permissioned_delegation`. No custom Move contract needed.
2719
+ *
2720
+ * @example
2721
+ * // 1. One-time setup (user signs once — can be keyless/Google login)
2722
+ * const session = await SmoothSendSession.create({
2723
+ * signer: keylessAccount,
2724
+ * expiresIn: '24h',
2725
+ * }, submitter)
2726
+ *
2727
+ * // 2. Every action after — zero popups, zero gas
2728
+ * await session.submit('0xgame::player::move', ['north'])
2729
+ * await session.submit('0xgame::player::attack', [enemyId])
2730
+ */
2731
+ class SmoothSendSession {
2732
+ constructor(args) {
2733
+ this.sessionAccount = args.sessionAccount;
2734
+ this.abstractedAccount = args.abstractedAccount;
2735
+ this.masterAddress = args.masterAddress;
2736
+ this.expiresAtMs = args.expiresAtMs;
2737
+ this.submitter = args.submitter;
2738
+ this.aptosClient = args.aptosClient;
2739
+ this._network = args.network;
2740
+ }
2741
+ /**
2742
+ * Create a new session.
2743
+ *
2744
+ * Registers the session key on-chain via
2745
+ * `0x1::permissioned_delegation::add_permissioned_handle`.
2746
+ * SmoothSend pays the gas for this setup transaction too.
2747
+ *
2748
+ * After this returns, the user never needs to approve anything again
2749
+ * until the session expires or is revoked.
2750
+ */
2751
+ static async create(options, submitter) {
2752
+ // Resolve network from options or submitter config
2753
+ const network = options.network ?? submitter.getConfig().network ?? 'testnet';
2754
+ const aptosNetwork = network === 'mainnet' ? tsSdk.Network.MAINNET : tsSdk.Network.TESTNET;
2755
+ const aptosClient = new tsSdk.Aptos(new tsSdk.AptosConfig({ network: aptosNetwork }));
2756
+ const feature = await aptosClient.view({
2757
+ payload: {
2758
+ function: '0x1::features::is_permissioned_signer_enabled',
2759
+ functionArguments: [],
2760
+ },
2761
+ }).catch(() => [false]);
2762
+ if (!Array.isArray(feature) || feature[0] !== true) {
2763
+ throw new Error('[SmoothSend] Session keys unavailable on this network (permissioned signer feature disabled).');
2764
+ }
2765
+ // Generate a fresh Ed25519 session keypair (lives in memory, never persisted)
2766
+ const sessionAccount = tsSdk.Account.generate();
2767
+ // Client-side expiry tracking (the bytecode script doesn't take an expiry arg)
2768
+ const nowSecs = Math.floor(Date.now() / 1000);
2769
+ const expirationTimeSecs = nowSecs + parseDurationToSeconds(options.expiresIn);
2770
+ // Step 1: Register the session key on-chain via a pre-compiled Move script.
2771
+ // add_permissioned_handle is NOT an entry function — only callable from a Move script.
2772
+ // Must happen BEFORE enabling account abstraction.
2773
+ const setupTx = await aptosClient.transaction.build.simple({
2774
+ sender: options.signer.accountAddress,
2775
+ withFeePayer: true,
2776
+ data: {
2777
+ bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
2778
+ functionArguments: [tsSdk.MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
2779
+ },
2780
+ options: {
2781
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2782
+ },
2783
+ });
2784
+ const senderAuth = aptosClient.transaction.sign({
2785
+ signer: options.signer,
2786
+ transaction: setupTx,
2787
+ });
2788
+ const setupResult = await submitter.submitTransaction({
2789
+ aptosConfig: aptosClient.config,
2790
+ transaction: setupTx,
2791
+ senderAuthenticator: senderAuth,
2792
+ });
2793
+ await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
2794
+ // Step 2: Enable account abstraction — tells the chain to use
2795
+ // 0x1::permissioned_delegation::authenticate for this account.
2796
+ // Idempotent — skip if already enabled.
2797
+ const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
2798
+ accountAddress: options.signer.accountAddress,
2799
+ authenticationFunction: '0x1::permissioned_delegation::authenticate',
2800
+ });
2801
+ if (!aaEnabled) {
2802
+ const aaTx = await aptosClient.transaction.build.simple({
2803
+ sender: options.signer.accountAddress,
2804
+ withFeePayer: true,
2805
+ data: {
2806
+ function: '0x1::account_abstraction::add_authentication_function',
2807
+ functionArguments: [
2808
+ tsSdk.AccountAddress.fromString('0x1'),
2809
+ 'permissioned_delegation',
2810
+ 'authenticate',
2811
+ ],
2812
+ },
2813
+ });
2814
+ const aaAuth = aptosClient.transaction.sign({ signer: options.signer, transaction: aaTx });
2815
+ const aaResult = await submitter.submitTransaction({
2816
+ aptosConfig: aptosClient.config,
2817
+ transaction: aaTx,
2818
+ senderAuthenticator: aaAuth,
2819
+ });
2820
+ await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
2821
+ }
2822
+ // Build AbstractedAccount — signs future txs with session key but
2823
+ // sender on-chain = master address. Chain validates via permissioned_delegation.
2824
+ const abstractedAccount = tsSdk.AbstractedAccount.fromPermissionedSigner({
2825
+ signer: sessionAccount,
2826
+ accountAddress: options.signer.accountAddress,
2827
+ });
2828
+ return new SmoothSendSession({
2829
+ sessionAccount,
2830
+ abstractedAccount,
2831
+ masterAddress: options.signer.accountAddress,
2832
+ expiresAtMs: expirationTimeSecs * 1000,
2833
+ submitter,
2834
+ aptosClient,
2835
+ network,
2836
+ });
2837
+ }
2838
+ /**
2839
+ * Submit a transaction silently — no wallet popup, zero gas.
2840
+ *
2841
+ * The transaction sender on-chain is still the user's main address.
2842
+ * The session key signs it, and `permissioned_delegation::authenticate`
2843
+ * validates the authorization at the VM level.
2844
+ *
2845
+ * @param functionName Full Move function identifier e.g. '0xgame::player::move'
2846
+ * @param functionArguments Arguments matching the Move function signature
2847
+ * @param typeArguments Optional type arguments for generic functions
2848
+ *
2849
+ * @example
2850
+ * await session.submit('0xgame::player::move', ['north'])
2851
+ * await session.submit('0x1::coin::transfer', [recipientAddr, 1000000n])
2852
+ */
2853
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2854
+ async submit(functionName, functionArguments = [], typeArguments = []) {
2855
+ if (!this.isValid()) {
2856
+ throw new Error(`Session expired at ${new Date(this.expiresAtMs).toISOString()}. ` +
2857
+ `Call SmoothSendSession.create() to start a new session.`);
2858
+ }
2859
+ // replayProtectionNonce: orderless transaction (AIP-123).
2860
+ // Lets users submit multiple session.submit() calls in parallel without
2861
+ // sequence number conflicts — critical for games, agents, rapid-fire actions.
2862
+ const tx = await this.aptosClient.transaction.build.simple({
2863
+ sender: this.masterAddress,
2864
+ withFeePayer: true,
2865
+ data: {
2866
+ function: functionName,
2867
+ functionArguments,
2868
+ ...(typeArguments.length > 0 ? { typeArguments } : {}),
2869
+ },
2870
+ options: {
2871
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2872
+ },
2873
+ });
2874
+ // Session key signs on behalf of master address
2875
+ const senderAuth = this.aptosClient.transaction.sign({
2876
+ signer: this.abstractedAccount,
2877
+ transaction: tx,
2878
+ });
2879
+ const result = await this.submitter.submitTransaction({
2880
+ aptosConfig: this.aptosClient.config,
2881
+ transaction: tx,
2882
+ senderAuthenticator: senderAuth,
2883
+ });
2884
+ return { hash: result.hash };
2885
+ }
2886
+ /**
2887
+ * Whether this session is still valid (not yet expired).
2888
+ */
2889
+ isValid() {
2890
+ return Date.now() < this.expiresAtMs;
2891
+ }
2892
+ /**
2893
+ * Milliseconds until this session expires. Returns 0 if already expired.
2894
+ */
2895
+ expiresInMs() {
2896
+ return Math.max(0, this.expiresAtMs - Date.now());
2897
+ }
2898
+ /**
2899
+ * Session metadata — useful for display or debugging.
2900
+ */
2901
+ get info() {
2902
+ return {
2903
+ masterAddress: this.masterAddress.toString(),
2904
+ sessionKeyAddress: this.sessionAccount.accountAddress.toString(),
2905
+ expiresAt: this.expiresAtMs,
2906
+ network: this._network,
2907
+ };
2908
+ }
2419
2909
  }
2420
2910
 
2421
2911
  /**
@@ -2668,6 +3158,134 @@ function createScriptComposerClient(config) {
2668
3158
  return new ScriptComposerClient(config);
2669
3159
  }
2670
3160
 
3161
+ /**
3162
+ * True Gasless Client
3163
+ *
3164
+ * Designed for server-side (backend) environments to securely build, sign,
3165
+ * and submit 100% sponsored gasless transactions using a Secret Key.
3166
+ *
3167
+ * @example
3168
+ * ```typescript
3169
+ * import { TrueGaslessClient } from '@smoothsend/sdk';
3170
+ * import { Account } from '@aptos-labs/ts-sdk';
3171
+ *
3172
+ * const backendWallet = Account.fromPrivateKey({ privateKey: '...' });
3173
+ * const client = new TrueGaslessClient({ apiKey: 'sk_nogas_...', network: 'mainnet' });
3174
+ *
3175
+ * const result = await client.execute({
3176
+ * senderAccount: backendWallet,
3177
+ * payload: {
3178
+ * function: "0x123::my_module::mint_nft",
3179
+ * functionArguments: []
3180
+ * }
3181
+ * });
3182
+ *
3183
+ * console.log("Gasless NFT Minted!", result.txHash);
3184
+ * ```
3185
+ */
3186
+ class TrueGaslessClient {
3187
+ constructor(config) {
3188
+ if (!config.apiKey) {
3189
+ throw new SmoothSendError('API key is required', 'MISSING_API_KEY', 400);
3190
+ }
3191
+ if (!config.apiKey.startsWith('sk_nogas_')) {
3192
+ console.warn('⚠️ WARNING: TrueGaslessClient is intended for backend use with a Secret Key (sk_nogas_*).\n' +
3193
+ 'Using a Public Key may result in CORS errors if ran in a browser environment.');
3194
+ }
3195
+ if (!config.network) {
3196
+ throw new SmoothSendError('Network is required (testnet or mainnet)', 'MISSING_NETWORK', 400);
3197
+ }
3198
+ this.config = {
3199
+ apiKey: config.apiKey,
3200
+ network: config.network,
3201
+ proxyUrl: config.proxyUrl,
3202
+ timeout: config.timeout || 30000,
3203
+ debug: config.debug || false,
3204
+ };
3205
+ this.httpClient = new HttpClient({
3206
+ apiKey: this.config.apiKey,
3207
+ network: this.config.network,
3208
+ timeout: this.config.timeout,
3209
+ retries: 3,
3210
+ includeOrigin: false, // Backend client should not send Origin header
3211
+ baseUrl: this.config.proxyUrl, // Use custom proxy URL if provided
3212
+ });
3213
+ const networkMap = {
3214
+ testnet: tsSdk.Network.TESTNET,
3215
+ mainnet: tsSdk.Network.MAINNET,
3216
+ };
3217
+ this.aptos = new tsSdk.Aptos(new tsSdk.AptosConfig({ network: networkMap[this.config.network] }));
3218
+ }
3219
+ log(message, data) {
3220
+ if (this.config.debug) {
3221
+ console.log(`[TrueGaslessClient] ${message}`, data || '');
3222
+ }
3223
+ }
3224
+ /**
3225
+ * Builds, signs (as sender), and relays an arbitrary payload for complete sponsorship.
3226
+ */
3227
+ async execute(params) {
3228
+ this.log('Starting gasless execution', { sender: params.senderAccount.accountAddress.toString(), payload: params.payload });
3229
+ if (!params.senderAccount || !params.payload) {
3230
+ throw new SmoothSendError('Missing required parameters: senderAccount and payload', 'INVALID_PARAMETERS', 400);
3231
+ }
3232
+ try {
3233
+ this.log('Building simple transaction with fee payer enabled');
3234
+ // Build the transaction and flag it requires a remote fee payer
3235
+ const transaction = await this.aptos.transaction.build.simple({
3236
+ sender: params.senderAccount.accountAddress,
3237
+ data: params.payload,
3238
+ withFeePayer: true,
3239
+ });
3240
+ this.log('Signing transaction locally with senderAccount');
3241
+ // Sign locally over the transaction hash
3242
+ const senderAuthenticator = this.aptos.transaction.sign({
3243
+ signer: params.senderAccount,
3244
+ transaction,
3245
+ });
3246
+ this.log('Serializing to bytes for relayer transmission');
3247
+ // Convert to BCS bytes expected by the proxy
3248
+ const transactionBytes = Array.from(transaction.bcsToBytes());
3249
+ const authenticatorBytes = Array.from(senderAuthenticator.bcsToBytes());
3250
+ this.log('Sending to relayer...');
3251
+ const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
3252
+ transactionBytes,
3253
+ authenticatorBytes,
3254
+ network: this.config.network,
3255
+ functionName: 'function' in params.payload ? params.payload.function : 'unknown',
3256
+ });
3257
+ this.log('Relayer submission successful', response.data);
3258
+ return {
3259
+ success: response.data.success ?? true,
3260
+ requestId: response.data.requestId,
3261
+ txHash: response.data.txnHash || response.data.txHash,
3262
+ gasUsed: response.data.gasUsed,
3263
+ vmStatus: response.data.vmStatus,
3264
+ sender: response.data.sender || params.senderAccount.accountAddress.toString(),
3265
+ };
3266
+ }
3267
+ catch (error) {
3268
+ this.log('Gasless execution failed', error);
3269
+ if (error instanceof SmoothSendError) {
3270
+ throw error;
3271
+ }
3272
+ throw new SmoothSendError(`Failed to execute gasless transaction: ${error.message}`, 'EXECUTION_FAILED', 500, { originalError: error.message });
3273
+ }
3274
+ }
3275
+ /**
3276
+ * Expose the core Aptos instance to allow backend developers to access chain state if needed
3277
+ */
3278
+ getAptosClient() {
3279
+ return this.aptos;
3280
+ }
3281
+ }
3282
+ /**
3283
+ * Helper to initialize TrueGaslessClient
3284
+ */
3285
+ function createTrueGaslessClient(config) {
3286
+ return new TrueGaslessClient(config);
3287
+ }
3288
+
2671
3289
  /**
2672
3290
  * SmoothSend SDK v2.0
2673
3291
  *
@@ -2699,7 +3317,7 @@ function createScriptComposerClient(config) {
2699
3317
  * SDK version
2700
3318
  * @public
2701
3319
  */
2702
- const VERSION = '2.1.3';
3320
+ const VERSION = '2.2.1';
2703
3321
 
2704
3322
  exports.APTOS_ERROR_CODES = APTOS_ERROR_CODES;
2705
3323
  exports.AptosAdapter = AptosAdapter;
@@ -2712,15 +3330,18 @@ exports.STELLAR_ERROR_CODES = STELLAR_ERROR_CODES;
2712
3330
  exports.ScriptComposerClient = ScriptComposerClient;
2713
3331
  exports.SmoothSendError = SmoothSendError;
2714
3332
  exports.SmoothSendSDK = SmoothSendSDK;
3333
+ exports.SmoothSendSession = SmoothSendSession;
2715
3334
  exports.SmoothSendTransactionSubmitter = SmoothSendTransactionSubmitter;
2716
3335
  exports.StellarAdapter = StellarAdapter;
2717
3336
  exports.StellarCAddressAdapter = StellarCAddressAdapter;
3337
+ exports.TrueGaslessClient = TrueGaslessClient;
2718
3338
  exports.VERSION = VERSION;
2719
3339
  exports.ValidationError = ValidationError;
2720
3340
  exports.createErrorFromResponse = createErrorFromResponse;
2721
3341
  exports.createNetworkError = createNetworkError;
2722
3342
  exports.createScriptComposerClient = createScriptComposerClient;
2723
3343
  exports.createSmoothSendSubmitter = createSmoothSendSubmitter;
3344
+ exports.createTrueGaslessClient = createTrueGaslessClient;
2724
3345
  exports.default = SmoothSendSDK;
2725
3346
  exports.useSmoothSend = useSmoothSend;
2726
3347
  //# sourceMappingURL=index.js.map