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

add evm provider #6

Closed
wants to merge 2 commits into from
Closed

add evm provider #6

wants to merge 2 commits into from

Conversation

ponderingdemocritus
Copy link
Contributor

@ponderingdemocritus ponderingdemocritus commented Jan 12, 2025

Adds basic EVM provider

(open to contributions)

Todo:

  • Example interacting with uniswap

Summary by CodeRabbit

  • New Features

    • Added Ethereum transaction support with the ethers library
    • Enhanced transaction handling capabilities across different blockchain networks
  • Dependencies

    • Introduced ethers library version 6.13.5
  • Documentation

    • Updated README with a more inclusive description of library capabilities

Copy link
Contributor

coderabbitai bot commented Jan 12, 2025

Walkthrough

The pull request introduces support for Ethereum transactions in the Daydreams core library. A new dependency on the ethers library is added to the package.json, and significant modifications are made to providers.ts to handle EVM (Ethereum Virtual Machine) transactions. This includes the creation of a new transaction interface and an asynchronous function for executing Ethereum transactions using JSON-RPC providers. Additionally, the readme is updated to broaden the library's described scope.

Changes

File Change Summary
packages/core/package.json Added "ethers": "^6.13.5" dependency
packages/core/src/core/providers.ts - Added EvmTransaction interface extending CoTTransaction
- Implemented executeEvmTransaction function for Ethereum transaction execution
readme.md Updated description from "play any onchain game" to "play anything onchain"

Sequence Diagram

sequenceDiagram
    participant User
    participant ExecuteEvmTransaction
    participant EthersProvider
    participant EthersWallet
    participant SmartContract

    User->>ExecuteEvmTransaction: Submit EvmTransaction
    ExecuteEvmTransaction->>EthersProvider: Initialize JSON-RPC Provider
    ExecuteEvmTransaction->>EthersWallet: Create Wallet Instance
    ExecuteEvmTransaction->>SmartContract: Create Contract Instance
    ExecuteEvmTransaction->>SmartContract: Execute Contract Method
    SmartContract-->>ExecuteEvmTransaction: Return Transaction Receipt
    ExecuteEvmTransaction-->>User: Return Transaction Result
Loading

Poem

🐰 Ethereum's dance, a blockchain delight,
Transactions now flow with ethereal might!
Ethers library joins our core's embrace,
Onchain adventures we'll now boldly trace.
A rabbit's dream of digital flight! 🚀

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

🧹 Nitpick comments (1)
readme.md (1)

3-3: LGTM! Documentation update reflects new capabilities.

The broader scope in the description accurately reflects the addition of EVM support alongside other chains.

Minor suggestion: Consider adding a hyphen to make it "on-chain" for better readability.

🧰 Tools
🪛 LanguageTool

[grammar] ~3-~3: Did you mean “are” or “were”?
Context: # Daydreams Daydreams is a generative agent library for playing ...

(SENT_START_NNS_IS)


[uncategorized] ~3-~3: This expression is ususally spelled with a hyphen
Context: ...ary for playing anything onchain. It is chain agnostic and can be used to play anything onchai...

(SPECIFIC_HYPHEN)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 19e501e and 0472dcf.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • packages/core/package.json (1 hunks)
  • packages/core/src/core/providers.ts (2 hunks)
  • readme.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
readme.md

[grammar] ~3-~3: Did you mean “are” or “were”?
Context: # Daydreams Daydreams is a generative agent library for playing ...

(SENT_START_NNS_IS)


[uncategorized] ~3-~3: This expression is ususally spelled with a hyphen
Context: ...ary for playing anything onchain. It is chain agnostic and can be used to play anything onchai...

(SPECIFIC_HYPHEN)

🔇 Additional comments (2)
packages/core/src/core/providers.ts (1)

87-92: LGTM! Well-structured interface definition.

The EvmTransaction interface properly extends CoTTransaction and includes essential EVM-specific fields.

packages/core/package.json (1)

21-21: Verify ethers.js version compatibility and security.

The ethers.js v6.13.5 is a recent version, but let's verify it's free from known vulnerabilities.

Run this script to check for security advisories:

✅ Verification successful

✓ ethers.js v6.13.5 dependency verified

The dependency is secure, up-to-date, and correctly implemented using v6 API patterns in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for security advisories in ethers package
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: NPM, package: "ethers") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

# Check latest version
npm view ethers versions --json | jq -r '.[-1]'

Length of output: 395


Script:

#!/bin/bash
# Check for peer dependencies and package usage
npm view [email protected] peerDependencies --json

# Search for ethers imports/requires in the codebase
rg -l "require\(['\"]ethers['\"]\)|from ['\"](ethers|@ethersproject)" --type js --type ts

# Look for existing ethers version in other package.json files
fd package.json --type f --exec grep -l "ethers" {}

Length of output: 265


Script:

#!/bin/bash
# Check ethers usage in providers.ts
cat packages/core/src/core/providers.ts

Length of output: 3211

Comment on lines +98 to +102
// Initialize provider (customize based on your needs)
const provider = new ethers.JsonRpcProvider(process.env.EVM_RPC_URL);

// Initialize wallet/signer
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add environment variable validation.

The code assumes environment variables will be present without validation.

Add validation before using environment variables:

-    const provider = new ethers.JsonRpcProvider(process.env.EVM_RPC_URL);
-    const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
+    const rpcUrl = process.env.EVM_RPC_URL;
+    const privateKey = process.env.PRIVATE_KEY;
+    
+    if (!rpcUrl || !privateKey) {
+      throw new Error('Missing required environment variables: EVM_RPC_URL or PRIVATE_KEY');
+    }
+    
+    const provider = new ethers.JsonRpcProvider(rpcUrl);
+    const wallet = new ethers.Wallet(privateKey, provider);
📝 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
// Initialize provider (customize based on your needs)
const provider = new ethers.JsonRpcProvider(process.env.EVM_RPC_URL);
// Initialize wallet/signer
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
// Initialize provider (customize based on your needs)
const rpcUrl = process.env.EVM_RPC_URL;
const privateKey = process.env.PRIVATE_KEY;
if (!rpcUrl || !privateKey) {
throw new Error('Missing required environment variables: EVM_RPC_URL or PRIVATE_KEY');
}
const provider = new ethers.JsonRpcProvider(rpcUrl);
const wallet = new ethers.Wallet(privateKey, provider);

Comment on lines +112 to +115
const txOptions = {
value: BigInt(transaction.value || "0"),
gasLimit: BigInt(transaction.gasLimit || "0"),
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve gas limit handling.

The current implementation might lead to transaction failures if gas limit is not properly set.

Consider these improvements:

  1. Add gas estimation
  2. Validate gas limit values
  3. Handle potential out-of-gas scenarios
-    const txOptions = {
-      value: BigInt(transaction.value || "0"),
-      gasLimit: BigInt(transaction.gasLimit || "0"),
-    };
+    const txOptions: ethers.ContractTransactionRequest = {
+      value: BigInt(transaction.value || "0"),
+    };
+
+    if (transaction.gasLimit) {
+      txOptions.gasLimit = BigInt(transaction.gasLimit);
+    } else {
+      // Estimate gas if not provided
+      try {
+        txOptions.gasLimit = await contract[transaction.method].estimateGas(
+          ...transaction.calldata,
+          { value: txOptions.value }
+        );
+      } catch (error) {
+        throw new Error(`Gas estimation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+      }
+    }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +118 to +124
const tx = await contract[transaction.method](
...transaction.calldata,
txOptions
);
const receipt = await tx.wait();

return receipt;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance transaction execution and receipt handling.

The current implementation lacks proper transaction monitoring and receipt validation.

Consider these improvements:

  1. Add transaction confirmation blocks
  2. Validate transaction receipt
  3. Handle revert reasons
-    const tx = await contract[transaction.method](
-      ...transaction.calldata,
-      txOptions
-    );
-    const receipt = await tx.wait();
-
-    return receipt;
+    try {
+      const tx = await contract[transaction.method](
+        ...transaction.calldata,
+        txOptions
+      );
+      
+      // Wait for 2 confirmations
+      const receipt = await tx.wait(2);
+      
+      if (!receipt.status) {
+        throw new Error('Transaction failed');
+      }
+      
+      return receipt;
+    } catch (error: any) {
+      // Handle revert reasons
+      if (error.data) {
+        throw new Error(`Transaction reverted: ${error.data}`);
+      }
+      throw error;
+    }
📝 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
const tx = await contract[transaction.method](
...transaction.calldata,
txOptions
);
const receipt = await tx.wait();
return receipt;
try {
const tx = await contract[transaction.method](
...transaction.calldata,
txOptions
);
// Wait for 2 confirmations
const receipt = await tx.wait(2);
if (!receipt.status) {
throw new Error('Transaction failed');
}
return receipt;
} catch (error: any) {
// Handle revert reasons
if (error.data) {
throw new Error(`Transaction reverted: ${error.data}`);
}
throw error;
}

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

♻️ Duplicate comments (3)
packages/core/src/core/providers.ts (3)

98-102: ⚠️ Potential issue

Add environment variable validation.

The code assumes environment variables will be present without validation.


120-123: ⚠️ Potential issue

Improve gas limit handling.

The current implementation might lead to transaction failures if gas limit is not properly set.


126-132: ⚠️ Potential issue

Enhance transaction execution and receipt handling.

The current implementation lacks proper transaction monitoring and receipt validation.

🧹 Nitpick comments (1)
packages/core/src/core/providers.ts (1)

87-92: Consider making the network field more flexible.

Instead of hardcoding "evm" as the only network type, consider using a union type to support potential future networks and maintain better type safety.

-  network: "evm";
+  network: "evm" | "arbitrum" | "optimism" | "polygon";  // Add other EVM-compatible networks as needed
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0472dcf and 5a8f745.

📒 Files selected for processing (1)
  • packages/core/src/core/providers.ts (2 hunks)
🔇 Additional comments (1)
packages/core/src/core/providers.ts (1)

3-4: LGTM! Required imports are correctly added.

The imports for CoTTransaction type and ethers library are properly added to support the new EVM functionality.

Comment on lines +133 to +135
} catch (error) {
return error instanceof Error ? error : new Error("Unknown error occurred");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling specificity.

The current error handling loses valuable information by converting all errors to a generic message. Consider handling specific error types differently.

   } catch (error) {
-    return error instanceof Error ? error : new Error("Unknown error occurred");
+    if (error instanceof ethers.ContractTransactionExecutionError) {
+      return new Error(`Transaction execution failed: ${error.message}`);
+    } else if (error instanceof ethers.ContractTransactionRevertedError) {
+      return new Error(`Transaction reverted: ${error.message}`);
+    } else if (error instanceof ethers.ProviderError) {
+      return new Error(`Provider error: ${error.message}`);
+    } else {
+      return error instanceof Error ? error : new Error("Unknown error occurred");
+    }
📝 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
} catch (error) {
return error instanceof Error ? error : new Error("Unknown error occurred");
}
} catch (error) {
if (error instanceof ethers.ContractTransactionExecutionError) {
return new Error(`Transaction execution failed: ${error.message}`);
} else if (error instanceof ethers.ContractTransactionRevertedError) {
return new Error(`Transaction reverted: ${error.message}`);
} else if (error instanceof ethers.ProviderError) {
return new Error(`Provider error: ${error.message}`);
} else {
return error instanceof Error ? error : new Error("Unknown error occurred");
}
}

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.

1 participant