Skip to content

Commit d65b963

Browse files
committed
refactor: lit session handling
1. Renamed clearLitStorage to resetDecryptionState: - The original name only mentioned storage clearing, but the function also changes UI state and disables decryption in the provider. - The new name better reflects that this is a complete reset of the decryption system. 2. Enhanced Error Handling: - Added error handling around cipher provider operations which could fail. - Added try/catch blocks for localStorage operations which might fail in private browsing mode. - Added error logging with more descriptive messages. 3. Improved State Consistency: - Made sure UI state (sliderValueForDecryption) is always updated regardless of storage operations success. - Added consistency checks between local storage state and UI state. 4. Better Documentation: - Updated function documentation to clarify what each function does. - Added return type for initializeLitSession to make it clear it returns a success status. 5. Optimized Query Invalidation: - Only invalidate queries when the decryption state actually changes, not on every load. - Added checks to compare current state vs desired state before performing operations. 6. Better Error Messages and Logging: - Added more descriptive console logs for better debugging. - More specific error messages in catch blocks.
1 parent 3620394 commit d65b963

File tree

1 file changed

+95
-50
lines changed

1 file changed

+95
-50
lines changed

packages/invoice-dashboard/src/lib/view-requests.svelte

+95-50
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,31 @@
243243
}
244244
};
245245
246+
/**
247+
* Disables decryption capabilities, clears Lit Protocol session data, and resets UI state
248+
*/
249+
const resetDecryptionState = () => {
250+
try {
251+
localStorage?.removeItem("lit-wallet-sig");
252+
localStorage?.removeItem("lit-session-key");
253+
localStorage?.setItem("isDecryptionEnabled", "false");
254+
sliderValueForDecryption = "off";
255+
256+
if (cipherProvider) {
257+
try {
258+
cipherProvider.enableDecryption(false);
259+
} catch (error) {
260+
console.error("Error while disabling cipher provider decryption:", error);
261+
// Continue execution even if this fails
262+
}
263+
}
264+
} catch (storageError) {
265+
console.error("Error while clearing storage:", storageError);
266+
// We still want to update the UI state even if storage operations fail
267+
sliderValueForDecryption = "off";
268+
}
269+
};
270+
246271
/**
247272
* Handles wallet disconnection cleanup
248273
* Resets all wallet-related state and clears storage
@@ -255,11 +280,15 @@
255280
activeRequest = undefined;
256281
initialized = false;
257282
258-
// Clear Lit Protocol session data
259-
clearLitStorage();
283+
// Reset decryption state
284+
resetDecryptionState();
260285
261286
if (cipherProvider?.disconnectWallet) {
262-
cipherProvider.disconnectWallet();
287+
try {
288+
cipherProvider.disconnectWallet();
289+
} catch (error) {
290+
console.error("Error during cipher provider disconnection:", error);
291+
}
263292
}
264293
265294
// Reset state
@@ -291,7 +320,7 @@
291320
litInitializationAttempted = false;
292321
initialized = false;
293322
previousAddress = undefined;
294-
clearLitStorage();
323+
resetDecryptionState();
295324
296325
loading = true;
297326
try {
@@ -442,62 +471,66 @@
442471
/**
443472
* Initializes Lit Protocol session for encrypted requests
444473
* Attempts to restore existing session if available
474+
* @returns {Promise<boolean>} Success status of the initialization
445475
*/
446476
const initializeLitSession = async (
447477
currentAccount: GetAccountReturnType | undefined
448-
) => {
449-
if (!currentAccount?.address || !cipherProvider || litInitializationAttempted) {
450-
console.error(
451-
"Initialization skipped: Missing account, cipherProvider, or already attempted."
452-
);
453-
return;
478+
): Promise<boolean> => {
479+
if (!currentAccount?.address) {
480+
console.error("Cannot initialize Lit session: Missing account address");
481+
return false;
482+
}
483+
484+
if (!cipherProvider) {
485+
console.error("Cannot initialize Lit session: Missing cipher provider");
486+
return false;
487+
}
488+
489+
if (litInitializationAttempted) {
490+
console.log("Lit initialization already attempted for this session");
491+
return false;
454492
}
455493
456494
litInitializationAttempted = true;
457495
458496
try {
459497
const storedSig = localStorage?.getItem("lit-wallet-sig");
460498
const sessionKey = localStorage?.getItem("lit-session-key");
499+
const isEnabled = localStorage?.getItem("isDecryptionEnabled") === "true";
461500
462-
if (storedSig && sessionKey) {
463-
const parsedSig = JSON.parse(storedSig);
501+
// If we have all necessary session data and they match the current account
502+
if (storedSig && sessionKey && isEnabled) {
503+
try {
504+
const parsedSig = JSON.parse(storedSig);
464505
465-
if (
466-
parsedSig.address?.toLowerCase() ===
467-
currentAccount.address?.toLowerCase()
468-
) {
469-
try {
506+
if (parsedSig.address?.toLowerCase() === currentAccount.address?.toLowerCase()) {
470507
// Use the stored session key and signature to restore the session
471-
cipherProvider.enableDecryption(true);
508+
await cipherProvider.enableDecryption(true);
472509
sliderValueForDecryption = "on";
510+
511+
// Ensure our UI state reflects the storage state
473512
localStorage.setItem("isDecryptionEnabled", "true");
474-
await getRequests(currentAccount, requestNetwork);
513+
514+
console.log("Successfully restored Lit session for account:", parsedSig.address);
475515
return true;
476-
} catch (error) {
477-
console.error("Failed to restore Lit session:", error);
478-
clearLitStorage();
516+
} else {
517+
console.log("Stored signature address doesn't match current account, resetting");
518+
resetDecryptionState();
479519
}
480-
} else {
481-
clearLitStorage();
520+
} catch (sessionError) {
521+
console.error("Failed to restore Lit session:", sessionError);
522+
resetDecryptionState();
482523
}
524+
} else {
525+
console.log("Incomplete session data, cannot restore Lit session");
483526
}
484527
} catch (error) {
485528
console.error("Failed to initialize Lit session:", error);
486-
clearLitStorage();
529+
resetDecryptionState();
487530
}
488531
return false;
489532
};
490533
491-
const clearLitStorage = () => {
492-
localStorage?.removeItem("lit-wallet-sig");
493-
localStorage?.removeItem("lit-session-key");
494-
localStorage?.setItem("isDecryptionEnabled", "false");
495-
sliderValueForDecryption = "off";
496-
if (cipherProvider) {
497-
cipherProvider.enableDecryption(false);
498-
}
499-
};
500-
501534
const getRequestsQueryKey = (address: string, currentPage: number) => [
502535
"requestsData",
503536
address,
@@ -846,38 +879,50 @@
846879
const previousNetworks = [...selectedNetworks]; // Store current selection
847880
848881
try {
882+
// Handle decryption state changes based on slider value
849883
if (sliderValue === "on") {
850-
if (localStorage?.getItem("isDecryptionEnabled") === "false") {
884+
const currentDecryptionState = localStorage?.getItem("isDecryptionEnabled") === "true";
885+
886+
// Only invalidate queries if we're changing the decryption state
887+
if (!currentDecryptionState) {
851888
queryClient.invalidateQueries();
852889
}
890+
853891
try {
854892
const signer = await getEthersSigner(wagmiConfig);
855893
if (signer && currentAccount?.address) {
856-
loadSessionSignatures =
857-
localStorage?.getItem("lit-wallet-sig") === null;
858-
await cipherProvider?.getSessionSignatures(
859-
signer,
860-
currentAccount.address,
861-
window.location.host,
862-
"Sign in to Lit Protocol through Request Network"
863-
);
864-
cipherProvider?.enableDecryption(true);
865-
localStorage?.setItem("isDecryptionEnabled", JSON.stringify(true));
894+
// Check if we need to get signatures
895+
loadSessionSignatures = localStorage?.getItem("lit-wallet-sig") === null;
896+
897+
if (loadSessionSignatures) {
898+
await cipherProvider?.getSessionSignatures(
899+
signer,
900+
currentAccount.address,
901+
window.location.host,
902+
"Sign in to Lit Protocol through Request Network"
903+
);
904+
}
905+
906+
await cipherProvider?.enableDecryption(true);
907+
localStorage?.setItem("isDecryptionEnabled", "true");
866908
}
867909
} catch (error) {
868910
console.error("Failed to enable decryption:", error);
869911
toast.error("Failed to enable decryption.");
870-
sliderValueForDecryption = "off";
912+
resetDecryptionState();
871913
return;
872914
} finally {
873915
loadSessionSignatures = false;
874916
}
875917
} else {
876-
if (localStorage?.getItem("isDecryptionEnabled") === "true") {
918+
const currentDecryptionState = localStorage?.getItem("isDecryptionEnabled") === "true";
919+
920+
// Only invalidate queries if we're changing the decryption state
921+
if (currentDecryptionState) {
877922
queryClient.invalidateQueries();
878923
}
879-
cipherProvider?.enableDecryption(false);
880-
localStorage?.setItem("isDecryptionEnabled", JSON.stringify(false));
924+
925+
resetDecryptionState();
881926
}
882927
883928
// Always load requests regardless of decryption state

0 commit comments

Comments
 (0)