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