Skip to content

fix: Updated lit signature logic #331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from

Conversation

sstefdev
Copy link
Contributor

@sstefdev sstefdev commented Feb 3, 2025

Fixes: #319
Fixes: #299
Fixes: #340

Problem

The Invoice Dashboard experiences issues with Lit Protocol sign-in when users switch accounts. Specifically, the sign-in process sometimes enters an infinite loop, preventing successful authentication and access.

Changes

  • Modified the Lit signing logic within the Invoice Dashboard component.
  • Modified the Lit signing logic within the Single Invoice component.
  • Pinned the web3modal-ethers5 version, which fixed the build issue.

To-do:

  • Testing without the "domain" error

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced management of wallet connections and session initialization.
    • Added state variables to track session status.
    • Introduced functionality for restoring sessions using stored signatures and session keys.
    • Added functionality to clear session-related data for improved state management.
  • Bug Fixes

    • Improved error handling during session initialization and decryption processes.
  • Refactor

    • Streamlined the secure invoice access by simplifying the wallet connection and decryption flow for a more reliable experience.
    • Updated dependency version to ensure compatibility with specific versions.
  • Chores

    • Updated build environment configuration for improved performance during the build process.

Copy link
Contributor

coderabbitai bot commented Feb 3, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces significant changes to the view-requests.svelte and single-invoice.svelte components, focusing on wallet connection management and session initialization. New state variables litSessionInitialized and initializationAttempted are added to track session status. The initializeLitSession function is introduced to restore sessions using stored data. The handling of wallet changes and session management is enhanced, including improved error handling during initialization and decryption processes. Additionally, the dependency version for @web3modal/ethers5 is updated to a specific version in the package.json.

Changes

File(s) Change Summary
packages/invoice-dashboard/src/lib/view-requests.svelte Added state variables litSessionInitialized and initializationAttempted; modified handleWalletChange to reset these variables and attempt Lit session initialization; updated onMount to be asynchronous with error handling; introduced initializeLitSession and clearLitStorage functions.
packages/single-invoice/src/lib/single-invoice.svelte Added state variables litSessionInitialized and initializationAttempted; introduced initializeLitSession for session restoration; simplified ensureDecryption function; updated handleWalletConnection and handleWalletDisconnection to manage local storage appropriately.
packages/payment-widget/package.json Updated dependency version for @web3modal/ethers5 from "^5.0.11" to "5.0.11", restricting it to a specific version.
.github/workflows/build.yml Added container configuration for the build job using node:18 image; reformatted setup-node action parameters; introduced NODE_OPTIONS environment variable to allow larger memory allocation during the build process.

Possibly related PRs

Suggested reviewers

  • rodrigopavezi
  • aimensahnoun

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sstefdev
Copy link
Contributor Author

sstefdev commented Feb 5, 2025

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
packages/single-invoice/src/lib/single-invoice.svelte (1)

420-435: Fix potential race condition in account assignment.

The account assignment after the early return could be stale if the wallet state changes between the check and the assignment.

Apply this diff to fix the race condition:

 const handleWalletConnection = async () => {
-  if (!account?.address) return;
+  const currentAccount = getAccount(wagmiConfig);
+  if (!currentAccount?.address) return;
 
-  account = getAccount(wagmiConfig);
+  account = currentAccount;
 
   if (isDecryptionEnabled && requestId) {
     const isEncrypted = await isRequestEncrypted(requestId);
     if (isEncrypted) {
       await ensureDecryption();
     }
   }
 
   if (requestId && requestNetwork) {
     await getOneRequest(requestId);
   }
 };
🧹 Nitpick comments (3)
packages/single-invoice/src/lib/single-invoice.svelte (2)

437-453: Improve cleanup atomicity in wallet disconnection.

The cleanup of local storage items should be atomic to prevent inconsistent states.

Apply this diff to improve the cleanup process:

 const handleWalletDisconnection = () => {
+  // First, clean up decryption state to prevent any ongoing operations
+  if (cipherProvider) {
+    cipherProvider.disconnectWallet();
+    // Clean up all storage items atomically
+    const storageItems = [
+      'lit-wallet-sig',
+      'lit-session-key',
+      'isDecryptionEnabled'
+    ];
+    storageItems.forEach(item => {
+      if (item === 'isDecryptionEnabled') {
+        localStorage.setItem(item, 'false');
+      } else {
+        localStorage.removeItem(item);
+      }
+    });
+  }
+
+  // Then reset all state variables
   account = undefined;
   address = undefined;
   request = undefined;
   requestData = null;
   signer = null;
   approved = false;
   isPayee = false;
-
-  // Clean up decryption state
-  if (cipherProvider) {
-    cipherProvider.disconnectWallet();
-    localStorage.removeItem("lit-wallet-sig");
-    localStorage.removeItem("lit-session-key");
-    localStorage.setItem("isDecryptionEnabled", "false");
-  }
 };

812-821: Address the FIXME comment by implementing proper rounding.

The current implementation truncates decimal numbers without rounding, which could lead to precision loss.

Would you like me to generate an implementation that properly rounds decimal numbers? Here's a suggested implementation:

-// FIXME: Add rounding functionality
 function truncateNumberString(
   value: string,
   maxDecimalDigits: number
 ): string {
   const [integerPart, decimalPart] = value.split(".");
-  return decimalPart
-    ? `${integerPart}.${decimalPart.substring(0, maxDecimalDigits)}`
-    : value;
+  if (!decimalPart) return value;
+  
+  const roundedDecimal = Number(`0.${decimalPart}`)
+    .toFixed(maxDecimalDigits);
+  
+  // Remove leading "0." from the rounded result
+  return `${integerPart}.${roundedDecimal.substring(2)}`;
 }
packages/invoice-dashboard/src/lib/view-requests.svelte (1)

501-564: Improve error handling in loadRequests.

The function could benefit from more robust error handling and cleanup in failure cases.

Apply this diff to improve error handling:

 const loadRequests = async (
   sliderValue: string,
   currentAccount: GetAccountReturnType | undefined,
   currentRequestNetwork: RequestNetwork | undefined | null
 ) => {
   if (!currentAccount?.address || !currentRequestNetwork || !cipherProvider)
     return;

   loading = true;
   const previousNetworks = [...selectedNetworks];

   try {
     if (sliderValue === "on") {
       if (localStorage?.getItem("isDecryptionEnabled") === "false") {
         queryClient.invalidateQueries();
       }
       try {
         const signer = await getEthersSigner(wagmiConfig);
         if (signer && currentAccount?.address) {
           loadSessionSignatures =
             localStorage?.getItem("lit-wallet-sig") === null;
           const signatures = await cipherProvider?.getSessionSignatures(
             signer,
             currentAccount.address,
             window.location.host,
             "Sign in to Lit Protocol through Request Network"
           );

           // Save both signatures
           localStorage?.setItem(
             "lit-wallet-sig",
             JSON.stringify({
               address: currentAccount.address,
               timestamp: Date.now(),
               sig: signatures.walletSig,
             })
           );
           localStorage?.setItem("lit-session-key", signatures.sessionKey);

           cipherProvider?.enableDecryption(true);
           localStorage?.setItem("isDecryptionEnabled", JSON.stringify(true));
         }
       } catch (error) {
         console.error("Failed to enable decryption:", error);
         toast.error("Failed to enable decryption.");
+        // Clean up any partial state
+        localStorage?.removeItem("lit-wallet-sig");
+        localStorage?.removeItem("lit-session-key");
+        localStorage?.setItem("isDecryptionEnabled", "false");
         return;
       } finally {
         loadSessionSignatures = false;
       }
     } else {
       if (localStorage?.getItem("isDecryptionEnabled") === "true") {
         queryClient.invalidateQueries();
       }
       cipherProvider?.enableDecryption(false);
       localStorage?.setItem("isDecryptionEnabled", JSON.stringify(false));
     }
     await getRequests(currentAccount, currentRequestNetwork);
     selectedNetworks = previousNetworks; // Restore selection
   } catch (error) {
+    console.error("Failed to load requests:", error);
+    toast.error("Failed to load requests. Please try again.");
+    // Restore previous state
+    selectedNetworks = previousNetworks;
   } finally {
     loading = false;
   }
-  await getRequests(currentAccount, currentRequestNetwork);
-  loading = false;
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 022f883 and 2f9011c.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • packages/invoice-dashboard/src/lib/view-requests.svelte (5 hunks)
  • packages/single-invoice/src/lib/single-invoice.svelte (3 hunks)
🔇 Additional comments (1)
packages/invoice-dashboard/src/lib/view-requests.svelte (1)

197-226: LGTM! Code formatting improvements enhance readability.

The reformatting of these functions improves code readability while maintaining the same functionality.

@MantisClone
Copy link
Member

I cannot enable decryption due to error. I tried refreshing, disconnecting and reconnecting wallet, and deleting my local storage (cookies), but same error each time.

Error:

TypeError: Cannot read properties of undefined (reading 'walletSig')

Screenshot from 2025-02-05 17-00-37

…319-invoice-dashboard-lit-protocol-sign-in-fails-when-switching-accounts-sometimes-lit-protocol-prompts-sign-in-infinite-loop
@sstefdev sstefdev marked this pull request as ready for review February 18, 2025 15:41
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/invoice-dashboard/src/lib/view-requests.svelte (1)

574-575: Invalidate queries selectively for performance improvements.
Calling queryClient.invalidateQueries() without a query key may re-fetch more data than needed. Consider a targeted invalidation for better performance, for example:

- queryClient.invalidateQueries();
+ queryClient.invalidateQueries({
+   queryKey: getRequestsQueryKey(currentAccount.address, currentPage),
+ });

Also applies to: 599-600

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2f9011c and 3b817f0.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • packages/invoice-dashboard/src/lib/view-requests.svelte (7 hunks)
  • packages/single-invoice/src/lib/single-invoice.svelte (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/single-invoice/src/lib/single-invoice.svelte
🔇 Additional comments (8)
packages/invoice-dashboard/src/lib/view-requests.svelte (8)

139-140: Initialize session states.
These flags help track whether the Lit session is established, preventing repeated or redundant initializations.


155-166: Resetting session on wallet change.
Clearing stored Lit data and resetting flags upon a wallet address change is a robust approach to avoid mismatched session data.


169-178: Graceful onMount initialization.
Good use of try/catch to handle potential failures in initializeCurrencyManager and Lit session setup. Consider logging a user-facing message if initialization fails, to improve UX.


203-243: Comprehensive session restoration logic.
This function thoroughly checks local storage and corresponds to the active address, which is vital to avoid re-signing. Logic and error handling look solid.


245-253: Straightforward session cleanup.
This method ensures that leftover session details are purged completely. Good approach to keep session data consistent.


255-260: Clear and concise query key generator.
Leveraging an array-based query key for pagination is a standard and effective approach.


261-278: Pagination-based request fetching.
Fetching paginated requests with requestNetwork.fromIdentity is neatly integrated, aligning with the new query-based approach.


295-297: Prefetching and sorting requests.
You employ React Query's fetch and prefetch effectively. Sorting by timestamp is a clear approach to keep data current.

Also applies to: 312-313

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
packages/single-invoice/src/lib/single-invoice.svelte (3)

221-223: Enhance error logging for better debugging.

The error message could be more specific about which condition failed.

Apply this diff to improve error logging:

-      console.error(
-        "Initialization skipped: Missing account, cipherProvider, or already attempted."
-      );
+      console.error(
+        "Initialization skipped:",
+        !currentAccount?.address ? "Missing account address" :
+        !cipherProvider ? "Missing cipher provider" :
+        "Initialization already attempted"
+      );

274-284: Consider using Svelte's reactive statement for initialization.

The current initialization in onMount might miss account changes. Using a reactive statement would be more robust.

Apply this diff to improve initialization reliability:

-  onMount(async () => {
-    currencyManager = await initializeCurrencyManager();
-    if (account?.address) {
-      // Attempt to use existing session from the dashboard
-      const sessionRestored = await initializeLitSession(account);
-      if (!sessionRestored) {
-        // If no session is restored, initialize a new session
-        await initializeLitSession(account);
-      }
-    }
-  });
+  onMount(async () => {
+    currencyManager = await initializeCurrencyManager();
+  });
+
+  $: if (account?.address && !initializationAttempted) {
+    initializeLitSession(account);
+  }

486-490: Remove redundant account assignment.

The account assignment on line 489 is unnecessary since it was just checked to be unavailable.

Apply this diff to remove the redundancy:

   if (!account?.address) return;

-  account = getAccount(wagmiConfig);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b817f0 and ede8ea8.

📒 Files selected for processing (1)
  • packages/single-invoice/src/lib/single-invoice.svelte (5 hunks)
🔇 Additional comments (2)
packages/single-invoice/src/lib/single-invoice.svelte (2)

127-128: LGTM! Clear and descriptive state variables.

The new state variables effectively track the Lit Protocol session initialization state.


326-347: Great improvement in error handling!

The function now properly returns boolean status and includes appropriate validation checks.

@MantisClone
Copy link
Member

@sstefdev Please resolve the build error when you can. I'll skim the code but I'll reserve my full review until after it builds successfully.

@sstefdev
Copy link
Contributor Author

The build for the payment-widget is going trough, but we get an error on the node side:


FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
 1: 0xb9c1f0 node::Abort() [node]
 2: 0xaa27ee  [node]
 3: 0xd73bc0 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xd73f67 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xf51375  [node]
 6: 0xf6384d v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 7: 0xf3df3e v8::internal::HeapAllocator::AllocateRawWithLightRetrySlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
 8: 0xf3f307 v8::internal::HeapAllocator::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
 9: 0xf1f880 v8::internal::Factory::AllocateRaw(int, v8::internal::AllocationType, v8::internal::AllocationAlignment) [node]
10: 0xf172f4 v8::internal::FactoryBase<v8::internal::Factory>::AllocateRawWithImmortalMap(int, v8::internal::AllocationType, v8::internal::Map, v8::internal::AllocationAlignment) [node]
11: 0xf195a8 v8::internal::FactoryBase<v8::internal::Factory>::NewRawOneByteString(int, v8::internal::AllocationType) [node]
12: 0xf22b6d v8::internal::Factory::NewStringFromUtf8(v8::base::Vector<char const> const&, v8::internal::AllocationType) [node]
13: 0xd82dd3 v8::String::NewFromUtf8(v8::Isolate*, char const*, v8::NewStringType, int) [node]
14: 0xc87719 node::StringBytes::Encode(v8::Isolate*, char const*, unsigned long, node::encoding, v8::Local<v8::Value>*) [node]
15: 0xb6d721  [node]
16: 0x1697c2f  [node]
Aborted (core dumped)```

Looking into it now

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 46bea85 and 96655a9.

📒 Files selected for processing (1)
  • .github/workflows/build.yml (1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/build.yml

20-20: the runner of "actions/setup-node@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (1)
.github/workflows/build.yml (1)

29-31: Validate the NODE_OPTIONS memory configuration
Setting NODE_OPTIONS to "--max-old-space-size=8192" is a good step to address out-of-memory errors during builds. Please confirm that this value is optimal across your different build environments and doesn't mask underlying performance issues.

@sstefdev
Copy link
Contributor Author

The build for the payment-widget is going trough, but we get an error on the node side:


FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
 1: 0xb9c1f0 node::Abort() [node]
 2: 0xaa27ee  [node]
 3: 0xd73bc0 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xd73f67 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xf51375  [node]
 6: 0xf6384d v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 7: 0xf3df3e v8::internal::HeapAllocator::AllocateRawWithLightRetrySlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
 8: 0xf3f307 v8::internal::HeapAllocator::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
 9: 0xf1f880 v8::internal::Factory::AllocateRaw(int, v8::internal::AllocationType, v8::internal::AllocationAlignment) [node]
10: 0xf172f4 v8::internal::FactoryBase<v8::internal::Factory>::AllocateRawWithImmortalMap(int, v8::internal::AllocationType, v8::internal::Map, v8::internal::AllocationAlignment) [node]
11: 0xf195a8 v8::internal::FactoryBase<v8::internal::Factory>::NewRawOneByteString(int, v8::internal::AllocationType) [node]
12: 0xf22b6d v8::internal::Factory::NewStringFromUtf8(v8::base::Vector<char const> const&, v8::internal::AllocationType) [node]
13: 0xd82dd3 v8::String::NewFromUtf8(v8::Isolate*, char const*, v8::NewStringType, int) [node]
14: 0xc87719 node::StringBytes::Encode(v8::Isolate*, char const*, unsigned long, node::encoding, v8::Local<v8::Value>*) [node]
15: 0xb6d721  [node]
16: 0x1697c2f  [node]
Aborted (core dumped)```

Looking into it now

This was fixed by adding the --max-old-space-size=8192 flag

aimensahnoun
aimensahnoun previously approved these changes Feb 27, 2025
@MantisClone
Copy link
Member

I still get a build error for the payment-widget, but I'm able to test the invoicing-template locally. 👍

@requestnetwork/payment-widget:build: Aborted (core dumped)
@requestnetwork/payment-widget:build: npm ERR! Lifecycle script `build:wc` failed with error: 
@requestnetwork/payment-widget:build: npm ERR! Error: command failed 
@requestnetwork/payment-widget:build: npm ERR!   in workspace: @requestnetwork/[email protected] 
@requestnetwork/payment-widget:build: npm ERR!   at location: /home/mantisclone/projects/web-components/packages/payment-widget 
@requestnetwork/payment-widget:build: npm ERR! Lifecycle script `package` failed with error: 
@requestnetwork/payment-widget:build: npm ERR! Error: command failed 
@requestnetwork/payment-widget:build: npm ERR!   in workspace: @requestnetwork/[email protected] 
@requestnetwork/payment-widget:build: npm ERR!   at location: /home/mantisclone/projects/web-components/packages/payment-widget 
@requestnetwork/payment-widget:build: npm ERR! Lifecycle script `build` failed with error: 
@requestnetwork/payment-widget:build: npm ERR! Error: command failed 
@requestnetwork/payment-widget:build: npm ERR!   in workspace: @requestnetwork/[email protected] 
@requestnetwork/payment-widget:build: npm ERR!   at location: /home/mantisclone/projects/web-components/packages/payment-widget 
@requestnetwork/payment-widget:build: 
@requestnetwork/payment-widget:build: ERROR: command finished with error: command (/home/mantisclone/projects/web-components/packages/payment-widget) /home/mantisclone/.nvm/versions/node/v20.11.0/bin/npm run build exited (1)
@requestnetwork/payment-widget#build: command (/home/mantisclone/projects/web-components/packages/payment-widget) /home/mantisclone/.nvm/versions/node/v20.11.0/bin/npm run build exited (1)

 Tasks:    4 successful, 5 total
Cached:    0 cached, 5 total
  Time:    1m16.822s 
Failed:    @requestnetwork/payment-widget#build

 ERROR  run failed: command  exited (1)

@MantisClone
Copy link
Member

Switching accounts no longer causes the table to reload.

I still can't see the "encrypted 6" invoice when Alice is connected, even though it appears when connecting with Bob. - but I'm starting to think that this is not worth investigating any further.

I wasn't able to test creating encrypted requests due to 500 Internal Server errors on the Gnosis Gateway on Staging. 😩

I'll take another look tomorrow.

@MantisClone MantisClone marked this pull request as draft February 27, 2025 21:26
Changes to invoice-dashboard/src/lib/view-requests.svelte

1. **Added Request Network Polling Mechanism**:
   - Implemented a `waitForRequestNetwork` function that actively polls for the `requestNetwork` object to become available
   - Added configurable retry attempts (MAX_RETRY_ATTEMPTS = 10) and interval (RETRY_INTERVAL = 500ms)
   - The function returns a Promise that resolves to true if requestNetwork becomes available or false after max retries

2. **Enhanced Wallet Connection Handling**:
   - Modified `handleWalletConnection` to wait for requestNetwork availability before proceeding
   - Added clear error handling and user notifications when requestNetwork isn't available
   - Improved logic to prevent unnecessary reinitialization when connections are already established

3. **Added Proper Wallet Disconnection Handling**:
   - Implemented a robust `handleWalletDisconnection` function to clean up all wallet-related state
   - Properly resets account, requests, and other user-specific data
   - Cleans up Lit Protocol session data and disconnects any active providers
   - Called during manual disconnections, account changes, and component destruction

4. **Improved Wallet Change Handler**:
   - Updated `handleWalletChange` to use the new wallet disconnection function
   - Added more robust error handling around network operations
   - Simplified the code flow by extracting common clean-up tasks

5. **Enhanced Component Lifecycle Management**:
   - Added proper cleanup on component destruction via `onDestroy` hook
   - Improved component initialization with better error handling and logging
   - Added a delay during component mounting to allow dependencies to initialize properly

6. **Added JSDoc-style Documentation**:
   - Added detailed function documentation for key functions
   - Improved code readability with clear purpose statements for complex functions
   - Documented parameters and return values where applicable

7. **Added Reactive Network Change Detection**:
   - Added monitoring for changes in the requestNetwork object availability
   - Implemented a reactive block to detect when requestNetwork changes from null to defined
   - Added debug logging throughout the connection flow

8. **Fixed Race Condition**:
   - Resolved the race condition where wallet connections could occur before requestNetwork was ready
   - The retry mechanism ensures requests are loaded once both the account and requestNetwork are available

9. **Implemented Debugging Utilities**:
   - Added a `debugState` function to output component state for troubleshooting
   - Enhanced console logging throughout the component for better traceability

These changes collectively create a more robust solution that properly handles initialization order issues, cleans up resources appropriately, and provides better error reporting when things go wrong. The component now gracefully handles the situation where a wallet connects before the Request Network is fully initialized.
@MantisClone
Copy link
Member

MantisClone commented Feb 28, 2025

I fixed the Invoice Dashboard so that it loads unencrypted requests after the initial wallet connection. I implemented these changes using Claude 3.7 Sonnet. In doing so, I overhauled much of the wallet connection and lit session logic.

  1. Added Request Network Polling Mechanism:

    • Implemented a waitForRequestNetwork function that actively polls for the requestNetwork object to become available
    • Added configurable retry attempts (MAX_RETRY_ATTEMPTS = 10) and interval (RETRY_INTERVAL = 500ms)
    • The function returns a Promise that resolves to true if requestNetwork becomes available or false after max retries
  2. Enhanced Wallet Connection Handling:

    • Modified handleWalletConnection to wait for requestNetwork availability before proceeding
    • Added clear error handling and user notifications when requestNetwork isn't available
    • Improved logic to prevent unnecessary reinitialization when connections are already established
  3. Added Proper Wallet Disconnection Handling:

    • Implemented a robust handleWalletDisconnection function to clean up all wallet-related state
    • Properly resets account, requests, and other user-specific data
    • Cleans up Lit Protocol session data and disconnects any active providers
    • Called during manual disconnections, account changes, and component destruction
  4. Improved Wallet Change Handler:

    • Updated handleWalletChange to use the new wallet disconnection function
    • Added more robust error handling around network operations
    • Simplified the code flow by extracting common clean-up tasks
  5. Enhanced Component Lifecycle Management:

    • Added proper cleanup on component destruction via onDestroy hook
    • Improved component initialization with better error handling and logging
    • Added a delay during component mounting to allow dependencies to initialize properly
  6. Added JSDoc-style Documentation:

    • Added detailed function documentation for key functions
    • Improved code readability with clear purpose statements for complex functions
    • Documented parameters and return values where applicable
  7. Added Reactive Network Change Detection:

    • Added monitoring for changes in the requestNetwork object availability
    • Implemented a reactive block to detect when requestNetwork changes from null to defined
    • Added debug logging throughout the connection flow
  8. Fixed Race Condition:

    • Resolved the race condition where wallet connections could occur before requestNetwork was ready
    • The retry mechanism ensures requests are loaded once both the account and requestNetwork are available
  9. Implemented Debugging Utilities:

    • Added a debugState function to output component state for troubleshooting
    • Enhanced console logging throughout the component for better traceability

These changes collectively create a more robust solution that properly handles initialization order issues, cleans up resources appropriately, and provides better error reporting when things go wrong. The component now gracefully handles the situation where a wallet connects before the Request Network is fully initialized.

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. **Removed unnecessary awaits for `enableDecryption`**:
   - The `cipherProvider.enableDecryption()` method is not asynchronous, so I removed the `await` before these calls in the `initializeLitSession`, `loadRequests`, and other functions.

2. **Added user-friendly error toasts**:
   - Added more descriptive toast messages for common error scenarios in the Lit Protocol initialization
   - Added informative toast when a decryption session is reset due to address mismatch
   - Improved error messages in the `loadRequests` function

3. **Enhanced error handling**:
   - Added specific try/catch block for session signature requests
   - Provided more context in error messages to help users understand what went wrong
   - Made error messages more actionable with suggestions on how to resolve issues

4. **Improved error descriptions**:
   - Using the actual error message when available
   - Providing helpful fallback messages when the error doesn't have a message property
   - Including user-friendly suggestions for resolving common issues
@MantisClone MantisClone dismissed aimensahnoun’s stale review March 1, 2025 13:00

Many large changes have occurred since @aimensahnoun approved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants