@talken/talkenkit 2.8.5 → 2.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/dist/{abcWallet-EOHU5AIB.js → abcWallet-WTHSP3A6.js} +22 -25
  2. package/dist/{chunk-WGSS57V6.js → chunk-S3KOGN7P.js} +2540 -715
  3. package/dist/gasless/api/ChainConfigApi.d.ts +2 -2
  4. package/dist/gasless/index.d.ts +1 -1
  5. package/dist/gasless/services/GaslessTransferService.d.ts +4 -3
  6. package/dist/gasless/signer/AbcWaasSigner.d.ts +9 -0
  7. package/dist/gasless/signer/GaslessSigner.d.ts +10 -0
  8. package/dist/gasless/signer/WagmiSigner.d.ts +40 -0
  9. package/dist/gasless/signer/index.d.ts +1 -1
  10. package/dist/gasless/utils/delegationGuard.d.ts +11 -11
  11. package/dist/gasless/utils/revokeDelegation.d.ts +22 -23
  12. package/dist/hooks/useMultiChainBalances.d.ts +2 -0
  13. package/dist/index.css +5 -3
  14. package/dist/index.d.ts +2 -1
  15. package/dist/index.js +1279 -584
  16. package/dist/services/AbcAuthService.d.ts +12 -1
  17. package/dist/solana/clusterIdentity.d.ts +5 -0
  18. package/dist/wallets/walletConnectors/abcWallet/AbcCredentialManager.d.ts +0 -1
  19. package/dist/wallets/walletConnectors/abcWallet/AbcCredentialManager.js +3 -3
  20. package/dist/wallets/walletConnectors/abcWallet/AbcEvmAutoConnector.js +4 -4
  21. package/dist/wallets/walletConnectors/abcWallet/AbstractChainProvider.d.ts +11 -0
  22. package/dist/wallets/walletConnectors/abcWallet/AbstractChainProvider.js +5 -2
  23. package/dist/wallets/walletConnectors/abcWallet/StorageService.js +2 -2
  24. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinConnector.d.ts +2 -0
  25. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinConnector.js +7 -5
  26. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinProvider.d.ts +1 -0
  27. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinProvider.js +10 -9
  28. package/dist/wallets/walletConnectors/abcWallet/abcConnector.js +23 -21
  29. package/dist/wallets/walletConnectors/abcWallet/abcProvider.d.ts +1 -0
  30. package/dist/wallets/walletConnectors/abcWallet/abcProvider.js +12 -11
  31. package/dist/wallets/walletConnectors/abcWallet/abcSolanaProvider.js +26 -24
  32. package/dist/wallets/walletConnectors/abcWallet/abcSolanaWalletAdapter.d.ts +3 -0
  33. package/dist/wallets/walletConnectors/abcWallet/abcSolanaWalletAdapter.js +183 -62
  34. package/dist/wallets/walletConnectors/abcWallet/abcTronProvider.d.ts +1 -0
  35. package/dist/wallets/walletConnectors/abcWallet/abcTronProvider.js +10 -9
  36. package/dist/wallets/walletConnectors/abcWallet/abcWallet.js +24 -22
  37. package/dist/wallets/walletConnectors/abcWallet/abcXrplProvider.d.ts +1 -0
  38. package/dist/wallets/walletConnectors/abcWallet/abcXrplProvider.js +10 -9
  39. package/dist/wallets/walletConnectors/abcWallet/api/AccessKeySessionBinding.d.ts +10 -0
  40. package/dist/wallets/walletConnectors/abcWallet/api/AccessKeySessionBinding.js +13 -0
  41. package/dist/wallets/walletConnectors/abcWallet/api/ConfigApi.js +5 -2
  42. package/dist/wallets/walletConnectors/abcWallet/api/GasApi.js +5 -1
  43. package/dist/wallets/walletConnectors/abcWallet/api/SolanaApi.js +5 -1
  44. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.d.ts +34 -12
  45. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.js +19 -16
  46. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiSingleton.d.ts +6 -0
  47. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiSingleton.js +10 -1
  48. package/dist/wallets/walletConnectors/abcWallet/api/TokenApi.js +5 -2
  49. package/dist/wallets/walletConnectors/abcWallet/api/WalletscanApi.js +13 -3
  50. package/dist/wallets/walletConnectors/abcWallet/api/index.js +26 -23
  51. package/dist/wallets/walletConnectors/abcWallet/api/modules/auth.d.ts +20 -10
  52. package/dist/wallets/walletConnectors/abcWallet/api/modules/auth.js +3 -3
  53. package/dist/wallets/walletConnectors/abcWallet/api/modules/bitcoin.js +11 -9
  54. package/dist/wallets/walletConnectors/abcWallet/api/modules/evm.d.ts +1 -1
  55. package/dist/wallets/walletConnectors/abcWallet/api/modules/evm.js +10 -8
  56. package/dist/wallets/walletConnectors/abcWallet/api/modules/executeBodies.js +4 -3
  57. package/dist/wallets/walletConnectors/abcWallet/api/modules/signBodies.js +2 -2
  58. package/dist/wallets/walletConnectors/abcWallet/api/modules/signingRefresh.js +6 -5
  59. package/dist/wallets/walletConnectors/abcWallet/api/modules/solana.js +6 -5
  60. package/dist/wallets/walletConnectors/abcWallet/api/modules/tron.js +10 -8
  61. package/dist/wallets/walletConnectors/abcWallet/api/modules/wallet.d.ts +2 -1
  62. package/dist/wallets/walletConnectors/abcWallet/api/modules/wallet.js +2 -2
  63. package/dist/wallets/walletConnectors/abcWallet/api/modules/walletscan.js +2 -2
  64. package/dist/wallets/walletConnectors/abcWallet/api/modules/xrp.js +10 -8
  65. package/dist/wallets/walletConnectors/abcWallet/constants.d.ts +18 -6
  66. package/dist/wallets/walletConnectors/abcWallet/constants.js +13 -3
  67. package/dist/wallets/walletConnectors/abcWallet/index.d.ts +1 -0
  68. package/dist/wallets/walletConnectors/abcWallet/index.js +40 -38
  69. package/dist/wallets/walletConnectors/abcWallet/sessionUtils.js +11 -3
  70. package/dist/wallets/walletConnectors/abcWallet/types/auth.types.d.ts +75 -0
  71. package/dist/wallets/walletConnectors/abcWallet/types/error.types.d.ts +2 -0
  72. package/dist/wallets/walletConnectors/abcWallet/types/error.types.js +5 -3
  73. package/dist/wallets/walletConnectors/abcWallet/types.js +5 -3
  74. package/dist/wallets/walletConnectors/abcWallet/utils.js +4 -4
  75. package/dist/wallets/walletConnectors/abcWallet/walletGeneration.js +6 -5
  76. package/dist/wallets/walletConnectors/chunk-2YCHXOLC.js +53 -0
  77. package/dist/wallets/walletConnectors/{chunk-6MZWQBNQ.js → chunk-3RUQ4ARU.js} +3 -3
  78. package/dist/wallets/walletConnectors/{chunk-MNGSJBPX.js → chunk-3XZJNLAA.js} +128 -77
  79. package/dist/wallets/walletConnectors/chunk-4UMY2AY7.js +414 -0
  80. package/dist/wallets/walletConnectors/chunk-5GTFKQGQ.js +739 -0
  81. package/dist/wallets/walletConnectors/{chunk-XGQUYXTL.js → chunk-5KPLYJOO.js} +12 -407
  82. package/dist/wallets/walletConnectors/{chunk-EGLT3GPM.js → chunk-5V5TLGH6.js} +58 -7
  83. package/dist/wallets/walletConnectors/{chunk-SUPFF4EQ.js → chunk-5ZTGAJ4K.js} +538 -191
  84. package/dist/wallets/walletConnectors/{chunk-PL56SINL.js → chunk-6GE2YBW5.js} +1 -1
  85. package/dist/wallets/walletConnectors/{chunk-M4SNNQU2.js → chunk-AROBVCG2.js} +29 -6
  86. package/dist/wallets/walletConnectors/{chunk-OTLZVWY7.js → chunk-BAKRM7LQ.js} +3 -1
  87. package/dist/wallets/walletConnectors/{chunk-6X2XITQP.js → chunk-BGDDDPVU.js} +3 -3
  88. package/dist/wallets/walletConnectors/{chunk-365TL36N.js → chunk-C3MTWYLE.js} +106 -53
  89. package/dist/wallets/walletConnectors/{chunk-UHVJ6AF6.js → chunk-CBXCYWLB.js} +6 -5
  90. package/dist/wallets/walletConnectors/{chunk-5SRSGEZR.js → chunk-DT2L5ADS.js} +35 -10
  91. package/dist/wallets/walletConnectors/{chunk-DKMR2ML5.js → chunk-DUEQONAP.js} +1 -1
  92. package/dist/wallets/walletConnectors/{chunk-ZBI7MSWF.js → chunk-EJB7HH6N.js} +7 -5
  93. package/dist/wallets/walletConnectors/{chunk-OTLPTGHO.js → chunk-EMFKD777.js} +4 -2
  94. package/dist/wallets/walletConnectors/{chunk-743DKBGG.js → chunk-F2TFFXON.js} +72 -20
  95. package/dist/wallets/walletConnectors/chunk-GM6AIRNT.js +71 -0
  96. package/dist/wallets/walletConnectors/chunk-H63QJV3U.js +84 -0
  97. package/dist/wallets/walletConnectors/chunk-HEZOSHLH.js +446 -0
  98. package/dist/wallets/walletConnectors/{chunk-GO6HUJTP.js → chunk-HJAUM3KX.js} +6 -6
  99. package/dist/wallets/walletConnectors/chunk-ICSPFTBY.js +246 -0
  100. package/dist/wallets/walletConnectors/{chunk-OMZSFUVN.js → chunk-LGFHSL7G.js} +7 -3
  101. package/dist/wallets/walletConnectors/{chunk-V6R6WDOQ.js → chunk-MRUBFVXX.js} +1 -1
  102. package/dist/wallets/walletConnectors/chunk-MZFLUT3E.js +243 -0
  103. package/dist/wallets/walletConnectors/chunk-N7ACKYTK.js +291 -0
  104. package/dist/wallets/walletConnectors/{chunk-RSR35XOZ.js → chunk-NNLRIZSK.js} +11 -7
  105. package/dist/wallets/walletConnectors/chunk-NWHJRPZL.js +158 -0
  106. package/dist/wallets/walletConnectors/{chunk-P64PMEPU.js → chunk-O77UF634.js} +66 -12
  107. package/dist/wallets/walletConnectors/{chunk-4CKIGJZD.js → chunk-PK5XVWRF.js} +81 -32
  108. package/dist/wallets/walletConnectors/{chunk-DFG3BSSC.js → chunk-PS66FDPT.js} +79 -30
  109. package/dist/wallets/walletConnectors/chunk-PWJLUT4Z.js +2629 -0
  110. package/dist/wallets/walletConnectors/chunk-QCVDHC6P.js +210 -0
  111. package/dist/wallets/walletConnectors/{chunk-HMIFFMGK.js → chunk-QNZQZ7IH.js} +26 -16
  112. package/dist/wallets/walletConnectors/chunk-RTECHRPH.js +154 -0
  113. package/dist/wallets/walletConnectors/{chunk-F4JUKZBB.js → chunk-RU6FIXMD.js} +3 -3
  114. package/dist/wallets/walletConnectors/{chunk-ZWIAZOVB.js → chunk-RUYSIXR3.js} +6 -4
  115. package/dist/wallets/walletConnectors/{chunk-TRFREYPH.js → chunk-S75DVWSP.js} +39 -9
  116. package/dist/wallets/walletConnectors/chunk-SN2BNZTO.js +739 -0
  117. package/dist/wallets/walletConnectors/{chunk-YPMD3ZHF.js → chunk-SRXI2XF5.js} +80 -44
  118. package/dist/wallets/walletConnectors/chunk-TOX35ET4.js +307 -0
  119. package/dist/wallets/walletConnectors/{chunk-XPZCOEQL.js → chunk-TPLIG5I7.js} +35 -7
  120. package/dist/wallets/walletConnectors/{chunk-TP4BDK7W.js → chunk-UVPRZEPJ.js} +5 -1
  121. package/dist/wallets/walletConnectors/{chunk-SORKIBWX.js → chunk-WUNGUZIQ.js} +4 -5
  122. package/dist/wallets/walletConnectors/{chunk-2OHHFQQ7.js → chunk-WZMAZENY.js} +3 -1
  123. package/dist/wallets/walletConnectors/chunk-XPOLIWQQ.js +200 -0
  124. package/dist/wallets/walletConnectors/{chunk-DRL2CDHT.js → chunk-YFYJ2CFB.js} +80 -44
  125. package/dist/wallets/walletConnectors/chunk-ZPICFPYN.js +79 -0
  126. package/dist/wallets/walletConnectors/index.js +67 -65
  127. package/package.json +1 -1
  128. package/dist/AbcCredentialManager-WZBF3GHF.js +0 -7
  129. package/dist/TalkenApiSingleton-TECFDCT4.js +0 -9
  130. package/dist/chunk-CUPPBGFC.js +0 -460
  131. package/dist/chunk-R6ZE7JAZ.js +0 -15
  132. package/dist/wallets/walletConnectors/chunk-2M6E3YXU.js +0 -382
  133. package/dist/wallets/walletConnectors/chunk-3DHUDD4U.js +0 -132
  134. package/dist/wallets/walletConnectors/chunk-GAJ4FJTW.js +0 -382
  135. package/dist/wallets/walletConnectors/chunk-R6ZE7JAZ.js +0 -15
package/dist/index.js CHANGED
@@ -1,4 +1,14 @@
1
1
  "use client";
2
+ import {
3
+ darkTheme
4
+ } from "./chunk-PUVP4PUZ.js";
5
+ import {
6
+ midnightTheme
7
+ } from "./chunk-7ZP3ENJ2.js";
8
+ import {
9
+ lightTheme
10
+ } from "./chunk-V22G3VGP.js";
11
+ import "./chunk-DQLAW7KN.js";
2
12
  import {
3
13
  AbcError,
4
14
  AbcErrorCode,
@@ -12,6 +22,8 @@ import {
12
22
  NETWORK_CONFIGS,
13
23
  NetworkType,
14
24
  SESSION_EXPIRED_EVENT,
25
+ STORAGE_NS,
26
+ STORAGE_PREFIX,
15
27
  SessionExpiredError,
16
28
  SolanaApi,
17
29
  SolanaNetwork,
@@ -24,6 +36,7 @@ import {
24
36
  cancelProactiveRefresh,
25
37
  chainIdToNetwork,
26
38
  checkDelegation,
39
+ clearNamespace,
27
40
  clearSession,
28
41
  configureLogger,
29
42
  createConfigApi,
@@ -38,69 +51,61 @@ import {
38
51
  dispatchSessionExpired,
39
52
  encryptWithPin,
40
53
  ensureDelegationCleared,
54
+ get,
41
55
  getBitcoinNetwork,
42
56
  getChainKey,
57
+ getCredentialManager,
43
58
  getEvmNetwork,
44
59
  getExplorerAddressUrl,
45
60
  getExplorerTxUrl,
46
61
  getGaslessConfig,
62
+ getJSON,
47
63
  getLoggerConfig,
48
64
  getNetworkByChainId,
49
65
  getNetworkByParam,
50
66
  getNetworkName,
51
67
  getSharedGaslessFeeService,
68
+ getShowPendingTransaction,
69
+ getShowTransactionResult,
52
70
  getSolanaNetwork,
53
71
  getSupportedChainIds,
54
72
  getSupportedNetworks,
73
+ getTalkenApiClient,
55
74
  getTronNetwork,
75
+ getUpdateTransactionResult,
56
76
  getXrplNetwork,
57
77
  hashPin,
58
78
  isEvmNetwork,
59
79
  isGaslessEligible,
60
80
  isTestnet,
61
81
  loadAuthState,
82
+ loadTgAccessKey,
62
83
  networkNameToChainKey,
63
84
  networkToChainId,
85
+ ownsTalkenApiSession,
86
+ ownsTalkenApiStorage,
87
+ remove,
64
88
  resolveFeeTokensFromConfig,
65
89
  resolveTalkenApiUrl,
66
90
  scheduleProactiveRefresh,
91
+ sendRevokeViaWalletClient,
92
+ set,
67
93
  setGaslessConfig,
94
+ setJSON,
95
+ setShowPendingTransaction,
96
+ setShowTransactionResult,
97
+ setTalkenApiClient,
98
+ setUpdateTransactionResult,
68
99
  setupVisibilityRefresh,
69
100
  toSplRawAmount,
70
101
  validateAmount
71
- } from "./chunk-WGSS57V6.js";
102
+ } from "./chunk-S3KOGN7P.js";
72
103
  import {
73
104
  en_US_default
74
105
  } from "./chunk-X4GSACNW.js";
75
- import {
76
- darkTheme
77
- } from "./chunk-PUVP4PUZ.js";
78
- import {
79
- midnightTheme
80
- } from "./chunk-7ZP3ENJ2.js";
81
- import {
82
- lightTheme
83
- } from "./chunk-V22G3VGP.js";
84
- import "./chunk-DQLAW7KN.js";
85
- import {
86
- getTalkenApiClient,
87
- setTalkenApiClient
88
- } from "./chunk-R6ZE7JAZ.js";
89
- import {
90
- STORAGE_NS,
91
- STORAGE_PREFIX,
92
- clearNamespace,
93
- get,
94
- getCredentialManager,
95
- getJSON,
96
- loadTgAccessKey,
97
- remove,
98
- set,
99
- setJSON
100
- } from "./chunk-CUPPBGFC.js";
101
106
 
102
107
  // src/components/ConnectButton/ConnectButton.tsx
103
- import React105, { useContext as useContext32, useEffect as useEffect38, useState as useState45 } from "react";
108
+ import React105, { useContext as useContext32, useEffect as useEffect39, useState as useState45 } from "react";
104
109
 
105
110
  // src/css/sprinkles.css.ts
106
111
  import { createMapValueFn as _51c72 } from "@vanilla-extract/sprinkles/createUtils";
@@ -199,7 +204,7 @@ function useBitcoinWallet() {
199
204
  wallet: bitcoinWallet,
200
205
  emptyState: emptyWalletState2,
201
206
  requestInterceptor,
202
- importProvider: async () => (await import("./abcWallet-EOHU5AIB.js")).AbcBitcoinProvider,
207
+ importProvider: async () => (await import("./abcWallet-WTHSP3A6.js")).AbcBitcoinProvider,
203
208
  mapState: (nextWallet, provider) => ({
204
209
  address: nextWallet.address,
205
210
  publicKey: nextWallet.publicKey,
@@ -1308,7 +1313,7 @@ var useShowBalance = () => useContext5(ShowBalanceContext);
1308
1313
 
1309
1314
  // src/components/ConnectButton/ConnectButtonRenderer.tsx
1310
1315
  import React104, { useContext as useContext31 } from "react";
1311
- import { useAccount as useAccount21, useConfig as useConfig5 } from "wagmi";
1316
+ import { useAccount as useAccount21, useConfig as useConfig6 } from "wagmi";
1312
1317
 
1313
1318
  // src/contexts/MultiChainContext.tsx
1314
1319
  import { useWallet as useWallet2 } from "@solana/wallet-adapter-react";
@@ -1372,7 +1377,7 @@ function useAbcSolanaState(evmConnected, connector, requestInterceptor) {
1372
1377
  wallet: solanaWallet,
1373
1378
  emptyState: emptyWalletState,
1374
1379
  requestInterceptor,
1375
- importProvider: async () => (await import("./abcWallet-EOHU5AIB.js")).AbcSolanaProvider,
1380
+ importProvider: async () => (await import("./abcWallet-WTHSP3A6.js")).AbcSolanaProvider,
1376
1381
  mapState: (nextWallet, provider) => ({
1377
1382
  address: nextWallet.address,
1378
1383
  publicKey: nextWallet.publicKey,
@@ -1406,6 +1411,12 @@ function useAbcSolanaState(evmConnected, connector, requestInterceptor) {
1406
1411
  };
1407
1412
  }
1408
1413
 
1414
+ // src/solana/clusterIdentity.ts
1415
+ var SOLANA_GENESIS_BY_NETWORK = Object.freeze({
1416
+ solana: "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",
1417
+ solana_devnet: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG"
1418
+ });
1419
+
1409
1420
  // src/hooks/useSolanaActions.ts
1410
1421
  async function sendExternalSolanaTransaction(params) {
1411
1422
  const { transaction, connection, externalWallet, options } = params;
@@ -1452,7 +1463,10 @@ async function normalizeSolanaSignature(signature) {
1452
1463
  );
1453
1464
  }
1454
1465
  function useSolanaActions(activeWallet, abcProvider, externalWallet, connection, solanaApiNetwork) {
1455
- const getWalletscanNetwork = () => process.env.NEXT_PUBLIC_ENVIRONMENT === "production" ? "solana" : "solana_devnet";
1466
+ const assertExternalNetwork = async () => {
1467
+ if (await connection.getGenesisHash() !== SOLANA_GENESIS_BY_NETWORK[solanaApiNetwork])
1468
+ throw new Error("Solana RPC cluster does not match the selected network");
1469
+ };
1456
1470
  const signMessage = async (params) => {
1457
1471
  if (activeWallet.type === "abc") {
1458
1472
  if (!abcProvider) {
@@ -1488,27 +1502,23 @@ function useSolanaActions(activeWallet, abcProvider, externalWallet, connection,
1488
1502
  }
1489
1503
  validateAmount(params.amount);
1490
1504
  const lamports = params.mintAddress ? void 0 : toSplRawAmount(params.amount, 9);
1505
+ await assertExternalNetwork();
1491
1506
  const solanaApi = createSolanaApi();
1492
1507
  if (params.mintAddress) {
1493
- const { PublicKey: PublicKey3, Transaction: Transaction3 } = await import("@solana/web3.js");
1508
+ const { PublicKey: PublicKey4, Transaction: Transaction3 } = await import("@solana/web3.js");
1494
1509
  const {
1495
1510
  getAssociatedTokenAddress,
1496
1511
  createAssociatedTokenAccountIdempotentInstruction,
1497
1512
  createTransferInstruction,
1498
- TOKEN_PROGRAM_ID
1513
+ TOKEN_PROGRAM_ID,
1514
+ getMint
1499
1515
  } = await import("@solana/spl-token");
1500
- const mintPubkey = new PublicKey3(params.mintAddress);
1516
+ const mintPubkey = new PublicKey4(params.mintAddress);
1501
1517
  const fromPubkey2 = externalWallet.publicKey;
1502
- const toPubkey2 = new PublicKey3(params.toAddress);
1503
- const walletscanApi = createWalletscanApi();
1504
- const tokenInfo = await walletscanApi.getContractTokenWithTimeout({
1505
- contractAddress: params.mintAddress,
1506
- networks: solanaApiNetwork
1507
- });
1508
- if (tokenInfo?.decimals == null)
1509
- throw new Error("SPL token decimals are missing or invalid");
1510
- const rawAmount = toSplRawAmount(params.amount, tokenInfo.decimals);
1511
- const { blockhash: blockhash2 } = await solanaApi.getLatestBlockhash(solanaApiNetwork);
1518
+ const toPubkey2 = new PublicKey4(params.toAddress);
1519
+ const { decimals } = await getMint(connection, mintPubkey);
1520
+ const rawAmount = toSplRawAmount(params.amount, decimals);
1521
+ const { blockhash: blockhash2 } = await connection.getLatestBlockhash();
1512
1522
  const fromTokenAccount = await getAssociatedTokenAddress(
1513
1523
  mintPubkey,
1514
1524
  fromPubkey2,
@@ -1554,10 +1564,10 @@ function useSolanaActions(activeWallet, abcProvider, externalWallet, connection,
1554
1564
  });
1555
1565
  return { signature: signature2 };
1556
1566
  }
1557
- const { PublicKey: PublicKey2, SystemProgram, Transaction: Transaction2 } = await import("@solana/web3.js");
1558
- const { blockhash } = await solanaApi.getLatestBlockhash(solanaApiNetwork);
1567
+ const { PublicKey: PublicKey3, SystemProgram, Transaction: Transaction2 } = await import("@solana/web3.js");
1568
+ const { blockhash } = await connection.getLatestBlockhash();
1559
1569
  const fromPubkey = externalWallet.publicKey;
1560
- const toPubkey = new PublicKey2(params.toAddress);
1570
+ const toPubkey = new PublicKey3(params.toAddress);
1561
1571
  const transaction = new Transaction2().add(
1562
1572
  SystemProgram.transfer({
1563
1573
  fromPubkey,
@@ -1591,23 +1601,28 @@ function useSolanaActions(activeWallet, abcProvider, externalWallet, connection,
1591
1601
  if (!externalWallet.publicKey) {
1592
1602
  throw new Error("Wallet not connected");
1593
1603
  }
1594
- const walletscanApi = createWalletscanApi();
1595
- const balance = await walletscanApi.getWalletTokenBalanceWithTimeout({
1596
- walletAddress: externalWallet.publicKey.toBase58(),
1597
- networks: getWalletscanNetwork(),
1598
- contractAddress: mintAddress
1599
- });
1600
- if (!balance) {
1601
- return {
1602
- amount: "0",
1603
- decimals: 0,
1604
- uiAmount: 0
1605
- };
1604
+ await assertExternalNetwork();
1605
+ const { PublicKey: PublicKey3 } = await import("@solana/web3.js");
1606
+ const { getMint, unpackAccount, TOKEN_PROGRAM_ID } = await import("@solana/spl-token");
1607
+ const mint = new PublicKey3(mintAddress);
1608
+ const { decimals } = await getMint(connection, mint);
1609
+ const accounts = await connection.getTokenAccountsByOwner(
1610
+ externalWallet.publicKey,
1611
+ { mint }
1612
+ );
1613
+ let amount = BigInt(0);
1614
+ for (const { pubkey, account } of accounts.value) {
1615
+ const token = unpackAccount(pubkey, account, TOKEN_PROGRAM_ID);
1616
+ if (!token.mint.equals(mint) || !token.owner.equals(externalWallet.publicKey))
1617
+ throw new Error(
1618
+ "Solana token account does not match the requested owner/mint"
1619
+ );
1620
+ amount += token.amount;
1606
1621
  }
1607
1622
  return {
1608
- amount: String(balance.balance ?? 0),
1609
- decimals: balance.decimals ?? 0,
1610
- uiAmount: balance.hrBalance ?? 0
1623
+ amount: amount.toString(),
1624
+ decimals,
1625
+ uiAmount: Number(amount) / 10 ** decimals
1611
1626
  };
1612
1627
  }
1613
1628
  throw new Error("No Solana wallet connected");
@@ -1725,7 +1740,14 @@ function useSolanaWallet() {
1725
1740
  );
1726
1741
  const stableActions = useMemo6(
1727
1742
  () => actions5,
1728
- [activeWallet.type, activeWallet.isConnected, abcWallet.provider]
1743
+ [
1744
+ activeWallet.type,
1745
+ activeWallet.isConnected,
1746
+ abcWallet.provider,
1747
+ externalWallet,
1748
+ connection,
1749
+ solanaApiNetwork
1750
+ ]
1729
1751
  );
1730
1752
  return {
1731
1753
  address: activeWallet.address,
@@ -2390,50 +2412,142 @@ import React103, {
2390
2412
  createContext as createContext20,
2391
2413
  useCallback as useCallback28,
2392
2414
  useContext as useContext30,
2393
- useEffect as useEffect37,
2415
+ useEffect as useEffect38,
2394
2416
  useMemo as useMemo24,
2395
2417
  useState as useState44
2396
2418
  } from "react";
2397
- import { useAccount as useAccount20, useAccountEffect as useAccountEffect3, useConfig as useConfig4 } from "wagmi";
2419
+ import { useAccount as useAccount20, useAccountEffect as useAccountEffect3, useConfig as useConfig5 } from "wagmi";
2398
2420
 
2399
2421
  // src/components/AccountModal/AccountModal.tsx
2400
2422
  import React67, { useContext as useContext19, useMemo as useMemo19 } from "react";
2401
2423
  import { useAccount as useAccount16, useDisconnect } from "wagmi";
2402
2424
 
2403
2425
  // src/hooks/useMultiChainBalances.ts
2426
+ import { useConnection as useConnection2 } from "@solana/wallet-adapter-react";
2427
+ import { PublicKey } from "@solana/web3.js";
2404
2428
  import { useQueries } from "@tanstack/react-query";
2405
- import { formatUnits } from "viem";
2429
+ import { formatUnits, keccak256, stringToHex } from "viem";
2430
+ import { useConfig as useConfig2 } from "wagmi";
2431
+ import { getPublicClient } from "wagmi/actions";
2432
+ var ownerIds = /* @__PURE__ */ new WeakMap();
2433
+ var nextOwnerId = 0;
2434
+ function ownerId(client) {
2435
+ if (!client)
2436
+ return 0;
2437
+ let id = ownerIds.get(client);
2438
+ if (id === void 0) {
2439
+ id = ++nextOwnerId;
2440
+ ownerIds.set(client, id);
2441
+ }
2442
+ return id;
2443
+ }
2444
+ function matchesWallet(chain, session) {
2445
+ if (chain.walletType !== "abc" || !session)
2446
+ return false;
2447
+ const address = session.wallets[chain.chainType];
2448
+ return !!address && (chain.chainType === "evm" ? address.toLowerCase() === chain.address.toLowerCase() : address === chain.address);
2449
+ }
2406
2450
  function useMultiChainBalances(chains, enabled) {
2451
+ const config = useConfig2();
2452
+ const { connection } = useConnection2();
2453
+ const client = getTalkenApiClient();
2454
+ const session = client?.getAuthenticatedWalletSession();
2455
+ const revision = client?.getSessionRevision();
2456
+ const solanaRpcIdentity = connection?.rpcEndpoint ? keccak256(stringToHex(connection.rpcEndpoint)) : void 0;
2407
2457
  const queries = useQueries({
2408
- queries: chains.map((chain) => ({
2409
- queryKey: createQueryKey("multiChainBalance", {
2410
- address: chain.address,
2411
- network: chain.network
2412
- }),
2413
- queryFn: async () => {
2414
- const api = createWalletscanApi();
2415
- const token = await api.getNativeTokenWithTimeout(
2416
- {
2417
- walletAddress: chain.address,
2418
- networks: chain.network,
2419
- minimalInfo: false
2420
- },
2421
- 3e3
2422
- );
2423
- if (!token)
2424
- return null;
2425
- const decimals = token.decimals ?? 18;
2426
- const value2 = BigInt(String(token.balance ?? 0));
2427
- return {
2428
- decimals,
2429
- formatted: formatUnits(value2, decimals),
2430
- symbol: token.symbol,
2431
- value: value2
2432
- };
2433
- },
2434
- enabled,
2435
- staleTime: 3e4
2436
- }))
2458
+ queries: chains.map((chain) => {
2459
+ const authenticated = matchesWallet(chain, session);
2460
+ const assertCurrent = () => {
2461
+ if (chain.walletType !== "abc")
2462
+ return;
2463
+ const active2 = getTalkenApiClient();
2464
+ if (active2 !== client || active2?.getSessionRevision() !== revision || matchesWallet(chain, active2?.getAuthenticatedWalletSession()) !== authenticated) {
2465
+ throw new Error("Wallet authentication changed; refresh balances");
2466
+ }
2467
+ };
2468
+ return {
2469
+ queryKey: createQueryKey("multiChainBalance", {
2470
+ address: chain.address,
2471
+ network: chain.network,
2472
+ chainType: chain.chainType,
2473
+ chainId: chain.chainId ?? getNetworkByParam(chain.network)?.chainId,
2474
+ solanaRpcIdentity: chain.chainType === "solana" ? solanaRpcIdentity : void 0,
2475
+ authenticated,
2476
+ walletType: chain.walletType ?? "external",
2477
+ session: chain.walletType === "abc" ? [ownerId(client), revision] : void 0
2478
+ }),
2479
+ queryFn: async () => {
2480
+ assertCurrent();
2481
+ const chainId = chain.chainId ?? getNetworkByParam(chain.network)?.chainId;
2482
+ const network = chain.chainType === "evm" ? typeof chainId === "number" ? chainIdToNetwork(chainId) : void 0 : chain.network;
2483
+ if (!authenticated || !network) {
2484
+ if (chain.chainType === "evm") {
2485
+ const configured = config.chains.find(
2486
+ (entry) => entry.id === chainId
2487
+ );
2488
+ if (!configured)
2489
+ throw new Error("Native balance network is not configured");
2490
+ const client2 = getPublicClient(config, {
2491
+ chainId: configured.id
2492
+ });
2493
+ if (!client2)
2494
+ throw new Error("Native balance RPC is unavailable");
2495
+ const value3 = await client2.getBalance({
2496
+ address: chain.address
2497
+ });
2498
+ assertCurrent();
2499
+ const { decimals: decimals2, symbol } = configured.nativeCurrency;
2500
+ return {
2501
+ value: value3,
2502
+ decimals: decimals2,
2503
+ symbol,
2504
+ formatted: formatUnits(value3, decimals2)
2505
+ };
2506
+ }
2507
+ if (chain.chainType === "solana") {
2508
+ if (!connection)
2509
+ return null;
2510
+ const expectedGenesis = SOLANA_GENESIS_BY_NETWORK[chain.network];
2511
+ if (!expectedGenesis || await connection.getGenesisHash() !== expectedGenesis)
2512
+ return null;
2513
+ const value3 = BigInt(
2514
+ await connection.getBalance(new PublicKey(chain.address))
2515
+ );
2516
+ assertCurrent();
2517
+ return {
2518
+ value: value3,
2519
+ decimals: 9,
2520
+ symbol: "SOL",
2521
+ formatted: formatUnits(value3, 9)
2522
+ };
2523
+ }
2524
+ return null;
2525
+ }
2526
+ const api = createWalletscanApi();
2527
+ const token = await api.getNativeTokenWithTimeout(
2528
+ {
2529
+ walletAddress: chain.address,
2530
+ networks: network,
2531
+ minimalInfo: false
2532
+ },
2533
+ 3e3
2534
+ );
2535
+ assertCurrent();
2536
+ if (!token)
2537
+ return null;
2538
+ const decimals = token.decimals ?? 18;
2539
+ const value2 = BigInt(String(token.balance ?? 0));
2540
+ return {
2541
+ decimals,
2542
+ formatted: formatUnits(value2, decimals),
2543
+ symbol: token.symbol,
2544
+ value: value2
2545
+ };
2546
+ },
2547
+ enabled,
2548
+ staleTime: 3e4
2549
+ };
2550
+ })
2437
2551
  });
2438
2552
  const balances = {};
2439
2553
  for (let i = 0; i < chains.length; i++) {
@@ -2468,7 +2582,7 @@ function useTronWallet() {
2468
2582
  wallet: tronWallet,
2469
2583
  emptyState: emptyWalletState2,
2470
2584
  requestInterceptor,
2471
- importProvider: async () => (await import("./abcWallet-EOHU5AIB.js")).AbcTronProvider,
2585
+ importProvider: async () => (await import("./abcWallet-WTHSP3A6.js")).AbcTronProvider,
2472
2586
  mapState: (nextWallet, provider) => ({
2473
2587
  address: nextWallet.address,
2474
2588
  publicKey: nextWallet.publicKey,
@@ -2545,7 +2659,7 @@ function useXrplWallet() {
2545
2659
  wallet: xrplWallet,
2546
2660
  emptyState: emptyWalletState2,
2547
2661
  requestInterceptor,
2548
- importProvider: async () => (await import("./abcWallet-EOHU5AIB.js")).AbcXrplProvider,
2662
+ importProvider: async () => (await import("./abcWallet-WTHSP3A6.js")).AbcXrplProvider,
2549
2663
  mapState: (nextWallet, provider) => ({
2550
2664
  address: nextWallet.address,
2551
2665
  publicKey: nextWallet.publicKey,
@@ -8168,29 +8282,6 @@ function useTransactionResult() {
8168
8282
  return useContext13(TransactionResultContext);
8169
8283
  }
8170
8284
 
8171
- // src/providers/TransactionResultProvider/TransactionResultSingleton.ts
8172
- var _showResult = null;
8173
- var _showPending = null;
8174
- var _updateResult = null;
8175
- function setShowTransactionResult(fn) {
8176
- _showResult = fn;
8177
- }
8178
- function getShowTransactionResult() {
8179
- return _showResult ?? void 0;
8180
- }
8181
- function setShowPendingTransaction(fn) {
8182
- _showPending = fn;
8183
- }
8184
- function getShowPendingTransaction() {
8185
- return _showPending ?? void 0;
8186
- }
8187
- function setUpdateTransactionResult(fn) {
8188
- _updateResult = fn;
8189
- }
8190
- function getUpdateTransactionResult() {
8191
- return _updateResult ?? void 0;
8192
- }
8193
-
8194
8285
  // src/providers/TransactionResultProvider/TransactionResultProvider.tsx
8195
8286
  function TransactionResultProvider({
8196
8287
  disabled,
@@ -8291,7 +8382,7 @@ import {
8291
8382
  isVersionedTransaction
8292
8383
  } from "@solana/wallet-adapter-base";
8293
8384
  import {
8294
- PublicKey
8385
+ PublicKey as PublicKey2
8295
8386
  } from "@solana/web3.js";
8296
8387
  var logger12 = createLogger("AbcSolanaWalletAdapter");
8297
8388
  var AbcWalletName = "ABC Wallet";
@@ -8497,39 +8588,103 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8497
8588
  get readyState() {
8498
8589
  return WalletReadyState.Installed;
8499
8590
  }
8591
+ assertWalletBinding() {
8592
+ this._talkenApi.getSessionRevision();
8593
+ if (getTalkenApiClient() === this._talkenApi && !ownsTalkenApiStorage(this._talkenApi))
8594
+ throw new WalletNotReadyError();
8595
+ if (!ownsTalkenApiSession(this._talkenApi))
8596
+ throw new WalletNotReadyError();
8597
+ if (getTalkenApiClient() !== this._talkenApi || !this._talkenApi.isAccessKeyMode())
8598
+ return;
8599
+ const session = this._talkenApi.getAuthenticatedWalletSession();
8600
+ if (!session || !this._wallet || session.wallets.solana !== this._wallet.address || this._wallet.uid && session.user.uid && String(this._wallet.uid) !== session.user.uid) {
8601
+ throw new WalletNotReadyError(
8602
+ "Please sign in again to bind the Solana wallet."
8603
+ );
8604
+ }
8605
+ }
8606
+ captureWalletOperation() {
8607
+ this.assertWalletBinding();
8608
+ const api = this._talkenApi;
8609
+ const revision = api.getSessionRevision();
8610
+ const wallet = this._wallet;
8611
+ const address = wallet?.address;
8612
+ const publicKey = this._publicKey?.toBase58();
8613
+ const network = this._getSigningNetwork();
8614
+ return () => {
8615
+ if (this._talkenApi !== api || api.getSessionRevision() !== revision || this._wallet !== wallet || this._wallet?.address !== address || this._publicKey?.toBase58() !== publicKey || this._getSigningNetwork() !== network) {
8616
+ throw new WalletNotReadyError(
8617
+ "The wallet session or network changed while the request was pending."
8618
+ );
8619
+ }
8620
+ this.assertWalletBinding();
8621
+ };
8622
+ }
8623
+ async awaitWalletOperation(assertCurrent, operation) {
8624
+ assertCurrent();
8625
+ try {
8626
+ const result = await operation();
8627
+ assertCurrent();
8628
+ return result;
8629
+ } catch (error2) {
8630
+ assertCurrent();
8631
+ throw error2;
8632
+ }
8633
+ }
8500
8634
  /**
8501
8635
  * Connect to ABC Wallet
8502
8636
  */
8503
8637
  async connect() {
8638
+ const originatingApi = this._talkenApi;
8639
+ const originatingNetwork = this._getSigningNetwork();
8640
+ let revision = this._talkenApi.getSessionRevision();
8641
+ const assertCurrent = () => {
8642
+ if (this._talkenApi !== originatingApi || this._getSigningNetwork() !== originatingNetwork)
8643
+ throw new WalletConnectionError(
8644
+ "The wallet context changed during authentication."
8645
+ );
8646
+ if (getTalkenApiClient() === this._talkenApi && !ownsTalkenApiStorage(this._talkenApi))
8647
+ throw new WalletConnectionError("The shared wallet session changed.");
8648
+ if (!ownsTalkenApiSession(this._talkenApi) || this._talkenApi.getSessionRevision() !== revision)
8649
+ throw new WalletConnectionError(
8650
+ "The wallet session changed. Please reconnect."
8651
+ );
8652
+ };
8504
8653
  try {
8654
+ assertCurrent();
8505
8655
  if (this.connecting)
8506
8656
  return;
8507
8657
  if (this.connected && this._publicKey) {
8658
+ this.assertWalletBinding();
8508
8659
  this.emit("connect", this._publicKey);
8509
8660
  return;
8510
8661
  }
8511
8662
  this._connecting = true;
8512
- const authStateRaw = get(STORAGE_NS.ABC, "auth_state");
8663
+ const authStateRaw = ownsTalkenApiStorage(this._talkenApi) ? get(STORAGE_NS.ABC, "auth_state") : null;
8513
8664
  if (authStateRaw) {
8514
8665
  try {
8515
8666
  const authData = JSON.parse(authStateRaw);
8516
- const hasAccessKey = !!loadTgAccessKey();
8667
+ const hasAccessKey = !!this._talkenApi.getAuthenticatedWalletSession();
8517
8668
  if (authData.solanaWallet && (this._talkenApi.isAuthenticated() || hasAccessKey)) {
8518
8669
  const wallet = authData.solanaWallet;
8519
8670
  const keyId = wallet.keyId || wallet.key_id;
8520
8671
  const encryptedShare = wallet.encryptedShare || wallet.encrypted_share;
8521
8672
  const secretStore = wallet.secretStore || wallet.secret_store;
8522
- if (!keyId || !encryptedShare) {
8673
+ if ((!keyId || !encryptedShare) && !this._talkenApi.getAuthenticatedWalletSession()) {
8523
8674
  this._connecting = false;
8524
8675
  return;
8525
8676
  }
8526
8677
  const normalizedWallet = {
8527
8678
  ...wallet,
8528
- keyId,
8529
- encryptedShare,
8679
+ keyId: keyId || "",
8680
+ encryptedShare: encryptedShare || "",
8530
8681
  secretStore: secretStore || ""
8531
8682
  };
8532
8683
  if (!this._talkenApi.isAccessKeyMode() && authData.accessToken) {
8684
+ if (this._talkenApi.getAccessToken() !== authData.accessToken || this._talkenApi.getRefreshToken() !== authData.refreshToken)
8685
+ throw new WalletConnectionError(
8686
+ "Stored wallet credentials do not match this session."
8687
+ );
8533
8688
  this._talkenApi.setTokens(
8534
8689
  authData.accessToken,
8535
8690
  authData.refreshToken,
@@ -8537,13 +8692,14 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8537
8692
  );
8538
8693
  }
8539
8694
  this._wallet = normalizedWallet;
8695
+ this.assertWalletBinding();
8540
8696
  const addressOrPubkey = normalizedWallet.address || normalizedWallet.publicKey;
8541
8697
  try {
8542
- this._publicKey = new PublicKey(addressOrPubkey);
8698
+ this._publicKey = new PublicKey2(addressOrPubkey);
8543
8699
  } catch (_error) {
8544
8700
  const hexKey = addressOrPubkey.startsWith("0x") ? addressOrPubkey.slice(2) : addressOrPubkey;
8545
8701
  const bytes = new Uint8Array(Buffer.from(hexKey, "hex"));
8546
- this._publicKey = new PublicKey(bytes);
8702
+ this._publicKey = new PublicKey2(bytes);
8547
8703
  }
8548
8704
  this._connecting = false;
8549
8705
  const displayAddress2 = this._publicKey.toBase58();
@@ -8553,7 +8709,8 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8553
8709
  this.emit("connect", this._publicKey);
8554
8710
  return;
8555
8711
  }
8556
- if (!this._talkenApi.isAccessKeyMode() && !hasAccessKey) {
8712
+ if (!this._talkenApi.isAccessKeyMode() && !hasAccessKey && ownsTalkenApiStorage(this._talkenApi)) {
8713
+ assertCurrent();
8557
8714
  logger12.info("Not authenticated, clearing session");
8558
8715
  remove(STORAGE_NS.ABC, "auth_state");
8559
8716
  }
@@ -8568,13 +8725,21 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8568
8725
  );
8569
8726
  }
8570
8727
  const authHandler = this._config.onRequestAuth || this._showAuthModal.bind(this);
8571
- await authHandler();
8572
- const loginResponse = await this._talkenApi.auth.loginWithSns({
8573
- token: "demo-token",
8574
- // Simplified authentication for standalone adapter
8575
- service: "google",
8576
- audience: "abc_wallet"
8577
- });
8728
+ const auth = await authHandler();
8729
+ assertCurrent();
8730
+ if (!auth.email || !auth.password)
8731
+ throw new WalletConnectionError(
8732
+ "This adapter requires completed TalkenKit authentication or an email/password auth handler."
8733
+ );
8734
+ const loginResponse = await this._talkenApi.auth.loginWithPassword(
8735
+ auth.email,
8736
+ auth.password
8737
+ );
8738
+ if (getTalkenApiClient() !== this._talkenApi || this._talkenApi.getSessionRevision() !== loginResponse.sessionRevision)
8739
+ throw new WalletConnectionError(
8740
+ "The wallet session changed during authentication."
8741
+ );
8742
+ revision = this._talkenApi.getSessionRevision();
8578
8743
  const expiresAt = Date.now() + loginResponse.expiresIn * 1e3;
8579
8744
  this._talkenApi.setTokens(
8580
8745
  loginResponse.accessToken,
@@ -8583,17 +8748,22 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8583
8748
  );
8584
8749
  const pinHandler = this._config.onRequestPin || this._showPinModal.bind(this);
8585
8750
  const pin = await pinHandler();
8751
+ assertCurrent();
8586
8752
  const pinHash = await hashPin(pin);
8753
+ assertCurrent();
8587
8754
  let walletResult;
8588
8755
  try {
8589
8756
  const response = await this._talkenApi.wallet.generate(pinHash);
8757
+ assertCurrent();
8590
8758
  if (!response.solana) {
8591
8759
  throw new Error("Solana wallet not returned from generation");
8592
8760
  }
8593
8761
  walletResult = response.solana;
8594
8762
  } catch (error2) {
8763
+ assertCurrent();
8595
8764
  if (error2.response?.status === 409 || error2.message?.includes("already exists")) {
8596
8765
  const response = await this._talkenApi.wallet.recover(pinHash);
8766
+ assertCurrent();
8597
8767
  if (!response.solana) {
8598
8768
  throw new Error("Solana wallet not returned from recovery");
8599
8769
  }
@@ -8603,12 +8773,13 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8603
8773
  }
8604
8774
  }
8605
8775
  this._wallet = walletResult;
8776
+ this.assertWalletBinding();
8606
8777
  try {
8607
- this._publicKey = new PublicKey(walletResult.address);
8778
+ this._publicKey = new PublicKey2(walletResult.address);
8608
8779
  } catch {
8609
8780
  const hexKey = walletResult.address.startsWith("0x") ? walletResult.address.slice(2) : walletResult.address;
8610
8781
  const bytes = new Uint8Array(Buffer.from(hexKey, "hex"));
8611
- this._publicKey = new PublicKey(bytes);
8782
+ this._publicKey = new PublicKey2(bytes);
8612
8783
  }
8613
8784
  this._connecting = false;
8614
8785
  const displayAddress = this._publicKey.toBase58();
@@ -8681,28 +8852,41 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8681
8852
  * Sign a message
8682
8853
  */
8683
8854
  async signMessage(message) {
8855
+ const assertOperation = this.captureWalletOperation();
8684
8856
  try {
8857
+ this.assertWalletBinding();
8858
+ const revision = this._talkenApi.getSessionRevision();
8685
8859
  if (!this._wallet)
8686
8860
  throw new WalletNotReadyError();
8687
8861
  const messageText = new TextDecoder().decode(message);
8688
- await this.callInterceptor({
8689
- chain: "solana",
8690
- method: "signMessage",
8691
- address: this._publicKey?.toBase58() || "",
8692
- network: this._config.network || "solana",
8693
- message: messageText
8694
- });
8862
+ await this.awaitWalletOperation(
8863
+ assertOperation,
8864
+ async () => this.callInterceptor({
8865
+ chain: "solana",
8866
+ method: "signMessage",
8867
+ address: this._publicKey?.toBase58() || "",
8868
+ network: this._config.network || "solana",
8869
+ message: messageText
8870
+ })
8871
+ );
8872
+ this.assertWalletBinding();
8873
+ if (this._talkenApi.getSessionRevision() !== revision)
8874
+ throw new WalletNotReadyError();
8695
8875
  const messageHex = Buffer.from(message).toString("hex");
8696
- const pinHash = getCredentialManager().getPinHash() || "";
8697
- const signatureResponse = await this._talkenApi.solana.sign({
8698
- message: messageHex,
8699
- pin: pinHash || void 0,
8700
- network: this._getSigningNetwork()
8701
- });
8876
+ const pinHash = (ownsTalkenApiStorage(this._talkenApi) ? getCredentialManager().getPinHash() : null) || "";
8877
+ const signatureResponse = await this.awaitWalletOperation(
8878
+ assertOperation,
8879
+ async () => this._talkenApi.solana.sign({
8880
+ message: messageHex,
8881
+ pin: pinHash || void 0,
8882
+ network: this._getSigningNetwork()
8883
+ })
8884
+ );
8702
8885
  const sig = signatureResponse.signature;
8703
8886
  const signatureBytes = /^[0-9a-fA-F]+$/.test(sig) && sig.length === 128 ? Buffer.from(sig, "hex") : Buffer.from(sig, "base64");
8704
8887
  return new Uint8Array(signatureBytes);
8705
8888
  } catch (error2) {
8889
+ assertOperation();
8706
8890
  throw new WalletSignMessageError(error2?.message, error2);
8707
8891
  }
8708
8892
  }
@@ -8710,22 +8894,30 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8710
8894
  * Sign a transaction
8711
8895
  */
8712
8896
  async signTransaction(transaction) {
8897
+ const assertOperation = this.captureWalletOperation();
8713
8898
  try {
8714
8899
  if (!this._wallet)
8715
8900
  throw new WalletNotReadyError();
8716
8901
  if (!this._publicKey)
8717
8902
  throw new WalletNotReadyError();
8718
8903
  const instructionsJson = this.serializeTransactionForDisplay(transaction);
8719
- await this.callInterceptor({
8720
- chain: "solana",
8721
- method: "signTransaction",
8722
- address: this._publicKey.toBase58(),
8723
- network: this._config.network || "solana",
8724
- message: instructionsJson,
8725
- isTransaction: true
8726
- });
8727
- return this._signTransactionInternal(transaction);
8904
+ await this.awaitWalletOperation(
8905
+ assertOperation,
8906
+ async () => this.callInterceptor({
8907
+ chain: "solana",
8908
+ method: "signTransaction",
8909
+ address: this._publicKey.toBase58(),
8910
+ network: this._config.network || "solana",
8911
+ message: instructionsJson,
8912
+ isTransaction: true
8913
+ })
8914
+ );
8915
+ return await this.awaitWalletOperation(
8916
+ assertOperation,
8917
+ async () => this._signTransactionInternal(transaction)
8918
+ );
8728
8919
  } catch (error2) {
8920
+ assertOperation();
8729
8921
  if (error2?.code !== 4001 && !error2?.cancelled) {
8730
8922
  logger12.error("signTransaction failed:", error2);
8731
8923
  }
@@ -8736,18 +8928,23 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8736
8928
  * Internal signing logic (no interceptor). Used by signTransaction and sendTransaction.
8737
8929
  */
8738
8930
  async _signTransactionInternal(transaction) {
8931
+ this.assertWalletBinding();
8739
8932
  if (!this._wallet)
8740
8933
  throw new WalletNotReadyError();
8741
8934
  if (!this._publicKey)
8742
8935
  throw new WalletNotReadyError();
8743
8936
  const messageBytes = isVersionedTransaction(transaction) ? transaction.message.serialize() : transaction.serializeMessage();
8744
8937
  const messageHex = Buffer.from(messageBytes).toString("hex");
8745
- const pinHash = getCredentialManager().getPinHash();
8746
- const signatureResponse = await this._talkenApi.solana.sign({
8747
- message: messageHex,
8748
- pin: pinHash || void 0,
8749
- network: this._getSigningNetwork()
8750
- });
8938
+ const pinHash = ownsTalkenApiStorage(this._talkenApi) ? getCredentialManager().getPinHash() : null;
8939
+ const assertOperation = this.captureWalletOperation();
8940
+ const signatureResponse = await this.awaitWalletOperation(
8941
+ assertOperation,
8942
+ async () => this._talkenApi.solana.sign({
8943
+ message: messageHex,
8944
+ pin: pinHash || void 0,
8945
+ network: this._getSigningNetwork()
8946
+ })
8947
+ );
8751
8948
  const signature = Buffer.from(signatureResponse.signature, "hex");
8752
8949
  if (isVersionedTransaction(transaction)) {
8753
8950
  transaction.addSignature(
@@ -8764,8 +8961,12 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8764
8961
  */
8765
8962
  async signAllTransactions(transactions) {
8766
8963
  const signedTransactions = [];
8964
+ const assertOperation = this.captureWalletOperation();
8767
8965
  for (const transaction of transactions) {
8768
- const signed = await this.signTransaction(transaction);
8966
+ const signed = await this.awaitWalletOperation(
8967
+ assertOperation,
8968
+ async () => this.signTransaction(transaction)
8969
+ );
8769
8970
  signedTransactions.push(signed);
8770
8971
  }
8771
8972
  return signedTransactions;
@@ -8777,25 +8978,36 @@ var AbcSolanaWalletAdapter = class extends BaseMessageSignerWalletAdapter {
8777
8978
  * Supports any Solana transaction (SOL, SPL, dApp interactions, etc.).
8778
8979
  */
8779
8980
  async sendTransaction(transaction, connection, options = {}) {
8981
+ const assertOperation = this.captureWalletOperation();
8780
8982
  try {
8781
8983
  if (!this._wallet)
8782
8984
  throw new WalletNotReadyError();
8783
8985
  if (!this._publicKey)
8784
8986
  throw new WalletNotReadyError();
8785
8987
  const instructionsJson = this.serializeTransactionForDisplay(transaction);
8786
- await this.callInterceptor({
8787
- chain: "solana",
8788
- method: "signTransaction",
8789
- address: this._publicKey.toBase58(),
8790
- network: this._config.network || "solana",
8791
- message: instructionsJson,
8792
- isTransaction: true
8793
- });
8794
- const signed = await this._signTransactionInternal(transaction);
8988
+ await this.awaitWalletOperation(
8989
+ assertOperation,
8990
+ async () => this.callInterceptor({
8991
+ chain: "solana",
8992
+ method: "signTransaction",
8993
+ address: this._publicKey.toBase58(),
8994
+ network: this._config.network || "solana",
8995
+ message: instructionsJson,
8996
+ isTransaction: true
8997
+ })
8998
+ );
8999
+ const signed = await this.awaitWalletOperation(
9000
+ assertOperation,
9001
+ async () => this._signTransactionInternal(transaction)
9002
+ );
8795
9003
  const serialized = Buffer.from(signed.serialize());
8796
- const txHash = await connection.sendRawTransaction(serialized, options);
9004
+ const txHash = await this.awaitWalletOperation(
9005
+ assertOperation,
9006
+ async () => connection.sendRawTransaction(serialized, options)
9007
+ );
8797
9008
  return txHash;
8798
9009
  } catch (error2) {
9010
+ assertOperation();
8799
9011
  if (error2?.code !== 4001 && !error2?.cancelled) {
8800
9012
  logger12.error("sendTransaction failed:", error2);
8801
9013
  }
@@ -9058,27 +9270,38 @@ function AbcSolanaAutoConnector() {
9058
9270
  const maxRetries = 3;
9059
9271
  const retryDelay = 500;
9060
9272
  const handleAutoConnect = async () => {
9273
+ const api = getTalkenApiClient();
9274
+ const revision = api?.getSessionRevision();
9275
+ const current = () => !!api && getTalkenApiClient() === api && api.getSessionRevision() === revision && ownsTalkenApiStorage(api);
9061
9276
  if (connected) {
9062
9277
  return;
9063
9278
  }
9064
9279
  if (isConnectingRef.current) {
9065
9280
  return;
9066
9281
  }
9067
- const authData = loadAuthState();
9282
+ const authData = getJSON(
9283
+ STORAGE_NS.ABC,
9284
+ "auth_state"
9285
+ );
9068
9286
  if (authData) {
9287
+ if (!current() || api?.isAccessKeyMode() && !api.getAuthenticatedWalletSession())
9288
+ return;
9069
9289
  try {
9070
9290
  if (authData.solanaWallet?.address) {
9071
9291
  const solWallet = authData.solanaWallet;
9072
9292
  const keyId = solWallet.keyId;
9073
9293
  const encryptedShare = solWallet.encryptedShare;
9074
- if (keyId && encryptedShare) {
9294
+ if (keyId && encryptedShare || api?.getAuthenticatedWalletSession()?.wallets.solana === solWallet.address) {
9075
9295
  const abcWallet = wallets.find(
9076
9296
  (w) => w.adapter.name === "ABC Wallet"
9077
9297
  );
9078
9298
  if (!abcWallet) {
9079
9299
  if (retryCount < maxRetries) {
9080
9300
  retryCount++;
9081
- setTimeout(() => handleAutoConnect(), retryDelay);
9301
+ setTimeout(() => {
9302
+ if (current())
9303
+ void handleAutoConnect();
9304
+ }, retryDelay);
9082
9305
  }
9083
9306
  return;
9084
9307
  }
@@ -9086,17 +9309,29 @@ function AbcSolanaAutoConnector() {
9086
9309
  try {
9087
9310
  select(abcWallet.adapter.name);
9088
9311
  await new Promise((r) => setTimeout(r, 50));
9312
+ if (!current())
9313
+ return;
9089
9314
  await abcWallet.adapter.connect();
9315
+ if (!current())
9316
+ return;
9090
9317
  hasAttemptedRef.current = true;
9091
9318
  return;
9092
9319
  } catch (error2) {
9320
+ if (!current())
9321
+ return;
9093
9322
  const hasAccessKey = loadTgAccessKey();
9094
9323
  if (!hasAccessKey && error2?.message?.includes("requires authentication")) {
9324
+ api?.clearSession();
9325
+ if (!api || !ownsTalkenApiStorage(api))
9326
+ return;
9095
9327
  localStorage.removeItem(`${STORAGE_PREFIX}auth_state`);
9096
9328
  }
9097
9329
  if (retryCount < maxRetries) {
9098
9330
  retryCount++;
9099
- setTimeout(() => handleAutoConnect(), retryDelay);
9331
+ setTimeout(() => {
9332
+ if (current())
9333
+ void handleAutoConnect();
9334
+ }, retryDelay);
9100
9335
  }
9101
9336
  } finally {
9102
9337
  isConnectingRef.current = false;
@@ -9247,7 +9482,7 @@ function setRainbowKitVersion({ version }) {
9247
9482
  }
9248
9483
  function useFingerprint() {
9249
9484
  const fingerprint = useCallback16(() => {
9250
- setRainbowKitVersion({ version: "2.8.5" });
9485
+ setRainbowKitVersion({ version: "2.8.7" });
9251
9486
  }, []);
9252
9487
  useEffect25(() => {
9253
9488
  fingerprint();
@@ -10854,7 +11089,7 @@ function ProfileDetails({
10854
11089
  size: mobile ? "14" : "13",
10855
11090
  weight: "medium"
10856
11091
  },
10857
- `${displayBalance ?? "0"} ${balance?.symbol || chain.symbol}`
11092
+ `${displayBalance ?? "\u2014"} ${balance?.symbol || chain.symbol}`
10858
11093
  )
10859
11094
  )
10860
11095
  );
@@ -10912,7 +11147,7 @@ function ProfileDetails({
10912
11147
 
10913
11148
  // src/components/AccountModal/AccountModal.tsx
10914
11149
  function AccountModal({ onClose, open }) {
10915
- const { address } = useAccount16();
11150
+ const { address, connector } = useAccount16();
10916
11151
  const chainId = useChainId();
10917
11152
  const { ensAvatar } = useProfile({ address });
10918
11153
  const { disconnect } = useDisconnect();
@@ -10927,7 +11162,9 @@ function AccountModal({ onClose, open }) {
10927
11162
  if (address && chainId) {
10928
11163
  chains.push({
10929
11164
  chainType: "evm",
11165
+ walletType: connector?.id === "abc" ? "abc" : "external",
10930
11166
  address,
11167
+ chainId,
10931
11168
  network: getNetworkName(chainId),
10932
11169
  symbol: "ETH",
10933
11170
  iconUrl: "https://coin-images.coingecko.com/coins/images/279/large/ethereum.png?1696501628"
@@ -10936,6 +11173,7 @@ function AccountModal({ onClose, open }) {
10936
11173
  if (solanaWallet?.address && solanaWallet.isConnected) {
10937
11174
  chains.push({
10938
11175
  chainType: "solana",
11176
+ walletType: solanaWallet.type === "abc" ? "abc" : "external",
10939
11177
  address: solanaWallet.address,
10940
11178
  network: solanaWallet.network || "solana",
10941
11179
  symbol: "SOL",
@@ -10945,6 +11183,7 @@ function AccountModal({ onClose, open }) {
10945
11183
  if (bitcoinWallet?.address && bitcoinWallet.isConnected) {
10946
11184
  chains.push({
10947
11185
  chainType: "bitcoin",
11186
+ walletType: "abc",
10948
11187
  address: bitcoinWallet.address,
10949
11188
  network: bitcoinWallet.network || "bitcoin",
10950
11189
  symbol: "BTC",
@@ -10954,6 +11193,7 @@ function AccountModal({ onClose, open }) {
10954
11193
  if (tronWallet?.address && tronWallet.isConnected) {
10955
11194
  chains.push({
10956
11195
  chainType: "tron",
11196
+ walletType: "abc",
10957
11197
  address: tronWallet.address,
10958
11198
  network: tronWallet.network || "tron",
10959
11199
  symbol: "TRX",
@@ -10963,6 +11203,7 @@ function AccountModal({ onClose, open }) {
10963
11203
  if (xrplWallet?.address && xrplWallet.isConnected) {
10964
11204
  chains.push({
10965
11205
  chainType: "xrpl",
11206
+ walletType: "abc",
10966
11207
  address: xrplWallet.address,
10967
11208
  network: xrplWallet.network || "xrpl",
10968
11209
  symbol: "XRP",
@@ -10970,7 +11211,15 @@ function AccountModal({ onClose, open }) {
10970
11211
  });
10971
11212
  }
10972
11213
  return chains;
10973
- }, [address, chainId, solanaWallet, bitcoinWallet, tronWallet, xrplWallet]);
11214
+ }, [
11215
+ address,
11216
+ connector?.id,
11217
+ chainId,
11218
+ solanaWallet,
11219
+ bitcoinWallet,
11220
+ tronWallet,
11221
+ xrplWallet
11222
+ ]);
10974
11223
  const balances = useMultiChainBalances(chainAddresses, open);
10975
11224
  if (!displayAddress) {
10976
11225
  return null;
@@ -11000,7 +11249,7 @@ function AccountModal({ onClose, open }) {
11000
11249
  // src/components/ChainModal/ChainModal.tsx
11001
11250
  import React71, { useContext as useContext21, useState as useState28 } from "react";
11002
11251
  import { useAccount as useAccount17, useDisconnect as useDisconnect2, useSwitchChain } from "wagmi";
11003
- import { useConfig as useConfig2 } from "wagmi";
11252
+ import { useConfig as useConfig3 } from "wagmi";
11004
11253
 
11005
11254
  // src/components/Icons/DisconnectSq.tsx
11006
11255
  import React68 from "react";
@@ -11193,7 +11442,7 @@ var MobileScrollClassName = "ty310n1";
11193
11442
  // src/components/ChainModal/ChainModal.tsx
11194
11443
  function ChainModal({ onClose, open }) {
11195
11444
  const { chainId } = useAccount17();
11196
- const { chains } = useConfig2();
11445
+ const { chains } = useConfig3();
11197
11446
  const [pendingChainId, setPendingChainId] = useState28(null);
11198
11447
  const { switchChain } = useSwitchChain({
11199
11448
  mutation: {
@@ -11354,7 +11603,7 @@ function addRecentSolanaWalletId(walletName2) {
11354
11603
  }
11355
11604
 
11356
11605
  // src/components/ConnectOptions/ConnectOptionsModal.tsx
11357
- import React95, { useContext as useContext24, useEffect as useEffect35, useRef as useRef18, useState as useState39 } from "react";
11606
+ import React95, { useContext as useContext24, useEffect as useEffect36, useRef as useRef19, useState as useState39 } from "react";
11358
11607
  import { useConnect as useConnect2, useConnectors } from "wagmi";
11359
11608
 
11360
11609
  // src/components/Disclaimer/DisclaimerLink.tsx
@@ -11759,7 +12008,6 @@ function AbcWaasAuthSections(props) {
11759
12008
  }
11760
12009
 
11761
12010
  // src/components/ConnectOptions/AbcWaasAuth/hooks/useAbcWaasAuth.ts
11762
- import { getTalkenApiClient as getTalkenApiClient2 } from "@talken/talkenkit";
11763
12011
  import { useState as useState30 } from "react";
11764
12012
  var logger15 = createLogger("useAbcWaasAuth");
11765
12013
  function useAbcWaasAuth(props) {
@@ -11770,27 +12018,8 @@ function useAbcWaasAuth(props) {
11770
12018
  const [error2, setError] = useState30("");
11771
12019
  const [isLoading, setIsLoading] = useState30(false);
11772
12020
  const [loginData, setLoginData] = useState30(null);
11773
- const clearExpiredEncryptedData = () => {
11774
- const expiresAtStr = get(STORAGE_NS.ABC, "expires_at");
11775
- const hasEncryptedTokens = get(STORAGE_NS.ABC, "enc_tokens");
11776
- if (!hasEncryptedTokens)
11777
- return;
11778
- const expiresAt = expiresAtStr ? Number(expiresAtStr) : 0;
11779
- const isExpired = Date.now() >= expiresAt;
11780
- if (isExpired) {
11781
- remove(STORAGE_NS.ABC, "enc_tokens");
11782
- remove(STORAGE_NS.ABC, "enc_salt");
11783
- remove(STORAGE_NS.ABC, "auth_state");
11784
- remove(STORAGE_NS.ABC, "user");
11785
- remove(STORAGE_NS.ABC, "wallet");
11786
- remove(STORAGE_NS.ABC, "solana_wallet");
11787
- remove(STORAGE_NS.ABC, "bitcoin_wallet");
11788
- remove(STORAGE_NS.ABC, "tron_wallet");
11789
- remove(STORAGE_NS.ABC, "xrpl_wallet");
11790
- }
11791
- };
11792
12021
  const getApi = () => {
11793
- const api = getTalkenApiClient2();
12022
+ const api = getTalkenApiClient();
11794
12023
  if (!api) {
11795
12024
  throw new Error("TalkenApiClient not initialized");
11796
12025
  }
@@ -11825,7 +12054,22 @@ function useAbcWaasAuth(props) {
11825
12054
  setError("");
11826
12055
  try {
11827
12056
  const api = getApi();
11828
- clearExpiredEncryptedData();
12057
+ const result = await api.auth.ensureAccessKey({
12058
+ credential: { type: "email_otp", email, otpCode: otp },
12059
+ accessKeyName: `talkenkit_${email}`
12060
+ });
12061
+ const assertLogin = () => {
12062
+ if (getTalkenApiClient() !== api || api.getSessionRevision() !== result.sessionRevision)
12063
+ throw new TalkenApiError(
12064
+ "AUTH_SESSION_CHANGED",
12065
+ "The wallet session changed during login.",
12066
+ 401
12067
+ );
12068
+ };
12069
+ assertLogin();
12070
+ remove(STORAGE_NS.ABC, "enc_tokens");
12071
+ remove(STORAGE_NS.ABC, "enc_salt");
12072
+ getCredentialManager().clear();
11829
12073
  remove(STORAGE_NS.ABC, "auth_state");
11830
12074
  remove(STORAGE_NS.ABC, "user");
11831
12075
  remove(STORAGE_NS.ABC, "wallet");
@@ -11836,15 +12080,10 @@ function useAbcWaasAuth(props) {
11836
12080
  remove(STORAGE_NS.ABC, "access_token");
11837
12081
  remove(STORAGE_NS.ABC, "refresh_token");
11838
12082
  remove(STORAGE_NS.ABC, "expires_at");
11839
- const result = await api.auth.ensureUser(
11840
- email,
11841
- otp,
11842
- `talkenkit_${email}`
11843
- );
11844
- api.setAccessKey(result.accessKey);
11845
12083
  const authState = {
11846
12084
  isAuthenticated: true,
11847
12085
  user: {
12086
+ uid: result.uid,
11848
12087
  email: result.email,
11849
12088
  provider: "email"
11850
12089
  },
@@ -11857,13 +12096,14 @@ function useAbcWaasAuth(props) {
11857
12096
  refreshToken: null,
11858
12097
  expiresAt: null,
11859
12098
  accessKeyMode: true,
11860
- accessKeyExpiresAt: result.accessKeyExpiresAt ?? result.expiresAt ?? null
12099
+ accessKeyExpiresAt: result.accessKeyExpiresAt ? new Date(result.accessKeyExpiresAt).toISOString() : null
11861
12100
  };
11862
12101
  setJSON(STORAGE_NS.ABC, "auth_state", authState);
11863
12102
  setJSON(STORAGE_NS.ABC, "user", authState.user);
11864
12103
  if (typeof window !== "undefined") {
11865
12104
  window.dispatchEvent(new Event("talkenkit_storage_update"));
11866
12105
  }
12106
+ assertLogin();
11867
12107
  const accessKeyLoginData = {
11868
12108
  email: result.email,
11869
12109
  credential: ""
@@ -11908,9 +12148,6 @@ function useAbcWaasAuth(props) {
11908
12148
  // src/components/ConnectOptions/AbcWaasAuth/hooks/useAbcWaasSocial.ts
11909
12149
  import { useState as useState31 } from "react";
11910
12150
 
11911
- // src/services/AbcAuthService.ts
11912
- import { getTalkenApiClient as getTalkenApiClient3 } from "@talken/talkenkit";
11913
-
11914
12151
  // src/wallets/walletConnectors/abcWallet/firebase.ts
11915
12152
  import { initializeApp } from "firebase/app";
11916
12153
  import { getAuth } from "firebase/auth";
@@ -12189,187 +12426,102 @@ async function kakaoLogin() {
12189
12426
  }
12190
12427
  }
12191
12428
 
12192
- // src/services/AbcAuthService.ts
12193
- async function registerUser(params, _config) {
12194
- const api = getTalkenApiClient3();
12195
- if (!api) {
12196
- throw new Error("TalkenApiClient not initialized");
12197
- }
12198
- const res = await api.auth.register({
12199
- email: params.username,
12200
- otpCode: params.emailCode,
12201
- password: params.password,
12202
- name: params.name
12203
- });
12204
- return { status: "success", data: res };
12205
- }
12206
- async function registerSnsUser(params, _config) {
12207
- const api = getTalkenApiClient3();
12208
- if (!api) {
12209
- throw new Error("TalkenApiClient not initialized");
12210
- }
12211
- const res = await api.auth.register({
12212
- email: params.username,
12213
- otpCode: params.sixCode,
12214
- password: "",
12215
- name: params.name
12216
- });
12217
- return { status: "success", data: res };
12218
- }
12219
- async function resetPassword(params, _config) {
12220
- const api = getTalkenApiClient3();
12221
- if (!api) {
12222
- throw new Error("TalkenApiClient not initialized");
12223
- }
12224
- const res = await api.auth.resetPassword(
12225
- params.username,
12226
- params.password,
12227
- params.emailCode
12228
- );
12229
- return { status: "success", data: res };
12230
- }
12231
- async function emailCheck(email, _config) {
12232
- const api = getTalkenApiClient3();
12233
- if (!api) {
12234
- throw new Error("TalkenApiClient not initialized");
12235
- }
12236
- const res = await api.auth.checkEmail(email);
12237
- return {
12238
- status: "success",
12239
- message: { code: res.code || 0, text: res.message || "" }
12429
+ // src/components/ConnectOptions/AbcWaasAuth/hooks/useAbcWaasSocial.ts
12430
+ function useAbcWaasSocial(props) {
12431
+ const { onPinRequired, onEmailSet } = props;
12432
+ const [isLoading, setIsLoading] = useState31(false);
12433
+ const [error2, setError] = useState31("");
12434
+ const captureLogin = () => {
12435
+ const api = getTalkenApiClient();
12436
+ if (!api)
12437
+ throw new Error("TalkenApiClient not initialized");
12438
+ return { api, revision: api.getSessionRevision() };
12240
12439
  };
12241
- }
12242
- async function sendOtpCode(email, _config) {
12243
- const api = getTalkenApiClient3();
12244
- if (!api) {
12245
- throw new Error("TalkenApiClient not initialized");
12246
- }
12247
- await api.auth.sendOtp(email);
12248
- return { status: "success", data: { sent: true } };
12249
- }
12250
- async function verifyOtpCode(email, code, _config) {
12251
- const api = getTalkenApiClient3();
12252
- if (!api) {
12253
- throw new Error("TalkenApiClient not initialized");
12254
- }
12255
- await api.auth.verifyOtp(email, code);
12256
- return { status: "success", data: { verified: true } };
12257
- }
12258
- async function loginWithPassword(params, _apiServer) {
12259
- const api = getTalkenApiClient3();
12260
- if (!api) {
12261
- throw new Error("TalkenApiClient not initialized");
12262
- }
12263
- const res = await api.auth.loginWithPassword(
12264
- params.username,
12265
- params.password
12266
- );
12267
- return {
12268
- access_token: res.accessToken,
12269
- refresh_token: res.refreshToken,
12270
- expires_in: res.expiresIn,
12271
- uid: res.uid,
12272
- email: res.email
12273
- };
12274
- }
12275
- async function performSnsLogin(token, service, email) {
12276
- const api = getTalkenApiClient3();
12277
- if (!api) {
12278
- throw new Error("TalkenApiClient not initialized");
12279
- }
12280
- const res = await api.auth.loginWithSns({ token, service });
12281
- return {
12282
- uid: res.uid,
12283
- access_token: res.accessToken,
12284
- refresh_token: res.refreshToken,
12285
- email: res.email || email,
12286
- user_type: res.isNewUser ? "new" : "existing"
12287
- };
12288
- }
12289
- async function googleLogin2(_config) {
12290
- initializeFirebase();
12291
- const googleAuth = await googleLogin();
12292
- if (!googleAuth)
12293
- return null;
12294
- return performSnsLogin(googleAuth.idToken, "google", googleAuth.email);
12295
- }
12296
- async function appleLogin2(_config) {
12297
- initializeFirebase();
12298
- const appleAuth = await appleLogin();
12299
- if (!appleAuth)
12300
- return null;
12301
- return performSnsLogin(appleAuth.idToken, "apple", appleAuth.email);
12302
- }
12303
- async function kakaoLogin2(_config) {
12304
- const kakaoAuth = await kakaoLogin();
12305
- if (!kakaoAuth)
12306
- return null;
12307
- return performSnsLogin(kakaoAuth.idToken, "kakao", kakaoAuth.email);
12308
- }
12309
-
12310
- // src/components/ConnectOptions/AbcWaasAuth/hooks/useAbcWaasSocial.ts
12311
- function useAbcWaasSocial(props) {
12312
- const { onPinRequired, onEmailSet } = props;
12313
- const [isLoading, setIsLoading] = useState31(false);
12314
- const [error2, setError] = useState31("");
12315
- const clearExpiredEncryptedData = () => {
12316
- const expiresAtStr = get(STORAGE_NS.ABC, "expires_at");
12317
- const hasEncryptedTokens = get(STORAGE_NS.ABC, "enc_tokens");
12318
- if (!hasEncryptedTokens)
12319
- return;
12320
- const expiresAt = expiresAtStr ? Number(expiresAtStr) : 0;
12321
- const isExpired = Date.now() >= expiresAt;
12322
- if (isExpired) {
12323
- remove(STORAGE_NS.ABC, "enc_tokens");
12324
- remove(STORAGE_NS.ABC, "enc_salt");
12325
- remove(STORAGE_NS.ABC, "auth_state");
12326
- remove(STORAGE_NS.ABC, "user");
12327
- remove(STORAGE_NS.ABC, "wallet");
12328
- remove(STORAGE_NS.ABC, "solana_wallet");
12329
- remove(STORAGE_NS.ABC, "bitcoin_wallet");
12330
- remove(STORAGE_NS.ABC, "tron_wallet");
12331
- remove(STORAGE_NS.ABC, "xrpl_wallet");
12440
+ const assertLogin = (session) => {
12441
+ if (getTalkenApiClient() !== session.api || session.api.getSessionRevision() !== session.revision) {
12442
+ throw new TalkenApiError(
12443
+ "AUTH_SESSION_CHANGED",
12444
+ "The wallet session changed during login.",
12445
+ 401
12446
+ );
12332
12447
  }
12333
12448
  };
12334
- const saveAuthState = (response, provider) => {
12449
+ const clearLegacyTokenState = () => {
12450
+ remove(STORAGE_NS.ABC, "enc_tokens");
12451
+ remove(STORAGE_NS.ABC, "enc_salt");
12452
+ getCredentialManager().clear();
12453
+ remove(STORAGE_NS.ABC, "auth_state");
12454
+ remove(STORAGE_NS.ABC, "user");
12455
+ remove(STORAGE_NS.ABC, "wallet");
12456
+ remove(STORAGE_NS.ABC, "solana_wallet");
12457
+ remove(STORAGE_NS.ABC, "bitcoin_wallet");
12458
+ remove(STORAGE_NS.ABC, "tron_wallet");
12459
+ remove(STORAGE_NS.ABC, "xrpl_wallet");
12460
+ remove(STORAGE_NS.ABC, "access_token");
12461
+ remove(STORAGE_NS.ABC, "refresh_token");
12462
+ remove(STORAGE_NS.ABC, "expires_at");
12463
+ };
12464
+ const bootstrapSnsAccessKey = async (service, providerIdToken, email, provider, session) => {
12465
+ assertLogin(session);
12466
+ const api = session.api;
12467
+ const result = await api.auth.ensureAccessKey({
12468
+ credential: { type: "sns", service, token: providerIdToken },
12469
+ accessKeyName: `talkenkit_${email}`
12470
+ });
12471
+ assertLogin({ api, revision: result.sessionRevision });
12472
+ clearLegacyTokenState();
12335
12473
  const authState = {
12336
12474
  isAuthenticated: true,
12337
12475
  user: {
12338
- uid: response.uid,
12339
- email: response.email,
12476
+ uid: result.uid,
12477
+ email: result.email,
12340
12478
  provider
12341
12479
  },
12342
- wallet: null,
12343
- solanaWallet: null,
12344
- accessToken: response.access_token,
12345
- refreshToken: response.refresh_token,
12346
- expiresAt: Date.now() + ((response.expires_in || response.expiresIn || 3600) > 0 ? response.expires_in || response.expiresIn || 3600 : 3600) * 1e3
12480
+ wallet: result.evmAddress ? { address: result.evmAddress, chainId: getEvmNetwork() } : null,
12481
+ solanaWallet: result.addresses?.sol ? { address: result.addresses.sol } : null,
12482
+ bitcoinWallet: result.addresses?.btc ? { address: result.addresses.btc } : null,
12483
+ tronWallet: result.addresses?.trx ? { address: result.addresses.trx } : null,
12484
+ xrplWallet: result.addresses?.xrp ? { address: result.addresses.xrp } : null,
12485
+ accessToken: null,
12486
+ refreshToken: null,
12487
+ expiresAt: null,
12488
+ accessKeyMode: true,
12489
+ accessKeyExpiresAt: result.accessKeyExpiresAt ? new Date(result.accessKeyExpiresAt).toISOString() : null
12347
12490
  };
12348
12491
  setJSON(STORAGE_NS.ABC, "auth_state", authState);
12349
12492
  setJSON(STORAGE_NS.ABC, "user", authState.user);
12350
- set(STORAGE_NS.ABC, "access_token", response.access_token);
12351
- set(STORAGE_NS.ABC, "refresh_token", response.refresh_token);
12352
- set(STORAGE_NS.ABC, "expires_at", String(authState.expiresAt));
12353
- };
12354
- const handleSocialSuccess = (response, provider) => {
12355
- onEmailSet?.(response.email);
12356
- clearExpiredEncryptedData();
12357
- saveAuthState(response, provider);
12493
+ if (typeof window !== "undefined") {
12494
+ window.dispatchEvent(new Event("talkenkit_storage_update"));
12495
+ }
12496
+ assertLogin({ api, revision: result.sessionRevision });
12497
+ onEmailSet?.(result.email);
12498
+ assertLogin({ api, revision: result.sessionRevision });
12499
+ const accessKeyLoginData = {
12500
+ email: result.email,
12501
+ credential: ""
12502
+ // PIN handled server-side
12503
+ };
12358
12504
  const hasEncryptedTokens = !!(get(STORAGE_NS.ABC, "enc_tokens") && get(STORAGE_NS.ABC, "enc_salt"));
12359
- onPinRequired(response, response.email, hasEncryptedTokens);
12505
+ onPinRequired(accessKeyLoginData, result.email, hasEncryptedTokens);
12360
12506
  };
12361
12507
  const handleGoogleLogin = async () => {
12362
12508
  setIsLoading(true);
12363
12509
  setError("");
12364
12510
  try {
12365
- const response = await googleLogin2({
12366
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT || "development"
12367
- });
12368
- if (!response)
12511
+ const session = captureLogin();
12512
+ initializeFirebase();
12513
+ const auth = await googleLogin();
12514
+ if (!auth)
12369
12515
  return;
12370
- handleSocialSuccess(response, "google");
12516
+ await bootstrapSnsAccessKey(
12517
+ "google",
12518
+ auth.idToken,
12519
+ auth.email,
12520
+ "google",
12521
+ session
12522
+ );
12371
12523
  } catch (e) {
12372
- setError(e.message || "Google login failed. Please try again.");
12524
+ setError(e?.message || "Google login failed. Please try again.");
12373
12525
  } finally {
12374
12526
  setIsLoading(false);
12375
12527
  }
@@ -12378,14 +12530,20 @@ function useAbcWaasSocial(props) {
12378
12530
  setIsLoading(true);
12379
12531
  setError("");
12380
12532
  try {
12381
- const response = await appleLogin2({
12382
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT || "development"
12383
- });
12384
- if (!response)
12533
+ const session = captureLogin();
12534
+ initializeFirebase();
12535
+ const auth = await appleLogin();
12536
+ if (!auth)
12385
12537
  return;
12386
- handleSocialSuccess(response, "apple");
12538
+ await bootstrapSnsAccessKey(
12539
+ "apple",
12540
+ auth.idToken,
12541
+ auth.email,
12542
+ "apple",
12543
+ session
12544
+ );
12387
12545
  } catch (e) {
12388
- setError(e.message || "Apple login failed. Please try again.");
12546
+ setError(e?.message || "Apple login failed. Please try again.");
12389
12547
  } finally {
12390
12548
  setIsLoading(false);
12391
12549
  }
@@ -12394,14 +12552,19 @@ function useAbcWaasSocial(props) {
12394
12552
  setIsLoading(true);
12395
12553
  setError("");
12396
12554
  try {
12397
- const response = await kakaoLogin2({
12398
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT || "development"
12399
- });
12400
- if (!response)
12555
+ const session = captureLogin();
12556
+ const auth = await kakaoLogin();
12557
+ if (!auth)
12401
12558
  return;
12402
- handleSocialSuccess(response, "kakao");
12559
+ await bootstrapSnsAccessKey(
12560
+ "kakao",
12561
+ auth.idToken,
12562
+ auth.email,
12563
+ "kakao",
12564
+ session
12565
+ );
12403
12566
  } catch (e) {
12404
- setError(e.message || "Kakao login failed. Please try again.");
12567
+ setError(e?.message || "Kakao login failed. Please try again.");
12405
12568
  } finally {
12406
12569
  setIsLoading(false);
12407
12570
  }
@@ -12940,7 +13103,7 @@ PopularWalletList.displayName = "PopularWalletList";
12940
13103
 
12941
13104
  // src/components/ConnectOptions/ExternalWallets/hooks/useWalletConnection.ts
12942
13105
  import { useCallback as useCallback23, useEffect as useEffect31, useRef as useRef17, useState as useState32 } from "react";
12943
- import { useAccount as useAccount18, useConfig as useConfig3 } from "wagmi";
13106
+ import { useAccount as useAccount18, useConfig as useConfig4 } from "wagmi";
12944
13107
  import { reconnect } from "wagmi/actions";
12945
13108
 
12946
13109
  // src/wallets/latestWalletId.ts
@@ -12965,7 +13128,7 @@ function useWalletConnection({
12965
13128
  const [qrCodeUri, setQrCodeUri] = useState32();
12966
13129
  const [connectionError, setConnectionError] = useState32(false);
12967
13130
  const { isConnected } = useAccount18();
12968
- const config = useConfig3();
13131
+ const config = useConfig4();
12969
13132
  const onSuccessRef = useRef17(onSuccess);
12970
13133
  onSuccessRef.current = onSuccess;
12971
13134
  const successCalledRef = useRef17(false);
@@ -13364,6 +13527,12 @@ function usePinCreation(props) {
13364
13527
  onShowConfirmModal?.();
13365
13528
  };
13366
13529
  const handlePinConfirm = async (confirmedPin) => {
13530
+ const api = getTalkenApiClient();
13531
+ const revision = api?.getSessionRevision();
13532
+ const assertCurrent = () => {
13533
+ if (!api || getTalkenApiClient() !== api || api.getSessionRevision() !== revision)
13534
+ throw new Error("AUTH_SESSION_CHANGED");
13535
+ };
13367
13536
  logger19.info("Confirming PIN");
13368
13537
  if (confirmedPin !== pin) {
13369
13538
  logger19.error("PINs do not match");
@@ -13375,8 +13544,10 @@ function usePinCreation(props) {
13375
13544
  try {
13376
13545
  logger19.debug("Hashing PIN...");
13377
13546
  const hashedPin = await hashPin(pin);
13547
+ assertCurrent();
13378
13548
  logger19.info("PIN hashed successfully");
13379
13549
  await onPinConfirmed(hashedPin);
13550
+ assertCurrent();
13380
13551
  setPin("");
13381
13552
  setConfirmPin("");
13382
13553
  } catch (error3) {
@@ -13405,14 +13576,52 @@ function usePinCreation(props) {
13405
13576
  }
13406
13577
 
13407
13578
  // src/components/ConnectOptions/PinAuth/hooks/usePinVerification.ts
13408
- import { useState as useState35 } from "react";
13579
+ import { useEffect as useEffect33, useRef as useRef18, useState as useState35 } from "react";
13409
13580
  var logger20 = createLogger("PinVerification");
13410
13581
  function usePinVerification(props) {
13411
13582
  const { email, onVerified, onSessionExpired } = props;
13412
13583
  const [isVerifying, setIsVerifying] = useState35(false);
13413
13584
  const [error2, setError] = useState35("");
13414
13585
  const [progress, setProgress] = useState35([]);
13586
+ const attempt = useRef18(0);
13587
+ const currentEmail = useRef18(email);
13588
+ currentEmail.current = email;
13589
+ useEffect33(
13590
+ () => () => {
13591
+ attempt.current++;
13592
+ },
13593
+ []
13594
+ );
13415
13595
  const handlePinVerify = async (pin) => {
13596
+ const operation = ++attempt.current;
13597
+ const api = getTalkenApiClient();
13598
+ let revision = api?.getSessionRevision();
13599
+ let storedAuth = get(STORAGE_NS.ABC, "auth_state");
13600
+ let encryptedData = get(STORAGE_NS.ABC, "enc_tokens");
13601
+ let saltHex = get(STORAGE_NS.ABC, "enc_salt");
13602
+ let credentials = JSON.stringify([
13603
+ api?.getAccessToken(),
13604
+ api?.getRefreshToken()
13605
+ ]);
13606
+ const ownerIdentity = (raw) => {
13607
+ try {
13608
+ const { accessToken, refreshToken, expiresAt, expires_in, ...owner2 } = JSON.parse(raw || "null") || {};
13609
+ return JSON.stringify(owner2);
13610
+ } catch {
13611
+ return raw;
13612
+ }
13613
+ };
13614
+ let owner = ownerIdentity(storedAuth);
13615
+ const ownsOperation = () => operation === attempt.current && currentEmail.current === email && getTalkenApiClient() === api && api?.getSessionRevision() === revision && !!api && ownsTalkenApiStorage(api) && ownerIdentity(get(STORAGE_NS.ABC, "auth_state")) === owner;
13616
+ const isCurrent = () => ownsOperation() && get(STORAGE_NS.ABC, "auth_state") === storedAuth && get(STORAGE_NS.ABC, "enc_tokens") === encryptedData && get(STORAGE_NS.ABC, "enc_salt") === saltHex && JSON.stringify([api?.getAccessToken(), api?.getRefreshToken()]) === credentials;
13617
+ const sessionChanged = () => Object.assign(
13618
+ new Error("The wallet session changed. Please try again."),
13619
+ { code: "AUTH_SESSION_CHANGED" }
13620
+ );
13621
+ const assertCurrent = () => {
13622
+ if (!isCurrent())
13623
+ throw sessionChanged();
13624
+ };
13416
13625
  logger20.info("Verifying PIN");
13417
13626
  setProgress([
13418
13627
  { label: "Verifying PIN...", status: "active" },
@@ -13420,13 +13629,13 @@ function usePinVerification(props) {
13420
13629
  ]);
13421
13630
  setIsVerifying(true);
13422
13631
  setError("");
13423
- await new Promise((resolve) => setTimeout(resolve, 100));
13424
13632
  try {
13633
+ await new Promise((resolve) => setTimeout(resolve, 100));
13634
+ assertCurrent();
13425
13635
  logger20.debug("Hashing PIN...");
13426
13636
  const hashedPin = await hashPin(pin);
13637
+ assertCurrent();
13427
13638
  logger20.debug("Decrypting stored data...");
13428
- const saltHex = get(STORAGE_NS.ABC, "enc_salt");
13429
- const encryptedData = get(STORAGE_NS.ABC, "enc_tokens");
13430
13639
  let sensitiveData;
13431
13640
  let isExpired = false;
13432
13641
  if (!saltHex || !encryptedData) {
@@ -13453,19 +13662,30 @@ function usePinVerification(props) {
13453
13662
  hashedPin,
13454
13663
  saltHex
13455
13664
  );
13665
+ assertCurrent();
13456
13666
  sensitiveData = JSON.parse(decrypted);
13457
13667
  logger20.info("PIN verified successfully");
13458
13668
  } catch (_decryptError) {
13669
+ assertCurrent();
13459
13670
  throw new Error("Incorrect PIN. Please try again.");
13460
13671
  }
13461
13672
  isExpired = sensitiveData.expiresAt ? Date.now() >= sensitiveData.expiresAt : true;
13462
13673
  }
13674
+ assertCurrent();
13675
+ const persisted = JSON.parse(storedAuth || "null");
13676
+ if (api?.isAccessKeyMode() || [api?.getAccessToken(), persisted?.accessToken].some(
13677
+ (token) => token && token !== sensitiveData.accessToken
13678
+ ) || [api?.getRefreshToken(), persisted?.refreshToken].some(
13679
+ (token) => token && token !== sensitiveData.refreshToken
13680
+ ))
13681
+ throw sessionChanged();
13463
13682
  setProgress([
13464
13683
  { label: "Verifying PIN...", status: "completed" },
13465
13684
  { label: "Restoring wallet data...", status: "active" }
13466
13685
  ]);
13467
13686
  logger20.info("Restoring wallet data...");
13468
13687
  await new Promise((resolve) => setTimeout(resolve, 100));
13688
+ assertCurrent();
13469
13689
  const authStateStr = get(STORAGE_NS.ABC, "auth_state");
13470
13690
  if (!authStateStr) {
13471
13691
  throw new Error("Auth state not found. Please login again.");
@@ -13481,16 +13701,31 @@ function usePinVerification(props) {
13481
13701
  if (!refreshToken) {
13482
13702
  throw new Error("No refresh token available");
13483
13703
  }
13484
- const api = getTalkenApiClient();
13485
13704
  if (!api) {
13486
13705
  throw new Error("TalkenApiClient not initialized");
13487
13706
  }
13707
+ assertCurrent();
13708
+ if (api.hasCredentials() && (api.isAccessKeyMode() || api.getAccessToken() !== sensitiveData.accessToken || api.getRefreshToken() !== refreshToken))
13709
+ throw sessionChanged();
13488
13710
  api.setTokens(
13489
13711
  sensitiveData.accessToken || "",
13490
13712
  refreshToken,
13491
13713
  sensitiveData.expiresAt || 0
13492
13714
  );
13715
+ revision = api.getSessionRevision();
13716
+ credentials = JSON.stringify([
13717
+ api.getAccessToken(),
13718
+ api.getRefreshToken()
13719
+ ]);
13493
13720
  const res = await api.auth.refresh();
13721
+ if (!ownsOperation() || get(STORAGE_NS.ABC, "enc_tokens") !== encryptedData || get(STORAGE_NS.ABC, "enc_salt") !== saltHex || api.getAccessToken() !== res.accessToken || api.getRefreshToken() !== (res.refreshToken || refreshToken))
13722
+ throw sessionChanged();
13723
+ storedAuth = get(STORAGE_NS.ABC, "auth_state");
13724
+ credentials = JSON.stringify([
13725
+ api.getAccessToken(),
13726
+ api.getRefreshToken()
13727
+ ]);
13728
+ assertCurrent();
13494
13729
  if (!res.accessToken) {
13495
13730
  throw new Error("Your session has expired. Please login again.");
13496
13731
  }
@@ -13519,10 +13754,16 @@ function usePinVerification(props) {
13519
13754
  hashedPin,
13520
13755
  saltBytes
13521
13756
  );
13757
+ assertCurrent();
13522
13758
  set(STORAGE_NS.ABC, "enc_tokens", encryptedTokens);
13759
+ encryptedData = encryptedTokens;
13523
13760
  setJSON(STORAGE_NS.ABC, "auth_state", authState);
13761
+ storedAuth = get(STORAGE_NS.ABC, "auth_state");
13762
+ owner = ownerIdentity(storedAuth);
13524
13763
  logger20.info("Encrypted tokens updated");
13525
13764
  } catch (refreshError) {
13765
+ if (!isCurrent() || refreshError?.code === "AUTH_SESSION_CHANGED")
13766
+ return;
13526
13767
  logger20.error("Token refresh failed:", refreshError);
13527
13768
  const freshAuthState = getJSON(STORAGE_NS.ABC, "auth_state");
13528
13769
  const hasFreshTokens = freshAuthState && (() => {
@@ -13535,6 +13776,14 @@ function usePinVerification(props) {
13535
13776
  })();
13536
13777
  if (!hasFreshTokens) {
13537
13778
  logger20.info("Clearing all auth data");
13779
+ assertCurrent();
13780
+ api?.clearSession();
13781
+ revision = api?.getSessionRevision();
13782
+ credentials = JSON.stringify([
13783
+ api?.getAccessToken(),
13784
+ api?.getRefreshToken()
13785
+ ]);
13786
+ getCredentialManager().clear();
13538
13787
  remove(STORAGE_NS.ABC, "auth_state");
13539
13788
  remove(STORAGE_NS.ABC, "enc_tokens");
13540
13789
  remove(STORAGE_NS.ABC, "enc_salt");
@@ -13542,12 +13791,18 @@ function usePinVerification(props) {
13542
13791
  remove(STORAGE_NS.ABC, "wallet");
13543
13792
  remove(STORAGE_NS.ABC, "access_token");
13544
13793
  remove(STORAGE_NS.ABC, "refresh_token");
13794
+ storedAuth = get(STORAGE_NS.ABC, "auth_state");
13795
+ owner = ownerIdentity(storedAuth);
13796
+ encryptedData = get(STORAGE_NS.ABC, "enc_tokens");
13797
+ saltHex = get(STORAGE_NS.ABC, "enc_salt");
13798
+ assertCurrent();
13545
13799
  onSessionExpired?.();
13546
13800
  throw new Error("Your session has expired. Please login again.");
13547
13801
  }
13548
13802
  logger20.info("Using fresh tokens from login, skipping refresh");
13549
13803
  }
13550
13804
  }
13805
+ assertCurrent();
13551
13806
  const user = getJSON(STORAGE_NS.ABC, "user");
13552
13807
  if (sensitiveData.solanaWallet)
13553
13808
  authState.solanaWallet = sensitiveData.solanaWallet;
@@ -13562,7 +13817,10 @@ function usePinVerification(props) {
13562
13817
  authState.wallet = wallet;
13563
13818
  if (user)
13564
13819
  authState.user = user;
13820
+ assertCurrent();
13565
13821
  setJSON(STORAGE_NS.ABC, "auth_state", authState);
13822
+ storedAuth = get(STORAGE_NS.ABC, "auth_state");
13823
+ owner = ownerIdentity(storedAuth);
13566
13824
  const credMgr = getCredentialManager();
13567
13825
  credMgr.setPinHash(hashedPin);
13568
13826
  credMgr.setEmail(email);
@@ -13572,17 +13830,23 @@ function usePinVerification(props) {
13572
13830
  ]);
13573
13831
  logger20.info("Wallet data restored successfully");
13574
13832
  window.dispatchEvent(new Event("talkenkit_storage_update"));
13833
+ assertCurrent();
13575
13834
  onVerified();
13576
13835
  } catch (err) {
13836
+ if (!isCurrent() || err?.code === "AUTH_SESSION_CHANGED")
13837
+ return;
13577
13838
  logger20.error("PIN verification failed:", err);
13578
13839
  setError(err.message || "Failed to verify PIN");
13579
13840
  throw err;
13580
13841
  } finally {
13581
- setIsVerifying(false);
13842
+ if (operation === attempt.current)
13843
+ setIsVerifying(false);
13582
13844
  }
13583
13845
  };
13584
13846
  const resetVerification = () => {
13585
13847
  logger20.debug("Resetting verification state");
13848
+ attempt.current++;
13849
+ setIsVerifying(false);
13586
13850
  setError("");
13587
13851
  setProgress([]);
13588
13852
  };
@@ -13619,20 +13883,45 @@ function useWalletGeneration(props) {
13619
13883
  setStatusMessage("Preparing wallet generation...");
13620
13884
  try {
13621
13885
  const api = getTalkenApiClient();
13886
+ if (!api)
13887
+ throw new Error("TalkenApiClient not initialized");
13888
+ const boundSession = api.isAccessKeyMode() ? api.getAuthenticatedWalletSession() : null;
13889
+ if (api.isAccessKeyMode() && (!boundSession || boundSession.user.email && boundSession.user.email !== email.trim().toLowerCase())) {
13890
+ throw new TalkenApiError(
13891
+ "AUTH_SESSION_UNBOUND",
13892
+ "Please sign in again before creating wallets.",
13893
+ 401
13894
+ );
13895
+ }
13622
13896
  if (!api.isAccessKeyMode()) {
13623
13897
  if (!loginData || !loginData.access_token) {
13624
13898
  throw new Error("Login data not found");
13625
13899
  }
13626
- const expiresAt = Date.now() + (loginData.expires_in > 0 ? loginData.expires_in : 3600) * 1e3;
13627
- set(STORAGE_NS.ABC, "access_token", loginData.access_token);
13628
- set(STORAGE_NS.ABC, "refresh_token", loginData.refresh_token || "");
13629
- set(STORAGE_NS.ABC, "expires_at", String(expiresAt));
13630
- api.setTokens(
13631
- loginData.access_token,
13632
- loginData.refresh_token || "",
13633
- expiresAt
13634
- );
13900
+ if (api.getAccessToken() !== loginData.access_token || api.getRefreshToken() !== (loginData.refresh_token || "") || loginData.sessionRevision !== void 0 && loginData.sessionRevision !== api.getSessionRevision()) {
13901
+ throw new TalkenApiError(
13902
+ "AUTH_SESSION_CHANGED",
13903
+ "The wallet login changed before wallet creation.",
13904
+ 401
13905
+ );
13906
+ }
13907
+ const expiresAt = api.getTokenExpiresAt();
13908
+ if (!expiresAt)
13909
+ throw new TalkenApiError(
13910
+ "AUTH_SESSION_CHANGED",
13911
+ "Token expiry is missing.",
13912
+ 401
13913
+ );
13635
13914
  }
13915
+ const revision = api.getSessionRevision();
13916
+ const assertCurrent = () => {
13917
+ if (getTalkenApiClient() !== api || api.getSessionRevision() !== revision) {
13918
+ throw new TalkenApiError(
13919
+ "AUTH_SESSION_CHANGED",
13920
+ "The wallet session changed during wallet creation.",
13921
+ 401
13922
+ );
13923
+ }
13924
+ };
13636
13925
  setProgress([
13637
13926
  { label: "Preparing wallet generation...", status: "completed" },
13638
13927
  { label: "Creating EVM wallet...", status: "active" },
@@ -13642,7 +13931,9 @@ function useWalletGeneration(props) {
13642
13931
  ]);
13643
13932
  setStatusMessage("Creating wallets...");
13644
13933
  const genResponse = await api.wallet.generate(hashedPin, email);
13934
+ assertCurrent();
13645
13935
  const infoResponse = await api.wallet.getInfo();
13936
+ assertCurrent();
13646
13937
  setProgress([
13647
13938
  { label: "Preparing wallet generation...", status: "completed" },
13648
13939
  { label: "Creating EVM wallet...", status: "completed" },
@@ -13663,6 +13954,7 @@ function useWalletGeneration(props) {
13663
13954
  if ((!btcAddress || !trxAddress || !xrpAddress) && pubkey) {
13664
13955
  try {
13665
13956
  const addrResponse = await api.wallet.getAddressForChain("all");
13957
+ assertCurrent();
13666
13958
  if (!btcAddress)
13667
13959
  btcAddress = addrResponse?.btc || addrResponse?.btcAddress || "";
13668
13960
  if (!trxAddress)
@@ -13670,6 +13962,7 @@ function useWalletGeneration(props) {
13670
13962
  if (!xrpAddress)
13671
13963
  xrpAddress = addrResponse?.xrp || addrResponse?.xrpAddress || "";
13672
13964
  } catch (err) {
13965
+ assertCurrent();
13673
13966
  logger21.warn("Failed to derive BTC/TRX/XRP addresses:", err);
13674
13967
  }
13675
13968
  }
@@ -13716,22 +14009,31 @@ function useWalletGeneration(props) {
13716
14009
  encryptedShare: "",
13717
14010
  network: getXrplNetwork()
13718
14011
  } : null;
13719
- getCredentialManager().setPinHash(hashedPin);
13720
- const pvencstr = evmAccount.pvencstr || "";
13721
- const encryptDevicePassword = evmAccount.encryptDevicePassword || "";
13722
- if (uid && genResponse.wid && sid && pvencstr && encryptDevicePassword) {
13723
- getCredentialManager().setEvmSigningCredentials({
13724
- uid,
13725
- wid: String(genResponse.wid),
13726
- sid,
13727
- pvencstr: String(pvencstr),
13728
- encryptDevicePassword: String(encryptDevicePassword)
13729
- });
13730
- }
14012
+ assertCurrent();
14013
+ const bearerSession = api.isAccessKeyMode() ? null : {
14014
+ accessToken: api.getAccessToken(),
14015
+ refreshToken: api.getRefreshToken(),
14016
+ expiresAt: api.getTokenExpiresAt()
14017
+ };
14018
+ if (bearerSession && (!bearerSession.accessToken || !bearerSession.refreshToken || !bearerSession.expiresAt))
14019
+ throw new TalkenApiError(
14020
+ "AUTH_SESSION_CHANGED",
14021
+ "Wallet credentials changed during creation.",
14022
+ 401
14023
+ );
14024
+ const assertCredentials = () => {
14025
+ assertCurrent();
14026
+ if (bearerSession && (api.getAccessToken() !== bearerSession.accessToken || api.getRefreshToken() !== bearerSession.refreshToken || api.getTokenExpiresAt() !== bearerSession.expiresAt))
14027
+ throw new TalkenApiError(
14028
+ "AUTH_SESSION_CHANGED",
14029
+ "Wallet credentials rotated during encryption.",
14030
+ 401
14031
+ );
14032
+ };
13731
14033
  const isAccessKey = api.isAccessKeyMode();
13732
14034
  const existingAuthState = getJSON(STORAGE_NS.ABC, "auth_state") || {};
13733
14035
  const walletData = {
13734
- address: sid,
14036
+ address: evmAddress,
13735
14037
  chainId: getEvmNetwork(),
13736
14038
  uid,
13737
14039
  sid,
@@ -13759,32 +14061,25 @@ function useWalletGeneration(props) {
13759
14061
  expiresAt: null,
13760
14062
  accessKeyMode: true
13761
14063
  } : {
13762
- accessToken: loginData.access_token,
13763
- refreshToken: loginData.refresh_token,
13764
- expiresAt: Date.now() + (loginData.expires_in > 0 ? loginData.expires_in : 3600) * 1e3
14064
+ accessToken: bearerSession.accessToken,
14065
+ refreshToken: bearerSession.refreshToken,
14066
+ expiresAt: bearerSession.expiresAt
13765
14067
  }
13766
14068
  };
13767
- setJSON(STORAGE_NS.ABC, "auth_state", authState);
13768
- setJSON(STORAGE_NS.ABC, "user", authState.user);
13769
- setJSON(STORAGE_NS.ABC, "wallet", walletData);
13770
- if (!isAccessKey) {
13771
- set(STORAGE_NS.ABC, "access_token", loginData.access_token);
13772
- set(STORAGE_NS.ABC, "refresh_token", loginData.refresh_token || "");
13773
- set(STORAGE_NS.ABC, "expires_at", String(authState.expiresAt));
13774
- }
13775
- if (typeof window !== "undefined") {
13776
- window.dispatchEvent(
13777
- new CustomEvent("talkenkit:token_updated", {
13778
- detail: { expiresAt: authState.expiresAt }
13779
- })
14069
+ assertCurrent();
14070
+ if (isAccessKey && !api.getAuthenticatedWalletSession(authState)) {
14071
+ throw new TalkenApiError(
14072
+ "AUTH_SESSION_CHANGED",
14073
+ "The generated account does not match this wallet login.",
14074
+ 401
13780
14075
  );
13781
- window.dispatchEvent(new Event("talkenkit_storage_update"));
13782
14076
  }
14077
+ let encryptedSession = null;
13783
14078
  if (!isAccessKey) {
13784
14079
  const salt = crypto.getRandomValues(new Uint8Array(16));
13785
14080
  const sensitiveData = JSON.stringify({
13786
- accessToken: loginData.access_token,
13787
- refreshToken: loginData.refresh_token || "",
14081
+ accessToken: bearerSession.accessToken,
14082
+ refreshToken: bearerSession.refreshToken,
13788
14083
  expiresAt: authState.expiresAt,
13789
14084
  solanaWallet: authState.solanaWallet,
13790
14085
  bitcoinWallet: authState.bitcoinWallet,
@@ -13792,18 +14087,55 @@ function useWalletGeneration(props) {
13792
14087
  xrplWallet: authState.xrplWallet
13793
14088
  });
13794
14089
  const encrypted = await encryptWithPin(sensitiveData, hashedPin, salt);
13795
- set(
13796
- STORAGE_NS.ABC,
13797
- "enc_salt",
13798
- Array.from(salt).map((b) => b.toString(16).padStart(2, "0")).join("")
14090
+ assertCredentials();
14091
+ encryptedSession = {
14092
+ salt: Array.from(salt).map((b) => b.toString(16).padStart(2, "0")).join(""),
14093
+ tokens: encrypted
14094
+ };
14095
+ }
14096
+ assertCredentials();
14097
+ getCredentialManager().setPinHash(hashedPin);
14098
+ const pvencstr = evmAccount.pvencstr || "";
14099
+ const encryptDevicePassword = evmAccount.encryptDevicePassword || "";
14100
+ if (uid && genResponse.wid && sid && pvencstr && encryptDevicePassword) {
14101
+ getCredentialManager().setEvmSigningCredentials({
14102
+ uid,
14103
+ wid: String(genResponse.wid),
14104
+ sid,
14105
+ pvencstr: String(pvencstr),
14106
+ encryptDevicePassword: String(encryptDevicePassword)
14107
+ });
14108
+ }
14109
+ setJSON(STORAGE_NS.ABC, "auth_state", authState);
14110
+ setJSON(STORAGE_NS.ABC, "user", authState.user);
14111
+ setJSON(STORAGE_NS.ABC, "wallet", walletData);
14112
+ if (!isAccessKey) {
14113
+ set(STORAGE_NS.ABC, "access_token", bearerSession.accessToken);
14114
+ set(STORAGE_NS.ABC, "refresh_token", bearerSession.refreshToken);
14115
+ set(STORAGE_NS.ABC, "expires_at", String(authState.expiresAt));
14116
+ }
14117
+ if (encryptedSession) {
14118
+ set(STORAGE_NS.ABC, "enc_salt", encryptedSession.salt);
14119
+ set(STORAGE_NS.ABC, "enc_tokens", encryptedSession.tokens);
14120
+ }
14121
+ if (typeof window !== "undefined") {
14122
+ assertCredentials();
14123
+ window.dispatchEvent(
14124
+ new CustomEvent("talkenkit:token_updated", {
14125
+ detail: { expiresAt: authState.expiresAt }
14126
+ })
13799
14127
  );
13800
- set(STORAGE_NS.ABC, "enc_tokens", encrypted);
14128
+ assertCredentials();
14129
+ window.dispatchEvent(new Event("talkenkit_storage_update"));
13801
14130
  }
14131
+ assertCredentials();
13802
14132
  if (loginData.credential) {
13803
14133
  delete loginData.credential;
13804
14134
  }
13805
14135
  if (typeof window !== "undefined") {
13806
14136
  setTimeout(() => {
14137
+ if (getTalkenApiClient() !== api || api.getSessionRevision() !== revision || bearerSession && (api.getAccessToken() !== bearerSession.accessToken || api.getRefreshToken() !== bearerSession.refreshToken))
14138
+ return;
13807
14139
  window.dispatchEvent(new Event("talkenkit_storage_update"));
13808
14140
  }, 500);
13809
14141
  }
@@ -13813,7 +14145,9 @@ function useWalletGeneration(props) {
13813
14145
  if (!abcConnector) {
13814
14146
  throw new Error("ABC connector not found");
13815
14147
  }
14148
+ assertCredentials();
13816
14149
  await connect({ connector: abcConnector });
14150
+ assertCredentials();
13817
14151
  onSuccess();
13818
14152
  } finally {
13819
14153
  setIsGenerating(false);
@@ -13862,7 +14196,11 @@ var PinAuthFlow = forwardRef(
13862
14196
  });
13863
14197
  },
13864
14198
  onShowConfirmModal: () => {
14199
+ const api = getTalkenApiClient();
14200
+ const revision = api?.getSessionRevision();
13865
14201
  setTimeout(() => {
14202
+ if (!api || getTalkenApiClient() !== api || api.getSessionRevision() !== revision)
14203
+ return;
13866
14204
  setIsPinCreateModalOpen(false);
13867
14205
  setIsPinConfirmModalOpen(true);
13868
14206
  }, 100);
@@ -13871,19 +14209,26 @@ var PinAuthFlow = forwardRef(
13871
14209
  const pinVerification = usePinVerification({
13872
14210
  email,
13873
14211
  onVerified: async () => {
14212
+ const api = getTalkenApiClient();
14213
+ const revision = api?.getSessionRevision();
14214
+ const assertCurrent = () => {
14215
+ if (!api || getTalkenApiClient() !== api || api.getSessionRevision() !== revision)
14216
+ throw new Error("AUTH_SESSION_CHANGED");
14217
+ };
14218
+ assertCurrent();
13874
14219
  setIsPinVerifyModalOpen(false);
13875
14220
  const authStateStr = localStorage.getItem(`${storagePrefix}auth_state`);
13876
14221
  const authState = authStateStr ? JSON.parse(authStateStr) : null;
13877
14222
  const needsWalletGeneration = authState && (!authState.wallet || !authState.solanaWallet || !authState.bitcoinWallet || !authState.tronWallet || !authState.xrplWallet);
13878
14223
  if (needsWalletGeneration) {
13879
- const { getCredentialManager: getCredentialManager2 } = await import("./AbcCredentialManager-WZBF3GHF.js");
13880
- const pinHash = getCredentialManager2().getPinHash();
14224
+ const pinHash = getCredentialManager().getPinHash();
13881
14225
  if (pinHash) {
13882
14226
  await walletGeneration.generateWallets({
13883
14227
  hashedPin: pinHash,
13884
14228
  email,
13885
14229
  loginData
13886
14230
  });
14231
+ assertCurrent();
13887
14232
  return;
13888
14233
  }
13889
14234
  }
@@ -13891,10 +14236,12 @@ var PinAuthFlow = forwardRef(
13891
14236
  (c) => c.id === "abc" || c.name === "ABC Wallet"
13892
14237
  );
13893
14238
  if (abcConnector) {
14239
+ assertCurrent();
13894
14240
  connect({ connector: abcConnector });
13895
14241
  } else {
13896
14242
  logger22.error("ABC Wallet connector not found");
13897
14243
  }
14244
+ assertCurrent();
13898
14245
  onComplete();
13899
14246
  },
13900
14247
  onSessionExpired: () => {
@@ -14057,7 +14404,7 @@ function ConnectModalIntro({
14057
14404
  }
14058
14405
 
14059
14406
  // src/components/ConnectOptions/ConnectDetails.tsx
14060
- import React94, { useContext as useContext23, useEffect as useEffect34 } from "react";
14407
+ import React94, { useContext as useContext23, useEffect as useEffect35 } from "react";
14061
14408
 
14062
14409
  // src/utils/colors.ts
14063
14410
  var convertHexToRGBA = (hexCode, opacity = 1) => {
@@ -14468,7 +14815,7 @@ function ConnectDetail({
14468
14815
  } : null;
14469
14816
  const { width: windowWidth } = useWindowSize();
14470
14817
  const smallWindow = windowWidth && windowWidth < 768;
14471
- useEffect34(() => {
14818
+ useEffect35(() => {
14472
14819
  preloadBrowserIcon();
14473
14820
  preloadPlatformIcon();
14474
14821
  }, []);
@@ -14848,7 +15195,7 @@ function DownloadOptionsDetail({
14848
15195
  mobileDownloadUrl
14849
15196
  } = wallet;
14850
15197
  const { i18n: i18n2 } = useContext23(I18nContext);
14851
- useEffect34(() => {
15198
+ useEffect35(() => {
14852
15199
  preloadCreateIcon();
14853
15200
  preloadScanIcon();
14854
15201
  preloadRefreshIcon();
@@ -14944,7 +15291,7 @@ function DownloadDetail({
14944
15291
  }) {
14945
15292
  const { downloadUrls, qrCode } = wallet;
14946
15293
  const { i18n: i18n2 } = useContext23(I18nContext);
14947
- useEffect34(() => {
15294
+ useEffect35(() => {
14948
15295
  preloadCreateIcon();
14949
15296
  preloadScanIcon();
14950
15297
  }, []);
@@ -15420,8 +15767,8 @@ function ConnectOptionsModal({
15420
15767
  const { i18n: i18n2 } = useContext24(I18nContext);
15421
15768
  const [abcWaasLoginData, setAbcWaasLoginData] = useState39(null);
15422
15769
  const [email, setEmail] = useState39("");
15423
- const initialized = useRef18(false);
15424
- const pinAuthFlowRef = useRef18(null);
15770
+ const initialized = useRef19(false);
15771
+ const pinAuthFlowRef = useRef19(null);
15425
15772
  const { connector } = useContext24(WalletButtonContext);
15426
15773
  const wallets = useWalletConnectors(false).filter((wallet) => wallet.ready || !!wallet.extensionDownloadUrl).sort((a, b) => a.groupIndex - b.groupIndex);
15427
15774
  const unfilteredWallets = useWalletConnectors();
@@ -15498,7 +15845,7 @@ function ConnectOptionsModal({
15498
15845
  connectWallet: walletConnection.connectWallet,
15499
15846
  selectWallet: walletConnection.selectWallet
15500
15847
  });
15501
- useEffect35(() => {
15848
+ useEffect36(() => {
15502
15849
  if (connector && !initialized.current) {
15503
15850
  changeWalletStep("CONNECT" /* Connect */);
15504
15851
  walletConnection.selectWallet(connector);
@@ -15782,8 +16129,8 @@ function ConnectOptionsModal({
15782
16129
  import React96, {
15783
16130
  useCallback as useCallback24,
15784
16131
  useContext as useContext25,
15785
- useEffect as useEffect36,
15786
- useRef as useRef19,
16132
+ useEffect as useEffect37,
16133
+ useRef as useRef20,
15787
16134
  useState as useState40
15788
16135
  } from "react";
15789
16136
 
@@ -15836,7 +16183,7 @@ function WalletButton({
15836
16183
  showWalletConnectModal
15837
16184
  } = wallet;
15838
16185
  const coolModeRef = useCoolMode2(iconUrl);
15839
- const initialized = useRef19(false);
16186
+ const initialized = useRef20(false);
15840
16187
  const { i18n: i18n2 } = useContext25(I18nContext);
15841
16188
  const onConnect = useCallback24(async () => {
15842
16189
  const onMobileUri = async () => {
@@ -15865,7 +16212,7 @@ function WalletButton({
15865
16212
  }
15866
16213
  connect?.();
15867
16214
  }, [connect, getMobileUri, showWalletConnectModal, onClose, name, id]);
15868
- useEffect36(() => {
16215
+ useEffect37(() => {
15869
16216
  if (connecting && !initialized.current) {
15870
16217
  onConnect();
15871
16218
  initialized.current = true;
@@ -16715,7 +17062,7 @@ function ModalProvider({ children }) {
16715
17062
  const [isWalletConnectModalOpen, setIsWalletConnectModalOpen] = useState44(false);
16716
17063
  const connectionStatus = useConnectionStatus();
16717
17064
  const { chainId } = useAccount20();
16718
- const { chains } = useConfig4();
17065
+ const { chains } = useConfig5();
16719
17066
  const isCurrentChainSupported = chains.some((chain) => chain.id === chainId);
16720
17067
  const multiChainContext = useContext30(MultiChainContext);
16721
17068
  const _isAnyChainConnected = connectionStatus === "connected" || multiChainContext?.solanaConnected;
@@ -16734,7 +17081,7 @@ function ModalProvider({ children }) {
16734
17081
  onConnect: () => closeModals({ keepConnectModalOpen: isUnauthenticated }),
16735
17082
  onDisconnect: () => closeModals()
16736
17083
  });
16737
- useEffect37(() => {
17084
+ useEffect38(() => {
16738
17085
  if (isUnauthenticated)
16739
17086
  closeModals();
16740
17087
  }, [isUnauthenticated, closeModals]);
@@ -16831,7 +17178,7 @@ function ConnectButtonRenderer({
16831
17178
  const isMounted = useIsMounted();
16832
17179
  const { address } = useAccount21();
16833
17180
  const { chainId } = useAccount21();
16834
- const { chains: wagmiChains } = useConfig5();
17181
+ const { chains: wagmiChains } = useConfig6();
16835
17182
  const isCurrentChainSupported = wagmiChains.some(
16836
17183
  (chain) => chain.id === chainId
16837
17184
  );
@@ -16919,12 +17266,12 @@ function ConnectButton({
16919
17266
  "bitcoin",
16920
17267
  "solana"
16921
17268
  ];
16922
- useEffect38(() => {
17269
+ useEffect39(() => {
16923
17270
  setShowBalance(showBalance);
16924
17271
  if (!ready)
16925
17272
  setReady(true);
16926
17273
  }, [showBalance, setShowBalance]);
16927
- useEffect38(() => {
17274
+ useEffect39(() => {
16928
17275
  const interval = setInterval(() => {
16929
17276
  setRollingChainIndex((prev) => (prev + 1) % chainTypes.length);
16930
17277
  }, 1e4);
@@ -17206,7 +17553,7 @@ var maxWidth = "hk857q1";
17206
17553
  // src/components/WalletButton/WalletButtonRenderer.tsx
17207
17554
  import React106, {
17208
17555
  useContext as useContext33,
17209
- useEffect as useEffect39,
17556
+ useEffect as useEffect40,
17210
17557
  useMemo as useMemo25,
17211
17558
  useState as useState46
17212
17559
  } from "react";
@@ -17230,7 +17577,7 @@ function WalletButtonRenderer({
17230
17577
  const [loading, setLoading] = useState46(false);
17231
17578
  const [isError, setIsError] = useState46(false);
17232
17579
  const mobile = isMobile();
17233
- useEffect39(() => {
17580
+ useEffect40(() => {
17234
17581
  if (!connectModalOpen && connector)
17235
17582
  setConnector(null);
17236
17583
  }, [connectModalOpen, connector, setConnector]);
@@ -18137,7 +18484,7 @@ var __private__ = {
18137
18484
  };
18138
18485
 
18139
18486
  // src/hooks/useDeviceType.ts
18140
- import { useEffect as useEffect40, useState as useState47 } from "react";
18487
+ import { useEffect as useEffect41, useState as useState47 } from "react";
18141
18488
  var BREAKPOINTS = {
18142
18489
  mobile: 1024,
18143
18490
  // 0-1024px (includes phones and tablets)
@@ -18162,7 +18509,7 @@ function useDeviceType() {
18162
18509
  }
18163
18510
  return getDeviceState(window.innerWidth);
18164
18511
  });
18165
- useEffect40(() => {
18512
+ useEffect41(() => {
18166
18513
  setState(getDeviceState(window.innerWidth));
18167
18514
  function handleResize() {
18168
18515
  setState(getDeviceState(window.innerWidth));
@@ -18174,7 +18521,7 @@ function useDeviceType() {
18174
18521
  }
18175
18522
 
18176
18523
  // src/hooks/useWalletCapabilities.ts
18177
- import { useCallback as useCallback30, useEffect as useEffect41, useState as useState48 } from "react";
18524
+ import { useCallback as useCallback30, useEffect as useEffect42, useState as useState48 } from "react";
18178
18525
  import { useAccount as useAccount24, useWalletClient } from "wagmi";
18179
18526
 
18180
18527
  // src/wallets/capabilities/requestWalletAction.ts
@@ -18382,7 +18729,7 @@ function useWalletCapabilities() {
18382
18729
  setIsLoading(false);
18383
18730
  }
18384
18731
  }, [address, connector?.id, connector?.name, isConnected, walletClient]);
18385
- useEffect41(() => {
18732
+ useEffect42(() => {
18386
18733
  void refresh();
18387
18734
  }, [refresh]);
18388
18735
  const signAuthorization = useCallback30(
@@ -18482,13 +18829,13 @@ function getSolanaConfig(options = {}) {
18482
18829
  }
18483
18830
 
18484
18831
  // src/wallets/walletConnectors/abcWallet/AbcEvmAutoConnector.tsx
18485
- import { useEffect as useEffect42, useRef as useRef20 } from "react";
18832
+ import { useEffect as useEffect43, useRef as useRef21 } from "react";
18486
18833
  import { useAccount as useAccount25, useConnect as useConnect3 } from "wagmi";
18487
18834
  function AbcEvmAutoConnector() {
18488
18835
  const { connectors, connect } = useConnect3();
18489
18836
  const { isConnected } = useAccount25();
18490
- const hasAttemptedRef = useRef20(false);
18491
- useEffect42(() => {
18837
+ const hasAttemptedRef = useRef21(false);
18838
+ useEffect43(() => {
18492
18839
  if (isConnected || hasAttemptedRef.current) {
18493
18840
  return;
18494
18841
  }
@@ -18547,13 +18894,118 @@ function ChainIndicator({
18547
18894
  ), showName && /* @__PURE__ */ React109.createElement(Text, { color: "modalText", className: chainName }, resolvedName), showBadge && /* @__PURE__ */ React109.createElement("div", { className: chainBadge }));
18548
18895
  }
18549
18896
 
18897
+ // src/services/AbcAuthService.ts
18898
+ async function registerUser(params, _config) {
18899
+ const api = getTalkenApiClient();
18900
+ if (!api) {
18901
+ throw new Error("TalkenApiClient not initialized");
18902
+ }
18903
+ const res = await api.auth.register({
18904
+ email: params.username,
18905
+ otpCode: params.emailCode,
18906
+ password: params.password,
18907
+ name: params.name
18908
+ });
18909
+ return { status: "success", data: res };
18910
+ }
18911
+ async function registerSnsUser(params, _config) {
18912
+ const api = getTalkenApiClient();
18913
+ if (!api) {
18914
+ throw new Error("TalkenApiClient not initialized");
18915
+ }
18916
+ const res = await api.auth.register({
18917
+ email: params.username,
18918
+ otpCode: params.sixCode,
18919
+ password: "",
18920
+ name: params.name
18921
+ });
18922
+ return { status: "success", data: res };
18923
+ }
18924
+ async function resetPassword(params, _config) {
18925
+ const api = getTalkenApiClient();
18926
+ if (!api) {
18927
+ throw new Error("TalkenApiClient not initialized");
18928
+ }
18929
+ const res = await api.auth.resetPassword(
18930
+ params.username,
18931
+ params.password,
18932
+ params.emailCode
18933
+ );
18934
+ return { status: "success", data: res };
18935
+ }
18936
+ async function emailCheck(email, _config) {
18937
+ const api = getTalkenApiClient();
18938
+ if (!api) {
18939
+ throw new Error("TalkenApiClient not initialized");
18940
+ }
18941
+ const res = await api.auth.checkEmail(email);
18942
+ return {
18943
+ status: "success",
18944
+ message: { code: res.code || 0, text: res.message || "" }
18945
+ };
18946
+ }
18947
+ async function sendOtpCode(email, _config) {
18948
+ const api = getTalkenApiClient();
18949
+ if (!api) {
18950
+ throw new Error("TalkenApiClient not initialized");
18951
+ }
18952
+ await api.auth.sendOtp(email);
18953
+ return { status: "success", data: { sent: true } };
18954
+ }
18955
+ async function verifyOtpCode(email, code, _config) {
18956
+ const api = getTalkenApiClient();
18957
+ if (!api) {
18958
+ throw new Error("TalkenApiClient not initialized");
18959
+ }
18960
+ await api.auth.verifyOtp(email, code);
18961
+ return { status: "success", data: { verified: true } };
18962
+ }
18963
+ async function loginWithPassword(params, _apiServer) {
18964
+ const api = getTalkenApiClient();
18965
+ if (!api) {
18966
+ throw new Error("TalkenApiClient not initialized");
18967
+ }
18968
+ const res = await api.auth.loginWithPassword(
18969
+ params.username,
18970
+ params.password
18971
+ );
18972
+ return {
18973
+ access_token: res.accessToken,
18974
+ refresh_token: res.refreshToken,
18975
+ expires_in: res.expiresIn,
18976
+ uid: res.uid,
18977
+ email: res.email
18978
+ };
18979
+ }
18980
+ async function performSnsLogin(token, service, email) {
18981
+ const api = getTalkenApiClient();
18982
+ if (!api) {
18983
+ throw new Error("TalkenApiClient not initialized");
18984
+ }
18985
+ const res = await api.auth.loginWithSns({ token, service });
18986
+ return {
18987
+ uid: res.uid,
18988
+ access_token: res.accessToken,
18989
+ refresh_token: res.refreshToken,
18990
+ email: res.email || email,
18991
+ user_type: res.isNewUser ? "new" : "existing"
18992
+ };
18993
+ }
18994
+ async function kakaoLogin2(_config) {
18995
+ const kakaoAuth = await kakaoLogin();
18996
+ if (!kakaoAuth)
18997
+ return null;
18998
+ return performSnsLogin(kakaoAuth.idToken, "kakao", kakaoAuth.email);
18999
+ }
19000
+
18550
19001
  // src/providers/AbcAuthProvider.tsx
18551
19002
  import React110, {
18552
19003
  createContext as createContext22,
18553
19004
  useContext as useContext36,
18554
19005
  useState as useState49,
18555
- useEffect as useEffect43,
18556
- useCallback as useCallback31
19006
+ useEffect as useEffect44,
19007
+ useCallback as useCallback31,
19008
+ useRef as useRef22
18557
19009
  } from "react";
18558
19010
  var logger28 = createLogger("AbcAuthProvider");
18559
19011
  var AbcAuthContext = createContext22(null);
@@ -18585,12 +19037,19 @@ function AbcAuthProvider({ children }) {
18585
19037
  },
18586
19038
  pinHash: null
18587
19039
  });
19040
+ const authGeneration = useRef22(0);
19041
+ useEffect44(
19042
+ () => () => {
19043
+ authGeneration.current++;
19044
+ },
19045
+ []
19046
+ );
18588
19047
  const isTokenExpired = useCallback31(() => {
18589
19048
  if (!state.tokens.expiresAt)
18590
19049
  return true;
18591
19050
  return Date.now() >= state.tokens.expiresAt;
18592
19051
  }, [state.tokens.expiresAt]);
18593
- useEffect43(() => {
19052
+ useEffect44(() => {
18594
19053
  if (state.tokens.expiresAt && state.tokens.expiresAt > Date.now()) {
18595
19054
  scheduleProactiveRefresh(state.tokens.expiresAt);
18596
19055
  }
@@ -18605,27 +19064,32 @@ function AbcAuthProvider({ children }) {
18605
19064
  logger28.debug("No refresh token available");
18606
19065
  return false;
18607
19066
  }
19067
+ const generation = authGeneration.current;
19068
+ const storedAuth = get(STORAGE_NS.ABC, "auth_state");
19069
+ const api = getTalkenApiClient();
19070
+ const revision = api?.getSessionRevision();
19071
+ const isCurrent = () => authGeneration.current === generation && getTalkenApiClient() === api && api?.getSessionRevision() === revision && !!api && ownsTalkenApiStorage(api) && get(STORAGE_NS.ABC, "auth_state") === storedAuth;
18608
19072
  try {
18609
- const api = getTalkenApiClient();
18610
19073
  if (!api) {
18611
19074
  logger28.error("TalkenApiClient not initialized");
18612
19075
  return false;
18613
19076
  }
18614
- api.setTokens(
18615
- state.tokens.accessToken || "",
18616
- state.tokens.refreshToken,
18617
- state.tokens.expiresAt || 0
18618
- );
19077
+ if (api.isAccessKeyMode() || api.getAccessToken() !== state.tokens.accessToken || api.getRefreshToken() !== state.tokens.refreshToken)
19078
+ return false;
18619
19079
  const res = await api.auth.refresh();
19080
+ if (!isCurrent())
19081
+ return false;
18620
19082
  const expiresAt = Date.now() + res.expiresIn * 1e3;
18621
- setState((prev) => ({
18622
- ...prev,
18623
- tokens: {
18624
- accessToken: res.accessToken,
18625
- refreshToken: res.refreshToken || prev.tokens.refreshToken,
18626
- expiresAt
18627
- }
18628
- }));
19083
+ setState(
19084
+ (prev) => isCurrent() ? {
19085
+ ...prev,
19086
+ tokens: {
19087
+ accessToken: res.accessToken,
19088
+ refreshToken: res.refreshToken || prev.tokens.refreshToken,
19089
+ expiresAt
19090
+ }
19091
+ } : prev
19092
+ );
18629
19093
  set(STORAGE_NS.ABC, "access_token", res.accessToken);
18630
19094
  if (res.refreshToken) {
18631
19095
  set(STORAGE_NS.ABC, "refresh_token", res.refreshToken);
@@ -18635,26 +19099,34 @@ function AbcAuthProvider({ children }) {
18635
19099
  logger28.info("Token refreshed");
18636
19100
  return true;
18637
19101
  } catch (error2) {
19102
+ if (!isCurrent())
19103
+ return false;
18638
19104
  logger28.error("Token refresh error:", error2);
18639
19105
  return false;
18640
19106
  }
18641
- }, [
18642
- state.tokens.refreshToken,
18643
- state.tokens.accessToken,
18644
- state.tokens.expiresAt
18645
- ]);
19107
+ }, [state.tokens.refreshToken, state.tokens.accessToken]);
18646
19108
  const unlockWithPin = useCallback31(async (pin) => {
19109
+ const api = getTalkenApiClient();
19110
+ const revision = api?.getSessionRevision();
19111
+ const generation = authGeneration.current;
19112
+ const storedAuth = get(STORAGE_NS.ABC, "auth_state");
19113
+ const credentials = JSON.stringify([
19114
+ api?.getAccessToken(),
19115
+ api?.getRefreshToken()
19116
+ ]);
19117
+ const encryptedTokens = get(STORAGE_NS.ABC, "enc_tokens");
19118
+ const saltHex = get(STORAGE_NS.ABC, "enc_salt");
19119
+ const storedPinHash = getCredentialManager().getPinHash();
19120
+ const isCurrent = () => authGeneration.current === generation && getTalkenApiClient() === api && api?.getSessionRevision() === revision && !!api && ownsTalkenApiStorage(api) && JSON.stringify([api?.getAccessToken(), api?.getRefreshToken()]) === credentials && get(STORAGE_NS.ABC, "auth_state") === storedAuth && get(STORAGE_NS.ABC, "enc_tokens") === encryptedTokens && get(STORAGE_NS.ABC, "enc_salt") === saltHex && getCredentialManager().getPinHash() === storedPinHash;
18647
19121
  try {
18648
- const encryptedTokens = get(STORAGE_NS.ABC, "enc_tokens");
18649
- const saltHex = get(STORAGE_NS.ABC, "enc_salt");
18650
- const { getCredentialManager: getCredentialManager2 } = await import("./AbcCredentialManager-WZBF3GHF.js");
18651
- const storedPinHash = getCredentialManager2().getPinHash();
18652
19122
  if (!encryptedTokens || !saltHex || !storedPinHash) {
18653
19123
  throw new Error("No encrypted data found");
18654
19124
  }
18655
19125
  const encoder = new TextEncoder();
18656
19126
  const data = encoder.encode(pin);
18657
19127
  const hash = await crypto.subtle.digest("SHA-256", data);
19128
+ if (!isCurrent())
19129
+ return false;
18658
19130
  const hashedPin = Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
18659
19131
  if (hashedPin !== storedPinHash) {
18660
19132
  throw new Error("Incorrect PIN");
@@ -18664,32 +19136,49 @@ function AbcAuthProvider({ children }) {
18664
19136
  hashedPin,
18665
19137
  saltHex
18666
19138
  );
19139
+ if (!isCurrent())
19140
+ return false;
18667
19141
  const sensitiveData = JSON.parse(decrypted);
18668
- setState((prev) => ({
18669
- ...prev,
18670
- isAuthenticated: true,
18671
- tokens: {
18672
- accessToken: sensitiveData.accessToken,
18673
- refreshToken: sensitiveData.refreshToken,
18674
- expiresAt: sensitiveData.expiresAt || Date.now() + 6e5
18675
- },
18676
- wallets: {
18677
- evm: sensitiveData.evmWallet || null,
18678
- solana: sensitiveData.solanaWallet || null,
18679
- bitcoin: sensitiveData.bitcoinWallet || null,
18680
- tron: sensitiveData.tronWallet || null,
18681
- xrpl: sensitiveData.xrplWallet || null
18682
- },
18683
- pinHash: hashedPin
18684
- }));
19142
+ const persisted = JSON.parse(storedAuth || "null");
19143
+ if (api?.isAccessKeyMode() || [api?.getAccessToken(), persisted?.accessToken].some(
19144
+ (token) => token && token !== sensitiveData.accessToken
19145
+ ) || [api?.getRefreshToken(), persisted?.refreshToken].some(
19146
+ (token) => token && token !== sensitiveData.refreshToken
19147
+ ))
19148
+ return false;
19149
+ setState(
19150
+ (prev) => isCurrent() ? {
19151
+ ...prev,
19152
+ isAuthenticated: true,
19153
+ tokens: {
19154
+ accessToken: sensitiveData.accessToken,
19155
+ refreshToken: sensitiveData.refreshToken,
19156
+ expiresAt: sensitiveData.expiresAt || Date.now() + 6e5
19157
+ },
19158
+ wallets: {
19159
+ evm: sensitiveData.evmWallet || null,
19160
+ solana: sensitiveData.solanaWallet || null,
19161
+ bitcoin: sensitiveData.bitcoinWallet || null,
19162
+ tron: sensitiveData.tronWallet || null,
19163
+ xrpl: sensitiveData.xrplWallet || null
19164
+ },
19165
+ pinHash: hashedPin
19166
+ } : prev
19167
+ );
18685
19168
  logger28.info("Unlocked with PIN");
18686
19169
  return true;
18687
19170
  } catch (error2) {
19171
+ if (!isCurrent())
19172
+ return false;
18688
19173
  logger28.error("Unlock failed:", error2);
18689
19174
  return false;
18690
19175
  }
18691
19176
  }, []);
18692
19177
  const logout = useCallback31(async () => {
19178
+ authGeneration.current++;
19179
+ const api = getTalkenApiClient();
19180
+ api?.clearSession();
19181
+ const ownsStorage = !!api && ownsTalkenApiStorage(api);
18693
19182
  setState({
18694
19183
  isAuthenticated: false,
18695
19184
  user: { email: null, uid: null },
@@ -18703,20 +19192,20 @@ function AbcAuthProvider({ children }) {
18703
19192
  },
18704
19193
  pinHash: null
18705
19194
  });
19195
+ if (!ownsStorage)
19196
+ return;
19197
+ cancelProactiveRefresh();
19198
+ getCredentialManager().clear();
18706
19199
  clearNamespace(STORAGE_NS.ABC);
18707
19200
  clearNamespace(STORAGE_NS.ABC, "session");
18708
19201
  remove(STORAGE_NS.API, "access_key_raw");
18709
- try {
18710
- const { getTalkenApiClient: getTalkenApiClient4 } = await import("./TalkenApiSingleton-TECFDCT4.js");
18711
- getTalkenApiClient4()?.clearSession();
18712
- } catch {
18713
- }
18714
19202
  logger28.info("Logged out");
18715
19203
  }, []);
18716
19204
  const setAuthState = useCallback31((partial) => {
19205
+ authGeneration.current++;
18717
19206
  setState((prev) => ({ ...prev, ...partial }));
18718
19207
  }, []);
18719
- useEffect43(() => {
19208
+ useEffect44(() => {
18720
19209
  const restoreSession = async () => {
18721
19210
  try {
18722
19211
  const authState = getJSON(STORAGE_NS.ABC, "auth_state");
@@ -18793,8 +19282,11 @@ function AbcAuthProvider({ children }) {
18793
19282
  );
18794
19283
  };
18795
19284
  }, []);
18796
- useEffect43(() => {
18797
- const handleExpired = () => {
19285
+ useEffect44(() => {
19286
+ const handleExpired = (event) => {
19287
+ const isCurrent = event.detail?.isCurrent;
19288
+ if (typeof isCurrent !== "function" || !isCurrent())
19289
+ return;
18798
19290
  logger28.info("Access key expired \u2014 logging out");
18799
19291
  logout();
18800
19292
  };
@@ -18817,73 +19309,115 @@ import React111, {
18817
19309
  createContext as createContext23,
18818
19310
  useContext as useContext37,
18819
19311
  useState as useState50,
18820
- useCallback as useCallback32
19312
+ useCallback as useCallback32,
19313
+ useRef as useRef23,
19314
+ useEffect as useEffect45
18821
19315
  } from "react";
18822
19316
  var PinContext = createContext23(null);
19317
+ var pinSessionChangedError = () => Object.assign(
19318
+ new Error("The wallet session changed. Please request PIN again."),
19319
+ { code: "AUTH_SESSION_CHANGED" }
19320
+ );
18823
19321
  function PinProvider({ children }) {
18824
19322
  const [isModalOpen, setIsModalOpen] = useState50(false);
18825
19323
  const [purpose, setPurpose] = useState50("transaction");
18826
- const [pinResolver, setPinResolver] = useState50(null);
18827
- const [pinRejecter, setPinRejecter] = useState50(null);
18828
- const [error2, setError] = useState50("");
19324
+ const [pending, setPending] = useState50(null);
19325
+ const pendingRef = useRef23(null);
19326
+ const nextModal = useRef23(0);
19327
+ const isCurrent = (request) => pendingRef.current === request && getTalkenApiClient() === request.api && request.api.getSessionRevision() === request.revision && ownsTalkenApiStorage(request.api) && getCredentialManager().getPinHash() === request.pinHash;
19328
+ useEffect45(
19329
+ () => () => {
19330
+ pendingRef.current?.reject(pinSessionChangedError());
19331
+ pendingRef.current = null;
19332
+ },
19333
+ []
19334
+ );
18829
19335
  const requestPin = useCallback32(
18830
19336
  (requestPurpose = "transaction") => {
19337
+ const api = getTalkenApiClient();
19338
+ const revision = api?.getSessionRevision();
19339
+ if (!api || !ownsTalkenApiStorage(api))
19340
+ return Promise.reject(pinSessionChangedError());
19341
+ pendingRef.current?.reject(pinSessionChangedError());
18831
19342
  return new Promise((resolve, reject) => {
19343
+ const request = {
19344
+ id: ++nextModal.current,
19345
+ api,
19346
+ revision,
19347
+ pinHash: getCredentialManager().getPinHash(),
19348
+ resolve,
19349
+ reject
19350
+ };
19351
+ pendingRef.current = request;
19352
+ setPending(request);
18832
19353
  setPurpose(requestPurpose);
18833
19354
  setIsModalOpen(true);
18834
- setError("");
18835
- setPinResolver(() => resolve);
18836
- setPinRejecter(() => reject);
18837
19355
  });
18838
19356
  },
18839
19357
  []
18840
19358
  );
18841
- const handlePinSubmit = useCallback32(
18842
- async (pin) => {
18843
- if (!pinResolver) {
19359
+ const closeRequest = (request) => {
19360
+ if (pendingRef.current !== request)
19361
+ return;
19362
+ pendingRef.current = null;
19363
+ setPending(null);
19364
+ setIsModalOpen(false);
19365
+ };
19366
+ const handlePinSubmit = async (pin) => {
19367
+ const request = pending;
19368
+ if (!request)
19369
+ return;
19370
+ if (!isCurrent(request)) {
19371
+ request.reject(pinSessionChangedError());
19372
+ closeRequest(request);
19373
+ return;
19374
+ }
19375
+ if (!request.pinHash)
19376
+ throw new Error("PIN not set. Please login again.");
19377
+ try {
19378
+ const enteredPinHash = await hashPin(pin);
19379
+ if (!isCurrent(request)) {
19380
+ request.reject(pinSessionChangedError());
19381
+ closeRequest(request);
18844
19382
  return;
18845
19383
  }
18846
- const { getCredentialManager: getCredentialManager2 } = await import("./AbcCredentialManager-WZBF3GHF.js");
18847
- const storedPinHash = getCredentialManager2().getPinHash();
18848
- if (!storedPinHash) {
18849
- throw new Error("PIN not set. Please login again.");
18850
- }
18851
- const enteredPinHash = await hashPin(pin);
18852
- if (enteredPinHash !== storedPinHash) {
19384
+ if (enteredPinHash !== request.pinHash)
18853
19385
  throw new Error("Incorrect PIN. Please try again.");
19386
+ request.resolve(pin);
19387
+ closeRequest(request);
19388
+ } catch (error2) {
19389
+ if (!isCurrent(request)) {
19390
+ request.reject(pinSessionChangedError());
19391
+ closeRequest(request);
19392
+ return;
18854
19393
  }
18855
- pinResolver(pin);
18856
- setIsModalOpen(false);
18857
- setPinResolver(null);
18858
- setPinRejecter(null);
18859
- setError("");
18860
- },
18861
- [pinResolver]
18862
- );
18863
- const handleModalClose = useCallback32(() => {
18864
- if (pinRejecter) {
18865
- const error3 = new Error("User cancelled PIN request");
18866
- error3.code = 4001;
18867
- error3.cancelled = true;
18868
- pinRejecter(error3);
18869
- setIsModalOpen(false);
18870
- setPinResolver(null);
18871
- setPinRejecter(null);
18872
- setError("");
19394
+ throw error2;
18873
19395
  }
18874
- }, [pinRejecter]);
19396
+ };
19397
+ const handleModalClose = () => {
19398
+ const request = pending;
19399
+ if (!request || pendingRef.current !== request)
19400
+ return;
19401
+ const error2 = Object.assign(new Error("User cancelled PIN request"), {
19402
+ code: 4001,
19403
+ cancelled: true
19404
+ });
19405
+ request.reject(error2);
19406
+ closeRequest(request);
19407
+ };
18875
19408
  const value2 = {
18876
19409
  requestPin
18877
19410
  };
18878
19411
  return /* @__PURE__ */ React111.createElement(PinContext.Provider, { value: value2 }, children, /* @__PURE__ */ React111.createElement(
18879
19412
  PinInputModal,
18880
19413
  {
19414
+ key: pending?.id ?? "closed",
18881
19415
  isOpen: isModalOpen,
18882
19416
  onClose: handleModalClose,
18883
19417
  onSubmit: handlePinSubmit,
18884
19418
  title: purpose === "transaction" ? "Confirm Transaction" : "Enter PIN",
18885
19419
  subtitle: purpose === "transaction" ? "Enter your PIN to sign this transaction" : "Enter your 6-digit PIN",
18886
- errorMessage: error2,
19420
+ errorMessage: "",
18887
19421
  showForgotPin: false
18888
19422
  }
18889
19423
  ));
@@ -19066,8 +19600,8 @@ function embeddedTxToWagmi(embeddedTx) {
19066
19600
  }
19067
19601
 
19068
19602
  // src/gasless/hooks/useGaslessTransfer.ts
19069
- import { useCallback as useCallback34, useEffect as useEffect44, useRef as useRef21, useState as useState51 } from "react";
19070
- import { useAccount as useAccount26, usePublicClient as usePublicClient2, useWalletClient as useWalletClient2 } from "wagmi";
19603
+ import { useCallback as useCallback34, useEffect as useEffect46, useRef as useRef24, useState as useState51 } from "react";
19604
+ import { useAccount as useAccount26, useConfig as useConfig7, usePublicClient as usePublicClient2, useWalletClient as useWalletClient2 } from "wagmi";
19071
19605
 
19072
19606
  // src/gasless/signer/WagmiSigner.ts
19073
19607
  var MAX_RETRY = 3;
@@ -19087,13 +19621,132 @@ var WagmiSigner = class {
19087
19621
  this.walletClient = params.walletClient;
19088
19622
  this.publicClient = params.publicClient;
19089
19623
  this._supportsAuth = params.supportsAuthorization ?? false;
19624
+ this.assertOrigin = params.assertSessionCurrent;
19625
+ const account = params.walletClient.account;
19626
+ this.originAccount = typeof account === "object" ? { ...account } : account;
19627
+ this.originAddress = this.accountAddress()?.toLowerCase();
19628
+ this.originChain = params.walletClient.chain ? { ...params.walletClient.chain } : void 0;
19629
+ this.originChainId = params.walletClient.chain?.id;
19630
+ }
19631
+ accountAddress() {
19632
+ const account = this.walletClient.account;
19633
+ return typeof account === "string" ? account : account?.address;
19634
+ }
19635
+ assertSessionCurrent() {
19636
+ if (!this.assertOrigin || !this.originAddress || !this.originChainId)
19637
+ throw new TalkenApiError(
19638
+ "AUTH_SESSION_UNBOUND",
19639
+ "An originating external wallet connection is required.",
19640
+ 401
19641
+ );
19642
+ this.assertOrigin();
19643
+ if (this.accountAddress()?.toLowerCase() !== this.originAddress || this.walletClient.chain?.id !== this.originChainId || this.publicClient.chain && this.publicClient.chain.id !== this.originChainId)
19644
+ throw new TalkenApiError(
19645
+ "AUTH_SESSION_CHANGED",
19646
+ "The originating external account or chain changed.",
19647
+ 401
19648
+ );
19649
+ }
19650
+ assertRequestedOrigin(address, chainId) {
19651
+ this.assertSessionCurrent();
19652
+ if (address !== void 0 && address.toLowerCase() !== this.originAddress || chainId !== void 0 && chainId !== this.originChainId)
19653
+ throw new TalkenApiError(
19654
+ "AUTH_SESSION_CHANGED",
19655
+ "The request does not match the originating external account and chain.",
19656
+ 401
19657
+ );
19658
+ }
19659
+ assertDelegationOrigin(chainKey, address) {
19660
+ this.assertRequestedOrigin(address);
19661
+ let originChainKey;
19662
+ try {
19663
+ originChainKey = getChainKey(this.originChainId);
19664
+ } catch {
19665
+ throw new TalkenApiError(
19666
+ "AUTH_SESSION_UNBOUND",
19667
+ "The originating external chain is unsupported.",
19668
+ 401
19669
+ );
19670
+ }
19671
+ if (chainKey !== originChainKey)
19672
+ throw new TalkenApiError(
19673
+ "AUTH_SESSION_CHANGED",
19674
+ "The delegation lookup does not match the originating chain.",
19675
+ 401
19676
+ );
19677
+ }
19678
+ async withSession(operation) {
19679
+ this.assertSessionCurrent();
19680
+ try {
19681
+ const result = await operation();
19682
+ this.assertSessionCurrent();
19683
+ return result;
19684
+ } catch (error2) {
19685
+ this.assertSessionCurrent();
19686
+ throw error2;
19687
+ }
19688
+ }
19689
+ getDelegationClient() {
19690
+ const readCode = this.publicClient.getCode;
19691
+ if (!readCode)
19692
+ return null;
19693
+ return {
19694
+ readCode: (chainKey, address) => this.withSession(async () => {
19695
+ this.assertDelegationOrigin(chainKey, address);
19696
+ return await readCode.call(this.publicClient, {
19697
+ address
19698
+ }) ?? "0x";
19699
+ }),
19700
+ revoke: (chainKey, chainId, address) => this.withSession(async () => {
19701
+ this.assertDelegationOrigin(chainKey, address);
19702
+ this.assertRequestedOrigin(address, chainId);
19703
+ const sign = this.walletClient.signAuthorization;
19704
+ const send = this.walletClient.sendTransaction;
19705
+ if (!sign || !send)
19706
+ throw new TalkenApiError(
19707
+ "EXTERNAL_REVOKE_UNSUPPORTED",
19708
+ "This wallet cannot sign and send an EIP-7702 revoke.",
19709
+ 400
19710
+ );
19711
+ return sendRevokeViaWalletClient(
19712
+ {
19713
+ assertSessionCurrent: () => this.assertSessionCurrent(),
19714
+ getTransactionCount: (args) => this.withSession(
19715
+ () => this.publicClient.getTransactionCount(args)
19716
+ ),
19717
+ signAuthorization: (args) => this.withSession(
19718
+ () => sign.call(this.walletClient, {
19719
+ ...args,
19720
+ account: this.originAccount
19721
+ })
19722
+ ),
19723
+ sendTransaction: (args) => this.withSession(
19724
+ () => send.call(this.walletClient, {
19725
+ ...args,
19726
+ account: this.originAccount,
19727
+ chain: this.originChain
19728
+ })
19729
+ ),
19730
+ ...this.publicClient.waitForTransactionReceipt && {
19731
+ waitForTransactionReceipt: (args) => this.withSession(
19732
+ () => this.publicClient.waitForTransactionReceipt(args)
19733
+ )
19734
+ }
19735
+ },
19736
+ chainId,
19737
+ address
19738
+ );
19739
+ })
19740
+ };
19090
19741
  }
19091
19742
  supportsAuthorization() {
19092
19743
  return this._supportsAuth && typeof this.walletClient.signAuthorization === "function";
19093
19744
  }
19094
19745
  async signTypedData(typedData) {
19746
+ this.assertRequestedOrigin(void 0, typedData.domain.chainId);
19095
19747
  return this.withRetry(
19096
19748
  () => this.walletClient.signTypedData({
19749
+ account: this.originAccount,
19097
19750
  domain: typedData.domain,
19098
19751
  types: typedData.types,
19099
19752
  primaryType: typedData.primaryType,
@@ -19102,11 +19755,13 @@ var WagmiSigner = class {
19102
19755
  );
19103
19756
  }
19104
19757
  async signAuthorization(authorization) {
19758
+ this.assertRequestedOrigin(void 0, authorization.chainId);
19105
19759
  if (!this.supportsAuthorization()) {
19106
19760
  throw new Error("This wallet does not support EIP-7702 authorization");
19107
19761
  }
19108
19762
  const result = await this.withRetry(
19109
19763
  () => this.walletClient.signAuthorization({
19764
+ account: this.originAccount,
19110
19765
  contractAddress: authorization.address,
19111
19766
  chainId: authorization.chainId,
19112
19767
  nonce: authorization.nonce
@@ -19122,10 +19777,13 @@ var WagmiSigner = class {
19122
19777
  };
19123
19778
  }
19124
19779
  async getNonce(address) {
19125
- return this.publicClient.getTransactionCount({
19126
- address,
19127
- blockTag: "pending"
19128
- });
19780
+ this.assertRequestedOrigin(address);
19781
+ return this.withSession(
19782
+ () => this.publicClient.getTransactionCount({
19783
+ address,
19784
+ blockTag: "pending"
19785
+ })
19786
+ );
19129
19787
  }
19130
19788
  /**
19131
19789
  * Retry wrapper. Retries on transient errors but NOT on user rejection.
@@ -19133,10 +19791,12 @@ var WagmiSigner = class {
19133
19791
  async withRetry(fn) {
19134
19792
  let lastError = null;
19135
19793
  for (let attempt = 0; attempt < MAX_RETRY; attempt++) {
19794
+ this.assertSessionCurrent();
19136
19795
  try {
19137
- return await fn();
19796
+ return await this.withSession(fn);
19138
19797
  } catch (error2) {
19139
- if (isUserRejection(error2))
19798
+ this.assertSessionCurrent();
19799
+ if (isUserRejection(error2) || error2?.code === "AUTH_SESSION_CHANGED" || error2?.code === "AUTH_SESSION_UNBOUND")
19140
19800
  throw error2;
19141
19801
  lastError = error2;
19142
19802
  if (attempt < MAX_RETRY - 1) {
@@ -19288,6 +19948,7 @@ function tryGetChainKey2(chainId) {
19288
19948
  function useGaslessTransfer(params) {
19289
19949
  const gaslessConfig = useGaslessConfig();
19290
19950
  const { connector } = useAccount26();
19951
+ const wagmiConfig = useConfig7();
19291
19952
  const { data: walletClient } = useWalletClient2();
19292
19953
  const publicClient = usePublicClient2();
19293
19954
  const [canGasless, setCanGasless] = useState51(false);
@@ -19298,48 +19959,81 @@ function useGaslessTransfer(params) {
19298
19959
  const [isExecuting, setIsExecuting] = useState51(false);
19299
19960
  const [error2, setError] = useState51(null);
19300
19961
  const [unavailableReason, setUnavailableReason] = useState51(null);
19301
- const feeServiceRef = useRef21(getSharedGaslessFeeService());
19302
- const abortRef = useRef21(0);
19303
- const executeLockRef = useRef21(Promise.resolve());
19304
- const mountedRef = useRef21(true);
19962
+ const feeServiceRef = useRef24(getSharedGaslessFeeService());
19963
+ const abortRef = useRef24(0);
19964
+ const executeLockRef = useRef24(Promise.resolve());
19965
+ const mountedRef = useRef24(true);
19305
19966
  const chainId = params?.chainId;
19306
19967
  const address = params?.address;
19307
19968
  const tokenAddress = params?.tokenAddress;
19308
19969
  const toAddress = params?.toAddress;
19309
19970
  const amount = params?.amount;
19310
19971
  const isAbcWallet = connector?.id === "abc";
19972
+ const originatingApi = isAbcWallet ? getTalkenApiClient() : void 0;
19973
+ const originatingRevision = originatingApi?.getSessionRevision();
19311
19974
  const signerSupportsAuth = isAbcWallet ? true : typeof walletClient?.signAuthorization === "function";
19312
19975
  const createSigner = useCallback34(() => {
19313
19976
  if (!chainId)
19314
19977
  return null;
19315
19978
  if (isAbcWallet) {
19979
+ const api = getTalkenApiClient();
19980
+ if (!api || api !== originatingApi || api.getSessionRevision() !== originatingRevision || !ownsTalkenApiStorage(api))
19981
+ return null;
19982
+ const session = api.isAccessKeyMode() ? api.getAuthenticatedWalletSession() : null;
19983
+ if (api.isAccessKeyMode() && (!session || !address || session.wallets.evm.toLowerCase() !== address.toLowerCase()))
19984
+ return null;
19316
19985
  const credentialManager = getCredentialManager();
19317
- const pinHash = credentialManager.getPinHash();
19318
- if (!pinHash)
19986
+ const pinHash = session ? void 0 : credentialManager.getPinHash() ?? void 0;
19987
+ if (!session && !pinHash)
19319
19988
  return null;
19320
19989
  return new AbcWaasSigner({
19321
19990
  pinHash,
19322
19991
  network: getNetworkName(chainId),
19323
- email: credentialManager.getEmail() ?? void 0
19992
+ email: session ? session.user.email ?? void 0 : credentialManager.getEmail() ?? void 0
19324
19993
  });
19325
19994
  }
19326
19995
  if (walletClient && publicClient) {
19996
+ const connection = wagmiConfig.state.connections.get(
19997
+ wagmiConfig.state.current ?? ""
19998
+ );
19999
+ if (wagmiConfig.state.status !== "connected" || !connection || connection.connector !== connector || connection.chainId !== chainId || !address || connection.accounts[0]?.toLowerCase() !== address.toLowerCase() || walletClient.account?.address.toLowerCase() !== address.toLowerCase())
20000
+ return null;
19327
20001
  return new WagmiSigner({
19328
20002
  walletClient,
19329
20003
  publicClient,
19330
- supportsAuthorization: true
20004
+ supportsAuthorization: true,
19331
20005
  // MetaMask supports EIP-7702
20006
+ assertSessionCurrent: () => {
20007
+ if (wagmiConfig.state.status !== "connected" || wagmiConfig.state.connections.get(
20008
+ wagmiConfig.state.current ?? ""
20009
+ ) !== connection)
20010
+ throw new TalkenApiError(
20011
+ "AUTH_SESSION_CHANGED",
20012
+ "The external wallet connection changed during the operation.",
20013
+ 401
20014
+ );
20015
+ }
19332
20016
  });
19333
20017
  }
19334
20018
  return null;
19335
- }, [isAbcWallet, chainId, walletClient, publicClient]);
19336
- useEffect44(() => {
20019
+ }, [
20020
+ isAbcWallet,
20021
+ chainId,
20022
+ address,
20023
+ walletClient,
20024
+ publicClient,
20025
+ originatingApi,
20026
+ originatingRevision,
20027
+ wagmiConfig,
20028
+ connector
20029
+ ]);
20030
+ useEffect46(() => {
19337
20031
  mountedRef.current = true;
19338
20032
  return () => {
19339
20033
  mountedRef.current = false;
19340
20034
  };
19341
20035
  }, []);
19342
- useEffect44(() => {
20036
+ useEffect46(() => {
19343
20037
  if (!gaslessConfig?.enabled || !chainId) {
19344
20038
  setFeeTokens([]);
19345
20039
  setCanGasless(false);
@@ -19452,7 +20146,7 @@ function useGaslessTransfer(params) {
19452
20146
  amount,
19453
20147
  signerSupportsAuth
19454
20148
  ]);
19455
- useEffect44(() => {
20149
+ useEffect46(() => {
19456
20150
  refreshEstimate();
19457
20151
  }, [refreshEstimate]);
19458
20152
  const execute = useCallback34(
@@ -19468,6 +20162,7 @@ function useGaslessTransfer(params) {
19468
20162
  throw new Error("Unsupported chain");
19469
20163
  const attempt = executeLockRef.current.catch(() => {
19470
20164
  }).then(async () => {
20165
+ signer.assertSessionCurrent?.();
19471
20166
  if (mountedRef.current) {
19472
20167
  setIsExecuting(true);
19473
20168
  setError(null);