@talken/talkenkit 2.7.5-beta.3 → 2.7.5-beta.5

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