Skip to content

fix: use justaname batch api call for resolving to ens#786

Merged
Hugo0 merged 2 commits intopeanut-wallet-devfrom
fix/justaname-batch-call
Apr 6, 2025
Merged

fix: use justaname batch api call for resolving to ens#786
Hugo0 merged 2 commits intopeanut-wallet-devfrom
fix/justaname-batch-call

Conversation

@kushagrasarathe
Copy link
Copy Markdown
Contributor

@kushagrasarathe kushagrasarathe commented Mar 31, 2025

  • now using justaname's batch usePrimaryNameBatch hook to resolve to ens names
  • contributes to TASK-10131
  • also fixes TASK-9912 : address resolution in link previews

Summary by CodeRabbit

  • New Features

    • Wallet displays now show more recognizable names by retrieving and displaying ENS names for wallet addresses. Users will see a primary name when available, with the address serving as a fallback.
  • Refactor

    • Updated the wallet display components to streamline data flow and consistently pass the primary name to wallet cards.
    • Simplified logic for retrieving primary names in the wallet display components.

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 31, 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 Apr 3, 2025 6:27pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 31, 2025

Walkthrough

This pull request integrates ENS name retrieval into the application by shifting the fetching logic from the WalletCard component into the parent pages. In the home page, a batch hook is used to obtain ENS names for multiple wallet addresses, while the wallet page employs a single-instance hook with an on-chain priority. Both pages then pass the resulting primaryName to the WalletCard component, which is updated to require this prop, streamlining its internal logic.

Changes

File(s) Change Summary
src/app/(mobile-ui)/home/page.tsx
src/app/(mobile-ui)/wallet/page.tsx
Added new imports and hook usage for ENS name fetching (usePrimaryNameBatch in home and usePrimaryName in wallet). Wallet addresses are processed to fetch primary ENS names, which are then passed as the primaryName prop (with a fallback to the address).
src/components/Home/WalletCard.tsx Updated the WalletCardWallet type to include primaryName: string and revised the getWalletDisplayInfo function signature. Removed the internal usePrimaryName hook, now relying on a prop-driven approach.
src/components/Global/ImageGeneration/LinkPreview.tsx Added import for usePrimaryName and updated the formatDisplayAddress function to utilize it for fetching primary names, while retaining existing address formatting logic.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant HP as HomePage Component
    participant B as usePrimaryNameBatch Hook
    participant WC as WalletCard Component

    U->>HP: Load Home Page
    HP->>HP: Map wallet addresses (useMemo)
    HP->>B: Fetch ENS names for addresses
    B-->>HP: Return allPrimaryNames
    HP->>WC: Pass primaryName prop to WalletCard
    WC-->>U: Render wallet with ENS names
Loading
sequenceDiagram
    participant U as User
    participant WP as WalletDetailsPage Component
    participant H as usePrimaryName Hook
    participant WC as WalletCard Component

    U->>WP: Open Wallet Details
    WP->>H: Retrieve primaryName for address (onChain priority)
    H-->>WP: Return primaryName
    WP->>WC: Pass primaryName prop to WalletCard
    WC-->>U: Render wallet with ENS name
Loading

Possibly related PRs

  • fix: don't shorten ens names #431: The changes in the main PR, which involve fetching and displaying ENS names for wallet addresses, are related to the retrieved PR that focuses on ensuring ENS names are not shortened, as both address the handling of ENS names in the user interface.
  • feat: justaname integration #664: The changes in the main PR are related to those in the retrieved PR as both involve the integration of the @justaname.id/react package to enhance wallet name resolution features, specifically through the use of hooks like usePrimaryNameBatch and usePrimaryName.

Suggested reviewers

  • Hugo0
  • jjramirezn

Poem

I hop through fields of code with cheer,
Fetching ENS names to make the path clear.
Wallets now wear a brighter name,
Replacing addresses with a flair so tame.
I'm a coding rabbit, joyfully on my way! 🐰

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 plan to trigger planning for file edits and PR creation.
  • @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.

@notion-workspace
Copy link
Copy Markdown

Copy link
Copy Markdown
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)
src/components/Home/WalletCard.tsx (1)

337-337: Consider adding more robust nullish checking.

While the function signature has been correctly updated to require primaryName, the implementation could be more robust when handling potential edge cases.

function getWalletDisplayInfo(wallet: IWallet, username: string, primaryName: string, isRewardsWallet: boolean) {
    // ...
    return {
-        displayName: primaryName || shortenAddressLong(wallet.address),
-        copyText: primaryName || wallet.address,
+        displayName: primaryName && primaryName.trim() ? primaryName : shortenAddressLong(wallet.address),
+        copyText: primaryName && primaryName.trim() ? primaryName : wallet.address,
    }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e3f00b0 and 8525786.

📒 Files selected for processing (3)
  • src/app/(mobile-ui)/home/page.tsx (3 hunks)
  • src/app/(mobile-ui)/wallet/page.tsx (3 hunks)
  • src/components/Home/WalletCard.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview
🔇 Additional comments (8)
src/app/(mobile-ui)/wallet/page.tsx (3)

20-20: Good addition of the ENS resolution library.

Adding the usePrimaryName hook from justaname.id is appropriate for enabling ENS name resolution functionality.


42-45: Well implemented ENS resolution.

The implementation of the usePrimaryName hook with 'onChain' priority is a good approach for fetching ENS names. The hook is correctly set up to use the wallet address when available.


149-149: Proper fallback for primaryName.

Good implementation of passing the primaryName to the WalletCard component with a fallback to the wallet's address if primaryName is null or undefined.

src/app/(mobile-ui)/home/page.tsx (3)

21-21: Good choice of batch API.

Using the batch version of the justaname API is appropriate for this context where multiple wallet addresses need to be resolved.


51-55: Efficient implementation of batch ENS resolution.

The implementation is well-structured:

  1. Using useMemo for the wallet addresses array is efficient
  2. The batch hook is properly configured with the enabled flag
  3. This approach is more efficient than making individual calls for each wallet

235-235: Correct usage of batch resolution results.

The primary name is correctly retrieved from the allPrimaryNames object using the wallet address as a key, with a proper fallback to the wallet address if no ENS name is found.

src/components/Home/WalletCard.tsx (2)

35-35: Interface update correctly reflects new requirements.

Adding the primaryName property to the WalletCardWallet interface ensures type safety and makes the dependency on this property explicit.


77-77: Component structure improved.

The component now receives the primaryName as a prop rather than fetching it internally, which is a good separation of concerns.

@notion-workspace
Copy link
Copy Markdown

Copy link
Copy Markdown
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

🔭 Outside diff range comments (2)
src/components/Global/ImageGeneration/LinkPreview.tsx (2)

20-37: ⚠️ Potential issue

Critical issue: React hook used inside a regular function

The usePrimaryName hook is being called inside the formatDisplayAddress function, which violates React's Rules of Hooks. Hooks can only be called from React function components or custom hooks (names starting with "use").

This will cause unpredictable behavior in your application. Here's how to fix it:

- function formatDisplayAddress(address: string): string {
-     const { primaryName } = usePrimaryName({
-         address,
-         priority: 'onChain',
-     })
- 
-     if (primaryName) {
-         return primaryName
-     }
- 
+// Separate hook function that can be used in components
+export function useFormattedAddress(address: string): string {
+    const { primaryName } = usePrimaryName({
+        address,
+        priority: 'onChain',
+    })
+    
+    return formatDisplayAddress(address, primaryName)
+}
+
+// Pure function that doesn't use hooks
+function formatDisplayAddress(address: string, primaryName?: string | null): string {
+    if (primaryName) {
+        return primaryName
+    }
+
     if (address.startsWith('0x')) {
         if (isAddress(address)) {
             return printableAddress(address)
         }
         return address
     }
     return address
 }

Then, modify the component to use the new hook:

 <label style={{ fontSize: '16px', fontWeight: 'bold', color: 'black' }}>
-    {formatDisplayAddress(address)}{' '}
+    {useFormattedAddress(address)}{' '}
     {showEmptyAmountMessage
         ? PREVIEW_TYPES[previewType].emptyAmountMessage
         : PREVIEW_TYPES[previewType].message}
 </label>

39-124: 🛠️ Refactor suggestion

Update the LinkPreviewImg component to use the new hook pattern

The LinkPreviewImg component also needs to be updated to properly use the ENS resolution via a hook at the component level rather than within the formatDisplayAddress function.

Here's how to refactor the component:

 export function LinkPreviewImg({
     amount,
     tokenSymbol,
     address,
     previewType,
 }: {
     amount: string
     tokenSymbol?: string
     address: string
     previewType: PreviewType
 }) {
+    // Use the hook at component level
+    const { primaryName } = usePrimaryName({
+        address,
+        priority: 'onChain',
+    })
+    
+    const formattedAddress = formatDisplayAddress(address, primaryName)
     
     const previewBg = `${
         process.env.NEXT_PUBLIC_VERCEL_URL
             ? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
             : process.env.NEXT_PUBLIC_BASE_URL
     }/social-preview-bg.png`

     const isEmptyAmount = !amount || parseFloat(amount) === 0
     const showEmptyAmountMessage = previewType === PreviewType.REQUEST && isEmptyAmount

     // Rest of the component...

     // In the JSX where address is displayed:
     <label style={{ fontSize: '16px', fontWeight: 'bold', color: 'black' }}>
-        {formatDisplayAddress(address)}{' '}
+        {formattedAddress}{' '}
         {showEmptyAmountMessage
             ? PREVIEW_TYPES[previewType].emptyAmountMessage
             : PREVIEW_TYPES[previewType].message}
     </label>

This approach ensures the hook is called at the component level, following React's rules of hooks, while still providing the ENS name resolution functionality.

🧹 Nitpick comments (2)
src/components/Global/ImageGeneration/LinkPreview.tsx (2)

21-24: Consider adding error handling for the ENS resolution

The current implementation doesn't handle potential errors that might occur during ENS name resolution.

 // In the refactored component
 export function LinkPreviewImg({...}) {
+    const [error, setError] = useState<Error | null>(null);
     const { primaryName, error: ensError } = usePrimaryName({
         address,
         priority: 'onChain',
+        onError: (err) => {
+            console.error('Error resolving ENS name:', err);
+            setError(err);
+        }
     })
     
+    // Handle error state if needed
+    useEffect(() => {
+        if (ensError) {
+            console.warn('Failed to resolve ENS name:', ensError);
+        }
+    }, [ensError]);
     
     const formattedAddress = formatDisplayAddress(address, primaryName)

This ensures any issues with the ENS resolution are properly logged and don't silently fail.


2-2: Consider using the batch hook for better performance

According to the PR objectives, this PR is about implementing justaname's batch API call. While you're importing the single-address hook here, consider if this component would benefit from the batch implementation as mentioned in the AI summary.

If multiple instances of LinkPreviewImg are rendered simultaneously with different addresses, using the batch hook usePrimaryNameBatch might be more efficient than making separate API calls for each address.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8525786 and 723ff8e.

📒 Files selected for processing (1)
  • src/components/Global/ImageGeneration/LinkPreview.tsx (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/components/Global/ImageGeneration/LinkPreview.tsx (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#460
File: src/components/Global/ImageGeneration/LinkPreview.tsx:125-128
Timestamp: 2025-04-02T19:11:13.628Z
Learning: 'tokenPrice' is not used currently and will be removed in future PRs.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Deploy-Preview

Copy link
Copy Markdown
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.

good initiative!

@Hugo0 Hugo0 merged commit 30e277f into peanut-wallet-dev Apr 6, 2025
5 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Apr 8, 2025
@Hugo0 Hugo0 deleted the fix/justaname-batch-call branch July 3, 2025 18:24
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