Skip to content

feat: WalletLinkForm support ens domain #121

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

Dangoz
Copy link
Contributor

@Dangoz Dangoz commented Jun 2, 2025

Integrate Ethereum Name Service to WalletLinkForm.

On /profile/edit page, Instead of inputting user's full wallet address, user will also be able to reference one's wallet address by providing an ENS domain.
Considering the risk that an ENS domain gets expired or transferred and the user neglects to adjust one's README.md hidden comment, ENS is only used for initially getting the corresponding wallet address on WalletLinkForm, anything beyond resolves to the raw address.
ens

If this flow makes sense, the same can perhaps be done for SNS (Solana Name Service)

Resolve #120

Summary by CodeRabbit

  • New Features

    • Added support for linking Ethereum and Solana wallets using human-readable domain names (ENS for Ethereum and SNS for Solana) in addition to raw addresses.
    • Wallet linking forms now validate and resolve ENS and SNS domains to their underlying blockchain addresses.
  • Bug Fixes

    • Improved wallet address validation by making it asynchronous, ensuring more accurate validation and error handling.
  • Chores

    • Added new dependencies to enable ENS and SNS domain resolution and validation.

Copy link

coderabbitai bot commented Jun 2, 2025

Walkthrough

The changes introduce asynchronous validation and resolution of wallet addresses, allowing users to input either raw blockchain addresses or human-readable ENS/SNS domain names. New utilities for ENS and SNS resolution and validation are added, and relevant code paths are updated to support async workflows and store resolved domain names alongside addresses.

Changes

File(s) Change Summary
package.json Added @bonfida/spl-name-service and @solana/web3.js dependencies.
src/app/profile/edit/components/WalletLinkForm.tsx Enhanced wallet input validation and resolution for ENS/SNS domains; updated placeholders and logic.
src/app/profile/edit/hooks/useProfileWallets.ts Awaited async wallet parsing function.
src/lib/pipelines/ingest/fetchWalletAddresses.ts Made wallet address validation asynchronous.
src/lib/walletLinking/chainUtils.ts Refactored validators to async; dynamic imports and error handling for address validation.
src/lib/walletLinking/domain.ts New module: async ENS/SNS resolution and format validation functions.
src/lib/walletLinking/fetchWalletDataFromGithub.ts Awaited async wallet parsing function.
src/lib/walletLinking/readmeUtils.ts Made wallet parsing async; supported ENS/SNS names in wallet schema and serialization.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WalletLinkForm
    participant DomainUtils
    participant ChainUtils

    User->>WalletLinkForm: Enter wallet (address or ENS/SNS)
    WalletLinkForm->>DomainUtils: Validate format (ENS/SNS)
    alt Domain name
        WalletLinkForm->>DomainUtils: Resolve ENS/SNS to address
        DomainUtils-->>WalletLinkForm: Return resolved address or error
    else Raw address
        WalletLinkForm->>ChainUtils: Validate address asynchronously
        ChainUtils-->>WalletLinkForm: Return validation result
    end
    WalletLinkForm-->>User: Show validation result or error
Loading

Assessment against linked issues

Objective Addressed Explanation
Allow wallet address resolution via ENS (#120)

Poem

ENS and SNS, what a pair,
Now wallet linking’s less of a bear!
Async checks and names resolve,
Blockchain puzzles, we now solve.
With code that’s nimble, smart, and neat,
Linking wallets is a treat! 🚀

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/app/profile/edit/hooks/useProfileWallets.ts

Oops! Something went wrong! :(

ESLint: 9.29.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)

src/app/profile/edit/components/WalletLinkForm.tsx

Oops! Something went wrong! :(

ESLint: 9.29.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)

src/lib/walletLinking/domain.ts

Oops! Something went wrong! :(

ESLint: 9.29.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:801:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:725:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:708:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:309:38)
at #link (node:internal/modules/esm/module_job:202:49)

  • 4 others
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

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 auto-generate unit tests to generate unit tests 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.

@MonteCrypto999
Copy link
Contributor

MonteCrypto999 commented Jun 2, 2025

The code looks fine. It would be good to also do it for .sol name as well not just for .eth

@MonteCrypto999
Copy link
Contributor

Just a quick addition regarding optimization and the vem package — I noticed the package is quite large considering it's only used for ENS fetching. It might be more efficient to simply perform a GET request to a public gateway like this:

REQ
https://api.ensideas.com/ens/resolve/alice.eth

RES
{"address":"0xcd2E72aEBe2A203b84f46DEEC948E6465dB51c75","name":"alice.eth","displayName":"alice.eth","avatar":"https://metadata.ens.domains/mainnet/avatar/alice.eth"}

@madjin
Copy link
Contributor

madjin commented Jun 2, 2025

I like the redundancy / risk mitigation measure of including the raw address also

@Dangoz
Copy link
Contributor Author

Dangoz commented Jun 5, 2025

I've updated a commit for supporting SNS.
sns

Regarding viem package's impact on build size. Here is a screenshot of two builds, the left one without viem, the right one with viem. The page to inspect is /profile/edit.
Screenshot 2025-06-05 at 1 44 02 PM

Currently, the changes for ENS support without viem are not yet committed, as I would like advice.
The tradeoff is that:

@madjin
Copy link
Contributor

madjin commented Jun 7, 2025

Linking the docs here for reference / research: https://docs.ens.domains/web/resolution

@MonteCrypto999
Copy link
Contributor

I've updated a commit for supporting SNS. sns sns

Regarding viem package's impact on build size. Here is a screenshot of two builds, the left one without viem, the right one with viem. The page to inspect is /profile/edit. Screenshot 2025-06-05 at 1 44 02 PM

Currently, the changes for ENS support without viem are not yet committed, as I would like advice. The tradeoff is that:

Looks like viem is more robust for resolution atm even if it costs the build size. Sol code looks good too.

@META-DREAMER
Copy link
Collaborator

Want to take a step back first and properly architect how we store and fetch walletAddresses to be chain agnostic and cleanly handle multichain (esp relevant for ETH L2s). See comment here on storing ensName / snsName in the user table and adding a separate walletAddresses table using CAIP-2 / CAIP-10

With ENS names, there's a lot more to it than just linking it to a single address, since a name can now store profile info and also addresses for different chains etc. Therefore I think ens/sns names should be stored at the user level and not alongside wallet addresses. That way we can derive many addresses (and other info) for a certain user from their ENS.

@MonteCrypto999
Copy link
Contributor

MonteCrypto999 commented Jun 9, 2025

True, global storage better for multiple usecases like this checkmark but if you have planned an upcoming airdrop it can be good to have a very primitive version first to onboard more people for this batch.

@Dangoz
Copy link
Contributor Author

Dangoz commented Jun 9, 2025

Thank you for the feedback!

For ENS/SNS names, the current relevant user flow is that:
An authenticated user arrives at /profile/edit page -> user enters one's ENS/SNS domain name -> the domain name is resolved to the corresponding wallet address -> user can copy/paste the hidden comment containing the address & domain name, and save it to one's Github Profile README.

The above flow only uses them for resolving wallet addresses that would be linked client-side.
If I'm understanding correctly, since the project is statically exported, there isn't a live server that can listen to requests for saving the domain names to database during the above process.
I understand and agree with the merits of how ENS can be used for much more, but I'm not sure where and when to save/retrieve the domain names to database, with regard to user flow.

@META-DREAMER
Copy link
Collaborator

Thank you for the feedback!

For ENS/SNS names, the current relevant user flow is that: An authenticated user arrives at /profile/edit page -> user enters one's ENS/SNS domain name -> the domain name is resolved to the corresponding wallet address -> user can copy/paste the hidden comment containing the address & domain name, and save it to one's Github Profile README.

The above flow only uses them for resolving wallet addresses that would be linked client-side. If I'm understanding correctly, since the project is statically exported, there isn't a live server that can listen to requests for saving the domain names to database during the above process. I understand and agree with the merits of how ENS can be used for much more, but I'm not sure where and when to save/retrieve the domain names to database, with regard to user flow.

Ah ok, I see what you're saying now, its needed to resolve names on client side to validate them before saving them to github. In that case, as long as we make sure that code splitting / dynamic module loading is setup properly so that it only loads viem once the user is logged in and on the update address page, then it shouldn't have negative impact on majority of users.

@Dangoz
Copy link
Contributor Author

Dangoz commented Jun 24, 2025

A commit is made to dynamically import domain name resolution dependencies for ENS (viem) and SNS (@solana/web3.js, @bonfida/spl-name-service)

The following are the build output before and after the commit (particularly for the page /profile/edit)

Before:
Screenshot 2025-06-24 at 11 09 40 AM

After:
Screenshot 2025-06-24 at 11 00 39 AM

@Dangoz Dangoz force-pushed the link-wallet-from-ens branch from 1b815dc to 5fbe057 Compare June 26, 2025 04:35
@META-DREAMER
Copy link
Collaborator

@coderabbitai review

Copy link

coderabbitai bot commented Jun 26, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

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

🧹 Nitpick comments (2)
src/lib/walletLinking/domain.ts (2)

14-30: Remove unnecessary continue statement

The continue is redundant as it's the last statement in the loop.

     } catch (error) {
       console.warn(`Failed to connect to RPC endpoint ${endpoint}:`, error);
-      continue; // Try next endpoint
     }

87-101: Consider supporting broader character sets for ENS

ENS supports Unicode and underscores, but current regex is ASCII-only.

Would you like me to provide a more comprehensive ENS validation regex that supports Unicode characters?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 00288f3 and 5fbe057.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • package.json (2 hunks)
  • src/app/profile/edit/components/WalletLinkForm.tsx (5 hunks)
  • src/app/profile/edit/hooks/useProfileWallets.ts (1 hunks)
  • src/lib/pipelines/ingest/fetchWalletAddresses.ts (1 hunks)
  • src/lib/walletLinking/chainUtils.ts (3 hunks)
  • src/lib/walletLinking/domain.ts (1 hunks)
  • src/lib/walletLinking/fetchWalletDataFromGithub.ts (1 hunks)
  • src/lib/walletLinking/readmeUtils.ts (4 hunks)
🧰 Additional context used
🧠 Learnings (1)
package.json (1)
Learnt from: CR
PR: elizaOS/elizaos.github.io#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T18:24:14.074Z
Learning: Import order in TypeScript/React files should be: React, external libraries, local components (using @/components), then utility functions, to improve readability and maintainability.
🧬 Code Graph Analysis (5)
src/lib/walletLinking/fetchWalletDataFromGithub.ts (1)
src/lib/walletLinking/readmeUtils.ts (1)
  • parseWalletLinkingDataFromReadme (32-83)
src/lib/pipelines/ingest/fetchWalletAddresses.ts (1)
src/lib/walletLinking/chainUtils.ts (1)
  • validateAddress (116-126)
src/app/profile/edit/hooks/useProfileWallets.ts (1)
src/lib/walletLinking/readmeUtils.ts (1)
  • parseWalletLinkingDataFromReadme (32-83)
src/app/profile/edit/components/WalletLinkForm.tsx (2)
src/lib/walletLinking/chainUtils.ts (1)
  • validateAddress (116-126)
src/lib/walletLinking/domain.ts (4)
  • validateEnsFormat (91-93)
  • validateSnsFormat (99-101)
  • resolveEnsDomain (67-85)
  • resolveSnsDomain (38-59)
src/lib/walletLinking/readmeUtils.ts (1)
src/lib/walletLinking/chainUtils.ts (2)
  • SUPPORTED_CHAINS_NAMES (73-73)
  • validateAddress (116-126)
🪛 Biome (1.9.4)
src/lib/walletLinking/domain.ts

[error] 25-25: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build
🔇 Additional comments (12)
package.json (1)

25-25: Verify package versions for security and compatibility.

The new dependencies support SNS domain resolution and Solana validation as intended. Ensure these versions are current and free from known vulnerabilities.

#!/bin/bash
# Check for latest versions and security advisories for new dependencies

echo "Checking @bonfida/spl-name-service..."
npm view @bonfida/spl-name-service version
npm audit --audit-level moderate --package-lock-only 2>/dev/null | grep -A5 -B5 "@bonfida/spl-name-service" || echo "No issues found"

echo "Checking @solana/web3.js..."
npm view @solana/web3.js version  
npm audit --audit-level moderate --package-lock-only 2>/dev/null | grep -A5 -B5 "@solana/web3.js" || echo "No issues found"

Also applies to: 43-43

src/lib/walletLinking/fetchWalletDataFromGithub.ts (1)

40-42: Correct async update.

The await addition properly handles the now-async parseWalletLinkingDataFromReadme function. This ensures asynchronous wallet validation completes before processing results.

src/lib/pipelines/ingest/fetchWalletAddresses.ts (1)

114-114: Correct async validation update.

The await addition properly handles the now-async validateAddress function, ensuring dynamic validation libraries are loaded and validation completes before proceeding.

src/app/profile/edit/hooks/useProfileWallets.ts (1)

63-64: Correct async parsing update.

The await addition properly handles the now-async parseWalletLinkingDataFromReadme function. The multi-line formatting enhances readability.

src/lib/walletLinking/readmeUtils.ts (4)

10-11: ENS/SNS domain name support added.

The optional ensName and snsName fields properly extend the schema to support domain names while maintaining backward compatibility.


32-34: Function signature updated for async validation.

The async conversion enables asynchronous wallet address validation, which is required for dynamic imports of validation libraries.


59-71: Async wallet validation implementation.

The replacement of synchronous filter with an async for loop correctly handles asynchronous address validation. Each wallet is properly validated before inclusion.


153-154: Domain names included in wallet generation.

The conditional inclusion of trimmed ensName and snsName fields ensures domain names are preserved in the generated wallet data when present.

src/app/profile/edit/components/WalletLinkForm.tsx (1)

114-150: LGTM!

Clean domain resolution implementation with proper error handling.

src/lib/walletLinking/domain.ts (1)

38-85: Well-implemented domain resolution with dynamic imports

Good use of dynamic imports for bundle optimization and proper error handling.

src/lib/walletLinking/chainUtils.ts (2)

27-40: Good async validator implementation with caching

Efficient use of dynamic imports and module-level caching.


45-64: Solid async Solana validation with proper error handling

Well-structured with dynamic imports and caching.

Comment on lines 67 to 84
useEffect(() => {
if (ethAddress === "") {
setIsEthValid(true);
setEthAddressError("");
} else {
const isValid = isAddress(ethAddress);
setIsEthValid(isValid);
setEthAddressError(isValid ? "" : "Invalid Ethereum address.");
return;
}

const validateEthAddress = async () => {
const isEVMValid = await validateAddress(ethAddress, "ethereum");
const isENSValid = validateEnsFormat(ethAddress);
setIsEthValid(isEVMValid || isENSValid);
setEthAddressError(
isEVMValid || isENSValid ? "" : "Invalid Ethereum address or ENS name.",
);
};

validateEthAddress();
}, [ethAddress]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add cleanup to prevent setState on unmounted component

Same issue as above - async validation needs cleanup.

   useEffect(() => {
+    let mounted = true;
     if (ethAddress === "") {
       setIsEthValid(true);
       setEthAddressError("");
       return;
     }

     const validateEthAddress = async () => {
       const isEVMValid = await validateAddress(ethAddress, "ethereum");
       const isENSValid = validateEnsFormat(ethAddress);
+      if (!mounted) return;
       setIsEthValid(isEVMValid || isENSValid);
       setEthAddressError(
         isEVMValid || isENSValid ? "" : "Invalid Ethereum address or ENS name.",
       );
     };

     validateEthAddress();
+    return () => { mounted = false; };
   }, [ethAddress]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
if (ethAddress === "") {
setIsEthValid(true);
setEthAddressError("");
} else {
const isValid = isAddress(ethAddress);
setIsEthValid(isValid);
setEthAddressError(isValid ? "" : "Invalid Ethereum address.");
return;
}
const validateEthAddress = async () => {
const isEVMValid = await validateAddress(ethAddress, "ethereum");
const isENSValid = validateEnsFormat(ethAddress);
setIsEthValid(isEVMValid || isENSValid);
setEthAddressError(
isEVMValid || isENSValid ? "" : "Invalid Ethereum address or ENS name.",
);
};
validateEthAddress();
}, [ethAddress]);
useEffect(() => {
let mounted = true;
if (ethAddress === "") {
setIsEthValid(true);
setEthAddressError("");
return;
}
const validateEthAddress = async () => {
const isEVMValid = await validateAddress(ethAddress, "ethereum");
const isENSValid = validateEnsFormat(ethAddress);
if (!mounted) return;
setIsEthValid(isEVMValid || isENSValid);
setEthAddressError(
isEVMValid || isENSValid ? "" : "Invalid Ethereum address or ENS name.",
);
};
validateEthAddress();
return () => {
mounted = false;
};
}, [ethAddress]);
🤖 Prompt for AI Agents
In src/app/profile/edit/components/WalletLinkForm.tsx around lines 67 to 84, the
async validation function inside useEffect can call setState after the component
has unmounted, causing a memory leak or warning. Fix this by adding a cleanup
mechanism: create a flag (e.g., isMounted) set to true at the start of
useEffect, set it to false in the cleanup function, and only call setIsEthValid
and setEthAddressError if isMounted is still true.

Comment on lines 86 to 103
useEffect(() => {
if (solAddress === "") {
setIsSolValid(true);
setSolAddressError("");
} else {
const isValid = SOL_ADDRESS_REGEX.test(solAddress);
setIsSolValid(isValid);
setSolAddressError(isValid ? "" : "Invalid Solana address format.");
return;
}

const validateSolAddress = async () => {
const isSOLValid = await validateAddress(solAddress, "solana");
const isSNSValid = validateSnsFormat(solAddress);
setIsSolValid(isSNSValid || isSOLValid);
setSolAddressError(
isSNSValid || isSOLValid ? "" : "Invalid Solana address or SNS name.",
);
};

validateSolAddress();
}, [solAddress]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add cleanup to prevent setState on unmounted component

Consistent with other validation hooks - needs cleanup.

   useEffect(() => {
+    let mounted = true;
     if (solAddress === "") {
       setIsSolValid(true);
       setSolAddressError("");
       return;
     }

     const validateSolAddress = async () => {
       const isSOLValid = await validateAddress(solAddress, "solana");
       const isSNSValid = validateSnsFormat(solAddress);
+      if (!mounted) return;
       setIsSolValid(isSNSValid || isSOLValid);
       setSolAddressError(
         isSNSValid || isSOLValid ? "" : "Invalid Solana address or SNS name.",
       );
     };

     validateSolAddress();
+    return () => { mounted = false; };
   }, [solAddress]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
if (solAddress === "") {
setIsSolValid(true);
setSolAddressError("");
} else {
const isValid = SOL_ADDRESS_REGEX.test(solAddress);
setIsSolValid(isValid);
setSolAddressError(isValid ? "" : "Invalid Solana address format.");
return;
}
const validateSolAddress = async () => {
const isSOLValid = await validateAddress(solAddress, "solana");
const isSNSValid = validateSnsFormat(solAddress);
setIsSolValid(isSNSValid || isSOLValid);
setSolAddressError(
isSNSValid || isSOLValid ? "" : "Invalid Solana address or SNS name.",
);
};
validateSolAddress();
}, [solAddress]);
useEffect(() => {
let mounted = true;
if (solAddress === "") {
setIsSolValid(true);
setSolAddressError("");
return;
}
const validateSolAddress = async () => {
const isSOLValid = await validateAddress(solAddress, "solana");
const isSNSValid = validateSnsFormat(solAddress);
if (!mounted) return;
setIsSolValid(isSNSValid || isSOLValid);
setSolAddressError(
isSNSValid || isSOLValid ? "" : "Invalid Solana address or SNS name.",
);
};
validateSolAddress();
return () => { mounted = false; };
}, [solAddress]);
🤖 Prompt for AI Agents
In src/app/profile/edit/components/WalletLinkForm.tsx around lines 86 to 103,
the useEffect hook that validates the solAddress needs a cleanup function to
prevent calling setState on an unmounted component. Add a flag variable inside
the effect to track if the component is still mounted, set it to false in the
cleanup function, and check this flag before calling setIsSolValid and
setSolAddressError to avoid state updates after unmount.

Comment on lines +45 to 65
// Validate initial addresses asynchronously
const validateInitialAddresses = async () => {
if (ethWallet?.address) {
const isValid = await validateAddress(ethWallet.address, "ethereum");
setIsEthValid(isValid);
if (!isValid) {
setEthAddressError("Invalid Ethereum address");
}
}

if (solWallet?.address) {
const isValid = await validateAddress(solWallet.address, "solana");
setIsSolValid(isValid);
if (!isValid) {
setSolAddressError("Invalid Solana address");
}
}
};

validateInitialAddresses();
}, [wallets]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add cleanup to prevent setState on unmounted component

The async validation could complete after component unmount, causing memory leaks.

   useEffect(() => {
+    let mounted = true;
     const validateInitialAddresses = async () => {
       if (ethWallet?.address) {
         const isValid = await validateAddress(ethWallet.address, "ethereum");
+        if (!mounted) return;
         setIsEthValid(isValid);
         if (!isValid) {
           setEthAddressError("Invalid Ethereum address");
         }
       }

       if (solWallet?.address) {
         const isValid = await validateAddress(solWallet.address, "solana");
+        if (!mounted) return;
         setIsSolValid(isValid);
         if (!isValid) {
           setSolAddressError("Invalid Solana address");
         }
       }
     };

     validateInitialAddresses();
+    return () => { mounted = false; };
   }, [wallets]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Validate initial addresses asynchronously
const validateInitialAddresses = async () => {
if (ethWallet?.address) {
const isValid = await validateAddress(ethWallet.address, "ethereum");
setIsEthValid(isValid);
if (!isValid) {
setEthAddressError("Invalid Ethereum address");
}
}
if (solWallet?.address) {
const isValid = await validateAddress(solWallet.address, "solana");
setIsSolValid(isValid);
if (!isValid) {
setSolAddressError("Invalid Solana address");
}
}
};
validateInitialAddresses();
}, [wallets]);
useEffect(() => {
let mounted = true;
// Validate initial addresses asynchronously
const validateInitialAddresses = async () => {
if (ethWallet?.address) {
const isValid = await validateAddress(ethWallet.address, "ethereum");
if (!mounted) return;
setIsEthValid(isValid);
if (!isValid) {
setEthAddressError("Invalid Ethereum address");
}
}
if (solWallet?.address) {
const isValid = await validateAddress(solWallet.address, "solana");
if (!mounted) return;
setIsSolValid(isValid);
if (!isValid) {
setSolAddressError("Invalid Solana address");
}
}
};
validateInitialAddresses();
return () => { mounted = false; };
}, [wallets]);
🤖 Prompt for AI Agents
In src/app/profile/edit/components/WalletLinkForm.tsx around lines 45 to 65, the
async function validateInitialAddresses may call setState after the component
has unmounted, causing memory leaks. To fix this, introduce a mounted flag that
is set to true at the start of the effect and false in a cleanup function.
Before calling any setState functions inside validateInitialAddresses, check if
the component is still mounted. This prevents state updates on unmounted
components.

Comment on lines +1 to +6
// Array of solana RPC endpoints to try in order
const RPC_ENDPOINTS = [
"https://api.mainnet-beta.solana.com", // Public Solana RPC
"https://solana-mainnet.g.alchemy.com/v2/lqe31XHZcBd-8FsgmYnHJ", // Alchemy endpoint, domain restricted to https://elizaos.github.io
process.env.NEXT_PUBLIC_SOLANA_RPC_URL || "", // Local/custom endpoint from environment
];
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove hardcoded API key from source code

Exposing API keys in public repositories is a security risk, even with domain restrictions.

 const RPC_ENDPOINTS = [
   "https://api.mainnet-beta.solana.com", // Public Solana RPC
-  "https://solana-mainnet.g.alchemy.com/v2/lqe31XHZcBd-8FsgmYnHJ", // Alchemy endpoint, domain restricted to https://elizaos.github.io
+  process.env.NEXT_PUBLIC_ALCHEMY_SOLANA_URL || "", // Alchemy endpoint from environment
   process.env.NEXT_PUBLIC_SOLANA_RPC_URL || "", // Local/custom endpoint from environment
 ];
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Array of solana RPC endpoints to try in order
const RPC_ENDPOINTS = [
"https://api.mainnet-beta.solana.com", // Public Solana RPC
"https://solana-mainnet.g.alchemy.com/v2/lqe31XHZcBd-8FsgmYnHJ", // Alchemy endpoint, domain restricted to https://elizaos.github.io
process.env.NEXT_PUBLIC_SOLANA_RPC_URL || "", // Local/custom endpoint from environment
];
// Array of solana RPC endpoints to try in order
const RPC_ENDPOINTS = [
"https://api.mainnet-beta.solana.com", // Public Solana RPC
process.env.NEXT_PUBLIC_ALCHEMY_SOLANA_URL || "", // Alchemy endpoint from environment
process.env.NEXT_PUBLIC_SOLANA_RPC_URL || "", // Local/custom endpoint from environment
];
🤖 Prompt for AI Agents
In src/lib/walletLinking/domain.ts lines 1 to 6, the Alchemy API key is
hardcoded in the RPC_ENDPOINTS array, which exposes sensitive information.
Remove the hardcoded API key string and instead load it securely from an
environment variable. Update the code to reference process.env for the Alchemy
endpoint URL, ensuring the key is not directly visible in the source code.

Copy link
Collaborator

@META-DREAMER META-DREAMER left a comment

Choose a reason for hiding this comment

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

just some suggestions on simplifying the code to be more maintainable

Comment on lines +115 to +148
const isENSValid = validateEnsFormat(ethAddress);
const address = isENSValid
? await resolveEnsDomain(ethAddress)
: ethAddress;

// If the address is not found, set the error and return
if (!address) {
setEthAddressError("Invalid Ethereum address or ENS name.");
return;
}

updatedWallets.push({
chain: "ethereum",
address: ethAddress,
address,
...(isENSValid && { ensName: ethAddress }),
});
}

if (solAddress) {
const isSNSValid = validateSnsFormat(solAddress);
const address = isSNSValid
? await resolveSnsDomain(solAddress)
: solAddress;

// If the address is not found, set the error and return
if (!address) {
setSolAddressError("Invalid Solana address or SNS name.");
return;
}

updatedWallets.push({
chain: "solana",
address: solAddress,
address,
...(isSNSValid && { snsName: solAddress }),
Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's move this logic into a custom hook. Components shouldn't have too much business logic inside them since its harder to test and maintain.

Also, a lot of this code could be simplified using Shadcn Form Component. Raw useState and useEffect like this has tricky edge cases and is often bug-prone. Especially if we add more fields / chains to this, it will become unweildy quickly.

Comment on lines +4 to +6
// Module-level caches for imported validators to optimize repeated calls
let viemValidator: ((address: string) => boolean) | null = null;
let solanaValidator: ((address: string) => boolean) | null = null;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why do we need this? AFAIK the dynamic imports are cached automatically by the es module system. Was there some sort of measurable performance issue this resolved?

Comment on lines +27 to +40
validator: async (address: string) => {
// Use cached validator if available, otherwise import and cache
if (!viemValidator) {
const { isAddress } = await import("viem");
viemValidator = isAddress;
}

try {
return viemValidator(address);
} catch (error) {
console.error(`Failed to validate Ethereum address ${address}:`, error);
return false;
}
},
Copy link
Collaborator

Choose a reason for hiding this comment

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

Dynamically importing viem in this function like this causes us to have to use await on every single validateAddress call, even when we dont need to worry about bundle size (like in pipelines).

Instead of dynamically importing these libraries, you can just dynamically import the chainUtils.ts or domain.ts files inside the frontend components. Or, you could even just dynamically load the whole WalletLinkForm component using Next/dynamic or React.lazy.

Would simplify a lot of the code in this PR that is doing dynamic loads in many functions. Put all the functions that depend on libraries you want to dynamically load into their own file(s), then just dynamically import that file wherever needed (or normal import and use as is in pipelines code)

@@ -79,7 +113,10 @@ export function createAccountId(chainId: string, address: string): string {
* @param chain The blockchain name (e.g., "ethereum", "solana")
* @returns True if the address is valid for the chain, false otherwise
*/
export function validateAddress(address: string, chain: string): boolean {
export async function validateAddress(
Copy link
Collaborator

Choose a reason for hiding this comment

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

should revert this back to being sync, see previous comment on dynamic loading

Comment on lines +87 to +101
// ENS name regex (name.eth format)
// Matches names that end with .eth and contain valid characters
const ENS_NAME_REGEX = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.eth$/;

export function validateEnsFormat(name: string): boolean {
return ENS_NAME_REGEX.test(name);
}

// SNS name regex (name.sol format)
// Matches names that end with .sol and contain valid characters
const SNS_NAME_REGEX = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.sol$/;

export function validateSnsFormat(name: string): boolean {
return SNS_NAME_REGEX.test(name);
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

e.g. things like this dont necesarily need to be dynamically loaded, so could be moved to a separate file if you think they would be used independently of the other functions in this file. Then you can dynamically load this file and just import from viem etc as usual at the top of the file.

@@ -37,7 +37,9 @@ export async function batchFetchWalletDataFromGithub(
const result = fileContents[i];

if (result.content) {
const walletData = parseWalletLinkingDataFromReadme(result.content);
const walletData = await parseWalletLinkingDataFromReadme(
Copy link
Collaborator

Choose a reason for hiding this comment

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

similarly this doesn't need to be async, since this code only runs in pipelines and not on clientside and therefore doesn't benefit from dynamic loading

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.

feat: allow wallet address resolution via ENS
4 participants