@kheopskit/core 6.0.0-rc.3 → 6.0.0-rc.5

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 (78) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/MIGRATING_TO_V6.md +78 -17
  3. package/README.md +138 -34
  4. package/dist/ethereum.d.mts +2 -2
  5. package/dist/ethereum.d.ts +2 -2
  6. package/dist/ethereum.js +4 -4
  7. package/dist/ethereum.js.map +1 -1
  8. package/dist/ethereum.mjs +4 -4
  9. package/dist/ethereum.mjs.map +1 -1
  10. package/dist/index.d.mts +12 -27
  11. package/dist/index.d.ts +12 -27
  12. package/dist/index.js +9 -921
  13. package/dist/index.mjs +4 -916
  14. package/dist/{injectedWallets-BQBgS-f0.js → injectedWallets-D7wzBr_f.js} +2 -2
  15. package/dist/{injectedWallets-BQBgS-f0.js.map → injectedWallets-D7wzBr_f.js.map} +1 -1
  16. package/dist/{injectedWallets-5GL1Jder.mjs → injectedWallets-DHf2lYVb.mjs} +2 -2
  17. package/dist/{injectedWallets-5GL1Jder.mjs.map → injectedWallets-DHf2lYVb.mjs.map} +1 -1
  18. package/dist/instance-1BgEld17.d.ts +109 -0
  19. package/dist/instance-BPAvq0v7.mjs +1457 -0
  20. package/dist/instance-BPAvq0v7.mjs.map +1 -0
  21. package/dist/instance-CCP7uJV3.js +1528 -0
  22. package/dist/instance-CCP7uJV3.js.map +1 -0
  23. package/dist/instance-DDvZiq1L.d.mts +109 -0
  24. package/dist/internal.d.mts +3 -3
  25. package/dist/internal.d.ts +3 -3
  26. package/dist/internal.js +8 -6
  27. package/dist/internal.mjs +3 -3
  28. package/dist/{platformAccounts-yyRUrnel.mjs → platformAccounts-BeMDbmUT.mjs} +2 -2
  29. package/dist/{platformAccounts-yyRUrnel.mjs.map → platformAccounts-BeMDbmUT.mjs.map} +1 -1
  30. package/dist/{platformAccounts-BjIeRcFN.js → platformAccounts-FE7oA3-Y.js} +2 -2
  31. package/dist/{platformAccounts-BjIeRcFN.js.map → platformAccounts-FE7oA3-Y.js.map} +1 -1
  32. package/dist/polkadot.d.mts +2 -2
  33. package/dist/polkadot.d.ts +2 -2
  34. package/dist/polkadot.js +6 -7
  35. package/dist/polkadot.js.map +1 -1
  36. package/dist/polkadot.mjs +5 -6
  37. package/dist/polkadot.mjs.map +1 -1
  38. package/dist/{polkadotExtensions-BoVKhNU_.mjs → registryReads-30CCkmHe.js} +43 -2
  39. package/dist/registryReads-30CCkmHe.js.map +1 -0
  40. package/dist/{polkadotExtensions-y4J9UzYl.js → registryReads-HvSaXRWX.mjs} +30 -5
  41. package/dist/registryReads-HvSaXRWX.mjs.map +1 -0
  42. package/dist/solana.d.mts +2 -2
  43. package/dist/solana.d.ts +2 -2
  44. package/dist/solana.js +4 -4
  45. package/dist/solana.js.map +1 -1
  46. package/dist/solana.mjs +4 -4
  47. package/dist/solana.mjs.map +1 -1
  48. package/dist/testing.d.mts +1 -1
  49. package/dist/testing.d.ts +1 -1
  50. package/dist/{types-C3I3w0jb.d.ts → types-BGeGUtxz.d.mts} +14 -4
  51. package/dist/{types-C3I3w0jb.d.mts → types-BGeGUtxz.d.ts} +14 -4
  52. package/dist/{types-BWHvNFlN.js → types-BrMtrjs9.js} +8 -1
  53. package/dist/types-BrMtrjs9.js.map +1 -0
  54. package/dist/{types-Yor672md.mjs → types-D7OWi0Td.mjs} +3 -2
  55. package/dist/types-D7OWi0Td.mjs.map +1 -0
  56. package/dist/walletconnect.d.mts +13 -2
  57. package/dist/walletconnect.d.ts +13 -2
  58. package/dist/walletconnect.js +19 -13
  59. package/dist/walletconnect.js.map +1 -1
  60. package/dist/walletconnect.mjs +19 -13
  61. package/dist/walletconnect.mjs.map +1 -1
  62. package/package.json +1 -1
  63. package/dist/getCachedObservable-LUq9IfEx.d.mts +0 -23
  64. package/dist/getCachedObservable-LUq9IfEx.d.ts +0 -23
  65. package/dist/iconCache-C-U3IEbP.mjs +0 -324
  66. package/dist/iconCache-C-U3IEbP.mjs.map +0 -1
  67. package/dist/iconCache-FR4iy6go.js +0 -377
  68. package/dist/iconCache-FR4iy6go.js.map +0 -1
  69. package/dist/index.js.map +0 -1
  70. package/dist/index.mjs.map +0 -1
  71. package/dist/polkadotExtensions-BoVKhNU_.mjs.map +0 -1
  72. package/dist/polkadotExtensions-y4J9UzYl.js.map +0 -1
  73. package/dist/registryReads-BpHsWLd7.js +0 -38
  74. package/dist/registryReads-BpHsWLd7.js.map +0 -1
  75. package/dist/registryReads-BvtznSo3.mjs +0 -33
  76. package/dist/registryReads-BvtznSo3.mjs.map +0 -1
  77. package/dist/types-BWHvNFlN.js.map +0 -1
  78. package/dist/types-Yor672md.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,916 +1,4 @@
1
- import { c as walletPendingError, d as isValidWalletId, f as parseWalletId, i as abortedError, l as WALLET_CONNECT_WALLET_ID, m as clearAllCachedObservables, n as isWalletConnectWallet, p as isWalletPlatform, r as KheopskitError, t as isInjectedWallet, u as getWalletId } from "./types-Yor672md.mjs";
2
- import { c as isValidAddress, n as framesOf, o as getWalletAccountId, s as parseWalletAccountId } from "./platformAccounts-yyRUrnel.mjs";
3
- import { a as safeLocalStorage, c as serializeAccount, l as serializeWallet, n as setCachedIcons, o as hydrateAccount, r as cookieStorage, s as hydrateWallet, t as getCachedIcon } from "./iconCache-C-U3IEbP.mjs";
4
- import { t as createRegistryReads$ } from "./registryReads-BvtznSo3.mjs";
5
- import { isEqual, uniq } from "lodash-es";
6
- import { BehaviorSubject, Observable, Subscription, asapScheduler, combineLatest, concat, debounceTime, distinctUntilChanged, filter, ignoreElements, map, mergeMap, of, scan, shareReplay, startWith, switchMap, take, tap, timer, withLatestFrom } from "rxjs";
7
- //#region src/api/config.ts
8
- /**
9
- * Default storage key for persisting wallet connection state.
10
- * Can be overridden via config.storageKey to avoid conflicts
11
- * when running multiple dapps on the same domain.
12
- */
13
- const DEFAULT_STORAGE_KEY = "kheopskit";
14
- const DEFAULTS = {
15
- autoReconnect: true,
16
- debug: false,
17
- storageKey: DEFAULT_STORAGE_KEY,
18
- hydrationGracePeriod: 500,
19
- hydrationTimeout: 3e3
20
- };
21
- const resolveConfig = (config) => {
22
- const platforms = config?.platforms ?? [];
23
- const invalidPlatforms = platforms.filter((p) => typeof p !== "object" || p === null || typeof p.getWallets$ !== "function");
24
- if (invalidPlatforms.length > 0) throw new Error(`[kheopskit] config.platforms must contain plugin instances created by the per-platform factories (e.g. platforms: [polkadot(), ethereum(), solana()] imported from "@kheopskit/core/<platform>"). Invalid entries: ${JSON.stringify(invalidPlatforms)}. String platform names like "polkadot" were removed in v4 — see MIGRATING_TO_V4.md.`);
25
- if (config?.walletConnect !== void 0 && typeof config.walletConnect?.getWallet$ !== "function") throw new KheopskitError("INVALID_CONFIG", "config.walletConnect must be created by walletConnect() imported from \"@kheopskit/core/walletconnect\", e.g. walletConnect: walletConnect({ projectId, metadata, networks }). Raw WalletConnect options were removed in v6, see MIGRATING_TO_V6.md.");
26
- if (platforms.length === 0) console.warn("[kheopskit] No platforms configured; wallets and accounts will be empty. Pass e.g. platforms: [polkadot()] from \"@kheopskit/core/polkadot\".");
27
- return Object.assign({}, DEFAULTS, config, { platforms });
28
- };
29
- //#endregion
30
- //#region src/utils/sortAccounts.ts
31
- const PLATFORM_ORDER$1 = {
32
- polkadot: 0,
33
- ethereum: 1,
34
- solana: 2
35
- };
36
- const byPlatform = (a1, a2) => PLATFORM_ORDER$1[a1.platform] - PLATFORM_ORDER$1[a2.platform];
37
- const byWalletName = (a1, a2) => {
38
- if (a1.walletName === a2.walletName) return 0;
39
- if (a1.walletName.toLowerCase() === "talisman") return -1;
40
- if (a2.walletName.toLowerCase() === "talisman") return 1;
41
- return a1.walletName.localeCompare(a2.walletName);
42
- };
43
- const sortAccounts = (a1, a2) => byPlatform(a1, a2) || byWalletName(a1, a2);
44
- //#endregion
45
- //#region src/utils/sortWallets.ts
46
- const PLATFORM_ORDER = {
47
- polkadot: 0,
48
- ethereum: 1,
49
- solana: 2
50
- };
51
- const orderOf = (wallet) => isWalletConnectWallet(wallet) ? 3 : PLATFORM_ORDER[wallet.platform];
52
- const sortWallets = (w1, w2) => {
53
- const o1 = orderOf(w1);
54
- const o2 = orderOf(w2);
55
- if (o1 !== o2) return o1 - o2;
56
- if (w1.name.toLowerCase() === "talisman") return -1;
57
- if (w2.name.toLowerCase() === "talisman") return 1;
58
- return w1.name.localeCompare(w2.name);
59
- };
60
- //#endregion
61
- //#region src/api/platform.ts
62
- /**
63
- * Whether a cached account should survive SSR hydration, per its platform
64
- * plugin's `acceptsCachedAccount` hook. Plugins without the hook (and platforms
65
- * with no enabled plugin) accept all — matching the pre-plugin behavior where
66
- * only Polkadot accounts were filtered (by key type).
67
- */
68
- const acceptsCachedAccount = (cached, platforms) => {
69
- return platforms.find((p) => p.platform === cached.platform)?.acceptsCachedAccount?.(cached) ?? true;
70
- };
71
- //#endregion
72
- //#region src/api/reconnectPolicy.ts
73
- const createReconnectPolicy = ({ maxAttempts = 3 } = {}) => {
74
- const states = /* @__PURE__ */ new Map();
75
- const shouldAttempt = (walletId) => {
76
- const state = states.get(walletId);
77
- if (!state) return true;
78
- return state.kind === "failed" && state.attempts < maxAttempts;
79
- };
80
- const attempt = async (walletId, connect) => {
81
- if (!shouldAttempt(walletId)) return false;
82
- const before = states.get(walletId);
83
- states.set(walletId, { kind: "pending" });
84
- const recordOutcome = (outcome) => {
85
- if (states.get(walletId)?.kind !== "settled") states.set(walletId, outcome);
86
- };
87
- try {
88
- await connect();
89
- recordOutcome({ kind: "reconnected" });
90
- return true;
91
- } catch (err) {
92
- recordOutcome({
93
- kind: "failed",
94
- attempts: before?.kind === "failed" ? before.attempts + 1 : 1
95
- });
96
- throw err;
97
- }
98
- };
99
- const settle = (walletId) => {
100
- states.set(walletId, { kind: "settled" });
101
- };
102
- return {
103
- shouldAttempt,
104
- attempt,
105
- settle
106
- };
107
- };
108
- const reconnectAccepts = (autoReconnect, wallet) => typeof autoReconnect === "function" ? autoReconnect(wallet) : autoReconnect;
109
- const reconnectCandidates$ = (store) => {
110
- const remembered$ = store.observable.pipe(map((s) => s.remembered ?? []));
111
- return remembered$.pipe(take(1), switchMap((initial) => remembered$.pipe(scan((remaining, current) => remaining.filter((id) => current.includes(id)), initial))), distinctUntilChanged(isEqual));
112
- };
113
- //#endregion
114
- //#region src/api/hydration.ts
115
- /**
116
- * Builds the cached-state snapshot every consumer must agree on: read the
117
- * store's cached state, hydrate wallets/accounts into placeholders, apply the
118
- * `autoReconnect` rule (a cached connected wallet it rejects becomes
119
- * `disconnected` and loses its cached accounts), filter accounts through each
120
- * platform plugin's `acceptsCachedAccount` hook, and sort with the same
121
- * comparators the live pipeline uses.
122
- *
123
- * This is the single implementation behind the observable's initial seed and
124
- * both React snapshot sources (`serverValue`/`initialValue`). They must produce
125
- * the same shape in the same order or the UI flickers/reorders on reload — by
126
- * sharing this helper, that agreement holds by construction.
127
- */
128
- const getHydratedSnapshot = (store, config, options = {}) => {
129
- const cached = store.getCachedState();
130
- const wallets = cached.wallets.map(hydrateWallet).map((wallet) => wallet.status === "connecting" && isInjectedWallet(wallet) && !reconnectAccepts(config.autoReconnect, wallet) ? {
131
- ...wallet,
132
- status: "disconnected"
133
- } : wallet).map((wallet) => {
134
- if (!options.icons || wallet.icon) return wallet;
135
- const icon = getCachedIcon(wallet.id);
136
- return icon ? {
137
- ...wallet,
138
- icon
139
- } : wallet;
140
- }).sort(sortWallets);
141
- const disconnected = new Set(wallets.filter((w) => w.status === "disconnected").map((w) => w.id));
142
- return {
143
- wallets,
144
- accounts: cached.accounts.filter((account) => !disconnected.has(account.walletId)).filter((account) => acceptsCachedAccount(account, config.platforms)).map(hydrateAccount).sort(sortAccounts)
145
- };
146
- };
147
- //#endregion
148
- //#region src/utils/createHydrationBuffer.ts
149
- const createBufferCore = (cachedItems, liveItems$, gracePeriodMs, timeoutMs, mergeFn, settled$) => {
150
- if (gracePeriodMs <= 0 || cachedItems.length === 0) return liveItems$.pipe(map((items) => ({
151
- items,
152
- isHydrating: false
153
- })));
154
- return new Observable((subscriber) => {
155
- const subscriptions = new Subscription();
156
- const isHydrating$ = new BehaviorSubject(true);
157
- const endHydration = () => {
158
- if (isHydrating$.value) isHydrating$.next(false);
159
- };
160
- const graceElapsed$ = timer(gracePeriodMs).pipe(map(() => true), startWith(false));
161
- const ended$ = settled$ ? combineLatest([graceElapsed$, settled$]).pipe(filter(([graceElapsed, settled]) => graceElapsed && settled), take(1)) : timer(gracePeriodMs);
162
- subscriptions.add(ended$.subscribe(endHydration));
163
- subscriptions.add(timer(timeoutMs).subscribe(endHydration));
164
- subscriptions.add(combineLatest([liveItems$.pipe(startWith([])), isHydrating$]).pipe(map(([liveItems, isHydrating]) => isHydrating ? {
165
- items: mergeFn(liveItems, cachedItems),
166
- isHydrating
167
- } : {
168
- items: liveItems,
169
- isHydrating
170
- })).subscribe(subscriber));
171
- return () => {
172
- subscriptions.unsubscribe();
173
- isHydrating$.complete();
174
- };
175
- });
176
- };
177
- /**
178
- * Creates a hydration buffer that merges cached items with live items.
179
- *
180
- * During hydration, cached items take precedence over live items with the same key.
181
- * This preserves the cached connected state (e.g., isConnected: true) while
182
- * auto-reconnect is still in progress. New live items not in the cache are added.
183
- *
184
- * @param cachedItems - Initial cached items from storage
185
- * @param liveItems$ - Observable of live items as they become available
186
- * @param gracePeriodMs - Minimum time in ms the cached items are shown
187
- * @param timeoutMs - Upper bound in ms on hydration
188
- * @param getKey - Function to extract a unique key from an item
189
- * @param settled$ - Whether the live state has caught up with the cache
190
- * @param mergeItem - Optional function to merge a live item with its cached counterpart
191
- * @param transformCachedOnly - Optional function to transform cached items not yet in the live stream
192
- */
193
- const createHydrationBuffer = (cachedItems, liveItems$, gracePeriodMs, timeoutMs, getKey, settled$, mergeItem, transformCachedOnly) => {
194
- return createBufferCore(cachedItems, liveItems$, gracePeriodMs, timeoutMs, (liveItems, cached) => {
195
- const cachedByKey = new Map(cached.map((item) => [getKey(item), item]));
196
- const liveKeys = new Set(liveItems.map(getKey));
197
- const mergedItems = liveItems.map((liveItem) => {
198
- const key = getKey(liveItem);
199
- const cachedItem = cachedByKey.get(key);
200
- if (!cachedItem) return liveItem;
201
- return mergeItem ? mergeItem(liveItem, cachedItem) : cachedItem;
202
- });
203
- for (const cachedItem of cached) if (!liveKeys.has(getKey(cachedItem))) {
204
- const transformed = transformCachedOnly ? transformCachedOnly(cachedItem) : cachedItem;
205
- mergedItems.push(transformed);
206
- }
207
- return mergedItems;
208
- }, settled$);
209
- };
210
- /**
211
- * Creates a hydration buffer specifically for accounts, which need special handling.
212
- *
213
- * Accounts are grouped by wallet - when a wallet provides its account list,
214
- * we replace all cached accounts for that wallet with the live ones.
215
- * Cached accounts for wallets that haven't provided accounts yet are preserved.
216
- *
217
- * @param cachedAccounts - Initial cached accounts from storage
218
- * @param liveAccounts$ - Observable of live accounts as they become available
219
- * @param gracePeriodMs - Minimum time in ms the cached accounts are shown
220
- * @param timeoutMs - Upper bound in ms on hydration
221
- * @param getWalletId - Function to extract the wallet ID from an account
222
- * @param settled$ - Whether the live state has caught up with the cache
223
- */
224
- const createAccountHydrationBuffer = (cachedAccounts, liveAccounts$, gracePeriodMs, timeoutMs, getWalletId, settled$) => {
225
- return createBufferCore(cachedAccounts, liveAccounts$, gracePeriodMs, timeoutMs, (liveAccounts, cached) => {
226
- const walletsWithLiveAccounts = new Set(liveAccounts.map(getWalletId));
227
- const mergedAccounts = [...liveAccounts];
228
- for (const cachedAccount of cached) if (!walletsWithLiveAccounts.has(getWalletId(cachedAccount))) mergedAccounts.push(cachedAccount);
229
- return mergedAccounts;
230
- }, settled$);
231
- };
232
- //#endregion
233
- //#region src/utils/logObservable.ts
234
- const logObservable = (label, opts) => tap((value) => {
235
- const { printValue = false, enabled = true } = opts || {};
236
- if (!label || !enabled) return;
237
- const text = `[kheopskit] observable ${label} emit`;
238
- if (printValue) console.debug(text, value);
239
- else console.debug(text);
240
- });
241
- //#endregion
242
- //#region src/api/accounts.ts
243
- const getAccounts$ = (config, wallets) => {
244
- return new Observable((subscriber) => {
245
- const sources = config.platforms.map((plugin) => framesOf(plugin.getAccounts$(wallets.pipe(map((ws) => ws.filter((w) => isWalletConnectWallet(w) || w.platform === plugin.platform))))));
246
- const sub = (sources.length ? combineLatest(sources).pipe(map((frames) => ({
247
- accounts: frames.flatMap((frame) => frame.accounts).sort(sortAccounts),
248
- answered: frames.flatMap((frame) => frame.answered)
249
- }))) : of({
250
- accounts: [],
251
- answered: []
252
- })).subscribe(subscriber);
253
- return () => {
254
- sub.unsubscribe();
255
- };
256
- }).pipe(shareReplay({
257
- refCount: true,
258
- bufferSize: 1
259
- }));
260
- };
261
- //#endregion
262
- //#region src/utils/createStore.ts
263
- const createStore = (key, defaultValue, storage = safeLocalStorage, normalize = (value) => value) => {
264
- const read = (str) => normalize(parseData(str, defaultValue));
265
- const syncsAcrossTabs = typeof window !== "undefined" && storage.subscribe !== void 0;
266
- const subject = new BehaviorSubject(read(storage.getItem(key)));
267
- let observers = 0;
268
- let stopSync;
269
- const latestValue = () => {
270
- if (syncsAcrossTabs && observers === 0) subject.next(read(storage.getItem(key)));
271
- return subject.getValue();
272
- };
273
- const observable = new Observable((subscriber) => {
274
- if (observers === 0 && syncsAcrossTabs) {
275
- latestValue();
276
- stopSync = storage.subscribe?.(key, (newValue) => {
277
- subject.next(read(newValue));
278
- });
279
- }
280
- observers++;
281
- const subscription = subject.subscribe(subscriber);
282
- return () => {
283
- subscription.unsubscribe();
284
- observers--;
285
- if (observers === 0) stopSync?.();
286
- };
287
- });
288
- const update = (val) => {
289
- persistBestEffort(key, val, storage);
290
- subject.next(val);
291
- };
292
- return {
293
- observable,
294
- set: (val) => update(val),
295
- mutate: (transform) => update(transform(latestValue())),
296
- get: () => structuredClone(latestValue()),
297
- destroy: () => subject.complete()
298
- };
299
- };
300
- const parseData = (str, defaultValue) => {
301
- try {
302
- if (str) return JSON.parse(str);
303
- } catch {}
304
- return defaultValue;
305
- };
306
- const persistBestEffort = (key, val, storage) => {
307
- const str = JSON.stringify(val);
308
- try {
309
- storage.setItem(key, str);
310
- } catch {}
311
- };
312
- //#endregion
313
- //#region src/api/compactStore.ts
314
- const EMPTY_STORE_DATA = {};
315
- const migratePreV6StoreData = (data) => {
316
- if (data?.autoReconnect === void 0) return data;
317
- const { autoReconnect, ...rest } = data;
318
- return rest.remembered === void 0 && Array.isArray(autoReconnect) ? {
319
- ...rest,
320
- remembered: autoReconnect
321
- } : rest;
322
- };
323
- const toCompactPolkadotAccountType = (type) => {
324
- switch (type) {
325
- case "sr25519": return 0;
326
- case "ed25519": return 1;
327
- case "ecdsa": return 2;
328
- case "ethereum": return 3;
329
- default: return null;
330
- }
331
- };
332
- const fromCompactPolkadotAccountType = (type) => {
333
- switch (type) {
334
- case 0: return "sr25519";
335
- case 1: return "ed25519";
336
- case 2: return "ecdsa";
337
- case 3: return "ethereum";
338
- default: return;
339
- }
340
- };
341
- const toCompactPlatform = (platform) => {
342
- switch (platform) {
343
- case "polkadot": return 0;
344
- case "ethereum": return 1;
345
- case "solana": return 2;
346
- }
347
- };
348
- const fromCompactPlatform = (code) => {
349
- switch (code) {
350
- case 0: return "polkadot";
351
- case 1: return "ethereum";
352
- case 2: return "solana";
353
- default: return;
354
- }
355
- };
356
- const isCompactStore = (value) => {
357
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
358
- if ("cachedWallets" in value || "cachedAccounts" in value) return false;
359
- return "v" in value || "w" in value || "a" in value || "r" in value;
360
- };
361
- const toCompactStore = (data) => {
362
- const wallets = data.cachedWallets?.map((wallet) => [
363
- wallet.id,
364
- wallet.name,
365
- wallet.isConnected ? 1 : 0,
366
- wallet.type === "walletconnect" ? 1 : 0
367
- ]);
368
- const accounts = data.cachedAccounts?.map((account) => [
369
- account.walletId,
370
- account.address,
371
- account.name ?? null,
372
- account.chainId ?? null,
373
- toCompactPolkadotAccountType(account.polkadotAccountType),
374
- toCompactPlatform(account.platform)
375
- ]);
376
- return {
377
- v: 1,
378
- r: data.remembered,
379
- w: wallets?.length ? wallets : void 0,
380
- a: accounts?.length ? accounts : void 0
381
- };
382
- };
383
- const fromCompactStore = (data) => {
384
- const walletNameMap = /* @__PURE__ */ new Map();
385
- const wallets = [];
386
- for (const item of Array.isArray(data.w) ? data.w : []) {
387
- if (!Array.isArray(item)) continue;
388
- const [id, name, isConnected, type] = item;
389
- if (!isValidWalletId(id)) continue;
390
- const isWalletConnect = id === WALLET_CONNECT_WALLET_ID;
391
- const walletType = type === 1 ? "walletconnect" : "injected";
392
- if (isWalletConnect !== (walletType === "walletconnect")) continue;
393
- walletNameMap.set(id, name);
394
- wallets.push({
395
- id,
396
- platform: isWalletConnect ? void 0 : parseWalletId(id).platform,
397
- type: walletType,
398
- name,
399
- isConnected: isConnected === 1
400
- });
401
- }
402
- const accounts = [];
403
- for (const item of Array.isArray(data.a) ? data.a : []) {
404
- if (!Array.isArray(item)) continue;
405
- const [walletId, address, name, chainId, polkadotAccountType, platformCode] = item;
406
- if (!isValidWalletId(walletId) || typeof address !== "string" || !address) continue;
407
- const platform = platformCode != null ? fromCompactPlatform(platformCode) : walletId === "walletconnect" ? void 0 : parseWalletId(walletId).platform;
408
- if (!isWalletPlatform(platform)) continue;
409
- accounts.push({
410
- id: getWalletAccountId(walletId, address),
411
- platform,
412
- address,
413
- name: name ?? void 0,
414
- chainId: chainId ?? void 0,
415
- polkadotAccountType: platform === "polkadot" ? fromCompactPolkadotAccountType(polkadotAccountType) : void 0,
416
- walletId,
417
- walletName: walletNameMap.get(walletId) ?? walletId
418
- });
419
- }
420
- return {
421
- remembered: data.r,
422
- cachedWallets: wallets,
423
- cachedAccounts: accounts
424
- };
425
- };
426
- const decodeStore = (raw, fallback) => {
427
- try {
428
- const parsed = JSON.parse(raw);
429
- if (isCompactStore(parsed)) return fromCompactStore(parsed);
430
- return migratePreV6StoreData(parsed);
431
- } catch {
432
- return fallback;
433
- }
434
- };
435
- const encodeStore = (data) => JSON.stringify(toCompactStore(data));
436
- /**
437
- * Cookie storage that transparently encodes/decodes {@link CompactStoreV1},
438
- * migrating legacy verbose-JSON cookies to the compact format on first read.
439
- */
440
- const createCompactCookieStorage = (initialCookies) => {
441
- const base = cookieStorage(initialCookies);
442
- return {
443
- getItem: (key) => {
444
- const raw = base.getItem(key);
445
- if (!raw) return null;
446
- const expanded = decodeStore(raw, EMPTY_STORE_DATA);
447
- if (typeof document !== "undefined") try {
448
- const parsed = JSON.parse(raw);
449
- if (!isCompactStore(parsed)) base.setItem(key, encodeStore(expanded));
450
- } catch {}
451
- return JSON.stringify(expanded);
452
- },
453
- setItem: (key, value) => {
454
- const expanded = decodeStore(value, EMPTY_STORE_DATA);
455
- base.setItem(key, encodeStore(expanded));
456
- },
457
- removeItem: base.removeItem,
458
- subscribe: (key, callback) => {
459
- const unsubscribe = base.subscribe?.(key, (value) => {
460
- if (!value) {
461
- callback(null);
462
- return;
463
- }
464
- const expanded = decodeStore(value, EMPTY_STORE_DATA);
465
- callback(JSON.stringify(expanded));
466
- });
467
- return () => {
468
- unsubscribe?.();
469
- };
470
- }
471
- };
472
- };
473
- //#endregion
474
- //#region src/api/store.ts
475
- const DEFAULT_SETTINGS = {};
476
- /**
477
- * Validates a cached wallet read from persisted storage. Cached state may have
478
- * been written by an older (or corrupted) version with a different shape, so we
479
- * drop anything that wouldn't survive hydration/sort rather than letting it
480
- * throw at render time. Only the fields downstream code relies on are checked.
481
- */
482
- const isValidCachedWallet = (value) => {
483
- if (!value || typeof value !== "object") return false;
484
- const w = value;
485
- if (!isValidWalletId(w.id)) return false;
486
- if (typeof w.name !== "string" || typeof w.isConnected !== "boolean") return false;
487
- if (w.type === "walletconnect") return w.id === "walletconnect" && w.platform === void 0;
488
- return w.type === "injected" && isWalletPlatform(w.platform);
489
- };
490
- /** Validates a cached account read from persisted storage. See {@link isValidCachedWallet}. */
491
- const isValidCachedAccount = (value) => {
492
- if (!value || typeof value !== "object") return false;
493
- const a = value;
494
- return typeof a.id === "string" && !!a.id && isWalletPlatform(a.platform) && typeof a.address === "string" && !!a.address && isValidWalletId(a.walletId) && typeof a.walletName === "string";
495
- };
496
- /**
497
- * Creates a kheopskit store with the appropriate storage backend.
498
- * Uses the given `storage` when provided, else cookieStorage when ssrCookies is
499
- * provided (for SSR hydration), otherwise safeLocalStorage.
500
- *
501
- * @param options - Configuration options for the store
502
- */
503
- const createKheopskitStore = (options = {}) => {
504
- const { ssrCookies, storageKey = DEFAULT_STORAGE_KEY } = options;
505
- const storage = options.storage ?? (ssrCookies !== void 0 ? createCompactCookieStorage(ssrCookies) : safeLocalStorage);
506
- const store = createStore(storageKey, DEFAULT_SETTINGS, storage, migratePreV6StoreData);
507
- const rememberWallet = (walletId) => {
508
- parseWalletId(walletId);
509
- store.mutate((prev) => ({
510
- ...prev,
511
- remembered: uniq((prev.remembered ?? []).concat(walletId))
512
- }));
513
- };
514
- const forgetWallet = (walletId) => {
515
- store.mutate((prev) => ({
516
- ...prev,
517
- remembered: uniq((prev.remembered ?? []).filter((id) => id !== walletId))
518
- }));
519
- };
520
- const getCachedState = () => {
521
- const data = store.get();
522
- const cachedWallets = Array.isArray(data?.cachedWallets) ? data.cachedWallets : [];
523
- const cachedAccounts = Array.isArray(data?.cachedAccounts) ? data.cachedAccounts : [];
524
- return {
525
- wallets: cachedWallets.filter(isValidCachedWallet),
526
- accounts: cachedAccounts.filter(isValidCachedAccount)
527
- };
528
- };
529
- const setCachedState = (wallets, accounts) => {
530
- store.mutate((prev) => ({
531
- ...prev,
532
- cachedWallets: wallets,
533
- cachedAccounts: accounts
534
- }));
535
- };
536
- return {
537
- observable: store.observable,
538
- rememberWallet,
539
- forgetWallet,
540
- getCachedState,
541
- setCachedState,
542
- destroy: store.destroy
543
- };
544
- };
545
- /**
546
- * Cached default store instance, anchored on globalThis so it stays a single
547
- * instance even if this module is duplicated across bundle chunks (e.g. CJS
548
- * subpath entries). Lazily initialized on first access to be SSR-safe.
549
- */
550
- const DEFAULT_STORE_SYMBOL = Symbol.for("kheopskit.defaultStore");
551
- /**
552
- * Gets the default store, creating it on first access.
553
- * Uses localStorage on client, noop on server.
554
- * Lazily initialized to avoid SSR issues with module-level code.
555
- */
556
- const getDefaultStore = () => {
557
- const g = globalThis;
558
- if (!g[DEFAULT_STORE_SYMBOL]) g[DEFAULT_STORE_SYMBOL] = createKheopskitStore();
559
- return g[DEFAULT_STORE_SYMBOL];
560
- };
561
- //#endregion
562
- //#region src/api/wallets.ts
563
- const getWallets$ = (config, store, registryReads$) => {
564
- return new Observable((subscriber) => {
565
- const ctx = {
566
- config,
567
- store,
568
- registryReads$
569
- };
570
- const observables = config.platforms.map((plugin) => plugin.getWallets$(ctx));
571
- const reconnectPolicy = createReconnectPolicy();
572
- const settleOnUserCall = (wallet) => ({
573
- ...wallet,
574
- connect: (options) => {
575
- reconnectPolicy.settle(wallet.id);
576
- return wallet.connect(options);
577
- },
578
- disconnect: () => {
579
- reconnectPolicy.settle(wallet.id);
580
- return wallet.disconnect();
581
- }
582
- });
583
- const platformWallets$ = observables.length ? combineLatest(observables).pipe(map((wallets) => wallets.flat())) : of([]);
584
- const walletConnect$ = config.walletConnect?.getWallet$(ctx);
585
- const rawWallets$ = (walletConnect$ ? combineLatest([platformWallets$, walletConnect$]).pipe(map(([platformWallets, walletConnect]) => walletConnect ? [...platformWallets, walletConnect] : platformWallets)) : platformWallets$).pipe(map((all) => all.sort(sortWallets)));
586
- const wallets$ = rawWallets$.pipe(map((wallets) => wallets.map((wallet) => isInjectedWallet(wallet) ? settleOnUserCall(wallet) : wallet)));
587
- const reconnect = async (wallet) => {
588
- try {
589
- await reconnectPolicy.attempt(wallet.id, () => wallet.connect());
590
- } catch (err) {
591
- if (subscriber.closed) return;
592
- if (err instanceof KheopskitError) {
593
- if (err.code === "USER_REJECTED") store.forgetWallet(wallet.id);
594
- if (err.code === "USER_REJECTED" || err.code === "ABORTED") reconnectPolicy.settle(wallet.id);
595
- }
596
- if (config.debug) console.debug("[kheopskit] reconnect of %s failed", wallet.id, err);
597
- }
598
- };
599
- const subWallets = wallets$.subscribe(subscriber);
600
- if (subscriber.closed) return subWallets;
601
- const subAutoReconnect = rawWallets$.pipe(withLatestFrom(reconnectCandidates$(store)), filter(([, walletIds]) => config.autoReconnect !== false && walletIds.length > 0), mergeMap(([wallets, walletIds]) => wallets.filter(isInjectedWallet).filter((wallet) => walletIds.includes(wallet.id))), tap((wallet) => {
602
- if (wallet.status === "connected") reconnectPolicy.settle(wallet.id);
603
- }), filter((wallet) => wallet.status === "disconnected" && reconnectAccepts(config.autoReconnect, wallet))).subscribe(reconnect);
604
- return () => {
605
- subAutoReconnect.unsubscribe();
606
- subWallets.unsubscribe();
607
- };
608
- }).pipe(shareReplay({
609
- refCount: true,
610
- bufferSize: 1
611
- }));
612
- };
613
- //#endregion
614
- //#region src/api/kheopskit.ts
615
- const getKheopskit$ = (config, options = {}) => {
616
- const { ssrCookies, store: existingStore } = options;
617
- const kc = resolveConfig(config);
618
- const store = existingStore ?? createKheopskitStore({
619
- ssrCookies,
620
- storageKey: kc.storageKey
621
- });
622
- if (kc.debug) console.debug("[kheopskit] config", kc);
623
- if (kc.debug && typeof window === "undefined" && ssrCookies === void 0) console.warn("[kheopskit] Running on server without `ssrCookies`. Wallet state will not be hydrated. Pass cookies for SSR support.");
624
- const { wallets: cachedWallets, accounts: cachedAccounts } = getHydratedSnapshot(store, kc, { icons: true });
625
- if (kc.debug && cachedWallets.length > 0) console.debug("[kheopskit] hydrating from cache:", {
626
- wallets: cachedWallets.length,
627
- accounts: cachedAccounts.length
628
- });
629
- return new Observable((subscriber) => {
630
- let latest;
631
- let closed = false;
632
- const waiters = /* @__PURE__ */ new Set();
633
- const liveWaiters = /* @__PURE__ */ new Set();
634
- const wrapped = /* @__PURE__ */ new WeakMap();
635
- const abandon = (waiter) => {
636
- waiters.delete(waiter);
637
- if (waiter.isConnected) waiter.reject(abortedError(waiter.walletId, "connect"));
638
- else waiter.resolve();
639
- };
640
- const settleIn = (waiter, state) => {
641
- const wallet = state.wallets.find((w) => w.id === waiter.walletId);
642
- if (!wallet || wallet.isConnected === waiter.isConnected) {
643
- waiters.delete(waiter);
644
- waiter.resolve();
645
- }
646
- };
647
- const supersede = (walletId, isConnected) => {
648
- for (const waiter of waiters) if (waiter.walletId === walletId && waiter.isConnected !== isConnected) abandon(waiter);
649
- };
650
- const whenState = (walletId, isConnected) => new Promise((resolve, reject) => {
651
- const waiter = {
652
- walletId,
653
- isConnected,
654
- resolve,
655
- reject
656
- };
657
- waiters.add(waiter);
658
- if (latest) settleIn(waiter, latest);
659
- if (closed && waiters.has(waiter)) abandon(waiter);
660
- });
661
- const whenLive = (walletId, signal) => new Promise((resolve, reject) => {
662
- const settle = (finish) => {
663
- liveWaiters.delete(check);
664
- signal?.removeEventListener("abort", onAbort);
665
- finish();
666
- };
667
- const onAbort = () => settle(() => reject(abortedError(walletId, "connect")));
668
- const check = (state) => {
669
- if (!state) return onAbort();
670
- const live = state.wallets.find((w) => w.id === walletId && !w.isPlaceholder);
671
- if (live) settle(() => resolve(live));
672
- else if (!state.isHydrating) settle(() => reject(walletPendingError(walletId)));
673
- };
674
- if (closed || signal?.aborted) return onAbort();
675
- signal?.addEventListener("abort", onAbort, { once: true });
676
- liveWaiters.add(check);
677
- if (latest) check(latest);
678
- });
679
- const deferToLive = (placeholder) => ({
680
- ...placeholder,
681
- connect: async (options) => {
682
- const live = await whenLive(placeholder.id, options?.signal);
683
- if (closed) throw abortedError(placeholder.id, "connect");
684
- await live.connect(options);
685
- },
686
- disconnect: async () => {
687
- if (closed) return;
688
- const live = latest?.wallets.find((w) => w.id === placeholder.id && !w.isPlaceholder);
689
- if (live) return live.disconnect();
690
- store.forgetWallet(placeholder.id);
691
- }
692
- });
693
- const settleWithState = (wallet) => {
694
- const existing = wrapped.get(wallet);
695
- if (existing) return existing;
696
- if (wallet.isPlaceholder) {
697
- const deferred = deferToLive(wallet);
698
- wrapped.set(wallet, deferred);
699
- return deferred;
700
- }
701
- if (!isInjectedWallet(wallet)) return wallet;
702
- const settled = {
703
- ...wallet,
704
- connect: async (options) => {
705
- if (closed) throw abortedError(wallet.id, "connect");
706
- await wallet.connect(options);
707
- supersede(wallet.id, true);
708
- await whenState(wallet.id, true);
709
- },
710
- disconnect: async () => {
711
- if (closed) throw abortedError(wallet.id, "disconnect");
712
- await wallet.disconnect();
713
- supersede(wallet.id, false);
714
- await whenState(wallet.id, false);
715
- }
716
- };
717
- wrapped.set(wallet, settled);
718
- return settled;
719
- };
720
- const registryReads$ = createRegistryReads$().pipe(shareReplay({
721
- bufferSize: 1,
722
- refCount: true
723
- }));
724
- const liveWallets$ = getWallets$(kc, store, registryReads$);
725
- const accountFrames$ = getAccounts$(kc, liveWallets$);
726
- const liveAccounts$ = accountFrames$.pipe(map(({ accounts }) => accounts.map(asLive)));
727
- const isDiscovering$ = concat(of(true), registryReads$.pipe(ignoreElements()), liveWallets$.pipe(take(1), map(() => false))).pipe(shareReplay({
728
- bufferSize: 1,
729
- refCount: true
730
- }));
731
- const hydrationSettled$ = combineLatest([
732
- liveWallets$,
733
- accountFrames$.pipe(startWith(noAnswerYet)),
734
- isDiscovering$,
735
- reconnectCandidates$(store)
736
- ]).pipe(map(([wallets, { accounts, answered }, isDiscovering, remembered]) => cachedWallets.every((cached) => {
737
- const wallet = wallets.find((w) => w.id === cached.id);
738
- if (!wallet) return !isDiscovering;
739
- return cached.status !== "connecting" || reconnectSettled(cached, wallet, {
740
- accounts,
741
- answered,
742
- cachedAccounts,
743
- remembered
744
- });
745
- })), debounceTime(0, asapScheduler), distinctUntilChanged());
746
- const bufferedWallets$ = createHydrationBuffer(cachedWallets, liveWallets$.pipe(map((wallets) => wallets.map(asLive))), kc.hydrationGracePeriod, kc.hydrationTimeout, (w) => w.id, hydrationSettled$, (live, cached) => {
747
- const status = sessionRestoring(live, cached) ? "connecting" : live.status;
748
- return {
749
- ...live,
750
- status,
751
- isConnected: status === "connected",
752
- icon: cached.icon || getCachedIcon(cached.id) || live.icon
753
- };
754
- }, (cached) => ({
755
- ...cached,
756
- icon: cached.icon || getCachedIcon(cached.id) || ""
757
- }));
758
- const bufferedAccounts$ = createAccountHydrationBuffer(cachedAccounts, liveAccounts$, kc.hydrationGracePeriod, kc.hydrationTimeout, (a) => a.walletId, hydrationSettled$);
759
- const sharedWallets$ = bufferedWallets$.pipe(shareReplay({
760
- bufferSize: 1,
761
- refCount: true
762
- }));
763
- const sharedAccounts$ = bufferedAccounts$.pipe(shareReplay({
764
- bufferSize: 1,
765
- refCount: true
766
- }));
767
- const subscription = combineLatest({
768
- wallets: sharedWallets$,
769
- accounts: sharedAccounts$,
770
- isDiscovering: isDiscovering$
771
- }).pipe(map(({ wallets, accounts, isDiscovering }) => {
772
- if (kc.debug) console.debug("[kheopskit] hydration state", {
773
- walletsHydrating: wallets.isHydrating,
774
- accountsHydrating: accounts.isHydrating,
775
- isDiscovering,
776
- walletsConnected: wallets.items.filter((w) => w.isConnected).length,
777
- walletsTotal: wallets.items.length
778
- });
779
- return {
780
- config: kc,
781
- wallets: [...wallets.items].sort(sortWallets).map(settleWithState),
782
- accounts: [...accounts.items].sort(sortAccounts),
783
- isHydrating: wallets.isHydrating || accounts.isHydrating,
784
- isDiscovering
785
- };
786
- }), debounceTime(0, asapScheduler), distinctUntilChanged(statesEqual), tap((state) => {
787
- latest = state;
788
- for (const check of liveWaiters) check(state);
789
- for (const waiter of waiters) settleIn(waiter, state);
790
- })).subscribe(subscriber);
791
- const persistSub = combineLatest({
792
- wallets: sharedWallets$,
793
- accounts: sharedAccounts$
794
- }).pipe(filter(({ wallets, accounts }) => !wallets.isHydrating && !accounts.isHydrating), debounceTime(1e3), distinctUntilChanged((prev, curr) => {
795
- const prevWalletKeys = prev.wallets.items.map(persistedWalletKey);
796
- const currWalletKeys = curr.wallets.items.map(persistedWalletKey);
797
- const prevAccountKeys = prev.accounts.items.map(accountChangeKey);
798
- const currAccountKeys = curr.accounts.items.map(accountChangeKey);
799
- return arraysEqual(prevWalletKeys, currWalletKeys) && arraysEqual(prevAccountKeys, currAccountKeys);
800
- })).subscribe(({ wallets, accounts }) => {
801
- const snapshot = persistedSnapshot(wallets.items, accounts.items, store.getCachedState());
802
- if (kc.debug) console.debug("[kheopskit] persisting state snapshot:", {
803
- wallets: snapshot.wallets.length,
804
- accounts: snapshot.accounts.length
805
- });
806
- store.setCachedState(snapshot.wallets, snapshot.accounts);
807
- const icons = {};
808
- for (const wallet of wallets.items) if (wallet.icon) icons[wallet.id] = wallet.icon;
809
- setCachedIcons(icons);
810
- });
811
- return () => {
812
- subscription.unsubscribe();
813
- persistSub.unsubscribe();
814
- closed = true;
815
- for (const waiter of waiters) abandon(waiter);
816
- for (const check of liveWaiters) check(void 0);
817
- };
818
- }).pipe(logObservable("kheopskit$", {
819
- enabled: kc.debug,
820
- printValue: true
821
- }), shareReplay({
822
- bufferSize: 1,
823
- refCount: true
824
- }));
825
- };
826
- const sessionRestoring = (live, cached) => isWalletConnectWallet(live) && live.status === "disconnected" && cached.status === "connecting";
827
- const flagged = /* @__PURE__ */ new WeakMap();
828
- const asLive = (item) => {
829
- const existing = flagged.get(item);
830
- if (existing) return existing;
831
- const live = {
832
- ...item,
833
- isPlaceholder: false
834
- };
835
- flagged.set(item, live);
836
- return live;
837
- };
838
- const noAnswerYet = {
839
- accounts: [],
840
- answered: []
841
- };
842
- /**
843
- * A remembered wallet that reads disconnected without an error is still
844
- * waiting for its reconnect: getWallets$ emits the wallet list before its
845
- * connect() flips the status to connecting.
846
- */
847
- const reconnectSettled = (cached, wallet, live) => {
848
- const status = sessionRestoring(wallet, cached) ? "connecting" : wallet.status;
849
- if (status === "connecting") return false;
850
- if (status === "disconnected") return wallet.error !== void 0 || !live.remembered.includes(cached.id);
851
- return live.answered.includes(cached.id) || !live.cachedAccounts.some((a) => a.walletId === cached.id) || live.accounts.some((a) => a.walletId === cached.id);
852
- };
853
- /**
854
- * A wallet still connecting keeps its previous cache entry and accounts:
855
- * written live it would read isConnected: false with no accounts, and the
856
- * next load would hydrate it as disconnected without placeholders while its
857
- * reconnect runs.
858
- */
859
- const persistedSnapshot = (wallets, accounts, previous) => {
860
- const connecting = new Set(wallets.filter((w) => w.status === "connecting").map((w) => w.id));
861
- const connected = new Set(wallets.filter((w) => w.isConnected).map((w) => w.id));
862
- const previousWallets = new Map(previous.wallets.map((w) => [w.id, w]));
863
- return {
864
- wallets: wallets.map((w) => connecting.has(w.id) && previousWallets.get(w.id) || serializeWallet(w)),
865
- accounts: [...accounts.filter((a) => connected.has(a.walletId)).map(serializeAccount), ...previous.accounts.filter((a) => connecting.has(a.walletId))]
866
- };
867
- };
868
- const arraysEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
869
- /**
870
- * A signature of an account covering its id, its name, plus the
871
- * platform-specific fields that can change without the id changing (Ethereum
872
- * chainId, Polkadot key type, Solana clusters). Used to detect both UI-relevant
873
- * changes and changes worth re-persisting, so the two comparators can't drift
874
- * apart.
875
- */
876
- const accountChangeKey = (account) => `${account.name ?? ""}|${accountPlatformKey(account)}`;
877
- const accountPlatformKey = (account) => {
878
- switch (account.platform) {
879
- case "ethereum": return `${account.id}|${account.chainId ?? ""}`;
880
- case "polkadot": return `${account.id}|${account.type ?? ""}`;
881
- case "solana": return `${account.id}|${(account.chains ?? []).join(",")}`;
882
- default: return account.id;
883
- }
884
- };
885
- /** Platforms a wallet's live session carries (only the WalletConnect connector). */
886
- const walletPlatforms = (wallet) => isWalletConnectWallet(wallet) ? wallet.platforms.join(",") : "";
887
- /** Fields persisted to the cache for a wallet (icon is stored separately). */
888
- const walletPersistKey = (wallet) => `${wallet.id}|${wallet.isConnected ? 1 : 0}|${wallet.name}`;
889
- /**
890
- * What decides a cache write: the persisted fields plus `status`, because a
891
- * wallet whose kept entry was written while connecting must be rewritten live
892
- * once its reconnect fails, and `isConnected` reads false on both sides.
893
- */
894
- const persistedWalletKey = (wallet) => `${walletPersistKey(wallet)}|${wallet.status}`;
895
- /**
896
- * UI-significant signature of a wallet: the persisted fields plus icon and the
897
- * WalletConnect connector's `platforms` array, which drive what the UI shows but
898
- * aren't part of the id (icon and platforms can arrive asynchronously after
899
- * connect without isConnected flipping).
900
- */
901
- const walletUiKey = (wallet) => `${walletPersistKey(wallet)}|${wallet.status}|${wallet.error?.code ?? ""}|${wallet.icon}|${walletPlatforms(wallet)}`;
902
- /**
903
- * Equality check for KheopskitState to prevent unnecessary emissions. Compares
904
- * the UI-significant signature of every wallet and account, in order.
905
- */
906
- const statesEqual = (a, b) => a.isHydrating === b.isHydrating && a.isDiscovering === b.isDiscovering && a.wallets.length === b.wallets.length && a.accounts.length === b.accounts.length && a.wallets.every((w, i) => {
907
- const other = b.wallets[i];
908
- return !!other && w.isPlaceholder === other.isPlaceholder && walletUiKey(w) === walletUiKey(other);
909
- }) && a.accounts.every((acc, i) => {
910
- const other = b.accounts[i];
911
- return !!other && acc.isPlaceholder === other.isPlaceholder && accountChangeKey(acc) === accountChangeKey(other);
912
- });
913
- //#endregion
914
- export { DEFAULT_STORAGE_KEY, KheopskitError, clearAllCachedObservables, createKheopskitStore, getDefaultStore, getHydratedSnapshot, getKheopskit$, getWalletAccountId, getWalletId, isInjectedWallet, isValidAddress, isValidWalletId, isWalletConnectWallet, parseWalletAccountId, parseWalletId, resolveConfig };
915
-
916
- //# sourceMappingURL=index.mjs.map
1
+ import { d as getWalletId, f as isValidWalletId, h as clearAllCachedObservables, n as isWalletConnectWallet, p as parseWalletId, r as KheopskitError, t as isInjectedWallet } from "./types-D7OWi0Td.mjs";
2
+ import { c as isValidAddress, o as getWalletAccountId, s as parseWalletAccountId } from "./platformAccounts-BeMDbmUT.mjs";
3
+ import { a as getDefaultStore, d as DEFAULT_STORAGE_KEY, f as resolveConfig, i as createKheopskitStore, n as createKheopskit, o as getHydratedSnapshot } from "./instance-BPAvq0v7.mjs";
4
+ export { DEFAULT_STORAGE_KEY, KheopskitError, clearAllCachedObservables, createKheopskit, createKheopskitStore, getDefaultStore, getHydratedSnapshot, getWalletAccountId, getWalletId, isInjectedWallet, isValidAddress, isValidWalletId, isWalletConnectWallet, parseWalletAccountId, parseWalletId, resolveConfig };