Skip to content

Conversation

jjramirezn
Copy link
Contributor

No description provided.

Copy link

vercel bot commented May 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 15, 2025 2:54pm

@jjramirezn jjramirezn requested a review from Hugo0 May 15, 2025 14:37
Copy link
Contributor

coderabbitai bot commented May 15, 2025

## Walkthrough

The changes introduce WebSocket-based real-time transaction updates to the application. This includes updating environment variables for API and WebSocket URLs, adding a new WebSocket service and hook, and modifying the `HomeHistory` component to merge live transaction data with initially fetched history. No changes were made to error or loading state handling.

## Changes

| Files/Paths                     | Change Summary                                                                                                                                                                                                                           |
|--------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `.env.example`                  | Updated `PEANUT_API_URL` and `NEXT_PUBLIC_PEANUT_API_URL` to use the `peanut.me` domain. Added a new `NEXT_PUBLIC_PEANUT_WS_URL` variable for the WebSocket endpoint.                                                                   |
| `src/components/Home/HomeHistory.tsx` | Modified `HomeHistory` to integrate real-time transaction updates via WebSocket, merging live entries with fetched history and updating filtering, rendering, and state logic accordingly.                                         |
| `src/hooks/useWebSocket.ts`     | Added new `useWebSocket` React hook to manage WebSocket connection lifecycle, track status, handle incoming messages, and provide control functions and history state to components.                                                   |
| `src/services/websocket.ts`     | Introduced `PeanutWebSocket` class implementing WebSocket connection with automatic reconnection, heartbeat pings, event-driven message handling, and a singleton accessor for shared usage.                                           |

## Suggested reviewers

- kushagrasarathe

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 78435a5 and 459e70b.

📒 Files selected for processing (2)
  • src/hooks/useWebSocket.ts (1 hunks)
  • src/services/websocket.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/hooks/useWebSocket.ts
  • src/services/websocket.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

Copy link

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: 7

🔭 Outside diff range comments (1)
.env.example (1)

17-37: 🛠️ Refactor suggestion

Duplicate NEXT_PUBLIC_INFURA_API_KEY entry may cause subtle config bugs

NEXT_PUBLIC_INFURA_API_KEY is declared twice (line 17 and line 37).
When developers source this file with bash -a or similar, the second assignment silently overrides the first one, which can be confusing and lead to environment–specific “works-on-my-machine” issues.

-export NEXT_PUBLIC_INFURA_API_KEY=""
...
-export NEXT_PUBLIC_INFURA_API_KEY=""

Remove the duplicate or add an inline comment clarifying why two assignments are necessary.

🧹 Nitpick comments (7)
src/services/websocket.ts (2)

145-160: Exponential back-off grows without an upper cap

this.reconnectDelay * 2^n doubles indefinitely until the hard limit of maxReconnectAttempts, but if maxReconnectAttempts is increased in the future you may quickly exceed browser limits (~24 days). Consider clamping to, say, 30 s.

Not critical for maxReconnectAttempts = 5, just a maintainability note.


67-79: Memory leak risk when many components add listeners

on/off store callbacks in a Set, but disconnect() never purges eventListeners. If the singleton lives for the entire session, stale callbacks accumulate as pages mount/unmount.

Either:

  1. Clear eventListeners inside disconnect(), or
  2. Document that consumers must call off in useEffect clean-ups.
src/components/Home/HomeHistory.tsx (2)

40-48: Mutating wsEntry breaks immutability & may trigger unexpected re-renders

You directly mutate objects from the hook (wsEntry.extraData = …). If another component relies on referential equality of that array, this introduces subtle bugs.

const cloned = { ...wsEntry, extraData: { ...wsEntry.extraData, usdAmount: wsEntry.amount.toString() } }
entries.unshift(cloned)

Avoid in-place mutation.


145-153: filteredEntries is recomputed inside every iteration

filteredEntries has the same value for each map pass; compute it once outside the loop to avoid unnecessary array allocations.

const displayEntries = combinedEntries.filter(
    (entry) => !pendingRequests.some((r) => r.uuid === entry.uuid)
)

displayEntries.map((item, index) => {
    // …
})

Tiny optimisation but keeps the render path clean.

src/hooks/useWebSocket.ts (3)

20-20: Consider adding pagination or limit for history entries

The current implementation stores all history entries in memory without any limit, which could lead to excessive memory usage if the connection stays open for a long time and receives many entries.

Consider either:

  1. Implementing a max length for the history entries array
  2. Adding pagination support
  3. Using a more memory-efficient data structure

Example implementation with a max length:

-const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([])
+const [historyEntries, setHistoryEntries] = useState<HistoryEntry[]>([])
+const MAX_HISTORY_ENTRIES = 50 // Or any appropriate number

Then in the handleHistoryEntry function:

-setHistoryEntries((prev) => [entry, ...prev])
+setHistoryEntries((prev) => [entry, ...prev].slice(0, MAX_HISTORY_ENTRIES))

29-41: Potential duplication in WebSocket initialization

The WebSocket instance is initialized both in the connect function and at the beginning of the main effect. While this approach works because getWebSocketInstance returns a singleton, it could be confusing and potentially lead to issues if the implementation of getWebSocketInstance changes.

Consider refactoring to initialize the WebSocket only once in the main effect, and have the connect function use the ref:

const connect = useCallback(() => {
    try {
-       const ws = getWebSocketInstance(username)
-       wsRef.current = ws
+       if (!wsRef.current) {
+           wsRef.current = getWebSocketInstance(username)
+       }
+       const ws = wsRef.current

        setStatus('connecting')
        ws.connect()
    } catch (error) {
        console.error('Failed to connect to WebSocket:', error)
        setStatus('error')
    }
}, [username])

Also applies to: 51-55


16-115: Add support for testing with mocks

The current implementation doesn't have an easy way to mock the WebSocket for testing purposes. This could make unit testing components that use this hook challenging.

Consider adding an optional parameter to inject a mock WebSocket instance for testing:

-export const useWebSocket = (options: UseWebSocketOptions = {}) => {
+export const useWebSocket = (
+   options: UseWebSocketOptions = {},
+   websocketFactory: (username?: string) => PeanutWebSocket = getWebSocketInstance
+) => {
    const { autoConnect = true, username, onHistoryEntry, onConnect, onDisconnect, onError } = options

    // ...

    // Then replace all instances of getWebSocketInstance with websocketFactory
    // For example:
    const connect = useCallback(() => {
        try {
-           const ws = getWebSocketInstance(username)
+           const ws = websocketFactory(username)
            wsRef.current = ws
            // ...

This allows tests to inject a mock implementation:

// In a test file
test('useWebSocket handles history entries correctly', () => {
  const mockWs = {
    connect: jest.fn(),
    disconnect: jest.fn(),
    on: jest.fn(),
    off: jest.fn(),
    // other methods
  };
  const mockFactory = () => mockWs;
  
  const { result } = renderHook(() => useWebSocket({}, mockFactory));
  
  // Now you can test the hook with the mock
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73495af and 95e9ad7.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • src/components/Home/HomeHistory.tsx (6 hunks)
  • src/hooks/useWebSocket.ts (1 hunks)
  • src/services/websocket.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/hooks/useWebSocket.ts (2)
src/hooks/useTransactionHistory.ts (1)
  • HistoryEntry (31-67)
src/services/websocket.ts (5)
  • PeanutWebSocket (8-187)
  • connect (24-44)
  • getWebSocketInstance (192-200)
  • disconnect (46-65)
  • handleError (126-129)
src/services/websocket.ts (1)
src/hooks/useTransactionHistory.ts (1)
  • HistoryEntry (31-67)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (2)
.env.example (1)

1-3: Confirm the staging URL & protocol are correct

Moving from peanut.topeanut.me and adding a wss:// endpoint looks intentional, but please make sure:

  1. DNS + TLS are already configured for api.staging.peanut.me.
  2. The backend actually accepts WebSocket traffic on that port / path; otherwise initial socket connections will fail silently at runtime.

No action needed if you already verified this.

src/hooks/useWebSocket.ts (1)

1-115: Overall implementation is well-structured

The hook is implemented with good practices:

  • Uses appropriate React hooks (useState, useCallback, useEffect, useRef)
  • Properly manages closures with refs to prevent stale callbacks
  • Has clear separation of concerns
  • Includes helpful comments
  • Carefully manages WebSocket connection lifecycle
  • Allows connection sharing between components

@jjramirezn jjramirezn force-pushed the feat/charges-websocket branch from 95e9ad7 to 78435a5 Compare May 15, 2025 14:42
Comment on lines +23 to +26
// WebSocket for real-time updates
const { historyEntries: wsHistoryEntries } = useWebSocket({
username, // Pass the username to the WebSocket hook
onHistoryEntry: useCallback(() => {
Copy link
Contributor

Choose a reason for hiding this comment

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

thought: auth

Copy link
Contributor Author

Choose a reason for hiding this comment

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

agree

Comment on lines +8 to +17
export class PeanutWebSocket {
private socket: WebSocket | null = null
private pingInterval: NodeJS.Timeout | null = null
private reconnectTimeout: NodeJS.Timeout | null = null
private eventListeners: Map<string, Set<(data: any) => void>> = new Map()
private isConnected = false
private reconnectAttempts = 0
private readonly maxReconnectAttempts = 5
private readonly reconnectDelay = 3000 // 3 seconds
private readonly pingIntervalTime = 30000 // 30 seconds
Copy link
Contributor

Choose a reason for hiding this comment

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

would be nice to justify these vars. is 3s normal? 5 attempts? whats reasonable

Comment on lines +94 to +97
case 'pong':
// Server responded to our ping
this.emit('pong', null)
break
Copy link
Contributor

Choose a reason for hiding this comment

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

wat?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

to anyone that is listening to this evenemitter, I emit that I received a pong

export const getWebSocketInstance = (username?: string): PeanutWebSocket => {
if (!websocketInstance && typeof window !== 'undefined') {
const wsUrl = process.env.NEXT_PUBLIC_PEANUT_WS_URL || ''
const path = username ? `/ws/charges/${username}` : '/ws/charges'
Copy link
Contributor

Choose a reason for hiding this comment

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

thought: we should also have an endpoint for /ws/ that just gives us all events we need for a single user

Copy link
Contributor

@Hugo0 Hugo0 left a comment

Choose a reason for hiding this comment

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

thought: make a task for manu to design some cool dynamic movement for when a new event comes in

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.

2 participants