@talken/talkenkit 2.3.5 → 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 (110) 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 +1445 -899
  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/abcApi.js +1 -1
  33. package/dist/wallets/walletConnectors/abcWallet/abcConnector.js +2 -2
  34. package/dist/wallets/walletConnectors/abcWallet/abcSolanaWallet.js +2 -2
  35. package/dist/wallets/walletConnectors/abcWallet/abcWallet.js +3 -3
  36. package/dist/wallets/walletConnectors/abcWallet/index.js +4 -4
  37. package/dist/wallets/walletConnectors/chunk-3SVPZCA6.js +71 -0
  38. package/dist/wallets/walletConnectors/chunk-5QEUEPNY.js +94 -0
  39. package/dist/wallets/walletConnectors/chunk-B6JLYR3I.js +66 -0
  40. package/dist/wallets/walletConnectors/{chunk-6JKWIEGA.js → chunk-BHMMHU7Y.js} +1 -1
  41. package/dist/wallets/walletConnectors/chunk-HKWBR5B7.js +102 -0
  42. package/dist/wallets/walletConnectors/chunk-K4APJ4PE.js +96 -0
  43. package/dist/wallets/walletConnectors/chunk-LJ2B47VF.js +108 -0
  44. package/dist/wallets/walletConnectors/chunk-LXINMUQC.js +186 -0
  45. package/dist/wallets/walletConnectors/chunk-MORUEOYX.js +76 -0
  46. package/dist/wallets/walletConnectors/chunk-MQTXA63X.js +27 -0
  47. package/dist/wallets/walletConnectors/{chunk-G2IHR6PW.js → chunk-NLKL4KD2.js} +11 -11
  48. package/dist/wallets/walletConnectors/{chunk-KOT7JYJR.js → chunk-OEB7MRS5.js} +1 -1
  49. package/dist/wallets/walletConnectors/{chunk-RWIZ25FJ.js → chunk-P2E4LSYH.js} +17 -23
  50. package/dist/wallets/walletConnectors/chunk-PMZJGS7X.js +73 -0
  51. package/dist/wallets/walletConnectors/{chunk-BRM4ZVXZ.js → chunk-RSZS2RMC.js} +1 -1
  52. package/dist/wallets/walletConnectors/chunk-WZZVA3LW.js +101 -0
  53. package/dist/wallets/walletConnectors/chunk-XEIKWKH7.js +63 -0
  54. package/dist/wallets/walletConnectors/chunk-XOQNQKZE.js +98 -0
  55. package/dist/wallets/walletConnectors/chunk-ZAGAF6PO.js +63 -0
  56. package/dist/wallets/walletConnectors/chunk-ZJ6OFFD5.js +95 -0
  57. package/dist/wallets/walletConnectors/index.js +24 -24
  58. package/package.json +17 -11
  59. package/LICENSE +0 -9
  60. package/dist/wallets/walletConnectors/chunk-2J66VMY5.js +0 -152
  61. package/dist/wallets/walletConnectors/chunk-2ZPGPZCP.js +0 -228
  62. package/dist/wallets/walletConnectors/chunk-3DPCIDW6.js +0 -1730
  63. package/dist/wallets/walletConnectors/chunk-4HKJ53H3.js +0 -1742
  64. package/dist/wallets/walletConnectors/chunk-5EARL7FN.js +0 -39
  65. package/dist/wallets/walletConnectors/chunk-7SXCH5TL.js +0 -1752
  66. package/dist/wallets/walletConnectors/chunk-7UZBDZZZ.js +0 -599
  67. package/dist/wallets/walletConnectors/chunk-BUDWZAL7.js +0 -44
  68. package/dist/wallets/walletConnectors/chunk-CSWWNAYR.js +0 -44
  69. package/dist/wallets/walletConnectors/chunk-E4N7SPPU.js +0 -39
  70. package/dist/wallets/walletConnectors/chunk-ENU7XLF5.js +0 -44
  71. package/dist/wallets/walletConnectors/chunk-ESRU5KCF.js +0 -151
  72. package/dist/wallets/walletConnectors/chunk-FF7ZIXKD.js +0 -39
  73. package/dist/wallets/walletConnectors/chunk-FJCL2YPU.js +0 -1737
  74. package/dist/wallets/walletConnectors/chunk-FSU3WBH3.js +0 -63
  75. package/dist/wallets/walletConnectors/chunk-HD6YCICR.js +0 -228
  76. package/dist/wallets/walletConnectors/chunk-HDYBRMYW.js +0 -194
  77. package/dist/wallets/walletConnectors/chunk-HIZCIW5L.js +0 -228
  78. package/dist/wallets/walletConnectors/chunk-JRNBDHFL.js +0 -44
  79. package/dist/wallets/walletConnectors/chunk-KIQDE4N6.js +0 -39
  80. package/dist/wallets/walletConnectors/chunk-KZOSE2PI.js +0 -228
  81. package/dist/wallets/walletConnectors/chunk-LNZJLKFB.js +0 -39
  82. package/dist/wallets/walletConnectors/chunk-LV765WZL.js +0 -1748
  83. package/dist/wallets/walletConnectors/chunk-MSI2BPP5.js +0 -1722
  84. package/dist/wallets/walletConnectors/chunk-MX2IY5CD.js +0 -44
  85. package/dist/wallets/walletConnectors/chunk-NLX2EV7O.js +0 -44
  86. package/dist/wallets/walletConnectors/chunk-NVAZ3B3V.js +0 -228
  87. package/dist/wallets/walletConnectors/chunk-OEWU3ZMN.js +0 -39
  88. package/dist/wallets/walletConnectors/chunk-P2MTINFI.js +0 -280
  89. package/dist/wallets/walletConnectors/chunk-PNMSIVVT.js +0 -44
  90. package/dist/wallets/walletConnectors/chunk-PZNYT2HC.js +0 -1722
  91. package/dist/wallets/walletConnectors/chunk-QPAE4SDS.js +0 -39
  92. package/dist/wallets/walletConnectors/chunk-QZRNNI3E.js +0 -39
  93. package/dist/wallets/walletConnectors/chunk-R4UYVU5X.js +0 -1721
  94. package/dist/wallets/walletConnectors/chunk-RLBGBBIO.js +0 -309
  95. package/dist/wallets/walletConnectors/chunk-TUUNSVKZ.js +0 -345
  96. package/dist/wallets/walletConnectors/chunk-U2CUEL35.js +0 -240
  97. package/dist/wallets/walletConnectors/chunk-V6NRLREB.js +0 -44
  98. package/dist/wallets/walletConnectors/chunk-VM7AEC7H.js +0 -39
  99. package/dist/wallets/walletConnectors/chunk-W2VDZD74.js +0 -478
  100. package/dist/wallets/walletConnectors/chunk-WAO3KL5U.js +0 -285
  101. package/dist/wallets/walletConnectors/chunk-WPHTIILX.js +0 -228
  102. package/dist/wallets/walletConnectors/chunk-WSCJY2QD.js +0 -228
  103. package/dist/wallets/walletConnectors/chunk-X3JQB5QL.js +0 -44
  104. package/dist/wallets/walletConnectors/chunk-X4CDP7L7.js +0 -228
  105. package/dist/wallets/walletConnectors/chunk-XETOVXYM.js +0 -228
  106. package/dist/wallets/walletConnectors/chunk-XYPR4BAF.js +0 -436
  107. package/dist/wallets/walletConnectors/chunk-Z2ZRPTPX.js +0 -1726
  108. package/dist/wallets/walletConnectors/{chunk-VCBVYFLJ.js → chunk-6TLWAEJV.js} +7 -7
  109. package/dist/wallets/walletConnectors/{chunk-47TQ23J4.js → chunk-74ALNZG4.js} +8 -8
  110. package/dist/wallets/walletConnectors/{chunk-66SCJ77O.js → chunk-CM5OGUJV.js} +6 -6
@@ -1,1730 +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
- const isKaiaNetwork = params.chainId === 1001 || params.chainId === 8217;
891
- if (!tx.maxFeePerGas || !tx.maxPriorityFeePerGas || !tx.gasLimit || !tx.gas) {
892
- try {
893
- if (!tx.maxFeePerGas || !tx.maxPriorityFeePerGas) {
894
- const gasFeeUrl = `${this.baseURL}${ABC_ENDPOINTS.GAS_SUGGESTED_FEES}?network=${network}`;
895
- const gasFeeResponse = await fetch(gasFeeUrl, {
896
- method: "GET",
897
- headers: {
898
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
899
- }
900
- });
901
- if (gasFeeResponse.ok) {
902
- const gasData = await gasFeeResponse.json();
903
- if (gasData.medium) {
904
- if (!tx.maxFeePerGas) {
905
- const maxFeeGwei = Number.parseFloat(
906
- gasData.medium.suggestedMaxFeePerGas
907
- );
908
- tx.maxFeePerGas = Math.floor(maxFeeGwei * 1e9).toString();
909
- }
910
- if (!tx.maxPriorityFeePerGas) {
911
- const priorityFeeGwei = Number.parseFloat(
912
- gasData.medium.suggestedMaxPriorityFeePerGas
913
- );
914
- tx.maxPriorityFeePerGas = Math.floor(
915
- priorityFeeGwei * 1e9
916
- ).toString();
917
- }
918
- }
919
- }
920
- }
921
- if (!tx.gasLimit && !tx.gas) {
922
- const estimateBody = new URLSearchParams({
923
- network,
924
- to: tx.to || "0x",
925
- // Use '0x' for contract deployment
926
- ...tx.from ? { from: tx.from } : {},
927
- ...tx.value ? { value: tx.value } : {},
928
- ...tx.data && tx.data !== "0x" ? { data: tx.data } : {},
929
- ...tx.maxFeePerGas ? { maxFeePerGas: tx.maxFeePerGas } : {},
930
- ...tx.maxPriorityFeePerGas ? { maxPriorityFeePerGas: tx.maxPriorityFeePerGas } : {}
931
- });
932
- const estimateUrl = `${this.baseURL}${ABC_ENDPOINTS.GAS_ESTIMATE_EIP1559}`;
933
- const estimateResponse = await fetch(estimateUrl, {
934
- method: "POST",
935
- headers: {
936
- "Content-Type": "application/x-www-form-urlencoded",
937
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
938
- },
939
- body: estimateBody.toString()
940
- });
941
- const estimateData = await estimateResponse.json();
942
- console.log("\u26FD Gas estimate response:", {
943
- status: estimateResponse.status,
944
- ok: estimateResponse.ok,
945
- response: estimateData
946
- });
947
- if (estimateResponse.ok && estimateData.result) {
948
- const estimatedGas = estimateData.result;
949
- const estimatedGasNumber = Number.parseInt(estimatedGas, 16);
950
- if (isKaiaNetwork) {
951
- const hasContractData = tx.data && tx.data !== "0x" && tx.data.length > 2;
952
- const minGas = hasContractData ? 1e5 : 21e3;
953
- if (estimatedGasNumber < minGas) {
954
- console.warn(
955
- "\u26A0\uFE0F [Kaia] Gas estimate too low, enforcing minimum:",
956
- {
957
- chainId: params.chainId,
958
- estimated: estimatedGas,
959
- estimatedDecimal: estimatedGasNumber,
960
- minimum: minGas,
961
- isContractCall: hasContractData
962
- }
963
- );
964
- tx.gasLimit = `0x${minGas.toString(16)}`;
965
- } else {
966
- const bufferedGas = Math.floor(estimatedGasNumber * 1.2);
967
- tx.gasLimit = `0x${bufferedGas.toString(16)}`;
968
- console.log("\u2705 [Kaia] Gas limit with 20% buffer:", {
969
- estimated: estimatedGas,
970
- buffered: tx.gasLimit
971
- });
972
- }
973
- } else {
974
- tx.gasLimit = estimatedGas;
975
- console.log("\u2705 Gas limit from estimate:", estimatedGas);
976
- }
977
- } else {
978
- const hasContractData = tx.data && tx.data !== "0x" && tx.data.length > 2;
979
- if (hasContractData) {
980
- tx.gasLimit = isKaiaNetwork ? "0x186a0" : "0x249f0";
981
- console.warn(
982
- "\u26A0\uFE0F Gas estimate failed, using contract call fallback:",
983
- {
984
- chainId: params.chainId,
985
- network,
986
- fallbackGasLimit: tx.gasLimit,
987
- isKaia: isKaiaNetwork,
988
- error: estimateData.errorMessage || estimateData.msg
989
- }
990
- );
991
- } else {
992
- tx.gasLimit = "0x5208";
993
- console.warn(
994
- "\u26A0\uFE0F Gas estimate failed, using native transfer fallback:",
995
- {
996
- chainId: params.chainId,
997
- network,
998
- fallbackGasLimit: tx.gasLimit
999
- }
1000
- );
1001
- }
1002
- }
1003
- }
1004
- } catch (error) {
1005
- console.warn("Failed to fetch gas parameters from ABC WaaS:", error);
1006
- }
1007
- }
1008
- const bodyData = {
1009
- network,
1010
- encryptDevicePassword: encryptedDevicePassword,
1011
- pvencstr: encryptedPvencstr,
1012
- uid: wallet.uid,
1013
- wid: encryptedWid,
1014
- sid: getAddress(wallet.address),
1015
- // EIP-55 checksum format
1016
- // For contract deployment, 'to' is '0x' (ABC WaaS convention)
1017
- // Reference: talken-nft-drops/src/libs/abc-waas-provider/index.ts:800 - to: to ?? '0x'
1018
- to: tx.to === "0x" ? "0x" : getAddress(tx.to),
1019
- // Required by ABC WaaS API
1020
- // Always use EIP1559 type (ABC WaaS handles network-specific conversion)
1021
- type: "EIP1559",
1022
- // ourpubkey and ucpubkey are required by ABC WaaS (empty strings for now)
1023
- // Based on successful tg-wallet payload analysis
1024
- ourpubkey: "",
1025
- ucpubkey: ""
1026
- };
1027
- bodyData.from = getAddress(tx.from || wallet.address);
1028
- if (tx.value) {
1029
- let hexValue = tx.value.startsWith("0x") ? tx.value.slice(2) : tx.value;
1030
- if (hexValue.length % 2 !== 0) {
1031
- hexValue = `0${hexValue}`;
1032
- }
1033
- bodyData.value = `0x${hexValue}`;
1034
- } else {
1035
- bodyData.value = "0x0";
1036
- }
1037
- if (tx.gasLimit || tx.gas) {
1038
- const gasLimitValue = tx.gasLimit || tx.gas;
1039
- if (gasLimitValue.toString().startsWith("0x")) {
1040
- bodyData.gasLimit = gasLimitValue.toString();
1041
- } else {
1042
- bodyData.gasLimit = `0x${BigInt(gasLimitValue).toString(16)}`;
1043
- }
1044
- }
1045
- if (tx.maxFeePerGas) {
1046
- if (tx.maxFeePerGas.toString().startsWith("0x")) {
1047
- bodyData.maxFeePerGas = tx.maxFeePerGas.toString();
1048
- } else {
1049
- bodyData.maxFeePerGas = `0x${BigInt(tx.maxFeePerGas).toString(16)}`;
1050
- }
1051
- }
1052
- if (tx.maxPriorityFeePerGas) {
1053
- if (tx.maxPriorityFeePerGas.toString().startsWith("0x")) {
1054
- bodyData.maxPriorityFeePerGas = tx.maxPriorityFeePerGas.toString();
1055
- } else {
1056
- bodyData.maxPriorityFeePerGas = `0x${BigInt(tx.maxPriorityFeePerGas).toString(16)}`;
1057
- }
1058
- }
1059
- if (tx.gasPrice) {
1060
- if (tx.gasPrice.toString().startsWith("0x")) {
1061
- bodyData.gasPrice = tx.gasPrice.toString();
1062
- } else {
1063
- bodyData.gasPrice = `0x${BigInt(tx.gasPrice).toString(16)}`;
1064
- }
1065
- }
1066
- if (tx.data !== void 0 && tx.data !== null) {
1067
- bodyData.data = tx.data || "0x";
1068
- } else {
1069
- bodyData.data = "0x";
1070
- }
1071
- const bodyString = new URLSearchParams(bodyData).toString();
1072
- const url = `${this.baseURL}${ABC_ENDPOINTS.SIGN_TRANSACTION}`;
1073
- const response = await fetch(url, {
1074
- method: "POST",
1075
- headers: {
1076
- "Content-Type": "application/x-www-form-urlencoded",
1077
- "Secure-Channel": secureChannelId,
1078
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1079
- },
1080
- body: bodyString
1081
- });
1082
- const res = await response.json();
1083
- console.log("\u{1F4E1} ABC WaaS /sign response:", {
1084
- status: response.status,
1085
- ok: response.ok,
1086
- response: res
1087
- });
1088
- if (!response.ok) {
1089
- console.error("\u274C ABC WaaS API error details:", {
1090
- status: response.status,
1091
- statusText: response.statusText,
1092
- errorCode: res.code,
1093
- errorMessage: res.msg || res.message || res.detail,
1094
- fullResponse: res
1095
- });
1096
- }
1097
- if (response.status === 401 && this.refreshToken) {
1098
- try {
1099
- await this.refreshAccessToken();
1100
- const retryResponse = await fetch(url, {
1101
- method: "POST",
1102
- headers: {
1103
- "Content-Type": "application/x-www-form-urlencoded",
1104
- "Secure-Channel": secureChannelId,
1105
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1106
- },
1107
- body: bodyString
1108
- });
1109
- const retryRes = await retryResponse.json();
1110
- if (retryRes.serializedTx && retryRes.rawTx) {
1111
- return {
1112
- signature: retryRes.serializedTx,
1113
- txHash: retryRes.rawTx
1114
- };
1115
- }
1116
- throw createAbcError(
1117
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1118
- "Failed to sign transaction after token refresh",
1119
- retryRes
1120
- );
1121
- } catch (refreshError) {
1122
- console.error("Token refresh failed in signTransaction:", refreshError);
1123
- throw refreshError;
1124
- }
1125
- }
1126
- if (res.serializedTx && res.rawTx) {
1127
- return {
1128
- signature: res.serializedTx,
1129
- txHash: res.rawTx
1130
- };
1131
- }
1132
- throw createAbcError(
1133
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1134
- "Failed to sign transaction",
1135
- res
1136
- );
1137
- }
1138
- /**
1139
- * Sign message (Personal Sign - EIP-191)
1140
- * Based on tg-wallet-frontend reference implementation
1141
- */
1142
- async signMessage(params) {
1143
- this.loadTokens();
1144
- const wallet = loadFromStorage("wallet" /* WALLET */);
1145
- if (!wallet) {
1146
- throw createAbcError(
1147
- "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1148
- "Wallet information not found in storage"
1149
- );
1150
- }
1151
- const ethers = await import("ethers");
1152
- const messageHash = ethers.ethers.utils.hashMessage(params.message);
1153
- const hash = messageHash.startsWith("0x") ? messageHash.slice(2) : messageHash;
1154
- const encryptedDevicePassword = await this.secure.getEncryptPlain(
1155
- wallet.encryptDevicePassword
1156
- );
1157
- const encryptedPvencstr = await this.secure.getEncryptPlain(
1158
- wallet.pvencstr
1159
- );
1160
- const encryptedWid = await this.secure.getEncryptPlain(wallet.wid);
1161
- const secureChannelId = await this.secure.getSecureChannelId();
1162
- const bodyData = {
1163
- hash,
1164
- encryptDevicePassword: encryptedDevicePassword,
1165
- pvencstr: encryptedPvencstr,
1166
- wid: encryptedWid,
1167
- uid: wallet.uid,
1168
- sid: wallet.sid
1169
- };
1170
- const bodyString = new URLSearchParams(bodyData).toString();
1171
- const url = `${this.baseURL}${ABC_ENDPOINTS.SIGN_HASH}`;
1172
- const response = await fetch(url, {
1173
- method: "POST",
1174
- headers: {
1175
- "Content-Type": "application/x-www-form-urlencoded",
1176
- "Secure-Channel": secureChannelId,
1177
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1178
- },
1179
- body: bodyString
1180
- });
1181
- const text = await response.text();
1182
- if (!text) {
1183
- throw createAbcError(
1184
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1185
- `Empty response from sign API (status: ${response.status})`,
1186
- { status: response.status }
1187
- );
1188
- }
1189
- const res = JSON.parse(text);
1190
- if (response.status === 401) {
1191
- if (!this.refreshToken) {
1192
- this.loadTokens();
1193
- }
1194
- if (this.refreshToken) {
1195
- try {
1196
- await this.refreshAccessToken();
1197
- const retryResponse = await fetch(url, {
1198
- method: "POST",
1199
- headers: {
1200
- "Content-Type": "application/x-www-form-urlencoded",
1201
- "Secure-Channel": secureChannelId,
1202
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1203
- },
1204
- body: bodyString
1205
- });
1206
- const retryText = await retryResponse.text();
1207
- if (!retryText) {
1208
- throw createAbcError(
1209
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1210
- `Empty response from retry (status: ${retryResponse.status})`,
1211
- { status: retryResponse.status }
1212
- );
1213
- }
1214
- const retryRes = JSON.parse(retryText);
1215
- if (retryRes.status === "success" && retryRes.result?.signstr) {
1216
- return { signature: retryRes.result.signstr };
1217
- }
1218
- throw createAbcError(
1219
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1220
- "Failed to sign message after token refresh",
1221
- retryRes
1222
- );
1223
- } catch (refreshError) {
1224
- console.error("Token refresh failed in signMessage:", refreshError);
1225
- throw refreshError;
1226
- }
1227
- }
1228
- }
1229
- if (res.signstr) {
1230
- const signData = JSON.parse(res.signstr);
1231
- const sigList = signData.sig_list?.[0];
1232
- if (!sigList || !sigList.r || !sigList.s) {
1233
- throw createAbcError(
1234
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1235
- "Invalid signature format",
1236
- res
1237
- );
1238
- }
1239
- const v = (sigList.vsource || 0) + 27;
1240
- const signature = sigList.r + sigList.s.slice(2) + v.toString(16).padStart(2, "0");
1241
- return { signature };
1242
- }
1243
- throw createAbcError(
1244
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1245
- "Failed to sign message",
1246
- res
1247
- );
1248
- }
1249
- /**
1250
- * Sign typed data (EIP-712)
1251
- * Reference: tg-wallet-frontend src/features/wallet/api/index.ts sign_typed_data()
1252
- */
1253
- async signTypedData(params) {
1254
- this.loadTokens();
1255
- const wallet = loadFromStorage("wallet" /* WALLET */);
1256
- if (!wallet) {
1257
- throw createAbcError(
1258
- "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1259
- "Wallet information not found in storage"
1260
- );
1261
- }
1262
- const encryptedDevicePassword = await this.secure.getEncryptPlain(
1263
- wallet.encryptDevicePassword
1264
- );
1265
- const encryptedPvencstr = await this.secure.getEncryptPlain(
1266
- wallet.pvencstr
1267
- );
1268
- const encryptedWid = await this.secure.getEncryptPlain(wallet.wid);
1269
- const secureChannelId = await this.secure.getSecureChannelId();
1270
- const getNetworkName = (chainId) => {
1271
- const networkMap = {
1272
- 1: "ethereum",
1273
- // Ethereum Mainnet
1274
- 11155111: "ethereum_sepolia",
1275
- // Sepolia Testnet
1276
- 8217: "klaytn",
1277
- // Klaytn Mainnet
1278
- 1001: "klaytn_baobab",
1279
- // Klaytn Baobab Testnet
1280
- 137: "polygon",
1281
- // Polygon Mainnet
1282
- 80002: "polygon_amoy",
1283
- // Polygon Amoy Testnet
1284
- 42161: "arbitrum",
1285
- // Arbitrum One
1286
- 421614: "arbitrum_sepolia",
1287
- // Arbitrum Sepolia
1288
- 5e3: "mantle",
1289
- // Mantle Mainnet
1290
- 5003: "mantle_testnet"
1291
- // Mantle Testnet
1292
- };
1293
- return networkMap[chainId] || "ethereum";
1294
- };
1295
- const network = getNetworkName(wallet.chainId);
1296
- const bodyData = {
1297
- messageJson: params.typedData,
1298
- // Server expects "messageJson" field
1299
- version: "v4",
1300
- // EIP-712 version
1301
- network,
1302
- // Network name (required for JSON-RPC)
1303
- encryptDevicePassword: encryptedDevicePassword,
1304
- pvencstr: encryptedPvencstr,
1305
- wid: encryptedWid,
1306
- uid: wallet.uid,
1307
- sid: wallet.sid
1308
- };
1309
- const bodyString = new URLSearchParams(bodyData).toString();
1310
- const url = `${this.baseURL}${ABC_ENDPOINTS.SIGN_TYPED}`;
1311
- const response = await fetch(url, {
1312
- method: "POST",
1313
- headers: {
1314
- "Content-Type": "application/x-www-form-urlencoded",
1315
- "Secure-Channel": secureChannelId,
1316
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1317
- },
1318
- body: bodyString
1319
- });
1320
- const text = await response.text();
1321
- if (!text) {
1322
- throw createAbcError(
1323
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1324
- `Empty response from signTypedData API (status: ${response.status})`,
1325
- { status: response.status }
1326
- );
1327
- }
1328
- const res = JSON.parse(text);
1329
- if (response.status === 401 && this.refreshToken) {
1330
- try {
1331
- await this.refreshAccessToken();
1332
- const retryResponse = await fetch(url, {
1333
- method: "POST",
1334
- headers: {
1335
- "Content-Type": "application/x-www-form-urlencoded",
1336
- "Secure-Channel": secureChannelId,
1337
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1338
- },
1339
- body: bodyString
1340
- });
1341
- const retryText = await retryResponse.text();
1342
- if (!retryText) {
1343
- throw createAbcError(
1344
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1345
- `Empty response after retry (status: ${retryResponse.status})`,
1346
- { status: retryResponse.status }
1347
- );
1348
- }
1349
- const retryRes = JSON.parse(retryText);
1350
- if (retryRes.serializedTx) {
1351
- return { signature: retryRes.serializedTx };
1352
- }
1353
- throw createAbcError(
1354
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1355
- "Failed to sign typed data after token refresh",
1356
- retryRes
1357
- );
1358
- } catch (refreshError) {
1359
- console.error("Token refresh failed in signTypedData:", refreshError);
1360
- throw refreshError;
1361
- }
1362
- }
1363
- if (res.serializedTx) {
1364
- return { signature: res.serializedTx };
1365
- }
1366
- throw createAbcError(
1367
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1368
- "Failed to sign typed data",
1369
- res
1370
- );
1371
- }
1372
- /**
1373
- * Send raw transaction
1374
- * Reference: tg-wallet-frontend src/features/wallet/api/index.ts sendRawTx()
1375
- */
1376
- async sendRawTransaction(chainId, signedTransaction) {
1377
- const wallet = loadFromStorage("wallet" /* WALLET */);
1378
- if (!wallet) {
1379
- throw createAbcError(
1380
- "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1381
- "Wallet information not found in storage"
1382
- );
1383
- }
1384
- const getNetworkName = (chainId2) => {
1385
- const networkMap = {
1386
- 1: "ethereum",
1387
- 11155111: "ethereum_sepolia",
1388
- 8217: "klaytn",
1389
- 1001: "klaytn_baobab",
1390
- 137: "polygon",
1391
- 80002: "polygon_amoy",
1392
- 42161: "arbitrum",
1393
- 421614: "arbitrum_sepolia",
1394
- 5e3: "mantle",
1395
- 5003: "mantle_testnet"
1396
- };
1397
- return networkMap[chainId2] || "ethereum";
1398
- };
1399
- const network = getNetworkName(chainId);
1400
- const secureChannelId = await this.secure.getSecureChannelId();
1401
- const bodyData = {
1402
- signedSerializeTx: signedTransaction,
1403
- network
1404
- // rpc parameter
1405
- };
1406
- const bodyString = new URLSearchParams(bodyData).toString();
1407
- const url = `${this.baseURL}${ABC_ENDPOINTS.SEND_RAW_TX}`;
1408
- const response = await fetch(url, {
1409
- method: "POST",
1410
- headers: {
1411
- "Content-Type": "application/x-www-form-urlencoded",
1412
- "Secure-Channel": secureChannelId,
1413
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1414
- },
1415
- body: bodyString
1416
- });
1417
- const text = await response.text();
1418
- if (!text) {
1419
- throw createAbcError(
1420
- "NETWORK_ERROR" /* NETWORK_ERROR */,
1421
- `Empty response from sendRawTx API (status: ${response.status})`,
1422
- { status: response.status }
1423
- );
1424
- }
1425
- const res = JSON.parse(text);
1426
- console.log("\u{1F4E1} sendRawTransaction response:", {
1427
- status: response.status,
1428
- ok: response.ok,
1429
- response: res
1430
- });
1431
- if (!response.ok) {
1432
- console.error("\u274C sendRawTransaction error:", {
1433
- status: response.status,
1434
- errorMessage: res.errorMessage || res.msg || res.message,
1435
- fullResponse: res
1436
- });
1437
- }
1438
- if (response.status === 401 && this.refreshToken) {
1439
- try {
1440
- await this.refreshAccessToken();
1441
- const retryResponse = await fetch(url, {
1442
- method: "POST",
1443
- headers: {
1444
- "Content-Type": "application/x-www-form-urlencoded",
1445
- "Secure-Channel": secureChannelId,
1446
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1447
- },
1448
- body: bodyString
1449
- });
1450
- const retryText = await retryResponse.text();
1451
- if (!retryText) {
1452
- throw createAbcError(
1453
- "NETWORK_ERROR" /* NETWORK_ERROR */,
1454
- `Empty response after retry (status: ${retryResponse.status})`,
1455
- { status: retryResponse.status }
1456
- );
1457
- }
1458
- const retryRes = JSON.parse(retryText);
1459
- if (retryRes.item || retryRes.txHash || retryRes.result?.txHash) {
1460
- const txHash = retryRes.item || retryRes.txHash || retryRes.result.txHash;
1461
- return { txHash };
1462
- }
1463
- throw createAbcError(
1464
- "NETWORK_ERROR" /* NETWORK_ERROR */,
1465
- "Failed to send transaction after token refresh",
1466
- retryRes
1467
- );
1468
- } catch (refreshError) {
1469
- console.error(
1470
- "Token refresh failed in sendRawTransaction:",
1471
- refreshError
1472
- );
1473
- throw refreshError;
1474
- }
1475
- }
1476
- if (res.result) {
1477
- if (typeof res.result === "string") {
1478
- console.log("\u2705 Transaction hash from result:", res.result);
1479
- return { txHash: res.result };
1480
- }
1481
- if (res.result.txHash) {
1482
- return { txHash: res.result.txHash };
1483
- }
1484
- }
1485
- if (res.item) {
1486
- return { txHash: res.item };
1487
- }
1488
- if (res.txHash) {
1489
- return { txHash: res.txHash };
1490
- }
1491
- throw createAbcError(
1492
- "NETWORK_ERROR" /* NETWORK_ERROR */,
1493
- "Failed to send transaction",
1494
- res
1495
- );
1496
- }
1497
- /**
1498
- * Get wallet info
1499
- */
1500
- async getWalletInfo(uid) {
1501
- const response = await this.request(ABC_ENDPOINTS.INFO, {
1502
- method: "POST",
1503
- body: { uid }
1504
- });
1505
- if (response.status === "success") {
1506
- return response.data;
1507
- }
1508
- throw createAbcError(
1509
- "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1510
- "Failed to get wallet info",
1511
- response
1512
- );
1513
- }
1514
- /**
1515
- * Logout (clear tokens)
1516
- */
1517
- async logout() {
1518
- this.clearTokens();
1519
- }
1520
- /**
1521
- * Check if user is authenticated
1522
- */
1523
- isAuthenticated() {
1524
- return !!this.accessToken && !this.isTokenExpired();
1525
- }
1526
- /**
1527
- * Set tokens in client instance (useful when restoring from storage or state)
1528
- * Call this before persistTokens() if you need to set tokens from external source
1529
- */
1530
- setTokens(accessToken, refreshToken, expiresAt) {
1531
- this.accessToken = accessToken;
1532
- this.refreshToken = refreshToken;
1533
- this.expiresAt = expiresAt;
1534
- }
1535
- /**
1536
- * Persist tokens to localStorage
1537
- * Call this after PIN verification is complete
1538
- *
1539
- * SECURITY NOTE: This should only be called after full authentication (password + PIN)
1540
- * to ensure tokens are only persisted after the user has proven ownership of both credentials.
1541
- */
1542
- persistTokens() {
1543
- if (!this.accessToken || !this.refreshToken || !this.expiresAt) {
1544
- console.warn(
1545
- "[AbcWaasClient] \u26A0\uFE0F No tokens to persist - ensure login was successful first"
1546
- );
1547
- return;
1548
- }
1549
- console.log(
1550
- "[AbcWaasClient] \u{1F4BE} Persisting tokens to localStorage after PIN verification"
1551
- );
1552
- saveToStorage("access_token" /* ACCESS_TOKEN */, this.accessToken);
1553
- saveToStorage("refresh_token" /* REFRESH_TOKEN */, this.refreshToken);
1554
- saveToStorage("expires_at" /* EXPIRES_AT */, this.expiresAt);
1555
- }
1556
- // ==========================================================================
1557
- // Solana Methods
1558
- // ==========================================================================
1559
- /**
1560
- * Generate or recover Solana wallet (Ed25519)
1561
- * Reference: SigningService.ts:56-72, wallet/api/index.ts:56-72
1562
- */
1563
- async generateSolanaWallet(pin, isRecover = false) {
1564
- const url = `${this.baseURL}/v3/wallet/${isRecover ? "recover" : "generate"}`;
1565
- const response = await fetch(url, {
1566
- method: "POST",
1567
- headers: {
1568
- ...DEFAULT_HEADERS,
1569
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1570
- },
1571
- body: JSON.stringify({
1572
- curve: "ed25519",
1573
- password: pin
1574
- // PIN will be encrypted by Secure Channel
1575
- })
1576
- });
1577
- const data = await response.json();
1578
- if (!response.ok || data.status !== "success") {
1579
- throw createAbcError(
1580
- "WALLET_NOT_FOUND" /* WALLET_NOT_FOUND */,
1581
- "Failed to generate Solana wallet",
1582
- data
1583
- );
1584
- }
1585
- const result = data.result;
1586
- const addressResult = await this.getSolanaAddress(
1587
- result.public_key,
1588
- this.config.environment === "production" ? "solana" : "solana_devnet"
1589
- );
1590
- return {
1591
- uid: result.uid || "",
1592
- sessionId: result.share_id,
1593
- shareId: result.share_id,
1594
- publicKey: result.public_key,
1595
- address: addressResult,
1596
- keyId: result.key_id || result.share_id,
1597
- encryptedShare: result.encrypted_share || ""
1598
- };
1599
- }
1600
- /**
1601
- * Get Solana address from Ed25519 public key
1602
- * Reference: wallet/api/index.ts:74-82
1603
- */
1604
- async getSolanaAddress(publicKey, network) {
1605
- const url = `${this.baseURL}/wapi/v2/solana/wallet/getAddress`;
1606
- const response = await fetch(url, {
1607
- method: "POST",
1608
- headers: {
1609
- ...DEFAULT_HEADERS,
1610
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1611
- },
1612
- body: JSON.stringify({
1613
- network,
1614
- publicKey
1615
- })
1616
- });
1617
- const data = await response.json();
1618
- if (!response.ok || data.status !== "success") {
1619
- throw createAbcError(
1620
- "NETWORK_ERROR" /* NETWORK_ERROR */,
1621
- "Failed to get Solana address",
1622
- data
1623
- );
1624
- }
1625
- return data.result?.data?.address;
1626
- }
1627
- /**
1628
- * Sign Solana transaction with Ed25519
1629
- * Reference: SigningService.ts:587-626, wallet/api/index.ts:114-122
1630
- */
1631
- async signSolanaTransaction(params) {
1632
- const url = `${this.baseURL}/v3/wallet/sign`;
1633
- const response = await fetch(url, {
1634
- method: "POST",
1635
- headers: {
1636
- ...DEFAULT_HEADERS,
1637
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1638
- },
1639
- body: JSON.stringify({
1640
- uid: params.uid,
1641
- share_id: params.shareId,
1642
- message: params.message,
1643
- // Hex-encoded transaction
1644
- password: params.pin
1645
- // PIN will be encrypted
1646
- })
1647
- });
1648
- const data = await response.json();
1649
- if (!response.ok || data.status !== "success") {
1650
- throw createAbcError(
1651
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1652
- "Failed to sign Solana transaction",
1653
- data
1654
- );
1655
- }
1656
- return {
1657
- signature: data.result?.signature
1658
- };
1659
- }
1660
- /**
1661
- * Sign Solana message with Ed25519
1662
- * Reference: SigningService.ts:546-579
1663
- */
1664
- async signSolanaMessage(params) {
1665
- const url = `${this.baseURL}/v3/wallet/sign`;
1666
- const response = await fetch(url, {
1667
- method: "POST",
1668
- headers: {
1669
- ...DEFAULT_HEADERS,
1670
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1671
- },
1672
- body: JSON.stringify({
1673
- uid: params.uid,
1674
- share_id: params.shareId,
1675
- message: params.message,
1676
- // Hex-encoded message
1677
- password: params.pin
1678
- })
1679
- });
1680
- const data = await response.json();
1681
- if (!response.ok || data.status !== "success") {
1682
- throw createAbcError(
1683
- "SIGNATURE_FAILED" /* SIGNATURE_FAILED */,
1684
- "Failed to sign Solana message",
1685
- data
1686
- );
1687
- }
1688
- return {
1689
- signature: data.result?.signature
1690
- };
1691
- }
1692
- /**
1693
- * Send Solana transaction
1694
- * Reference: SigningService.ts:418, wallet/api/index.ts:124-132
1695
- */
1696
- async sendSolanaTransaction(params) {
1697
- const url = `${this.baseURL}/wapi/v2/solana/tx/sendTransaction`;
1698
- const response = await fetch(url, {
1699
- method: "POST",
1700
- headers: {
1701
- ...DEFAULT_HEADERS,
1702
- ...this.accessToken ? { Authorization: `Bearer ${this.accessToken}` } : {}
1703
- },
1704
- body: JSON.stringify({
1705
- network: params.network,
1706
- serializedTX: params.serializedTX,
1707
- signatures: params.signatures
1708
- })
1709
- });
1710
- const data = await response.json();
1711
- if (!response.ok || data.status !== "success") {
1712
- throw createAbcError(
1713
- "NETWORK_ERROR" /* NETWORK_ERROR */,
1714
- "Failed to send Solana transaction",
1715
- data
1716
- );
1717
- }
1718
- return {
1719
- txHash: data.result?.data
1720
- };
1721
- }
1722
- };
1723
- function createAbcWaasClient(config) {
1724
- return new AbcWaasClient(config);
1725
- }
1726
-
1727
- export {
1728
- AbcWaasClient,
1729
- createAbcWaasClient
1730
- };