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

hardhat config #116

Merged
merged 7 commits into from
Dec 19, 2024
Merged

hardhat config #116

merged 7 commits into from
Dec 19, 2024

Conversation

aazhou1
Copy link

@aazhou1 aazhou1 commented Dec 18, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a script for deploying strategy contracts in a blockchain environment.
    • Added configuration for multiple blockchain networks, including Sepolia, Avalanche, and Mainnet.
    • Added new scripts for deploying strategies on Sepolia and Mainnet using environment variables.
  • Bug Fixes

    • Improved error handling during the deployment process.
  • Documentation

    • Updated TypeScript configuration to specify included directories and files.
  • Chores

    • Added a new dependency for managing environment variables.

@aazhou1 aazhou1 self-assigned this Dec 18, 2024
Copy link

coderabbitai bot commented Dec 18, 2024

Warning

Rate limit exceeded

@robotoer has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 20 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 92ba27f and 8ac7484.

📒 Files selected for processing (2)
  • .github/workflows/deploy-strategy-hardhat.yaml (1 hunks)
  • hardhat-scripts/deploy-strategy.ts (1 hunks)

Walkthrough

The pull request introduces several changes across four main files: deploy-strategy.ts, hardhat.config.ts, tsconfig.json, and package.json. The deploy-strategy.ts script implements a comprehensive approach for deploying a strategy contract, including utility functions for input conversion and asset verification. The hardhat.config.ts file establishes a configuration for Hardhat with network settings and compiler specifications. The tsconfig.json enhances TypeScript setup by defining included directories. Lastly, package.json updates include a new dependency and deployment scripts for different networks.

Changes

File Change Summary
hardhat-scripts/deploy-strategy.ts Added multiple utility and deployment functions:
- stringToAddressArray: Convert string to address array
- stringToUintArray: Convert string to uint array
- checkUnderlyingVaultAsset: Verify vault asset
- buildStrategyParams: Gather deployment parameters
- deployEventEmitter: Deploy event emitter contract
- main(): Orchestrate full deployment process
hardhat.config.ts Added Hardhat configuration with:
- Solidity compiler version 0.8.23
- Network configs for Sepolia, Avalanche, Mainnet
- Environment-based network and account settings
tsconfig.json Updated TypeScript configuration to include:
- "include": ["./src", "./scripts"]
- "files": ["./hardhat.config.ts"]
package.json Added new dependency and scripts:
- Dependency: "env-cmd": "^10.1.0"
- Scripts: sepolia:deploy-strategy, mainnet:deploy-strategy

Sequence Diagram

sequenceDiagram
    participant Deployer
    participant EventEmitter
    participant Strategy
    participant Vault

    Deployer->>EventEmitter: Deploy Event Emitter
    Deployer->>Vault: Check Underlying Asset
    Deployer->>Strategy: Deploy Strategy
    Deployer->>Strategy: Configure Parameters
    Deployer->>Strategy: Pair with Event Emitter
Loading

Poem

🐰 Deploying contracts with glee and might,
Hardhat scripts dancing in the blockchain light,
Networks align, parameters set just right,
From Sepolia to Avalanche, our strategy takes flight!
Rabbit's code hops, deployment complete ✨


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

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

🧹 Nitpick comments (1)
hardhat-scripts/deploy-strategy.ts (1)

13-16: Consider using BigNumber for large integers.
Using JavaScript’s native 'parseInt()' caps the numeric range, which may matter if large values are expected. If you only expect typical integer ranges, this is fine. Otherwise consider using BigNumber-based parsing.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 779add0 and b7fe587.

📒 Files selected for processing (2)
  • hardhat-scripts/deploy-strategy.ts (1 hunks)
  • hardhat.config.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
hardhat-scripts/deploy-strategy.ts

[error] 62-62: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (7)
hardhat-scripts/deploy-strategy.ts (4)

8-11: Good use of string splitting for address arrays.
The utility function handles trimming and splitting correctly, avoiding potential spacing issues.


18-24: Well-implemented asset verification.
Comparing underlying assets (case-insensitively) is a robust approach. The logic here is clear and correct.


76-104: Validate addresses before calling setters.
Environment variables like STRATEGY_MANAGEMENT_ADDRESS, KEEPER_ADDRESS, and FEE_RECIPIENT must be valid addresses. Consider adding lightweight runtime checks or fail-fast validations.


121-123: Governor role assignment appears consistent.
This step properly handles transferring governance. Ensure that the final acceptance (e.g., acceptGovernor call) is performed after deployment if required by the contract.

hardhat.config.ts (3)

1-3: Plugins and import structure look good.
No issues found with the plugin imports.


33-33: Exporting the Hardhat config is correct.
Configuration object is properly structured and exported.


4-31: Verify environment variables for network configurations.
For each network, confirm that the relevant RPC URLs and PRIVATE_KEY are valid.

Use this script to confirm references to environment variables in the codebase:


console.log("Deployed event emitter impl to:", eventEmitterImpl.address);

const Proxy = (await ethers.getContractFactory("ERC1967Proxy")).connect(managedSigner);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid shadowing the global "Proxy" property.
Rename this local variable (e.g., ERC1967ProxyFactory) to remove ambiguity.

- const Proxy = (await ethers.getContractFactory("ERC1967Proxy")).connect(managedSigner);
+ const ERC1967ProxyFactory = (await ethers.getContractFactory("ERC1967Proxy")).connect(managedSigner);
📝 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 Proxy = (await ethers.getContractFactory("ERC1967Proxy")).connect(managedSigner);
const ERC1967ProxyFactory = (await ethers.getContractFactory("ERC1967Proxy")).connect(managedSigner);
🧰 Tools
🪛 Biome (1.9.4)

[error] 62-62: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

hardhat-scripts/deploy-strategy.ts Outdated Show resolved Hide resolved
hardhat-scripts/deploy-strategy.ts Outdated Show resolved Hide resolved
Copy link

codecov bot commented Dec 18, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 89.23%. Comparing base (779add0) to head (8ac7484).
Report is 11 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #116   +/-   ##
=======================================
  Coverage   89.23%   89.23%           
=======================================
  Files           5        5           
  Lines         604      604           
  Branches       90       90           
=======================================
  Hits          539      539           
  Misses         54       54           
  Partials       11       11           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

♻️ Duplicate comments (3)
hardhat-scripts/deploy-strategy.ts (3)

35-64: ⚠️ Potential issue

Add validation for required environment variables

The function uses TypeScript's non-null assertion operator (!) but lacks proper validation of environment variables.

 async function buildStrategyParams(
   eventEmitter: string,
   deployer: string,
   managedSigner: Signer
 ) {
+  const requiredEnvVars = {
+    ASSET_ADDRESS: process.env.ASSET_ADDRESS,
+    YEARN_VAULT_ADDRESS: process.env.YEARN_VAULT_ADDRESS,
+    DISCOUNT_RATE_ADAPTER_ADDRESS: process.env.DISCOUNT_RATE_ADAPTER_ADDRESS,
+    TERM_CONTROLLER_ADDRESS: process.env.TERM_CONTROLLER_ADDRESS,
+    DISCOUNT_RATE_MARKUP: process.env.DISCOUNT_RATE_MARKUP,
+    TIME_TO_MATURITY_THRESHOLD: process.env.TIME_TO_MATURITY_THRESHOLD,
+    REPOTOKEN_CONCENTRATION_LIMIT: process.env.REPOTOKEN_CONCENTRATION_LIMIT,
+    NEW_REQUIRED_RESERVE_RATIO: process.env.NEW_REQUIRED_RESERVE_RATIO
+  };
+
+  const missingVars = Object.entries(requiredEnvVars)
+    .filter(([_, value]) => !value)
+    .map(([key]) => key);
+
+  if (missingVars.length > 0) {
+    throw new Error(`Missing required environment variables: ${missingVars.join(', ')}`);
+  }

   const asset = process.env.ASSET_ADDRESS!;
   // ... rest of the function

78-81: ⚠️ Potential issue

Avoid shadowing the global "Proxy" property

Rename this local variable to remove ambiguity.

- const Proxy = (await hre.ethers.getContractFactory("ERC1967Proxy")).connect(
+ const ERC1967ProxyFactory = (await hre.ethers.getContractFactory("ERC1967Proxy")).connect(
    managedSigner
  );
🧰 Tools
🪛 Biome (1.9.4)

[error] 78-78: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)


157-162: ⚠️ Potential issue

Prevent mismatched array lengths in collateral token setup

When splitting environment variables, ensure both arrays have the same length.

+ if (collateralTokens.length !== minCollateralRatios.length) {
+   throw new Error("COLLATERAL_TOKEN_ADDRESSES and MIN_COLLATERAL_RATIOS must have the same number of entries");
+ }
 for (let i = 0; i < collateralTokens.length; i++) {
   await strategy.setCollateralTokenParams(
     collateralTokens[i],
     minCollateralRatios[i]
   );
 }
🧹 Nitpick comments (2)
hardhat-scripts/deploy-strategy.ts (2)

19-33: Enhance error message with more details

The error message could be more informative by including the actual and expected asset addresses.

 if (underlyingAsset.toLowerCase() !== asset.toLowerCase()) {
-    throw new Error("Underlying asset does not match asset");
+    throw new Error(
+      `Underlying asset mismatch. Expected: ${asset}, Got: ${underlyingAsset}`
+    );
 }

168-173: Enhance error handling in script execution

Improve error reporting to provide more context about deployment failures.

 main()
   .then(() => process.exit(0))
   .catch((error) => {
-    console.error(error);
+    console.error('Deployment failed:', {
+      message: error.message,
+      stack: error.stack,
+      // For contract deployment errors
+      transaction: error.transaction,
+      receipt: error.receipt
+    });
     process.exit(1);
   });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b7fe587 and 493bdce.

📒 Files selected for processing (2)
  • hardhat-scripts/deploy-strategy.ts (1 hunks)
  • tsconfig.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tsconfig.json
🧰 Additional context used
🪛 Biome (1.9.4)
hardhat-scripts/deploy-strategy.ts

[error] 78-78: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

hardhat-scripts/deploy-strategy.ts Outdated Show resolved Hide resolved
hardhat-scripts/deploy-strategy.ts Outdated Show resolved Hide resolved
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 493bdce and caac109.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (1)
  • package.json (2 hunks)
🔇 Additional comments (1)
package.json (1)

8-8: LGTM: env-cmd dependency addition

The addition of env-cmd is appropriate for managing environment-specific configurations during deployment.

package.json Outdated Show resolved Hide resolved
robotoer and others added 2 commits December 19, 2024 13:57
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

🧹 Nitpick comments (3)
hardhat-scripts/deploy-strategy.ts (3)

32-46: Enhance error message with actual values

The error message should include the expected and actual asset addresses to help with debugging.

   if (underlyingAsset.toLowerCase() !== asset.toLowerCase()) {
-    throw new Error("Underlying asset does not match asset");
+    throw new Error(
+      `Underlying asset mismatch. Expected: ${asset}, Actual: ${underlyingAsset}`
+    );
   }

79-112: Add deployment status verification

Add verification steps after deployment to ensure the event emitter is properly initialized.

   await eventEmitterProxy.deployed();
+  
+  // Verify deployment
+  const deployedEmitter = await hre.ethers.getContractAt(
+    "TermVaultEventEmitter",
+    await eventEmitterProxy.getAddress(),
+    managedSigner
+  );
+  
+  // Verify initialization
+  const actualAdmin = await deployedEmitter.admin();
+  const actualDevops = await deployedEmitter.devops();
+  if (actualAdmin.toLowerCase() !== admin.toLowerCase() || 
+      actualDevops.toLowerCase() !== devops.toLowerCase()) {
+    throw new Error("Event emitter initialization verification failed");
+  }

   console.log("Deployed event emitter proxy to:", eventEmitterProxy.address);
🧰 Tools
🪛 Biome (1.9.4)

[error] 91-91: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)


130-132: Remove redundant null check

The managedSigner is always defined at this point, making the null coalescing operator unnecessary.

   const Strategy = (await hre.ethers.getContractFactory("Strategy")).connect(
-    managedSigner ?? null
+    managedSigner
   );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between caac109 and 92ba27f.

📒 Files selected for processing (2)
  • hardhat-scripts/deploy-strategy.ts (1 hunks)
  • package.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🧰 Additional context used
🪛 Biome (1.9.4)
hardhat-scripts/deploy-strategy.ts

[error] 91-91: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)


[error] 25-25: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Comment on lines +20 to +30
function stringToUintArray(input: string): number[] {
if (!input) return [];
return input.split(",").map((num) => {
const trimmed = num.trim();
const parsed = parseInt(trimmed);
if (isNaN(parsed) || parsed.toString() !== trimmed) {
throw new Error(`Invalid number: ${trimmed}`);
}
return parsed;
});
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace unsafe isNaN with Number.isNaN

The isNaN function performs type coercion which can lead to unexpected results. Use Number.isNaN for safer number validation.

   return input.split(",").map((num) => {
     const trimmed = num.trim();
     const parsed = parseInt(trimmed);
-    if (isNaN(parsed) || parsed.toString() !== trimmed) {
+    if (Number.isNaN(parsed) || parsed.toString() !== trimmed) {
       throw new Error(`Invalid number: ${trimmed}`);
     }
     return parsed;
   });
📝 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
function stringToUintArray(input: string): number[] {
if (!input) return [];
return input.split(",").map((num) => {
const trimmed = num.trim();
const parsed = parseInt(trimmed);
if (isNaN(parsed) || parsed.toString() !== trimmed) {
throw new Error(`Invalid number: ${trimmed}`);
}
return parsed;
});
}
function stringToUintArray(input: string): number[] {
if (!input) return [];
return input.split(",").map((num) => {
const trimmed = num.trim();
const parsed = parseInt(trimmed);
if (Number.isNaN(parsed) || parsed.toString() !== trimmed) {
throw new Error(`Invalid number: ${trimmed}`);
}
return parsed;
});
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 25-25: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@robotoer robotoer merged commit abb1d78 into master Dec 19, 2024
4 checks passed
@robotoer robotoer deleted the hardhat-script branch December 19, 2024 22:19
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