@smoothsend/sdk 2.1.2 → 2.2.0

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/README.md CHANGED
@@ -21,9 +21,9 @@ Multi-chain gasless transaction SDK. Enable gas-free transactions with just 3 li
21
21
  npm install @smoothsend/sdk
22
22
  ```
23
23
 
24
- ## ⚡ Quick Start - Wallet Adapter (EASIEST - 3 Lines!)
24
+ ## ⚡ Quick Start - Wallet Adapter (EASIEST - All Transactions Gasless)
25
25
 
26
- The easiest way to integrate SmoothSend is using the Wallet Adapter integration. Just add 3 lines of code and ALL your transactions become gasless automatically!
26
+ The simplest integration — pass `transactionSubmitter` to your wallet provider and **every transaction becomes gasless automatically**. Ideal when you want to sponsor all functions.
27
27
 
28
28
  ```typescript
29
29
  import { SmoothSendTransactionSubmitter } from '@smoothsend/sdk';
@@ -53,7 +53,7 @@ function App() {
53
53
  // 3. Use normal wallet functions - they're now gasless!
54
54
  function TransferButton() {
55
55
  const { signAndSubmitTransaction } = useWallet();
56
-
56
+
57
57
  const handleTransfer = async () => {
58
58
  // This is now gasless! No code changes needed!
59
59
  const result = await signAndSubmitTransaction({
@@ -65,12 +65,58 @@ function TransferButton() {
65
65
  });
66
66
  console.log('Gasless transaction:', result.hash);
67
67
  };
68
-
68
+
69
69
  return <button onClick={handleTransfer}>Send (Gasless!)</button>;
70
70
  }
71
71
  ```
72
72
 
73
- **That's it!** All transactions in your app are now gasless. Users don't need APT for gas fees!
73
+ ---
74
+
75
+ ## 🎯 useSmoothSend Hook (Per-Function Routing)
76
+
77
+ Use `useSmoothSend` when you want **some functions gasless and others not** — for example, free to create but user pays to delete. The hook automatically routes each transaction based on your project's sponsored-functions allowlist configured in the dashboard.
78
+
79
+ ```typescript
80
+ import { useSmoothSend, SmoothSendTransactionSubmitter } from '@smoothsend/sdk';
81
+
82
+ // Create once at module scope (not inside the component)
83
+ const submitter = new SmoothSendTransactionSubmitter({
84
+ apiKey: process.env.NEXT_PUBLIC_SMOOTHSEND_API_KEY!,
85
+ network: 'testnet',
86
+ });
87
+
88
+ function MyComponent() {
89
+ // Drop-in replacement for useWallet().signAndSubmitTransaction
90
+ const { signAndSubmitTransaction } = useSmoothSend(submitter);
91
+
92
+ const handleAction = async () => {
93
+ // Automatically routed:
94
+ // function in allowlist → fee-payer gasless (user pays 0 gas)
95
+ // function not in list → walletSignAndSubmit fallback (user pays gas)
96
+ await signAndSubmitTransaction({
97
+ data: {
98
+ function: '0xABC::mymodule::my_function',
99
+ functionArguments: [arg1, arg2],
100
+ }
101
+ });
102
+ };
103
+ }
104
+ ```
105
+
106
+ **Requirements for `useSmoothSend`:**
107
+ - `react >= 17`
108
+ - `@aptos-labs/wallet-adapter-react >= 8`
109
+ - `@aptos-labs/ts-sdk >= 5.0.0` ← required for `withFeePayer: true` support
110
+
111
+ **Do NOT use `transactionSubmitter` in `AptosWalletAdapterProvider`** when using `useSmoothSend` — the hook handles all routing directly.
112
+
113
+ ### When to use which
114
+
115
+ | Want to... | Use |
116
+ |---|---|
117
+ | Make ALL transactions gasless, zero config | `transactionSubmitter` in `AptosWalletAdapterProvider` |
118
+ | Sponsor only specific functions (allowlist) | `useSmoothSend(submitter)` hook |
119
+ | Mainnet free tier — deduct fee from token | `ScriptComposerClient` |
74
120
 
75
121
  ---
76
122
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AptosConfig, AnyRawTransaction, AccountAuthenticator, PendingTransactionResponse } from '@aptos-labs/ts-sdk';
1
+ import { AptosConfig, AnyRawTransaction, AccountAuthenticator, PendingTransactionResponse, Account } from '@aptos-labs/ts-sdk';
2
2
  import { AxiosRequestConfig } from 'axios';
3
3
 
4
4
  /**
@@ -1641,6 +1641,113 @@ interface UseSmoothSendResult {
1641
1641
  */
1642
1642
  declare function useSmoothSend(submitter: SmoothSendTransactionSubmitter): UseSmoothSendResult;
1643
1643
 
1644
+ interface CreateSessionOptions {
1645
+ /**
1646
+ * The master account that owns the Aptos address.
1647
+ * Can be a KeylessAccount (Google/Apple login), Ed25519Account, or any Account
1648
+ * that implements the Aptos Account interface.
1649
+ *
1650
+ * @example keylessAccount from aptos.deriveKeylessAccount(...)
1651
+ * @example Account.fromPrivateKey({ privateKey })
1652
+ */
1653
+ signer: Account;
1654
+ /**
1655
+ * How long the session should stay valid.
1656
+ * Format: number + unit (s = seconds, m = minutes, h = hours, d = days)
1657
+ * @example '2h' | '24h' | '7d'
1658
+ */
1659
+ expiresIn: string;
1660
+ /**
1661
+ * Network to use. Inferred from submitter if not provided.
1662
+ */
1663
+ network?: 'testnet' | 'mainnet';
1664
+ }
1665
+ interface SessionInfo {
1666
+ /** The user's main account address — sender for all transactions */
1667
+ masterAddress: string;
1668
+ /** The temporary session key address (for debugging / display) */
1669
+ sessionKeyAddress: string;
1670
+ /** When this session expires (Unix timestamp in ms) */
1671
+ expiresAt: number;
1672
+ /** Network this session operates on */
1673
+ network: 'testnet' | 'mainnet';
1674
+ }
1675
+ interface SubmitResult {
1676
+ hash: string;
1677
+ }
1678
+ /**
1679
+ * @experimental
1680
+ * Session keys require ACCOUNT_ABSTRACTION (feature 85) and PERMISSIONED_SIGNER (feature 84)
1681
+ * to be enabled on the Aptos network. As of now these features are only live on devnet/local node.
1682
+ * This will be fully released when the features are activated on testnet and mainnet.
1683
+ *
1684
+ * A session that lets your app submit transactions on behalf of a user
1685
+ * without any wallet popup after the initial one-time setup.
1686
+ *
1687
+ * Uses Aptos AIP-103 Permissioned Signers — authorization is enforced
1688
+ * on-chain by `0x1::permissioned_delegation`. No custom Move contract needed.
1689
+ *
1690
+ * @example
1691
+ * // 1. One-time setup (user signs once — can be keyless/Google login)
1692
+ * const session = await SmoothSendSession.create({
1693
+ * signer: keylessAccount,
1694
+ * expiresIn: '24h',
1695
+ * }, submitter)
1696
+ *
1697
+ * // 2. Every action after — zero popups, zero gas
1698
+ * await session.submit('0xgame::player::move', ['north'])
1699
+ * await session.submit('0xgame::player::attack', [enemyId])
1700
+ */
1701
+ declare class SmoothSendSession {
1702
+ private readonly sessionAccount;
1703
+ private readonly abstractedAccount;
1704
+ private readonly masterAddress;
1705
+ private readonly expiresAtMs;
1706
+ private readonly submitter;
1707
+ private readonly aptosClient;
1708
+ private readonly _network;
1709
+ private constructor();
1710
+ /**
1711
+ * Create a new session.
1712
+ *
1713
+ * Registers the session key on-chain via
1714
+ * `0x1::permissioned_delegation::add_permissioned_handle`.
1715
+ * SmoothSend pays the gas for this setup transaction too.
1716
+ *
1717
+ * After this returns, the user never needs to approve anything again
1718
+ * until the session expires or is revoked.
1719
+ */
1720
+ static create(options: CreateSessionOptions, submitter: SmoothSendTransactionSubmitter): Promise<SmoothSendSession>;
1721
+ /**
1722
+ * Submit a transaction silently — no wallet popup, zero gas.
1723
+ *
1724
+ * The transaction sender on-chain is still the user's main address.
1725
+ * The session key signs it, and `permissioned_delegation::authenticate`
1726
+ * validates the authorization at the VM level.
1727
+ *
1728
+ * @param functionName Full Move function identifier e.g. '0xgame::player::move'
1729
+ * @param functionArguments Arguments matching the Move function signature
1730
+ * @param typeArguments Optional type arguments for generic functions
1731
+ *
1732
+ * @example
1733
+ * await session.submit('0xgame::player::move', ['north'])
1734
+ * await session.submit('0x1::coin::transfer', [recipientAddr, 1000000n])
1735
+ */
1736
+ submit(functionName: `${string}::${string}::${string}`, functionArguments?: any[], typeArguments?: string[]): Promise<SubmitResult>;
1737
+ /**
1738
+ * Whether this session is still valid (not yet expired).
1739
+ */
1740
+ isValid(): boolean;
1741
+ /**
1742
+ * Milliseconds until this session expires. Returns 0 if already expired.
1743
+ */
1744
+ expiresInMs(): number;
1745
+ /**
1746
+ * Session metadata — useful for display or debugging.
1747
+ */
1748
+ get info(): SessionInfo;
1749
+ }
1750
+
1644
1751
  /**
1645
1752
  * Script Composer Client
1646
1753
  *
@@ -2315,7 +2422,7 @@ declare class StellarAdapter implements IChainAdapter {
2315
2422
  * SDK version
2316
2423
  * @public
2317
2424
  */
2318
- declare const VERSION = "2.1.2";
2425
+ declare const VERSION = "2.2.0";
2319
2426
 
2320
- 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 };
2321
- export type { ApiResponse, AptosErrorCode, AptosTransferData, AptosWallet, AvalancheTransferData, BatchRelayTransferRequest, BatchTransferRequest, BuildTransferParams, BuildTransferResult, CAddressBalance, CAddressBalanceResult, CAddressBuildTransferResult, CAddressCreateResult, CAddressHealthResult, CAddressHistoryResult, CAddressLookupResult, CAddressSubmitResult, CAddressTransaction, ChainConfig, ChainEcosystem, ChainInfo, DomainSeparatorResponse, EVMTransferData, ErrorResponse, EstimateGasRequest, EventListener, FeeEstimate, FeeEstimateResult, GasEstimateResponse, HealthResponse, IChainAdapter, PermitData, PrepareSignatureRequest, PrepareSignatureResponse, RelayTransferRequest, RelayTransferResponse, ScriptComposerConfig, SignatureData, SignedTransferData, SmoothSendConfig, SmoothSendTransactionSubmitterConfig, StellarWallet, SubmitSignedTransactionParams, SubmitTransactionResult, SuccessResponse, SupportedChain, TokenBalance, TokenInfo, TransactionSubmitter, TransferData, TransferEvent, TransferQuote, TransferQuoteRequest, TransferQuoteResponse, TransferRequest, TransferResult, TransferStatusResponse, UsageMetadata, UseSmoothSendResult };
2427
+ 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 };
2428
+ export type { ApiResponse, AptosErrorCode, AptosTransferData, AptosWallet, AvalancheTransferData, BatchRelayTransferRequest, BatchTransferRequest, BuildTransferParams, BuildTransferResult, CAddressBalance, CAddressBalanceResult, CAddressBuildTransferResult, CAddressCreateResult, CAddressHealthResult, CAddressHistoryResult, CAddressLookupResult, CAddressSubmitResult, CAddressTransaction, ChainConfig, ChainEcosystem, ChainInfo, CreateSessionOptions, DomainSeparatorResponse, EVMTransferData, ErrorResponse, EstimateGasRequest, EventListener, FeeEstimate, FeeEstimateResult, GasEstimateResponse, HealthResponse, IChainAdapter, PermitData, PrepareSignatureRequest, PrepareSignatureResponse, RelayTransferRequest, RelayTransferResponse, ScriptComposerConfig, SessionInfo, SignatureData, SignedTransferData, SmoothSendConfig, SmoothSendTransactionSubmitterConfig, StellarWallet, SubmitResult, SubmitSignedTransactionParams, SubmitTransactionResult, SuccessResponse, SupportedChain, TokenBalance, TokenInfo, TransactionSubmitter, TransferData, TransferEvent, TransferQuote, TransferQuoteRequest, TransferQuoteResponse, TransferRequest, TransferResult, TransferStatusResponse, UsageMetadata, UseSmoothSendResult };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIrD,OAAO,EACL,8BAA8B,EAC9B,yBAAyB,EACzB,KAAK,oCAAoC,EACzC,KAAK,oBAAoB,EACzB,aAAa,EACb,KAAK,mBAAmB,GACzB,MAAM,kBAAkB,CAAC;AAI1B,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAC1B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,6BAA6B,EAClC,KAAK,uBAAuB,EAC5B,KAAK,iBAAiB,GACvB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EACL,sBAAsB,EACtB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EAChC,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,GAC1B,MAAM,8BAA8B,CAAC;AAGtC,cAAc,SAAS,CAAC;AAGxB,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,OAAO,UAAU,CAAC;AAG/B,OAAO,EAAE,aAAa,IAAI,OAAO,EAAE,MAAM,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIrD,OAAO,EACL,8BAA8B,EAC9B,yBAAyB,EACzB,KAAK,oCAAoC,EACzC,KAAK,oBAAoB,EACzB,aAAa,EACb,KAAK,mBAAmB,GACzB,MAAM,kBAAkB,CAAC;AAI1B,OAAO,EACL,iBAAiB,EACjB,KAAK,oBAAoB,EACzB,KAAK,WAAW,EAChB,KAAK,YAAY,GAClB,MAAM,WAAW,CAAC;AAInB,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAC1B,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,6BAA6B,EAClC,KAAK,uBAAuB,EAC5B,KAAK,iBAAiB,GACvB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EACL,sBAAsB,EACtB,KAAK,oBAAoB,EACzB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EAChC,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,GAC1B,MAAM,8BAA8B,CAAC;AAGtC,cAAc,SAAS,CAAC;AAGxB,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,OAAO,UAAU,CAAC;AAG/B,OAAO,EAAE,aAAa,IAAI,OAAO,EAAE,MAAM,sBAAsB,CAAC"}
package/dist/index.esm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import axios from 'axios';
2
2
  import { useEffect, useCallback } from 'react';
3
3
  import { useWallet } from '@aptos-labs/wallet-adapter-react';
4
- import { Network, Aptos, AptosConfig } from '@aptos-labs/ts-sdk';
4
+ import { Network, Aptos, AptosConfig, Account, MoveVector, AccountAddress, AbstractedAccount } from '@aptos-labs/ts-sdk';
5
5
 
6
6
  /**
7
7
  * Error handling system for SmoothSend SDK v2
@@ -2370,17 +2370,29 @@ function useSmoothSend(submitter) {
2370
2370
  const config = submitter.getConfig();
2371
2371
  const network = config.network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2372
2372
  const aptos = new Aptos(new AptosConfig({ network }));
2373
- // Build transaction with fee-payer placeholder (AccountAddress.ZERO)
2373
+ // Build transaction with fee-payer placeholder (AccountAddress.ZERO).
2374
+ // replayProtectionNonce (AIP-123): random nonce instead of sequence number
2375
+ // so concurrent gasless calls from many users never conflict.
2374
2376
  const transaction = await aptos.transaction.build.simple({
2375
2377
  sender: account.address.toString(),
2376
2378
  data: input.data,
2377
- options: input.options,
2379
+ options: {
2380
+ ...input.options,
2381
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2382
+ },
2378
2383
  withFeePayer: true,
2379
2384
  });
2380
- // Wallet signs sender portion only (no gas required from user)
2381
- // Cast to any: wallet-adapter-react ships its own bundled @aptos-labs/ts-sdk,
2382
- // so its signTransaction type is structurally incompatible with ours at compile time.
2383
- const senderAuthenticator = await signTransaction(transaction);
2385
+ // Wallet signs sender portion only (no gas required from user).
2386
+ // wallet-adapter v8 changed signTransaction to accept { transactionOrPayload, asFeePayer }
2387
+ // and returns { authenticator, rawTransaction }.
2388
+ // Cast to any to bridge the type mismatch between SDK devDep version and runtime v8.
2389
+ const rawResult = await signTransaction({
2390
+ transactionOrPayload: transaction,
2391
+ asFeePayer: false,
2392
+ });
2393
+ // Handle both old API (returns AccountAuthenticator directly) and
2394
+ // new v8 API (returns { authenticator, rawTransaction })
2395
+ const senderAuthenticator = rawResult?.authenticator ?? rawResult;
2384
2396
  // Relayer signs as fee payer and submits
2385
2397
  return await submitter.submitTransaction({
2386
2398
  aptosConfig: aptos.config,
@@ -2407,6 +2419,223 @@ function useSmoothSend(submitter) {
2407
2419
  return { signAndSubmitTransaction };
2408
2420
  }
2409
2421
 
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
+ // ─── helpers ────────────────────────────────────────────────────────────────
2430
+ function parseDurationToSeconds(duration) {
2431
+ const n = parseInt(duration, 10);
2432
+ if (isNaN(n))
2433
+ throw new Error(`Invalid duration "${duration}". Use e.g. "2h", "24h", "7d".`);
2434
+ if (duration.endsWith('s'))
2435
+ return n;
2436
+ if (duration.endsWith('m'))
2437
+ return n * 60;
2438
+ if (duration.endsWith('h'))
2439
+ return n * 3600;
2440
+ if (duration.endsWith('d'))
2441
+ return n * 86400;
2442
+ throw new Error(`Unknown duration unit in "${duration}". Supported: s, m, h, d.`);
2443
+ }
2444
+ // ─── SmoothSendSession ───────────────────────────────────────────────────────
2445
+ /**
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
+ * A session that lets your app submit transactions on behalf of a user
2452
+ * without any wallet popup after the initial one-time setup.
2453
+ *
2454
+ * Uses Aptos AIP-103 Permissioned Signers — authorization is enforced
2455
+ * on-chain by `0x1::permissioned_delegation`. No custom Move contract needed.
2456
+ *
2457
+ * @example
2458
+ * // 1. One-time setup (user signs once — can be keyless/Google login)
2459
+ * const session = await SmoothSendSession.create({
2460
+ * signer: keylessAccount,
2461
+ * expiresIn: '24h',
2462
+ * }, submitter)
2463
+ *
2464
+ * // 2. Every action after — zero popups, zero gas
2465
+ * await session.submit('0xgame::player::move', ['north'])
2466
+ * await session.submit('0xgame::player::attack', [enemyId])
2467
+ */
2468
+ class SmoothSendSession {
2469
+ constructor(args) {
2470
+ this.sessionAccount = args.sessionAccount;
2471
+ this.abstractedAccount = args.abstractedAccount;
2472
+ this.masterAddress = args.masterAddress;
2473
+ this.expiresAtMs = args.expiresAtMs;
2474
+ this.submitter = args.submitter;
2475
+ this.aptosClient = args.aptosClient;
2476
+ this._network = args.network;
2477
+ }
2478
+ /**
2479
+ * Create a new session.
2480
+ *
2481
+ * Registers the session key on-chain via
2482
+ * `0x1::permissioned_delegation::add_permissioned_handle`.
2483
+ * SmoothSend pays the gas for this setup transaction too.
2484
+ *
2485
+ * After this returns, the user never needs to approve anything again
2486
+ * until the session expires or is revoked.
2487
+ */
2488
+ static async create(options, submitter) {
2489
+ // Resolve network from options or submitter config
2490
+ const network = options.network ?? submitter.getConfig().network ?? 'testnet';
2491
+ const aptosNetwork = network === 'mainnet' ? Network.MAINNET : Network.TESTNET;
2492
+ const aptosClient = new Aptos(new AptosConfig({ network: aptosNetwork }));
2493
+ // Generate a fresh Ed25519 session keypair (lives in memory, never persisted)
2494
+ const sessionAccount = Account.generate();
2495
+ // Client-side expiry tracking (the bytecode script doesn't take an expiry arg)
2496
+ const nowSecs = Math.floor(Date.now() / 1000);
2497
+ const expirationTimeSecs = nowSecs + parseDurationToSeconds(options.expiresIn);
2498
+ // Step 1: Register the session key on-chain via a pre-compiled Move script.
2499
+ // add_permissioned_handle is NOT an entry function — only callable from a Move script.
2500
+ // Must happen BEFORE enabling account abstraction.
2501
+ const setupTx = await aptosClient.transaction.build.simple({
2502
+ sender: options.signer.accountAddress,
2503
+ withFeePayer: true,
2504
+ data: {
2505
+ bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
2506
+ functionArguments: [MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
2507
+ },
2508
+ options: {
2509
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2510
+ },
2511
+ });
2512
+ const senderAuth = aptosClient.transaction.sign({
2513
+ signer: options.signer,
2514
+ transaction: setupTx,
2515
+ });
2516
+ const setupResult = await submitter.submitTransaction({
2517
+ aptosConfig: aptosClient.config,
2518
+ transaction: setupTx,
2519
+ senderAuthenticator: senderAuth,
2520
+ });
2521
+ await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
2522
+ // Step 2: Enable account abstraction — tells the chain to use
2523
+ // 0x1::permissioned_delegation::authenticate for this account.
2524
+ // Idempotent — skip if already enabled.
2525
+ const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
2526
+ accountAddress: options.signer.accountAddress,
2527
+ authenticationFunction: '0x1::permissioned_delegation::authenticate',
2528
+ });
2529
+ if (!aaEnabled) {
2530
+ const aaTx = await aptosClient.transaction.build.simple({
2531
+ sender: options.signer.accountAddress,
2532
+ withFeePayer: true,
2533
+ data: {
2534
+ function: '0x1::account_abstraction::add_authentication_function',
2535
+ functionArguments: [
2536
+ AccountAddress.fromString('0x1'),
2537
+ 'permissioned_delegation',
2538
+ 'authenticate',
2539
+ ],
2540
+ },
2541
+ });
2542
+ const aaAuth = aptosClient.transaction.sign({ signer: options.signer, transaction: aaTx });
2543
+ const aaResult = await submitter.submitTransaction({
2544
+ aptosConfig: aptosClient.config,
2545
+ transaction: aaTx,
2546
+ senderAuthenticator: aaAuth,
2547
+ });
2548
+ await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
2549
+ }
2550
+ // Build AbstractedAccount — signs future txs with session key but
2551
+ // sender on-chain = master address. Chain validates via permissioned_delegation.
2552
+ const abstractedAccount = AbstractedAccount.fromPermissionedSigner({
2553
+ signer: sessionAccount,
2554
+ accountAddress: options.signer.accountAddress,
2555
+ });
2556
+ return new SmoothSendSession({
2557
+ sessionAccount,
2558
+ abstractedAccount,
2559
+ masterAddress: options.signer.accountAddress,
2560
+ expiresAtMs: expirationTimeSecs * 1000,
2561
+ submitter,
2562
+ aptosClient,
2563
+ network,
2564
+ });
2565
+ }
2566
+ /**
2567
+ * Submit a transaction silently — no wallet popup, zero gas.
2568
+ *
2569
+ * The transaction sender on-chain is still the user's main address.
2570
+ * The session key signs it, and `permissioned_delegation::authenticate`
2571
+ * validates the authorization at the VM level.
2572
+ *
2573
+ * @param functionName Full Move function identifier e.g. '0xgame::player::move'
2574
+ * @param functionArguments Arguments matching the Move function signature
2575
+ * @param typeArguments Optional type arguments for generic functions
2576
+ *
2577
+ * @example
2578
+ * await session.submit('0xgame::player::move', ['north'])
2579
+ * await session.submit('0x1::coin::transfer', [recipientAddr, 1000000n])
2580
+ */
2581
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2582
+ async submit(functionName, functionArguments = [], typeArguments = []) {
2583
+ if (!this.isValid()) {
2584
+ throw new Error(`Session expired at ${new Date(this.expiresAtMs).toISOString()}. ` +
2585
+ `Call SmoothSendSession.create() to start a new session.`);
2586
+ }
2587
+ // replayProtectionNonce: orderless transaction (AIP-123).
2588
+ // Lets users submit multiple session.submit() calls in parallel without
2589
+ // sequence number conflicts — critical for games, agents, rapid-fire actions.
2590
+ const tx = await this.aptosClient.transaction.build.simple({
2591
+ sender: this.masterAddress,
2592
+ withFeePayer: true,
2593
+ data: {
2594
+ function: functionName,
2595
+ functionArguments,
2596
+ ...(typeArguments.length > 0 ? { typeArguments } : {}),
2597
+ },
2598
+ options: {
2599
+ replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
2600
+ },
2601
+ });
2602
+ // Session key signs on behalf of master address
2603
+ const senderAuth = this.aptosClient.transaction.sign({
2604
+ signer: this.abstractedAccount,
2605
+ transaction: tx,
2606
+ });
2607
+ const result = await this.submitter.submitTransaction({
2608
+ aptosConfig: this.aptosClient.config,
2609
+ transaction: tx,
2610
+ senderAuthenticator: senderAuth,
2611
+ });
2612
+ return { hash: result.hash };
2613
+ }
2614
+ /**
2615
+ * Whether this session is still valid (not yet expired).
2616
+ */
2617
+ isValid() {
2618
+ return Date.now() < this.expiresAtMs;
2619
+ }
2620
+ /**
2621
+ * Milliseconds until this session expires. Returns 0 if already expired.
2622
+ */
2623
+ expiresInMs() {
2624
+ return Math.max(0, this.expiresAtMs - Date.now());
2625
+ }
2626
+ /**
2627
+ * Session metadata — useful for display or debugging.
2628
+ */
2629
+ get info() {
2630
+ return {
2631
+ masterAddress: this.masterAddress.toString(),
2632
+ sessionKeyAddress: this.sessionAccount.accountAddress.toString(),
2633
+ expiresAt: this.expiresAtMs,
2634
+ network: this._network,
2635
+ };
2636
+ }
2637
+ }
2638
+
2410
2639
  /**
2411
2640
  * Script Composer Client
2412
2641
  *
@@ -2688,7 +2917,7 @@ function createScriptComposerClient(config) {
2688
2917
  * SDK version
2689
2918
  * @public
2690
2919
  */
2691
- const VERSION = '2.1.2';
2920
+ const VERSION = '2.2.0';
2692
2921
 
2693
- 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 };
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 };
2694
2923
  //# sourceMappingURL=index.esm.js.map