@smoothsend/sdk 2.3.6 → 2.3.7
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/LICENSE +22 -22
- package/README.md +349 -349
- package/dist/adapters/evm.d.ts +39 -0
- package/dist/adapters/evm.d.ts.map +1 -0
- package/dist/config/chains.d.ts +7 -0
- package/dist/config/chains.d.ts.map +1 -0
- package/dist/index.esm.js +3 -1846
- package/dist/index.esm.js.map +1 -1
- package/dist/services/chainConfigService.d.ts +49 -0
- package/dist/services/chainConfigService.d.ts.map +1 -0
- package/package.json +120 -120
- package/dist/aptos-privy/index.cjs +0 -40
- package/dist/aptos-privy/index.cjs.map +0 -1
- package/dist/aptos-privy/index.js +0 -34
- package/dist/aptos-privy/index.js.map +0 -1
- package/dist/aptos-privy/normalizePrivyAptosWallet.d.ts +0 -4
- package/dist/aptos-privy/normalizePrivyAptosWallet.d.ts.map +0 -1
- package/dist/aptos-privy/privyAptosSigner.d.ts +0 -32
- package/dist/aptos-privy/privyAptosSigner.d.ts.map +0 -1
- package/dist/aptos-privy/useSmoothSendAptosPrivy.d.ts +0 -13
- package/dist/aptos-privy/useSmoothSendAptosPrivy.d.ts.map +0 -1
- package/dist/aptos-privy-entry.d.ts +0 -9
- package/dist/aptos-privy-entry.d.ts.map +0 -1
- package/dist/chunks/SmoothSendSDK-C_ofuBkk.cjs +0 -1519
- package/dist/chunks/SmoothSendSDK-C_ofuBkk.cjs.map +0 -1
- package/dist/chunks/SmoothSendSDK-CaV_PCIG.js +0 -1511
- package/dist/chunks/SmoothSendSDK-CaV_PCIG.js.map +0 -1
- package/dist/chunks/SmoothSendSDK.d-9GBgZONY.d.ts +0 -262
- package/dist/chunks/TrueGaslessClient-DThO4Tpb.cjs +0 -1237
- package/dist/chunks/TrueGaslessClient-DThO4Tpb.cjs.map +0 -1
- package/dist/chunks/TrueGaslessClient-l2uFvNAa.js +0 -1228
- package/dist/chunks/TrueGaslessClient-l2uFvNAa.js.map +0 -1
- package/dist/chunks/shared-2xx2VLH3.js +0 -453
- package/dist/chunks/shared-2xx2VLH3.js.map +0 -1
- package/dist/chunks/shared-B8UdyBTN.d.ts +0 -143
- package/dist/chunks/shared-BJv1JV1H.cjs +0 -702
- package/dist/chunks/shared-BJv1JV1H.cjs.map +0 -1
- package/dist/chunks/shared-BXvqbQ6f.d.ts +0 -262
- package/dist/chunks/shared-Bh4xtpHv.js +0 -740
- package/dist/chunks/shared-Bh4xtpHv.js.map +0 -1
- package/dist/chunks/shared-BlIQttCf.d.ts +0 -1279
- package/dist/chunks/shared-BoRfHN1w.js +0 -1511
- package/dist/chunks/shared-BoRfHN1w.js.map +0 -1
- package/dist/chunks/shared-CNF22ESH.js +0 -557
- package/dist/chunks/shared-CNF22ESH.js.map +0 -1
- package/dist/chunks/shared-CPpb2n9T.d.ts +0 -780
- package/dist/chunks/shared-CaQMAGQR.js +0 -1511
- package/dist/chunks/shared-CaQMAGQR.js.map +0 -1
- package/dist/chunks/shared-Cgb7mhwI.d.ts +0 -471
- package/dist/chunks/shared-Cn4duBJT.d.ts +0 -1279
- package/dist/chunks/shared-CzR0rIwZ.cjs +0 -635
- package/dist/chunks/shared-CzR0rIwZ.cjs.map +0 -1
- package/dist/chunks/shared-DEurKmpI.cjs +0 -1519
- package/dist/chunks/shared-DEurKmpI.cjs.map +0 -1
- package/dist/chunks/shared-DQbEIiTE.cjs +0 -746
- package/dist/chunks/shared-DQbEIiTE.cjs.map +0 -1
- package/dist/chunks/shared-DYAVFARB.d.ts +0 -472
- package/dist/chunks/shared-DzwYUjQn.cjs +0 -457
- package/dist/chunks/shared-DzwYUjQn.cjs.map +0 -1
- package/dist/chunks/shared-KUvoQkzf.d.ts +0 -471
- package/dist/chunks/shared-RVkwmkG7.d.ts +0 -262
- package/dist/chunks/shared-XH1iLZjy.js +0 -629
- package/dist/chunks/shared-XH1iLZjy.js.map +0 -1
- package/dist/chunks/shared-kovW7ATj.js +0 -694
- package/dist/chunks/shared-kovW7ATj.js.map +0 -1
- package/dist/chunks/shared-viO0MYao.d.ts +0 -459
- package/dist/chunks/shared-x1-VC-Li.cjs +0 -568
- package/dist/chunks/shared-x1-VC-Li.cjs.map +0 -1
- package/dist/chunks/useSmoothSendAvax-BHeW_6x8.cjs +0 -1865
- package/dist/chunks/useSmoothSendAvax-BHeW_6x8.cjs.map +0 -1
- package/dist/chunks/useSmoothSendAvax-ZuHw1aYi.js +0 -1848
- package/dist/chunks/useSmoothSendAvax-ZuHw1aYi.js.map +0 -1
- package/dist/chunks/version-CNF22ESH.js +0 -557
- package/dist/chunks/version-CNF22ESH.js.map +0 -1
- package/dist/chunks/version-x1-VC-Li.cjs +0 -568
- package/dist/chunks/version-x1-VC-Li.cjs.map +0 -1
- package/dist/chunks/version.d-Cn4duBJT.d.ts +0 -1279
|
@@ -1,1237 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var tsSdk = require('@aptos-labs/ts-sdk');
|
|
4
|
-
var require$$0 = require('react');
|
|
5
|
-
var walletAdapterReact = require('@aptos-labs/wallet-adapter-react');
|
|
6
|
-
var http = require('./version-x1-VC-Li.cjs');
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Pre-compiled Move script bytecode for add_permissioned_handle
|
|
10
|
-
*
|
|
11
|
-
* This bytecode is used to register session keys on-chain via the
|
|
12
|
-
* `0x1::permissioned_delegation::add_permissioned_handle` function.
|
|
13
|
-
*
|
|
14
|
-
* The function cannot be called as an entry function directly — only via a Move script.
|
|
15
|
-
* This bytecode handles:
|
|
16
|
-
* - Takes the session public key bytes (vector<u8>) as input
|
|
17
|
-
* - Constructs DelegationKey from the bytes
|
|
18
|
-
* - Passes option::none() for rate limiter
|
|
19
|
-
* - Hardcodes u64::MAX for expiration (on-chain handle never expires)
|
|
20
|
-
*
|
|
21
|
-
* Source: aptos-labs/aptos-ts-sdk tests/e2e/transaction/helper.ts
|
|
22
|
-
*/
|
|
23
|
-
const ADD_PERMISSIONED_HANDLE_BYTECODE = 'a11ceb0b0700000a0801001002101603262c04520405563d079301d70208ea034010aa041f0103010401060109010d010e011201140002080002080700030b0700040c0f0005100701000001050301010001020704050001030a05060001050f01080100010311090a000106130b01000107150b0100010002030702060c0a020001080001060c010a02010801010802010803010b0401090004060c08020b0401080303010c03060c060c03050802030b04010803060c0c083c53454c463e5f30046d61696e094170746f73436f696e0a6170746f735f636f696e04636f696e196d6967726174655f746f5f66756e6769626c655f73746f72650765643235353139256e65775f756e76616c6964617465645f7075626c69635f6b65795f66726f6d5f627974657314556e76616c6964617465645075626c69634b657917' +
|
|
24
|
-
'7065726d697373696f6e65645f64656c65676174696f6e0f67656e5f656432353531395f6b65790d44656c65676174696f6e4b65790b526174654c696d697465720c726174655f6c696d69746572066f7074696f6e046e6f6e65064f7074696f6e176164645f7065726d697373696f6e65645f68616e646c65167072696d6172795f66756e6769626c655f73746f7265146772616e745f6170745f7065726d697373696f6e167472616e73616374696f6e5f76616c69646174696f6e146772616e745f6761735f7065726d697373696f6effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000114636f6d70696c6174696f6e5f6d65746164617461090003322e3003322e3100000c170a0038000b01110111020c020a0038010c040b020b040600a0724e1809000011040c060a000e060600e1f5050000000011050b000e060600e1f50500000000110602';
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* SmoothSend Transaction Submitter
|
|
28
|
-
*
|
|
29
|
-
* A TransactionSubmitter implementation that integrates with the Aptos Wallet Adapter
|
|
30
|
-
* to enable gasless transactions via SmoothSend's relayer network.
|
|
31
|
-
*
|
|
32
|
-
* @example
|
|
33
|
-
* ```typescript
|
|
34
|
-
* import { SmoothSendTransactionSubmitter } from '@smoothsend/sdk';
|
|
35
|
-
* import { AptosWalletAdapterProvider } from '@aptos-labs/wallet-adapter-react';
|
|
36
|
-
*
|
|
37
|
-
* // Create the transaction submitter
|
|
38
|
-
* const transactionSubmitter = new SmoothSendTransactionSubmitter({
|
|
39
|
-
* apiKey: 'pk_nogas_your_api_key_here',
|
|
40
|
-
* network: 'testnet'
|
|
41
|
-
* });
|
|
42
|
-
*
|
|
43
|
-
* // Use in your wallet provider - that's it!
|
|
44
|
-
* <AptosWalletAdapterProvider
|
|
45
|
-
* dappConfig={{
|
|
46
|
-
* network: Network.TESTNET,
|
|
47
|
-
* transactionSubmitter: transactionSubmitter
|
|
48
|
-
* }}
|
|
49
|
-
* >
|
|
50
|
-
* <App />
|
|
51
|
-
* </AptosWalletAdapterProvider>
|
|
52
|
-
* ```
|
|
53
|
-
*/
|
|
54
|
-
/**
|
|
55
|
-
* SmoothSend Transaction Submitter
|
|
56
|
-
*
|
|
57
|
-
* Implements the TransactionSubmitter interface to enable gasless transactions
|
|
58
|
-
* through the Aptos Wallet Adapter. Simply pass this to your AptosWalletAdapterProvider
|
|
59
|
-
* and all transactions will automatically be submitted as gasless through SmoothSend.
|
|
60
|
-
*/
|
|
61
|
-
class SmoothSendTransactionSubmitter {
|
|
62
|
-
constructor(config) {
|
|
63
|
-
this._session = null;
|
|
64
|
-
this.sponsoredFunctionsCache = null;
|
|
65
|
-
this.sponsoredFunctionsCacheAt = 0;
|
|
66
|
-
this.SPONSORED_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
|
|
67
|
-
if (!config.apiKey) {
|
|
68
|
-
throw new Error('SmoothSend API key is required. Get your key at dashboard.smoothsend.xyz');
|
|
69
|
-
}
|
|
70
|
-
// Validate API key format
|
|
71
|
-
if (!config.apiKey.startsWith('pk_nogas_') &&
|
|
72
|
-
!config.apiKey.startsWith('sk_nogas_') &&
|
|
73
|
-
!config.apiKey.startsWith('no_gas_')) {
|
|
74
|
-
throw new Error('Invalid API key format. Key must start with pk_nogas_, sk_nogas_, or no_gas_');
|
|
75
|
-
}
|
|
76
|
-
// Warn if using secret key in browser
|
|
77
|
-
if (config.apiKey.startsWith('sk_nogas_') && typeof window !== 'undefined') {
|
|
78
|
-
console.warn('⚠️ WARNING: Secret key detected in browser environment.\n' +
|
|
79
|
-
'Secret keys (sk_nogas_*) should only be used in server-side code.\n' +
|
|
80
|
-
'Use public keys (pk_nogas_*) for frontend applications.');
|
|
81
|
-
}
|
|
82
|
-
this.apiKey = config.apiKey;
|
|
83
|
-
this.network = config.network || 'testnet';
|
|
84
|
-
this.gatewayUrl = config.gatewayUrl || 'https://proxy.smoothsend.xyz';
|
|
85
|
-
this.timeout = config.timeout || 30000;
|
|
86
|
-
this.getCaptchaToken = config.getCaptchaToken;
|
|
87
|
-
this.debug = config.debug || false;
|
|
88
|
-
this.sessionEnabled = config.session || false;
|
|
89
|
-
this.sessionDuration = config.sessionDuration || '24h';
|
|
90
|
-
}
|
|
91
|
-
// ─── Session key methods ────────────────────────────────────────────────────
|
|
92
|
-
/**
|
|
93
|
-
* Whether a valid session is currently active.
|
|
94
|
-
*/
|
|
95
|
-
hasSession() {
|
|
96
|
-
return this._session !== null && Date.now() < this._session.expiresAtMs;
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Create a session key for the given master account.
|
|
100
|
-
* Called once by useSmoothSend when session: true and no session exists.
|
|
101
|
-
* SmoothSend pays gas for the setup transaction.
|
|
102
|
-
*
|
|
103
|
-
* @param masterAccount - The user's wallet account (from wallet adapter)
|
|
104
|
-
*/
|
|
105
|
-
async createSession(masterAccount) {
|
|
106
|
-
const network = this.network === 'mainnet' ? tsSdk.Network.MAINNET : tsSdk.Network.TESTNET;
|
|
107
|
-
const aptosClient = new tsSdk.Aptos(new tsSdk.AptosConfig({ network }));
|
|
108
|
-
// Generate fresh in-memory session keypair
|
|
109
|
-
const sessionAccount = tsSdk.Account.generate();
|
|
110
|
-
const expiresAtMs = Date.now() + this._parseDuration(this.sessionDuration);
|
|
111
|
-
// Step 1: Register session key on-chain via pre-compiled Move script
|
|
112
|
-
const setupTx = await aptosClient.transaction.build.simple({
|
|
113
|
-
sender: masterAccount.accountAddress,
|
|
114
|
-
withFeePayer: true,
|
|
115
|
-
data: {
|
|
116
|
-
bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
|
|
117
|
-
functionArguments: [tsSdk.MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
|
|
118
|
-
},
|
|
119
|
-
options: {
|
|
120
|
-
replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
|
|
121
|
-
},
|
|
122
|
-
});
|
|
123
|
-
const senderAuth = await this.signSenderAuthenticator(masterAccount, setupTx, aptosClient);
|
|
124
|
-
const setupResult = await this.submitTransaction({
|
|
125
|
-
aptosConfig: aptosClient.config,
|
|
126
|
-
transaction: setupTx,
|
|
127
|
-
senderAuthenticator: senderAuth,
|
|
128
|
-
});
|
|
129
|
-
await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
|
|
130
|
-
if (this.debug) {
|
|
131
|
-
console.log('[SmoothSend] Session key registered on-chain:', setupResult.hash);
|
|
132
|
-
}
|
|
133
|
-
// Step 2: Enable account abstraction (idempotent — skip if already on)
|
|
134
|
-
const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
|
|
135
|
-
accountAddress: masterAccount.accountAddress,
|
|
136
|
-
authenticationFunction: '0x1::permissioned_delegation::authenticate',
|
|
137
|
-
});
|
|
138
|
-
if (!aaEnabled) {
|
|
139
|
-
const aaTx = await aptosClient.transaction.build.simple({
|
|
140
|
-
sender: masterAccount.accountAddress,
|
|
141
|
-
withFeePayer: true,
|
|
142
|
-
data: {
|
|
143
|
-
function: '0x1::account_abstraction::add_authentication_function',
|
|
144
|
-
functionArguments: [
|
|
145
|
-
tsSdk.AccountAddress.fromString('0x1'),
|
|
146
|
-
'permissioned_delegation',
|
|
147
|
-
'authenticate',
|
|
148
|
-
],
|
|
149
|
-
},
|
|
150
|
-
options: {
|
|
151
|
-
replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
|
|
152
|
-
},
|
|
153
|
-
});
|
|
154
|
-
const aaAuth = await this.signSenderAuthenticator(masterAccount, aaTx, aptosClient);
|
|
155
|
-
const aaResult = await this.submitTransaction({
|
|
156
|
-
aptosConfig: aptosClient.config,
|
|
157
|
-
transaction: aaTx,
|
|
158
|
-
senderAuthenticator: aaAuth,
|
|
159
|
-
});
|
|
160
|
-
await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
|
|
161
|
-
if (this.debug) {
|
|
162
|
-
console.log('[SmoothSend] Account abstraction enabled:', aaResult.hash);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
// Build AbstractedAccount — signs future txs with session key,
|
|
166
|
-
// sender on-chain = master address, chain validates via permissioned_delegation
|
|
167
|
-
const abstractedAccount = tsSdk.AbstractedAccount.fromPermissionedSigner({
|
|
168
|
-
signer: sessionAccount,
|
|
169
|
-
accountAddress: masterAccount.accountAddress,
|
|
170
|
-
});
|
|
171
|
-
this._session = {
|
|
172
|
-
sessionAccount,
|
|
173
|
-
abstractedAccount,
|
|
174
|
-
masterAddress: masterAccount.accountAddress,
|
|
175
|
-
expiresAtMs,
|
|
176
|
-
aptosClient,
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
async isPermissionedSignerEnabled(aptosClient) {
|
|
180
|
-
try {
|
|
181
|
-
const result = await aptosClient.view({
|
|
182
|
-
payload: {
|
|
183
|
-
function: '0x1::features::is_permissioned_signer_enabled',
|
|
184
|
-
functionArguments: [],
|
|
185
|
-
},
|
|
186
|
-
});
|
|
187
|
-
return Array.isArray(result) && result[0] === true;
|
|
188
|
-
}
|
|
189
|
-
catch (error) {
|
|
190
|
-
if (this.debug) {
|
|
191
|
-
console.warn('[SmoothSend] Failed to probe permissioned signer feature:', error);
|
|
192
|
-
}
|
|
193
|
-
return false;
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
async signSenderAuthenticator(signer, transaction, aptosClient) {
|
|
197
|
-
const walletLikeSigner = signer;
|
|
198
|
-
// Wallet-adapter compatible path (returns { authenticator, rawTransaction } in v8)
|
|
199
|
-
if (typeof walletLikeSigner?.signTransactionWithAuthenticator === 'function') {
|
|
200
|
-
const result = await walletLikeSigner.signTransactionWithAuthenticator(transaction);
|
|
201
|
-
return (result?.authenticator ?? result);
|
|
202
|
-
}
|
|
203
|
-
// Native ts-sdk account path
|
|
204
|
-
return aptosClient.transaction.sign({
|
|
205
|
-
signer,
|
|
206
|
-
transaction,
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Submit a transaction using the active session key — no wallet popup.
|
|
211
|
-
* Called by useSmoothSend after session is established.
|
|
212
|
-
*/
|
|
213
|
-
async submitWithSession(functionName, functionArguments = [], typeArguments = []) {
|
|
214
|
-
if (!this._session || !this.hasSession()) {
|
|
215
|
-
throw new Error('[SmoothSend] No active session. Call createSession() first.');
|
|
216
|
-
}
|
|
217
|
-
const { abstractedAccount, masterAddress, aptosClient } = this._session;
|
|
218
|
-
const tx = await aptosClient.transaction.build.simple({
|
|
219
|
-
sender: masterAddress,
|
|
220
|
-
withFeePayer: true,
|
|
221
|
-
data: {
|
|
222
|
-
function: functionName,
|
|
223
|
-
functionArguments,
|
|
224
|
-
...(typeArguments.length > 0 ? { typeArguments } : {}),
|
|
225
|
-
},
|
|
226
|
-
options: {
|
|
227
|
-
replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
|
|
228
|
-
},
|
|
229
|
-
});
|
|
230
|
-
const senderAuth = aptosClient.transaction.sign({
|
|
231
|
-
signer: abstractedAccount,
|
|
232
|
-
transaction: tx,
|
|
233
|
-
});
|
|
234
|
-
return this.submitTransaction({
|
|
235
|
-
aptosConfig: aptosClient.config,
|
|
236
|
-
transaction: tx,
|
|
237
|
-
senderAuthenticator: senderAuth,
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
_parseDuration(duration) {
|
|
241
|
-
if (duration === 'never') {
|
|
242
|
-
// Client-side "never expires" mode; on-chain handle already uses u64::MAX.
|
|
243
|
-
return Number.MAX_SAFE_INTEGER;
|
|
244
|
-
}
|
|
245
|
-
const n = parseInt(duration, 10);
|
|
246
|
-
if (isNaN(n))
|
|
247
|
-
throw new Error(`Invalid sessionDuration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
|
|
248
|
-
if (duration.endsWith('s'))
|
|
249
|
-
return n * 1000;
|
|
250
|
-
if (duration.endsWith('m'))
|
|
251
|
-
return n * 60 * 1000;
|
|
252
|
-
if (duration.endsWith('h'))
|
|
253
|
-
return n * 3600 * 1000;
|
|
254
|
-
if (duration.endsWith('d'))
|
|
255
|
-
return n * 86400 * 1000;
|
|
256
|
-
throw new Error(`Unknown unit in "${duration}". Supported: s, m, h, d, or "never".`);
|
|
257
|
-
}
|
|
258
|
-
// ─── Transaction submission ──────────────────────────────────────────────────
|
|
259
|
-
/**
|
|
260
|
-
* Submit a transaction through SmoothSend's gasless relayer
|
|
261
|
-
*
|
|
262
|
-
* This method is called automatically by the Aptos Wallet Adapter when
|
|
263
|
-
* you use signAndSubmitTransaction. The transaction is submitted to
|
|
264
|
-
* SmoothSend's relayer which sponsors the gas fees.
|
|
265
|
-
*/
|
|
266
|
-
async submitTransaction(args) {
|
|
267
|
-
const { aptosConfig, transaction, senderAuthenticator, pluginParams } = args;
|
|
268
|
-
// Auto-detect network from aptosConfig (source of truth from wallet adapter)
|
|
269
|
-
// Falls back to constructor value if aptosConfig doesn't have a recognized network
|
|
270
|
-
const detectedNetwork = this.resolveNetwork(aptosConfig);
|
|
271
|
-
if (this.debug) {
|
|
272
|
-
console.log('[SmoothSend] Submitting gasless transaction:', {
|
|
273
|
-
sender: transaction.rawTransaction?.sender?.toString(),
|
|
274
|
-
configNetwork: this.network,
|
|
275
|
-
detectedNetwork,
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
if (detectedNetwork !== this.network && this.debug) {
|
|
279
|
-
console.warn(`[SmoothSend] Network mismatch: constructor=${this.network}, aptosConfig=${detectedNetwork}. ` +
|
|
280
|
-
`Using aptosConfig network (${detectedNetwork}).`);
|
|
281
|
-
}
|
|
282
|
-
try {
|
|
283
|
-
// Serialize transaction and authenticator to bytes
|
|
284
|
-
const transactionBytes = Array.from(transaction.bcsToBytes());
|
|
285
|
-
const authenticatorBytes = Array.from(senderAuthenticator.bcsToBytes());
|
|
286
|
-
// Prepare request payload — always use the detected network
|
|
287
|
-
const payload = {
|
|
288
|
-
transactionBytes,
|
|
289
|
-
authenticatorBytes,
|
|
290
|
-
network: detectedNetwork,
|
|
291
|
-
functionName: pluginParams?.functionName || 'unknown',
|
|
292
|
-
};
|
|
293
|
-
// Make request to SmoothSend gateway
|
|
294
|
-
const response = await this.makeRequest('/api/v1/relayer/gasless-transaction', payload, detectedNetwork);
|
|
295
|
-
if (!response.success || !response.txnHash) {
|
|
296
|
-
throw new Error(response.error || response.details || 'Transaction submission failed');
|
|
297
|
-
}
|
|
298
|
-
if (this.debug) {
|
|
299
|
-
console.log('[SmoothSend] Transaction successful:', {
|
|
300
|
-
hash: response.txnHash,
|
|
301
|
-
gasUsed: response.gasUsed,
|
|
302
|
-
});
|
|
303
|
-
}
|
|
304
|
-
// Return in the format expected by Aptos SDK
|
|
305
|
-
return {
|
|
306
|
-
hash: response.txnHash,
|
|
307
|
-
sender: response.sender || transaction.rawTransaction?.sender?.toString() || '',
|
|
308
|
-
sequence_number: transaction.rawTransaction?.sequence_number?.toString() || '0',
|
|
309
|
-
max_gas_amount: transaction.rawTransaction?.max_gas_amount?.toString() || '0',
|
|
310
|
-
gas_unit_price: transaction.rawTransaction?.gas_unit_price?.toString() || '0',
|
|
311
|
-
expiration_timestamp_secs: transaction.rawTransaction?.expiration_timestamp_secs?.toString() || '0',
|
|
312
|
-
payload: {},
|
|
313
|
-
signature: undefined,
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
catch (error) {
|
|
317
|
-
if (this.debug) {
|
|
318
|
-
console.error('[SmoothSend] Transaction failed:', error);
|
|
319
|
-
}
|
|
320
|
-
throw new Error(`SmoothSend gasless transaction failed: ${error.message}`);
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
/**
|
|
324
|
-
* Resolve the effective network from aptosConfig.
|
|
325
|
-
* aptosConfig.network is the source of truth set by AptosWalletAdapterProvider.
|
|
326
|
-
*/
|
|
327
|
-
resolveNetwork(aptosConfig) {
|
|
328
|
-
try {
|
|
329
|
-
const configNetwork = aptosConfig?.network;
|
|
330
|
-
if (configNetwork === 'testnet' || configNetwork === 'mainnet') {
|
|
331
|
-
return configNetwork;
|
|
332
|
-
}
|
|
333
|
-
if (typeof configNetwork === 'string') {
|
|
334
|
-
const normalized = configNetwork.toLowerCase();
|
|
335
|
-
if (normalized === 'testnet' || normalized === 'mainnet') {
|
|
336
|
-
return normalized;
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
catch {
|
|
341
|
-
// fall through
|
|
342
|
-
}
|
|
343
|
-
return this.network;
|
|
344
|
-
}
|
|
345
|
-
/**
|
|
346
|
-
* Make an HTTP request to the SmoothSend gateway
|
|
347
|
-
*/
|
|
348
|
-
async makeRequest(endpoint, payload, network, method = 'POST') {
|
|
349
|
-
const effectiveNetwork = network || this.network;
|
|
350
|
-
const url = `${this.gatewayUrl}${endpoint}`;
|
|
351
|
-
const headers = {
|
|
352
|
-
'Content-Type': 'application/json',
|
|
353
|
-
'X-API-Key': this.apiKey,
|
|
354
|
-
'X-Chain': `aptos-${effectiveNetwork}`,
|
|
355
|
-
};
|
|
356
|
-
// Add Origin header for public keys in browser
|
|
357
|
-
if (this.apiKey.startsWith('pk_nogas_') && typeof window !== 'undefined') {
|
|
358
|
-
headers['Origin'] = window.location.origin;
|
|
359
|
-
}
|
|
360
|
-
// Add captcha token if the project requires it
|
|
361
|
-
if (this.getCaptchaToken) {
|
|
362
|
-
try {
|
|
363
|
-
const token = await this.getCaptchaToken();
|
|
364
|
-
if (token) {
|
|
365
|
-
headers['X-Captcha-Token'] = token;
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
catch (e) {
|
|
369
|
-
if (this.debug) {
|
|
370
|
-
console.warn('[SmoothSend] Failed to get captcha token:', e);
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
const controller = new AbortController();
|
|
375
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
376
|
-
try {
|
|
377
|
-
const response = await fetch(url, {
|
|
378
|
-
method,
|
|
379
|
-
headers,
|
|
380
|
-
body: method === 'GET' ? undefined : JSON.stringify(payload),
|
|
381
|
-
signal: controller.signal,
|
|
382
|
-
});
|
|
383
|
-
clearTimeout(timeoutId);
|
|
384
|
-
if (!response.ok) {
|
|
385
|
-
const errorData = await response.json().catch(() => ({}));
|
|
386
|
-
throw new Error(errorData.error || errorData.message || `HTTP ${response.status}`);
|
|
387
|
-
}
|
|
388
|
-
return await response.json();
|
|
389
|
-
}
|
|
390
|
-
catch (error) {
|
|
391
|
-
clearTimeout(timeoutId);
|
|
392
|
-
if (error.name === 'AbortError') {
|
|
393
|
-
throw new Error('Request timed out');
|
|
394
|
-
}
|
|
395
|
-
throw error;
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
/**
|
|
399
|
-
* Fetch the list of sponsored functions for this API key's project.
|
|
400
|
-
* Results are cached for 5 minutes. Returns ['*'] if all functions are sponsored.
|
|
401
|
-
*/
|
|
402
|
-
async getSponsoredFunctions() {
|
|
403
|
-
const now = Date.now();
|
|
404
|
-
if (this.sponsoredFunctionsCache !== null && now - this.sponsoredFunctionsCacheAt < this.SPONSORED_CACHE_TTL) {
|
|
405
|
-
return this.sponsoredFunctionsCache;
|
|
406
|
-
}
|
|
407
|
-
try {
|
|
408
|
-
const response = await this.makeRequest('/api/v1/sponsorship', {}, undefined, 'GET');
|
|
409
|
-
const fns = response.sponsoredFunctions;
|
|
410
|
-
this.sponsoredFunctionsCache = Array.isArray(fns) ? fns : ['*'];
|
|
411
|
-
}
|
|
412
|
-
catch {
|
|
413
|
-
this.sponsoredFunctionsCache = ['*']; // fail-open: assume all sponsored
|
|
414
|
-
}
|
|
415
|
-
this.sponsoredFunctionsCacheAt = now;
|
|
416
|
-
return this.sponsoredFunctionsCache;
|
|
417
|
-
}
|
|
418
|
-
/**
|
|
419
|
-
* Check if a specific function is sponsored for gasless execution.
|
|
420
|
-
* @param functionName - Full function identifier, e.g. "0x123::module::function"
|
|
421
|
-
*/
|
|
422
|
-
async isSponsored(functionName) {
|
|
423
|
-
const fns = await this.getSponsoredFunctions();
|
|
424
|
-
if (fns.includes('*'))
|
|
425
|
-
return true;
|
|
426
|
-
const normalize = (id) => id.replace(/^(0x)0+([1-9a-f][0-9a-f]*)(::.+)$/i, '$1$2$3').toLowerCase();
|
|
427
|
-
const normalized = normalize(functionName);
|
|
428
|
-
return fns.some(f => normalize(f) === normalized);
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
*/
|
|
432
|
-
getConfig() {
|
|
433
|
-
return {
|
|
434
|
-
apiKey: this.apiKey.substring(0, 15) + '...', // Don't expose full key
|
|
435
|
-
network: this.network,
|
|
436
|
-
gatewayUrl: this.gatewayUrl,
|
|
437
|
-
timeout: this.timeout,
|
|
438
|
-
debug: this.debug,
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
}
|
|
442
|
-
/**
|
|
443
|
-
* Create a SmoothSend transaction submitter with minimal configuration
|
|
444
|
-
*
|
|
445
|
-
* @example
|
|
446
|
-
* ```typescript
|
|
447
|
-
* const submitter = createSmoothSendSubmitter('pk_nogas_your_key');
|
|
448
|
-
* ```
|
|
449
|
-
*/
|
|
450
|
-
function createSmoothSendSubmitter(apiKey, options) {
|
|
451
|
-
return new SmoothSendTransactionSubmitter({
|
|
452
|
-
apiKey,
|
|
453
|
-
...options,
|
|
454
|
-
});
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
/**
|
|
458
|
-
* useSmoothSend — React hook for automatic gasless / user-pays-gas routing
|
|
459
|
-
*
|
|
460
|
-
* Drop-in replacement for useWallet()'s signAndSubmitTransaction.
|
|
461
|
-
* Fetches the project's sponsored-functions list from the gateway on mount
|
|
462
|
-
* and routes each transaction automatically:
|
|
463
|
-
* - Function in allowlist → fee-payer gasless path via SmoothSend
|
|
464
|
-
* - Function not in allowlist → regular wallet submission (user pays gas)
|
|
465
|
-
*
|
|
466
|
-
* When submitter has session: true, the first transaction triggers a one-time
|
|
467
|
-
* wallet sign to register a session key on-chain. Every transaction after that
|
|
468
|
-
* is signed silently — zero wallet popups.
|
|
469
|
-
*
|
|
470
|
-
* Requires: react >=17, @aptos-labs/wallet-adapter-react >=3, @aptos-labs/ts-sdk >=1
|
|
471
|
-
*
|
|
472
|
-
* @example
|
|
473
|
-
* ```tsx
|
|
474
|
-
* // Replace useWallet() with useSmoothSend() where you submit transactions.
|
|
475
|
-
* // No other changes needed.
|
|
476
|
-
*
|
|
477
|
-
* const { signAndSubmitTransaction } = useSmoothSend(submitter);
|
|
478
|
-
* await signAndSubmitTransaction({ data: { function: '0x1::coin::transfer', functionArguments: [to, amount] } });
|
|
479
|
-
* ```
|
|
480
|
-
*/
|
|
481
|
-
function useSmoothSend(submitter) {
|
|
482
|
-
const { account, signTransaction, signAndSubmitTransaction: walletSignAndSubmit, } = walletAdapterReact.useWallet();
|
|
483
|
-
// Track session state reactively so UI updates when session is created/expires
|
|
484
|
-
const initialHasSession = submitter?.hasSession?.() ?? false;
|
|
485
|
-
const [hasSessionState, setHasSessionState] = require$$0.useState(initialHasSession);
|
|
486
|
-
// Prefetch the sponsored-functions list on mount so the first transaction
|
|
487
|
-
// benefits from an already-populated cache with no added latency.
|
|
488
|
-
require$$0.useEffect(() => {
|
|
489
|
-
submitter.getSponsoredFunctions().catch(() => {
|
|
490
|
-
// Fail-open: getSponsoredFunctions already handles errors internally
|
|
491
|
-
});
|
|
492
|
-
}, [submitter]);
|
|
493
|
-
require$$0.useEffect(() => {
|
|
494
|
-
if (!submitter)
|
|
495
|
-
return;
|
|
496
|
-
const refresh = () => {
|
|
497
|
-
const hasSession = submitter.hasSession?.() ?? false;
|
|
498
|
-
setHasSessionState(hasSession);
|
|
499
|
-
};
|
|
500
|
-
refresh();
|
|
501
|
-
const timer = setInterval(refresh, 1000);
|
|
502
|
-
return () => clearInterval(timer);
|
|
503
|
-
}, [submitter]);
|
|
504
|
-
const signAndSubmitTransaction = require$$0.useCallback(async (input) => {
|
|
505
|
-
if (!account?.address) {
|
|
506
|
-
throw new Error('[SmoothSend] Wallet not connected');
|
|
507
|
-
}
|
|
508
|
-
const functionName = input?.data?.function ?? '';
|
|
509
|
-
console.log('[SmoothSend] signAndSubmitTransaction called:', {
|
|
510
|
-
functionName,
|
|
511
|
-
sessionEnabled: submitter.sessionEnabled,
|
|
512
|
-
hasSession: submitter.hasSession(),
|
|
513
|
-
});
|
|
514
|
-
// ── Session key path ────────────────────────────────────────────────────
|
|
515
|
-
// When session: true, bypass wallet signing entirely after first setup.
|
|
516
|
-
// Still respects the per-function allowlist — non-sponsored functions
|
|
517
|
-
// fall through to regular wallet submission (user pays gas).
|
|
518
|
-
if (submitter.sessionEnabled) {
|
|
519
|
-
console.log('[SmoothSend] Session mode enabled');
|
|
520
|
-
// Check allowlist first — no point setting up a session for a non-sponsored function
|
|
521
|
-
const canGoGasless = typeof signTransaction === 'function';
|
|
522
|
-
const sponsored = canGoGasless && (await submitter.isSponsored(functionName));
|
|
523
|
-
console.log('[SmoothSend] Sponsored check:', { sponsored, canGoGasless });
|
|
524
|
-
if (sponsored) {
|
|
525
|
-
// If no active session, do the one-time setup
|
|
526
|
-
if (!submitter.hasSession()) {
|
|
527
|
-
console.log('[SmoothSend] No session, creating one...');
|
|
528
|
-
if (!signTransaction) {
|
|
529
|
-
console.warn('[SmoothSend] session: true requires signTransaction support. Falling back to regular submission.');
|
|
530
|
-
}
|
|
531
|
-
else {
|
|
532
|
-
try {
|
|
533
|
-
// Adapter object only needs accountAddress + signTransactionWithAuthenticator.
|
|
534
|
-
// The submitter handles both wallet-adapter and native signer shapes.
|
|
535
|
-
const walletAccount = {
|
|
536
|
-
accountAddress: account.address,
|
|
537
|
-
signTransactionWithAuthenticator: async (tx) => {
|
|
538
|
-
const rawResult = await signTransaction({
|
|
539
|
-
transactionOrPayload: tx,
|
|
540
|
-
asFeePayer: false,
|
|
541
|
-
});
|
|
542
|
-
return rawResult?.authenticator ?? rawResult;
|
|
543
|
-
},
|
|
544
|
-
};
|
|
545
|
-
await submitter.createSession(walletAccount);
|
|
546
|
-
console.log('[SmoothSend] Session created successfully');
|
|
547
|
-
setHasSessionState(submitter.hasSession?.() ?? false);
|
|
548
|
-
}
|
|
549
|
-
catch (err) {
|
|
550
|
-
console.warn('[SmoothSend] Session setup failed, falling back to regular gasless:', err.message);
|
|
551
|
-
// Fall through to normal gasless path below
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
// If session is now active, submit silently — no wallet popup
|
|
556
|
-
if (submitter.hasSession()) {
|
|
557
|
-
console.log('[SmoothSend] Session is active, using submitWithSession');
|
|
558
|
-
try {
|
|
559
|
-
return await submitter.submitWithSession(functionName, input.data?.functionArguments ?? [], input.data?.typeArguments ?? []);
|
|
560
|
-
}
|
|
561
|
-
catch (err) {
|
|
562
|
-
// Session may have expired mid-flight — clear it and fall through
|
|
563
|
-
console.warn('[SmoothSend] Session submit failed, will re-auth on next call:', err.message);
|
|
564
|
-
setHasSessionState(false);
|
|
565
|
-
// Fall through to regular gasless path for this call
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
// Non-sponsored function → fall through to walletSignAndSubmit below
|
|
570
|
-
}
|
|
571
|
-
// ── Regular gasless path (TransactionSubmitter) ─────────────────────────
|
|
572
|
-
// signTransaction (sign-only) must be available for the gasless path.
|
|
573
|
-
// Most modern wallets (Petra, Nightly) support it. If absent, fall through.
|
|
574
|
-
const canGoGasless = typeof signTransaction === 'function';
|
|
575
|
-
const sponsored = canGoGasless && (await submitter.isSponsored(functionName));
|
|
576
|
-
if (sponsored && signTransaction) {
|
|
577
|
-
try {
|
|
578
|
-
const config = submitter.getConfig();
|
|
579
|
-
const network = config.network === 'mainnet' ? tsSdk.Network.MAINNET : tsSdk.Network.TESTNET;
|
|
580
|
-
const aptos = new tsSdk.Aptos(new tsSdk.AptosConfig({ network }));
|
|
581
|
-
// Build transaction with fee-payer placeholder (AccountAddress.ZERO).
|
|
582
|
-
// replayProtectionNonce (AIP-123): random nonce instead of sequence number
|
|
583
|
-
// so concurrent gasless calls from many users never conflict.
|
|
584
|
-
const transaction = await aptos.transaction.build.simple({
|
|
585
|
-
sender: account.address.toString(),
|
|
586
|
-
data: input.data,
|
|
587
|
-
options: {
|
|
588
|
-
...input.options,
|
|
589
|
-
replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
|
|
590
|
-
},
|
|
591
|
-
withFeePayer: true,
|
|
592
|
-
});
|
|
593
|
-
// Wallet signs sender portion only (no gas required from user).
|
|
594
|
-
// wallet-adapter v8 changed signTransaction to accept { transactionOrPayload, asFeePayer }
|
|
595
|
-
// and returns { authenticator, rawTransaction }.
|
|
596
|
-
// Cast to any to bridge the type mismatch between SDK devDep version and runtime v8.
|
|
597
|
-
const rawResult = await signTransaction({
|
|
598
|
-
transactionOrPayload: transaction,
|
|
599
|
-
asFeePayer: false,
|
|
600
|
-
});
|
|
601
|
-
// Handle both old API (returns AccountAuthenticator directly) and
|
|
602
|
-
// new v8 API (returns { authenticator, rawTransaction })
|
|
603
|
-
const senderAuthenticator = rawResult?.authenticator ?? rawResult;
|
|
604
|
-
// Relayer signs as fee payer and submits
|
|
605
|
-
return await submitter.submitTransaction({
|
|
606
|
-
aptosConfig: aptos.config,
|
|
607
|
-
transaction: transaction,
|
|
608
|
-
senderAuthenticator: senderAuthenticator,
|
|
609
|
-
});
|
|
610
|
-
}
|
|
611
|
-
catch (err) {
|
|
612
|
-
// If the relayer rejects (e.g. function not in allowlist after a config change),
|
|
613
|
-
// fall through to user-pays-gas path rather than surfacing a hard error.
|
|
614
|
-
if (err?.message?.includes('SPONSORSHIP') ||
|
|
615
|
-
err?.message?.includes('not allowed') ||
|
|
616
|
-
err?.message?.includes('403') ||
|
|
617
|
-
err?.message?.includes('gasless')) {
|
|
618
|
-
console.warn('[SmoothSend] Sponsorship rejected, falling back to user-pays-gas:', err.message);
|
|
619
|
-
return walletSignAndSubmit(input);
|
|
620
|
-
}
|
|
621
|
-
throw err;
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
// Not sponsored or signTransaction unavailable → regular wallet submission
|
|
625
|
-
return walletSignAndSubmit(input);
|
|
626
|
-
}, [account, signTransaction, walletSignAndSubmit, submitter]);
|
|
627
|
-
return {
|
|
628
|
-
signAndSubmitTransaction,
|
|
629
|
-
hasSession: hasSessionState,
|
|
630
|
-
};
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
// ─── helpers ────────────────────────────────────────────────────────────────
|
|
634
|
-
function parseDurationToSeconds(duration) {
|
|
635
|
-
if (duration === 'never') {
|
|
636
|
-
// Client-side "never expires" mode; on-chain handle already uses u64::MAX.
|
|
637
|
-
return Math.floor(Number.MAX_SAFE_INTEGER / 1000);
|
|
638
|
-
}
|
|
639
|
-
const n = parseInt(duration, 10);
|
|
640
|
-
if (isNaN(n))
|
|
641
|
-
throw new Error(`Invalid duration "${duration}". Use e.g. "2h", "24h", "7d", or "never".`);
|
|
642
|
-
if (duration.endsWith('s'))
|
|
643
|
-
return n;
|
|
644
|
-
if (duration.endsWith('m'))
|
|
645
|
-
return n * 60;
|
|
646
|
-
if (duration.endsWith('h'))
|
|
647
|
-
return n * 3600;
|
|
648
|
-
if (duration.endsWith('d'))
|
|
649
|
-
return n * 86400;
|
|
650
|
-
throw new Error(`Unknown duration unit in "${duration}". Supported: s, m, h, d, or "never".`);
|
|
651
|
-
}
|
|
652
|
-
// ─── SmoothSendSession ───────────────────────────────────────────────────────
|
|
653
|
-
/**
|
|
654
|
-
* A session that lets your app submit transactions on behalf of a user
|
|
655
|
-
* without any wallet popup after the initial one-time setup.
|
|
656
|
-
*
|
|
657
|
-
* Uses Aptos AIP-103 Permissioned Signers — authorization is enforced
|
|
658
|
-
* on-chain by `0x1::permissioned_delegation`. No custom Move contract needed.
|
|
659
|
-
*
|
|
660
|
-
* @example
|
|
661
|
-
* // 1. One-time setup (user signs once — can be keyless/Google login)
|
|
662
|
-
* const session = await SmoothSendSession.create({
|
|
663
|
-
* signer: keylessAccount,
|
|
664
|
-
* expiresIn: '24h',
|
|
665
|
-
* }, submitter)
|
|
666
|
-
*
|
|
667
|
-
* // 2. Every action after — zero popups, zero gas
|
|
668
|
-
* await session.submit('0xgame::player::move', ['north'])
|
|
669
|
-
* await session.submit('0xgame::player::attack', [enemyId])
|
|
670
|
-
*/
|
|
671
|
-
class SmoothSendSession {
|
|
672
|
-
constructor(args) {
|
|
673
|
-
this.sessionAccount = args.sessionAccount;
|
|
674
|
-
this.abstractedAccount = args.abstractedAccount;
|
|
675
|
-
this.masterAddress = args.masterAddress;
|
|
676
|
-
this.expiresAtMs = args.expiresAtMs;
|
|
677
|
-
this.submitter = args.submitter;
|
|
678
|
-
this.aptosClient = args.aptosClient;
|
|
679
|
-
this._network = args.network;
|
|
680
|
-
}
|
|
681
|
-
/**
|
|
682
|
-
* Create a new session.
|
|
683
|
-
*
|
|
684
|
-
* Registers the session key on-chain via
|
|
685
|
-
* `0x1::permissioned_delegation::add_permissioned_handle`.
|
|
686
|
-
* SmoothSend pays the gas for this setup transaction too.
|
|
687
|
-
*
|
|
688
|
-
* After this returns, the user never needs to approve anything again
|
|
689
|
-
* until the session expires or is revoked.
|
|
690
|
-
*/
|
|
691
|
-
static async create(options, submitter) {
|
|
692
|
-
// Resolve network from options or submitter config
|
|
693
|
-
const network = options.network ?? submitter.getConfig().network ?? 'testnet';
|
|
694
|
-
const aptosNetwork = network === 'mainnet' ? tsSdk.Network.MAINNET : tsSdk.Network.TESTNET;
|
|
695
|
-
const aptosClient = new tsSdk.Aptos(new tsSdk.AptosConfig({ network: aptosNetwork }));
|
|
696
|
-
const feature = await aptosClient.view({
|
|
697
|
-
payload: {
|
|
698
|
-
function: '0x1::features::is_permissioned_signer_enabled',
|
|
699
|
-
functionArguments: [],
|
|
700
|
-
},
|
|
701
|
-
}).catch(() => [false]);
|
|
702
|
-
if (!Array.isArray(feature) || feature[0] !== true) {
|
|
703
|
-
throw new Error('[SmoothSend] Session keys unavailable on this network (permissioned signer feature disabled).');
|
|
704
|
-
}
|
|
705
|
-
// Generate a fresh Ed25519 session keypair (lives in memory, never persisted)
|
|
706
|
-
const sessionAccount = tsSdk.Account.generate();
|
|
707
|
-
// Client-side expiry tracking (the bytecode script doesn't take an expiry arg)
|
|
708
|
-
const nowSecs = Math.floor(Date.now() / 1000);
|
|
709
|
-
const expirationTimeSecs = nowSecs + parseDurationToSeconds(options.expiresIn);
|
|
710
|
-
// Step 1: Register the session key on-chain via a pre-compiled Move script.
|
|
711
|
-
// add_permissioned_handle is NOT an entry function — only callable from a Move script.
|
|
712
|
-
// Must happen BEFORE enabling account abstraction.
|
|
713
|
-
const setupTx = await aptosClient.transaction.build.simple({
|
|
714
|
-
sender: options.signer.accountAddress,
|
|
715
|
-
withFeePayer: true,
|
|
716
|
-
data: {
|
|
717
|
-
bytecode: ADD_PERMISSIONED_HANDLE_BYTECODE,
|
|
718
|
-
functionArguments: [tsSdk.MoveVector.U8(sessionAccount.publicKey.toUint8Array())],
|
|
719
|
-
},
|
|
720
|
-
options: {
|
|
721
|
-
replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
|
|
722
|
-
},
|
|
723
|
-
});
|
|
724
|
-
const senderAuth = aptosClient.transaction.sign({
|
|
725
|
-
signer: options.signer,
|
|
726
|
-
transaction: setupTx,
|
|
727
|
-
});
|
|
728
|
-
const setupResult = await submitter.submitTransaction({
|
|
729
|
-
aptosConfig: aptosClient.config,
|
|
730
|
-
transaction: setupTx,
|
|
731
|
-
senderAuthenticator: senderAuth,
|
|
732
|
-
});
|
|
733
|
-
await aptosClient.waitForTransaction({ transactionHash: setupResult.hash });
|
|
734
|
-
// Step 2: Enable account abstraction — tells the chain to use
|
|
735
|
-
// 0x1::permissioned_delegation::authenticate for this account.
|
|
736
|
-
// Idempotent — skip if already enabled.
|
|
737
|
-
const aaEnabled = await aptosClient.abstraction.isAccountAbstractionEnabled({
|
|
738
|
-
accountAddress: options.signer.accountAddress,
|
|
739
|
-
authenticationFunction: '0x1::permissioned_delegation::authenticate',
|
|
740
|
-
});
|
|
741
|
-
if (!aaEnabled) {
|
|
742
|
-
const aaTx = await aptosClient.transaction.build.simple({
|
|
743
|
-
sender: options.signer.accountAddress,
|
|
744
|
-
withFeePayer: true,
|
|
745
|
-
data: {
|
|
746
|
-
function: '0x1::account_abstraction::add_authentication_function',
|
|
747
|
-
functionArguments: [
|
|
748
|
-
tsSdk.AccountAddress.fromString('0x1'),
|
|
749
|
-
'permissioned_delegation',
|
|
750
|
-
'authenticate',
|
|
751
|
-
],
|
|
752
|
-
},
|
|
753
|
-
});
|
|
754
|
-
const aaAuth = aptosClient.transaction.sign({ signer: options.signer, transaction: aaTx });
|
|
755
|
-
const aaResult = await submitter.submitTransaction({
|
|
756
|
-
aptosConfig: aptosClient.config,
|
|
757
|
-
transaction: aaTx,
|
|
758
|
-
senderAuthenticator: aaAuth,
|
|
759
|
-
});
|
|
760
|
-
await aptosClient.waitForTransaction({ transactionHash: aaResult.hash });
|
|
761
|
-
}
|
|
762
|
-
// Build AbstractedAccount — signs future txs with session key but
|
|
763
|
-
// sender on-chain = master address. Chain validates via permissioned_delegation.
|
|
764
|
-
const abstractedAccount = tsSdk.AbstractedAccount.fromPermissionedSigner({
|
|
765
|
-
signer: sessionAccount,
|
|
766
|
-
accountAddress: options.signer.accountAddress,
|
|
767
|
-
});
|
|
768
|
-
return new SmoothSendSession({
|
|
769
|
-
sessionAccount,
|
|
770
|
-
abstractedAccount,
|
|
771
|
-
masterAddress: options.signer.accountAddress,
|
|
772
|
-
expiresAtMs: expirationTimeSecs * 1000,
|
|
773
|
-
submitter,
|
|
774
|
-
aptosClient,
|
|
775
|
-
network,
|
|
776
|
-
});
|
|
777
|
-
}
|
|
778
|
-
/**
|
|
779
|
-
* Submit a transaction silently — no wallet popup, zero gas.
|
|
780
|
-
*
|
|
781
|
-
* The transaction sender on-chain is still the user's main address.
|
|
782
|
-
* The session key signs it, and `permissioned_delegation::authenticate`
|
|
783
|
-
* validates the authorization at the VM level.
|
|
784
|
-
*
|
|
785
|
-
* @param functionName Full Move function identifier e.g. '0xgame::player::move'
|
|
786
|
-
* @param functionArguments Arguments matching the Move function signature
|
|
787
|
-
* @param typeArguments Optional type arguments for generic functions
|
|
788
|
-
*
|
|
789
|
-
* @example
|
|
790
|
-
* await session.submit('0xgame::player::move', ['north'])
|
|
791
|
-
* await session.submit('0x1::coin::transfer', [recipientAddr, 1000000n])
|
|
792
|
-
*/
|
|
793
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
794
|
-
async submit(functionName, functionArguments = [], typeArguments = []) {
|
|
795
|
-
if (!this.isValid()) {
|
|
796
|
-
throw new Error(`Session expired at ${new Date(this.expiresAtMs).toISOString()}. ` +
|
|
797
|
-
`Call SmoothSendSession.create() to start a new session.`);
|
|
798
|
-
}
|
|
799
|
-
// replayProtectionNonce: orderless transaction (AIP-123).
|
|
800
|
-
// Lets users submit multiple session.submit() calls in parallel without
|
|
801
|
-
// sequence number conflicts — critical for games, agents, rapid-fire actions.
|
|
802
|
-
const tx = await this.aptosClient.transaction.build.simple({
|
|
803
|
-
sender: this.masterAddress,
|
|
804
|
-
withFeePayer: true,
|
|
805
|
-
data: {
|
|
806
|
-
function: functionName,
|
|
807
|
-
functionArguments,
|
|
808
|
-
...(typeArguments.length > 0 ? { typeArguments } : {}),
|
|
809
|
-
},
|
|
810
|
-
options: {
|
|
811
|
-
replayProtectionNonce: BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)),
|
|
812
|
-
},
|
|
813
|
-
});
|
|
814
|
-
// Session key signs on behalf of master address
|
|
815
|
-
const senderAuth = this.aptosClient.transaction.sign({
|
|
816
|
-
signer: this.abstractedAccount,
|
|
817
|
-
transaction: tx,
|
|
818
|
-
});
|
|
819
|
-
const result = await this.submitter.submitTransaction({
|
|
820
|
-
aptosConfig: this.aptosClient.config,
|
|
821
|
-
transaction: tx,
|
|
822
|
-
senderAuthenticator: senderAuth,
|
|
823
|
-
});
|
|
824
|
-
return { hash: result.hash };
|
|
825
|
-
}
|
|
826
|
-
/**
|
|
827
|
-
* Whether this session is still valid (not yet expired).
|
|
828
|
-
*/
|
|
829
|
-
isValid() {
|
|
830
|
-
return Date.now() < this.expiresAtMs;
|
|
831
|
-
}
|
|
832
|
-
/**
|
|
833
|
-
* Milliseconds until this session expires. Returns 0 if already expired.
|
|
834
|
-
*/
|
|
835
|
-
expiresInMs() {
|
|
836
|
-
return Math.max(0, this.expiresAtMs - Date.now());
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* Session metadata — useful for display or debugging.
|
|
840
|
-
*/
|
|
841
|
-
get info() {
|
|
842
|
-
return {
|
|
843
|
-
masterAddress: this.masterAddress.toString(),
|
|
844
|
-
sessionKeyAddress: this.sessionAccount.accountAddress.toString(),
|
|
845
|
-
expiresAt: this.expiresAtMs,
|
|
846
|
-
network: this._network,
|
|
847
|
-
};
|
|
848
|
-
}
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
/**
|
|
852
|
-
* Script Composer Client
|
|
853
|
-
*
|
|
854
|
-
* Wrapper for Script Composer gasless transactions.
|
|
855
|
-
* Use this for token transfers on mainnet with free tier (fee deducted from token).
|
|
856
|
-
*
|
|
857
|
-
* @remarks
|
|
858
|
-
* Script Composer builds a batched transaction that:
|
|
859
|
-
* 1. Withdraws (amount + fee) from sender
|
|
860
|
-
* 2. Deposits amount to recipient
|
|
861
|
-
* 3. Deposits fee to treasury
|
|
862
|
-
*
|
|
863
|
-
* This allows gasless transactions where the fee is paid in the token being transferred.
|
|
864
|
-
*
|
|
865
|
-
* @example
|
|
866
|
-
* ```typescript
|
|
867
|
-
* import { ScriptComposerClient } from '@smoothsend/aptos-sdk';
|
|
868
|
-
*
|
|
869
|
-
* const client = new ScriptComposerClient({
|
|
870
|
-
* apiKey: 'pk_nogas_xxx',
|
|
871
|
-
* network: 'mainnet'
|
|
872
|
-
* });
|
|
873
|
-
*
|
|
874
|
-
* // Step 1: Build transaction (fee calculated automatically)
|
|
875
|
-
* const { transactionBytes, fee, totalAmount } = await client.buildTransfer({
|
|
876
|
-
* sender: wallet.address,
|
|
877
|
-
* recipient: '0x123...',
|
|
878
|
-
* amount: '1000000', // 1 USDC (6 decimals)
|
|
879
|
-
* assetType: '0x...::usdc::USDC',
|
|
880
|
-
* decimals: 6,
|
|
881
|
-
* symbol: 'USDC'
|
|
882
|
-
* });
|
|
883
|
-
*
|
|
884
|
-
* // Step 2: Sign with wallet
|
|
885
|
-
* const signedTx = await wallet.signTransaction(transactionBytes);
|
|
886
|
-
*
|
|
887
|
-
* // Step 3: Submit
|
|
888
|
-
* const result = await client.submitSignedTransaction({
|
|
889
|
-
* transactionBytes: signedTx.transactionBytes,
|
|
890
|
-
* authenticatorBytes: signedTx.authenticatorBytes
|
|
891
|
-
* });
|
|
892
|
-
*
|
|
893
|
-
* console.log('Tx:', result.txHash);
|
|
894
|
-
* ```
|
|
895
|
-
*/
|
|
896
|
-
/**
|
|
897
|
-
* Script Composer Client
|
|
898
|
-
*
|
|
899
|
-
* For gasless token transfers with fee deducted from the token.
|
|
900
|
-
* Use this on mainnet with free tier, or anytime you want fee-in-token.
|
|
901
|
-
*/
|
|
902
|
-
class ScriptComposerClient {
|
|
903
|
-
constructor(config) {
|
|
904
|
-
if (!config.apiKey) {
|
|
905
|
-
throw new http.SmoothSendError('API key is required', 'MISSING_API_KEY', 400);
|
|
906
|
-
}
|
|
907
|
-
if (!config.network) {
|
|
908
|
-
throw new http.SmoothSendError('Network is required (testnet or mainnet)', 'MISSING_NETWORK', 400);
|
|
909
|
-
}
|
|
910
|
-
this.config = {
|
|
911
|
-
apiKey: config.apiKey,
|
|
912
|
-
network: config.network,
|
|
913
|
-
proxyUrl: config.proxyUrl,
|
|
914
|
-
timeout: config.timeout || 30000,
|
|
915
|
-
debug: config.debug || false,
|
|
916
|
-
};
|
|
917
|
-
this.httpClient = new http.HttpClient({
|
|
918
|
-
apiKey: this.config.apiKey,
|
|
919
|
-
network: this.config.network,
|
|
920
|
-
timeout: this.config.timeout,
|
|
921
|
-
retries: 3,
|
|
922
|
-
includeOrigin: this.isBrowser(),
|
|
923
|
-
});
|
|
924
|
-
}
|
|
925
|
-
isBrowser() {
|
|
926
|
-
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
927
|
-
}
|
|
928
|
-
log(message, data) {
|
|
929
|
-
if (this.config.debug) {
|
|
930
|
-
console.log(`[ScriptComposer] ${message}`, data || '');
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
/**
|
|
934
|
-
* Estimate fee for a transfer without building the transaction
|
|
935
|
-
*
|
|
936
|
-
* @param params Transfer parameters
|
|
937
|
-
* @returns Fee estimation with pricing details
|
|
938
|
-
*/
|
|
939
|
-
async estimateFee(params) {
|
|
940
|
-
this.log('Estimating fee', params);
|
|
941
|
-
try {
|
|
942
|
-
const response = await this.httpClient.post('/api/v1/relayer/estimate-fee', {
|
|
943
|
-
sender: params.sender,
|
|
944
|
-
recipient: params.recipient,
|
|
945
|
-
amount: params.amount,
|
|
946
|
-
assetType: params.assetType,
|
|
947
|
-
decimals: params.decimals,
|
|
948
|
-
symbol: params.symbol,
|
|
949
|
-
network: this.config.network,
|
|
950
|
-
apiKey: this.config.apiKey,
|
|
951
|
-
});
|
|
952
|
-
this.log('Fee estimate received', response.data);
|
|
953
|
-
return response.data;
|
|
954
|
-
}
|
|
955
|
-
catch (error) {
|
|
956
|
-
this.log('Fee estimation failed', error);
|
|
957
|
-
if (error instanceof http.SmoothSendError) {
|
|
958
|
-
throw error;
|
|
959
|
-
}
|
|
960
|
-
throw new http.SmoothSendError(`Failed to estimate fee: ${error.message}`, 'FEE_ESTIMATION_FAILED', 500, { originalError: error.message });
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
/**
|
|
964
|
-
* Build a gasless transfer transaction
|
|
965
|
-
*
|
|
966
|
-
* Returns unsigned transaction bytes that must be signed by the user's wallet.
|
|
967
|
-
* The fee will be deducted from the token being transferred.
|
|
968
|
-
*
|
|
969
|
-
* @param params Transfer parameters
|
|
970
|
-
* @returns Transaction bytes for signing and fee details
|
|
971
|
-
*/
|
|
972
|
-
async buildTransfer(params) {
|
|
973
|
-
this.log('Building transfer', params);
|
|
974
|
-
// Validate parameters
|
|
975
|
-
if (!params.sender || !params.recipient || !params.amount) {
|
|
976
|
-
throw new http.SmoothSendError('Missing required parameters: sender, recipient, amount', 'INVALID_PARAMETERS', 400);
|
|
977
|
-
}
|
|
978
|
-
if (!params.assetType || params.decimals === undefined || !params.symbol) {
|
|
979
|
-
throw new http.SmoothSendError('Missing token parameters: assetType, decimals, symbol', 'INVALID_PARAMETERS', 400);
|
|
980
|
-
}
|
|
981
|
-
try {
|
|
982
|
-
// Call the gasless-transaction endpoint in Script Composer mode
|
|
983
|
-
const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
|
|
984
|
-
sender: params.sender,
|
|
985
|
-
recipient: params.recipient,
|
|
986
|
-
amount: params.amount,
|
|
987
|
-
assetType: params.assetType,
|
|
988
|
-
decimals: params.decimals,
|
|
989
|
-
symbol: params.symbol,
|
|
990
|
-
network: this.config.network,
|
|
991
|
-
});
|
|
992
|
-
this.log('Transaction built', response.data);
|
|
993
|
-
return response.data;
|
|
994
|
-
}
|
|
995
|
-
catch (error) {
|
|
996
|
-
this.log('Build transfer failed', error);
|
|
997
|
-
if (error instanceof http.SmoothSendError) {
|
|
998
|
-
throw error;
|
|
999
|
-
}
|
|
1000
|
-
throw new http.SmoothSendError(`Failed to build transfer: ${error.message}`, 'BUILD_TRANSFER_FAILED', 500, { originalError: error.message });
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
/**
|
|
1004
|
-
* Submit a signed transaction
|
|
1005
|
-
*
|
|
1006
|
-
* After the user signs the transaction bytes returned by buildTransfer(),
|
|
1007
|
-
* use this method to submit the signed transaction.
|
|
1008
|
-
*
|
|
1009
|
-
* @param params Signed transaction bytes
|
|
1010
|
-
* @returns Transaction result with hash
|
|
1011
|
-
*/
|
|
1012
|
-
async submitSignedTransaction(params) {
|
|
1013
|
-
this.log('Submitting signed transaction');
|
|
1014
|
-
if (!params.transactionBytes || !params.authenticatorBytes) {
|
|
1015
|
-
throw new http.SmoothSendError('Missing required parameters: transactionBytes, authenticatorBytes', 'INVALID_PARAMETERS', 400);
|
|
1016
|
-
}
|
|
1017
|
-
try {
|
|
1018
|
-
// Call the gasless-transaction endpoint in Legacy mode (with signed tx)
|
|
1019
|
-
const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
|
|
1020
|
-
transactionBytes: params.transactionBytes,
|
|
1021
|
-
authenticatorBytes: params.authenticatorBytes,
|
|
1022
|
-
network: this.config.network,
|
|
1023
|
-
});
|
|
1024
|
-
this.log('Transaction submitted', response.data);
|
|
1025
|
-
return {
|
|
1026
|
-
success: response.data.success,
|
|
1027
|
-
requestId: response.data.requestId,
|
|
1028
|
-
txHash: response.data.txnHash || response.data.txHash,
|
|
1029
|
-
gasUsed: response.data.gasUsed,
|
|
1030
|
-
vmStatus: response.data.vmStatus,
|
|
1031
|
-
sender: response.data.sender,
|
|
1032
|
-
};
|
|
1033
|
-
}
|
|
1034
|
-
catch (error) {
|
|
1035
|
-
this.log('Submit transaction failed', error);
|
|
1036
|
-
if (error instanceof http.SmoothSendError) {
|
|
1037
|
-
throw error;
|
|
1038
|
-
}
|
|
1039
|
-
throw new http.SmoothSendError(`Failed to submit transaction: ${error.message}`, 'SUBMIT_FAILED', 500, { originalError: error.message });
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
/**
|
|
1043
|
-
* Complete transfer flow: build, sign, and submit
|
|
1044
|
-
*
|
|
1045
|
-
* Convenience method that handles the entire flow.
|
|
1046
|
-
* Requires a wallet that can sign transactions.
|
|
1047
|
-
*
|
|
1048
|
-
* @param params Transfer parameters
|
|
1049
|
-
* @param wallet Wallet with signTransaction method
|
|
1050
|
-
* @returns Transaction result
|
|
1051
|
-
*
|
|
1052
|
-
* @example
|
|
1053
|
-
* ```typescript
|
|
1054
|
-
* const result = await client.transfer({
|
|
1055
|
-
* sender: wallet.address,
|
|
1056
|
-
* recipient: '0x123...',
|
|
1057
|
-
* amount: '1000000',
|
|
1058
|
-
* assetType: USDC_ADDRESS,
|
|
1059
|
-
* decimals: 6,
|
|
1060
|
-
* symbol: 'USDC'
|
|
1061
|
-
* }, wallet);
|
|
1062
|
-
* ```
|
|
1063
|
-
*/
|
|
1064
|
-
async transfer(params, wallet) {
|
|
1065
|
-
this.log('Starting complete transfer flow');
|
|
1066
|
-
// Step 1: Build transaction
|
|
1067
|
-
const buildResult = await this.buildTransfer(params);
|
|
1068
|
-
this.log('Transaction built, fee:', buildResult.fee);
|
|
1069
|
-
// Step 2: Sign with wallet
|
|
1070
|
-
const signedTx = await wallet.signTransaction(buildResult.transactionBytes);
|
|
1071
|
-
this.log('Transaction signed');
|
|
1072
|
-
// Step 3: Submit
|
|
1073
|
-
const result = await this.submitSignedTransaction({
|
|
1074
|
-
transactionBytes: signedTx.transactionBytes,
|
|
1075
|
-
authenticatorBytes: signedTx.authenticatorBytes,
|
|
1076
|
-
});
|
|
1077
|
-
this.log('Transfer complete', result);
|
|
1078
|
-
return result;
|
|
1079
|
-
}
|
|
1080
|
-
/**
|
|
1081
|
-
* Get current network
|
|
1082
|
-
*/
|
|
1083
|
-
getNetwork() {
|
|
1084
|
-
return this.config.network;
|
|
1085
|
-
}
|
|
1086
|
-
/**
|
|
1087
|
-
* Set network
|
|
1088
|
-
*/
|
|
1089
|
-
setNetwork(network) {
|
|
1090
|
-
this.config.network = network;
|
|
1091
|
-
this.httpClient.setNetwork(network);
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
/**
|
|
1095
|
-
* Create a Script Composer client (convenience function)
|
|
1096
|
-
*/
|
|
1097
|
-
function createScriptComposerClient(config) {
|
|
1098
|
-
return new ScriptComposerClient(config);
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
/**
|
|
1102
|
-
* True Gasless Client
|
|
1103
|
-
*
|
|
1104
|
-
* Designed for server-side (backend) environments to securely build, sign,
|
|
1105
|
-
* and submit 100% sponsored gasless transactions using a Secret Key.
|
|
1106
|
-
*
|
|
1107
|
-
* @example
|
|
1108
|
-
* ```typescript
|
|
1109
|
-
* import { TrueGaslessClient } from '@smoothsend/sdk';
|
|
1110
|
-
* import { Account } from '@aptos-labs/ts-sdk';
|
|
1111
|
-
*
|
|
1112
|
-
* const backendWallet = Account.fromPrivateKey({ privateKey: '...' });
|
|
1113
|
-
* const client = new TrueGaslessClient({ apiKey: 'sk_nogas_...', network: 'mainnet' });
|
|
1114
|
-
*
|
|
1115
|
-
* const result = await client.execute({
|
|
1116
|
-
* senderAccount: backendWallet,
|
|
1117
|
-
* payload: {
|
|
1118
|
-
* function: "0x123::my_module::mint_nft",
|
|
1119
|
-
* functionArguments: []
|
|
1120
|
-
* }
|
|
1121
|
-
* });
|
|
1122
|
-
*
|
|
1123
|
-
* console.log("Gasless NFT Minted!", result.txHash);
|
|
1124
|
-
* ```
|
|
1125
|
-
*/
|
|
1126
|
-
class TrueGaslessClient {
|
|
1127
|
-
constructor(config) {
|
|
1128
|
-
if (!config.apiKey) {
|
|
1129
|
-
throw new http.SmoothSendError('API key is required', 'MISSING_API_KEY', 400);
|
|
1130
|
-
}
|
|
1131
|
-
if (!config.apiKey.startsWith('sk_nogas_')) {
|
|
1132
|
-
console.warn('⚠️ WARNING: TrueGaslessClient is intended for backend use with a Secret Key (sk_nogas_*).\n' +
|
|
1133
|
-
'Using a Public Key may result in CORS errors if ran in a browser environment.');
|
|
1134
|
-
}
|
|
1135
|
-
if (!config.network) {
|
|
1136
|
-
throw new http.SmoothSendError('Network is required (testnet or mainnet)', 'MISSING_NETWORK', 400);
|
|
1137
|
-
}
|
|
1138
|
-
this.config = {
|
|
1139
|
-
apiKey: config.apiKey,
|
|
1140
|
-
network: config.network,
|
|
1141
|
-
proxyUrl: config.proxyUrl,
|
|
1142
|
-
timeout: config.timeout || 30000,
|
|
1143
|
-
debug: config.debug || false,
|
|
1144
|
-
};
|
|
1145
|
-
this.httpClient = new http.HttpClient({
|
|
1146
|
-
apiKey: this.config.apiKey,
|
|
1147
|
-
network: this.config.network,
|
|
1148
|
-
timeout: this.config.timeout,
|
|
1149
|
-
retries: 3,
|
|
1150
|
-
includeOrigin: false, // Backend client should not send Origin header
|
|
1151
|
-
baseUrl: this.config.proxyUrl, // Use custom proxy URL if provided
|
|
1152
|
-
});
|
|
1153
|
-
const networkMap = {
|
|
1154
|
-
testnet: tsSdk.Network.TESTNET,
|
|
1155
|
-
mainnet: tsSdk.Network.MAINNET,
|
|
1156
|
-
};
|
|
1157
|
-
this.aptos = new tsSdk.Aptos(new tsSdk.AptosConfig({ network: networkMap[this.config.network] }));
|
|
1158
|
-
}
|
|
1159
|
-
log(message, data) {
|
|
1160
|
-
if (this.config.debug) {
|
|
1161
|
-
console.log(`[TrueGaslessClient] ${message}`, data || '');
|
|
1162
|
-
}
|
|
1163
|
-
}
|
|
1164
|
-
/**
|
|
1165
|
-
* Builds, signs (as sender), and relays an arbitrary payload for complete sponsorship.
|
|
1166
|
-
*/
|
|
1167
|
-
async execute(params) {
|
|
1168
|
-
this.log('Starting gasless execution', { sender: params.senderAccount.accountAddress.toString(), payload: params.payload });
|
|
1169
|
-
if (!params.senderAccount || !params.payload) {
|
|
1170
|
-
throw new http.SmoothSendError('Missing required parameters: senderAccount and payload', 'INVALID_PARAMETERS', 400);
|
|
1171
|
-
}
|
|
1172
|
-
try {
|
|
1173
|
-
this.log('Building simple transaction with fee payer enabled');
|
|
1174
|
-
// Build the transaction and flag it requires a remote fee payer
|
|
1175
|
-
const transaction = await this.aptos.transaction.build.simple({
|
|
1176
|
-
sender: params.senderAccount.accountAddress,
|
|
1177
|
-
data: params.payload,
|
|
1178
|
-
withFeePayer: true,
|
|
1179
|
-
});
|
|
1180
|
-
this.log('Signing transaction locally with senderAccount');
|
|
1181
|
-
// Sign locally over the transaction hash
|
|
1182
|
-
const senderAuthenticator = this.aptos.transaction.sign({
|
|
1183
|
-
signer: params.senderAccount,
|
|
1184
|
-
transaction,
|
|
1185
|
-
});
|
|
1186
|
-
this.log('Serializing to bytes for relayer transmission');
|
|
1187
|
-
// Convert to BCS bytes expected by the proxy
|
|
1188
|
-
const transactionBytes = Array.from(transaction.bcsToBytes());
|
|
1189
|
-
const authenticatorBytes = Array.from(senderAuthenticator.bcsToBytes());
|
|
1190
|
-
this.log('Sending to relayer...');
|
|
1191
|
-
const response = await this.httpClient.post('/api/v1/relayer/gasless-transaction', {
|
|
1192
|
-
transactionBytes,
|
|
1193
|
-
authenticatorBytes,
|
|
1194
|
-
network: this.config.network,
|
|
1195
|
-
functionName: 'function' in params.payload ? params.payload.function : 'unknown',
|
|
1196
|
-
});
|
|
1197
|
-
this.log('Relayer submission successful', response.data);
|
|
1198
|
-
return {
|
|
1199
|
-
success: response.data.success ?? true,
|
|
1200
|
-
requestId: response.data.requestId,
|
|
1201
|
-
txHash: response.data.txnHash || response.data.txHash,
|
|
1202
|
-
gasUsed: response.data.gasUsed,
|
|
1203
|
-
vmStatus: response.data.vmStatus,
|
|
1204
|
-
sender: response.data.sender || params.senderAccount.accountAddress.toString(),
|
|
1205
|
-
};
|
|
1206
|
-
}
|
|
1207
|
-
catch (error) {
|
|
1208
|
-
this.log('Gasless execution failed', error);
|
|
1209
|
-
if (error instanceof http.SmoothSendError) {
|
|
1210
|
-
throw error;
|
|
1211
|
-
}
|
|
1212
|
-
throw new http.SmoothSendError(`Failed to execute gasless transaction: ${error.message}`, 'EXECUTION_FAILED', 500, { originalError: error.message });
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
/**
|
|
1216
|
-
* Expose the core Aptos instance to allow backend developers to access chain state if needed
|
|
1217
|
-
*/
|
|
1218
|
-
getAptosClient() {
|
|
1219
|
-
return this.aptos;
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
/**
|
|
1223
|
-
* Helper to initialize TrueGaslessClient
|
|
1224
|
-
*/
|
|
1225
|
-
function createTrueGaslessClient(config) {
|
|
1226
|
-
return new TrueGaslessClient(config);
|
|
1227
|
-
}
|
|
1228
|
-
|
|
1229
|
-
exports.ScriptComposerClient = ScriptComposerClient;
|
|
1230
|
-
exports.SmoothSendSession = SmoothSendSession;
|
|
1231
|
-
exports.SmoothSendTransactionSubmitter = SmoothSendTransactionSubmitter;
|
|
1232
|
-
exports.TrueGaslessClient = TrueGaslessClient;
|
|
1233
|
-
exports.createScriptComposerClient = createScriptComposerClient;
|
|
1234
|
-
exports.createSmoothSendSubmitter = createSmoothSendSubmitter;
|
|
1235
|
-
exports.createTrueGaslessClient = createTrueGaslessClient;
|
|
1236
|
-
exports.useSmoothSend = useSmoothSend;
|
|
1237
|
-
//# sourceMappingURL=TrueGaslessClient-DThO4Tpb.cjs.map
|