@talken/talkenkit 2.5.8 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,347 @@
1
+ "use client";
2
+ import {
3
+ setTalkenApiClient
4
+ } from "./chunk-R6ZE7JAZ.js";
5
+ import {
6
+ resolveTalkenApiUrl
7
+ } from "./chunk-GFWUFYT2.js";
8
+ import {
9
+ AbcAccessKeyProvider
10
+ } from "./chunk-E6ZG77AF.js";
11
+ import {
12
+ setGlobalDefaultBitcoinNetwork,
13
+ setGlobalDefaultChainId,
14
+ setGlobalDefaultSolanaNetwork
15
+ } from "./chunk-O4AU63LK.js";
16
+ import {
17
+ createAbcEvmProvider
18
+ } from "./chunk-EKGPNKHR.js";
19
+ import {
20
+ clearAuthState,
21
+ clearStorage,
22
+ loadAuthState,
23
+ loadFromStorage,
24
+ saveAuthState
25
+ } from "./chunk-EBTKWCIS.js";
26
+ import {
27
+ createTalkenApiClient
28
+ } from "./chunk-5ERWBR7D.js";
29
+ import {
30
+ getCredentialManager
31
+ } from "./chunk-36BJXEBA.js";
32
+ import {
33
+ loadTgAccessKey
34
+ } from "./chunk-6KRX73ED.js";
35
+
36
+ // src/wallets/walletConnectors/abcWallet/abcConnector.ts
37
+ import { getTalkenApiClient } from "@talken/talkenkit";
38
+ import { createConnector } from "wagmi";
39
+ function abcConnector(options) {
40
+ const { config } = options;
41
+ if (config.defaultChainId) {
42
+ setGlobalDefaultChainId(config.defaultChainId);
43
+ }
44
+ if (config.defaultSolanaNetwork) {
45
+ setGlobalDefaultSolanaNetwork(config.defaultSolanaNetwork);
46
+ }
47
+ if (config.defaultBitcoinNetwork) {
48
+ setGlobalDefaultBitcoinNetwork(config.defaultBitcoinNetwork);
49
+ }
50
+ return createConnector((wagmiConfig) => {
51
+ const talkenApi = getTalkenApiClient() || createTalkenApiClient({
52
+ baseUrl: resolveTalkenApiUrl(config.talkenApiUrl),
53
+ environment: config.environment,
54
+ debug: config.environment === "development",
55
+ defaultChainId: config.defaultChainId
56
+ });
57
+ setTalkenApiClient(talkenApi);
58
+ const storedAccessKey = typeof window !== "undefined" ? (() => {
59
+ try {
60
+ return localStorage.getItem("talken_api_access_key_raw");
61
+ } catch {
62
+ return null;
63
+ }
64
+ })() : null;
65
+ const effectiveAccessKey = config.accessKey || storedAccessKey;
66
+ const isAccessKeyMode = !!effectiveAccessKey;
67
+ const provider = isAccessKeyMode ? new AbcAccessKeyProvider(
68
+ effectiveAccessKey,
69
+ resolveTalkenApiUrl(config.talkenApiUrl)
70
+ ) : createAbcEvmProvider(talkenApi);
71
+ let accountsChangedHandler;
72
+ let chainChangedHandler;
73
+ let disconnectHandler;
74
+ return {
75
+ id: "abc",
76
+ name: "ABC Wallet",
77
+ type: "abc",
78
+ /**
79
+ * Connect wallet
80
+ */
81
+ async connect() {
82
+ try {
83
+ const authState = loadAuthState();
84
+ if (!authState || !authState.isAuthenticated || !authState.wallet) {
85
+ throw new Error("ABC_LOGIN_REQUIRED");
86
+ }
87
+ if (isAccessKeyMode) {
88
+ const w = authState.wallet;
89
+ provider.setWallet({
90
+ address: w.address,
91
+ chainId: w.chainId || config.defaultChainId || 1,
92
+ uid: w.uid || "",
93
+ sessionId: w.sessionId || "",
94
+ keyId: w.keyId || "",
95
+ encryptedShare: w.encryptedShare || "",
96
+ sid: w.sid || "",
97
+ type: "evm",
98
+ email: w.email || authState.user?.email || ""
99
+ });
100
+ } else {
101
+ provider.setWallet(authState.wallet);
102
+ if (authState.accessToken && authState.refreshToken && authState.expiresAt) {
103
+ talkenApi.setTokens(
104
+ authState.accessToken,
105
+ authState.refreshToken,
106
+ authState.expiresAt
107
+ );
108
+ }
109
+ }
110
+ const accounts = await provider.request({
111
+ method: "eth_requestAccounts"
112
+ });
113
+ let currentChainId = await provider.request({
114
+ method: "eth_chainId"
115
+ });
116
+ const currentChainIdNumber = Number(currentChainId);
117
+ const isChainSupported = wagmiConfig.chains.some(
118
+ (c) => c.id === currentChainIdNumber
119
+ );
120
+ if (!isChainSupported && wagmiConfig.chains.length > 0) {
121
+ const fallbackChainId = wagmiConfig.chains[0].id;
122
+ await provider.request({
123
+ method: "wallet_switchEthereumChain",
124
+ params: [{ chainId: `0x${fallbackChainId.toString(16)}` }]
125
+ });
126
+ currentChainId = `0x${fallbackChainId.toString(16)}`;
127
+ if (authState.wallet) {
128
+ authState.wallet.chainId = fallbackChainId;
129
+ saveAuthState(authState);
130
+ }
131
+ }
132
+ if (accountsChangedHandler) {
133
+ provider.removeListener("accountsChanged", accountsChangedHandler);
134
+ }
135
+ accountsChangedHandler = (accounts2) => {
136
+ wagmiConfig.emitter.emit("change", {
137
+ accounts: accounts2
138
+ });
139
+ };
140
+ provider.on("accountsChanged", accountsChangedHandler);
141
+ if (chainChangedHandler) {
142
+ provider.removeListener("chainChanged", chainChangedHandler);
143
+ }
144
+ chainChangedHandler = (chainId) => {
145
+ wagmiConfig.emitter.emit("change", {
146
+ chainId: Number(chainId)
147
+ });
148
+ };
149
+ provider.on("chainChanged", chainChangedHandler);
150
+ if (disconnectHandler) {
151
+ provider.removeListener("disconnect", disconnectHandler);
152
+ }
153
+ disconnectHandler = () => {
154
+ wagmiConfig.emitter.emit("disconnect");
155
+ this.onDisconnect();
156
+ };
157
+ provider.on("disconnect", disconnectHandler);
158
+ wagmiConfig.emitter.emit("connect", {
159
+ accounts,
160
+ chainId: Number(currentChainId)
161
+ });
162
+ return {
163
+ accounts,
164
+ chainId: Number(currentChainId)
165
+ };
166
+ } catch (error) {
167
+ console.error("\u274C ABC Connector connect() failed:", {
168
+ message: error.message,
169
+ code: error.code,
170
+ error
171
+ });
172
+ if (error.message === "ABC_LOGIN_REQUIRED") {
173
+ throw error;
174
+ }
175
+ throw error;
176
+ }
177
+ },
178
+ /**
179
+ * Disconnect wallet
180
+ */
181
+ async disconnect() {
182
+ if (accountsChangedHandler) {
183
+ provider.removeListener("accountsChanged", accountsChangedHandler);
184
+ accountsChangedHandler = void 0;
185
+ }
186
+ if (chainChangedHandler) {
187
+ provider.removeListener("chainChanged", chainChangedHandler);
188
+ chainChangedHandler = void 0;
189
+ }
190
+ if (disconnectHandler) {
191
+ provider.removeListener("disconnect", disconnectHandler);
192
+ disconnectHandler = void 0;
193
+ }
194
+ provider.clearWallet();
195
+ talkenApi.auth.logout();
196
+ try {
197
+ localStorage.removeItem("talken_api_access_key_raw");
198
+ } catch {
199
+ }
200
+ clearAuthState();
201
+ getCredentialManager().clear();
202
+ },
203
+ /**
204
+ * Get accounts
205
+ */
206
+ async getAccounts() {
207
+ const accounts = await provider.request({
208
+ method: "eth_accounts"
209
+ });
210
+ return accounts.map((account) => account);
211
+ },
212
+ /**
213
+ * Get chain ID
214
+ */
215
+ async getChainId() {
216
+ const chainId = await provider.request({
217
+ method: "eth_chainId"
218
+ });
219
+ return Number(chainId);
220
+ },
221
+ /**
222
+ * Get provider
223
+ */
224
+ async getProvider() {
225
+ return provider;
226
+ },
227
+ /**
228
+ * Check if authorized (has valid session)
229
+ * Auto-refreshes access token if expired but refresh token is valid
230
+ */
231
+ async isAuthorized() {
232
+ try {
233
+ if (isAccessKeyMode) {
234
+ if (provider.isConnected())
235
+ return true;
236
+ const hasKey = !!effectiveAccessKey || typeof localStorage !== "undefined" && (!!localStorage.getItem("talken_api_access_key_raw") || !!loadTgAccessKey());
237
+ const authState2 = loadAuthState();
238
+ return hasKey && !!authState2?.wallet?.address;
239
+ }
240
+ const authState = loadAuthState();
241
+ if (!authState || !authState.isAuthenticated) {
242
+ return false;
243
+ }
244
+ if (!authState.wallet) {
245
+ return false;
246
+ }
247
+ if (talkenApi.isAuthenticated()) {
248
+ return true;
249
+ }
250
+ if (talkenApi.isAccessKeyMode()) {
251
+ return true;
252
+ }
253
+ const refreshToken = loadFromStorage(
254
+ "refresh_token" /* REFRESH_TOKEN */
255
+ );
256
+ if (!refreshToken) {
257
+ clearStorage();
258
+ return false;
259
+ }
260
+ try {
261
+ const api = getTalkenApiClient();
262
+ if (!api) {
263
+ clearStorage();
264
+ return false;
265
+ }
266
+ const res = await api.auth.refresh();
267
+ talkenApi.setTokens(
268
+ res.accessToken,
269
+ res.refreshToken,
270
+ Date.now() + res.expiresIn * 1e3
271
+ );
272
+ const updatedState = loadAuthState();
273
+ return updatedState?.isAuthenticated ?? false;
274
+ } catch (error) {
275
+ console.error("[AbcConnector] Token refresh failed:", error);
276
+ clearStorage();
277
+ return false;
278
+ }
279
+ } catch (error) {
280
+ console.error(
281
+ "[AbcConnector] Unexpected error in isAuthorized:",
282
+ error
283
+ );
284
+ return false;
285
+ }
286
+ },
287
+ /**
288
+ * Switch chain
289
+ */
290
+ async switchChain({ chainId }) {
291
+ await provider.request({
292
+ method: "wallet_switchEthereumChain",
293
+ params: [{ chainId: `0x${chainId.toString(16)}` }]
294
+ });
295
+ const newChainId = await this.getChainId();
296
+ const authState = loadAuthState();
297
+ if (authState?.wallet) {
298
+ authState.wallet.chainId = newChainId;
299
+ saveAuthState(authState);
300
+ }
301
+ return wagmiConfig.chains.find((x) => x.id === chainId) ?? {
302
+ id: chainId,
303
+ name: `Chain ${chainId}`,
304
+ nativeCurrency: {
305
+ name: "Ether",
306
+ decimals: 18,
307
+ symbol: "ETH"
308
+ },
309
+ rpcUrls: {
310
+ default: { http: [""] }
311
+ }
312
+ };
313
+ },
314
+ /**
315
+ * Handle accounts changed
316
+ */
317
+ onAccountsChanged(accounts) {
318
+ if (accounts.length === 0) {
319
+ this.onDisconnect();
320
+ } else {
321
+ wagmiConfig.emitter.emit("change", {
322
+ accounts
323
+ });
324
+ }
325
+ },
326
+ /**
327
+ * Handle chain changed
328
+ */
329
+ onChainChanged(chain) {
330
+ const chainId = Number(chain);
331
+ wagmiConfig.emitter.emit("change", { chainId });
332
+ },
333
+ /**
334
+ * Handle disconnect
335
+ */
336
+ onDisconnect(_error) {
337
+ provider.clearWallet();
338
+ clearAuthState();
339
+ wagmiConfig.emitter.emit("disconnect");
340
+ }
341
+ };
342
+ });
343
+ }
344
+
345
+ export {
346
+ abcConnector
347
+ };
@@ -0,0 +1,58 @@
1
+ "use client";
2
+ import {
3
+ abcConnector
4
+ } from "./chunk-HRB2TD63.js";
5
+ import {
6
+ resolveTalkenApiUrl
7
+ } from "./chunk-GFWUFYT2.js";
8
+ import {
9
+ createTalkenApiClient
10
+ } from "./chunk-5ERWBR7D.js";
11
+ import {
12
+ ABC_WALLET_METADATA,
13
+ loadTgAccessKey
14
+ } from "./chunk-6KRX73ED.js";
15
+
16
+ // src/wallets/walletConnectors/abcWallet/abcWallet.ts
17
+ import { setTalkenApiClient } from "@talken/talkenkit";
18
+ var abcWallet = (specificOptions) => ({ projectId }) => {
19
+ const talkenApiUrl = resolveTalkenApiUrl(specificOptions?.talkenApiUrl);
20
+ const talkenApi = createTalkenApiClient({
21
+ baseUrl: talkenApiUrl,
22
+ debug: specificOptions?.environment === "development"
23
+ });
24
+ setTalkenApiClient(talkenApi);
25
+ const accessKey = specificOptions?.accessKey || loadTgAccessKey() || null;
26
+ const config = {
27
+ talkenApiUrl,
28
+ apiKey: specificOptions?.apiKey,
29
+ plain: specificOptions?.plain || "",
30
+ // Deprecated - not used (secure.ts uses random generation)
31
+ environment: specificOptions?.environment || "development",
32
+ defaultChainId: specificOptions?.defaultChainId,
33
+ defaultSolanaNetwork: specificOptions?.defaultSolanaNetwork,
34
+ defaultBitcoinNetwork: specificOptions?.defaultBitcoinNetwork,
35
+ projectId,
36
+ ...accessKey && { accessKey }
37
+ };
38
+ return {
39
+ id: ABC_WALLET_METADATA.id,
40
+ name: ABC_WALLET_METADATA.name,
41
+ rdns: ABC_WALLET_METADATA.rdns,
42
+ iconUrl: async () => (await import("./abcWallet-AYWSIGAG.js")).default,
43
+ iconBackground: ABC_WALLET_METADATA.iconBackground,
44
+ // Embedded wallet - no installation required
45
+ installed: void 0,
46
+ // No download URLs for embedded wallet
47
+ downloadUrls: void 0,
48
+ // Create connector - wrapper function required by Wallet type
49
+ // If accessKey exists, abcConnector will use AbcAccessKeyProvider internally
50
+ createConnector: (_walletDetails) => abcConnector({ config }),
51
+ // Embedded wallet always available
52
+ hidden: () => false
53
+ };
54
+ };
55
+
56
+ export {
57
+ abcWallet
58
+ };
@@ -0,0 +1,147 @@
1
+ "use client";
2
+ import {
3
+ STORAGE_PREFIX,
4
+ TOKEN_EXPIRY
5
+ } from "./chunk-6KRX73ED.js";
6
+
7
+ // src/wallets/walletConnectors/abcWallet/sessionUtils.ts
8
+ import { getTalkenApiClient } from "@talken/talkenkit";
9
+ var SESSION_EXPIRED_EVENT = "talkenkit:session-expired";
10
+ var SessionExpiredError = class extends Error {
11
+ constructor(message = "Session expired. Please reconnect your wallet.") {
12
+ super(message);
13
+ this.name = "SessionExpiredError";
14
+ }
15
+ };
16
+ function dispatchSessionExpired() {
17
+ if (typeof window !== "undefined") {
18
+ window.dispatchEvent(new CustomEvent(SESSION_EXPIRED_EVENT));
19
+ }
20
+ }
21
+ function clearSession() {
22
+ const api = getTalkenApiClient();
23
+ if (api) {
24
+ try {
25
+ api.clearSession();
26
+ } catch {
27
+ }
28
+ }
29
+ try {
30
+ localStorage.removeItem(`${STORAGE_PREFIX}auth_state`);
31
+ } catch {
32
+ }
33
+ }
34
+ function handleUnauthorizedResponse(response) {
35
+ if (response.status === 401) {
36
+ handleSessionExpiry();
37
+ throw new SessionExpiredError();
38
+ }
39
+ }
40
+ async function fetchWithSessionCheck(url, options) {
41
+ const response = await fetch(url, options);
42
+ if (!response.ok && response.status === 401) {
43
+ console.error("[ABC WaaS] \u274C Unauthorized (401)");
44
+ handleSessionExpiry();
45
+ throw new SessionExpiredError();
46
+ }
47
+ return response;
48
+ }
49
+ async function refreshAccessToken(pinCallback) {
50
+ if (pinCallback) {
51
+ await pinCallback();
52
+ }
53
+ const api = getTalkenApiClient();
54
+ if (!api) {
55
+ handleSessionExpiry();
56
+ throw new SessionExpiredError();
57
+ }
58
+ const refreshToken = api.getRefreshToken() || localStorage.getItem(`${STORAGE_PREFIX}refresh_token`);
59
+ if (!refreshToken) {
60
+ handleSessionExpiry();
61
+ throw new SessionExpiredError();
62
+ }
63
+ try {
64
+ const res = await api.auth.refresh();
65
+ const expiresAt = Date.now() + res.expiresIn * 1e3;
66
+ api.setTokens(res.accessToken, res.refreshToken || refreshToken, expiresAt);
67
+ localStorage.setItem(`${STORAGE_PREFIX}access_token`, res.accessToken);
68
+ if (res.refreshToken) {
69
+ localStorage.setItem(`${STORAGE_PREFIX}refresh_token`, res.refreshToken);
70
+ }
71
+ localStorage.setItem(`${STORAGE_PREFIX}expires_at`, String(expiresAt));
72
+ scheduleProactiveRefresh(expiresAt);
73
+ return res.accessToken;
74
+ } catch (error) {
75
+ console.error("[SessionUtils] Token refresh failed:", error);
76
+ handleSessionExpiry();
77
+ throw new SessionExpiredError();
78
+ }
79
+ }
80
+ function handleSessionExpiry() {
81
+ clearSession();
82
+ dispatchSessionExpired();
83
+ }
84
+ var refreshTimer = null;
85
+ function scheduleProactiveRefresh(expiresAt) {
86
+ cancelProactiveRefresh();
87
+ const delay = expiresAt - Date.now() - TOKEN_EXPIRY.REFRESH_BUFFER;
88
+ if (delay <= 0) {
89
+ void refreshAccessToken().catch(() => {
90
+ });
91
+ return;
92
+ }
93
+ refreshTimer = setTimeout(() => {
94
+ refreshTimer = null;
95
+ void refreshAccessToken().catch(() => {
96
+ });
97
+ }, delay);
98
+ }
99
+ function cancelProactiveRefresh() {
100
+ if (refreshTimer) {
101
+ clearTimeout(refreshTimer);
102
+ refreshTimer = null;
103
+ }
104
+ }
105
+ function setupVisibilityRefresh() {
106
+ if (typeof document === "undefined")
107
+ return () => {
108
+ };
109
+ const handler = () => {
110
+ if (document.visibilityState !== "visible")
111
+ return;
112
+ let expiresAtStr = null;
113
+ try {
114
+ expiresAtStr = localStorage.getItem(`${STORAGE_PREFIX}expires_at`);
115
+ } catch {
116
+ return;
117
+ }
118
+ if (!expiresAtStr)
119
+ return;
120
+ const expiresAt = Number(expiresAtStr);
121
+ const now = Date.now();
122
+ if (now >= expiresAt) {
123
+ void refreshAccessToken().catch(() => {
124
+ });
125
+ } else if (now >= expiresAt - TOKEN_EXPIRY.REFRESH_BUFFER) {
126
+ void refreshAccessToken().catch(() => {
127
+ });
128
+ } else {
129
+ scheduleProactiveRefresh(expiresAt);
130
+ }
131
+ };
132
+ document.addEventListener("visibilitychange", handler);
133
+ return () => document.removeEventListener("visibilitychange", handler);
134
+ }
135
+
136
+ export {
137
+ SESSION_EXPIRED_EVENT,
138
+ SessionExpiredError,
139
+ dispatchSessionExpired,
140
+ clearSession,
141
+ handleUnauthorizedResponse,
142
+ fetchWithSessionCheck,
143
+ refreshAccessToken,
144
+ scheduleProactiveRefresh,
145
+ cancelProactiveRefresh,
146
+ setupVisibilityRefresh
147
+ };