📄 src/web3/session/storage.ts
D-OPEN SOVEREIGN
1// Cache-only (re-derivable data — sync results, project locale/count caching);
2// safe to change independently of store.ts's PREFIX, which persists actual
3// wallet session/account state and must not be touched casually.
4const STORAGE_KEY_PREFIX = '@the_library/web3-cache:';
5
6function isLocalStorageAvailable(): boolean {
7 if (typeof window === 'undefined' || typeof localStorage === 'undefined') {
8 return false;
9 }
10 try {
11 const testKey = '__storage_test__';
12 localStorage.setItem(testKey, 'test');
13 localStorage.removeItem(testKey);
14 return true;
15 } catch {
16 return false;
17 }
18}
19
20export function getItem<T = any>(key: string): T | null {
21 if (!isLocalStorageAvailable()) return null;
22 try {
23 const item = localStorage.getItem(STORAGE_KEY_PREFIX + key);
24 return item ? JSON.parse(item) : null;
25 } catch {
26 return null;
27 }
28}
29
30export function setItem<T = any>(key: string, value: T): void {
31 if (!isLocalStorageAvailable()) return;
32 try {
33 localStorage.setItem(STORAGE_KEY_PREFIX + key, JSON.stringify(value));
34 } catch (error) {
35 console.warn('[session/storage] Failed to save to localStorage:', error);
36 }
37}
38