@talken/talkenkit 2.4.16 → 2.4.17

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 (233) hide show
  1. package/dist/abcWallet-54KUGWUZ.js +192 -0
  2. package/dist/abcWallet-KZHOADBJ.js +192 -0
  3. package/dist/abcWallet-NZAVB4PI.js +190 -0
  4. package/dist/chunk-5X3ROW3U.js +8777 -0
  5. package/dist/chunk-DKA3NVFM.js +8497 -0
  6. package/dist/chunk-QNZ5HSPM.js +8339 -0
  7. package/dist/chunk-VE53ZNZV.js +331 -0
  8. package/dist/components/ConfirmationModal/ApproveSection.css.d.ts +16 -0
  9. package/dist/components/ConfirmationModal/ApproveSection.d.ts +8 -0
  10. package/dist/components/ConfirmationModal/NFTPlaceholder.css.d.ts +7 -0
  11. package/dist/components/ConfirmationModal/NFTPlaceholder.d.ts +8 -0
  12. package/dist/components/ConfirmationModal/NftApprovalSection.css.d.ts +10 -0
  13. package/dist/components/ConfirmationModal/NftApprovalSection.d.ts +7 -0
  14. package/dist/components/ConfirmationModal/SignConfirmationModal.css.d.ts +35 -0
  15. package/dist/components/ConfirmationModal/SignConfirmationModal.d.ts +17 -0
  16. package/dist/components/ConfirmationModal/SwapSection.css.d.ts +17 -0
  17. package/dist/components/ConfirmationModal/SwapSection.d.ts +7 -0
  18. package/dist/components/ConfirmationModal/TransactionConfirmationModal.css.d.ts +49 -0
  19. package/dist/components/ConfirmationModal/TransactionConfirmationModal.d.ts +12 -0
  20. package/dist/components/ConfirmationModal/TransferSection.css.d.ts +17 -0
  21. package/dist/components/ConfirmationModal/TransferSection.d.ts +7 -0
  22. package/dist/components/ConfirmationModal/commonStyles.css.d.ts +37 -0
  23. package/dist/components/ConfirmationModal/constants.d.ts +16 -0
  24. package/dist/components/ConfirmationModal/index.d.ts +9 -0
  25. package/dist/components/ConfirmationModal/modalTheme.css.d.ts +20 -0
  26. package/dist/components/ConfirmationModal/transactionUIRegistry.d.ts +134 -0
  27. package/dist/components/ConfirmationModal/utils.d.ts +37 -0
  28. package/dist/components/ConnectOptions/AbcWaasAuth/AbcWaasAuthSections.css.d.ts +1 -0
  29. package/dist/components/ConnectOptions/AbcWaasAuth/AbcWaasAuthSections.d.ts +1 -1
  30. package/dist/components/ConnectOptions/AbcWaasAuth/hooks/useAbcWaasAuth.d.ts +2 -25
  31. package/dist/components/ConnectOptions/AbcWaasAuth/hooks/useAbcWaasSocial.d.ts +1 -47
  32. package/dist/components/ConnectOptions/PinAuth/hooks/useWalletGeneration.d.ts +4 -21
  33. package/dist/components/GasFeeModal/GasFeeEditModal.css.d.ts +32 -0
  34. package/dist/components/GasFeeModal/GasFeeEditModal.d.ts +21 -0
  35. package/dist/components/GasFeeModal/index.d.ts +3 -0
  36. package/dist/components/GasFeeModal/modalTheme.css.d.ts +19 -0
  37. package/dist/components/Icons/Close2.d.ts +7 -0
  38. package/dist/components/Icons/Copy2.d.ts +4 -0
  39. package/dist/components/Icons/Dropdown2.d.ts +4 -0
  40. package/dist/components/Icons/Edit.d.ts +4 -0
  41. package/dist/components/Icons/InfoCircle.d.ts +4 -0
  42. package/dist/components/Icons/Kakao.d.ts +2 -0
  43. package/dist/components/Icons/Minus.d.ts +4 -0
  44. package/dist/components/Icons/Plus.d.ts +4 -0
  45. package/dist/components/Icons/SettingsGear.d.ts +4 -0
  46. package/dist/components/Icons/SpeedHigh.d.ts +4 -0
  47. package/dist/components/Icons/SpeedLow.d.ts +4 -0
  48. package/dist/components/Icons/SpeedMedium.d.ts +4 -0
  49. package/dist/components/RainbowKitProvider/InternalPinProvider.d.ts +7 -9
  50. package/dist/components/RainbowKitProvider/RainbowKitProvider.d.ts +7 -1
  51. package/dist/components/Toast/Toast.css.d.ts +2 -0
  52. package/dist/components/Toast/Toast.d.ts +6 -0
  53. package/dist/components/Toast/index.d.ts +4 -0
  54. package/dist/components/Toast/useToast.d.ts +10 -0
  55. package/dist/config/networks.d.ts +10 -0
  56. package/dist/css/sprinkles.css.d.ts +1 -1
  57. package/dist/hooks/useSolanaWallet.d.ts +5 -23
  58. package/dist/hooks/useTronWallet.d.ts +63 -0
  59. package/dist/index.css +1903 -236
  60. package/dist/index.d.ts +8 -3
  61. package/dist/index.js +7970 -4015
  62. package/dist/klipWallet-RD5Y4UEK.js +8 -0
  63. package/dist/providers/SignConfirmationProvider/SignConfirmationProvider.d.ts +22 -0
  64. package/dist/providers/SignConfirmationProvider/index.d.ts +6 -0
  65. package/dist/providers/SignConfirmationProvider/requestParsers.d.ts +24 -0
  66. package/dist/providers/SignConfirmationProvider/types.d.ts +91 -0
  67. package/dist/providers/SignConfirmationProvider/useApiClient.d.ts +15 -0
  68. package/dist/providers/SignConfirmationProvider/useTransactionResolver.d.ts +18 -0
  69. package/dist/secure-AEBFSVWE.js +8 -0
  70. package/dist/services/AbcAgenticWalletService.d.ts +111 -0
  71. package/dist/services/AbcAuthService.d.ts +26 -20
  72. package/dist/types/index.d.ts +3 -0
  73. package/dist/types/token.d.ts +82 -0
  74. package/dist/utils/abi/abiDecoder.d.ts +144 -0
  75. package/dist/utils/apiClientFactory.d.ts +21 -0
  76. package/dist/utils/blockies.d.ts +12 -0
  77. package/dist/utils/tokenMapper.d.ts +10 -0
  78. package/dist/wallets/walletConnectors/abcWallet/abcApi.d.ts +4 -1
  79. package/dist/wallets/walletConnectors/abcWallet/abcApi.js +7 -7
  80. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinConnector.js +5 -5
  81. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinProvider.d.ts +6 -8
  82. package/dist/wallets/walletConnectors/abcWallet/abcBitcoinProvider.js +1 -1
  83. package/dist/wallets/walletConnectors/abcWallet/abcConnector.js +9 -9
  84. package/dist/wallets/walletConnectors/abcWallet/abcProvider.d.ts +17 -6
  85. package/dist/wallets/walletConnectors/abcWallet/abcProvider.js +5 -4
  86. package/dist/wallets/walletConnectors/abcWallet/abcSolanaProvider.d.ts +11 -34
  87. package/dist/wallets/walletConnectors/abcWallet/abcSolanaProvider.js +1 -1
  88. package/dist/wallets/walletConnectors/abcWallet/abcSolanaWalletAdapter.d.ts +3 -11
  89. package/dist/wallets/walletConnectors/abcWallet/abcSolanaWalletAdapter.js +17 -80
  90. package/dist/wallets/walletConnectors/abcWallet/abcTronProvider.d.ts +112 -0
  91. package/dist/wallets/walletConnectors/abcWallet/abcTronProvider.js +11 -0
  92. package/dist/wallets/walletConnectors/abcWallet/abcWallet.d.ts +2 -0
  93. package/dist/wallets/walletConnectors/abcWallet/abcWallet.js +11 -10
  94. package/dist/wallets/walletConnectors/abcWallet/api/AuthApi.d.ts +9 -11
  95. package/dist/wallets/walletConnectors/abcWallet/api/AuthApi.js +6 -6
  96. package/dist/wallets/walletConnectors/abcWallet/api/BaseApiClient.d.ts +1 -1
  97. package/dist/wallets/walletConnectors/abcWallet/api/BaseApiClient.js +5 -5
  98. package/dist/wallets/walletConnectors/abcWallet/api/BitcoinApi.js +6 -6
  99. package/dist/wallets/walletConnectors/abcWallet/api/GasApi.d.ts +45 -0
  100. package/dist/wallets/walletConnectors/abcWallet/api/GasApi.js +12 -0
  101. package/dist/wallets/walletConnectors/abcWallet/api/SigningApi.js +7 -7
  102. package/dist/wallets/walletConnectors/abcWallet/api/SolanaApi.d.ts +9 -1
  103. package/dist/wallets/walletConnectors/abcWallet/api/SolanaApi.js +7 -7
  104. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.d.ts +333 -0
  105. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiClient.js +11 -0
  106. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiSingleton.d.ts +18 -0
  107. package/dist/wallets/walletConnectors/abcWallet/api/TalkenApiSingleton.js +14 -0
  108. package/dist/wallets/walletConnectors/abcWallet/api/TransactionApi.d.ts +2 -2
  109. package/dist/wallets/walletConnectors/abcWallet/api/TransactionApi.js +7 -7
  110. package/dist/wallets/walletConnectors/abcWallet/api/TronApi.d.ts +102 -0
  111. package/dist/wallets/walletConnectors/abcWallet/api/TronApi.js +12 -0
  112. package/dist/wallets/walletConnectors/abcWallet/api/WalletApi.d.ts +4 -2
  113. package/dist/wallets/walletConnectors/abcWallet/api/WalletApi.js +7 -7
  114. package/dist/wallets/walletConnectors/abcWallet/api/WalletscanApi.d.ts +60 -0
  115. package/dist/wallets/walletConnectors/abcWallet/api/WalletscanApi.js +12 -0
  116. package/dist/wallets/walletConnectors/abcWallet/api/index.d.ts +24 -0
  117. package/dist/wallets/walletConnectors/abcWallet/api/index.js +35 -17
  118. package/dist/wallets/walletConnectors/abcWallet/constants.d.ts +39 -1
  119. package/dist/wallets/walletConnectors/abcWallet/constants.js +5 -1
  120. package/dist/wallets/walletConnectors/abcWallet/googleAuth.d.ts +6 -0
  121. package/dist/wallets/walletConnectors/abcWallet/googleAuth.js +37 -1
  122. package/dist/wallets/walletConnectors/abcWallet/index.d.ts +5 -3
  123. package/dist/wallets/walletConnectors/abcWallet/index.js +44 -31
  124. package/dist/wallets/walletConnectors/abcWallet/kakaoAuth.d.ts +27 -0
  125. package/dist/wallets/walletConnectors/abcWallet/kakaoAuth.js +290 -0
  126. package/dist/wallets/walletConnectors/abcWallet/networkConfig.d.ts +39 -3
  127. package/dist/wallets/walletConnectors/abcWallet/networkConfig.js +11 -3
  128. package/dist/wallets/walletConnectors/abcWallet/secure.js +2 -2
  129. package/dist/wallets/walletConnectors/abcWallet/sessionUtils.js +1 -1
  130. package/dist/wallets/walletConnectors/abcWallet/types.d.ts +369 -7
  131. package/dist/wallets/walletConnectors/abcWallet/types.js +5 -3
  132. package/dist/wallets/walletConnectors/abcWallet/utils.js +3 -3
  133. package/dist/wallets/walletConnectors/abcWallet/walletGeneration.d.ts +10 -19
  134. package/dist/wallets/walletConnectors/abcWallet/walletGeneration.js +2 -2
  135. package/dist/wallets/walletConnectors/berasigWallet/berasigWallet.js +2 -2
  136. package/dist/wallets/walletConnectors/bifrostWallet/bifrostWallet.js +2 -2
  137. package/dist/wallets/walletConnectors/binanceWallet/binanceWallet.js +2 -2
  138. package/dist/wallets/walletConnectors/bitgetWallet/bitgetWallet.js +2 -2
  139. package/dist/wallets/walletConnectors/bybitWallet/bybitWallet.js +2 -2
  140. package/dist/wallets/walletConnectors/chunk-25V3FW3O.js +282 -0
  141. package/dist/wallets/walletConnectors/chunk-27346T3J.js +134 -0
  142. package/dist/wallets/walletConnectors/chunk-5CNLMOB2.js +75 -0
  143. package/dist/wallets/walletConnectors/chunk-5K45TCAM.js +333 -0
  144. package/dist/wallets/walletConnectors/chunk-5VDSMZC4.js +286 -0
  145. package/dist/wallets/walletConnectors/chunk-5W7RBMPH.js +351 -0
  146. package/dist/wallets/walletConnectors/chunk-5XORKEWE.js +326 -0
  147. package/dist/wallets/walletConnectors/chunk-63WBO52A.js +77 -0
  148. package/dist/wallets/walletConnectors/chunk-7IRF225N.js +75 -0
  149. package/dist/wallets/walletConnectors/chunk-7QHCSJDN.js +726 -0
  150. package/dist/wallets/walletConnectors/chunk-A27H6PEU.js +739 -0
  151. package/dist/wallets/walletConnectors/chunk-A4WR3CFN.js +130 -0
  152. package/dist/wallets/walletConnectors/chunk-A6FUNQWF.js +572 -0
  153. package/dist/wallets/walletConnectors/chunk-AF4OCS7N.js +46 -0
  154. package/dist/wallets/walletConnectors/chunk-AFWBXEEC.js +66 -0
  155. package/dist/wallets/walletConnectors/chunk-AUGP2LJR.js +182 -0
  156. package/dist/wallets/walletConnectors/chunk-AWLDVQXC.js +317 -0
  157. package/dist/wallets/walletConnectors/chunk-BLEKTKBN.js +479 -0
  158. package/dist/wallets/walletConnectors/chunk-BVL6G5HI.js +1757 -0
  159. package/dist/wallets/walletConnectors/chunk-CMTGEHDI.js +485 -0
  160. package/dist/wallets/walletConnectors/chunk-D5EFTEOM.js +56 -0
  161. package/dist/wallets/walletConnectors/chunk-DM5NLSWD.js +346 -0
  162. package/dist/wallets/walletConnectors/chunk-EBGI4D2T.js +69 -0
  163. package/dist/wallets/walletConnectors/chunk-EEH2HMFG.js +47 -0
  164. package/dist/wallets/walletConnectors/chunk-F5JWDBKK.js +47 -0
  165. package/dist/wallets/walletConnectors/chunk-FN67MIIH.js +75 -0
  166. package/dist/wallets/walletConnectors/chunk-FWYVBX5F.js +75 -0
  167. package/dist/wallets/walletConnectors/chunk-GH6ZDY4K.js +58 -0
  168. package/dist/wallets/walletConnectors/chunk-GIJZMIBD.js +63 -0
  169. package/dist/wallets/walletConnectors/chunk-GO6OLTNF.js +479 -0
  170. package/dist/wallets/walletConnectors/chunk-HKXBK3NY.js +75 -0
  171. package/dist/wallets/walletConnectors/chunk-HMD2WWFQ.js +75 -0
  172. package/dist/wallets/walletConnectors/chunk-HO5Z2CTL.js +280 -0
  173. package/dist/wallets/walletConnectors/chunk-I3GFVK5O.js +151 -0
  174. package/dist/wallets/walletConnectors/chunk-IUHZ5ZCE.js +121 -0
  175. package/dist/wallets/walletConnectors/chunk-JODNZWWG.js +330 -0
  176. package/dist/wallets/walletConnectors/chunk-JTST3KMW.js +75 -0
  177. package/dist/wallets/walletConnectors/chunk-KH2L3ONV.js +1599 -0
  178. package/dist/wallets/walletConnectors/chunk-LHV22375.js +182 -0
  179. package/dist/wallets/walletConnectors/chunk-LZZE462U.js +315 -0
  180. package/dist/wallets/walletConnectors/chunk-MGCRUAHX.js +276 -0
  181. package/dist/wallets/walletConnectors/chunk-MURSKRMJ.js +63 -0
  182. package/dist/wallets/walletConnectors/chunk-NG7PSAPX.js +115 -0
  183. package/dist/wallets/walletConnectors/chunk-NHP6D6AH.js +204 -0
  184. package/dist/wallets/walletConnectors/chunk-O4AU63LK.js +181 -0
  185. package/dist/wallets/walletConnectors/chunk-OBS74J5N.js +221 -0
  186. package/dist/wallets/walletConnectors/chunk-ON4U54WO.js +115 -0
  187. package/dist/wallets/walletConnectors/chunk-PPYBE5TV.js +276 -0
  188. package/dist/wallets/walletConnectors/chunk-PWWSAM4G.js +309 -0
  189. package/dist/wallets/walletConnectors/chunk-QB5GDLRU.js +330 -0
  190. package/dist/wallets/walletConnectors/chunk-QMLG7MAP.js +107 -0
  191. package/dist/wallets/walletConnectors/chunk-RGIB7FFH.js +47 -0
  192. package/dist/wallets/walletConnectors/chunk-SHJBMDP4.js +278 -0
  193. package/dist/wallets/walletConnectors/chunk-SOBJYYIX.js +484 -0
  194. package/dist/wallets/walletConnectors/chunk-T66U3ADD.js +58 -0
  195. package/dist/wallets/walletConnectors/chunk-THCKLFSJ.js +75 -0
  196. package/dist/wallets/walletConnectors/chunk-TS466TDR.js +286 -0
  197. package/dist/wallets/walletConnectors/chunk-UJGFYQEV.js +459 -0
  198. package/dist/wallets/walletConnectors/chunk-UXNEBBUV.js +224 -0
  199. package/dist/wallets/walletConnectors/chunk-VRCNFVPM.js +276 -0
  200. package/dist/wallets/walletConnectors/chunk-WODNUC65.js +333 -0
  201. package/dist/wallets/walletConnectors/chunk-X6A2FSHK.js +484 -0
  202. package/dist/wallets/walletConnectors/chunk-XVRNEES5.js +1541 -0
  203. package/dist/wallets/walletConnectors/chunk-XWVM2Y5A.js +306 -0
  204. package/dist/wallets/walletConnectors/chunk-XXG7ABSJ.js +328 -0
  205. package/dist/wallets/walletConnectors/chunk-YJH4BHSB.js +254 -0
  206. package/dist/wallets/walletConnectors/chunk-YRDNIP2H.js +90 -0
  207. package/dist/wallets/walletConnectors/chunk-YTPAWPCA.js +156 -0
  208. package/dist/wallets/walletConnectors/chunk-ZCSHD7UG.js +562 -0
  209. package/dist/wallets/walletConnectors/chunk-ZZCZ3RJU.js +272 -0
  210. package/dist/wallets/walletConnectors/clvWallet/clvWallet.js +2 -2
  211. package/dist/wallets/walletConnectors/coin98Wallet/coin98Wallet.js +2 -2
  212. package/dist/wallets/walletConnectors/coreWallet/coreWallet.js +2 -2
  213. package/dist/wallets/walletConnectors/foxWallet/foxWallet.js +2 -2
  214. package/dist/wallets/walletConnectors/frontierWallet/frontierWallet.js +2 -2
  215. package/dist/wallets/walletConnectors/gateWallet/gateWallet.js +2 -2
  216. package/dist/wallets/walletConnectors/index.js +57 -56
  217. package/dist/wallets/walletConnectors/iopayWallet/iopayWallet.js +2 -2
  218. package/dist/wallets/walletConnectors/kaiaWallet/kaiaWallet.js +2 -2
  219. package/dist/wallets/walletConnectors/kaikasWallet/kaikasWallet.js +2 -2
  220. package/dist/wallets/walletConnectors/klipWallet/klipWallet.d.ts +3 -0
  221. package/dist/wallets/walletConnectors/klipWallet/klipWallet.js +8 -0
  222. package/dist/wallets/walletConnectors/klipWallet-PPTYYB5G.js +7 -0
  223. package/dist/wallets/walletConnectors/metaMaskWallet/metaMaskWallet.js +2 -2
  224. package/dist/wallets/walletConnectors/okxWallet/okxWallet.js +2 -2
  225. package/dist/wallets/walletConnectors/rainbowWallet/rainbowWallet.js +2 -2
  226. package/dist/wallets/walletConnectors/roninWallet/roninWallet.js +2 -2
  227. package/dist/wallets/walletConnectors/safepalWallet/safepalWallet.js +2 -2
  228. package/dist/wallets/walletConnectors/subWallet/subWallet.js +2 -2
  229. package/dist/wallets/walletConnectors/tokenPocketWallet/tokenPocketWallet.js +2 -2
  230. package/dist/wallets/walletConnectors/trustWallet/trustWallet.js +2 -2
  231. package/dist/wallets/walletConnectors/zealWallet/zealWallet.js +2 -2
  232. package/dist/wallets/walletConnectors/zerionWallet/zerionWallet.js +2 -2
  233. package/package.json +2 -1
@@ -0,0 +1,1757 @@
1
+ "use client";
2
+ import {
3
+ getNetworkName
4
+ } from "./chunk-4PCVQBFZ.js";
5
+ import {
6
+ secure_default
7
+ } from "./chunk-ON4U54WO.js";
8
+ import {
9
+ getSolanaNetwork
10
+ } from "./chunk-O4AU63LK.js";
11
+ import {
12
+ calculateExpiryTimestamp,
13
+ createAbcError,
14
+ isTokenExpired,
15
+ loadFromStorage,
16
+ parseApiError,
17
+ removeFromStorage,
18
+ saveToStorage
19
+ } from "./chunk-BLEKTKBN.js";
20
+ import {
21
+ ABC_AUDIENCE,
22
+ ABC_ENDPOINTS,
23
+ DEFAULT_HEADERS,
24
+ REQUEST_TIMEOUT
25
+ } from "./chunk-OBS74J5N.js";
26
+
27
+ // src/wallets/walletConnectors/abcWallet/abcApi.ts
28
+ import { parseGwei } from "viem";
29
+ import { getAddress } from "viem";
30
+ var AbcWaasClient = class {
31
+ constructor(config) {
32
+ this.accessToken = null;
33
+ this.refreshToken = null;
34
+ this.expiresAt = null;
35
+ this.isRefreshing = false;
36
+ this.refreshPromise = null;
37
+ this.config = config;
38
+ this.baseURL = config.waasUrl;
39
+ this.secure = new secure_default(this.baseURL);
40
+ this.loadTokens();
41
+ }
42
+ /**
43
+ * Load tokens from storage
44
+ */
45
+ loadTokens() {
46
+ this.accessToken = loadFromStorage("access_token" /* ACCESS_TOKEN */);
47
+ this.refreshToken = loadFromStorage("refresh_token" /* REFRESH_TOKEN */);
48
+ this.expiresAt = loadFromStorage("expires_at" /* EXPIRES_AT */);
49
+ }
50
+ /**
51
+ * Save tokens to storage
52
+ */
53
+ saveTokens(accessToken, refreshToken, expiresIn) {
54
+ this.accessToken = accessToken;
55
+ this.refreshToken = refreshToken;
56
+ this.expiresAt = calculateExpiryTimestamp(expiresIn);
57
+ saveToStorage("access_token" /* ACCESS_TOKEN */, accessToken);
58
+ saveToStorage("refresh_token" /* REFRESH_TOKEN */, refreshToken);
59
+ saveToStorage("expires_at" /* EXPIRES_AT */, this.expiresAt);
60
+ }
61
+ /**
62
+ * Clear tokens
63
+ */
64
+ clearTokens() {
65
+ this.accessToken = null;
66
+ this.refreshToken = null;
67
+ this.expiresAt = null;
68
+ removeFromStorage("access_token" /* ACCESS_TOKEN */);
69
+ removeFromStorage("refresh_token" /* REFRESH_TOKEN */);
70
+ removeFromStorage("expires_at" /* EXPIRES_AT */);
71
+ }
72
+ /**
73
+ * Check if access token is expired
74
+ */
75
+ isTokenExpired() {
76
+ return isTokenExpired(this.expiresAt);
77
+ }
78
+ /**
79
+ * Get current access token
80
+ */
81
+ getAccessToken() {
82
+ return this.accessToken;
83
+ }
84
+ /**
85
+ * Refresh access token
86
+ */
87
+ async refreshAccessToken() {
88
+ if (this.isRefreshing) {
89
+ if (this.refreshPromise) {
90
+ await this.refreshPromise;
91
+ }
92
+ return;
93
+ }
94
+ if (!this.refreshToken) {
95
+ throw createAbcError(
96
+ "TOKEN_EXPIRED" /* TOKEN_EXPIRED */,
97
+ "No refresh token available"
98
+ );
99
+ }
100
+ this.isRefreshing = true;
101
+ this.refreshPromise = (async () => {
102
+ try {
103
+ const isIframe = typeof window !== "undefined" && window.self !== window.top;
104
+ const talkenApiUrl = process.env.NEXT_PUBLIC_API_SERVER || "https://dev.walletapi.talken.io";
105
+ const response = await fetch(
106
+ `${talkenApiUrl}${ABC_ENDPOINTS.REFRESH_TOKEN}`,
107
+ {
108
+ method: "POST",
109
+ headers: DEFAULT_HEADERS,
110
+ credentials: "include",
111
+ // Important: withCredentials from reference
112
+ body: new URLSearchParams({
113
+ refresh_token: this.refreshToken || "",
114
+ // Use snake_case (reference pattern)
115
+ isIframe: String(isIframe)
116
+ }).toString()
117
+ }
118
+ );
119
+ const text = await response.text();
120
+ const data = text ? JSON.parse(text) : {};
121
+ if (response.ok && data.access_token) {
122
+ const expiresIn = data.expire_in || 3600;
123
+ this.saveTokens(
124
+ data.access_token,
125
+ data.refresh_token || this.refreshToken,
126
+ // Keep old if not provided
127
+ expiresIn
128
+ );
129
+ } else {
130
+ throw createAbcError(
131
+ "TOKEN_EXPIRED" /* TOKEN_EXPIRED */,
132
+ "Failed to refresh token"
133
+ );
134
+ }
135
+ } finally {
136
+ this.isRefreshing = false;
137
+ this.refreshPromise = null;
138
+ }
139
+ })();
140
+ await this.refreshPromise;
141
+ }
142
+ /**
143
+ * Make HTTP request
144
+ */
145
+ async request(endpoint, options = {}) {
146
+ const {
147
+ method = "GET",
148
+ body,
149
+ headers = {},
150
+ skipAuth = false,
151
+ isRetry = false
152
+ } = options;
153
+ if (!skipAuth && this.isTokenExpired() && this.refreshToken) {
154
+ await this.refreshAccessToken();
155
+ }
156
+ const url = `${this.baseURL}${endpoint}`;
157
+ const requestHeaders = {
158
+ ...DEFAULT_HEADERS,
159
+ ...headers
160
+ };
161
+ if (!skipAuth && this.accessToken) {
162
+ requestHeaders.Authorization = `Bearer ${this.accessToken}`;
163
+ }
164
+ if (this.config.apiKey) {
165
+ requestHeaders["X-API-Key"] = this.config.apiKey;
166
+ }
167
+ try {
168
+ const controller = new AbortController();
169
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT);
170
+ const requestBody = body ? new URLSearchParams(body).toString() : void 0;
171
+ const response = await fetch(url, {
172
+ method,
173
+ headers: requestHeaders,
174
+ body: requestBody,
175
+ signal: controller.signal
176
+ });
177
+ clearTimeout(timeoutId);
178
+ const text = await response.text();
179
+ let data;
180
+ if (text) {
181
+ try {
182
+ data = JSON.parse(text);
183
+ } catch (parseError) {
184
+ console.error("[AbcWaasClient] \u274C JSON parse error:", {
185
+ url,
186
+ method,
187
+ status: response.status,
188
+ responseText: text.substring(0, 200)
189
+ // Log first 200 chars
190
+ });
191
+ throw createAbcError(
192
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
193
+ "Invalid JSON response from server",
194
+ { text, parseError }
195
+ );
196
+ }
197
+ } else {
198
+ console.log("[AbcWaasClient] \u2139\uFE0F Empty response received:", {
199
+ url,
200
+ method,
201
+ status: response.status
202
+ });
203
+ data = { status: "success" };
204
+ }
205
+ if (response.status === 401 && !skipAuth && this.refreshToken && !isRetry) {
206
+ try {
207
+ await this.refreshAccessToken();
208
+ return await this.request(endpoint, {
209
+ ...options,
210
+ isRetry: true
211
+ // Prevent infinite retry loop
212
+ });
213
+ } catch (refreshError) {
214
+ console.error("Token refresh failed:", refreshError);
215
+ throw parseApiError({
216
+ response: {
217
+ status: response.status,
218
+ data
219
+ }
220
+ });
221
+ }
222
+ }
223
+ if (!response.ok) {
224
+ console.error("[AbcWaasClient] \u274C API Error:", {
225
+ url,
226
+ method,
227
+ status: response.status,
228
+ statusText: response.statusText,
229
+ data
230
+ });
231
+ throw parseApiError({
232
+ response: {
233
+ status: response.status,
234
+ data
235
+ }
236
+ });
237
+ }
238
+ return data;
239
+ } catch (error) {
240
+ console.error("[AbcWaasClient] \u274C Request failed:", {
241
+ url,
242
+ method,
243
+ error: error.message,
244
+ errorName: error.name,
245
+ errorType: error.constructor.name,
246
+ stack: error.stack
247
+ });
248
+ if (error.name === "AbortError") {
249
+ throw createAbcError(
250
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
251
+ "Request timeout",
252
+ error
253
+ );
254
+ }
255
+ if (error.code && error.message) {
256
+ throw error;
257
+ }
258
+ throw parseApiError(error);
259
+ }
260
+ }
261
+ /**
262
+ * Login with email and password
263
+ * NOTE: Tokens are stored in memory only. Call persistTokens() after PIN verification to save to localStorage.
264
+ */
265
+ async loginWithEmail(email, password) {
266
+ const response = await this.request(
267
+ ABC_ENDPOINTS.SNS_LOGIN,
268
+ {
269
+ method: "POST",
270
+ body: {
271
+ email,
272
+ token: password,
273
+ // Use password as token
274
+ service: "email",
275
+ audience: ABC_AUDIENCE
276
+ },
277
+ skipAuth: true
278
+ }
279
+ );
280
+ if (response.status === "success" && response.data) {
281
+ this.accessToken = response.data.accessToken;
282
+ this.refreshToken = response.data.refreshToken;
283
+ this.expiresAt = calculateExpiryTimestamp(response.data.expiresIn);
284
+ console.log(
285
+ "[AbcWaasClient] \u2705 Login successful, tokens stored in memory (not persisted yet)"
286
+ );
287
+ return response.data;
288
+ }
289
+ throw createAbcError(
290
+ "INVALID_CREDENTIALS" /* INVALID_CREDENTIALS */,
291
+ "Email login failed",
292
+ response
293
+ );
294
+ }
295
+ /**
296
+ * Login with email and OTP (for PIN recovery)
297
+ * NOTE: Tokens are stored in memory only. Call persistTokens() after PIN verification to save to localStorage.
298
+ */
299
+ async loginWithOtp(email, otpCode) {
300
+ const response = await this.request(
301
+ ABC_ENDPOINTS.SNS_LOGIN,
302
+ {
303
+ method: "POST",
304
+ body: {
305
+ email,
306
+ token: otpCode,
307
+ service: "email",
308
+ audience: ABC_AUDIENCE
309
+ },
310
+ skipAuth: true
311
+ }
312
+ );
313
+ if (response.status === "success" && response.data) {
314
+ this.accessToken = response.data.accessToken;
315
+ this.refreshToken = response.data.refreshToken;
316
+ this.expiresAt = calculateExpiryTimestamp(response.data.expiresIn);
317
+ console.log(
318
+ "[AbcWaasClient] \u2705 OTP login successful, tokens stored in memory (not persisted yet)"
319
+ );
320
+ return response.data;
321
+ }
322
+ throw createAbcError(
323
+ "INVALID_CREDENTIALS" /* INVALID_CREDENTIALS */,
324
+ "OTP login failed",
325
+ response
326
+ );
327
+ }
328
+ /**
329
+ * Login with social provider
330
+ * NOTE: Tokens are stored in memory only. Call persistTokens() after PIN verification to save to localStorage.
331
+ */
332
+ async loginWithSocial(provider, token, email) {
333
+ const response = await this.request(
334
+ ABC_ENDPOINTS.SNS_LOGIN,
335
+ {
336
+ method: "POST",
337
+ body: {
338
+ token,
339
+ service: provider,
340
+ audience: ABC_AUDIENCE,
341
+ email
342
+ },
343
+ skipAuth: true
344
+ }
345
+ );
346
+ if (response.status === "success" && response.data) {
347
+ this.accessToken = response.data.accessToken;
348
+ this.refreshToken = response.data.refreshToken;
349
+ this.expiresAt = calculateExpiryTimestamp(response.data.expiresIn);
350
+ console.log(
351
+ "[AbcWaasClient] \u2705 Social login successful, tokens stored in memory (not persisted yet)"
352
+ );
353
+ return response.data;
354
+ }
355
+ throw createAbcError(
356
+ "INVALID_CREDENTIALS" /* INVALID_CREDENTIALS */,
357
+ "Social login failed",
358
+ response
359
+ );
360
+ }
361
+ /**
362
+ * Refresh access token using refresh token (public wrapper)
363
+ */
364
+ async refreshTokens(refreshTokenValue) {
365
+ const oldRefreshToken = this.refreshToken;
366
+ this.refreshToken = refreshTokenValue;
367
+ try {
368
+ await this.refreshAccessToken();
369
+ return {
370
+ accessToken: this.accessToken,
371
+ refreshToken: this.refreshToken,
372
+ expiresIn: Math.floor((this.expiresAt - Date.now()) / 1e3)
373
+ };
374
+ } catch (error) {
375
+ this.refreshToken = oldRefreshToken;
376
+ throw error;
377
+ }
378
+ }
379
+ /**
380
+ * Request OTP code for email
381
+ */
382
+ async requestOtpCode(email) {
383
+ const response = await this.request(
384
+ ABC_ENDPOINTS.SEND_OTP,
385
+ {
386
+ method: "POST",
387
+ body: { email },
388
+ skipAuth: true
389
+ }
390
+ );
391
+ if (response.status === "success" && response.data) {
392
+ return response.data;
393
+ }
394
+ throw createAbcError(
395
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
396
+ "Failed to request OTP",
397
+ response
398
+ );
399
+ }
400
+ /**
401
+ * Verify OTP code
402
+ */
403
+ async verifyOtpCode(email, code) {
404
+ const response = await this.request(ABC_ENDPOINTS.VERIFY_OTP, {
405
+ method: "POST",
406
+ body: { email, code },
407
+ skipAuth: true
408
+ });
409
+ return response.status === "success";
410
+ }
411
+ /**
412
+ * Check if email already exists
413
+ * Reference: tg-wallet-frontend src/features/user/api/index.ts:63-69
414
+ */
415
+ async emailCheck(email) {
416
+ const talkenApiUrl = process.env.NEXT_PUBLIC_API_SERVER || "https://dev.walletapi.talken.io";
417
+ const url = `${talkenApiUrl}/abc/emailCheck?email=${encodeURIComponent(email)}`;
418
+ const method = "GET";
419
+ console.log("[AbcWaasClient] \u{1F4EC} Checking email");
420
+ try {
421
+ const response = await fetch(url, {
422
+ method,
423
+ headers: DEFAULT_HEADERS
424
+ });
425
+ const text = await response.text();
426
+ const data = text ? JSON.parse(text) : { status: "success" };
427
+ if (!response.ok) {
428
+ console.error("[AbcWaasClient] \u274C API Error:", {
429
+ url,
430
+ method,
431
+ status: response.status,
432
+ statusText: response.statusText,
433
+ data
434
+ });
435
+ throw parseApiError({
436
+ response: {
437
+ status: response.status,
438
+ data
439
+ }
440
+ });
441
+ }
442
+ return data;
443
+ } catch (error) {
444
+ if (error.name === "AbortError") {
445
+ throw createAbcError(
446
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
447
+ "Request timeout",
448
+ error
449
+ );
450
+ }
451
+ throw parseApiError(error);
452
+ }
453
+ }
454
+ /**
455
+ * Send OTP code to email for signup
456
+ * Reference: tg-wallet-frontend src/features/user/api/index.ts:105-110
457
+ * Note: Uses ABC WaaS endpoint, not Talken API
458
+ */
459
+ async sendOtpCode(email) {
460
+ const endpoint = `/member/mail-service/${encodeURIComponent(email)}/sendcode`;
461
+ console.log("[AbcWaasClient] \u{1F4E7} Sending OTP code");
462
+ const response = await this.request(endpoint, {
463
+ method: "GET",
464
+ skipAuth: true
465
+ });
466
+ if (response.status === "success") {
467
+ return response;
468
+ }
469
+ throw createAbcError(
470
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
471
+ "Failed to send OTP code",
472
+ response
473
+ );
474
+ }
475
+ /**
476
+ * Verify OTP code for signup
477
+ * Reference: tg-wallet-frontend src/features/user/api/index.ts:112-123
478
+ * Note: Uses ABC WaaS endpoint, not Talken API
479
+ */
480
+ async verifyOtpCodeSignup(email, code) {
481
+ const endpoint = `/member/mail-service/${encodeURIComponent(email)}/verifycode`;
482
+ const requestBody = {
483
+ email,
484
+ code,
485
+ serviceid: ABC_AUDIENCE
486
+ // 'https://mw.myabcwallet.com'
487
+ };
488
+ console.log("[AbcWaasClient] \u{1F510} Verifying OTP code");
489
+ const response = await this.request(endpoint, {
490
+ method: "POST",
491
+ body: requestBody,
492
+ skipAuth: true
493
+ });
494
+ console.log("[verifyOtpCodeSignup] Response:", response);
495
+ const isSuccess = response.status === "success" || response.status === 200 || response.message === "success";
496
+ if (isSuccess) {
497
+ return response;
498
+ }
499
+ console.error("[verifyOtpCodeSignup] Failed:", response);
500
+ throw createAbcError(
501
+ "UNKNOWN_ERROR" /* UNKNOWN_ERROR */,
502
+ "Invalid or expired OTP code",
503
+ response
504
+ );
505
+ }
506
+ /**
507
+ * SNS (Social) Login via Google/Apple/Kakao
508
+ * Reference: tg-wallet-frontend src/features/user/api/index.ts:43-51
509
+ * Note: Uses Talken API server, not ABC WaaS
510
+ */
511
+ async snsLogin(params) {
512
+ const talkenApiUrl = process.env.NEXT_PUBLIC_API_SERVER || "https://dev.walletapi.talken.io";
513
+ const url = `${talkenApiUrl}/abc/snsLogin`;
514
+ console.log("[AbcWaasClient] \u{1F510} SNS Login");
515
+ try {
516
+ const response = await fetch(url, {
517
+ method: "POST",
518
+ headers: {
519
+ ...DEFAULT_HEADERS
520
+ },
521
+ credentials: "include",
522
+ // withCredentials from reference
523
+ body: new URLSearchParams(params).toString()
524
+ });
525
+ const data = await response.json();
526
+ if (!response.ok) {
527
+ console.error("[AbcWaasClient] \u274C SNS Login failed:", {
528
+ url,
529
+ status: response.status,
530
+ statusText: response.statusText,
531
+ data
532
+ });
533
+ throw parseApiError({
534
+ response: {
535
+ status: response.status,
536
+ data
537
+ }
538
+ });
539
+ }
540
+ if (!data.access_token) {
541
+ throw createAbcError(
542
+ "INVALID_CREDENTIALS" /* INVALID_CREDENTIALS */,
543
+ "SNS login failed: Invalid response from server",
544
+ { service: params.service, response: data }
545
+ );
546
+ }
547
+ console.log("[AbcWaasClient] \u2705 SNS login successful");
548
+ return {
549
+ uid: "",
550
+ // Will be fetched later via info() API
551
+ email: params.email,
552
+ access_token: data.access_token,
553
+ refresh_token: data.refresh_token,
554
+ user_type: "existing"
555
+ // Default to existing, will be determined later
556
+ };
557
+ } catch (error) {
558
+ if (error.name === "AbortError") {
559
+ throw createAbcError(
560
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
561
+ "SNS login request timeout",
562
+ error
563
+ );
564
+ }
565
+ throw error;
566
+ }
567
+ }
568
+ /**
569
+ * Register new user
570
+ * Reference: tg-wallet-frontend src/features/user/api/index.ts:71-78
571
+ * Note: Uses Talken API server, not ABC WaaS
572
+ */
573
+ async registerUser(params) {
574
+ const talkenApiUrl = process.env.NEXT_PUBLIC_API_SERVER || "https://dev.walletapi.talken.io";
575
+ const url = `${talkenApiUrl}/abc/adduser`;
576
+ const method = "POST";
577
+ console.log("[AbcWaasClient] \u{1F4DD} Registering user");
578
+ try {
579
+ const response = await fetch(url, {
580
+ method,
581
+ headers: {
582
+ ...DEFAULT_HEADERS
583
+ },
584
+ credentials: "include",
585
+ // withCredentials from reference
586
+ body: new URLSearchParams(params).toString()
587
+ });
588
+ const text = await response.text();
589
+ const data = text ? JSON.parse(text) : { status: "success" };
590
+ if (!response.ok) {
591
+ console.error("[AbcWaasClient] \u274C API Error:", {
592
+ url,
593
+ method,
594
+ status: response.status,
595
+ statusText: response.statusText,
596
+ data
597
+ });
598
+ throw parseApiError({
599
+ response: {
600
+ status: response.status,
601
+ data
602
+ }
603
+ });
604
+ }
605
+ return data;
606
+ } catch (error) {
607
+ if (error.name === "AbortError") {
608
+ throw createAbcError(
609
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
610
+ "Request timeout",
611
+ error
612
+ );
613
+ }
614
+ throw parseApiError(error);
615
+ }
616
+ }
617
+ /**
618
+ * Register new SNS user (email-based registration with OTP)
619
+ * Reference: tg-wallet-frontend src/features/user/api/index.ts:80-87
620
+ * Note: Uses Talken API server, not ABC WaaS
621
+ */
622
+ async registerSnsUser(params) {
623
+ const talkenApiUrl = process.env.NEXT_PUBLIC_API_SERVER || "https://dev.walletapi.talken.io";
624
+ const url = `${talkenApiUrl}/abc/snsAdduser`;
625
+ const method = "POST";
626
+ console.log("[AbcWaasClient] \u{1F4DD} Registering SNS user");
627
+ try {
628
+ const response = await fetch(url, {
629
+ method,
630
+ headers: {
631
+ ...DEFAULT_HEADERS
632
+ },
633
+ credentials: "include",
634
+ // withCredentials from reference
635
+ body: new URLSearchParams(params).toString()
636
+ });
637
+ const text = await response.text();
638
+ const data = text ? JSON.parse(text) : { status: "success" };
639
+ if (!response.ok) {
640
+ console.error("[AbcWaasClient] \u274C API Error:", {
641
+ url,
642
+ method,
643
+ status: response.status,
644
+ statusText: response.statusText,
645
+ data
646
+ });
647
+ throw parseApiError({
648
+ response: {
649
+ status: response.status,
650
+ data
651
+ }
652
+ });
653
+ }
654
+ console.log("[AbcWaasClient] \u2705 SNS user registered successfully");
655
+ return data;
656
+ } catch (error) {
657
+ if (error.name === "AbortError") {
658
+ throw createAbcError(
659
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
660
+ "Request timeout",
661
+ error
662
+ );
663
+ }
664
+ throw parseApiError(error);
665
+ }
666
+ }
667
+ /**
668
+ * Reset/Set password for existing user
669
+ * Reference: tg-wallet-frontend src/features/user/api/index.ts:89-95
670
+ * Note: Uses Talken API server, not ABC WaaS
671
+ */
672
+ async resetPassword(params) {
673
+ const talkenApiUrl = process.env.NEXT_PUBLIC_API_SERVER || "https://dev.walletapi.talken.io";
674
+ const url = `${talkenApiUrl}/abc/initpassword`;
675
+ const method = "POST";
676
+ console.log("[AbcWaasClient] \u{1F510} Setting password");
677
+ try {
678
+ const response = await fetch(url, {
679
+ method,
680
+ headers: {
681
+ ...DEFAULT_HEADERS
682
+ },
683
+ credentials: "include",
684
+ body: new URLSearchParams(params).toString()
685
+ });
686
+ const text = await response.text();
687
+ const data = text ? JSON.parse(text) : { status: "success" };
688
+ if (!response.ok) {
689
+ console.error("[AbcWaasClient] \u274C API Error:", {
690
+ url,
691
+ method,
692
+ status: response.status,
693
+ statusText: response.statusText,
694
+ data
695
+ });
696
+ throw parseApiError({
697
+ response: {
698
+ status: response.status,
699
+ data
700
+ }
701
+ });
702
+ }
703
+ console.log("[AbcWaasClient] \u2705 Password set successfully");
704
+ return data;
705
+ } catch (error) {
706
+ if (error.name === "AbortError") {
707
+ throw createAbcError(
708
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
709
+ "Request timeout",
710
+ error
711
+ );
712
+ }
713
+ throw parseApiError(error);
714
+ }
715
+ }
716
+ /**
717
+ * Generate or recover wallet
718
+ */
719
+ async generateOrRecoverWallet(params) {
720
+ const response = await this.request(
721
+ // Use 'any' to get raw API response
722
+ ABC_ENDPOINTS.MPC_WALLETS,
723
+ // Use correct EVM endpoint, not WALLETS_V3 (Solana only)
724
+ {
725
+ method: "POST",
726
+ body: {
727
+ uid: params.uid,
728
+ pin: params.pin,
729
+ chainId: params.chainId,
730
+ network: params.network || "mainnet"
731
+ }
732
+ }
733
+ );
734
+ if (response.status === "success" && response.data) {
735
+ const raw = response.data;
736
+ console.log("[AbcWaasClient] Raw wallet API response:", {
737
+ hasUid: !!raw.uid,
738
+ hasSid: !!raw.sid,
739
+ hasKeyId: !!raw.key_id,
740
+ hasWid: !!raw.wid,
741
+ hasPvencstr: !!raw.pvencstr,
742
+ hasEncryptDevicePassword: !!raw.encryptDevicePassword,
743
+ hasEncryptedShare: !!raw.encrypted_share,
744
+ hasPubkey: !!raw.pubkey,
745
+ allKeys: Object.keys(raw)
746
+ });
747
+ return {
748
+ address: raw.sid || "",
749
+ // FIX: sid is the EVM address
750
+ keyId: raw.key_id || raw.keyId || raw.sid,
751
+ encryptedShare: raw.encrypted_share || raw.key_id || "",
752
+ // Use key_id as fallback
753
+ uid: raw.uid,
754
+ sid: raw.sid,
755
+ wid: raw.wid,
756
+ // Preserve for Bitcoin signing
757
+ pvencstr: raw.pvencstr,
758
+ // Preserve for Bitcoin signing
759
+ encryptDevicePassword: raw.encryptDevicePassword,
760
+ // Preserve for Bitcoin signing
761
+ pubkey: raw.pubkey || null
762
+ };
763
+ }
764
+ throw createAbcError(
765
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
766
+ "Failed to generate wallet",
767
+ response
768
+ );
769
+ }
770
+ /**
771
+ * Sign EVM transaction (EIP-1559)
772
+ * Based on ABC WaaS official documentation
773
+ */
774
+ async signTransaction(params) {
775
+ this.loadTokens();
776
+ const wallet = loadFromStorage("wallet" /* WALLET */);
777
+ if (!wallet) {
778
+ throw createAbcError(
779
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
780
+ "Wallet information not found in storage"
781
+ );
782
+ }
783
+ const encryptedDevicePassword = await this.secure.getEncryptPlain(
784
+ wallet.encryptDevicePassword
785
+ );
786
+ const encryptedPvencstr = await this.secure.getEncryptPlain(
787
+ wallet.pvencstr
788
+ );
789
+ const encryptedWid = await this.secure.getEncryptPlain(wallet.wid);
790
+ const secureChannelId = await this.secure.getSecureChannelId();
791
+ const network = getNetworkName(params.chainId);
792
+ const tx = params.transaction;
793
+ if (!tx.maxFeePerGas || !tx.maxPriorityFeePerGas || !tx.gasLimit || !tx.gas) {
794
+ try {
795
+ if (!tx.maxFeePerGas || !tx.maxPriorityFeePerGas) {
796
+ const gasFeeUrl = `${this.baseURL}${ABC_ENDPOINTS.GAS_SUGGESTED_FEES}?network=${network}`;
797
+ const gasFeeResponse = await fetch(gasFeeUrl, {
798
+ method: "GET",
799
+ headers: {
800
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
801
+ }
802
+ });
803
+ if (gasFeeResponse.ok) {
804
+ const gasData = await gasFeeResponse.json();
805
+ if (gasData.medium) {
806
+ if (!tx.maxFeePerGas) {
807
+ tx.maxFeePerGas = parseGwei(
808
+ gasData.medium.suggestedMaxFeePerGas
809
+ ).toString();
810
+ }
811
+ if (!tx.maxPriorityFeePerGas) {
812
+ tx.maxPriorityFeePerGas = parseGwei(
813
+ gasData.medium.suggestedMaxPriorityFeePerGas
814
+ ).toString();
815
+ }
816
+ }
817
+ }
818
+ }
819
+ if (!tx.gasLimit && !tx.gas) {
820
+ const estimateBody = new URLSearchParams({
821
+ network,
822
+ to: tx.to || "0x",
823
+ // Use '0x' for contract deployment
824
+ ...tx.from ? { from: tx.from } : {},
825
+ ...tx.value ? { value: tx.value } : {},
826
+ ...tx.data && tx.data !== "0x" ? { data: tx.data } : {},
827
+ ...tx.maxFeePerGas ? { maxFeePerGas: tx.maxFeePerGas } : {},
828
+ ...tx.maxPriorityFeePerGas ? { maxPriorityFeePerGas: tx.maxPriorityFeePerGas } : {}
829
+ });
830
+ const estimateUrl = `${this.baseURL}${ABC_ENDPOINTS.GAS_ESTIMATE_EIP1559}`;
831
+ const estimateResponse = await fetch(estimateUrl, {
832
+ method: "POST",
833
+ headers: {
834
+ "Content-Type": "application/x-www-form-urlencoded",
835
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
836
+ },
837
+ body: estimateBody.toString()
838
+ });
839
+ const estimateData = await estimateResponse.json();
840
+ if (estimateResponse.ok && estimateData.result) {
841
+ tx.gasLimit = estimateData.result;
842
+ } else {
843
+ const fallbackGasLimit = "0x2dc6c0";
844
+ tx.gasLimit = fallbackGasLimit;
845
+ }
846
+ }
847
+ } catch (error) {
848
+ console.warn("Failed to fetch gas parameters from ABC WaaS:", error);
849
+ }
850
+ }
851
+ const bodyData = {
852
+ network,
853
+ encryptDevicePassword: encryptedDevicePassword,
854
+ pvencstr: encryptedPvencstr,
855
+ uid: wallet.uid,
856
+ wid: encryptedWid,
857
+ sid: getAddress(wallet.address),
858
+ // EIP-55 checksum format
859
+ // For contract deployment, 'to' is '0x' (ABC WaaS convention)
860
+ // Reference: talken-nft-drops/src/libs/abc-waas-provider/index.ts:800 - to: to ?? '0x'
861
+ to: tx.to === "0x" ? "0x" : getAddress(tx.to),
862
+ // Required by ABC WaaS API
863
+ // Always use EIP1559 type (ABC WaaS handles network-specific conversion)
864
+ type: "EIP1559",
865
+ // ourpubkey and ucpubkey are required by ABC WaaS (empty strings for now)
866
+ // Based on successful tg-wallet payload analysis
867
+ ourpubkey: "",
868
+ ucpubkey: ""
869
+ };
870
+ bodyData.from = getAddress(tx.from || wallet.address);
871
+ if (tx.value) {
872
+ let hexValue = tx.value.startsWith("0x") ? tx.value.slice(2) : tx.value;
873
+ if (hexValue.length % 2 !== 0) {
874
+ hexValue = `0${hexValue}`;
875
+ }
876
+ bodyData.value = `0x${hexValue}`;
877
+ } else {
878
+ bodyData.value = "0x0";
879
+ }
880
+ if (tx.gasLimit || tx.gas) {
881
+ const gasLimitValue = tx.gasLimit || tx.gas;
882
+ if (gasLimitValue.toString().startsWith("0x")) {
883
+ bodyData.gasLimit = gasLimitValue.toString();
884
+ } else {
885
+ bodyData.gasLimit = `0x${BigInt(gasLimitValue).toString(16)}`;
886
+ }
887
+ }
888
+ if (tx.maxFeePerGas) {
889
+ if (tx.maxFeePerGas.toString().startsWith("0x")) {
890
+ bodyData.maxFeePerGas = tx.maxFeePerGas.toString();
891
+ } else {
892
+ bodyData.maxFeePerGas = `0x${BigInt(tx.maxFeePerGas).toString(16)}`;
893
+ }
894
+ }
895
+ if (tx.maxPriorityFeePerGas) {
896
+ if (tx.maxPriorityFeePerGas.toString().startsWith("0x")) {
897
+ bodyData.maxPriorityFeePerGas = tx.maxPriorityFeePerGas.toString();
898
+ } else {
899
+ bodyData.maxPriorityFeePerGas = `0x${BigInt(tx.maxPriorityFeePerGas).toString(16)}`;
900
+ }
901
+ }
902
+ if (tx.gasPrice) {
903
+ if (tx.gasPrice.toString().startsWith("0x")) {
904
+ bodyData.gasPrice = tx.gasPrice.toString();
905
+ } else {
906
+ bodyData.gasPrice = `0x${BigInt(tx.gasPrice).toString(16)}`;
907
+ }
908
+ }
909
+ if (tx.data !== void 0 && tx.data !== null) {
910
+ bodyData.data = tx.data || "0x";
911
+ } else {
912
+ bodyData.data = "0x";
913
+ }
914
+ const bodyString = new URLSearchParams(bodyData).toString();
915
+ const url = `${this.baseURL}${ABC_ENDPOINTS.SIGN_TRANSACTION}`;
916
+ const response = await fetch(url, {
917
+ method: "POST",
918
+ headers: {
919
+ "Content-Type": "application/x-www-form-urlencoded",
920
+ "Secure-Channel": secureChannelId,
921
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
922
+ },
923
+ body: bodyString
924
+ });
925
+ const res = await response.json();
926
+ console.log("\u{1F4E1} ABC WaaS /sign response:", {
927
+ status: response.status,
928
+ ok: response.ok,
929
+ response: res
930
+ });
931
+ if (!response.ok) {
932
+ console.error("\u274C ABC WaaS API error details:", {
933
+ status: response.status,
934
+ statusText: response.statusText,
935
+ errorCode: res.code,
936
+ errorMessage: res.msg || res.message || res.detail,
937
+ fullResponse: res
938
+ });
939
+ }
940
+ if (response.status === 401 && this.refreshToken) {
941
+ try {
942
+ await this.refreshAccessToken();
943
+ const retryResponse = await fetch(url, {
944
+ method: "POST",
945
+ headers: {
946
+ "Content-Type": "application/x-www-form-urlencoded",
947
+ "Secure-Channel": secureChannelId,
948
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
949
+ },
950
+ body: bodyString
951
+ });
952
+ const retryRes = await retryResponse.json();
953
+ if (retryRes.serializedTx && retryRes.rawTx) {
954
+ return {
955
+ signature: retryRes.serializedTx,
956
+ txHash: retryRes.rawTx
957
+ };
958
+ }
959
+ throw createAbcError(
960
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
961
+ "Failed to sign transaction after token refresh",
962
+ retryRes
963
+ );
964
+ } catch (refreshError) {
965
+ console.error("Token refresh failed in signTransaction:", refreshError);
966
+ throw refreshError;
967
+ }
968
+ }
969
+ if (res.serializedTx && res.rawTx) {
970
+ return {
971
+ signature: res.serializedTx,
972
+ txHash: res.rawTx
973
+ };
974
+ }
975
+ throw createAbcError(
976
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
977
+ "Failed to sign transaction",
978
+ res
979
+ );
980
+ }
981
+ /**
982
+ * Sign message (Personal Sign - EIP-191)
983
+ * Based on tg-wallet-frontend reference implementation
984
+ */
985
+ async signMessage(params) {
986
+ this.loadTokens();
987
+ const wallet = loadFromStorage("wallet" /* WALLET */);
988
+ if (!wallet) {
989
+ throw createAbcError(
990
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
991
+ "Wallet information not found in storage"
992
+ );
993
+ }
994
+ const ethers = await import("ethers");
995
+ const messageHash = ethers.utils.hashMessage(params.message);
996
+ const hash = messageHash.startsWith("0x") ? messageHash.slice(2) : messageHash;
997
+ const encryptedDevicePassword = await this.secure.getEncryptPlain(
998
+ wallet.encryptDevicePassword
999
+ );
1000
+ const encryptedPvencstr = await this.secure.getEncryptPlain(
1001
+ wallet.pvencstr
1002
+ );
1003
+ const encryptedWid = await this.secure.getEncryptPlain(wallet.wid);
1004
+ const secureChannelId = await this.secure.getSecureChannelId();
1005
+ const bodyData = {
1006
+ hash,
1007
+ encryptDevicePassword: encryptedDevicePassword,
1008
+ pvencstr: encryptedPvencstr,
1009
+ wid: encryptedWid,
1010
+ uid: wallet.uid,
1011
+ sid: wallet.sid
1012
+ };
1013
+ const bodyString = new URLSearchParams(bodyData).toString();
1014
+ const url = `${this.baseURL}${ABC_ENDPOINTS.SIGN_HASH}`;
1015
+ const response = await fetch(url, {
1016
+ method: "POST",
1017
+ headers: {
1018
+ "Content-Type": "application/x-www-form-urlencoded",
1019
+ "Secure-Channel": secureChannelId,
1020
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1021
+ },
1022
+ body: bodyString
1023
+ });
1024
+ const text = await response.text();
1025
+ if (!text) {
1026
+ throw createAbcError(
1027
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1028
+ `Empty response from sign API (status: ${response.status})`,
1029
+ { status: response.status }
1030
+ );
1031
+ }
1032
+ const res = JSON.parse(text);
1033
+ if (response.status === 401) {
1034
+ if (!this.refreshToken) {
1035
+ this.loadTokens();
1036
+ }
1037
+ if (this.refreshToken) {
1038
+ try {
1039
+ await this.refreshAccessToken();
1040
+ const retryResponse = await fetch(url, {
1041
+ method: "POST",
1042
+ headers: {
1043
+ "Content-Type": "application/x-www-form-urlencoded",
1044
+ "Secure-Channel": secureChannelId,
1045
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1046
+ },
1047
+ body: bodyString
1048
+ });
1049
+ const retryText = await retryResponse.text();
1050
+ if (!retryText) {
1051
+ throw createAbcError(
1052
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1053
+ `Empty response from retry (status: ${retryResponse.status})`,
1054
+ { status: retryResponse.status }
1055
+ );
1056
+ }
1057
+ const retryRes = JSON.parse(retryText);
1058
+ if (retryRes.status === "success" && retryRes.result?.signstr) {
1059
+ return { signature: retryRes.result.signstr };
1060
+ }
1061
+ throw createAbcError(
1062
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1063
+ "Failed to sign message after token refresh",
1064
+ retryRes
1065
+ );
1066
+ } catch (refreshError) {
1067
+ console.error("Token refresh failed in signMessage:", refreshError);
1068
+ throw refreshError;
1069
+ }
1070
+ }
1071
+ }
1072
+ if (res.signstr) {
1073
+ const signData = JSON.parse(res.signstr);
1074
+ const sigList = signData.sig_list?.[0];
1075
+ if (!sigList || !sigList.r || !sigList.s) {
1076
+ throw createAbcError(
1077
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1078
+ "Invalid signature format",
1079
+ res
1080
+ );
1081
+ }
1082
+ const v = (sigList.vsource || 0) + 27;
1083
+ const signature = sigList.r + sigList.s.slice(2) + v.toString(16).padStart(2, "0");
1084
+ return { signature };
1085
+ }
1086
+ throw createAbcError(
1087
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1088
+ "Failed to sign message",
1089
+ res
1090
+ );
1091
+ }
1092
+ /**
1093
+ * Sign typed data (EIP-712)
1094
+ * Reference: tg-wallet-frontend src/features/wallet/api/index.ts sign_typed_data()
1095
+ */
1096
+ async signTypedData(params) {
1097
+ this.loadTokens();
1098
+ const wallet = loadFromStorage("wallet" /* WALLET */);
1099
+ if (!wallet) {
1100
+ throw createAbcError(
1101
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1102
+ "Wallet information not found in storage"
1103
+ );
1104
+ }
1105
+ const encryptedDevicePassword = await this.secure.getEncryptPlain(
1106
+ wallet.encryptDevicePassword
1107
+ );
1108
+ const encryptedPvencstr = await this.secure.getEncryptPlain(
1109
+ wallet.pvencstr
1110
+ );
1111
+ const encryptedWid = await this.secure.getEncryptPlain(wallet.wid);
1112
+ const secureChannelId = await this.secure.getSecureChannelId();
1113
+ const network = getNetworkName(wallet.chainId);
1114
+ const bodyData = {
1115
+ messageJson: params.typedData,
1116
+ // Server expects "messageJson" field
1117
+ version: "v4",
1118
+ // EIP-712 version
1119
+ network,
1120
+ // Network name (required for JSON-RPC)
1121
+ encryptDevicePassword: encryptedDevicePassword,
1122
+ pvencstr: encryptedPvencstr,
1123
+ wid: encryptedWid,
1124
+ uid: wallet.uid,
1125
+ sid: wallet.sid
1126
+ };
1127
+ const bodyString = new URLSearchParams(bodyData).toString();
1128
+ const url = `${this.baseURL}${ABC_ENDPOINTS.SIGN_TYPED}`;
1129
+ const response = await fetch(url, {
1130
+ method: "POST",
1131
+ headers: {
1132
+ "Content-Type": "application/x-www-form-urlencoded",
1133
+ "Secure-Channel": secureChannelId,
1134
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1135
+ },
1136
+ body: bodyString
1137
+ });
1138
+ const text = await response.text();
1139
+ if (!text) {
1140
+ throw createAbcError(
1141
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1142
+ `Empty response from signTypedData API (status: ${response.status})`,
1143
+ { status: response.status }
1144
+ );
1145
+ }
1146
+ const res = JSON.parse(text);
1147
+ if (response.status === 401 && this.refreshToken) {
1148
+ try {
1149
+ await this.refreshAccessToken();
1150
+ const retryResponse = await fetch(url, {
1151
+ method: "POST",
1152
+ headers: {
1153
+ "Content-Type": "application/x-www-form-urlencoded",
1154
+ "Secure-Channel": secureChannelId,
1155
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1156
+ },
1157
+ body: bodyString
1158
+ });
1159
+ const retryText = await retryResponse.text();
1160
+ if (!retryText) {
1161
+ throw createAbcError(
1162
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1163
+ `Empty response after retry (status: ${retryResponse.status})`,
1164
+ { status: retryResponse.status }
1165
+ );
1166
+ }
1167
+ const retryRes = JSON.parse(retryText);
1168
+ if (retryRes.serializedTx) {
1169
+ return { signature: retryRes.serializedTx };
1170
+ }
1171
+ throw createAbcError(
1172
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1173
+ "Failed to sign typed data after token refresh",
1174
+ retryRes
1175
+ );
1176
+ } catch (refreshError) {
1177
+ console.error("Token refresh failed in signTypedData:", refreshError);
1178
+ throw refreshError;
1179
+ }
1180
+ }
1181
+ if (res.serializedTx) {
1182
+ return { signature: res.serializedTx };
1183
+ }
1184
+ throw createAbcError(
1185
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1186
+ "Failed to sign typed data",
1187
+ res
1188
+ );
1189
+ }
1190
+ /**
1191
+ * Send raw transaction
1192
+ * Reference: tg-wallet-frontend src/features/wallet/api/index.ts sendRawTx()
1193
+ */
1194
+ async sendRawTransaction(chainId, signedTransaction) {
1195
+ const wallet = loadFromStorage("wallet" /* WALLET */);
1196
+ if (!wallet) {
1197
+ throw createAbcError(
1198
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1199
+ "Wallet information not found in storage"
1200
+ );
1201
+ }
1202
+ const network = getNetworkName(chainId);
1203
+ const secureChannelId = await this.secure.getSecureChannelId();
1204
+ const bodyData = {
1205
+ signedSerializeTx: signedTransaction,
1206
+ network
1207
+ // rpc parameter
1208
+ };
1209
+ const bodyString = new URLSearchParams(bodyData).toString();
1210
+ const url = `${this.baseURL}${ABC_ENDPOINTS.SEND_RAW_TX}`;
1211
+ const response = await fetch(url, {
1212
+ method: "POST",
1213
+ headers: {
1214
+ "Content-Type": "application/x-www-form-urlencoded",
1215
+ "Secure-Channel": secureChannelId,
1216
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1217
+ },
1218
+ body: bodyString
1219
+ });
1220
+ const text = await response.text();
1221
+ if (!text) {
1222
+ throw createAbcError(
1223
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1224
+ `Empty response from sendRawTx API (status: ${response.status})`,
1225
+ { status: response.status }
1226
+ );
1227
+ }
1228
+ const res = JSON.parse(text);
1229
+ console.log("\u{1F4E1} sendRawTransaction response:", {
1230
+ status: response.status,
1231
+ ok: response.ok,
1232
+ response: res
1233
+ });
1234
+ if (!response.ok) {
1235
+ console.error("\u274C sendRawTransaction error:", {
1236
+ status: response.status,
1237
+ errorMessage: res.errorMessage || res.msg || res.message,
1238
+ fullResponse: res
1239
+ });
1240
+ }
1241
+ if (response.status === 401 && this.refreshToken) {
1242
+ try {
1243
+ await this.refreshAccessToken();
1244
+ const retryResponse = await fetch(url, {
1245
+ method: "POST",
1246
+ headers: {
1247
+ "Content-Type": "application/x-www-form-urlencoded",
1248
+ "Secure-Channel": secureChannelId,
1249
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1250
+ },
1251
+ body: bodyString
1252
+ });
1253
+ const retryText = await retryResponse.text();
1254
+ if (!retryText) {
1255
+ throw createAbcError(
1256
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1257
+ `Empty response after retry (status: ${retryResponse.status})`,
1258
+ { status: retryResponse.status }
1259
+ );
1260
+ }
1261
+ const retryRes = JSON.parse(retryText);
1262
+ if (retryRes.item || retryRes.txHash || retryRes.result?.txHash) {
1263
+ const txHash = retryRes.item || retryRes.txHash || retryRes.result.txHash;
1264
+ return { txHash };
1265
+ }
1266
+ throw createAbcError(
1267
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1268
+ "Failed to send transaction after token refresh",
1269
+ retryRes
1270
+ );
1271
+ } catch (refreshError) {
1272
+ console.error(
1273
+ "Token refresh failed in sendRawTransaction:",
1274
+ refreshError
1275
+ );
1276
+ throw refreshError;
1277
+ }
1278
+ }
1279
+ if (res.result) {
1280
+ if (typeof res.result === "string") {
1281
+ console.log("\u2705 Transaction hash from result:", res.result);
1282
+ return { txHash: res.result };
1283
+ }
1284
+ if (res.result.txHash) {
1285
+ return { txHash: res.result.txHash };
1286
+ }
1287
+ }
1288
+ if (res.item) {
1289
+ return { txHash: res.item };
1290
+ }
1291
+ if (res.txHash) {
1292
+ return { txHash: res.txHash };
1293
+ }
1294
+ throw createAbcError(
1295
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1296
+ "Failed to send transaction",
1297
+ res
1298
+ );
1299
+ }
1300
+ /**
1301
+ * Estimate gas for EIP-1559 transaction
1302
+ * Reference: ABC WaaS API docs - /wapi/v2/gas/estimate/eip1559
1303
+ */
1304
+ async estimateGas(params) {
1305
+ const network = getNetworkName(params.chainId);
1306
+ const secureChannelId = await this.secure.getSecureChannelId();
1307
+ const bodyData = {
1308
+ network,
1309
+ to: params.to
1310
+ };
1311
+ if (params.from)
1312
+ bodyData.from = params.from;
1313
+ if (params.value)
1314
+ bodyData.value = params.value;
1315
+ if (params.data)
1316
+ bodyData.data = params.data;
1317
+ const bodyString = new URLSearchParams(bodyData).toString();
1318
+ const url = `${this.baseURL}${ABC_ENDPOINTS.GAS_ESTIMATE_EIP1559}`;
1319
+ const response = await fetch(url, {
1320
+ method: "POST",
1321
+ headers: {
1322
+ "Content-Type": "application/x-www-form-urlencoded",
1323
+ "Secure-Channel": secureChannelId,
1324
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1325
+ },
1326
+ body: bodyString
1327
+ });
1328
+ const text = await response.text();
1329
+ if (!text) {
1330
+ throw createAbcError(
1331
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1332
+ `Empty response from gas estimation API (status: ${response.status})`,
1333
+ { status: response.status }
1334
+ );
1335
+ }
1336
+ const res = JSON.parse(text);
1337
+ console.log("\u{1F4E1} estimateGas response:", {
1338
+ status: response.status,
1339
+ ok: response.ok,
1340
+ network,
1341
+ params,
1342
+ response: res
1343
+ });
1344
+ if (response.status === 401 && this.refreshToken) {
1345
+ try {
1346
+ await this.refreshAccessToken();
1347
+ const retryResponse = await fetch(url, {
1348
+ method: "POST",
1349
+ headers: {
1350
+ "Content-Type": "application/x-www-form-urlencoded",
1351
+ "Secure-Channel": secureChannelId,
1352
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1353
+ },
1354
+ body: bodyString
1355
+ });
1356
+ const retryText = await retryResponse.text();
1357
+ if (!retryText) {
1358
+ throw createAbcError(
1359
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1360
+ `Empty response after retry (status: ${retryResponse.status})`,
1361
+ { status: retryResponse.status }
1362
+ );
1363
+ }
1364
+ const retryRes = JSON.parse(retryText);
1365
+ if (retryRes.result) {
1366
+ return retryRes.result;
1367
+ }
1368
+ throw createAbcError(
1369
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1370
+ "Failed to estimate gas after token refresh",
1371
+ retryRes
1372
+ );
1373
+ } catch (refreshError) {
1374
+ console.error("Token refresh failed in estimateGas:", refreshError);
1375
+ throw refreshError;
1376
+ }
1377
+ }
1378
+ if (res.result) {
1379
+ return res.result;
1380
+ }
1381
+ console.error("\u274C estimateGas failed:", {
1382
+ status: response.status,
1383
+ network,
1384
+ errorMessage: res.errorMessage || res.msg || res.message,
1385
+ fullResponse: res
1386
+ });
1387
+ throw createAbcError(
1388
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1389
+ res.errorMessage || res.msg || "Failed to estimate gas",
1390
+ res
1391
+ );
1392
+ }
1393
+ /**
1394
+ * Get transaction count (nonce)
1395
+ * Reference: ABC WaaS API - /wapi/v2/transactions/count
1396
+ */
1397
+ async getTransactionCount(params) {
1398
+ const network = getNetworkName(params.chainId);
1399
+ const secureChannelId = await this.secure.getSecureChannelId();
1400
+ const bodyData = {
1401
+ network,
1402
+ address: params.address
1403
+ };
1404
+ const bodyString = new URLSearchParams(bodyData).toString();
1405
+ const url = `${this.baseURL}${ABC_ENDPOINTS.TRANSACTION_COUNT}`;
1406
+ const response = await fetch(url, {
1407
+ method: "POST",
1408
+ headers: {
1409
+ "Content-Type": "application/x-www-form-urlencoded",
1410
+ "Secure-Channel": secureChannelId,
1411
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1412
+ },
1413
+ body: bodyString
1414
+ });
1415
+ const text = await response.text();
1416
+ if (!text) {
1417
+ throw createAbcError(
1418
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1419
+ `Empty response from transaction count API (status: ${response.status})`,
1420
+ { status: response.status }
1421
+ );
1422
+ }
1423
+ const res = JSON.parse(text);
1424
+ if (response.status === 401 && this.refreshToken) {
1425
+ try {
1426
+ await this.refreshAccessToken();
1427
+ const retryResponse = await fetch(url, {
1428
+ method: "POST",
1429
+ headers: {
1430
+ "Content-Type": "application/x-www-form-urlencoded",
1431
+ "Secure-Channel": secureChannelId,
1432
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1433
+ },
1434
+ body: bodyString
1435
+ });
1436
+ const retryText = await retryResponse.text();
1437
+ if (!retryText) {
1438
+ throw createAbcError(
1439
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1440
+ `Empty response after retry (status: ${retryResponse.status})`,
1441
+ { status: retryResponse.status }
1442
+ );
1443
+ }
1444
+ const retryRes = JSON.parse(retryText);
1445
+ if (retryRes.result !== void 0) {
1446
+ return typeof retryRes.result === "number" ? `0x${retryRes.result.toString(16)}` : retryRes.result;
1447
+ }
1448
+ throw createAbcError(
1449
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1450
+ "Failed to get transaction count after token refresh",
1451
+ retryRes
1452
+ );
1453
+ } catch (refreshError) {
1454
+ console.error(
1455
+ "Token refresh failed in getTransactionCount:",
1456
+ refreshError
1457
+ );
1458
+ throw refreshError;
1459
+ }
1460
+ }
1461
+ if (res.result !== void 0) {
1462
+ return typeof res.result === "number" ? `0x${res.result.toString(16)}` : res.result;
1463
+ }
1464
+ throw createAbcError(
1465
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1466
+ res.errorMessage || res.msg || "Failed to get transaction count",
1467
+ res
1468
+ );
1469
+ }
1470
+ /**
1471
+ * Get wallet info
1472
+ */
1473
+ async getWalletInfo(uid) {
1474
+ const response = await this.request(ABC_ENDPOINTS.INFO, {
1475
+ method: "POST",
1476
+ body: { uid }
1477
+ });
1478
+ if (response.status === "success") {
1479
+ return response.data;
1480
+ }
1481
+ throw createAbcError(
1482
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1483
+ "Failed to get wallet info",
1484
+ response
1485
+ );
1486
+ }
1487
+ /**
1488
+ * Logout (clear tokens)
1489
+ */
1490
+ async logout() {
1491
+ this.clearTokens();
1492
+ }
1493
+ /**
1494
+ * Check if user is authenticated
1495
+ */
1496
+ isAuthenticated() {
1497
+ return !!this.accessToken && !this.isTokenExpired();
1498
+ }
1499
+ /**
1500
+ * Set tokens in client instance (useful when restoring from storage or state)
1501
+ * Call this before persistTokens() if you need to set tokens from external source
1502
+ */
1503
+ setTokens(accessToken, refreshToken, expiresAt) {
1504
+ this.accessToken = accessToken;
1505
+ this.refreshToken = refreshToken;
1506
+ this.expiresAt = expiresAt;
1507
+ }
1508
+ /**
1509
+ * Persist tokens to localStorage
1510
+ * Call this after PIN verification is complete
1511
+ *
1512
+ * SECURITY NOTE: This should only be called after full authentication (password + PIN)
1513
+ * to ensure tokens are only persisted after the user has proven ownership of both credentials.
1514
+ */
1515
+ persistTokens() {
1516
+ if (!this.accessToken || !this.refreshToken || !this.expiresAt) {
1517
+ console.warn(
1518
+ "[AbcWaasClient] \u26A0\uFE0F No tokens to persist - ensure login was successful first"
1519
+ );
1520
+ return;
1521
+ }
1522
+ console.log(
1523
+ "[AbcWaasClient] \u{1F4BE} Persisting tokens to localStorage after PIN verification"
1524
+ );
1525
+ saveToStorage("access_token" /* ACCESS_TOKEN */, this.accessToken);
1526
+ saveToStorage("refresh_token" /* REFRESH_TOKEN */, this.refreshToken);
1527
+ saveToStorage("expires_at" /* EXPIRES_AT */, this.expiresAt);
1528
+ }
1529
+ // ==========================================================================
1530
+ // Solana Methods
1531
+ // ==========================================================================
1532
+ /**
1533
+ * Generate or recover Solana wallet (Ed25519)
1534
+ * Reference: SigningService.ts:56-72, wallet/api/index.ts:56-72
1535
+ */
1536
+ async generateSolanaWallet(pin, isRecover = false) {
1537
+ const url = `${this.baseURL}/v3/wallet/${isRecover ? "recover" : "generate"}`;
1538
+ const response = await fetch(url, {
1539
+ method: "POST",
1540
+ headers: {
1541
+ "Content-Type": "application/json",
1542
+ // V3 API requires JSON, not form-urlencoded
1543
+ Accept: "application/json",
1544
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1545
+ },
1546
+ body: JSON.stringify({
1547
+ curve: "ed25519",
1548
+ password: pin
1549
+ // PIN will be encrypted by Secure Channel
1550
+ // Note: network parameter not needed for v3 API
1551
+ })
1552
+ });
1553
+ let data;
1554
+ try {
1555
+ data = await response.json();
1556
+ } catch (e) {
1557
+ console.error(`[AbcWaasClient] Failed to parse response from ${url}:`, e);
1558
+ throw createAbcError(
1559
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1560
+ `Failed to ${isRecover ? "recover" : "generate"} Solana wallet - invalid response`,
1561
+ { status: response.status }
1562
+ );
1563
+ }
1564
+ if (!response.ok) {
1565
+ if (!isRecover && response.status === 409) {
1566
+ const error = createAbcError(
1567
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1568
+ "Wallet already exists",
1569
+ data
1570
+ );
1571
+ error.response = { status: 409 };
1572
+ throw error;
1573
+ }
1574
+ console.error(
1575
+ `[AbcWaasClient] ${isRecover ? "Recover" : "Generate"} failed:`,
1576
+ data
1577
+ );
1578
+ throw createAbcError(
1579
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1580
+ `Failed to ${isRecover ? "recover" : "generate"} Solana wallet`,
1581
+ data
1582
+ );
1583
+ }
1584
+ const result = data.result || data;
1585
+ if (!result.key_id || !result.public_key || !result.encrypted_share) {
1586
+ console.error(
1587
+ "[AbcWaasClient] Invalid wallet response, missing required fields:",
1588
+ result
1589
+ );
1590
+ throw createAbcError(
1591
+ "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1592
+ `Invalid wallet response from ${isRecover ? "recover" : "generate"}`,
1593
+ data
1594
+ );
1595
+ }
1596
+ const solanaNetwork = getSolanaNetwork();
1597
+ const addressResult = await this.getSolanaAddress(
1598
+ result.public_key,
1599
+ solanaNetwork
1600
+ );
1601
+ return {
1602
+ uid: result.uid || "",
1603
+ sessionId: result.share_id || result.key_id,
1604
+ shareId: result.share_id || result.key_id,
1605
+ publicKey: result.public_key,
1606
+ address: addressResult,
1607
+ keyId: result.key_id,
1608
+ encryptedShare: result.encrypted_share || "",
1609
+ secretStore: result.secret_store || "",
1610
+ network: solanaNetwork
1611
+ };
1612
+ }
1613
+ /**
1614
+ * Get Solana address from Ed25519 public key
1615
+ * Reference: wallet/api/index.ts:74-82
1616
+ */
1617
+ async getSolanaAddress(publicKey, network) {
1618
+ const url = `${this.baseURL}/wapi/v2/solana/wallet/getAddress`;
1619
+ const body = new URLSearchParams({
1620
+ network,
1621
+ publicKey
1622
+ }).toString();
1623
+ const response = await fetch(url, {
1624
+ method: "POST",
1625
+ headers: {
1626
+ ...DEFAULT_HEADERS,
1627
+ // Contains 'Content-Type': 'application/x-www-form-urlencoded'
1628
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1629
+ },
1630
+ body
1631
+ });
1632
+ const data = await response.json();
1633
+ if (!response.ok || data.status !== "success") {
1634
+ throw createAbcError(
1635
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1636
+ "Failed to get Solana address",
1637
+ data
1638
+ );
1639
+ }
1640
+ return data.result?.data?.address;
1641
+ }
1642
+ /**
1643
+ * Sign Solana transaction with Ed25519
1644
+ * Reference: SigningService.ts:587-626, wallet/api/index.ts:114-122
1645
+ */
1646
+ async signSolanaTransaction(params) {
1647
+ const url = `${this.baseURL}/v3/wallet/sign`;
1648
+ const response = await fetch(url, {
1649
+ method: "POST",
1650
+ headers: {
1651
+ "Content-Type": "application/json",
1652
+ Accept: "application/json",
1653
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1654
+ },
1655
+ body: JSON.stringify({
1656
+ uid: params.uid,
1657
+ share_id: params.shareId,
1658
+ key_id: params.keyId,
1659
+ encrypted_share: params.encryptedShare,
1660
+ public_key: params.publicKey,
1661
+ message: params.message,
1662
+ // Hex-encoded transaction
1663
+ password: params.pin,
1664
+ // PIN will be encrypted
1665
+ network: params.network
1666
+ // Required: 'solana' or 'solana_devnet'
1667
+ })
1668
+ });
1669
+ const data = await response.json();
1670
+ if (!response.ok || data.status !== "success") {
1671
+ throw createAbcError(
1672
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1673
+ "Failed to sign Solana transaction",
1674
+ data
1675
+ );
1676
+ }
1677
+ return {
1678
+ signature: data.result?.signature
1679
+ };
1680
+ }
1681
+ /**
1682
+ * Sign Solana message with Ed25519
1683
+ * Reference: SigningService.ts:546-579
1684
+ */
1685
+ async signSolanaMessage(params) {
1686
+ const url = `${this.baseURL}/v3/wallet/sign`;
1687
+ const response = await fetch(url, {
1688
+ method: "POST",
1689
+ headers: {
1690
+ "Content-Type": "application/json",
1691
+ Accept: "application/json",
1692
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1693
+ },
1694
+ body: JSON.stringify({
1695
+ uid: params.uid,
1696
+ share_id: params.shareId,
1697
+ key_id: params.keyId,
1698
+ encrypted_share: params.encryptedShare,
1699
+ public_key: params.publicKey,
1700
+ message: params.message,
1701
+ // Hex-encoded message
1702
+ password: params.pin,
1703
+ network: params.network
1704
+ // Required: 'solana' or 'solana_devnet'
1705
+ })
1706
+ });
1707
+ const data = await response.json();
1708
+ if (!response.ok || data.status !== "success") {
1709
+ throw createAbcError(
1710
+ "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1711
+ "Failed to sign Solana message",
1712
+ data
1713
+ );
1714
+ }
1715
+ return {
1716
+ signature: data.result?.signature
1717
+ };
1718
+ }
1719
+ /**
1720
+ * Send Solana transaction
1721
+ * Reference: SigningService.ts:418, wallet/api/index.ts:124-132
1722
+ */
1723
+ async sendSolanaTransaction(params) {
1724
+ const url = `${this.baseURL}/wapi/v2/solana/tx/sendTransaction`;
1725
+ const response = await fetch(url, {
1726
+ method: "POST",
1727
+ headers: {
1728
+ ...DEFAULT_HEADERS,
1729
+ ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1730
+ },
1731
+ body: JSON.stringify({
1732
+ network: params.network,
1733
+ serializedTX: params.serializedTX,
1734
+ signatures: params.signatures
1735
+ })
1736
+ });
1737
+ const data = await response.json();
1738
+ if (!response.ok || data.status !== "success") {
1739
+ throw createAbcError(
1740
+ "NETWORK_ERROR" /* NETWORK_ERROR */,
1741
+ "Failed to send Solana transaction",
1742
+ data
1743
+ );
1744
+ }
1745
+ return {
1746
+ txHash: data.result?.data
1747
+ };
1748
+ }
1749
+ };
1750
+ function createAbcWaasClient(config) {
1751
+ return new AbcWaasClient(config);
1752
+ }
1753
+
1754
+ export {
1755
+ AbcWaasClient,
1756
+ createAbcWaasClient
1757
+ };