@talken/talkenkit 2.8.5 → 2.8.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/dist/{abcWallet-EOHU5AIB.js → abcWallet-WTHSP3A6.js} +22 -25
- package/dist/{chunk-WGSS57V6.js → chunk-S3KOGN7P.js} +2540 -715
- package/dist/gasless/api/ChainConfigApi.d.ts +2 -2
- package/dist/gasless/index.d.ts +1 -1
- package/dist/gasless/services/GaslessTransferService.d.ts +4 -3
- package/dist/gasless/signer/AbcWaasSigner.d.ts +9 -0
- package/dist/gasless/signer/GaslessSigner.d.ts +10 -0
- package/dist/gasless/signer/WagmiSigner.d.ts +40 -0
- package/dist/gasless/signer/index.d.ts +1 -1
- package/dist/gasless/utils/delegationGuard.d.ts +11 -11
- package/dist/gasless/utils/revokeDelegation.d.ts +22 -23
- package/dist/hooks/useMultiChainBalances.d.ts +2 -0
- package/dist/index.css +5 -3
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1279 -584
- package/dist/services/AbcAuthService.d.ts +12 -1
- package/dist/solana/clusterIdentity.d.ts +5 -0
- package/dist/wallets/walletConnectors/abcWallet/AbcCredentialManager.d.ts +0 -1
- package/dist/wallets/walletConnectors/abcWallet/AbcCredentialManager.js +3 -3
- package/dist/wallets/walletConnectors/abcWallet/AbcEvmAutoConnector.js +4 -4
- package/dist/wallets/walletConnectors/abcWallet/AbstractChainProvider.d.ts +11 -0
- package/dist/wallets/walletConnectors/abcWallet/AbstractChainProvider.js +5 -2
- package/dist/wallets/walletConnectors/abcWallet/StorageService.js +2 -2
- package/dist/wallets/walletConnectors/abcWallet/abcBitcoinConnector.d.ts +2 -0
- package/dist/wallets/walletConnectors/abcWallet/abcBitcoinConnector.js +7 -5
- package/dist/wallets/walletConnectors/abcWallet/abcBitcoinProvider.d.ts +1 -0
- package/dist/wallets/walletConnectors/abcWallet/abcBitcoinProvider.js +10 -9
- package/dist/wallets/walletConnectors/abcWallet/abcConnector.js +23 -21
- package/dist/wallets/walletConnectors/abcWallet/abcProvider.d.ts +1 -0
- package/dist/wallets/walletConnectors/abcWallet/abcProvider.js +12 -11
- package/dist/wallets/walletConnectors/abcWallet/abcSolanaProvider.js +26 -24
- package/dist/wallets/walletConnectors/abcWallet/abcSolanaWalletAdapter.d.ts +3 -0
- package/dist/wallets/walletConnectors/abcWallet/abcSolanaWalletAdapter.js +183 -62
- package/dist/wallets/walletConnectors/abcWallet/abcTronProvider.d.ts +1 -0
- package/dist/wallets/walletConnectors/abcWallet/abcTronProvider.js +10 -9
- package/dist/wallets/walletConnectors/abcWallet/abcWallet.js +24 -22
- package/dist/wallets/walletConnectors/abcWallet/abcXrplProvider.d.ts +1 -0
- package/dist/wallets/walletConnectors/abcWallet/abcXrplProvider.js +10 -9
- package/dist/wallets/walletConnectors/abcWallet/api/AccessKeySessionBinding.d.ts +10 -0
- package/dist/wallets/walletConnectors/abcWallet/api/AccessKeySessionBinding.js +13 -0
- package/dist/wallets/walletConnectors/abcWallet/api/ConfigApi.js +5 -2
- package/dist/wallets/walletConnectors/abcWallet/api/GasApi.js +5 -1
- package/dist/wallets/walletConnectors/abcWallet/api/SolanaApi.js +5 -1
- package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.d.ts +34 -12
- package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.js +19 -16
- package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiSingleton.d.ts +6 -0
- package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiSingleton.js +10 -1
- package/dist/wallets/walletConnectors/abcWallet/api/TokenApi.js +5 -2
- package/dist/wallets/walletConnectors/abcWallet/api/WalletscanApi.js +13 -3
- package/dist/wallets/walletConnectors/abcWallet/api/index.js +26 -23
- package/dist/wallets/walletConnectors/abcWallet/api/modules/auth.d.ts +20 -10
- package/dist/wallets/walletConnectors/abcWallet/api/modules/auth.js +3 -3
- package/dist/wallets/walletConnectors/abcWallet/api/modules/bitcoin.js +11 -9
- package/dist/wallets/walletConnectors/abcWallet/api/modules/evm.d.ts +1 -1
- package/dist/wallets/walletConnectors/abcWallet/api/modules/evm.js +10 -8
- package/dist/wallets/walletConnectors/abcWallet/api/modules/executeBodies.js +4 -3
- package/dist/wallets/walletConnectors/abcWallet/api/modules/signBodies.js +2 -2
- package/dist/wallets/walletConnectors/abcWallet/api/modules/signingRefresh.js +6 -5
- package/dist/wallets/walletConnectors/abcWallet/api/modules/solana.js +6 -5
- package/dist/wallets/walletConnectors/abcWallet/api/modules/tron.js +10 -8
- package/dist/wallets/walletConnectors/abcWallet/api/modules/wallet.d.ts +2 -1
- package/dist/wallets/walletConnectors/abcWallet/api/modules/wallet.js +2 -2
- package/dist/wallets/walletConnectors/abcWallet/api/modules/walletscan.js +2 -2
- package/dist/wallets/walletConnectors/abcWallet/api/modules/xrp.js +10 -8
- package/dist/wallets/walletConnectors/abcWallet/constants.d.ts +18 -6
- package/dist/wallets/walletConnectors/abcWallet/constants.js +13 -3
- package/dist/wallets/walletConnectors/abcWallet/index.d.ts +1 -0
- package/dist/wallets/walletConnectors/abcWallet/index.js +40 -38
- package/dist/wallets/walletConnectors/abcWallet/sessionUtils.js +11 -3
- package/dist/wallets/walletConnectors/abcWallet/types/auth.types.d.ts +75 -0
- package/dist/wallets/walletConnectors/abcWallet/types/error.types.d.ts +2 -0
- package/dist/wallets/walletConnectors/abcWallet/types/error.types.js +5 -3
- package/dist/wallets/walletConnectors/abcWallet/types.js +5 -3
- package/dist/wallets/walletConnectors/abcWallet/utils.js +4 -4
- package/dist/wallets/walletConnectors/abcWallet/walletGeneration.js +6 -5
- package/dist/wallets/walletConnectors/chunk-2YCHXOLC.js +53 -0
- package/dist/wallets/walletConnectors/{chunk-6MZWQBNQ.js → chunk-3RUQ4ARU.js} +3 -3
- package/dist/wallets/walletConnectors/{chunk-MNGSJBPX.js → chunk-3XZJNLAA.js} +128 -77
- package/dist/wallets/walletConnectors/chunk-4UMY2AY7.js +414 -0
- package/dist/wallets/walletConnectors/chunk-5GTFKQGQ.js +739 -0
- package/dist/wallets/walletConnectors/{chunk-XGQUYXTL.js → chunk-5KPLYJOO.js} +12 -407
- package/dist/wallets/walletConnectors/{chunk-EGLT3GPM.js → chunk-5V5TLGH6.js} +58 -7
- package/dist/wallets/walletConnectors/{chunk-SUPFF4EQ.js → chunk-5ZTGAJ4K.js} +538 -191
- package/dist/wallets/walletConnectors/{chunk-PL56SINL.js → chunk-6GE2YBW5.js} +1 -1
- package/dist/wallets/walletConnectors/{chunk-M4SNNQU2.js → chunk-AROBVCG2.js} +29 -6
- package/dist/wallets/walletConnectors/{chunk-OTLZVWY7.js → chunk-BAKRM7LQ.js} +3 -1
- package/dist/wallets/walletConnectors/{chunk-6X2XITQP.js → chunk-BGDDDPVU.js} +3 -3
- package/dist/wallets/walletConnectors/{chunk-365TL36N.js → chunk-C3MTWYLE.js} +106 -53
- package/dist/wallets/walletConnectors/{chunk-UHVJ6AF6.js → chunk-CBXCYWLB.js} +6 -5
- package/dist/wallets/walletConnectors/{chunk-5SRSGEZR.js → chunk-DT2L5ADS.js} +35 -10
- package/dist/wallets/walletConnectors/{chunk-DKMR2ML5.js → chunk-DUEQONAP.js} +1 -1
- package/dist/wallets/walletConnectors/{chunk-ZBI7MSWF.js → chunk-EJB7HH6N.js} +7 -5
- package/dist/wallets/walletConnectors/{chunk-OTLPTGHO.js → chunk-EMFKD777.js} +4 -2
- package/dist/wallets/walletConnectors/{chunk-743DKBGG.js → chunk-F2TFFXON.js} +72 -20
- package/dist/wallets/walletConnectors/chunk-GM6AIRNT.js +71 -0
- package/dist/wallets/walletConnectors/chunk-H63QJV3U.js +84 -0
- package/dist/wallets/walletConnectors/chunk-HEZOSHLH.js +446 -0
- package/dist/wallets/walletConnectors/{chunk-GO6HUJTP.js → chunk-HJAUM3KX.js} +6 -6
- package/dist/wallets/walletConnectors/chunk-ICSPFTBY.js +246 -0
- package/dist/wallets/walletConnectors/{chunk-OMZSFUVN.js → chunk-LGFHSL7G.js} +7 -3
- package/dist/wallets/walletConnectors/{chunk-V6R6WDOQ.js → chunk-MRUBFVXX.js} +1 -1
- package/dist/wallets/walletConnectors/chunk-MZFLUT3E.js +243 -0
- package/dist/wallets/walletConnectors/chunk-N7ACKYTK.js +291 -0
- package/dist/wallets/walletConnectors/{chunk-RSR35XOZ.js → chunk-NNLRIZSK.js} +11 -7
- package/dist/wallets/walletConnectors/chunk-NWHJRPZL.js +158 -0
- package/dist/wallets/walletConnectors/{chunk-P64PMEPU.js → chunk-O77UF634.js} +66 -12
- package/dist/wallets/walletConnectors/{chunk-4CKIGJZD.js → chunk-PK5XVWRF.js} +81 -32
- package/dist/wallets/walletConnectors/{chunk-DFG3BSSC.js → chunk-PS66FDPT.js} +79 -30
- package/dist/wallets/walletConnectors/chunk-PWJLUT4Z.js +2629 -0
- package/dist/wallets/walletConnectors/chunk-QCVDHC6P.js +210 -0
- package/dist/wallets/walletConnectors/{chunk-HMIFFMGK.js → chunk-QNZQZ7IH.js} +26 -16
- package/dist/wallets/walletConnectors/chunk-RTECHRPH.js +154 -0
- package/dist/wallets/walletConnectors/{chunk-F4JUKZBB.js → chunk-RU6FIXMD.js} +3 -3
- package/dist/wallets/walletConnectors/{chunk-ZWIAZOVB.js → chunk-RUYSIXR3.js} +6 -4
- package/dist/wallets/walletConnectors/{chunk-TRFREYPH.js → chunk-S75DVWSP.js} +39 -9
- package/dist/wallets/walletConnectors/chunk-SN2BNZTO.js +739 -0
- package/dist/wallets/walletConnectors/{chunk-YPMD3ZHF.js → chunk-SRXI2XF5.js} +80 -44
- package/dist/wallets/walletConnectors/chunk-TOX35ET4.js +307 -0
- package/dist/wallets/walletConnectors/{chunk-XPZCOEQL.js → chunk-TPLIG5I7.js} +35 -7
- package/dist/wallets/walletConnectors/{chunk-TP4BDK7W.js → chunk-UVPRZEPJ.js} +5 -1
- package/dist/wallets/walletConnectors/{chunk-SORKIBWX.js → chunk-WUNGUZIQ.js} +4 -5
- package/dist/wallets/walletConnectors/{chunk-2OHHFQQ7.js → chunk-WZMAZENY.js} +3 -1
- package/dist/wallets/walletConnectors/chunk-XPOLIWQQ.js +200 -0
- package/dist/wallets/walletConnectors/{chunk-DRL2CDHT.js → chunk-YFYJ2CFB.js} +80 -44
- package/dist/wallets/walletConnectors/chunk-ZPICFPYN.js +79 -0
- package/dist/wallets/walletConnectors/index.js +67 -65
- package/package.json +1 -1
- package/dist/AbcCredentialManager-WZBF3GHF.js +0 -7
- package/dist/TalkenApiSingleton-TECFDCT4.js +0 -9
- package/dist/chunk-CUPPBGFC.js +0 -460
- package/dist/chunk-R6ZE7JAZ.js +0 -15
- package/dist/wallets/walletConnectors/chunk-2M6E3YXU.js +0 -382
- package/dist/wallets/walletConnectors/chunk-3DHUDD4U.js +0 -132
- package/dist/wallets/walletConnectors/chunk-GAJ4FJTW.js +0 -382
- package/dist/wallets/walletConnectors/chunk-R6ZE7JAZ.js +0 -15
|
@@ -0,0 +1,2629 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import {
|
|
3
|
+
resolveEvmSignType
|
|
4
|
+
} from "./chunk-OESFVVLA.js";
|
|
5
|
+
import {
|
|
6
|
+
isSigningCredentialError
|
|
7
|
+
} from "./chunk-AROBVCG2.js";
|
|
8
|
+
import {
|
|
9
|
+
toBroadcastBody
|
|
10
|
+
} from "./chunk-4UMY2AY7.js";
|
|
11
|
+
import {
|
|
12
|
+
getChainKey,
|
|
13
|
+
getExplorerTxUrl,
|
|
14
|
+
getNetworkName
|
|
15
|
+
} from "./chunk-5KPLYJOO.js";
|
|
16
|
+
import {
|
|
17
|
+
AbstractChainProvider
|
|
18
|
+
} from "./chunk-ICSPFTBY.js";
|
|
19
|
+
import {
|
|
20
|
+
ProviderErrorCode,
|
|
21
|
+
ProviderRpcError
|
|
22
|
+
} from "./chunk-YXWHHI4S.js";
|
|
23
|
+
import {
|
|
24
|
+
createLogger
|
|
25
|
+
} from "./chunk-2DFJ6LEN.js";
|
|
26
|
+
import {
|
|
27
|
+
getTalkenApiClient,
|
|
28
|
+
ownsTalkenApiStorage
|
|
29
|
+
} from "./chunk-2YCHXOLC.js";
|
|
30
|
+
import {
|
|
31
|
+
getCredentialManager
|
|
32
|
+
} from "./chunk-WUNGUZIQ.js";
|
|
33
|
+
import {
|
|
34
|
+
hexToNumber,
|
|
35
|
+
numberToHex
|
|
36
|
+
} from "./chunk-RU6FIXMD.js";
|
|
37
|
+
import {
|
|
38
|
+
TalkenApiError
|
|
39
|
+
} from "./chunk-UVPRZEPJ.js";
|
|
40
|
+
import {
|
|
41
|
+
SEND_REQUEST_TIMEOUT,
|
|
42
|
+
TALKEN_API_ENDPOINTS,
|
|
43
|
+
chainTokenBalancesPath
|
|
44
|
+
} from "./chunk-TPLIG5I7.js";
|
|
45
|
+
|
|
46
|
+
// src/wallets/walletConnectors/abcWallet/abcProvider.ts
|
|
47
|
+
import { parseGwei } from "viem";
|
|
48
|
+
|
|
49
|
+
// src/gasless/GaslessConfigSingleton.ts
|
|
50
|
+
var _gaslessConfig = null;
|
|
51
|
+
function getGaslessConfig() {
|
|
52
|
+
return _gaslessConfig;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// src/gasless/api/RelayerApi.ts
|
|
56
|
+
var RelayerApi = class {
|
|
57
|
+
async estimateFee(params) {
|
|
58
|
+
const api = getTalkenApiClient();
|
|
59
|
+
if (!api)
|
|
60
|
+
throw new Error("TalkenApiClient not initialized");
|
|
61
|
+
return api.post(
|
|
62
|
+
TALKEN_API_ENDPOINTS.RELAYER_FEE_ESTIMATE,
|
|
63
|
+
params
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
async execute(params) {
|
|
67
|
+
const api = getTalkenApiClient();
|
|
68
|
+
if (!api)
|
|
69
|
+
throw new Error("TalkenApiClient not initialized");
|
|
70
|
+
const isEip7702 = params.auth?.method === "eip7702";
|
|
71
|
+
return api.post(
|
|
72
|
+
TALKEN_API_ENDPOINTS.RELAYER_EXECUTE,
|
|
73
|
+
params,
|
|
74
|
+
{ timeout: isEip7702 ? 12e4 : 6e4 }
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
async getRelayerBalance(chainKey) {
|
|
78
|
+
const api = getTalkenApiClient();
|
|
79
|
+
if (!api)
|
|
80
|
+
throw new Error("TalkenApiClient not initialized");
|
|
81
|
+
return api.get(
|
|
82
|
+
`${TALKEN_API_ENDPOINTS.RELAYER_BALANCE}/${encodeURIComponent(chainKey)}`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Get EIP-7702 execution nonce for an address on a chain.
|
|
87
|
+
*
|
|
88
|
+
* Known issue (testnet only): The server's /wallet/execution-nonce endpoint
|
|
89
|
+
* reads the wrong storage slot on testnet due to an older delegate contract
|
|
90
|
+
* (Sepolia), causing it to always return a stale nonce of 0. Production
|
|
91
|
+
* contracts are unaffected.
|
|
92
|
+
*
|
|
93
|
+
* Previously, a client-side dev-only fallback (devNonceFallback.ts) worked
|
|
94
|
+
* around this by calling eth_getStorageAt directly via hardcoded testnet
|
|
95
|
+
* public RPCs. That fallback has been removed to eliminate external RPC
|
|
96
|
+
* dependencies. The proper fix is to update the server endpoint to read
|
|
97
|
+
* the correct storage slot (0x1). Note that the Talken API does not expose
|
|
98
|
+
* an eth_getStorageAt proxy (AbcEvmProvider treats it as UNSUPPORTED_METHOD),
|
|
99
|
+
* so there is no client-side alternative.
|
|
100
|
+
*
|
|
101
|
+
* @see https://sepolia.etherscan.io/address/0x0733De884289DA5D1349db8d09D7b14f4Ab1EF5c
|
|
102
|
+
*/
|
|
103
|
+
async getExecutionNonce(chainKey, address) {
|
|
104
|
+
const api = getTalkenApiClient();
|
|
105
|
+
if (!api)
|
|
106
|
+
throw new Error("TalkenApiClient not initialized");
|
|
107
|
+
const response = await api.get(
|
|
108
|
+
`${TALKEN_API_ENDPOINTS.EXECUTION_NONCE}/${encodeURIComponent(chainKey)}/${encodeURIComponent(address)}`
|
|
109
|
+
);
|
|
110
|
+
return response.executionNonce ?? "0";
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// src/gasless/api/ChainConfigApi.ts
|
|
115
|
+
var CACHE_TTL_MS = 60 * 60 * 1e3;
|
|
116
|
+
var BALANCE_CACHE_TTL_MS = 30 * 1e3;
|
|
117
|
+
var ChainConfigApi = class {
|
|
118
|
+
constructor() {
|
|
119
|
+
this.configCache = /* @__PURE__ */ new Map();
|
|
120
|
+
this.balanceCache = /* @__PURE__ */ new Map();
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Get runtime chain config (eip7702Delegate, token addresses, etc.).
|
|
124
|
+
* GET /chains/{chainKey}
|
|
125
|
+
*
|
|
126
|
+
* Cached for 60 minutes.
|
|
127
|
+
*/
|
|
128
|
+
async getChainConfig(chainKey) {
|
|
129
|
+
const cached = this.configCache.get(chainKey);
|
|
130
|
+
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
|
|
131
|
+
return cached.data;
|
|
132
|
+
}
|
|
133
|
+
const api = getTalkenApiClient();
|
|
134
|
+
if (!api)
|
|
135
|
+
throw new Error("TalkenApiClient not initialized");
|
|
136
|
+
const response = await api.get(
|
|
137
|
+
`${TALKEN_API_ENDPOINTS.CONFIG_CHAIN}/${encodeURIComponent(chainKey)}`
|
|
138
|
+
);
|
|
139
|
+
this.configCache.set(chainKey, {
|
|
140
|
+
data: response,
|
|
141
|
+
timestamp: Date.now()
|
|
142
|
+
});
|
|
143
|
+
return response;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Get token balances for an address on a chain.
|
|
147
|
+
* GET /chains/{chainKey}/accounts/{address}/token-balances
|
|
148
|
+
*
|
|
149
|
+
* Cached for 30 seconds.
|
|
150
|
+
*/
|
|
151
|
+
async getTokenBalances(address, chainKey) {
|
|
152
|
+
const cacheKey = `${chainKey}:${address.toLowerCase()}`;
|
|
153
|
+
const cached = this.balanceCache.get(cacheKey);
|
|
154
|
+
if (cached && Date.now() - cached.timestamp < BALANCE_CACHE_TTL_MS) {
|
|
155
|
+
return cached.data;
|
|
156
|
+
}
|
|
157
|
+
const api = getTalkenApiClient();
|
|
158
|
+
if (!api)
|
|
159
|
+
throw new Error("TalkenApiClient not initialized");
|
|
160
|
+
const response = await api.get(
|
|
161
|
+
chainTokenBalancesPath(chainKey, address)
|
|
162
|
+
);
|
|
163
|
+
const balances = Array.isArray(response) ? response : [];
|
|
164
|
+
this.balanceCache.set(cacheKey, {
|
|
165
|
+
data: balances,
|
|
166
|
+
timestamp: Date.now()
|
|
167
|
+
});
|
|
168
|
+
return balances;
|
|
169
|
+
}
|
|
170
|
+
clearCache() {
|
|
171
|
+
this.configCache.clear();
|
|
172
|
+
this.balanceCache.clear();
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// src/gasless/api/TokenCapabilityApi.ts
|
|
177
|
+
var CACHE_TTL_MS2 = 60 * 60 * 1e3;
|
|
178
|
+
var TokenCapabilityApi = class {
|
|
179
|
+
constructor() {
|
|
180
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Get EIP-3009 / ERC-2612 capabilities for a token on a chain.
|
|
184
|
+
* GET /tokens/capabilities/{chainKey}/{tokenAddress}
|
|
185
|
+
*
|
|
186
|
+
* Results are cached for 60 minutes.
|
|
187
|
+
*/
|
|
188
|
+
async getCapabilities(chainKey, tokenAddress) {
|
|
189
|
+
const cacheKey = `${chainKey}:${tokenAddress.toLowerCase()}`;
|
|
190
|
+
const cached = this.cache.get(cacheKey);
|
|
191
|
+
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS2) {
|
|
192
|
+
return cached.data;
|
|
193
|
+
}
|
|
194
|
+
const api = getTalkenApiClient();
|
|
195
|
+
if (!api)
|
|
196
|
+
throw new Error("TalkenApiClient not initialized");
|
|
197
|
+
const response = await api.get(
|
|
198
|
+
`${TALKEN_API_ENDPOINTS.TOKENS_CAPABILITIES}/${encodeURIComponent(chainKey)}/${encodeURIComponent(tokenAddress)}`
|
|
199
|
+
);
|
|
200
|
+
this.cache.set(cacheKey, {
|
|
201
|
+
data: response,
|
|
202
|
+
timestamp: Date.now()
|
|
203
|
+
});
|
|
204
|
+
return response;
|
|
205
|
+
}
|
|
206
|
+
clearCache() {
|
|
207
|
+
this.cache.clear();
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
// src/gasless/utils/feeTokenResolver.ts
|
|
212
|
+
function resolveFeeTokensFromConfig(chainConfig, chainId, gaslessConfig) {
|
|
213
|
+
const tokens = [];
|
|
214
|
+
if (chainConfig.usdt) {
|
|
215
|
+
const isBsc = chainConfig.chainKey === "bsc" || chainConfig.chainKey === "bscTestnet";
|
|
216
|
+
tokens.push({
|
|
217
|
+
symbol: "USDT",
|
|
218
|
+
address: chainConfig.usdt,
|
|
219
|
+
decimals: isBsc ? 18 : 6
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
if (chainConfig.usdc) {
|
|
223
|
+
const isBsc = chainConfig.chainKey === "bsc" || chainConfig.chainKey === "bscTestnet";
|
|
224
|
+
tokens.push({
|
|
225
|
+
symbol: "USDC",
|
|
226
|
+
address: chainConfig.usdc,
|
|
227
|
+
decimals: isBsc ? 18 : 6
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
if (gaslessConfig.projectFeeTokens) {
|
|
231
|
+
for (const pt of gaslessConfig.projectFeeTokens) {
|
|
232
|
+
if (pt.chainId !== chainId)
|
|
233
|
+
continue;
|
|
234
|
+
const exists = tokens.some(
|
|
235
|
+
(t) => t.address.toLowerCase() === pt.address.toLowerCase()
|
|
236
|
+
);
|
|
237
|
+
if (exists)
|
|
238
|
+
continue;
|
|
239
|
+
tokens.push({
|
|
240
|
+
symbol: pt.symbol,
|
|
241
|
+
address: pt.address,
|
|
242
|
+
decimals: pt.decimals,
|
|
243
|
+
icon: pt.icon,
|
|
244
|
+
isProjectToken: true
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return applyFeeTokenPriority(tokens, gaslessConfig.feeTokenPriority);
|
|
249
|
+
}
|
|
250
|
+
function applyFeeTokenPriority(tokens, priority) {
|
|
251
|
+
if (!priority || priority.length === 0)
|
|
252
|
+
return tokens;
|
|
253
|
+
const upperPriority = priority.map((s) => s.toUpperCase());
|
|
254
|
+
const result = [];
|
|
255
|
+
for (const symbol of upperPriority) {
|
|
256
|
+
const match = tokens.find((t) => t.symbol.toUpperCase() === symbol);
|
|
257
|
+
if (match)
|
|
258
|
+
result.push(match);
|
|
259
|
+
}
|
|
260
|
+
return result;
|
|
261
|
+
}
|
|
262
|
+
function selectDefaultFeeToken(feeTokens, chainId, gaslessConfig) {
|
|
263
|
+
if (feeTokens.length === 0)
|
|
264
|
+
return null;
|
|
265
|
+
const defaultAddr = gaslessConfig.defaultFeeToken?.[chainId];
|
|
266
|
+
if (defaultAddr) {
|
|
267
|
+
const match = feeTokens.find(
|
|
268
|
+
(t) => t.address.toLowerCase() === defaultAddr.toLowerCase()
|
|
269
|
+
);
|
|
270
|
+
if (match)
|
|
271
|
+
return match;
|
|
272
|
+
}
|
|
273
|
+
return feeTokens[0];
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// src/gasless/services/GaslessFeeService.ts
|
|
277
|
+
var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
278
|
+
var PRICE_UNAVAILABLE_COOLDOWN_MS = 5 * 60 * 1e3;
|
|
279
|
+
var NOT_FOUND_COOLDOWN_MS = 60 * 1e3;
|
|
280
|
+
var GaslessFeeService = class {
|
|
281
|
+
constructor(deps) {
|
|
282
|
+
/** Per-chain cooldown for 404 (unsupported chain) */
|
|
283
|
+
this.chainCooldown = /* @__PURE__ */ new Map();
|
|
284
|
+
/** Per-token cooldown for PRICE_UNAVAILABLE */
|
|
285
|
+
this.tokenCooldown = /* @__PURE__ */ new Map();
|
|
286
|
+
this.relayerApi = deps?.relayerApi ?? new RelayerApi();
|
|
287
|
+
this.tokenCapabilityApi = deps?.tokenCapabilityApi ?? new TokenCapabilityApi();
|
|
288
|
+
this.chainConfigApi = deps?.chainConfigApi ?? new ChainConfigApi();
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Estimate gasless fee for a transfer across all tiers.
|
|
292
|
+
*
|
|
293
|
+
* Iterates fee token candidates in order, tries Tier 1 first,
|
|
294
|
+
* then Tier 2, finally Tier 3 (if getRewardsBalance provided).
|
|
295
|
+
*
|
|
296
|
+
* Returns null if gasless is not possible.
|
|
297
|
+
*/
|
|
298
|
+
async estimateFee(params) {
|
|
299
|
+
const {
|
|
300
|
+
chainKey,
|
|
301
|
+
chainId,
|
|
302
|
+
tokenAddress,
|
|
303
|
+
fromAddress,
|
|
304
|
+
amount,
|
|
305
|
+
gaslessConfig,
|
|
306
|
+
supportsAuthorization = true
|
|
307
|
+
} = params;
|
|
308
|
+
const chainCooldownUntil = this.chainCooldown.get(chainKey);
|
|
309
|
+
if (chainCooldownUntil && Date.now() < chainCooldownUntil) {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
const allModes = gaslessConfig.modePreference ?? [
|
|
313
|
+
"generic",
|
|
314
|
+
"eip7702-fee",
|
|
315
|
+
"eip7702-points"
|
|
316
|
+
];
|
|
317
|
+
const modePreference = supportsAuthorization ? allModes : allModes.filter((m) => m === "generic");
|
|
318
|
+
let chainConfig;
|
|
319
|
+
let balances;
|
|
320
|
+
try {
|
|
321
|
+
[chainConfig, balances] = await Promise.all([
|
|
322
|
+
this.chainConfigApi.getChainConfig(chainKey),
|
|
323
|
+
this.chainConfigApi.getTokenBalances(fromAddress, chainKey)
|
|
324
|
+
]);
|
|
325
|
+
} catch (err) {
|
|
326
|
+
console.warn(
|
|
327
|
+
"[GaslessFeeService] Chain config/balance fetch failed:",
|
|
328
|
+
err
|
|
329
|
+
);
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
const feeTokens = resolveFeeTokensFromConfig(
|
|
333
|
+
chainConfig,
|
|
334
|
+
chainId,
|
|
335
|
+
gaslessConfig
|
|
336
|
+
);
|
|
337
|
+
if (feeTokens.length === 0)
|
|
338
|
+
return null;
|
|
339
|
+
let inputTokenCaps;
|
|
340
|
+
try {
|
|
341
|
+
inputTokenCaps = await this.tokenCapabilityApi.getCapabilities(
|
|
342
|
+
chainKey,
|
|
343
|
+
tokenAddress
|
|
344
|
+
);
|
|
345
|
+
} catch (err) {
|
|
346
|
+
console.warn("[GaslessFeeService] Token capability fetch failed:", err);
|
|
347
|
+
inputTokenCaps = null;
|
|
348
|
+
}
|
|
349
|
+
let eip7702FeeCandidate = null;
|
|
350
|
+
for (const feeToken of feeTokens) {
|
|
351
|
+
const tokenCooldownUntil = this.tokenCooldown.get(
|
|
352
|
+
feeToken.symbol.toUpperCase()
|
|
353
|
+
);
|
|
354
|
+
if (tokenCooldownUntil && Date.now() < tokenCooldownUntil) {
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
let feeEstimateRaw;
|
|
358
|
+
try {
|
|
359
|
+
feeEstimateRaw = await this.relayerApi.estimateFee({
|
|
360
|
+
chainKey,
|
|
361
|
+
user: fromAddress,
|
|
362
|
+
tokenIn: tokenAddress,
|
|
363
|
+
amountIn: amount,
|
|
364
|
+
tokenOut: ZERO_ADDRESS,
|
|
365
|
+
minAmountOut: "0",
|
|
366
|
+
deadline: Math.floor(Date.now() / 1e3) + 20 * 60,
|
|
367
|
+
dexType: 2,
|
|
368
|
+
dexData: "0x",
|
|
369
|
+
feeToken: feeToken.symbol
|
|
370
|
+
});
|
|
371
|
+
} catch (err) {
|
|
372
|
+
const status = err?.statusCode ?? err?.response?.status;
|
|
373
|
+
const errCode = err?.code ?? err?.response?.data?.code;
|
|
374
|
+
if (status === 404) {
|
|
375
|
+
this.chainCooldown.set(chainKey, Date.now() + NOT_FOUND_COOLDOWN_MS);
|
|
376
|
+
break;
|
|
377
|
+
}
|
|
378
|
+
if (errCode === "PRICE_UNAVAILABLE" || status === 400 && String(err).includes("price")) {
|
|
379
|
+
this.tokenCooldown.set(
|
|
380
|
+
feeToken.symbol.toUpperCase(),
|
|
381
|
+
Date.now() + PRICE_UNAVAILABLE_COOLDOWN_MS
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
console.warn(
|
|
385
|
+
`[GaslessFeeService] Fee estimate failed for ${feeToken.symbol}:`,
|
|
386
|
+
err
|
|
387
|
+
);
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
const feeAmountRaw = feeEstimateRaw.feeInToken;
|
|
391
|
+
const feeAmountBig = BigInt(feeAmountRaw);
|
|
392
|
+
const isSameTokenAsInput = feeToken.address.toLowerCase() === tokenAddress.toLowerCase();
|
|
393
|
+
const formattedFee = this.formatFee(feeAmountRaw, feeToken.decimals);
|
|
394
|
+
const feeTokenBalance = this.getBalance(balances, feeToken.address);
|
|
395
|
+
const inputBalance = this.getBalance(balances, tokenAddress);
|
|
396
|
+
if (modePreference.includes("generic")) {
|
|
397
|
+
let canGeneric = false;
|
|
398
|
+
if (isSameTokenAsInput) {
|
|
399
|
+
canGeneric = !!(inputTokenCaps?.supportsEIP3009 || inputTokenCaps?.supportsERC2612);
|
|
400
|
+
if (canGeneric && BigInt(amount) <= feeAmountBig)
|
|
401
|
+
canGeneric = false;
|
|
402
|
+
} else if (inputTokenCaps?.supportsEIP3009 || inputTokenCaps?.supportsERC2612) {
|
|
403
|
+
try {
|
|
404
|
+
const feeCaps = await this.tokenCapabilityApi.getCapabilities(
|
|
405
|
+
chainKey,
|
|
406
|
+
feeToken.address
|
|
407
|
+
);
|
|
408
|
+
canGeneric = !!(feeCaps.supportsEIP3009 || feeCaps.supportsERC2612);
|
|
409
|
+
} catch {
|
|
410
|
+
canGeneric = false;
|
|
411
|
+
}
|
|
412
|
+
if (canGeneric && feeTokenBalance < feeAmountBig)
|
|
413
|
+
canGeneric = false;
|
|
414
|
+
}
|
|
415
|
+
if (canGeneric) {
|
|
416
|
+
return this.buildEstimate(
|
|
417
|
+
feeToken,
|
|
418
|
+
formattedFee,
|
|
419
|
+
feeAmountRaw,
|
|
420
|
+
"generic"
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
if (modePreference.includes("eip7702-fee") && chainConfig.eip7702Delegate && !eip7702FeeCandidate) {
|
|
425
|
+
let canEip7702Fee = true;
|
|
426
|
+
if (isSameTokenAsInput) {
|
|
427
|
+
if (inputBalance < BigInt(amount) + feeAmountBig)
|
|
428
|
+
canEip7702Fee = false;
|
|
429
|
+
} else {
|
|
430
|
+
if (feeTokenBalance < feeAmountBig)
|
|
431
|
+
canEip7702Fee = false;
|
|
432
|
+
}
|
|
433
|
+
if (canEip7702Fee) {
|
|
434
|
+
eip7702FeeCandidate = this.buildEstimate(
|
|
435
|
+
feeToken,
|
|
436
|
+
formattedFee,
|
|
437
|
+
feeAmountRaw,
|
|
438
|
+
"eip7702-fee"
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (eip7702FeeCandidate)
|
|
444
|
+
return eip7702FeeCandidate;
|
|
445
|
+
if (modePreference.includes("eip7702-points") && chainConfig.eip7702Delegate && gaslessConfig.getRewardsBalance) {
|
|
446
|
+
const pointsFeeToken = feeTokens.find((t) => t.isProjectToken) ?? selectDefaultFeeToken(feeTokens, chainId, gaslessConfig);
|
|
447
|
+
if (pointsFeeToken) {
|
|
448
|
+
const pointsCooldownUntil = this.tokenCooldown.get(
|
|
449
|
+
pointsFeeToken.symbol.toUpperCase()
|
|
450
|
+
);
|
|
451
|
+
if (pointsCooldownUntil && Date.now() < pointsCooldownUntil) {
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
try {
|
|
455
|
+
const rewards = await gaslessConfig.getRewardsBalance({
|
|
456
|
+
address: fromAddress,
|
|
457
|
+
chainId
|
|
458
|
+
});
|
|
459
|
+
if (!rewards || BigInt(rewards.balance) <= BigInt(0)) {
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
let feeEstimateRaw;
|
|
463
|
+
try {
|
|
464
|
+
feeEstimateRaw = await this.relayerApi.estimateFee({
|
|
465
|
+
chainKey,
|
|
466
|
+
user: fromAddress,
|
|
467
|
+
tokenIn: tokenAddress,
|
|
468
|
+
amountIn: amount,
|
|
469
|
+
tokenOut: ZERO_ADDRESS,
|
|
470
|
+
minAmountOut: "0",
|
|
471
|
+
deadline: Math.floor(Date.now() / 1e3) + 20 * 60,
|
|
472
|
+
dexType: 2,
|
|
473
|
+
dexData: "0x",
|
|
474
|
+
feeToken: pointsFeeToken.symbol
|
|
475
|
+
});
|
|
476
|
+
} catch (feeErr) {
|
|
477
|
+
const feeStatus = feeErr?.statusCode ?? feeErr?.response?.status;
|
|
478
|
+
const feeErrCode = feeErr?.code ?? feeErr?.response?.data?.code;
|
|
479
|
+
if (feeErrCode === "PRICE_UNAVAILABLE" || feeStatus === 400 && String(feeErr).includes("price")) {
|
|
480
|
+
this.tokenCooldown.set(
|
|
481
|
+
pointsFeeToken.symbol.toUpperCase(),
|
|
482
|
+
Date.now() + PRICE_UNAVAILABLE_COOLDOWN_MS
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
throw feeErr;
|
|
486
|
+
}
|
|
487
|
+
const rewardsInSmallest = BigInt(rewards.balance) * BigInt(10) ** BigInt(pointsFeeToken.decimals);
|
|
488
|
+
if (rewardsInSmallest < BigInt(feeEstimateRaw.feeInToken)) {
|
|
489
|
+
return null;
|
|
490
|
+
}
|
|
491
|
+
const formattedFee = this.formatFee(
|
|
492
|
+
feeEstimateRaw.feeInToken,
|
|
493
|
+
pointsFeeToken.decimals
|
|
494
|
+
);
|
|
495
|
+
return this.buildEstimate(
|
|
496
|
+
pointsFeeToken,
|
|
497
|
+
formattedFee,
|
|
498
|
+
feeEstimateRaw.feeInToken,
|
|
499
|
+
"eip7702-points"
|
|
500
|
+
);
|
|
501
|
+
} catch (err) {
|
|
502
|
+
console.warn(
|
|
503
|
+
"[GaslessFeeService] Points (Tier 3) estimation failed:",
|
|
504
|
+
err
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return null;
|
|
510
|
+
}
|
|
511
|
+
/** Access the chain config API for external use */
|
|
512
|
+
getChainConfigApi() {
|
|
513
|
+
return this.chainConfigApi;
|
|
514
|
+
}
|
|
515
|
+
/** Access the relayer API for shared use */
|
|
516
|
+
getRelayerApi() {
|
|
517
|
+
return this.relayerApi;
|
|
518
|
+
}
|
|
519
|
+
/** Clear all API caches (call on disconnect or chain switch) */
|
|
520
|
+
clearCache() {
|
|
521
|
+
this.chainConfigApi.clearCache();
|
|
522
|
+
this.tokenCapabilityApi.clearCache();
|
|
523
|
+
this.chainCooldown.clear();
|
|
524
|
+
this.tokenCooldown.clear();
|
|
525
|
+
}
|
|
526
|
+
getBalance(balances, tokenAddress) {
|
|
527
|
+
const entry = balances.find(
|
|
528
|
+
(b) => b.address?.toLowerCase() === tokenAddress.toLowerCase()
|
|
529
|
+
);
|
|
530
|
+
if (!entry?.balance)
|
|
531
|
+
return BigInt(0);
|
|
532
|
+
try {
|
|
533
|
+
return BigInt(entry.balance);
|
|
534
|
+
} catch {
|
|
535
|
+
return BigInt(0);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
formatFee(raw, decimals) {
|
|
539
|
+
try {
|
|
540
|
+
const value = BigInt(raw);
|
|
541
|
+
const divisor = BigInt(10) ** BigInt(decimals);
|
|
542
|
+
const whole = value / divisor;
|
|
543
|
+
const remainder = value % divisor;
|
|
544
|
+
const fractional = remainder.toString().padStart(decimals, "0").slice(0, Math.min(decimals, 6)).replace(/0+$/, "");
|
|
545
|
+
return fractional ? `${whole}.${fractional}` : whole.toString();
|
|
546
|
+
} catch {
|
|
547
|
+
return "0";
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
buildEstimate(feeToken, feeAmount, feeAmountRaw, gaslessMode) {
|
|
551
|
+
return { feeToken, feeAmount, feeAmountRaw, gaslessMode };
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
var _sharedInstance = null;
|
|
555
|
+
function getSharedGaslessFeeService() {
|
|
556
|
+
if (!_sharedInstance) {
|
|
557
|
+
_sharedInstance = new GaslessFeeService();
|
|
558
|
+
}
|
|
559
|
+
return _sharedInstance;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// src/gasless/services/GaslessTransferService.ts
|
|
563
|
+
import { encodeFunctionData, erc20Abi, isAddress as isAddress2 } from "viem";
|
|
564
|
+
|
|
565
|
+
// src/gasless/utils/revokeDelegation.ts
|
|
566
|
+
import {
|
|
567
|
+
isAddress,
|
|
568
|
+
keccak256,
|
|
569
|
+
recoverAddress,
|
|
570
|
+
toHex,
|
|
571
|
+
toRlp
|
|
572
|
+
} from "viem";
|
|
573
|
+
var ZERO_ADDRESS2 = "0x0000000000000000000000000000000000000000";
|
|
574
|
+
var DEFAULT_GAS_LIMIT = BigInt(1e5);
|
|
575
|
+
var DEFAULT_MAX_FEE = BigInt(3e10);
|
|
576
|
+
var DEFAULT_MAX_PRIORITY_FEE = BigInt(15e8);
|
|
577
|
+
function rlpUint(n) {
|
|
578
|
+
if (n === 0 || n === BigInt(0))
|
|
579
|
+
return "0x";
|
|
580
|
+
return toHex(BigInt(n));
|
|
581
|
+
}
|
|
582
|
+
function stripLeadingZeroBytes(hex) {
|
|
583
|
+
const stripped = hex.replace(/^0x0*/, "0x");
|
|
584
|
+
return stripped === "0x" ? "0x00" : stripped;
|
|
585
|
+
}
|
|
586
|
+
async function recoverYParity(hash, r, s, expectedAddress) {
|
|
587
|
+
for (const yp of [0, 1]) {
|
|
588
|
+
try {
|
|
589
|
+
const recovered = await recoverAddress({
|
|
590
|
+
hash,
|
|
591
|
+
signature: { r, s, yParity: yp }
|
|
592
|
+
});
|
|
593
|
+
if (recovered.toLowerCase() === expectedAddress.toLowerCase())
|
|
594
|
+
return yp;
|
|
595
|
+
} catch {
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
throw new Error("Failed to recover yParity from tx signature");
|
|
599
|
+
}
|
|
600
|
+
async function sendRevokeTx(userAddress, chainKey, chainId, assertOrigin) {
|
|
601
|
+
assertOrigin?.();
|
|
602
|
+
const api = getTalkenApiClient();
|
|
603
|
+
if (!api)
|
|
604
|
+
throw new Error("TalkenApiClient not initialized");
|
|
605
|
+
const revision = api.getSessionRevision();
|
|
606
|
+
const assertCurrent = () => {
|
|
607
|
+
assertOrigin?.();
|
|
608
|
+
if (getTalkenApiClient() !== api || api.getSessionRevision() !== revision || !ownsTalkenApiStorage(api))
|
|
609
|
+
throw new Error("AUTH_SESSION_CHANGED");
|
|
610
|
+
if (api.isAccessKeyMode() && api.getAuthenticatedWalletSession()?.wallets.evm !== userAddress.toLowerCase())
|
|
611
|
+
throw new Error("AUTH_SESSION_CHANGED");
|
|
612
|
+
};
|
|
613
|
+
assertCurrent();
|
|
614
|
+
const credentialManager = getCredentialManager();
|
|
615
|
+
const pinHash = credentialManager.getPinHash() || "";
|
|
616
|
+
const email = api.isAccessKeyMode() ? api.getAuthenticatedWalletSession()?.user.email ?? void 0 : credentialManager.getEmail() ?? void 0;
|
|
617
|
+
const network = getNetworkName(chainId);
|
|
618
|
+
const nonceResult = await api.evm.getNonce(network, userAddress);
|
|
619
|
+
assertCurrent();
|
|
620
|
+
const nonceRaw = nonceResult?.data?.result ?? nonceResult?.nonce ?? nonceResult?.result ?? nonceResult;
|
|
621
|
+
const currentNonce = Number(nonceRaw);
|
|
622
|
+
if (!Number.isFinite(currentNonce)) {
|
|
623
|
+
throw new Error("Failed to resolve wallet nonce for revoke");
|
|
624
|
+
}
|
|
625
|
+
const authNonce = currentNonce + 1;
|
|
626
|
+
const authResult = await api.evm.signAuthorization({
|
|
627
|
+
network,
|
|
628
|
+
authorization: {
|
|
629
|
+
chainId,
|
|
630
|
+
address: ZERO_ADDRESS2,
|
|
631
|
+
nonce: String(authNonce)
|
|
632
|
+
},
|
|
633
|
+
pin: pinHash,
|
|
634
|
+
...email && { email }
|
|
635
|
+
});
|
|
636
|
+
assertCurrent();
|
|
637
|
+
const auth = authResult?.authorization ?? authResult;
|
|
638
|
+
if (!auth?.r || !auth?.s) {
|
|
639
|
+
throw new Error("signAuthorization returned empty r/s for revoke");
|
|
640
|
+
}
|
|
641
|
+
const authYParity = Number(auth.yParity ?? auth.v ?? 0);
|
|
642
|
+
const normalizedYParity = authYParity === 27 ? 0 : authYParity === 28 ? 1 : authYParity;
|
|
643
|
+
const authR = stripLeadingZeroBytes(auth.r);
|
|
644
|
+
const authS = stripLeadingZeroBytes(auth.s);
|
|
645
|
+
let maxFeePerGas = DEFAULT_MAX_FEE;
|
|
646
|
+
let maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE;
|
|
647
|
+
try {
|
|
648
|
+
const suggested = await api.evm.getGasSuggested(network);
|
|
649
|
+
assertCurrent();
|
|
650
|
+
if (suggested?.high) {
|
|
651
|
+
maxPriorityFeePerGas = BigInt(
|
|
652
|
+
Math.round(Number(suggested.high.suggestedMaxPriorityFeePerGas) * 1e9)
|
|
653
|
+
);
|
|
654
|
+
maxFeePerGas = BigInt(
|
|
655
|
+
Math.round(Number(suggested.high.suggestedMaxFeePerGas) * 1e9)
|
|
656
|
+
);
|
|
657
|
+
}
|
|
658
|
+
} catch {
|
|
659
|
+
assertCurrent();
|
|
660
|
+
}
|
|
661
|
+
const authEntry = [
|
|
662
|
+
rlpUint(chainId),
|
|
663
|
+
ZERO_ADDRESS2,
|
|
664
|
+
rlpUint(authNonce),
|
|
665
|
+
normalizedYParity ? "0x01" : "0x",
|
|
666
|
+
authR,
|
|
667
|
+
authS
|
|
668
|
+
];
|
|
669
|
+
const unsignedFields = [
|
|
670
|
+
rlpUint(chainId),
|
|
671
|
+
rlpUint(currentNonce),
|
|
672
|
+
rlpUint(maxPriorityFeePerGas),
|
|
673
|
+
rlpUint(maxFeePerGas),
|
|
674
|
+
rlpUint(DEFAULT_GAS_LIMIT),
|
|
675
|
+
userAddress,
|
|
676
|
+
"0x",
|
|
677
|
+
// value
|
|
678
|
+
"0x",
|
|
679
|
+
// data
|
|
680
|
+
[],
|
|
681
|
+
// accessList
|
|
682
|
+
[authEntry]
|
|
683
|
+
// authorizationList
|
|
684
|
+
];
|
|
685
|
+
const signingPayload = `0x04${toRlp(unsignedFields).slice(2)}`;
|
|
686
|
+
const signingHash = keccak256(signingPayload);
|
|
687
|
+
const signResult = await api.bitcoin.signHash({
|
|
688
|
+
hash: signingHash,
|
|
689
|
+
pin: pinHash,
|
|
690
|
+
...network && { network },
|
|
691
|
+
...email && { email }
|
|
692
|
+
});
|
|
693
|
+
assertCurrent();
|
|
694
|
+
const signStr = signResult?.signstr ?? signResult?.signature ?? "";
|
|
695
|
+
if (!signStr)
|
|
696
|
+
throw new Error("signHash returned empty signature");
|
|
697
|
+
let txRRaw;
|
|
698
|
+
let txSRaw;
|
|
699
|
+
try {
|
|
700
|
+
const parsed = JSON.parse(signStr);
|
|
701
|
+
const sig = parsed.sig_list?.[0];
|
|
702
|
+
if (!sig?.r || !sig?.s)
|
|
703
|
+
throw new Error("Missing r/s in sig_list");
|
|
704
|
+
txRRaw = sig.r.startsWith("0x") ? sig.r : `0x${sig.r}`;
|
|
705
|
+
txSRaw = sig.s.startsWith("0x") ? sig.s : `0x${sig.s}`;
|
|
706
|
+
} catch (_parseErr) {
|
|
707
|
+
const sigHex = signStr.startsWith("0x") ? signStr.slice(2) : signStr;
|
|
708
|
+
if (sigHex.length < 128)
|
|
709
|
+
throw new Error(`signHash response too short: ${sigHex.length}`);
|
|
710
|
+
txRRaw = `0x${sigHex.slice(0, 64)}`;
|
|
711
|
+
txSRaw = `0x${sigHex.slice(64, 128)}`;
|
|
712
|
+
}
|
|
713
|
+
const txR = stripLeadingZeroBytes(txRRaw);
|
|
714
|
+
const txS = stripLeadingZeroBytes(txSRaw);
|
|
715
|
+
const txYParity = await recoverYParity(
|
|
716
|
+
signingHash,
|
|
717
|
+
txRRaw,
|
|
718
|
+
txSRaw,
|
|
719
|
+
userAddress
|
|
720
|
+
);
|
|
721
|
+
assertCurrent();
|
|
722
|
+
const signedFields = [...unsignedFields, txYParity ? "0x01" : "0x", txR, txS];
|
|
723
|
+
const signedTx = `0x04${toRlp(signedFields).slice(2)}`;
|
|
724
|
+
const { txHash } = await api.post(
|
|
725
|
+
TALKEN_API_ENDPOINTS.EXECUTE_BROADCAST,
|
|
726
|
+
toBroadcastBody(chainKey, signedTx),
|
|
727
|
+
{ timeout: SEND_REQUEST_TIMEOUT }
|
|
728
|
+
);
|
|
729
|
+
assertCurrent();
|
|
730
|
+
console.log(`[RevokeDelegation] Revoke tx broadcast: ${txHash}`);
|
|
731
|
+
return { txHash };
|
|
732
|
+
}
|
|
733
|
+
function unsupportedRevoke(message) {
|
|
734
|
+
return new TalkenApiError("EXTERNAL_REVOKE_UNSUPPORTED", message, 400);
|
|
735
|
+
}
|
|
736
|
+
function unsupportedAuthorization(error) {
|
|
737
|
+
let current = error;
|
|
738
|
+
for (let depth = 0; current && typeof current === "object" && depth < 5; depth++) {
|
|
739
|
+
const value = current;
|
|
740
|
+
if (value.name === "AccountTypeNotSupportedError" || value.name === "MethodNotSupportedRpcError" || value.name === "MethodNotFoundRpcError" || value.code === -32601 || value.code === 4200)
|
|
741
|
+
return true;
|
|
742
|
+
current = value.cause;
|
|
743
|
+
}
|
|
744
|
+
return false;
|
|
745
|
+
}
|
|
746
|
+
function normalizeRevokeRejection(error) {
|
|
747
|
+
const topCode = error?.code;
|
|
748
|
+
if (topCode === 4001 || topCode === "AUTH_SESSION_CHANGED" || topCode === "AUTH_SESSION_UNBOUND")
|
|
749
|
+
return error;
|
|
750
|
+
let current = error;
|
|
751
|
+
let rejected = false;
|
|
752
|
+
for (let depth = 0; current && typeof current === "object" && depth < 5; depth++) {
|
|
753
|
+
const value = current;
|
|
754
|
+
if (value.possibleTxHash || value.txHash || value.transactionHash || value.details?.broadcast === true || value.details?.broadcast === "unknown")
|
|
755
|
+
return error;
|
|
756
|
+
if (value.code === 4001)
|
|
757
|
+
rejected = true;
|
|
758
|
+
current = value.cause;
|
|
759
|
+
}
|
|
760
|
+
return rejected ? Object.assign(new Error("User rejected the external revoke request."), {
|
|
761
|
+
code: 4001,
|
|
762
|
+
cause: error
|
|
763
|
+
}) : error;
|
|
764
|
+
}
|
|
765
|
+
async function sendRevokeViaWalletClient(walletClient, chainId, userAddress) {
|
|
766
|
+
if (!walletClient || typeof walletClient.assertSessionCurrent !== "function")
|
|
767
|
+
throw unsupportedRevoke(
|
|
768
|
+
"External revoke requires an originating account and network guard."
|
|
769
|
+
);
|
|
770
|
+
const assertCurrent = () => walletClient.assertSessionCurrent();
|
|
771
|
+
assertCurrent();
|
|
772
|
+
if (typeof walletClient.getTransactionCount !== "function" || typeof walletClient.signAuthorization !== "function" || typeof walletClient.sendTransaction !== "function" || walletClient.waitForTransactionReceipt !== void 0 && typeof walletClient.waitForTransactionReceipt !== "function")
|
|
773
|
+
throw unsupportedRevoke(
|
|
774
|
+
"External revoke requires pending nonce, authorization signing and transaction capabilities."
|
|
775
|
+
);
|
|
776
|
+
if (!isAddress(userAddress))
|
|
777
|
+
throw new Error(`Invalid address for revoke: ${userAddress}`);
|
|
778
|
+
if (!Number.isSafeInteger(chainId) || chainId <= 0)
|
|
779
|
+
throw unsupportedRevoke(
|
|
780
|
+
"External revoke requires an explicit valid chain."
|
|
781
|
+
);
|
|
782
|
+
const guarded = async (operation) => {
|
|
783
|
+
assertCurrent();
|
|
784
|
+
try {
|
|
785
|
+
const result = await operation();
|
|
786
|
+
assertCurrent();
|
|
787
|
+
return result;
|
|
788
|
+
} catch (error) {
|
|
789
|
+
assertCurrent();
|
|
790
|
+
throw error;
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
const nonce = await guarded(
|
|
794
|
+
() => walletClient.getTransactionCount({
|
|
795
|
+
address: userAddress,
|
|
796
|
+
blockTag: "pending"
|
|
797
|
+
})
|
|
798
|
+
);
|
|
799
|
+
if (!Number.isSafeInteger(nonce) || nonce < 0 || nonce >= Number.MAX_SAFE_INTEGER)
|
|
800
|
+
throw unsupportedRevoke(
|
|
801
|
+
"External revoke could not prepare a safe pending nonce."
|
|
802
|
+
);
|
|
803
|
+
let raw;
|
|
804
|
+
try {
|
|
805
|
+
raw = await guarded(
|
|
806
|
+
() => walletClient.signAuthorization({
|
|
807
|
+
contractAddress: ZERO_ADDRESS2,
|
|
808
|
+
chainId,
|
|
809
|
+
nonce: nonce + 1,
|
|
810
|
+
executor: "self"
|
|
811
|
+
})
|
|
812
|
+
);
|
|
813
|
+
} catch (error) {
|
|
814
|
+
const refusal = normalizeRevokeRejection(error);
|
|
815
|
+
if (refusal !== error)
|
|
816
|
+
throw refusal;
|
|
817
|
+
if (["AUTH_SESSION_CHANGED", "AUTH_SESSION_UNBOUND", 4001].includes(
|
|
818
|
+
error?.code ?? ""
|
|
819
|
+
))
|
|
820
|
+
throw error;
|
|
821
|
+
if (unsupportedAuthorization(error))
|
|
822
|
+
throw unsupportedRevoke(
|
|
823
|
+
"This wallet cannot sign an EIP-7702 revoke authorization."
|
|
824
|
+
);
|
|
825
|
+
throw error;
|
|
826
|
+
}
|
|
827
|
+
const signed = raw;
|
|
828
|
+
const parity = signed?.yParity ?? (signed?.v === BigInt(0) || signed?.v === 0 || signed?.v === BigInt(27) || signed?.v === 27 ? 0 : signed?.v === BigInt(1) || signed?.v === 1 || signed?.v === BigInt(28) || signed?.v === 28 ? 1 : signed?.v);
|
|
829
|
+
if (!signed || signed.address !== ZERO_ADDRESS2 || signed.chainId !== chainId || signed.nonce !== nonce + 1 || typeof signed.r !== "string" || !/^0x[0-9a-fA-F]{1,64}$/.test(signed.r) || typeof signed.s !== "string" || !/^0x[0-9a-fA-F]{1,64}$/.test(signed.s) || parity !== 0 && parity !== 1)
|
|
830
|
+
throw unsupportedRevoke(
|
|
831
|
+
"The wallet returned an invalid EIP-7702 revoke authorization."
|
|
832
|
+
);
|
|
833
|
+
const authorization = {
|
|
834
|
+
address: ZERO_ADDRESS2,
|
|
835
|
+
chainId,
|
|
836
|
+
nonce: nonce + 1,
|
|
837
|
+
r: signed.r,
|
|
838
|
+
s: signed.s,
|
|
839
|
+
yParity: parity
|
|
840
|
+
};
|
|
841
|
+
let txHash;
|
|
842
|
+
try {
|
|
843
|
+
txHash = await guarded(
|
|
844
|
+
() => walletClient.sendTransaction({
|
|
845
|
+
authorizationList: [authorization],
|
|
846
|
+
nonce,
|
|
847
|
+
to: userAddress,
|
|
848
|
+
value: BigInt(0)
|
|
849
|
+
})
|
|
850
|
+
);
|
|
851
|
+
} catch (error) {
|
|
852
|
+
throw normalizeRevokeRejection(error);
|
|
853
|
+
}
|
|
854
|
+
if (walletClient.waitForTransactionReceipt) {
|
|
855
|
+
const receipt = await guarded(
|
|
856
|
+
() => walletClient.waitForTransactionReceipt({ hash: txHash })
|
|
857
|
+
);
|
|
858
|
+
if (receipt.status === "reverted")
|
|
859
|
+
throw new Error(`Revoke transaction reverted: ${txHash}`);
|
|
860
|
+
}
|
|
861
|
+
return { txHash };
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// src/gasless/utils/delegationGuard.ts
|
|
865
|
+
var logger = createLogger("DelegationGuard");
|
|
866
|
+
var EIP7702_CODE_PREFIX = "0xef0100";
|
|
867
|
+
var POLL_INTERVAL_MS = 2e3;
|
|
868
|
+
var POLL_TIMEOUT_MS = 3e4;
|
|
869
|
+
var _locks = /* @__PURE__ */ new Map();
|
|
870
|
+
function lockKey(chainKey, address) {
|
|
871
|
+
return `${chainKey}:${address.toLowerCase()}`;
|
|
872
|
+
}
|
|
873
|
+
async function checkDelegation(chainKey, address, delegationClient, assertCurrent) {
|
|
874
|
+
if (!delegationClient || typeof delegationClient.readCode !== "function")
|
|
875
|
+
throw new TalkenApiError(
|
|
876
|
+
"DELEGATION_CONTEXT_REQUIRED",
|
|
877
|
+
"An originating wallet delegation client is required.",
|
|
878
|
+
401
|
|
879
|
+
);
|
|
880
|
+
assertCurrent?.();
|
|
881
|
+
let rawCode;
|
|
882
|
+
try {
|
|
883
|
+
rawCode = await delegationClient.readCode(chainKey, address);
|
|
884
|
+
} catch (error) {
|
|
885
|
+
assertCurrent?.();
|
|
886
|
+
throw error;
|
|
887
|
+
}
|
|
888
|
+
assertCurrent?.();
|
|
889
|
+
const code = String(rawCode).toLowerCase();
|
|
890
|
+
const hasDelegation = code.startsWith(EIP7702_CODE_PREFIX) && code.length >= EIP7702_CODE_PREFIX.length + 40;
|
|
891
|
+
return {
|
|
892
|
+
hasDelegation,
|
|
893
|
+
code,
|
|
894
|
+
delegateAddress: hasDelegation ? `0x${code.slice(EIP7702_CODE_PREFIX.length, EIP7702_CODE_PREFIX.length + 40)}` : ""
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
async function ensureDelegationCleared(chainKey, chainId, address, options) {
|
|
898
|
+
const delegationClient = options?.delegationClient;
|
|
899
|
+
if (!delegationClient)
|
|
900
|
+
throw new TalkenApiError(
|
|
901
|
+
"DELEGATION_CONTEXT_REQUIRED",
|
|
902
|
+
"An originating wallet delegation client is required.",
|
|
903
|
+
401
|
|
904
|
+
);
|
|
905
|
+
const assertCurrent = () => options?.assertSessionCurrent?.();
|
|
906
|
+
const readDelegation = () => checkDelegation(chainKey, address, delegationClient, assertCurrent);
|
|
907
|
+
assertCurrent();
|
|
908
|
+
const key = lockKey(chainKey, address);
|
|
909
|
+
const existing = _locks.get(key);
|
|
910
|
+
if (existing) {
|
|
911
|
+
try {
|
|
912
|
+
await existing;
|
|
913
|
+
assertCurrent();
|
|
914
|
+
return;
|
|
915
|
+
} catch {
|
|
916
|
+
assertCurrent();
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
const check = async () => {
|
|
920
|
+
assertCurrent();
|
|
921
|
+
const initial = await readDelegation();
|
|
922
|
+
assertCurrent();
|
|
923
|
+
if (!initial.hasDelegation)
|
|
924
|
+
return;
|
|
925
|
+
logger.warn(
|
|
926
|
+
`Stale delegation detected on ${chainKey}: delegate=${initial.delegateAddress}. Sending revoke tx...`
|
|
927
|
+
);
|
|
928
|
+
try {
|
|
929
|
+
const { txHash } = options?.walletClient ? await sendRevokeViaWalletClient(
|
|
930
|
+
options.walletClient,
|
|
931
|
+
chainId,
|
|
932
|
+
address
|
|
933
|
+
) : delegationClient.revoke ? await delegationClient.revoke(chainKey, chainId, address) : (() => {
|
|
934
|
+
throw new TalkenApiError(
|
|
935
|
+
"EXTERNAL_REVOKE_UNSUPPORTED",
|
|
936
|
+
"This wallet has no delegation revoke capability.",
|
|
937
|
+
400
|
|
938
|
+
);
|
|
939
|
+
})();
|
|
940
|
+
assertCurrent();
|
|
941
|
+
logger.info(`Revoke tx sent: ${txHash}. Polling for clearance...`);
|
|
942
|
+
} catch (revokeErr) {
|
|
943
|
+
assertCurrent();
|
|
944
|
+
if (["AUTH_SESSION_CHANGED", "EXTERNAL_REVOKE_UNSUPPORTED"].includes(
|
|
945
|
+
revokeErr?.code ?? ""
|
|
946
|
+
))
|
|
947
|
+
throw revokeErr;
|
|
948
|
+
if (revokeErr && typeof revokeErr === "object" && "code" in revokeErr && revokeErr.code === 4001) {
|
|
949
|
+
throw revokeErr;
|
|
950
|
+
}
|
|
951
|
+
logger.warn("Revoke tx failed, falling back to passive wait:", revokeErr);
|
|
952
|
+
}
|
|
953
|
+
const deadline = Date.now() + POLL_TIMEOUT_MS;
|
|
954
|
+
while (Date.now() < deadline) {
|
|
955
|
+
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
|
|
956
|
+
assertCurrent();
|
|
957
|
+
const current = await readDelegation();
|
|
958
|
+
assertCurrent();
|
|
959
|
+
if (!current.hasDelegation) {
|
|
960
|
+
logger.info("Delegation cleared");
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
const message = "Previous transaction delegation is still active. Please wait a moment and try again.";
|
|
965
|
+
assertCurrent();
|
|
966
|
+
if (options?.onDelegationError) {
|
|
967
|
+
options.onDelegationError({
|
|
968
|
+
chainId,
|
|
969
|
+
address,
|
|
970
|
+
delegateAddress: initial.delegateAddress,
|
|
971
|
+
message
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
throw new Error(message);
|
|
975
|
+
};
|
|
976
|
+
const promise = check().finally(() => {
|
|
977
|
+
if (_locks.get(key) === promise)
|
|
978
|
+
_locks.delete(key);
|
|
979
|
+
});
|
|
980
|
+
_locks.set(key, promise);
|
|
981
|
+
return promise;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
// src/gasless/services/Eip7702Service.ts
|
|
985
|
+
import { encodeAbiParameters, keccak256 as keccak2562, parseAbiParameters } from "viem";
|
|
986
|
+
var Eip7702Service = class {
|
|
987
|
+
constructor(deps) {
|
|
988
|
+
this.chainConfigApi = deps.chainConfigApi ?? new ChainConfigApi();
|
|
989
|
+
this.relayerApi = deps.relayerApi ?? new RelayerApi();
|
|
990
|
+
this.signer = deps.signer;
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Pre-flight check: detect and wait for stale delegation to clear.
|
|
994
|
+
* If a previous relay's revoke tx is still pending, waits for it
|
|
995
|
+
* to be mined before proceeding (prevents nonce collision).
|
|
996
|
+
*/
|
|
997
|
+
async preflight(chainKey, chainId, address, options) {
|
|
998
|
+
try {
|
|
999
|
+
await ensureDelegationCleared(chainKey, chainId, address, {
|
|
1000
|
+
...options,
|
|
1001
|
+
delegationClient: options?.delegationClient ?? this.signer.getDelegationClient?.(),
|
|
1002
|
+
assertSessionCurrent: () => {
|
|
1003
|
+
this.signer.assertSessionCurrent?.();
|
|
1004
|
+
options?.assertSessionCurrent?.();
|
|
1005
|
+
}
|
|
1006
|
+
});
|
|
1007
|
+
} catch (error) {
|
|
1008
|
+
console.warn(
|
|
1009
|
+
"[Eip7702Service] Pre-flight delegation check failed:",
|
|
1010
|
+
error
|
|
1011
|
+
);
|
|
1012
|
+
throw error;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Sign EIP-7702 delegate authorization.
|
|
1017
|
+
*
|
|
1018
|
+
* Revoke authorization is intentionally omitted: the server previously
|
|
1019
|
+
* broadcast revoke as a separate TX, which caused nonce competition
|
|
1020
|
+
* (2-TX pattern). Delegation persists across relays but each new relay
|
|
1021
|
+
* overwrites the previous delegate authorization, so this is safe.
|
|
1022
|
+
* If the server adds single-TX delegate+revoke support in the future,
|
|
1023
|
+
* add revokeAuth signing here (nonce + 1) and include it in the relay
|
|
1024
|
+
* request.
|
|
1025
|
+
*/
|
|
1026
|
+
async signDelegate(chainKey, chainId, address) {
|
|
1027
|
+
if (!this.signer.supportsAuthorization()) {
|
|
1028
|
+
throw new Error("Signer does not support EIP-7702 authorization");
|
|
1029
|
+
}
|
|
1030
|
+
const chainConfig = await this.chainConfigApi.getChainConfig(chainKey);
|
|
1031
|
+
if (!chainConfig.eip7702Delegate) {
|
|
1032
|
+
throw new Error(`No EIP-7702 delegate configured for chain ${chainKey}`);
|
|
1033
|
+
}
|
|
1034
|
+
const nonce = await this.signer.getNonce(address);
|
|
1035
|
+
const delegateAuth = await this.signer.signAuthorization({
|
|
1036
|
+
chainId,
|
|
1037
|
+
address: chainConfig.eip7702Delegate,
|
|
1038
|
+
nonce
|
|
1039
|
+
});
|
|
1040
|
+
return { delegateAuth };
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Sign the EIP-712 execution typed data for the relay.
|
|
1044
|
+
*/
|
|
1045
|
+
async signExecutionTypedData(typedData) {
|
|
1046
|
+
const sig = await this.signer.signTypedData(typedData);
|
|
1047
|
+
if (!sig || sig === "0x") {
|
|
1048
|
+
throw new Error("signTypedData returned empty signature");
|
|
1049
|
+
}
|
|
1050
|
+
const hex = sig.startsWith("0x") ? sig.slice(2) : sig;
|
|
1051
|
+
if (hex.length !== 130) {
|
|
1052
|
+
throw new Error(
|
|
1053
|
+
`Unexpected signature length: ${hex.length} (expected 130)`
|
|
1054
|
+
);
|
|
1055
|
+
}
|
|
1056
|
+
return {
|
|
1057
|
+
nonce: String(typedData.message.nonce ?? "0"),
|
|
1058
|
+
deadline: Number(typedData.message.deadline ?? 0),
|
|
1059
|
+
v: Number.parseInt(hex.slice(128, 130), 16),
|
|
1060
|
+
r: `0x${hex.slice(0, 64)}`,
|
|
1061
|
+
s: `0x${hex.slice(64, 128)}`
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Get relayer info needed for EIP-7702 execution.
|
|
1066
|
+
*/
|
|
1067
|
+
async getRelayerInfo(chainKey, address) {
|
|
1068
|
+
const [balanceInfo, executionNonce] = await Promise.all([
|
|
1069
|
+
this.relayerApi.getRelayerBalance(chainKey),
|
|
1070
|
+
this.relayerApi.getExecutionNonce(chainKey, address)
|
|
1071
|
+
]);
|
|
1072
|
+
return {
|
|
1073
|
+
relayerAddress: balanceInfo.relayer,
|
|
1074
|
+
executionNonce
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
/** Access chain config API */
|
|
1078
|
+
getChainConfigApi() {
|
|
1079
|
+
return this.chainConfigApi;
|
|
1080
|
+
}
|
|
1081
|
+
};
|
|
1082
|
+
var EIP7702_DOMAIN_NAME = "Talken EIP7702 Delegate";
|
|
1083
|
+
var EIP7702_DOMAIN_VERSION = "1";
|
|
1084
|
+
function hashSingleBatchCall(target, calldata) {
|
|
1085
|
+
const calldataHash = keccak2562(calldata);
|
|
1086
|
+
const encoded = encodeAbiParameters(
|
|
1087
|
+
parseAbiParameters("address, uint256, bytes32"),
|
|
1088
|
+
[target, BigInt(0), calldataHash]
|
|
1089
|
+
);
|
|
1090
|
+
const callHash = keccak2562(encoded);
|
|
1091
|
+
return keccak2562(callHash);
|
|
1092
|
+
}
|
|
1093
|
+
function buildExecuteBatchWithFeeTypedData(params) {
|
|
1094
|
+
return {
|
|
1095
|
+
types: {
|
|
1096
|
+
EIP712Domain: [
|
|
1097
|
+
{ name: "name", type: "string" },
|
|
1098
|
+
{ name: "version", type: "string" },
|
|
1099
|
+
{ name: "chainId", type: "uint256" },
|
|
1100
|
+
{ name: "verifyingContract", type: "address" }
|
|
1101
|
+
],
|
|
1102
|
+
ExecuteBatchWithFee: [
|
|
1103
|
+
{ name: "router", type: "address" },
|
|
1104
|
+
{ name: "callsHash", type: "bytes32" },
|
|
1105
|
+
{ name: "feeToken", type: "address" },
|
|
1106
|
+
{ name: "feeAmount", type: "uint256" },
|
|
1107
|
+
{ name: "feeRecipient", type: "address" },
|
|
1108
|
+
{ name: "relayer", type: "address" },
|
|
1109
|
+
{ name: "nonce", type: "uint256" },
|
|
1110
|
+
{ name: "deadline", type: "uint256" }
|
|
1111
|
+
]
|
|
1112
|
+
},
|
|
1113
|
+
domain: {
|
|
1114
|
+
name: EIP7702_DOMAIN_NAME,
|
|
1115
|
+
version: EIP7702_DOMAIN_VERSION,
|
|
1116
|
+
chainId: params.chainId,
|
|
1117
|
+
verifyingContract: params.fromAddress
|
|
1118
|
+
},
|
|
1119
|
+
primaryType: "ExecuteBatchWithFee",
|
|
1120
|
+
message: {
|
|
1121
|
+
router: params.tokenAddress,
|
|
1122
|
+
callsHash: hashSingleBatchCall(
|
|
1123
|
+
params.tokenAddress,
|
|
1124
|
+
params.transferCalldata
|
|
1125
|
+
),
|
|
1126
|
+
feeToken: params.feeToken,
|
|
1127
|
+
feeAmount: params.feeAmount,
|
|
1128
|
+
feeRecipient: params.relayerAddress,
|
|
1129
|
+
relayer: params.relayerAddress,
|
|
1130
|
+
nonce: params.executionNonce,
|
|
1131
|
+
deadline: String(params.deadline)
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
function buildExecuteDelegatedSwapTypedData(params) {
|
|
1136
|
+
return {
|
|
1137
|
+
types: {
|
|
1138
|
+
EIP712Domain: [
|
|
1139
|
+
{ name: "name", type: "string" },
|
|
1140
|
+
{ name: "version", type: "string" },
|
|
1141
|
+
{ name: "chainId", type: "uint256" },
|
|
1142
|
+
{ name: "verifyingContract", type: "address" }
|
|
1143
|
+
],
|
|
1144
|
+
ExecuteDelegatedSwap: [
|
|
1145
|
+
{ name: "router", type: "address" },
|
|
1146
|
+
{ name: "token", type: "address" },
|
|
1147
|
+
{ name: "usePermit2", type: "bool" },
|
|
1148
|
+
{ name: "dataHash", type: "bytes32" },
|
|
1149
|
+
{ name: "relayer", type: "address" },
|
|
1150
|
+
{ name: "nonce", type: "uint256" },
|
|
1151
|
+
{ name: "deadline", type: "uint256" }
|
|
1152
|
+
]
|
|
1153
|
+
},
|
|
1154
|
+
domain: {
|
|
1155
|
+
name: EIP7702_DOMAIN_NAME,
|
|
1156
|
+
version: EIP7702_DOMAIN_VERSION,
|
|
1157
|
+
chainId: params.chainId,
|
|
1158
|
+
verifyingContract: params.fromAddress
|
|
1159
|
+
},
|
|
1160
|
+
primaryType: "ExecuteDelegatedSwap",
|
|
1161
|
+
message: {
|
|
1162
|
+
router: params.tokenAddress,
|
|
1163
|
+
token: params.tokenAddress,
|
|
1164
|
+
usePermit2: false,
|
|
1165
|
+
dataHash: keccak2562(params.transferCalldata),
|
|
1166
|
+
relayer: params.relayerAddress,
|
|
1167
|
+
nonce: params.executionNonce,
|
|
1168
|
+
deadline: String(params.deadline)
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
// src/gasless/services/PermitSignService.ts
|
|
1174
|
+
var PermitSignService = class {
|
|
1175
|
+
constructor(signer) {
|
|
1176
|
+
this.signer = signer;
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Sign all signature requests from the relayer's Phase 1 response.
|
|
1180
|
+
* Returns an array of signed signatures keyed by purpose.
|
|
1181
|
+
*/
|
|
1182
|
+
async signAll(requests) {
|
|
1183
|
+
const results = [];
|
|
1184
|
+
for (const req of requests) {
|
|
1185
|
+
const typedData = this.buildTypedData(req);
|
|
1186
|
+
const signature = await this.signer.signTypedData(typedData);
|
|
1187
|
+
results.push({
|
|
1188
|
+
purpose: req.purpose,
|
|
1189
|
+
...this.parseSignature(signature)
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
return results;
|
|
1193
|
+
}
|
|
1194
|
+
buildTypedData(req) {
|
|
1195
|
+
const typedData = {
|
|
1196
|
+
domain: req.domain,
|
|
1197
|
+
message: req.message,
|
|
1198
|
+
primaryType: req.primaryType ?? this.inferPrimaryType(req),
|
|
1199
|
+
types: {}
|
|
1200
|
+
};
|
|
1201
|
+
if (req.types) {
|
|
1202
|
+
typedData.types = {
|
|
1203
|
+
...req.types,
|
|
1204
|
+
EIP712Domain: [
|
|
1205
|
+
{ name: "name", type: "string" },
|
|
1206
|
+
{ name: "version", type: "string" },
|
|
1207
|
+
{ name: "chainId", type: "uint256" },
|
|
1208
|
+
{ name: "verifyingContract", type: "address" }
|
|
1209
|
+
]
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
return typedData;
|
|
1213
|
+
}
|
|
1214
|
+
inferPrimaryType(req) {
|
|
1215
|
+
switch (req.type) {
|
|
1216
|
+
case "eip3009":
|
|
1217
|
+
return "TransferWithAuthorization";
|
|
1218
|
+
case "erc2612":
|
|
1219
|
+
return "Permit";
|
|
1220
|
+
case "eip712":
|
|
1221
|
+
return "RelayRequest";
|
|
1222
|
+
default:
|
|
1223
|
+
return "RelayRequest";
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
parseSignature(sig) {
|
|
1227
|
+
if (!sig || sig === "0x") {
|
|
1228
|
+
return { raw: sig };
|
|
1229
|
+
}
|
|
1230
|
+
const hex = sig.startsWith("0x") ? sig.slice(2) : sig;
|
|
1231
|
+
if (hex.length === 130) {
|
|
1232
|
+
const r = `0x${hex.slice(0, 64)}`;
|
|
1233
|
+
const s = `0x${hex.slice(64, 128)}`;
|
|
1234
|
+
const parsedV = Number.parseInt(hex.slice(128, 130), 16);
|
|
1235
|
+
const v = parsedV === 0 || parsedV === 1 ? parsedV + 27 : parsedV;
|
|
1236
|
+
return { v, r, s };
|
|
1237
|
+
}
|
|
1238
|
+
return { raw: sig };
|
|
1239
|
+
}
|
|
1240
|
+
};
|
|
1241
|
+
|
|
1242
|
+
// src/gasless/services/GaslessTransferService.ts
|
|
1243
|
+
var ZERO_ADDRESS3 = "0x0000000000000000000000000000000000000000";
|
|
1244
|
+
var RelayPhase2Error = class extends Error {
|
|
1245
|
+
constructor(requestId, cause) {
|
|
1246
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1247
|
+
super(
|
|
1248
|
+
`Relay Phase 2 failed (requestId: ${requestId}). The transaction may have been submitted on-chain. Check the explorer before retrying. Original: ${message}`
|
|
1249
|
+
);
|
|
1250
|
+
this.name = "RelayPhase2Error";
|
|
1251
|
+
this.requestId = requestId;
|
|
1252
|
+
this.originalError = cause;
|
|
1253
|
+
}
|
|
1254
|
+
};
|
|
1255
|
+
var GaslessTransferService = class {
|
|
1256
|
+
constructor(deps) {
|
|
1257
|
+
this.assertSessionCurrent = () => this.signer.assertSessionCurrent?.();
|
|
1258
|
+
this.relayerApi = deps.relayerApi ?? new RelayerApi();
|
|
1259
|
+
this.signer = deps.signer;
|
|
1260
|
+
this.walletClient = deps.walletClient;
|
|
1261
|
+
this.permitService = new PermitSignService(deps.signer);
|
|
1262
|
+
this.eip7702Service = deps.eip7702Service ?? new Eip7702Service({
|
|
1263
|
+
relayerApi: this.relayerApi,
|
|
1264
|
+
signer: deps.signer
|
|
1265
|
+
});
|
|
1266
|
+
}
|
|
1267
|
+
async execute(params, gaslessConfig) {
|
|
1268
|
+
this.assertSessionCurrent();
|
|
1269
|
+
try {
|
|
1270
|
+
switch (params.gaslessMode) {
|
|
1271
|
+
case "generic":
|
|
1272
|
+
return await this.executeGenericRelay(params);
|
|
1273
|
+
case "eip7702-fee":
|
|
1274
|
+
case "eip7702-points":
|
|
1275
|
+
return await this.executeEip7702Relay(params, gaslessConfig);
|
|
1276
|
+
default:
|
|
1277
|
+
throw new Error(`Unknown gasless mode: ${params.gaslessMode}`);
|
|
1278
|
+
}
|
|
1279
|
+
} catch (error) {
|
|
1280
|
+
this.assertSessionCurrent();
|
|
1281
|
+
throw error;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Generic 2-phase relay execution.
|
|
1286
|
+
*
|
|
1287
|
+
* Phase 1: POST /relay/execute { auth: { method: 'auto' } }
|
|
1288
|
+
* → Server responds with signatureRequests
|
|
1289
|
+
* Phase 2: Sign all requests → POST /relay/execute { requestId, signatures }
|
|
1290
|
+
* → Server responds with txHash
|
|
1291
|
+
*/
|
|
1292
|
+
async executeGenericRelay(params) {
|
|
1293
|
+
try {
|
|
1294
|
+
await this.eip7702Service.preflight(
|
|
1295
|
+
params.chainKey,
|
|
1296
|
+
params.chainId,
|
|
1297
|
+
params.fromAddress,
|
|
1298
|
+
{
|
|
1299
|
+
walletClient: this.walletClient,
|
|
1300
|
+
assertSessionCurrent: this.assertSessionCurrent,
|
|
1301
|
+
delegationClient: this.signer.getDelegationClient?.()
|
|
1302
|
+
}
|
|
1303
|
+
);
|
|
1304
|
+
} catch (err) {
|
|
1305
|
+
this.assertSessionCurrent();
|
|
1306
|
+
if (["AUTH_SESSION_CHANGED", "EXTERNAL_REVOKE_UNSUPPORTED", 4001].includes(
|
|
1307
|
+
err?.code ?? ""
|
|
1308
|
+
))
|
|
1309
|
+
throw err;
|
|
1310
|
+
console.warn(
|
|
1311
|
+
"[GaslessTransferService] Preflight check failed (non-blocking):",
|
|
1312
|
+
err
|
|
1313
|
+
);
|
|
1314
|
+
}
|
|
1315
|
+
this.assertSessionCurrent();
|
|
1316
|
+
const deadline = Math.floor(Date.now() / 1e3) + 20 * 60;
|
|
1317
|
+
const feeMaxAmount = (BigInt(params.feeAmountRaw) * BigInt(3) / BigInt(2)).toString();
|
|
1318
|
+
const baseRequest = {
|
|
1319
|
+
chainKey: params.chainKey,
|
|
1320
|
+
user: params.fromAddress,
|
|
1321
|
+
tokenIn: params.tokenAddress,
|
|
1322
|
+
amountIn: params.amount,
|
|
1323
|
+
target: ZERO_ADDRESS3,
|
|
1324
|
+
targetCalldata: "0x",
|
|
1325
|
+
tokenOut: ZERO_ADDRESS3,
|
|
1326
|
+
minAmountOut: "0",
|
|
1327
|
+
recipient: params.toAddress,
|
|
1328
|
+
deadline,
|
|
1329
|
+
fee: {
|
|
1330
|
+
token: params.feeToken.symbol,
|
|
1331
|
+
amount: params.feeAmountRaw,
|
|
1332
|
+
maxAmount: feeMaxAmount
|
|
1333
|
+
},
|
|
1334
|
+
auth: { method: "auto" }
|
|
1335
|
+
};
|
|
1336
|
+
const phase1 = await this.relayerApi.execute(baseRequest);
|
|
1337
|
+
this.assertSessionCurrent();
|
|
1338
|
+
if (phase1.phase !== "sign") {
|
|
1339
|
+
return this.extractResult(phase1, params);
|
|
1340
|
+
}
|
|
1341
|
+
const signatures = await this.permitService.signAll(
|
|
1342
|
+
phase1.signatureRequests
|
|
1343
|
+
);
|
|
1344
|
+
this.assertSessionCurrent();
|
|
1345
|
+
let phase2;
|
|
1346
|
+
try {
|
|
1347
|
+
phase2 = await this.relayerApi.execute({
|
|
1348
|
+
...baseRequest,
|
|
1349
|
+
requestId: phase1.requestId,
|
|
1350
|
+
signatures
|
|
1351
|
+
});
|
|
1352
|
+
} catch (err) {
|
|
1353
|
+
this.assertSessionCurrent();
|
|
1354
|
+
if (err?.code === "AUTH_SESSION_CHANGED")
|
|
1355
|
+
throw err;
|
|
1356
|
+
throw new RelayPhase2Error(phase1.requestId, err);
|
|
1357
|
+
}
|
|
1358
|
+
this.assertSessionCurrent();
|
|
1359
|
+
return this.extractResult(phase2, params);
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* EIP-7702 relay execution (fee or points mode).
|
|
1363
|
+
*
|
|
1364
|
+
* 1. Pre-flight delegation check
|
|
1365
|
+
* 2. Sign delegate authorization
|
|
1366
|
+
* 3. Get relayer info (address + execution nonce)
|
|
1367
|
+
* 4. Build and sign execution typed data
|
|
1368
|
+
* 5. Submit to relayer
|
|
1369
|
+
* 6. On failure: cleanup delegation
|
|
1370
|
+
*/
|
|
1371
|
+
async executeEip7702Relay(params, gaslessConfig) {
|
|
1372
|
+
await this.eip7702Service.preflight(
|
|
1373
|
+
params.chainKey,
|
|
1374
|
+
params.chainId,
|
|
1375
|
+
params.fromAddress,
|
|
1376
|
+
{
|
|
1377
|
+
walletClient: this.walletClient,
|
|
1378
|
+
onDelegationError: gaslessConfig.onDelegationError,
|
|
1379
|
+
assertSessionCurrent: this.assertSessionCurrent,
|
|
1380
|
+
delegationClient: this.signer.getDelegationClient?.()
|
|
1381
|
+
}
|
|
1382
|
+
);
|
|
1383
|
+
this.assertSessionCurrent();
|
|
1384
|
+
try {
|
|
1385
|
+
const { delegateAuth } = await this.eip7702Service.signDelegate(
|
|
1386
|
+
params.chainKey,
|
|
1387
|
+
params.chainId,
|
|
1388
|
+
params.fromAddress
|
|
1389
|
+
);
|
|
1390
|
+
this.assertSessionCurrent();
|
|
1391
|
+
const { relayerAddress, executionNonce } = await this.eip7702Service.getRelayerInfo(
|
|
1392
|
+
params.chainKey,
|
|
1393
|
+
params.fromAddress
|
|
1394
|
+
);
|
|
1395
|
+
this.assertSessionCurrent();
|
|
1396
|
+
const deadline = Math.floor(Date.now() / 1e3) + 20 * 60;
|
|
1397
|
+
const isPointsMode = params.gaslessMode === "eip7702-points";
|
|
1398
|
+
const transferCalldata = this.encodeErc20Transfer(
|
|
1399
|
+
params.toAddress,
|
|
1400
|
+
params.amount
|
|
1401
|
+
);
|
|
1402
|
+
const executionTypedData = isPointsMode ? buildExecuteDelegatedSwapTypedData({
|
|
1403
|
+
chainId: params.chainId,
|
|
1404
|
+
fromAddress: params.fromAddress,
|
|
1405
|
+
tokenAddress: params.tokenAddress,
|
|
1406
|
+
transferCalldata,
|
|
1407
|
+
executionNonce,
|
|
1408
|
+
deadline,
|
|
1409
|
+
relayerAddress
|
|
1410
|
+
}) : buildExecuteBatchWithFeeTypedData({
|
|
1411
|
+
chainId: params.chainId,
|
|
1412
|
+
fromAddress: params.fromAddress,
|
|
1413
|
+
tokenAddress: params.tokenAddress,
|
|
1414
|
+
transferCalldata,
|
|
1415
|
+
executionNonce,
|
|
1416
|
+
deadline,
|
|
1417
|
+
relayerAddress,
|
|
1418
|
+
feeToken: params.feeToken.address,
|
|
1419
|
+
feeAmount: params.feeAmountRaw
|
|
1420
|
+
});
|
|
1421
|
+
const executionAuth = await this.eip7702Service.signExecutionTypedData(executionTypedData);
|
|
1422
|
+
this.assertSessionCurrent();
|
|
1423
|
+
const feeAmount = isPointsMode ? "0" : params.feeAmountRaw;
|
|
1424
|
+
const feeMaxAmount = isPointsMode ? "0" : (BigInt(params.feeAmountRaw) * BigInt(3) / BigInt(2)).toString();
|
|
1425
|
+
const result = await this.relayerApi.execute({
|
|
1426
|
+
chainKey: params.chainKey,
|
|
1427
|
+
user: params.fromAddress,
|
|
1428
|
+
tokenIn: params.tokenAddress,
|
|
1429
|
+
amountIn: params.amount,
|
|
1430
|
+
target: params.tokenAddress,
|
|
1431
|
+
targetCalldata: transferCalldata,
|
|
1432
|
+
tokenOut: ZERO_ADDRESS3,
|
|
1433
|
+
minAmountOut: "0",
|
|
1434
|
+
recipient: params.toAddress,
|
|
1435
|
+
deadline,
|
|
1436
|
+
fee: {
|
|
1437
|
+
token: isPointsMode ? "USDC" : params.feeToken.symbol,
|
|
1438
|
+
amount: feeAmount,
|
|
1439
|
+
maxAmount: feeMaxAmount
|
|
1440
|
+
},
|
|
1441
|
+
auth: {
|
|
1442
|
+
method: "eip7702",
|
|
1443
|
+
usePermit2: false,
|
|
1444
|
+
authorization: delegateAuth,
|
|
1445
|
+
executionAuth
|
|
1446
|
+
}
|
|
1447
|
+
});
|
|
1448
|
+
this.assertSessionCurrent();
|
|
1449
|
+
return this.extractResult(result, params);
|
|
1450
|
+
} catch (error) {
|
|
1451
|
+
this.assertSessionCurrent();
|
|
1452
|
+
if (error?.code === "AUTH_SESSION_CHANGED")
|
|
1453
|
+
throw error;
|
|
1454
|
+
try {
|
|
1455
|
+
await ensureDelegationCleared(
|
|
1456
|
+
params.chainKey,
|
|
1457
|
+
params.chainId,
|
|
1458
|
+
params.fromAddress,
|
|
1459
|
+
{
|
|
1460
|
+
walletClient: this.walletClient,
|
|
1461
|
+
onDelegationError: gaslessConfig.onDelegationError,
|
|
1462
|
+
assertSessionCurrent: this.assertSessionCurrent,
|
|
1463
|
+
delegationClient: this.signer.getDelegationClient?.()
|
|
1464
|
+
}
|
|
1465
|
+
);
|
|
1466
|
+
} catch (cleanupError) {
|
|
1467
|
+
this.assertSessionCurrent();
|
|
1468
|
+
if (cleanupError?.code === "AUTH_SESSION_CHANGED")
|
|
1469
|
+
throw cleanupError;
|
|
1470
|
+
console.error(
|
|
1471
|
+
"[GaslessTransferService] Post-failure delegation cleanup failed:",
|
|
1472
|
+
cleanupError
|
|
1473
|
+
);
|
|
1474
|
+
}
|
|
1475
|
+
throw error;
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
extractResult(response, params) {
|
|
1479
|
+
if (response.phase === "sign") {
|
|
1480
|
+
throw new Error("Unexpected sign phase in final response");
|
|
1481
|
+
}
|
|
1482
|
+
if (response.error) {
|
|
1483
|
+
const err = new Error(
|
|
1484
|
+
`Relay failed: ${response.error.code}: ${response.error.message}`
|
|
1485
|
+
);
|
|
1486
|
+
err.txHash = response.data?.txHash ?? "";
|
|
1487
|
+
throw err;
|
|
1488
|
+
}
|
|
1489
|
+
const txHash = response.data?.txHash ?? response.txHash;
|
|
1490
|
+
if (!txHash) {
|
|
1491
|
+
throw new Error("Relay did not return txHash");
|
|
1492
|
+
}
|
|
1493
|
+
return {
|
|
1494
|
+
txHash,
|
|
1495
|
+
gaslessMode: params.gaslessMode,
|
|
1496
|
+
feeToken: params.feeToken.symbol,
|
|
1497
|
+
feeAmount: params.feeAmountRaw,
|
|
1498
|
+
cleanup: response.data?.cleanup
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
/** Encode ERC-20 transfer(address,uint256) calldata */
|
|
1502
|
+
encodeErc20Transfer(to, amount) {
|
|
1503
|
+
if (!isAddress2(to)) {
|
|
1504
|
+
throw new Error(`Invalid recipient address: ${to}`);
|
|
1505
|
+
}
|
|
1506
|
+
return encodeFunctionData({
|
|
1507
|
+
abi: erc20Abi,
|
|
1508
|
+
functionName: "transfer",
|
|
1509
|
+
args: [to, BigInt(amount)]
|
|
1510
|
+
});
|
|
1511
|
+
}
|
|
1512
|
+
};
|
|
1513
|
+
|
|
1514
|
+
// src/gasless/signer/AbcWaasSigner.ts
|
|
1515
|
+
var MAX_SIGN_ATTEMPTS = 3;
|
|
1516
|
+
var RETRY_BASE_MS = 500;
|
|
1517
|
+
function sleep(ms) {
|
|
1518
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1519
|
+
}
|
|
1520
|
+
var AbcWaasSigner = class {
|
|
1521
|
+
constructor(params) {
|
|
1522
|
+
this.api = getTalkenApiClient();
|
|
1523
|
+
this.revision = this.api?.getSessionRevision();
|
|
1524
|
+
this.pinHash = params.pinHash;
|
|
1525
|
+
this.network = params.network;
|
|
1526
|
+
this.email = params.email;
|
|
1527
|
+
}
|
|
1528
|
+
getDelegationClient() {
|
|
1529
|
+
return {
|
|
1530
|
+
readCode: async (chainKey, address) => {
|
|
1531
|
+
const api = this.getApiOrThrow();
|
|
1532
|
+
const result = await api.get(
|
|
1533
|
+
`/wallet/code/${encodeURIComponent(chainKey)}/${encodeURIComponent(address)}`
|
|
1534
|
+
);
|
|
1535
|
+
this.getApiOrThrow();
|
|
1536
|
+
return result.code ?? "0x";
|
|
1537
|
+
},
|
|
1538
|
+
revoke: (chainKey, chainId, address) => sendRevokeTx(
|
|
1539
|
+
address,
|
|
1540
|
+
chainKey,
|
|
1541
|
+
chainId,
|
|
1542
|
+
() => this.assertSessionCurrent()
|
|
1543
|
+
)
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
assertSessionCurrent() {
|
|
1547
|
+
this.getApiOrThrow();
|
|
1548
|
+
}
|
|
1549
|
+
supportsAuthorization() {
|
|
1550
|
+
return true;
|
|
1551
|
+
}
|
|
1552
|
+
async signTypedData(typedData) {
|
|
1553
|
+
const api = this.getApiOrThrow();
|
|
1554
|
+
let lastError = null;
|
|
1555
|
+
for (let attempt = 0; attempt < MAX_SIGN_ATTEMPTS; attempt++) {
|
|
1556
|
+
try {
|
|
1557
|
+
this.getApiOrThrow();
|
|
1558
|
+
const result = await api.evm.signTypedData({
|
|
1559
|
+
network: this.network,
|
|
1560
|
+
typedData: JSON.stringify(typedData),
|
|
1561
|
+
...this.pinHash && { pin: this.pinHash },
|
|
1562
|
+
...this.email && { email: this.email }
|
|
1563
|
+
});
|
|
1564
|
+
this.getApiOrThrow();
|
|
1565
|
+
const sig = typeof result === "string" ? result : result?.signature ?? result?.result;
|
|
1566
|
+
if (sig)
|
|
1567
|
+
return sig;
|
|
1568
|
+
throw new Error("signTypedData returned empty signature");
|
|
1569
|
+
} catch (error) {
|
|
1570
|
+
this.getApiOrThrow();
|
|
1571
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1572
|
+
if (attempt < MAX_SIGN_ATTEMPTS - 1) {
|
|
1573
|
+
await sleep(RETRY_BASE_MS * 2 ** attempt);
|
|
1574
|
+
this.getApiOrThrow();
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
throw lastError ?? new Error("Failed to sign typed data");
|
|
1579
|
+
}
|
|
1580
|
+
async signAuthorization(authorization) {
|
|
1581
|
+
const api = this.getApiOrThrow();
|
|
1582
|
+
let lastError = null;
|
|
1583
|
+
for (let attempt = 0; attempt < MAX_SIGN_ATTEMPTS; attempt++) {
|
|
1584
|
+
try {
|
|
1585
|
+
this.getApiOrThrow();
|
|
1586
|
+
const result = await api.evm.signAuthorization({
|
|
1587
|
+
network: this.network,
|
|
1588
|
+
authorization: {
|
|
1589
|
+
chainId: authorization.chainId,
|
|
1590
|
+
address: authorization.address,
|
|
1591
|
+
nonce: String(authorization.nonce)
|
|
1592
|
+
},
|
|
1593
|
+
...this.pinHash && { pin: this.pinHash },
|
|
1594
|
+
...this.email && { email: this.email }
|
|
1595
|
+
});
|
|
1596
|
+
this.getApiOrThrow();
|
|
1597
|
+
const auth = result?.authorization ?? result;
|
|
1598
|
+
if (!auth?.r || !auth?.s) {
|
|
1599
|
+
throw new Error("signAuthorization returned empty r/s");
|
|
1600
|
+
}
|
|
1601
|
+
return {
|
|
1602
|
+
chainId: authorization.chainId,
|
|
1603
|
+
address: authorization.address,
|
|
1604
|
+
nonce: authorization.nonce,
|
|
1605
|
+
yParity: normalizeYParity(auth.yParity ?? auth.v),
|
|
1606
|
+
r: auth.r,
|
|
1607
|
+
s: auth.s
|
|
1608
|
+
};
|
|
1609
|
+
} catch (error) {
|
|
1610
|
+
this.getApiOrThrow();
|
|
1611
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1612
|
+
if (attempt < MAX_SIGN_ATTEMPTS - 1) {
|
|
1613
|
+
await sleep(RETRY_BASE_MS * 2 ** attempt);
|
|
1614
|
+
this.getApiOrThrow();
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
throw lastError ?? new Error("Failed to sign authorization");
|
|
1619
|
+
}
|
|
1620
|
+
async getNonce(address) {
|
|
1621
|
+
const api = this.getApiOrThrow();
|
|
1622
|
+
const nonceResult = await api.evm.getNonce(this.network, address);
|
|
1623
|
+
this.getApiOrThrow();
|
|
1624
|
+
const raw = nonceResult?.data?.result ?? nonceResult?.nonce ?? nonceResult?.result ?? nonceResult;
|
|
1625
|
+
const nonce = Number(raw);
|
|
1626
|
+
if (!Number.isFinite(nonce)) {
|
|
1627
|
+
throw new Error("Failed to resolve wallet nonce");
|
|
1628
|
+
}
|
|
1629
|
+
return nonce;
|
|
1630
|
+
}
|
|
1631
|
+
getApiOrThrow() {
|
|
1632
|
+
const api = getTalkenApiClient();
|
|
1633
|
+
if (!api)
|
|
1634
|
+
throw new Error("TalkenApiClient not initialized");
|
|
1635
|
+
if (api !== this.api || api.getSessionRevision() !== this.revision || !ownsTalkenApiStorage(api))
|
|
1636
|
+
throw new TalkenApiError(
|
|
1637
|
+
"AUTH_SESSION_CHANGED",
|
|
1638
|
+
"The signer wallet session changed.",
|
|
1639
|
+
401
|
|
1640
|
+
);
|
|
1641
|
+
const session = api.isAccessKeyMode() ? api.getAuthenticatedWalletSession() : null;
|
|
1642
|
+
if (api.isAccessKeyMode() && (!session || this.email && session.user.email !== this.email.trim().toLowerCase()))
|
|
1643
|
+
throw new TalkenApiError(
|
|
1644
|
+
"AUTH_SESSION_CHANGED",
|
|
1645
|
+
"The signer account does not match this login.",
|
|
1646
|
+
401
|
|
1647
|
+
);
|
|
1648
|
+
return api;
|
|
1649
|
+
}
|
|
1650
|
+
};
|
|
1651
|
+
function normalizeYParity(value) {
|
|
1652
|
+
if (value === void 0 || value === null)
|
|
1653
|
+
return 0;
|
|
1654
|
+
if (value === 27)
|
|
1655
|
+
return 0;
|
|
1656
|
+
if (value === 28)
|
|
1657
|
+
return 1;
|
|
1658
|
+
if (value === 0 || value === 1)
|
|
1659
|
+
return value;
|
|
1660
|
+
throw new Error(
|
|
1661
|
+
`Invalid yParity/v value: ${value}. Expected 0, 1, 27, or 28.`
|
|
1662
|
+
);
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
// src/gasless/utils/transferDetector.ts
|
|
1666
|
+
var ERC20_TRANSFER_SELECTOR = "0xa9059cbb";
|
|
1667
|
+
var MIN_TRANSFER_DATA_LENGTH = 138;
|
|
1668
|
+
function detectErc20Transfer(data) {
|
|
1669
|
+
if (!data)
|
|
1670
|
+
return null;
|
|
1671
|
+
const trimmed = data.trim();
|
|
1672
|
+
const normalized = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
|
|
1673
|
+
if (normalized.length < MIN_TRANSFER_DATA_LENGTH)
|
|
1674
|
+
return null;
|
|
1675
|
+
const selector = normalized.slice(0, 10).toLowerCase();
|
|
1676
|
+
if (selector !== ERC20_TRANSFER_SELECTOR)
|
|
1677
|
+
return null;
|
|
1678
|
+
try {
|
|
1679
|
+
const toHex2 = normalized.slice(10, 74);
|
|
1680
|
+
const amountHex = normalized.slice(74, 138);
|
|
1681
|
+
const to = `0x${toHex2.slice(24)}`;
|
|
1682
|
+
const amount = BigInt(`0x${amountHex}`).toString();
|
|
1683
|
+
if (to.length !== 42)
|
|
1684
|
+
return null;
|
|
1685
|
+
return { to, amount };
|
|
1686
|
+
} catch {
|
|
1687
|
+
return null;
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
function isGaslessEligible(tx) {
|
|
1691
|
+
if (!tx.to || tx.to === "0x" || tx.to === "0x0")
|
|
1692
|
+
return false;
|
|
1693
|
+
const ZERO_ADDR = "0x0000000000000000000000000000000000000000";
|
|
1694
|
+
if (tx.to.toLowerCase() === ZERO_ADDR)
|
|
1695
|
+
return false;
|
|
1696
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(tx.to))
|
|
1697
|
+
return false;
|
|
1698
|
+
if (tx.value && tx.value !== "0x0" && tx.value !== "0x" && tx.value !== "0") {
|
|
1699
|
+
try {
|
|
1700
|
+
if (BigInt(tx.value) > BigInt(0))
|
|
1701
|
+
return false;
|
|
1702
|
+
} catch {
|
|
1703
|
+
return false;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
const transfer = detectErc20Transfer(tx.data);
|
|
1707
|
+
if (!transfer)
|
|
1708
|
+
return false;
|
|
1709
|
+
if (transfer.amount === "0")
|
|
1710
|
+
return false;
|
|
1711
|
+
return true;
|
|
1712
|
+
}
|
|
1713
|
+
|
|
1714
|
+
// src/wallets/walletConnectors/abcWallet/abcProvider.ts
|
|
1715
|
+
var logger2 = createLogger("AbcProvider");
|
|
1716
|
+
var AbcEvmProvider = class extends AbstractChainProvider {
|
|
1717
|
+
constructor() {
|
|
1718
|
+
super(...arguments);
|
|
1719
|
+
this.chainId = 1;
|
|
1720
|
+
// Default to Ethereum mainnet
|
|
1721
|
+
// Gasless: shared singleton preserves cooldown state across all callers
|
|
1722
|
+
this._sharedRelayerApi = new RelayerApi();
|
|
1723
|
+
this.gaslessFeeService = getSharedGaslessFeeService();
|
|
1724
|
+
this.gaslessLock = Promise.resolve();
|
|
1725
|
+
}
|
|
1726
|
+
getWalletOperationNetwork() {
|
|
1727
|
+
return this.chainId;
|
|
1728
|
+
}
|
|
1729
|
+
getRecoveryEmail() {
|
|
1730
|
+
const walletEmail = this.wallet?.email?.trim();
|
|
1731
|
+
if (walletEmail) {
|
|
1732
|
+
return walletEmail;
|
|
1733
|
+
}
|
|
1734
|
+
return this.getSharedCredentials()?.getEmail() || void 0;
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* Set wallet — EVM override for chainId tracking + chainChanged event
|
|
1738
|
+
*/
|
|
1739
|
+
setWallet(wallet) {
|
|
1740
|
+
this.assertWalletSession(wallet);
|
|
1741
|
+
const previousChainId = this.chainId;
|
|
1742
|
+
this.chainId = wallet.chainId;
|
|
1743
|
+
super.setWallet(wallet);
|
|
1744
|
+
if (previousChainId !== wallet.chainId) {
|
|
1745
|
+
this.emit("chainChanged", numberToHex(wallet.chainId));
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
onWalletSet(wallet) {
|
|
1749
|
+
this.emit("connect", { chainId: numberToHex(wallet.chainId) });
|
|
1750
|
+
}
|
|
1751
|
+
/**
|
|
1752
|
+
* Clear wallet — override to reset gasless state
|
|
1753
|
+
*/
|
|
1754
|
+
clearWallet() {
|
|
1755
|
+
this.gaslessFeeService.clearCache();
|
|
1756
|
+
this.gaslessLock = Promise.resolve();
|
|
1757
|
+
super.clearWallet();
|
|
1758
|
+
}
|
|
1759
|
+
/**
|
|
1760
|
+
* Check if an error is a "Missing required wallet fields" 502 from the server.
|
|
1761
|
+
* When the server's in-memory signing credential cache is cold, it needs
|
|
1762
|
+
* a wallet.generate() call (idempotent create/recover) to repopulate.
|
|
1763
|
+
*/
|
|
1764
|
+
isSigningCredentialError(error) {
|
|
1765
|
+
return isSigningCredentialError(error);
|
|
1766
|
+
}
|
|
1767
|
+
/**
|
|
1768
|
+
* Refresh server-side signing credentials.
|
|
1769
|
+
*
|
|
1770
|
+
* Strategy (in priority order):
|
|
1771
|
+
* 1. PIN hash in memory → wallet.generate() to repopulate server cache
|
|
1772
|
+
* 2. Neither available → throw UNAUTHORIZED
|
|
1773
|
+
*
|
|
1774
|
+
* Note: the /sign/* and /execute/* routes do not accept cached `evmCreds`,
|
|
1775
|
+
* so this refresh is the only recovery from a cold server credential cache.
|
|
1776
|
+
*/
|
|
1777
|
+
async refreshSigningCredentials() {
|
|
1778
|
+
const credMgr = this.getSharedCredentials();
|
|
1779
|
+
const pinHash = credMgr?.getPinHash();
|
|
1780
|
+
const email = this.getRecoveryEmail();
|
|
1781
|
+
const assertOperation = this.captureWalletOperation();
|
|
1782
|
+
if (pinHash && email) {
|
|
1783
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
1784
|
+
logger2.info("Refreshing signing credentials via wallet.generate...");
|
|
1785
|
+
await this.awaitWalletOperation(
|
|
1786
|
+
assertOperation,
|
|
1787
|
+
async () => api.wallet.generate(pinHash, email)
|
|
1788
|
+
);
|
|
1789
|
+
logger2.info("Signing credentials refreshed via PIN");
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
logger2.warn(
|
|
1793
|
+
"Cannot refresh signing credentials \u2014 PIN hash or email missing"
|
|
1794
|
+
);
|
|
1795
|
+
throw new ProviderRpcError(
|
|
1796
|
+
ProviderErrorCode.UNAUTHORIZED,
|
|
1797
|
+
"Session expired. Please reconnect and verify your PIN."
|
|
1798
|
+
);
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* Wrap a signing operation with auto-retry on "Missing required wallet fields" error.
|
|
1802
|
+
* On first failure, refreshes the server's signing credential cache and retries once.
|
|
1803
|
+
*/
|
|
1804
|
+
async withSigningCredentialRetry(operation) {
|
|
1805
|
+
const assertOperation = this.captureWalletOperation();
|
|
1806
|
+
try {
|
|
1807
|
+
return await this.awaitWalletOperation(
|
|
1808
|
+
assertOperation,
|
|
1809
|
+
async () => operation()
|
|
1810
|
+
);
|
|
1811
|
+
} catch (error) {
|
|
1812
|
+
assertOperation();
|
|
1813
|
+
if (this.isSigningCredentialError(error)) {
|
|
1814
|
+
logger2.info(
|
|
1815
|
+
"Signing credentials missing on server \u2014 attempting refresh and retry"
|
|
1816
|
+
);
|
|
1817
|
+
await this.awaitWalletOperation(
|
|
1818
|
+
assertOperation,
|
|
1819
|
+
async () => this.refreshSigningCredentials()
|
|
1820
|
+
);
|
|
1821
|
+
return await this.awaitWalletOperation(
|
|
1822
|
+
assertOperation,
|
|
1823
|
+
async () => operation()
|
|
1824
|
+
);
|
|
1825
|
+
}
|
|
1826
|
+
throw error;
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Call request interceptor if configured
|
|
1831
|
+
* Called by specific signing/transaction methods that need user confirmation
|
|
1832
|
+
* @returns Resolved transaction with user modifications if changed in confirmation modal
|
|
1833
|
+
*/
|
|
1834
|
+
async callInterceptor(method, params) {
|
|
1835
|
+
if (!this.requestInterceptor) {
|
|
1836
|
+
return void 0;
|
|
1837
|
+
}
|
|
1838
|
+
const request = {
|
|
1839
|
+
method,
|
|
1840
|
+
params,
|
|
1841
|
+
chainId: this.chainId,
|
|
1842
|
+
address: this.wallet?.address || ""
|
|
1843
|
+
};
|
|
1844
|
+
return this.requestInterceptor(request);
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* EIP-1193 request method
|
|
1848
|
+
*/
|
|
1849
|
+
async request(args) {
|
|
1850
|
+
if (this.wallet)
|
|
1851
|
+
this.assertWalletSession();
|
|
1852
|
+
const { method, params } = args;
|
|
1853
|
+
switch (method) {
|
|
1854
|
+
case "eth_requestAccounts":
|
|
1855
|
+
return this.eth_requestAccounts();
|
|
1856
|
+
case "eth_accounts":
|
|
1857
|
+
return this.eth_accounts();
|
|
1858
|
+
case "eth_chainId":
|
|
1859
|
+
return this.eth_chainId();
|
|
1860
|
+
case "eth_sendTransaction":
|
|
1861
|
+
case "wallet_sendTransaction":
|
|
1862
|
+
return this.eth_sendTransaction(params);
|
|
1863
|
+
case "eth_signTransaction":
|
|
1864
|
+
return this.eth_signTransaction(params);
|
|
1865
|
+
case "personal_sign":
|
|
1866
|
+
return this.personal_sign(params);
|
|
1867
|
+
case "eth_sign":
|
|
1868
|
+
return this.eth_sign(params);
|
|
1869
|
+
case "eth_signTypedData":
|
|
1870
|
+
case "eth_signTypedData_v3":
|
|
1871
|
+
case "eth_signTypedData_v4":
|
|
1872
|
+
return this.eth_signTypedData(params);
|
|
1873
|
+
case "wallet_getCapabilities":
|
|
1874
|
+
return this.wallet_getCapabilities();
|
|
1875
|
+
case "eth_signAuthorization":
|
|
1876
|
+
return this.eth_signAuthorization(params);
|
|
1877
|
+
case "wallet_switchEthereumChain":
|
|
1878
|
+
return this.wallet_switchEthereumChain(params);
|
|
1879
|
+
case "wallet_addEthereumChain":
|
|
1880
|
+
return this.wallet_addEthereumChain(params);
|
|
1881
|
+
case "eth_estimateGas":
|
|
1882
|
+
return this.eth_estimateGas(params);
|
|
1883
|
+
case "eth_getTransactionCount":
|
|
1884
|
+
return this.eth_getTransactionCount(
|
|
1885
|
+
Array.isArray(params) ? params : []
|
|
1886
|
+
);
|
|
1887
|
+
case "eth_call":
|
|
1888
|
+
return this.eth_call(params);
|
|
1889
|
+
case "eth_getBalance":
|
|
1890
|
+
return this.eth_getBalance(params);
|
|
1891
|
+
case "eth_blockNumber":
|
|
1892
|
+
case "eth_gasPrice":
|
|
1893
|
+
case "eth_getBlockByHash":
|
|
1894
|
+
case "eth_getBlockByNumber":
|
|
1895
|
+
case "eth_getCode":
|
|
1896
|
+
case "eth_getStorageAt":
|
|
1897
|
+
case "eth_getTransactionByHash":
|
|
1898
|
+
case "eth_getTransactionReceipt":
|
|
1899
|
+
throw new ProviderRpcError(
|
|
1900
|
+
ProviderErrorCode.UNSUPPORTED_METHOD,
|
|
1901
|
+
`Method ${method} should be handled by RPC provider`
|
|
1902
|
+
);
|
|
1903
|
+
default:
|
|
1904
|
+
throw new ProviderRpcError(
|
|
1905
|
+
ProviderErrorCode.UNSUPPORTED_METHOD,
|
|
1906
|
+
`Method ${method} not supported`
|
|
1907
|
+
);
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* Request accounts (EIP-1193)
|
|
1912
|
+
*/
|
|
1913
|
+
async eth_requestAccounts() {
|
|
1914
|
+
if (!this.wallet) {
|
|
1915
|
+
throw new ProviderRpcError(
|
|
1916
|
+
ProviderErrorCode.UNAUTHORIZED,
|
|
1917
|
+
"Wallet not connected"
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
return [this.wallet.address];
|
|
1921
|
+
}
|
|
1922
|
+
/**
|
|
1923
|
+
* Get accounts
|
|
1924
|
+
*/
|
|
1925
|
+
async eth_accounts() {
|
|
1926
|
+
if (!this.wallet) {
|
|
1927
|
+
return [];
|
|
1928
|
+
}
|
|
1929
|
+
return [this.wallet.address];
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Get chain ID
|
|
1933
|
+
*/
|
|
1934
|
+
async eth_chainId() {
|
|
1935
|
+
return numberToHex(this.chainId);
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Send transaction
|
|
1939
|
+
*/
|
|
1940
|
+
async eth_sendTransaction(params) {
|
|
1941
|
+
if (!this.wallet) {
|
|
1942
|
+
throw new ProviderRpcError(
|
|
1943
|
+
ProviderErrorCode.UNAUTHORIZED,
|
|
1944
|
+
"Wallet not connected"
|
|
1945
|
+
);
|
|
1946
|
+
}
|
|
1947
|
+
if (!Array.isArray(params) || params.length === 0) {
|
|
1948
|
+
throw new ProviderRpcError(
|
|
1949
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
1950
|
+
"Invalid transaction params"
|
|
1951
|
+
);
|
|
1952
|
+
}
|
|
1953
|
+
resolveEvmSignType(params[0]);
|
|
1954
|
+
const assertOperation = this.captureWalletOperation();
|
|
1955
|
+
const resolved = await this.awaitWalletOperation(
|
|
1956
|
+
assertOperation,
|
|
1957
|
+
async () => this.callInterceptor("eth_sendTransaction", params)
|
|
1958
|
+
);
|
|
1959
|
+
const tx = params[0];
|
|
1960
|
+
logger2.debug("eth_sendTransaction incoming gas params:", {
|
|
1961
|
+
gas: tx.gas ?? tx.gasLimit,
|
|
1962
|
+
gasPrice: tx.gasPrice,
|
|
1963
|
+
maxFeePerGas: tx.maxFeePerGas,
|
|
1964
|
+
maxPriorityFeePerGas: tx.maxPriorityFeePerGas
|
|
1965
|
+
});
|
|
1966
|
+
if (resolved) {
|
|
1967
|
+
if (resolved.data) {
|
|
1968
|
+
tx.data = resolved.data;
|
|
1969
|
+
}
|
|
1970
|
+
if (resolved.gasFee?.maxFeePerGas) {
|
|
1971
|
+
try {
|
|
1972
|
+
const maxFeeWei = parseGwei(resolved.gasFee.maxFeePerGas);
|
|
1973
|
+
tx.maxFeePerGas = `0x${maxFeeWei.toString(16)}`;
|
|
1974
|
+
} catch (error) {
|
|
1975
|
+
assertOperation();
|
|
1976
|
+
logger2.error("Failed to parse maxFeePerGas:", error);
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
if (resolved.gasFee?.maxPriorityFeePerGas) {
|
|
1980
|
+
try {
|
|
1981
|
+
const priorityFeeWei = parseGwei(
|
|
1982
|
+
resolved.gasFee.maxPriorityFeePerGas
|
|
1983
|
+
);
|
|
1984
|
+
tx.maxPriorityFeePerGas = `0x${priorityFeeWei.toString(16)}`;
|
|
1985
|
+
} catch (error) {
|
|
1986
|
+
assertOperation();
|
|
1987
|
+
logger2.error("Failed to parse maxPriorityFeePerGas:", error);
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
logger2.debug("eth_sendTransaction final gas params:", {
|
|
1992
|
+
gas: tx.gas ?? tx.gasLimit,
|
|
1993
|
+
gasPrice: tx.gasPrice,
|
|
1994
|
+
maxFeePerGas: tx.maxFeePerGas,
|
|
1995
|
+
maxPriorityFeePerGas: tx.maxPriorityFeePerGas
|
|
1996
|
+
});
|
|
1997
|
+
const isContractDeployment = !tx.to || tx.to === "0x" || tx.to === "0x0" || tx.to === "0x0000000000000000000000000000000000000000";
|
|
1998
|
+
if (isContractDeployment) {
|
|
1999
|
+
tx.to = "0x";
|
|
2000
|
+
} else if (!tx.to) {
|
|
2001
|
+
throw new ProviderRpcError(
|
|
2002
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2003
|
+
'Transaction must have "to" field'
|
|
2004
|
+
);
|
|
2005
|
+
}
|
|
2006
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2007
|
+
const pinHash = api.isAccessKeyMode() ? void 0 : this.getSharedCredentials()?.getPinHash() || void 0;
|
|
2008
|
+
if (!pinHash && !api.isAccessKeyMode()) {
|
|
2009
|
+
throw new ProviderRpcError(
|
|
2010
|
+
ProviderErrorCode.INTERNAL_ERROR,
|
|
2011
|
+
"PIN hash not found. Please login again."
|
|
2012
|
+
);
|
|
2013
|
+
}
|
|
2014
|
+
const email = this.getRecoveryEmail();
|
|
2015
|
+
const chainKey = getChainKey(this.chainId);
|
|
2016
|
+
const gaslessConfig = getGaslessConfig();
|
|
2017
|
+
const preEstimatedFee = resolved?.gaslessInfo?.canGasless ? resolved.gaslessInfo.feeEstimate : void 0;
|
|
2018
|
+
this.showPendingTx({ network: chainKey, chain: "evm" });
|
|
2019
|
+
const shouldTryGasless = (preEstimatedFee || gaslessConfig?.enabled) && isGaslessEligible(tx);
|
|
2020
|
+
if (shouldTryGasless) {
|
|
2021
|
+
const effectiveConfig = gaslessConfig ?? { enabled: true };
|
|
2022
|
+
const attempt = this.gaslessLock.catch(() => {
|
|
2023
|
+
}).then(() => {
|
|
2024
|
+
assertOperation();
|
|
2025
|
+
return this.tryGaslessTransfer(
|
|
2026
|
+
tx,
|
|
2027
|
+
chainKey,
|
|
2028
|
+
pinHash,
|
|
2029
|
+
email,
|
|
2030
|
+
effectiveConfig,
|
|
2031
|
+
preEstimatedFee
|
|
2032
|
+
);
|
|
2033
|
+
});
|
|
2034
|
+
this.gaslessLock = attempt;
|
|
2035
|
+
try {
|
|
2036
|
+
const gaslessResult = await this.awaitWalletOperation(
|
|
2037
|
+
assertOperation,
|
|
2038
|
+
async () => attempt
|
|
2039
|
+
);
|
|
2040
|
+
if (gaslessResult)
|
|
2041
|
+
return gaslessResult;
|
|
2042
|
+
} catch (gaslessError) {
|
|
2043
|
+
assertOperation();
|
|
2044
|
+
const failedTxHash = gaslessError?.txHash || "";
|
|
2045
|
+
this.updateTxResult({
|
|
2046
|
+
txHash: failedTxHash,
|
|
2047
|
+
network: chainKey,
|
|
2048
|
+
chain: "evm",
|
|
2049
|
+
receipt: { status: 0, blockNumber: null, gasUsed: null },
|
|
2050
|
+
...failedTxHash && {
|
|
2051
|
+
explorerUrl: getExplorerTxUrl(this.chainId, failedTxHash)
|
|
2052
|
+
}
|
|
2053
|
+
});
|
|
2054
|
+
console.error("[AbcProvider] Gasless relay failed:", gaslessError);
|
|
2055
|
+
if (failedTxHash)
|
|
2056
|
+
return failedTxHash;
|
|
2057
|
+
throw gaslessError;
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
const rawValue = tx.value || "0x0";
|
|
2061
|
+
const hexValue = rawValue === "0x" ? "0x0" : rawValue;
|
|
2062
|
+
const amountWei = BigInt(hexValue).toString();
|
|
2063
|
+
try {
|
|
2064
|
+
const gasLimit = tx.gas || tx.gasLimit;
|
|
2065
|
+
const result = await this.awaitWalletOperation(
|
|
2066
|
+
assertOperation,
|
|
2067
|
+
async () => api.evm.sendTransaction({
|
|
2068
|
+
chainKey,
|
|
2069
|
+
to: tx.to,
|
|
2070
|
+
amountWei,
|
|
2071
|
+
pin: pinHash,
|
|
2072
|
+
data: tx.data || "0x",
|
|
2073
|
+
waitForReceipt: true,
|
|
2074
|
+
...gasLimit && { gasLimit },
|
|
2075
|
+
...tx.gasPrice && { gasPrice: tx.gasPrice },
|
|
2076
|
+
...tx.maxFeePerGas && { maxFeePerGas: tx.maxFeePerGas },
|
|
2077
|
+
...tx.maxPriorityFeePerGas && {
|
|
2078
|
+
maxPriorityFeePerGas: tx.maxPriorityFeePerGas
|
|
2079
|
+
},
|
|
2080
|
+
...email && { email }
|
|
2081
|
+
})
|
|
2082
|
+
);
|
|
2083
|
+
this.updateTxResult({
|
|
2084
|
+
txHash: result.txHash,
|
|
2085
|
+
network: chainKey,
|
|
2086
|
+
chain: "evm",
|
|
2087
|
+
receipt: result.receipt,
|
|
2088
|
+
explorerUrl: getExplorerTxUrl(this.chainId, result.txHash)
|
|
2089
|
+
});
|
|
2090
|
+
return result.txHash;
|
|
2091
|
+
} catch (error) {
|
|
2092
|
+
assertOperation();
|
|
2093
|
+
this.failTxResult({
|
|
2094
|
+
network: chainKey,
|
|
2095
|
+
chain: "evm",
|
|
2096
|
+
errorMessage: error.message
|
|
2097
|
+
});
|
|
2098
|
+
throw error;
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Attempt gasless relay for an ERC-20 transfer.
|
|
2103
|
+
*
|
|
2104
|
+
* Return semantics (important for double-spend prevention):
|
|
2105
|
+
* - `string` → success, txHash returned
|
|
2106
|
+
* - `null` → estimation found no viable mode, caller should fall back to normal gas
|
|
2107
|
+
* - `throw` → relay execution was attempted and failed, caller must NOT fall back
|
|
2108
|
+
*/
|
|
2109
|
+
async tryGaslessTransfer(tx, chainKey, pinHash, email, gaslessConfig, preEstimatedFee) {
|
|
2110
|
+
const detected = detectErc20Transfer(tx.data);
|
|
2111
|
+
if (!detected)
|
|
2112
|
+
return null;
|
|
2113
|
+
let feeEstimate = preEstimatedFee ?? null;
|
|
2114
|
+
const assertOperation = this.captureWalletOperation();
|
|
2115
|
+
if (!feeEstimate) {
|
|
2116
|
+
try {
|
|
2117
|
+
feeEstimate = await this.awaitWalletOperation(
|
|
2118
|
+
assertOperation,
|
|
2119
|
+
async () => this.gaslessFeeService.estimateFee({
|
|
2120
|
+
chainKey,
|
|
2121
|
+
chainId: this.chainId,
|
|
2122
|
+
tokenAddress: tx.to,
|
|
2123
|
+
fromAddress: this.wallet.address,
|
|
2124
|
+
toAddress: detected.to,
|
|
2125
|
+
amount: detected.amount,
|
|
2126
|
+
gaslessConfig
|
|
2127
|
+
})
|
|
2128
|
+
);
|
|
2129
|
+
} catch (err) {
|
|
2130
|
+
assertOperation();
|
|
2131
|
+
console.warn("[AbcProvider] Gasless fee estimation failed:", err);
|
|
2132
|
+
return null;
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
if (!feeEstimate)
|
|
2136
|
+
return null;
|
|
2137
|
+
const signer = new AbcWaasSigner({
|
|
2138
|
+
pinHash,
|
|
2139
|
+
network: getNetworkName(this.chainId),
|
|
2140
|
+
email
|
|
2141
|
+
});
|
|
2142
|
+
const transferService = new GaslessTransferService({
|
|
2143
|
+
relayerApi: this._sharedRelayerApi,
|
|
2144
|
+
signer
|
|
2145
|
+
});
|
|
2146
|
+
const gaslessResult = await this.awaitWalletOperation(
|
|
2147
|
+
assertOperation,
|
|
2148
|
+
async () => transferService.execute(
|
|
2149
|
+
{
|
|
2150
|
+
chainId: this.chainId,
|
|
2151
|
+
chainKey,
|
|
2152
|
+
fromAddress: this.wallet.address,
|
|
2153
|
+
toAddress: detected.to,
|
|
2154
|
+
tokenAddress: tx.to,
|
|
2155
|
+
amount: detected.amount,
|
|
2156
|
+
feeToken: feeEstimate.feeToken,
|
|
2157
|
+
gaslessMode: feeEstimate.gaslessMode,
|
|
2158
|
+
feeAmountRaw: feeEstimate.feeAmountRaw
|
|
2159
|
+
},
|
|
2160
|
+
gaslessConfig
|
|
2161
|
+
)
|
|
2162
|
+
);
|
|
2163
|
+
this.updateTxResult({
|
|
2164
|
+
txHash: gaslessResult.txHash,
|
|
2165
|
+
network: chainKey,
|
|
2166
|
+
chain: "evm",
|
|
2167
|
+
receipt: { status: 1, blockNumber: null, gasUsed: null },
|
|
2168
|
+
explorerUrl: getExplorerTxUrl(this.chainId, gaslessResult.txHash),
|
|
2169
|
+
gasless: {
|
|
2170
|
+
mode: gaslessResult.gaslessMode,
|
|
2171
|
+
fee: feeEstimate.feeAmount,
|
|
2172
|
+
feeSymbol: gaslessResult.feeToken
|
|
2173
|
+
}
|
|
2174
|
+
});
|
|
2175
|
+
console.log(
|
|
2176
|
+
`[AbcProvider] Gasless transfer success: ${gaslessResult.gaslessMode}, fee=${gaslessResult.feeAmount} ${gaslessResult.feeToken}`
|
|
2177
|
+
);
|
|
2178
|
+
return gaslessResult.txHash;
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Sign transaction (without sending)
|
|
2182
|
+
*/
|
|
2183
|
+
async eth_signTransaction(params) {
|
|
2184
|
+
if (!this.wallet) {
|
|
2185
|
+
throw new ProviderRpcError(
|
|
2186
|
+
ProviderErrorCode.UNAUTHORIZED,
|
|
2187
|
+
"Wallet not connected"
|
|
2188
|
+
);
|
|
2189
|
+
}
|
|
2190
|
+
if (!Array.isArray(params) || params.length === 0) {
|
|
2191
|
+
throw new ProviderRpcError(
|
|
2192
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2193
|
+
"Invalid transaction params"
|
|
2194
|
+
);
|
|
2195
|
+
}
|
|
2196
|
+
const signType = resolveEvmSignType(params[0]);
|
|
2197
|
+
const assertOperation = this.captureWalletOperation();
|
|
2198
|
+
const resolved = await this.awaitWalletOperation(
|
|
2199
|
+
assertOperation,
|
|
2200
|
+
async () => this.callInterceptor("eth_signTransaction", params)
|
|
2201
|
+
);
|
|
2202
|
+
const tx = params[0];
|
|
2203
|
+
if (resolved) {
|
|
2204
|
+
if (resolved.data) {
|
|
2205
|
+
tx.data = resolved.data;
|
|
2206
|
+
}
|
|
2207
|
+
if (resolved.gasFee?.maxFeePerGas) {
|
|
2208
|
+
try {
|
|
2209
|
+
const maxFeeWei = parseGwei(resolved.gasFee.maxFeePerGas);
|
|
2210
|
+
tx.maxFeePerGas = `0x${maxFeeWei.toString(16)}`;
|
|
2211
|
+
} catch (error) {
|
|
2212
|
+
assertOperation();
|
|
2213
|
+
logger2.error("Failed to parse maxFeePerGas:", error);
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
if (resolved.gasFee?.maxPriorityFeePerGas) {
|
|
2217
|
+
try {
|
|
2218
|
+
const priorityFeeWei = parseGwei(
|
|
2219
|
+
resolved.gasFee.maxPriorityFeePerGas
|
|
2220
|
+
);
|
|
2221
|
+
tx.maxPriorityFeePerGas = `0x${priorityFeeWei.toString(16)}`;
|
|
2222
|
+
} catch (error) {
|
|
2223
|
+
assertOperation();
|
|
2224
|
+
logger2.error("Failed to parse maxPriorityFeePerGas:", error);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2229
|
+
const pinHash = this.getSharedCredentials()?.getPinHash() || void 0;
|
|
2230
|
+
const email = this.getRecoveryEmail();
|
|
2231
|
+
const result = await this.awaitWalletOperation(
|
|
2232
|
+
assertOperation,
|
|
2233
|
+
async () => this.withSigningCredentialRetry(
|
|
2234
|
+
() => api.evm.signTransaction({
|
|
2235
|
+
network: getNetworkName(this.chainId),
|
|
2236
|
+
to: tx.to,
|
|
2237
|
+
value: tx.value || "0x0",
|
|
2238
|
+
data: tx.data || "0x",
|
|
2239
|
+
gasLimit: tx.gas || tx.gasLimit,
|
|
2240
|
+
maxFeePerGas: tx.maxFeePerGas,
|
|
2241
|
+
maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
|
|
2242
|
+
nonce: tx.nonce ? String(Number.parseInt(tx.nonce, 16)) : void 0,
|
|
2243
|
+
...signType && { type: signType },
|
|
2244
|
+
...pinHash && { pin: pinHash },
|
|
2245
|
+
...email && { email }
|
|
2246
|
+
})
|
|
2247
|
+
)
|
|
2248
|
+
);
|
|
2249
|
+
return result.signature;
|
|
2250
|
+
}
|
|
2251
|
+
/**
|
|
2252
|
+
* Personal sign (EIP-191)
|
|
2253
|
+
*/
|
|
2254
|
+
async personal_sign(params) {
|
|
2255
|
+
if (!this.wallet) {
|
|
2256
|
+
logger2.error("Wallet not connected");
|
|
2257
|
+
throw new ProviderRpcError(
|
|
2258
|
+
ProviderErrorCode.UNAUTHORIZED,
|
|
2259
|
+
"Wallet not connected"
|
|
2260
|
+
);
|
|
2261
|
+
}
|
|
2262
|
+
if (!Array.isArray(params) || params.length < 2) {
|
|
2263
|
+
logger2.error("Invalid params:", params);
|
|
2264
|
+
throw new ProviderRpcError(
|
|
2265
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2266
|
+
"Invalid personal_sign params"
|
|
2267
|
+
);
|
|
2268
|
+
}
|
|
2269
|
+
const assertOperation = this.captureWalletOperation();
|
|
2270
|
+
await this.awaitWalletOperation(
|
|
2271
|
+
assertOperation,
|
|
2272
|
+
async () => this.callInterceptor("personal_sign", params)
|
|
2273
|
+
);
|
|
2274
|
+
const [message, address] = params;
|
|
2275
|
+
if (address.toLowerCase() !== this.wallet.address.toLowerCase()) {
|
|
2276
|
+
logger2.error("Address mismatch");
|
|
2277
|
+
throw new ProviderRpcError(
|
|
2278
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2279
|
+
"Address does not match connected wallet"
|
|
2280
|
+
);
|
|
2281
|
+
}
|
|
2282
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2283
|
+
const network = getNetworkName(this.chainId);
|
|
2284
|
+
const pinHash = this.getSharedCredentials()?.getPinHash() || void 0;
|
|
2285
|
+
const email = this.getRecoveryEmail();
|
|
2286
|
+
const rawOpts = Array.isArray(params) && params.length > 2 ? params[2] : null;
|
|
2287
|
+
const validPrefixes = ["eip191", "native"];
|
|
2288
|
+
const signaturePrefix = rawOpts != null && typeof rawOpts === "object" && "signaturePrefix" in rawOpts && validPrefixes.includes(rawOpts.signaturePrefix) ? rawOpts.signaturePrefix : void 0;
|
|
2289
|
+
const result = await this.awaitWalletOperation(
|
|
2290
|
+
assertOperation,
|
|
2291
|
+
async () => this.withSigningCredentialRetry(
|
|
2292
|
+
() => api.evm.signPersonal({
|
|
2293
|
+
network,
|
|
2294
|
+
message,
|
|
2295
|
+
address,
|
|
2296
|
+
pin: pinHash,
|
|
2297
|
+
...email && { email },
|
|
2298
|
+
...signaturePrefix && { signaturePrefix }
|
|
2299
|
+
})
|
|
2300
|
+
)
|
|
2301
|
+
);
|
|
2302
|
+
return result.signature;
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* Eth sign
|
|
2306
|
+
*/
|
|
2307
|
+
async eth_sign(params) {
|
|
2308
|
+
if (!Array.isArray(params) || params.length < 2) {
|
|
2309
|
+
throw new ProviderRpcError(
|
|
2310
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2311
|
+
"Invalid eth_sign params"
|
|
2312
|
+
);
|
|
2313
|
+
}
|
|
2314
|
+
const [address, message] = params;
|
|
2315
|
+
return this.personal_sign([message, address]);
|
|
2316
|
+
}
|
|
2317
|
+
/**
|
|
2318
|
+
* Sign typed data (EIP-712)
|
|
2319
|
+
*/
|
|
2320
|
+
async eth_signTypedData(params) {
|
|
2321
|
+
if (!this.wallet) {
|
|
2322
|
+
throw new ProviderRpcError(
|
|
2323
|
+
ProviderErrorCode.UNAUTHORIZED,
|
|
2324
|
+
"Wallet not connected"
|
|
2325
|
+
);
|
|
2326
|
+
}
|
|
2327
|
+
if (!Array.isArray(params) || params.length < 2) {
|
|
2328
|
+
throw new ProviderRpcError(
|
|
2329
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2330
|
+
"Invalid signTypedData params"
|
|
2331
|
+
);
|
|
2332
|
+
}
|
|
2333
|
+
const assertOperation = this.captureWalletOperation();
|
|
2334
|
+
await this.awaitWalletOperation(
|
|
2335
|
+
assertOperation,
|
|
2336
|
+
async () => this.callInterceptor("eth_signTypedData_v4", params)
|
|
2337
|
+
);
|
|
2338
|
+
const [address, typedData] = params;
|
|
2339
|
+
if (address.toLowerCase() !== this.wallet.address.toLowerCase()) {
|
|
2340
|
+
throw new ProviderRpcError(
|
|
2341
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2342
|
+
"Address does not match connected wallet"
|
|
2343
|
+
);
|
|
2344
|
+
}
|
|
2345
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2346
|
+
const network = getNetworkName(this.chainId);
|
|
2347
|
+
const pinHash = this.getSharedCredentials()?.getPinHash() || void 0;
|
|
2348
|
+
const email = this.getRecoveryEmail();
|
|
2349
|
+
const result = await this.awaitWalletOperation(
|
|
2350
|
+
assertOperation,
|
|
2351
|
+
async () => this.withSigningCredentialRetry(
|
|
2352
|
+
() => api.evm.signTypedData({
|
|
2353
|
+
network,
|
|
2354
|
+
typedData: typeof typedData === "string" ? typedData : JSON.stringify(typedData),
|
|
2355
|
+
pin: pinHash,
|
|
2356
|
+
...email && { email }
|
|
2357
|
+
})
|
|
2358
|
+
)
|
|
2359
|
+
);
|
|
2360
|
+
return result.signature;
|
|
2361
|
+
}
|
|
2362
|
+
/**
|
|
2363
|
+
* Return normalized wallet capabilities for ABC embedded wallets.
|
|
2364
|
+
* ABC supports EIP-7702 authorization signing via talken-api.
|
|
2365
|
+
*/
|
|
2366
|
+
async wallet_getCapabilities() {
|
|
2367
|
+
return {
|
|
2368
|
+
supportsTypedDataV4: true,
|
|
2369
|
+
supports7702Authorization: true,
|
|
2370
|
+
supports5792Batch: false,
|
|
2371
|
+
supportsPaymasterService: false,
|
|
2372
|
+
supportsPermit2RelayHints: true,
|
|
2373
|
+
walletType: "abc-embedded"
|
|
2374
|
+
};
|
|
2375
|
+
}
|
|
2376
|
+
/**
|
|
2377
|
+
* Sign EIP-7702 authorization via Talken API.
|
|
2378
|
+
*/
|
|
2379
|
+
async eth_signAuthorization(params) {
|
|
2380
|
+
if (!this.wallet) {
|
|
2381
|
+
throw new ProviderRpcError(
|
|
2382
|
+
ProviderErrorCode.UNAUTHORIZED,
|
|
2383
|
+
"Wallet not connected"
|
|
2384
|
+
);
|
|
2385
|
+
}
|
|
2386
|
+
if (!Array.isArray(params) || params.length < 2) {
|
|
2387
|
+
throw new ProviderRpcError(
|
|
2388
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2389
|
+
"Invalid signAuthorization params"
|
|
2390
|
+
);
|
|
2391
|
+
}
|
|
2392
|
+
const [address, authorization] = params;
|
|
2393
|
+
if (address.toLowerCase() !== this.wallet.address.toLowerCase()) {
|
|
2394
|
+
throw new ProviderRpcError(
|
|
2395
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2396
|
+
"Address does not match connected wallet"
|
|
2397
|
+
);
|
|
2398
|
+
}
|
|
2399
|
+
if (!authorization?.address || authorization.chainId == null || authorization.nonce == null) {
|
|
2400
|
+
throw new ProviderRpcError(
|
|
2401
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2402
|
+
"Authorization payload is incomplete"
|
|
2403
|
+
);
|
|
2404
|
+
}
|
|
2405
|
+
const assertOperation = this.captureWalletOperation();
|
|
2406
|
+
await this.awaitWalletOperation(
|
|
2407
|
+
assertOperation,
|
|
2408
|
+
async () => this.callInterceptor("eth_signAuthorization", params)
|
|
2409
|
+
);
|
|
2410
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2411
|
+
const network = getNetworkName(this.chainId);
|
|
2412
|
+
const pinHash = this.getSharedCredentials()?.getPinHash() || void 0;
|
|
2413
|
+
const email = this.getRecoveryEmail();
|
|
2414
|
+
const chainIdValue = typeof authorization.chainId === "string" ? Number(BigInt(authorization.chainId)) : Number(authorization.chainId);
|
|
2415
|
+
const nonceValue = typeof authorization.nonce === "string" ? BigInt(authorization.nonce).toString() : String(authorization.nonce);
|
|
2416
|
+
const authAddress = authorization.address;
|
|
2417
|
+
const result = await this.awaitWalletOperation(
|
|
2418
|
+
assertOperation,
|
|
2419
|
+
async () => this.withSigningCredentialRetry(
|
|
2420
|
+
() => api.evm.signAuthorization({
|
|
2421
|
+
network,
|
|
2422
|
+
authorization: {
|
|
2423
|
+
chainId: chainIdValue,
|
|
2424
|
+
address: authAddress,
|
|
2425
|
+
nonce: nonceValue
|
|
2426
|
+
},
|
|
2427
|
+
pin: pinHash,
|
|
2428
|
+
...email && { email }
|
|
2429
|
+
})
|
|
2430
|
+
)
|
|
2431
|
+
);
|
|
2432
|
+
return result.authorization;
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* Switch Ethereum chain
|
|
2436
|
+
*/
|
|
2437
|
+
async wallet_switchEthereumChain(params) {
|
|
2438
|
+
if (!Array.isArray(params) || params.length === 0) {
|
|
2439
|
+
throw new ProviderRpcError(
|
|
2440
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2441
|
+
"Invalid switchEthereumChain params"
|
|
2442
|
+
);
|
|
2443
|
+
}
|
|
2444
|
+
const { chainId } = params[0];
|
|
2445
|
+
const newChainId = hexToNumber(chainId);
|
|
2446
|
+
if (this.chainId === newChainId) {
|
|
2447
|
+
return null;
|
|
2448
|
+
}
|
|
2449
|
+
const _previousChainId = this.chainId;
|
|
2450
|
+
this.invalidateWalletOperations();
|
|
2451
|
+
this.chainId = newChainId;
|
|
2452
|
+
if (this.wallet) {
|
|
2453
|
+
this.wallet.chainId = newChainId;
|
|
2454
|
+
}
|
|
2455
|
+
this.gaslessFeeService.clearCache();
|
|
2456
|
+
this.emit("chainChanged", numberToHex(newChainId));
|
|
2457
|
+
return null;
|
|
2458
|
+
}
|
|
2459
|
+
/**
|
|
2460
|
+
* Add Ethereum chain
|
|
2461
|
+
*/
|
|
2462
|
+
async wallet_addEthereumChain(params) {
|
|
2463
|
+
return this.wallet_switchEthereumChain(params);
|
|
2464
|
+
}
|
|
2465
|
+
/**
|
|
2466
|
+
* Get transaction count (nonce) using ABC WaaS API
|
|
2467
|
+
*/
|
|
2468
|
+
async eth_getTransactionCount(params) {
|
|
2469
|
+
const address = params[0]?.toLowerCase();
|
|
2470
|
+
if (!address) {
|
|
2471
|
+
throw new ProviderRpcError(
|
|
2472
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2473
|
+
"Missing address parameter"
|
|
2474
|
+
);
|
|
2475
|
+
}
|
|
2476
|
+
const currentChainId = this.chainId;
|
|
2477
|
+
const assertOperation = this.captureWalletOperation();
|
|
2478
|
+
try {
|
|
2479
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2480
|
+
const response = await this.awaitWalletOperation(
|
|
2481
|
+
assertOperation,
|
|
2482
|
+
async () => api.evm.getNonce(getNetworkName(currentChainId), address)
|
|
2483
|
+
);
|
|
2484
|
+
const nonce = response.result !== void 0 ? typeof response.result === "number" ? `0x${response.result.toString(16)}` : response.result : void 0;
|
|
2485
|
+
if (!nonce) {
|
|
2486
|
+
throw new Error("No result in nonce response");
|
|
2487
|
+
}
|
|
2488
|
+
return nonce;
|
|
2489
|
+
} catch (error) {
|
|
2490
|
+
assertOperation();
|
|
2491
|
+
logger2.error("Failed to get transaction count from ABC WaaS:", error);
|
|
2492
|
+
throw new ProviderRpcError(
|
|
2493
|
+
ProviderErrorCode.INTERNAL_ERROR,
|
|
2494
|
+
`Failed to get transaction count: ${error instanceof Error ? error.message : String(error)}`
|
|
2495
|
+
);
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
/**
|
|
2499
|
+
* Estimate gas for transaction
|
|
2500
|
+
* Uses ABC WaaS gas estimation API with fallback
|
|
2501
|
+
*/
|
|
2502
|
+
async eth_estimateGas(params) {
|
|
2503
|
+
if (!Array.isArray(params) || params.length === 0) {
|
|
2504
|
+
throw new ProviderRpcError(
|
|
2505
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2506
|
+
"Invalid estimateGas params"
|
|
2507
|
+
);
|
|
2508
|
+
}
|
|
2509
|
+
const tx = params[0];
|
|
2510
|
+
if (!tx.to) {
|
|
2511
|
+
throw new ProviderRpcError(
|
|
2512
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2513
|
+
'Transaction must have "to" field'
|
|
2514
|
+
);
|
|
2515
|
+
}
|
|
2516
|
+
const assertOperation = this.captureWalletOperation();
|
|
2517
|
+
try {
|
|
2518
|
+
const response = await this.awaitWalletOperation(
|
|
2519
|
+
assertOperation,
|
|
2520
|
+
async () => this.getTalkenApiClientOrThrow().evm.estimateGas({
|
|
2521
|
+
network: getNetworkName(this.chainId),
|
|
2522
|
+
from: tx.from || this.wallet?.address || "",
|
|
2523
|
+
to: tx.to,
|
|
2524
|
+
value: tx.value,
|
|
2525
|
+
data: tx.data
|
|
2526
|
+
})
|
|
2527
|
+
);
|
|
2528
|
+
if (!response.result) {
|
|
2529
|
+
throw new Error("No result in gas estimate response");
|
|
2530
|
+
}
|
|
2531
|
+
return response.result;
|
|
2532
|
+
} catch (error) {
|
|
2533
|
+
assertOperation();
|
|
2534
|
+
logger2.warn("Gas estimation failed, using fallback:", error);
|
|
2535
|
+
if (tx.data && tx.data !== "0x") {
|
|
2536
|
+
return "0x493e0";
|
|
2537
|
+
}
|
|
2538
|
+
return "0x5208";
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* Execute read-only eth_call via talken-api
|
|
2543
|
+
*/
|
|
2544
|
+
async eth_call(params) {
|
|
2545
|
+
const p = Array.isArray(params) ? params : [];
|
|
2546
|
+
const tx = p[0];
|
|
2547
|
+
if (!tx?.to || !tx?.data) {
|
|
2548
|
+
throw new ProviderRpcError(
|
|
2549
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2550
|
+
"eth_call requires to and data"
|
|
2551
|
+
);
|
|
2552
|
+
}
|
|
2553
|
+
const assertOperation = this.captureWalletOperation();
|
|
2554
|
+
try {
|
|
2555
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2556
|
+
const response = await this.awaitWalletOperation(
|
|
2557
|
+
assertOperation,
|
|
2558
|
+
async () => api.evm.ethCall({
|
|
2559
|
+
network: getNetworkName(this.chainId),
|
|
2560
|
+
to: tx.to,
|
|
2561
|
+
data: tx.data,
|
|
2562
|
+
from: tx.from || this.wallet?.address
|
|
2563
|
+
})
|
|
2564
|
+
);
|
|
2565
|
+
return response?.result ?? response?.data ?? "0x";
|
|
2566
|
+
} catch (error) {
|
|
2567
|
+
assertOperation();
|
|
2568
|
+
throw new ProviderRpcError(
|
|
2569
|
+
ProviderErrorCode.INTERNAL_ERROR,
|
|
2570
|
+
`eth_call failed: ${error instanceof Error ? error.message : String(error)}`
|
|
2571
|
+
);
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
/**
|
|
2575
|
+
* Get native balance via talken-api
|
|
2576
|
+
*/
|
|
2577
|
+
async eth_getBalance(params) {
|
|
2578
|
+
const p = Array.isArray(params) ? params : [];
|
|
2579
|
+
const address = p[0] || this.wallet?.address;
|
|
2580
|
+
if (!address) {
|
|
2581
|
+
throw new ProviderRpcError(
|
|
2582
|
+
ProviderErrorCode.INVALID_PARAMS,
|
|
2583
|
+
"Missing address parameter"
|
|
2584
|
+
);
|
|
2585
|
+
}
|
|
2586
|
+
const assertOperation = this.captureWalletOperation();
|
|
2587
|
+
try {
|
|
2588
|
+
const api = this.getTalkenApiClientOrThrow();
|
|
2589
|
+
const response = await this.awaitWalletOperation(
|
|
2590
|
+
assertOperation,
|
|
2591
|
+
async () => api.evm.getBalance(getNetworkName(this.chainId), address)
|
|
2592
|
+
);
|
|
2593
|
+
return response?.balance ?? "0x0";
|
|
2594
|
+
} catch (error) {
|
|
2595
|
+
assertOperation();
|
|
2596
|
+
throw new ProviderRpcError(
|
|
2597
|
+
ProviderErrorCode.INTERNAL_ERROR,
|
|
2598
|
+
`eth_getBalance failed: ${error instanceof Error ? error.message : String(error)}`
|
|
2599
|
+
);
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
/**
|
|
2603
|
+
* Get current wallet
|
|
2604
|
+
*/
|
|
2605
|
+
getWallet() {
|
|
2606
|
+
try {
|
|
2607
|
+
this.assertWalletSession();
|
|
2608
|
+
} catch {
|
|
2609
|
+
return null;
|
|
2610
|
+
}
|
|
2611
|
+
return this.wallet;
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* Get current chain ID
|
|
2615
|
+
*/
|
|
2616
|
+
getChainId() {
|
|
2617
|
+
return this.chainId;
|
|
2618
|
+
}
|
|
2619
|
+
};
|
|
2620
|
+
function createAbcEvmProvider(talkenApi) {
|
|
2621
|
+
return new AbcEvmProvider(talkenApi);
|
|
2622
|
+
}
|
|
2623
|
+
var createAbcProvider = createAbcEvmProvider;
|
|
2624
|
+
|
|
2625
|
+
export {
|
|
2626
|
+
AbcEvmProvider,
|
|
2627
|
+
createAbcEvmProvider,
|
|
2628
|
+
createAbcProvider
|
|
2629
|
+
};
|