@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.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import axios from 'axios';
2
- import { useEffect, useCallback } from 'react';
2
+ import { Network, Aptos, AptosConfig, Account, MoveVector, AccountAddress, AbstractedAccount } from '@aptos-labs/ts-sdk';
3
+ import { useState, useEffect, useCallback } from 'react';
3
4
  import { useWallet } from '@aptos-labs/wallet-adapter-react';
4
- import { Network, Aptos, AptosConfig } from '@aptos-labs/ts-sdk';
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';
2126
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
+ });
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';
@@ -2370,11 +2634,16 @@ function useSmoothSend(submitter) {
2370
2634
  const config = submitter.getConfig();
2371
2635
  const network = config.network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2372
2636
  const aptos = new Aptos(new AptosConfig({ network }));
2373
- // Build transaction with fee-payer placeholder (AccountAddress.ZERO)
2637
+ // Build transaction with fee-payer placeholder (AccountAddress.ZERO).
2638
+ // replayProtectionNonce (AIP-123): random nonce instead of sequence number
2639
+ // so concurrent gasless calls from many users never conflict.
2374
2640
  const transaction = await aptos.transaction.build.simple({
2375
2641
  sender: account.address.toString(),
2376
2642
  data: input.data,
2377
- options: input.options,
2643
+ options: {
2644
+ ...input.options,
2645
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2646
+ },
2378
2647
  withFeePayer: true,
2379
2648
  });
2380
2649
  // Wallet signs sender portion only (no gas required from user).
@@ -2411,7 +2680,228 @@ function useSmoothSend(submitter) {
2411
2680
  // Not sponsored or signTransaction unavailable → regular wallet submission
2412
2681
  return walletSignAndSubmit(input);
2413
2682
  }, [account, signTransaction, walletSignAndSubmit, submitter]);
2414
- return { signAndSubmitTransaction };
2683
+ return {
2684
+ signAndSubmitTransaction,
2685
+ hasSession: hasSessionState,
2686
+ };
2687
+ }
2688
+
2689
+ // ─── helpers ────────────────────────────────────────────────────────────────
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
+ }
2695
+ const n = parseInt(duration, 10);
2696
+ if (isNaN(n))
2697
+ throw new Error(`Invalid duration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
2698
+ if (duration.endsWith('s'))
2699
+ return n;
2700
+ if (duration.endsWith('m'))
2701
+ return n * 60;
2702
+ if (duration.endsWith('h'))
2703
+ return n * 3600;
2704
+ if (duration.endsWith('d'))
2705
+ return n * 86400;
2706
+ throw new Error(`Unknown duration unit in "${duration}". Supported: s, m, h, d, or "never".`);
2707
+ }
2708
+ // ─── SmoothSendSession ───────────────────────────────────────────────────────
2709
+ /**
2710
+ * A session that lets your app submit transactions on behalf of a user
2711
+ * without any wallet popup after the initial one-time setup.
2712
+ *
2713
+ * Uses Aptos AIP-103 Permissioned Signers — authorization is enforced
2714
+ * on-chain by `0x1::permissioned_delegation`. No custom Move contract needed.
2715
+ *
2716
+ * @example
2717
+ * // 1. One-time setup (user signs once — can be keyless/Google login)
2718
+ * const session = await SmoothSendSession.create({
2719
+ * signer: keylessAccount,
2720
+ * expiresIn: '24h',
2721
+ * }, submitter)
2722
+ *
2723
+ * // 2. Every action after — zero popups, zero gas
2724
+ * await session.submit('0xgame::player::move', ['north'])
2725
+ * await session.submit('0xgame::player::attack', [enemyId])
2726
+ */
2727
+ class SmoothSendSession {
2728
+ constructor(args) {
2729
+ this.sessionAccount = args.sessionAccount;
2730
+ this.abstractedAccount = args.abstractedAccount;
2731
+ this.masterAddress = args.masterAddress;
2732
+ this.expiresAtMs = args.expiresAtMs;
2733
+ this.submitter = args.submitter;
2734
+ this.aptosClient = args.aptosClient;
2735
+ this._network = args.network;
2736
+ }
2737
+ /**
2738
+ * Create a new session.
2739
+ *
2740
+ * Registers the session key on-chain via
2741
+ * `0x1::permissioned_delegation::add_permissioned_handle`.
2742
+ * SmoothSend pays the gas for this setup transaction too.
2743
+ *
2744
+ * After this returns, the user never needs to approve anything again
2745
+ * until the session expires or is revoked.
2746
+ */
2747
+ static async create(options, submitter) {
2748
+ // Resolve network from options or submitter config
2749
+ const network = options.network ?? submitter.getConfig().network ?? 'testnet';
2750
+ const aptosNetwork = network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
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
+ }
2761
+ // Generate a fresh Ed25519 session keypair (lives in memory, never persisted)
2762
+ const sessionAccount = Account.generate();
2763
+ // Client-side expiry tracking (the bytecode script doesn't take an expiry arg)
2764
+ const nowSecs = Math.floor(Date.now() / 1000);
2765
+ const expirationTimeSecs = nowSecs + parseDurationToSeconds(options.expiresIn);
2766
+ // Step 1: Register the session key on-chain via a pre-compiled Move script.
2767
+ // add_permissioned_handle is NOT an entry function — only callable from a Move script.
2768
+ // Must happen BEFORE enabling account abstraction.
2769
+ const setupTx = await aptosClient.transaction.build.simple({
2770
+ sender: options.signer.accountAddress,
2771
+ withFeePayer: true,
2772
+ data: {
2773
+ bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
2774
+ functionArguments: [MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
2775
+ },
2776
+ options: {
2777
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2778
+ },
2779
+ });
2780
+ const senderAuth = aptosClient.transaction.sign({
2781
+ signer: options.signer,
2782
+ transaction: setupTx,
2783
+ });
2784
+ const setupResult = await submitter.submitTransaction({
2785
+ aptosConfig: aptosClient.config,
2786
+ transaction: setupTx,
2787
+ senderAuthenticator: senderAuth,
2788
+ });
2789
+ await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
2790
+ // Step 2: Enable account abstraction — tells the chain to use
2791
+ // 0x1::permissioned_delegation::authenticate for this account.
2792
+ // Idempotent — skip if already enabled.
2793
+ const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
2794
+ accountAddress: options.signer.accountAddress,
2795
+ authenticationFunction: '0x1::permissioned_delegation::authenticate',
2796
+ });
2797
+ if (!aaEnabled) {
2798
+ const aaTx = await aptosClient.transaction.build.simple({
2799
+ sender: options.signer.accountAddress,
2800
+ withFeePayer: true,
2801
+ data: {
2802
+ function: '0x1::account_abstraction::add_authentication_function',
2803
+ functionArguments: [
2804
+ AccountAddress.fromString('0x1'),
2805
+ 'permissioned_delegation',
2806
+ 'authenticate',
2807
+ ],
2808
+ },
2809
+ });
2810
+ const aaAuth = aptosClient.transaction.sign({ signer: options.signer, transaction: aaTx });
2811
+ const aaResult = await submitter.submitTransaction({
2812
+ aptosConfig: aptosClient.config,
2813
+ transaction: aaTx,
2814
+ senderAuthenticator: aaAuth,
2815
+ });
2816
+ await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
2817
+ }
2818
+ // Build AbstractedAccount — signs future txs with session key but
2819
+ // sender on-chain = master address. Chain validates via permissioned_delegation.
2820
+ const abstractedAccount = AbstractedAccount.fromPermissionedSigner({
2821
+ signer: sessionAccount,
2822
+ accountAddress: options.signer.accountAddress,
2823
+ });
2824
+ return new SmoothSendSession({
2825
+ sessionAccount,
2826
+ abstractedAccount,
2827
+ masterAddress: options.signer.accountAddress,
2828
+ expiresAtMs: expirationTimeSecs * 1000,
2829
+ submitter,
2830
+ aptosClient,
2831
+ network,
2832
+ });
2833
+ }
2834
+ /**
2835
+ * Submit a transaction silently — no wallet popup, zero gas.
2836
+ *
2837
+ * The transaction sender on-chain is still the user's main address.
2838
+ * The session key signs it, and `permissioned_delegation::authenticate`
2839
+ * validates the authorization at the VM level.
2840
+ *
2841
+ * @param functionName Full Move function identifier e.g. '0xgame::player::move'
2842
+ * @param functionArguments Arguments matching the Move function signature
2843
+ * @param typeArguments Optional type arguments for generic functions
2844
+ *
2845
+ * @example
2846
+ * await session.submit('0xgame::player::move', ['north'])
2847
+ * await session.submit('0x1::coin::transfer', [recipientAddr, 1000000n])
2848
+ */
2849
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2850
+ async submit(functionName, functionArguments = [], typeArguments = []) {
2851
+ if (!this.isValid()) {
2852
+ throw new Error(`Session expired at ${new Date(this.expiresAtMs).toISOString()}. ` +
2853
+ `Call SmoothSendSession.create() to start a new session.`);
2854
+ }
2855
+ // replayProtectionNonce: orderless transaction (AIP-123).
2856
+ // Lets users submit multiple session.submit() calls in parallel without
2857
+ // sequence number conflicts — critical for games, agents, rapid-fire actions.
2858
+ const tx = await this.aptosClient.transaction.build.simple({
2859
+ sender: this.masterAddress,
2860
+ withFeePayer: true,
2861
+ data: {
2862
+ function: functionName,
2863
+ functionArguments,
2864
+ ...(typeArguments.length > 0 ? { typeArguments } : {}),
2865
+ },
2866
+ options: {
2867
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2868
+ },
2869
+ });
2870
+ // Session key signs on behalf of master address
2871
+ const senderAuth = this.aptosClient.transaction.sign({
2872
+ signer: this.abstractedAccount,
2873
+ transaction: tx,
2874
+ });
2875
+ const result = await this.submitter.submitTransaction({
2876
+ aptosConfig: this.aptosClient.config,
2877
+ transaction: tx,
2878
+ senderAuthenticator: senderAuth,
2879
+ });
2880
+ return { hash: result.hash };
2881
+ }
2882
+ /**
2883
+ * Whether this session is still valid (not yet expired).
2884
+ */
2885
+ isValid() {
2886
+ return Date.now() < this.expiresAtMs;
2887
+ }
2888
+ /**
2889
+ * Milliseconds until this session expires. Returns 0 if already expired.
2890
+ */
2891
+ expiresInMs() {
2892
+ return Math.max(0, this.expiresAtMs - Date.now());
2893
+ }
2894
+ /**
2895
+ * Session metadata — useful for display or debugging.
2896
+ */
2897
+ get info() {
2898
+ return {
2899
+ masterAddress: this.masterAddress.toString(),
2900
+ sessionKeyAddress: this.sessionAccount.accountAddress.toString(),
2901
+ expiresAt: this.expiresAtMs,
2902
+ network: this._network,
2903
+ };
2904
+ }
2415
2905
  }
2416
2906
 
2417
2907
  /**
@@ -2664,6 +3154,134 @@ function createScriptComposerClient(config) {
2664
3154
  return new ScriptComposerClient(config);
2665
3155
  }
2666
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
+
2667
3285
  /**
2668
3286
  * SmoothSend SDK v2.0
2669
3287
  *
@@ -2695,7 +3313,7 @@ function createScriptComposerClient(config) {
2695
3313
  * SDK version
2696
3314
  * @public
2697
3315
  */
2698
- const VERSION = '2.1.3';
3316
+ const VERSION = '2.2.1';
2699
3317
 
2700
- export { APTOS_ERROR_CODES, AptosAdapter, AuthenticationError, CHAIN_ECOSYSTEM_MAP, HttpClient, NetworkError, RateLimitError, STELLAR_ERROR_CODES, ScriptComposerClient, SmoothSendError, SmoothSendSDK, 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 };
2701
3319
  //# sourceMappingURL=index.esm.js.map