@talken/talkenkit 2.5.1 → 2.5.2

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.
@@ -0,0 +1,843 @@
1
+ "use client";
2
+ import {
3
+ getChainKey,
4
+ getExplorerTxUrl,
5
+ getNetworkName
6
+ } from "./chunk-OASBABPG.js";
7
+ import {
8
+ getCredentialManager
9
+ } from "./chunk-QKK3OPQA.js";
10
+ import {
11
+ hexToNumber,
12
+ numberToHex
13
+ } from "./chunk-PF65YS3T.js";
14
+ import {
15
+ TalkenApiError
16
+ } from "./chunk-4P3SPC44.js";
17
+
18
+ // src/wallets/walletConnectors/abcWallet/abcProvider.ts
19
+ import {
20
+ getShowPendingTransaction,
21
+ getTalkenApiClient,
22
+ getUpdateTransactionResult
23
+ } from "@talken/talkenkit";
24
+ import { parseGwei } from "viem";
25
+ var EventEmitter = class {
26
+ constructor() {
27
+ this.events = /* @__PURE__ */ new Map();
28
+ }
29
+ on(event, listener) {
30
+ if (!this.events.has(event)) {
31
+ this.events.set(event, []);
32
+ }
33
+ this.events.get(event).push(listener);
34
+ return this;
35
+ }
36
+ off(event, listener) {
37
+ const listeners = this.events.get(event);
38
+ if (listeners) {
39
+ const index = listeners.indexOf(listener);
40
+ if (index !== -1) {
41
+ listeners.splice(index, 1);
42
+ }
43
+ }
44
+ return this;
45
+ }
46
+ removeListener(event, listener) {
47
+ return this.off(event, listener);
48
+ }
49
+ emit(event, ...args) {
50
+ const listeners = this.events.get(event);
51
+ if (listeners) {
52
+ for (const listener of listeners) {
53
+ listener(...args);
54
+ }
55
+ return true;
56
+ }
57
+ return false;
58
+ }
59
+ removeAllListeners(event) {
60
+ if (event) {
61
+ this.events.delete(event);
62
+ } else {
63
+ this.events.clear();
64
+ }
65
+ return this;
66
+ }
67
+ };
68
+ var ProviderRpcError = class extends Error {
69
+ constructor(code, message, data) {
70
+ super(message);
71
+ this.code = code;
72
+ this.data = data;
73
+ this.name = "ProviderRpcError";
74
+ }
75
+ };
76
+ var ErrorCode = {
77
+ USER_REJECTED: 4001,
78
+ UNAUTHORIZED: 4100,
79
+ UNSUPPORTED_METHOD: 4200,
80
+ DISCONNECTED: 4900,
81
+ CHAIN_DISCONNECTED: 4901,
82
+ INVALID_PARAMS: -32602,
83
+ INTERNAL_ERROR: -32603
84
+ };
85
+ var AbcEvmProvider = class extends EventEmitter {
86
+ constructor(talkenApi) {
87
+ super();
88
+ this.wallet = null;
89
+ this.chainId = 1;
90
+ // Default to Ethereum mainnet
91
+ this.connected = false;
92
+ this.talkenApi = talkenApi;
93
+ }
94
+ getRecoveryEmail() {
95
+ const walletEmail = this.wallet?.email?.trim();
96
+ if (walletEmail) {
97
+ return walletEmail;
98
+ }
99
+ return getCredentialManager().getEmail() || void 0;
100
+ }
101
+ /**
102
+ * Set wallet information
103
+ */
104
+ setWallet(wallet) {
105
+ const previousAddress = this.wallet?.address;
106
+ const previousChainId = this.chainId;
107
+ this.wallet = wallet;
108
+ this.chainId = wallet.chainId;
109
+ this.connected = true;
110
+ if (previousAddress !== wallet.address) {
111
+ this.emit("accountsChanged", [wallet.address]);
112
+ }
113
+ if (previousChainId !== wallet.chainId) {
114
+ this.emit("chainChanged", numberToHex(wallet.chainId));
115
+ }
116
+ this.emit("connect", { chainId: numberToHex(wallet.chainId) });
117
+ }
118
+ /**
119
+ * Clear wallet (disconnect)
120
+ */
121
+ clearWallet() {
122
+ this.wallet = null;
123
+ this.connected = false;
124
+ this.emit("disconnect", {
125
+ code: ErrorCode.DISCONNECTED,
126
+ message: "User disconnected"
127
+ });
128
+ this.emit("accountsChanged", []);
129
+ }
130
+ /**
131
+ * Set request interceptor for sign confirmation
132
+ * The interceptor is called before signing operations to show confirmation UI
133
+ */
134
+ setRequestInterceptor(interceptor) {
135
+ this.requestInterceptor = interceptor;
136
+ }
137
+ /**
138
+ * Set TalkenApiClient for backend-proxied transaction flow
139
+ * When set, transaction methods will use a single API call instead of multi-step WaaS
140
+ */
141
+ setTalkenApi(talkenApi) {
142
+ this.talkenApi = talkenApi;
143
+ }
144
+ getTalkenApiClientOrThrow() {
145
+ const api = this.talkenApi || getTalkenApiClient();
146
+ if (!api) {
147
+ throw new ProviderRpcError(
148
+ ErrorCode.INTERNAL_ERROR,
149
+ "TalkenApiClient not initialized"
150
+ );
151
+ }
152
+ return api;
153
+ }
154
+ /**
155
+ * Check if an error is a "Missing required wallet fields" 502 from the server.
156
+ * When the server's in-memory signing credential cache is cold, it needs
157
+ * a wallet.generate() call (idempotent create/recover) to repopulate.
158
+ */
159
+ isSigningCredentialError(error) {
160
+ return error instanceof TalkenApiError && error.statusCode === 502 && error.message.includes("Missing required wallet fields");
161
+ }
162
+ /**
163
+ * Refresh server-side signing credentials.
164
+ *
165
+ * Strategy (in priority order):
166
+ * 1. PIN hash in memory → wallet.generate() to repopulate server cache
167
+ * 2. Neither available → throw UNAUTHORIZED
168
+ *
169
+ * Note: sessionStorage-cached credentials (evmCreds) are automatically
170
+ * attached to every signing request by TalkenApiClient, so the server
171
+ * can use them as fallback without a separate refresh call.
172
+ */
173
+ async refreshSigningCredentials() {
174
+ const credMgr = getCredentialManager();
175
+ const pinHash = credMgr.getPinHash();
176
+ const email = this.getRecoveryEmail();
177
+ if (pinHash && email) {
178
+ const api = this.getTalkenApiClientOrThrow();
179
+ console.log(
180
+ "[AbcProvider] Refreshing signing credentials via wallet.generate..."
181
+ );
182
+ await api.wallet.generate(pinHash, email);
183
+ console.log("[AbcProvider] Signing credentials refreshed via PIN");
184
+ return;
185
+ }
186
+ console.warn(
187
+ "[AbcProvider] Cannot refresh signing credentials \u2014 PIN hash or email missing"
188
+ );
189
+ throw new ProviderRpcError(
190
+ ErrorCode.UNAUTHORIZED,
191
+ "Session expired. Please reconnect and verify your PIN."
192
+ );
193
+ }
194
+ /**
195
+ * Wrap a signing operation with auto-retry on "Missing required wallet fields" error.
196
+ * On first failure, refreshes the server's signing credential cache and retries once.
197
+ */
198
+ async withSigningCredentialRetry(operation) {
199
+ try {
200
+ return await operation();
201
+ } catch (error) {
202
+ if (this.isSigningCredentialError(error)) {
203
+ console.log(
204
+ "[AbcProvider] Signing credentials missing on server \u2014 attempting refresh and retry"
205
+ );
206
+ await this.refreshSigningCredentials();
207
+ return await operation();
208
+ }
209
+ throw error;
210
+ }
211
+ }
212
+ /**
213
+ * Call request interceptor if configured
214
+ * Called by specific signing/transaction methods that need user confirmation
215
+ * @returns Resolved transaction with user modifications if changed in confirmation modal
216
+ */
217
+ async callInterceptor(method, params) {
218
+ if (!this.requestInterceptor) {
219
+ return void 0;
220
+ }
221
+ const request = {
222
+ method,
223
+ params,
224
+ chainId: this.chainId,
225
+ address: this.wallet?.address || ""
226
+ };
227
+ return this.requestInterceptor(request);
228
+ }
229
+ /**
230
+ * EIP-1193 request method
231
+ */
232
+ async request(args) {
233
+ const { method, params } = args;
234
+ switch (method) {
235
+ case "eth_requestAccounts":
236
+ return this.eth_requestAccounts();
237
+ case "eth_accounts":
238
+ return this.eth_accounts();
239
+ case "eth_chainId":
240
+ return this.eth_chainId();
241
+ case "eth_sendTransaction":
242
+ case "wallet_sendTransaction":
243
+ return this.eth_sendTransaction(params);
244
+ case "eth_signTransaction":
245
+ return this.eth_signTransaction(params);
246
+ case "personal_sign":
247
+ return this.personal_sign(params);
248
+ case "eth_sign":
249
+ return this.eth_sign(params);
250
+ case "eth_signTypedData":
251
+ case "eth_signTypedData_v3":
252
+ case "eth_signTypedData_v4":
253
+ return this.eth_signTypedData(params);
254
+ case "wallet_getCapabilities":
255
+ return this.wallet_getCapabilities();
256
+ case "eth_signAuthorization":
257
+ return this.eth_signAuthorization(params);
258
+ case "wallet_switchEthereumChain":
259
+ return this.wallet_switchEthereumChain(params);
260
+ case "wallet_addEthereumChain":
261
+ return this.wallet_addEthereumChain(params);
262
+ case "eth_estimateGas":
263
+ return this.eth_estimateGas(params);
264
+ case "eth_getTransactionCount":
265
+ return this.eth_getTransactionCount(
266
+ Array.isArray(params) ? params : []
267
+ );
268
+ case "eth_call":
269
+ return this.eth_call(params);
270
+ case "eth_getBalance":
271
+ return this.eth_getBalance(params);
272
+ case "eth_blockNumber":
273
+ case "eth_gasPrice":
274
+ case "eth_getBlockByHash":
275
+ case "eth_getBlockByNumber":
276
+ case "eth_getCode":
277
+ case "eth_getStorageAt":
278
+ case "eth_getTransactionByHash":
279
+ case "eth_getTransactionReceipt":
280
+ throw new ProviderRpcError(
281
+ ErrorCode.UNSUPPORTED_METHOD,
282
+ `Method ${method} should be handled by RPC provider`
283
+ );
284
+ default:
285
+ throw new ProviderRpcError(
286
+ ErrorCode.UNSUPPORTED_METHOD,
287
+ `Method ${method} not supported`
288
+ );
289
+ }
290
+ }
291
+ /**
292
+ * Request accounts (EIP-1193)
293
+ */
294
+ async eth_requestAccounts() {
295
+ if (!this.wallet) {
296
+ throw new ProviderRpcError(
297
+ ErrorCode.UNAUTHORIZED,
298
+ "Wallet not connected"
299
+ );
300
+ }
301
+ return [this.wallet.address];
302
+ }
303
+ /**
304
+ * Get accounts
305
+ */
306
+ async eth_accounts() {
307
+ if (!this.wallet) {
308
+ return [];
309
+ }
310
+ return [this.wallet.address];
311
+ }
312
+ /**
313
+ * Get chain ID
314
+ */
315
+ async eth_chainId() {
316
+ return numberToHex(this.chainId);
317
+ }
318
+ /**
319
+ * Send transaction
320
+ */
321
+ async eth_sendTransaction(params) {
322
+ if (!this.wallet) {
323
+ throw new ProviderRpcError(
324
+ ErrorCode.UNAUTHORIZED,
325
+ "Wallet not connected"
326
+ );
327
+ }
328
+ if (!Array.isArray(params) || params.length === 0) {
329
+ throw new ProviderRpcError(
330
+ ErrorCode.INVALID_PARAMS,
331
+ "Invalid transaction params"
332
+ );
333
+ }
334
+ const resolved = await this.callInterceptor("eth_sendTransaction", params);
335
+ const tx = params[0];
336
+ console.log("[AbcProvider] eth_sendTransaction incoming gas params:", {
337
+ gas: tx.gas ?? tx.gasLimit,
338
+ gasPrice: tx.gasPrice,
339
+ maxFeePerGas: tx.maxFeePerGas,
340
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas
341
+ });
342
+ if (resolved) {
343
+ if (resolved.data) {
344
+ tx.data = resolved.data;
345
+ }
346
+ if (resolved.gasFee?.maxFeePerGas) {
347
+ try {
348
+ const maxFeeWei = parseGwei(resolved.gasFee.maxFeePerGas);
349
+ tx.maxFeePerGas = `0x${maxFeeWei.toString(16)}`;
350
+ } catch (error) {
351
+ console.error(
352
+ "[AbcProvider] \u274C Failed to parse maxFeePerGas:",
353
+ error
354
+ );
355
+ }
356
+ }
357
+ if (resolved.gasFee?.maxPriorityFeePerGas) {
358
+ try {
359
+ const priorityFeeWei = parseGwei(
360
+ resolved.gasFee.maxPriorityFeePerGas
361
+ );
362
+ tx.maxPriorityFeePerGas = `0x${priorityFeeWei.toString(16)}`;
363
+ } catch (error) {
364
+ console.error(
365
+ "[AbcProvider] \u274C Failed to parse maxPriorityFeePerGas:",
366
+ error
367
+ );
368
+ }
369
+ }
370
+ }
371
+ console.log("[AbcProvider] eth_sendTransaction final gas params:", {
372
+ gas: tx.gas ?? tx.gasLimit,
373
+ gasPrice: tx.gasPrice,
374
+ maxFeePerGas: tx.maxFeePerGas,
375
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas
376
+ });
377
+ const isContractDeployment = !tx.to || tx.to === "0x" || tx.to === "0x0" || tx.to === "0x0000000000000000000000000000000000000000";
378
+ if (isContractDeployment) {
379
+ tx.to = "0x";
380
+ } else if (!tx.to) {
381
+ throw new ProviderRpcError(
382
+ ErrorCode.INVALID_PARAMS,
383
+ 'Transaction must have "to" field'
384
+ );
385
+ }
386
+ const pinHash = getCredentialManager().getPinHash();
387
+ if (!pinHash) {
388
+ throw new ProviderRpcError(
389
+ ErrorCode.INTERNAL_ERROR,
390
+ "PIN hash not found. Please login again."
391
+ );
392
+ }
393
+ const hexValue = tx.value || "0x0";
394
+ const amountWei = BigInt(hexValue).toString();
395
+ const email = this.getRecoveryEmail();
396
+ const chainKey = getChainKey(this.chainId);
397
+ const showPending = getShowPendingTransaction();
398
+ if (showPending) {
399
+ showPending({
400
+ txHash: "",
401
+ network: chainKey,
402
+ chain: "evm",
403
+ explorerUrl: void 0
404
+ });
405
+ }
406
+ const api = this.getTalkenApiClientOrThrow();
407
+ const result = await this.withSigningCredentialRetry(
408
+ () => api.evm.sendTransaction({
409
+ chainKey,
410
+ to: tx.to,
411
+ amountWei,
412
+ pin: pinHash,
413
+ data: tx.data || "0x",
414
+ gasLimit: tx.gas || tx.gasLimit,
415
+ maxFeePerGas: tx.maxFeePerGas,
416
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
417
+ waitForReceipt: true,
418
+ ...email && { email }
419
+ })
420
+ );
421
+ const updateResult = getUpdateTransactionResult();
422
+ if (updateResult) {
423
+ updateResult({
424
+ txHash: result.txHash,
425
+ network: chainKey,
426
+ chain: "evm",
427
+ receipt: result.receipt ?? null,
428
+ explorerUrl: getExplorerTxUrl(this.chainId, result.txHash)
429
+ });
430
+ }
431
+ return result.txHash;
432
+ }
433
+ /**
434
+ * Sign transaction (without sending)
435
+ */
436
+ async eth_signTransaction(params) {
437
+ if (!this.wallet) {
438
+ throw new ProviderRpcError(
439
+ ErrorCode.UNAUTHORIZED,
440
+ "Wallet not connected"
441
+ );
442
+ }
443
+ if (!Array.isArray(params) || params.length === 0) {
444
+ throw new ProviderRpcError(
445
+ ErrorCode.INVALID_PARAMS,
446
+ "Invalid transaction params"
447
+ );
448
+ }
449
+ const resolved = await this.callInterceptor("eth_signTransaction", params);
450
+ const tx = params[0];
451
+ if (resolved) {
452
+ if (resolved.data) {
453
+ tx.data = resolved.data;
454
+ }
455
+ if (resolved.gasFee?.maxFeePerGas) {
456
+ try {
457
+ const maxFeeWei = parseGwei(resolved.gasFee.maxFeePerGas);
458
+ tx.maxFeePerGas = `0x${maxFeeWei.toString(16)}`;
459
+ } catch (error) {
460
+ console.error(
461
+ "[AbcProvider] \u274C Failed to parse maxFeePerGas:",
462
+ error
463
+ );
464
+ }
465
+ }
466
+ if (resolved.gasFee?.maxPriorityFeePerGas) {
467
+ try {
468
+ const priorityFeeWei = parseGwei(
469
+ resolved.gasFee.maxPriorityFeePerGas
470
+ );
471
+ tx.maxPriorityFeePerGas = `0x${priorityFeeWei.toString(16)}`;
472
+ } catch (error) {
473
+ console.error(
474
+ "[AbcProvider] \u274C Failed to parse maxPriorityFeePerGas:",
475
+ error
476
+ );
477
+ }
478
+ }
479
+ }
480
+ const api = this.getTalkenApiClientOrThrow();
481
+ const pinHash = getCredentialManager().getPinHash() || void 0;
482
+ const email = this.getRecoveryEmail();
483
+ const result = await this.withSigningCredentialRetry(
484
+ () => api.evm.signTransaction({
485
+ network: getNetworkName(this.chainId),
486
+ to: tx.to,
487
+ value: tx.value || "0x0",
488
+ data: tx.data || "0x",
489
+ gasLimit: tx.gas || tx.gasLimit,
490
+ maxFeePerGas: tx.maxFeePerGas,
491
+ maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
492
+ nonce: tx.nonce ? String(Number.parseInt(tx.nonce, 16)) : void 0,
493
+ ...pinHash && { pin: pinHash },
494
+ ...email && { email }
495
+ })
496
+ );
497
+ return result.signature;
498
+ }
499
+ /**
500
+ * Personal sign (EIP-191)
501
+ */
502
+ async personal_sign(params) {
503
+ if (!this.wallet) {
504
+ console.error("[AbcProvider] \u274C Wallet not connected");
505
+ throw new ProviderRpcError(
506
+ ErrorCode.UNAUTHORIZED,
507
+ "Wallet not connected"
508
+ );
509
+ }
510
+ if (!Array.isArray(params) || params.length < 2) {
511
+ console.error("[AbcProvider] \u274C Invalid params:", params);
512
+ throw new ProviderRpcError(
513
+ ErrorCode.INVALID_PARAMS,
514
+ "Invalid personal_sign params"
515
+ );
516
+ }
517
+ await this.callInterceptor("personal_sign", params);
518
+ const [message, address] = params;
519
+ if (address.toLowerCase() !== this.wallet.address.toLowerCase()) {
520
+ console.error("[AbcProvider] \u274C Address mismatch");
521
+ throw new ProviderRpcError(
522
+ ErrorCode.INVALID_PARAMS,
523
+ "Address does not match connected wallet"
524
+ );
525
+ }
526
+ const api = this.getTalkenApiClientOrThrow();
527
+ const network = getNetworkName(this.chainId);
528
+ const pinHash = getCredentialManager().getPinHash() || void 0;
529
+ const email = this.getRecoveryEmail();
530
+ const result = await this.withSigningCredentialRetry(
531
+ () => api.evm.signPersonal({
532
+ network,
533
+ message,
534
+ address,
535
+ pin: pinHash,
536
+ ...email && { email }
537
+ })
538
+ );
539
+ return result.signature;
540
+ }
541
+ /**
542
+ * Eth sign
543
+ */
544
+ async eth_sign(params) {
545
+ if (!Array.isArray(params) || params.length < 2) {
546
+ throw new ProviderRpcError(
547
+ ErrorCode.INVALID_PARAMS,
548
+ "Invalid eth_sign params"
549
+ );
550
+ }
551
+ const [address, message] = params;
552
+ return this.personal_sign([message, address]);
553
+ }
554
+ /**
555
+ * Sign typed data (EIP-712)
556
+ */
557
+ async eth_signTypedData(params) {
558
+ if (!this.wallet) {
559
+ throw new ProviderRpcError(
560
+ ErrorCode.UNAUTHORIZED,
561
+ "Wallet not connected"
562
+ );
563
+ }
564
+ if (!Array.isArray(params) || params.length < 2) {
565
+ throw new ProviderRpcError(
566
+ ErrorCode.INVALID_PARAMS,
567
+ "Invalid signTypedData params"
568
+ );
569
+ }
570
+ await this.callInterceptor("eth_signTypedData_v4", params);
571
+ const [address, typedData] = params;
572
+ if (address.toLowerCase() !== this.wallet.address.toLowerCase()) {
573
+ throw new ProviderRpcError(
574
+ ErrorCode.INVALID_PARAMS,
575
+ "Address does not match connected wallet"
576
+ );
577
+ }
578
+ const api = this.getTalkenApiClientOrThrow();
579
+ const network = getNetworkName(this.chainId);
580
+ const pinHash = getCredentialManager().getPinHash() || void 0;
581
+ const email = this.getRecoveryEmail();
582
+ const result = await this.withSigningCredentialRetry(
583
+ () => api.evm.signTypedData({
584
+ network,
585
+ typedData: typeof typedData === "string" ? typedData : JSON.stringify(typedData),
586
+ pin: pinHash,
587
+ ...email && { email }
588
+ })
589
+ );
590
+ return result.signature;
591
+ }
592
+ /**
593
+ * Return normalized wallet capabilities for ABC embedded wallets.
594
+ * ABC supports EIP-7702 authorization signing via talken-api.
595
+ */
596
+ async wallet_getCapabilities() {
597
+ return {
598
+ supportsTypedDataV4: true,
599
+ supports7702Authorization: true,
600
+ supports5792Batch: false,
601
+ supportsPaymasterService: false,
602
+ supportsPermit2RelayHints: true,
603
+ walletType: "abc-embedded"
604
+ };
605
+ }
606
+ /**
607
+ * Sign EIP-7702 authorization via Talken API.
608
+ */
609
+ async eth_signAuthorization(params) {
610
+ if (!this.wallet) {
611
+ throw new ProviderRpcError(
612
+ ErrorCode.UNAUTHORIZED,
613
+ "Wallet not connected"
614
+ );
615
+ }
616
+ if (!Array.isArray(params) || params.length < 2) {
617
+ throw new ProviderRpcError(
618
+ ErrorCode.INVALID_PARAMS,
619
+ "Invalid signAuthorization params"
620
+ );
621
+ }
622
+ const [address, authorization] = params;
623
+ if (address.toLowerCase() !== this.wallet.address.toLowerCase()) {
624
+ throw new ProviderRpcError(
625
+ ErrorCode.INVALID_PARAMS,
626
+ "Address does not match connected wallet"
627
+ );
628
+ }
629
+ if (!authorization?.address || authorization.chainId == null || authorization.nonce == null) {
630
+ throw new ProviderRpcError(
631
+ ErrorCode.INVALID_PARAMS,
632
+ "Authorization payload is incomplete"
633
+ );
634
+ }
635
+ await this.callInterceptor("eth_signAuthorization", params);
636
+ const api = this.getTalkenApiClientOrThrow();
637
+ const network = getNetworkName(this.chainId);
638
+ const pinHash = getCredentialManager().getPinHash() || void 0;
639
+ const email = this.getRecoveryEmail();
640
+ const chainIdValue = typeof authorization.chainId === "string" ? Number(BigInt(authorization.chainId)) : Number(authorization.chainId);
641
+ const nonceValue = typeof authorization.nonce === "string" ? BigInt(authorization.nonce).toString() : String(authorization.nonce);
642
+ const authAddress = authorization.address;
643
+ const result = await this.withSigningCredentialRetry(
644
+ () => api.evm.signAuthorization({
645
+ network,
646
+ authorization: {
647
+ chainId: chainIdValue,
648
+ address: authAddress,
649
+ nonce: nonceValue
650
+ },
651
+ pin: pinHash,
652
+ ...email && { email }
653
+ })
654
+ );
655
+ return result.authorization;
656
+ }
657
+ /**
658
+ * Switch Ethereum chain
659
+ */
660
+ async wallet_switchEthereumChain(params) {
661
+ if (!Array.isArray(params) || params.length === 0) {
662
+ throw new ProviderRpcError(
663
+ ErrorCode.INVALID_PARAMS,
664
+ "Invalid switchEthereumChain params"
665
+ );
666
+ }
667
+ const { chainId } = params[0];
668
+ const newChainId = hexToNumber(chainId);
669
+ if (this.chainId === newChainId) {
670
+ return null;
671
+ }
672
+ const _previousChainId = this.chainId;
673
+ this.chainId = newChainId;
674
+ if (this.wallet) {
675
+ this.wallet.chainId = newChainId;
676
+ }
677
+ this.emit("chainChanged", numberToHex(newChainId));
678
+ return null;
679
+ }
680
+ /**
681
+ * Add Ethereum chain
682
+ */
683
+ async wallet_addEthereumChain(params) {
684
+ return this.wallet_switchEthereumChain(params);
685
+ }
686
+ /**
687
+ * Get transaction count (nonce) using ABC WaaS API
688
+ */
689
+ async eth_getTransactionCount(params) {
690
+ const address = params[0]?.toLowerCase();
691
+ if (!address) {
692
+ throw new ProviderRpcError(
693
+ ErrorCode.INVALID_PARAMS,
694
+ "Missing address parameter"
695
+ );
696
+ }
697
+ const currentChainId = this.chainId;
698
+ try {
699
+ const api = this.getTalkenApiClientOrThrow();
700
+ const response = await api.evm.getNonce(
701
+ getNetworkName(currentChainId),
702
+ address
703
+ );
704
+ const nonce = response.result !== void 0 ? typeof response.result === "number" ? `0x${response.result.toString(16)}` : response.result : void 0;
705
+ if (!nonce) {
706
+ throw new Error("No result in nonce response");
707
+ }
708
+ return nonce;
709
+ } catch (error) {
710
+ console.error(
711
+ "[AbcEvmProvider] \u274C Failed to get transaction count from ABC WaaS:",
712
+ error
713
+ );
714
+ throw new ProviderRpcError(
715
+ ErrorCode.INTERNAL_ERROR,
716
+ `Failed to get transaction count: ${error instanceof Error ? error.message : String(error)}`
717
+ );
718
+ }
719
+ }
720
+ /**
721
+ * Estimate gas for transaction
722
+ * Uses ABC WaaS gas estimation API with fallback
723
+ */
724
+ async eth_estimateGas(params) {
725
+ if (!Array.isArray(params) || params.length === 0) {
726
+ throw new ProviderRpcError(
727
+ ErrorCode.INVALID_PARAMS,
728
+ "Invalid estimateGas params"
729
+ );
730
+ }
731
+ const tx = params[0];
732
+ if (!tx.to) {
733
+ throw new ProviderRpcError(
734
+ ErrorCode.INVALID_PARAMS,
735
+ 'Transaction must have "to" field'
736
+ );
737
+ }
738
+ try {
739
+ const response = await this.getTalkenApiClientOrThrow().evm.estimateGas({
740
+ network: getNetworkName(this.chainId),
741
+ from: tx.from || this.wallet?.address || "",
742
+ to: tx.to,
743
+ value: tx.value,
744
+ data: tx.data
745
+ });
746
+ if (!response.result) {
747
+ throw new Error("No result in gas estimate response");
748
+ }
749
+ return response.result;
750
+ } catch (error) {
751
+ console.warn(
752
+ "[AbcEvmProvider] Gas estimation failed, using fallback:",
753
+ error
754
+ );
755
+ if (tx.data && tx.data !== "0x") {
756
+ return "0x493e0";
757
+ }
758
+ return "0x5208";
759
+ }
760
+ }
761
+ /**
762
+ * Execute read-only eth_call via talken-api
763
+ */
764
+ async eth_call(params) {
765
+ const p = Array.isArray(params) ? params : [];
766
+ const tx = p[0];
767
+ if (!tx?.to || !tx?.data) {
768
+ throw new ProviderRpcError(
769
+ ErrorCode.INVALID_PARAMS,
770
+ "eth_call requires to and data"
771
+ );
772
+ }
773
+ try {
774
+ const api = this.getTalkenApiClientOrThrow();
775
+ const response = await api.evm.ethCall({
776
+ network: getNetworkName(this.chainId),
777
+ to: tx.to,
778
+ data: tx.data,
779
+ from: tx.from || this.wallet?.address
780
+ });
781
+ return response?.result ?? response?.data ?? "0x";
782
+ } catch (error) {
783
+ throw new ProviderRpcError(
784
+ ErrorCode.INTERNAL_ERROR,
785
+ `eth_call failed: ${error instanceof Error ? error.message : String(error)}`
786
+ );
787
+ }
788
+ }
789
+ /**
790
+ * Get native balance via talken-api
791
+ */
792
+ async eth_getBalance(params) {
793
+ const p = Array.isArray(params) ? params : [];
794
+ const address = p[0] || this.wallet?.address;
795
+ if (!address) {
796
+ throw new ProviderRpcError(
797
+ ErrorCode.INVALID_PARAMS,
798
+ "Missing address parameter"
799
+ );
800
+ }
801
+ try {
802
+ const api = this.getTalkenApiClientOrThrow();
803
+ const response = await api.evm.getBalance(
804
+ getNetworkName(this.chainId),
805
+ address
806
+ );
807
+ return response?.balance ?? "0x0";
808
+ } catch (error) {
809
+ throw new ProviderRpcError(
810
+ ErrorCode.INTERNAL_ERROR,
811
+ `eth_getBalance failed: ${error instanceof Error ? error.message : String(error)}`
812
+ );
813
+ }
814
+ }
815
+ /**
816
+ * Check if connected
817
+ */
818
+ isConnected() {
819
+ return this.connected;
820
+ }
821
+ /**
822
+ * Get current wallet
823
+ */
824
+ getWallet() {
825
+ return this.wallet;
826
+ }
827
+ /**
828
+ * Get current chain ID
829
+ */
830
+ getChainId() {
831
+ return this.chainId;
832
+ }
833
+ };
834
+ function createAbcEvmProvider(talkenApi) {
835
+ return new AbcEvmProvider(talkenApi);
836
+ }
837
+ var createAbcProvider = createAbcEvmProvider;
838
+
839
+ export {
840
+ AbcEvmProvider,
841
+ createAbcEvmProvider,
842
+ createAbcProvider
843
+ };