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