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

feat: add router nitro plugin #2590

Merged
merged 6 commits into from
Jan 21, 2025
Merged

Conversation

RaveenaBhasin
Copy link
Contributor

@RaveenaBhasin RaveenaBhasin commented Jan 21, 2025

Relates to

LINK TO ISSUE OR TICKET

#2561

Risks

No changes to core functionality or external APIs.

Background

What does this PR do?

Introducing new plugin for agent to cross chain swap/bridge tokens using Router Nitro Bridge.
Currently, only EVM chains are supported, but since the Router Nitro Bridge also facilitates swaps to and from various non-EVM chains, this plugin can be expanded to include those functionalities in the future.
The plugin supports both native and ERC20 cross-chain token swaps.
image
Transaction Link: https://arbiscan.io/tx/0x36a1f91c228b3a02ec26b877152ccd59c10139abce4b16466240bebfcc6613dd
image

What kind of change is this?

Features (non-breaking change which adds functionality)

Documentation changes needed?

Testing

Where should a reviewer start?

Spin up a agent and configure router-nitro-plugin. Go to the router-nitro-plugin directory for detailed understanding.

Detailed testing steps

Summary by CodeRabbit

  • New Features

    • Added a new Nitro Plugin for cross-chain token swaps
    • Introduced router functionality with support for multiple blockchain networks
    • Implemented utility functions for chain and token interactions
  • Improvements

    • Enhanced agent configuration with new plugin support
    • Added robust error handling and validation for swap transactions
    • Implemented chain and token configuration utilities
  • Technical Updates

    • Added new package @elizaos/plugin-router-nitro
    • Configured TypeScript and build settings for the new plugin

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Hi @RaveenaBhasin! Welcome to the elizaOS community. Thanks for submitting your first pull request; your efforts are helping us accelerate towards AGI. We'll review it shortly. You are now an elizaOS contributor!

Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

📝 Walkthrough

Walkthrough

This pull request introduces the @elizaos/plugin-router-nitro, a new plugin for cross-chain token swaps and bridging capabilities. The changes include creating a comprehensive plugin with actions for executing swaps, managing chain and token configurations, and validating transactions across different blockchain networks. The implementation adds utility functions for chain interactions, balance checking, and transaction processing.

Changes

File Change Summary
agent/package.json Added @elizaos/plugin-router-nitro as a workspace dependency
agent/src/index.ts Updated plugin imports, added nitroPlugin
packages/plugin-router-nitro/... New package with configuration files, source code for chain utilities, swap actions, and plugin definition

Possibly related issues

  • Add Router Nitro Agent #2561: Directly addresses the user's request for Router Nitro Bridge Integration, providing a plugin that enables cross-chain asset transfers

Possibly related PRs

Suggested labels

Needs Testing, Plugin_new

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @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: 8

🧹 Nitpick comments (7)
packages/plugin-router-nitro/src/actions/utils.ts (2)

3-5: Enhance type safety by defining interfaces instead of 'any'

Consider defining TypeScript interfaces for the chain data structures to improve type safety and prevent potential runtime errors.

Also applies to: 43-44


75-117: Avoid code duplication by extracting a common method for retrieving chain data

The methods getChainId, getChainType, isChainLive, and getGasToken use similar logic to retrieve the chain object. Extract this logic into a private method to reduce duplication.

Apply this diff to refactor the code:

+    private getChainByName(normalizedName: string): any | null {
+        return this.chainData.find(
+            c => c.name.toLowerCase() === normalizedName.toLowerCase()
+        );
+    }

     getChainId(chainName: string): string | null {
         if (!chainName) return null;
         const normalizedName = this.normalizeChainName(chainName);
-        const chain = this.chainData.find(
-            c => c.name.toLowerCase() === normalizedName.toLowerCase()
-        );
+        const chain = this.getChainByName(normalizedName);
         return chain ? chain.chainId : null;
     }

Repeat similar changes for getChainType, isChainLive, and getGasToken.

packages/plugin-router-nitro/src/actions/executeSwap.ts (1)

196-202: Correct the chain name in the example

In the second example, the agent mentions "Solana" instead of "Avalanche". Ensure the chain names are consistent.

Apply this diff:

-                        text: "Sure, I'll swap 1 ETH into USDC from Solana to Base on address 0xF43042865f4D3B32A19ECBD1C7d4d924613c41E8",
+                        text: "Sure, I'll swap 1 ETH into USDC from Avalanche to Base on address 0xF43042865f4D3B32A19ECBD1C7d4d924613c41E8",
packages/plugin-router-nitro/src/actions/swapTemplate.ts (1)

1-28: Add validation hints and type constraints to the template.

The template should include:

  • Format requirements for token symbols
  • Chain ID format expectations
  • Amount format (decimal places, scientific notation)
 Extract the following details for the cross-chain swap request:
-  - **From Token**: The symbol of the token to swap from.
+  - **From Token**: The token symbol (e.g., "ETH", "USDC"). Must be a valid token symbol.
-  - **Amount**: The amount to swap, in the "From Token."
+  - **Amount**: The amount to swap as a decimal number (e.g., "1.5", "0.01").
packages/plugin-router-nitro/src/actions/chains.ts (1)

11-18: Add caching for RPC URLs.

Frequent RPC URL lookups could be optimized with a caching mechanism.

+ const rpcUrlCache = new Map<number, string>();

 export const getRpcUrlFromChainId = (chainId) => {
+  const cached = rpcUrlCache.get(chainId);
+  if (cached) return cached;

   const chain = chains[chainId];
   if (!chain) {
     throw new Error(`Chain ID ${chainId} not found`);
   }
   
-  return chain.rpcUrls.default.http[0];
+  const url = chain.rpcUrls.default.http[0];
+  rpcUrlCache.set(chainId, url);
+  return url;
 }
agent/src/index.ts (2)

42-42: Remove duplicate import.

The DirectClient import is already present at line 14.

-// import { DirectClient } from "@elizaos/client-direct";

734-735: Use optional chaining for safer property access.

Replace the nested condition with optional chaining to improve code safety.

-            getSecret(character, "WALLET_PUBLIC_KEY") &&
-                getSecret(character, "WALLET_PUBLIC_KEY")?.startsWith("0x")
+            getSecret(character, "WALLET_PUBLIC_KEY")?.startsWith("0x")
🧰 Tools
🪛 Biome (1.9.4)

[error] 734-735: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a00f723 and cae874f.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • agent/package.json (1 hunks)
  • agent/src/index.ts (10 hunks)
  • packages/plugin-router-nitro/eslint.config.mjs (1 hunks)
  • packages/plugin-router-nitro/package.json (1 hunks)
  • packages/plugin-router-nitro/src/actions/chains.ts (1 hunks)
  • packages/plugin-router-nitro/src/actions/executeSwap.ts (1 hunks)
  • packages/plugin-router-nitro/src/actions/swapTemplate.ts (1 hunks)
  • packages/plugin-router-nitro/src/actions/txns.ts (1 hunks)
  • packages/plugin-router-nitro/src/actions/utils.ts (1 hunks)
  • packages/plugin-router-nitro/src/environment.ts (1 hunks)
  • packages/plugin-router-nitro/src/index.ts (1 hunks)
  • packages/plugin-router-nitro/tsconfig.json (1 hunks)
  • packages/plugin-router-nitro/tsup.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • packages/plugin-router-nitro/eslint.config.mjs
  • packages/plugin-router-nitro/tsconfig.json
  • packages/plugin-router-nitro/package.json
  • packages/plugin-router-nitro/tsup.config.ts
🧰 Additional context used
🪛 Biome (1.9.4)
agent/src/index.ts

[error] 185-185: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


[error] 734-735: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
packages/plugin-router-nitro/src/index.ts (1)

1-13: LGTM!

The plugin setup is correct, and the implementation looks good.

agent/src/index.ts (2)

178-193: LGTM! Well-structured environment variable handling.

The code properly handles character-specific environment variables with a clear prefix structure.

🧰 Tools
🪛 Biome (1.9.4)

[error] 185-185: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


717-717: LGTM! Proper environment variable checks for nitroPlugin.

The plugin initialization correctly checks for both required environment variables: ROUTER_NITRO_EVM_PRIVATE_KEY and ROUTER_NITRO_EVM_ADDRESS.

agent/package.json (1)

95-95: LGTM! Dependency added correctly.

The router-nitro plugin dependency is properly added with workspace versioning.

@wtfsayo
Copy link
Member

wtfsayo commented Jan 21, 2025

Screenshot 2025-01-21 at 3 48 52 PM

could you allow me to push changes + request to take URLParam related suggestions from coderabbit review!

@wtfsayo wtfsayo enabled auto-merge (squash) January 21, 2025 11:11
@wtfsayo wtfsayo self-requested a review January 21, 2025 11:12
Copy link
Member

@wtfsayo wtfsayo left a comment

Choose a reason for hiding this comment

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

would suggest to implement the feedback; in subsequent PR

@wtfsayo wtfsayo merged commit b77b995 into elizaOS:develop Jan 21, 2025
6 of 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.

2 participants