Skip to content
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

Adding private RPC on transport for all supported chains #4863

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

mateodaza
Copy link
Member

@mateodaza mateodaza commented Nov 11, 2024

@geleeroyale we set the key on vercel for staging, we'd need one rate limited before releasing to production 💯

Summary by CodeRabbit

  • New Features

    • Introduced a new method for identifying networks by chainId, enhancing network mapping capabilities.
    • Added dynamic transport configuration for client creation based on chainId, improving flexibility in network connections.
  • Bug Fixes

    • Maintained existing error handling for network identification and client creation, ensuring stability.

Copy link

vercel bot commented Nov 11, 2024

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

Name Status Preview Comments Updated (UTC)
giveth-dapps-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 11, 2024 2:18pm

@mateodaza mateodaza changed the title Adding private RPC for all supported chains Adding private RPC on transport for all supported chains Nov 11, 2024
Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The changes introduce two new functions: getDrpcNetwork in src/lib/network.ts, which maps chainId values to network names, and createDrpcTransport in src/wagmiConfigs.ts, which constructs a transport for client creation based on the chainId. The createDrpcTransport function utilizes the getDrpcNetwork function to determine the network and checks for a drpcKey in the environment variables. The existing function getChainName and error handling for projectId remain unchanged.

Changes

File Change Summary
src/lib/network.ts Added `getDrpcNetwork(chainId: number): string
src/wagmiConfigs.ts Added createDrpcTransport(chainId: number) for dynamic transport configuration; updated client property to use this new transport logic.

Poem

In the code where rabbits play,
New functions hop in bright array.
From chainId to names they leap,
Transporting data, oh so deep!
With every change, we dance and cheer,
For better paths, the future's near! 🐇✨


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 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
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 and nitpick comments (2)
src/lib/network.ts (2)

23-24: Enhance function documentation

While the function signature is well-typed, consider adding a JSDoc comment to provide more context about:

  • The purpose of DRPC (Distributed RPC)
  • Parameter constraints or valid chainId ranges
  • Return value meaning (null case implications)
-// Network mapping for DRPC
+/**
+ * Maps chain IDs to their corresponding DRPC (Distributed RPC) network identifiers.
+ * @param chainId - The blockchain network identifier
+ * @returns The DRPC network name if supported, null otherwise
+ */

42-43: Add input validation for chainId

The current implementation doesn't validate the chainId parameter. Consider adding checks for:

  • Invalid numbers (negative values, decimals)
  • Commonly mistyped chainIds
  • Type coercion issues
 export const getDrpcNetwork = (chainId: number): string | null => {
+  if (!Number.isInteger(chainId) || chainId < 0) {
+    throw new Error('Invalid chainId: must be a positive integer');
+  }
   const networkMap: { [key: number]: string } = {
     // ... network mappings
   };
   return networkMap[chainId] || null;
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 02a85a3 and 642f6ca.

📒 Files selected for processing (2)
  • src/lib/network.ts (1 hunks)
  • src/wagmiConfigs.ts (3 hunks)
🔇 Additional comments (3)
src/lib/network.ts (1)

25-40: Consider externalizing network configuration

The hardcoded network mapping could be challenging to maintain as new networks are added or network identifiers change. Consider:

  1. Moving this configuration to a dedicated config file
  2. Aligning it with the existing config.NETWORKS_CONFIG
  3. Adding validation for supported networks

Let's check if these networks align with the existing configuration:

src/wagmiConfigs.ts (2)

49-52: Consider rate limiting and monitoring strategy for DRPC usage

The client configuration now uses DRPC for all chains when available. This has important operational implications:

  1. Rate limiting needs to be considered across all chains collectively
  2. Transport failures should be monitored for fallback scenarios
  3. Usage metrics would be valuable for capacity planning

Consider implementing:

  1. A monitoring solution to track DRPC usage per chain
  2. Circuit breakers for automatic fallback on rate limit exhaustion
  3. Metrics collection for transport performance

Let's check which chains are supported:

#!/bin/bash
# Check configured chains and their usage
echo "Checking chain configurations..."
rg -A 5 "EVM_CHAINS" 

23-29: 🛠️ Refactor suggestion

Enhance error handling and security in DRPC transport creation

The function needs additional safeguards for production readiness:

  1. The fallback to http() when DRPC is unavailable should be logged for monitoring
  2. The environment variable access should be validated earlier
  3. The URL construction should be more secure

Consider this improved implementation:

 const createDrpcTransport = (chainId: number) => {
+  const drpcKey = process.env.NEXT_PUBLIC_DRPC_KEY;
+  if (!drpcKey) {
+    console.warn(`DRPC key not found, falling back to public RPC for chain ${chainId}`);
+    return http();
+  }
+
   const network = getDrpcNetwork(chainId);
-  const drpcKey = process.env.NEXT_PUBLIC_DRPC_KEY;
-  return network && drpcKey
-    ? http(`https://lb.drpc.org/ogrpc?network=${network}&dkey=${drpcKey}`)
-    : http();
+  if (!network) {
+    console.warn(`Unsupported network for DRPC: ${chainId}`);
+    return http();
+  }
+
+  const drpcUrl = new URL('https://lb.drpc.org/ogrpc');
+  drpcUrl.searchParams.append('network', network);
+  drpcUrl.searchParams.append('dkey', drpcKey);
+  return http(drpcUrl.toString());
 };

Let's verify the DRPC key is properly set in the environment:

Comment on lines +24 to +43
export const getDrpcNetwork = (chainId: number): string | null => {
const networkMap: { [key: number]: string } = {
1: 'ethereum',
137: 'polygon',
10: 'optimism',
42161: 'arbitrum',
8453: 'base',
42220: 'celo',
100: 'gnosis',
1101: 'polygon-zkevm',
11155111: 'sepolia',
11155420: 'optimism-sepolia',
421614: 'arbitrum-sepolia',
84532: 'base-sepolia',
44787: 'celo-alfajores',
1442: 'polygon-zkevm-cardona',
};

return networkMap[chainId] || null;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Based on the search results, I can now generate the final response:

DRPC key implementation needs error handling improvements

The current implementation in wagmiConfigs.ts uses DRPC key from environment variables but lacks:

  • Error handling for invalid or missing DRPC keys
  • Rate limit handling mechanisms
  • Fallback strategy when DRPC requests fail

Specific locations that need attention:

  • src/wagmiConfigs.ts: The transport configuration simply falls back to default HTTP transport without any error handling when DRPC key is missing
  • Consider adding validation similar to the projectId check that's already implemented (if (!projectId) throw new Error('Project ID is not defined'))
🔗 Analysis chain

Verify DRPC key handling

The PR objectives mention a rate-limited key requirement for production. While this function handles network mapping, ensure that:

  1. The DRPC key is properly validated in the transport configuration
  2. Rate limiting is properly implemented
  3. Error handling exists for cases when the key is invalid or rate limit is exceeded

Let's check how the DRPC key is handled:


Let me gather more context about the transport configuration and error handling:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check DRPC key usage and validation
# Look for DRPC key handling in the codebase
rg -g '!node_modules' -g '*.ts' -g '*.js' -A 5 'drpcKey|DRPC_KEY'

Length of output: 458


Script:

#!/bin/bash
# Check the complete transport configuration and error handling
rg -g '*.ts' -g '*.js' -A 10 'createConfig|http\(' 

# Look for any error handling related to RPC
rg -g '*.ts' -g '*.js' -A 5 'RpcError|rpcError|transport.*error'

Length of output: 3142

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

1 participant