Skip to content

fix: safeguard against getEtherspotProvider crash in delegated mode#503

Merged
aldin4u merged 4 commits intostagingfrom
fix/delegated-eoa-signing
Feb 3, 2026
Merged

fix: safeguard against getEtherspotProvider crash in delegated mode#503
aldin4u merged 4 commits intostagingfrom
fix/delegated-eoa-signing

Conversation

@aldin4u
Copy link
Collaborator

@aldin4u aldin4u commented Feb 3, 2026

Description

How Has This Been Tested?

Screenshots (if appropriate):

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling in the delegated wallet fallback so failures when retrieving the wallet address or initializing the wallet client are caught and logged instead of crashing, reducing disruption in delegation scenarios.
  • New Features

    • Added an algorithm insights stats hook that provides PnL metrics (1m/3m/6m), win/loss status, risk level placeholder, and cumulative PnL histories with a loading guard for use in UI displays.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 3, 2026

📝 Walkthrough

Walkthrough

Adds a new hook useAlgoInsightsStats that computes PnL summaries and cumulative history from trading signals, and hardens the delegatedEoa fallback in useHyperliquid.ts by wrapping wallet-provider EOA retrieval and wallet client creation in a try/catch and logging warnings on failure. (39 words)

Changes

Cohort / File(s) Summary
Delegated EOA error handling
src/apps/perps/hooks/useHyperliquid.ts
Wrapped wallet-provider EOA retrieval and wallet client creation in a try/catch in the delegatedEoa fallback path; failures are logged as warnings instead of being thrown.
New algorithm insights hook
src/apps/pillarx-app/hooks/useAlgoInsightsStats.ts
Added useAlgoInsightsStats hook and AlgoInsightsStats interface: subscribes to trading signals, computes 1m/3m/6m PnL, derives pnlStatus and riskLevel, and builds cumulative PnL histories (1w,1m,3m,6m). Memoized and returns { stats, loading }.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I nibble logs and count the gains,
From tiny hops through signal plains.
If wallets trip, I warn and stay —
Then tally PnL along the way. ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description is entirely empty except for the template skeleton. All required sections (Description, How Has This Been Tested, and Types of changes) lack any substantive content or details. Add a description of the changes and rationale for the fix, detail the testing approach, and mark the appropriate type of change checkbox (Bug fix).
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: safeguard against getEtherspotProvider crash in delegated mode' is specific and clearly relates to the main change: adding error handling in useHyperliquid's delegatedEoa path to prevent crashes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/delegated-eoa-signing

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Feb 3, 2026

Deploying x with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0b8260f
Status: ✅  Deploy successful!
Preview URL: https://e36bae58.x-e62.pages.dev
Branch Preview URL: https://fix-delegated-eoa-signing.x-e62.pages.dev

View logs

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Feb 3, 2026

Deploying pillarx-debug with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0b8260f
Status: ✅  Deploy successful!
Preview URL: https://1f4c7781.pillarx-debug.pages.dev
Branch Preview URL: https://fix-delegated-eoa-signing.pillarx-debug.pages.dev

View logs

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

🤖 Fix all issues with AI agents
In `@src/apps/perps/hooks/useHyperliquid.ts`:
- Around line 79-80: The hook useHyperliquid contains a duplicated `else` token
causing a parse error; locate the conditional block inside useHyperliquid (the
`if ... else` chain around the lines with the duplicated `else`) and remove the
extra `else` so the control flow has a single matching `else` block (or merge
the intended logic into one `else` branch), ensuring braces remain balanced and
the function compiles.

@github-actions github-actions bot temporarily deployed to Preview (fix/delegated-eoa-signing) February 3, 2026 12:36 Inactive
@github-actions github-actions bot temporarily deployed to Preview (fix/delegated-eoa-signing) February 3, 2026 12:53 Inactive
@github-actions github-actions bot temporarily deployed to Preview (fix/delegated-eoa-signing) February 3, 2026 13:49 Inactive
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

🤖 Fix all issues with AI agents
In `@src/apps/pillarx-app/hooks/useAlgoInsightsStats.ts`:
- Around line 23-27: The hook useAlgoInsightsStats currently ignores the error
returned by useTradingSignals; destructure the error (e.g., const { signals,
loading, error } = useTradingSignals({ enabled: true })) and propagate it in the
hook's return value so consumers can distinguish fetch failures from empty data
(update the returned shape to include error alongside stats and loading, and
ensure stats remains null when loading or error is present). Ensure references
to useAlgoInsightsStats and useTradingSignals are updated so callers can handle
error state.
🧹 Nitpick comments (3)
src/apps/pillarx-app/hooks/useAlgoInsightsStats.ts (3)

107-109: Remove leftover comment/question.

This appears to be a development note that should be resolved and removed before merging.

🧹 Proposed cleanup
       });

-      // Ensure we have a starting point? Or just the trade history.
-      // If history is empty, return empty array
       return history;
     };

119-119: Track the placeholder riskLevel implementation.

The hardcoded 'Low Risk' value is noted as placeholder logic. Consider adding a TODO comment with context or creating an issue to track the proper implementation.

📝 Suggested documentation
-      riskLevel: 'Low Risk', // Placeholder logic
+      // TODO: Implement risk level calculation based on portfolio volatility/exposure
+      riskLevel: 'Low Risk',

126-136: Consider extracting 1w calculation for consistency.

The 1w period calculates its value inline while 1m, 3m, and 6m use pre-computed variables. This inconsistency slightly reduces readability and maintainability.

♻️ Optional refactor for consistency

Add a pre-computed variable alongside the others at lines 36-39:

     const now = Date.now();
+    const oneWeekAgo = now - 7 * 24 * 60 * 60 * 1000;
     const oneMonthAgo = now - 30 * 24 * 60 * 60 * 1000;

Add the 1w PnL calculation alongside lines 42-55:

+    const pnl1w = calculatePnL((s) => {
+      const closedAt = s.closed_at ? new Date(s.closed_at).getTime() : 0;
+      return closedAt > oneWeekAgo;
+    });
+
     const pnl1m = calculatePnL((s) => {

Then simplify the return:

         '1w': {
-          value: Number(
-            calculatePnL((s) =>
-              s.closed_at
-                ? new Date(s.closed_at).getTime() >
-                  now - 7 * 24 * 60 * 60 * 1000
-                : false
-            ).toFixed(2)
-          ),
-          history: generateHistory(now - 7 * 24 * 60 * 60 * 1000),
+          value: Number(pnl1w.toFixed(2)),
+          history: generateHistory(oneWeekAgo),
         },

Comment on lines +23 to +27
export const useAlgoInsightsStats = () => {
const { signals, loading } = useTradingSignals({ enabled: true });

const stats = useMemo<AlgoInsightsStats | null>(() => {
if (loading || signals.length === 0) return null;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Missing error state propagation.

The useTradingSignals hook returns an error state (per the relevant code snippet), but it's not destructured or exposed. If signal fetching fails, consumers cannot distinguish between "no data available" and "fetch error occurred" since both result in stats: null.

Consider exposing the error state:

🛡️ Proposed fix to propagate error state
 export const useAlgoInsightsStats = () => {
-  const { signals, loading } = useTradingSignals({ enabled: true });
+  const { signals, loading, error } = useTradingSignals({ enabled: true });

   const stats = useMemo<AlgoInsightsStats | null>(() => {
     // ...existing code...
   }, [signals, loading]);

-  return { stats, loading };
+  return { stats, loading, error };
 };
🤖 Prompt for AI Agents
In `@src/apps/pillarx-app/hooks/useAlgoInsightsStats.ts` around lines 23 - 27, The
hook useAlgoInsightsStats currently ignores the error returned by
useTradingSignals; destructure the error (e.g., const { signals, loading, error
} = useTradingSignals({ enabled: true })) and propagate it in the hook's return
value so consumers can distinguish fetch failures from empty data (update the
returned shape to include error alongside stats and loading, and ensure stats
remains null when loading or error is present). Ensure references to
useAlgoInsightsStats and useTradingSignals are updated so callers can handle
error state.

@aldin4u aldin4u merged commit 4e87410 into staging Feb 3, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant