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 params to IR factory #198

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

Conversation

andresaiello
Copy link
Collaborator

@andresaiello andresaiello commented Dec 10, 2024

Summary

  • Add image to IR
  • Add description
  • Remove withdraw validation
  • Add index to event
  • Fix test

Summary by CodeRabbit

  • New Features

    • Enhanced InstantRewardsFactory contract with additional parameters for creating instant rewards.
    • New metadata fields added to the InstantRewardsV2 contract, including promotional and avatar URLs, and a description.
    • Updated network configurations for zeta_testnet and added new settings for zeta_mainnet.
    • Updated verification process to include optional contract type specification.
  • Bug Fixes

    • Modified withdrawal logic in the InstantRewardsV2 contract to allow withdrawals even when rewards are active.
  • Chores

    • Updated deployment scripts and test cases to accommodate new parameters and changes in contract behavior.
    • Updated address entries in the addresses.json file for both testnet and mainnet.

Copy link

coderabbitai bot commented Dec 10, 2024

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.

packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

TypeError: prettier.resolveConfig.sync is not a function
Occurred while linting /packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts:1
Rule: "prettier/prettier"
at Program (/node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js:138:40)
at ruleErrorHandler (/node_modules/eslint/lib/linter/linter.js:1076:28)
at /node_modules/eslint/lib/linter/safe-emitter.js:45:58
at Array.forEach ()
at Object.emit (/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (/node_modules/eslint/lib/linter/node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (/node_modules/eslint/lib/linter/node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (/node_modules/eslint/lib/linter/node-event-generator.js:340:14)
at CodePathAnalyzer.enterNode (/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:803:23)
at /node_modules/eslint/lib/linter/linter.js:1111:32

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces significant changes to the InstantRewardsFactory and InstantRewardsV2 contracts, enhancing their functionality by adding new parameters and modifying existing methods. The InstantRewardsFactory now inherits from Ownable, and its event and method signatures have been updated to accommodate additional metadata. The InstantRewardsV2 contract has been adjusted to include new state variables and constructor parameters. Additionally, updates to the addresses.json file and the Hardhat configuration reflect these changes, while tests have been modified to align with the new contract behaviors.

Changes

File Change Summary
packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsFactory.sol - Inherited from Ownable instead of Ownable2Step.
- Updated InstantRewardsCreated event to include string indexed name.
- Modified createInstantRewards to accept additional parameters: promoUrl, avatarUrl, description.
packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsV2.sol - Added state variables: promoUrl, avatarUrl, description.
- Updated constructor to accept new parameters.
- Modified withdrawal logic by removing prior active reward check.
packages/zevm-app-contracts/data/addresses.json - Added InstantRewardsFactory address in zeta_testnet.
- Updated InstantRewards address in zeta_mainnet.
packages/zevm-app-contracts/hardhat.config.ts - Updated zeta_testnet API and browser URLs.
- Added new network configuration for zeta_mainnet.
packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts - Updated owner address.
- Changed saved address key from "InstantRewards" to "InstantRewardsFactory".
packages/zevm-app-contracts/test/instant-rewards/instant-rewards-v2-compatibility.ts - Updated deploy method to include new parameters.
- Renamed and modified test case logic regarding withdrawals.
packages/zevm-app-contracts/test/instant-rewards/instant-rewards-v2.ts - Updated createInstantRewards method calls in tests to include new parameters.
- Removed ownership acceptance logic from beforeEach setup.

Possibly related PRs

Suggested reviewers

  • GMaiolo

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request.


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

🧹 Outside diff range and nitpick comments (8)
packages/zevm-app-contracts/hardhat.config.ts (1)

55-61: Consider enhancing mainnet configuration security and reliability

While the configuration is functional, there are several production-grade improvements to consider:

  1. Using a public RPC endpoint (blockpi.network) for mainnet could lead to rate limiting or reliability issues
  2. The gasMultiplier of 3 might be excessive and lead to higher transaction costs
  3. The private keys are directly used from environment variables without additional validation

Consider these improvements:

  1. Use multiple RPC endpoints with fallback mechanism
  2. Implement a more conservative gas multiplier (1.2-1.5 range)
  3. Add environment variable validation
 zeta_mainnet: {
   accounts: PRIVATE_KEYS,
   chainId: 7000,
   gas: "auto",
-  gasMultiplier: 3,
+  gasMultiplier: 1.2,
-  url: `https://zetachain-evm.blockpi.network/v1/rpc/public`,
+  url: process.env.ZETA_MAINNET_RPC_URL || "https://zetachain-evm.blockpi.network/v1/rpc/public",
 },

Add at the top of the file:

if (process.env.NODE_ENV === 'production' && !process.env.ZETA_MAINNET_RPC_URL) {
  throw new Error('ZETA_MAINNET_RPC_URL is required for production deployment');
}
packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsFactory.sol (2)

16-16: Event parameter indexing may not be efficient for strings

Indexing the string parameter name in the InstantRewardsCreated event can be costly due to the way strings are handled in event logs. Since strings are hashed when indexed, it may not provide meaningful filtering capability. Consider using a bytes32 or avoiding indexing the name if not essential.


43-52: Align parameter order for clarity and maintainability

In the instantiation of InstantRewardsV2, the parameters are passed in an order that may not align with the constructor's definition or logical grouping. Consider ordering the parameters logically, grouping related parameters together (e.g., all URLs together).

Apply this diff to reorder the parameters:

 InstantRewardsV2 instantRewards = new InstantRewardsV2(
     signerAddress,
     owner(),
     start,
     end,
     name,
-    promoUrl,
     avatarUrl,
+    promoUrl,
     description
 );

Ensure that this change corresponds to the constructor's parameter order in InstantRewardsV2.

packages/zevm-app-contracts/test/instant-rewards/instant-rewards-v2-compatibility.ts (2)

51-60: Update test setup to handle new constructor parameters

The added parameters in the InstantRewardsV2 deployment require corresponding assertions to validate their correctness. Consider adding tests to verify that these parameters are set as expected after deployment.

Add assertions to check the new parameters:

expect(await instantRewards.name()).to.equal("Instant Rewards");
expect(await instantRewards.promoUrl()).to.equal("http://img.com");
expect(await instantRewards.avatarUrl()).to.equal("http://avatar.com");
expect(await instantRewards.description()).to.equal("Description");

Line range hint 334-343: Test description does not match the test logic

The test case is titled "Should be able to withdraw an active IR," but there is no assertion or verification of the withdrawal outcome. Include assertions to confirm that the withdrawal behaves as expected during the active period.

Add assertions to validate the withdrawal:

await expect(
  instantRewards.withdraw(user.address, amountToWithdraw)
).to.emit(instantRewards, "Withdrawn").withArgs(user.address, amountToWithdraw);

const contractBalance = await ethers.provider.getBalance(instantRewards.address);
expect(contractBalance).to.equal(amount.sub(amountToWithdraw));
packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsV2.sol (2)

Line range hint 21-38: Consider grouping related constructor parameters

The constructor parameters mix core functionality (addresses, timeframe) with metadata. Consider reordering parameters to group related fields together.

 constructor(
     address signerAddress_,
     address owner,
     uint256 start_,
     uint256 end_,
-    string memory name_,
-    string memory promoUrl_,
-    string memory avatarUrl_,
-    string memory description_
+    // Metadata group
+    string memory name_,
+    string memory description_,
+    string memory promoUrl_,
+    string memory avatarUrl_
 )

Line range hint 61-63: Critical: Restore withdraw validation or document security implications

The removal of the active status check in the withdraw function could allow premature withdrawal of funds before the reward period ends. This is a significant security change that could affect user trust.

Additionally, consider adding an event emission for withdrawals to improve transparency.

 function withdraw(address wallet, uint256 amount) public override onlyOwner {
+    if (isActive()) revert InstantRewardStillActive();
     super.withdraw(wallet, amount);
+    emit Withdrawal(wallet, amount);
 }

+ event Withdrawal(address indexed wallet, uint256 amount);
packages/zevm-app-contracts/test/instant-rewards/instant-rewards-v2.ts (1)

Line range hint 1-81: Add test coverage for modified withdraw behavior

The removal of withdraw validation requires comprehensive test coverage to ensure security. Add test cases for:

  • Withdrawal during active period
  • Withdrawal after period ends
  • Multiple withdrawals

Example test structure:

describe("withdraw", () => {
  it("Should allow withdrawal after period ends", async () => {
    // Setup and advance time past end
    await ethers.provider.send("evm_increaseTime", [end + 1]);
    await expect(instantRewards.withdraw(wallet.address, amount))
      .to.emit(instantRewards, "Withdrawal")
      .withArgs(wallet.address, amount);
  });
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0f7b077 and 908d098.

📒 Files selected for processing (7)
  • packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsFactory.sol (4 hunks)
  • packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsV2.sol (2 hunks)
  • packages/zevm-app-contracts/data/addresses.json (2 hunks)
  • packages/zevm-app-contracts/hardhat.config.ts (2 hunks)
  • packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (2 hunks)
  • packages/zevm-app-contracts/test/instant-rewards/instant-rewards-v2-compatibility.ts (3 hunks)
  • packages/zevm-app-contracts/test/instant-rewards/instant-rewards-v2.ts (3 hunks)
🔇 Additional comments (7)
packages/zevm-app-contracts/hardhat.config.ts (1)

43-44: LGTM: BlockScout explorer URLs updated correctly

The updated BlockScout URLs for the testnet are correct and align with the current ZetaChain testnet infrastructure.

packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsFactory.sol (2)

4-4: Reverting to Ownable may reduce security during ownership transfers

The change from Ownable2Step to Ownable alters the ownership handover process from a two-step procedure to a single-step, which can be less secure. Consider whether this change is intentional and assess its impact on the contract's security and administrative controls.


54-54: Ensure consistency in event emission parameters

The InstantRewardsCreated event now includes the name parameter. Ensure that all emitted parameters are accurate and consistent with the event definition, especially if additional parameters are added in the future.

packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (2)

10-10: Confirm the ownership address is correct

The owner address has been updated. Verify that 0xD7E8bD37db625a4856E056D2617C9d140dB99182 is the intended owner, and that it aligns with your deployment and administration plans.


24-24: Update the address label to match the deployed contract

The address is being saved under the key "InstantRewardsFactory", which reflects the deployment of the InstantRewardsFactory contract. Ensure that this change is intentional and consistent across your deployment scripts and configuration files.

packages/zevm-app-contracts/data/addresses.json (2)

15-16: Ensure the new InstantRewardsFactory address is correctly integrated

The addition of "InstantRewardsFactory" with address "0x02F054A5BeeB2653d1c2403cBe9B262356fdD5E4" requires that all components referencing this contract are updated accordingly. Verify that any services, scripts, or front-end applications consuming this address are adjusted to prevent inconsistencies.


26-26: Confirm the updated InstantRewards address for mainnet

The InstantRewards address on mainnet has changed. Ensure that this update is reflected across all environments and that any dependencies or integrations are using the correct address.

Comment on lines +30 to +33
string memory name,
string memory promoUrl,
string memory avatarUrl,
string memory description
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider validating new string parameters to prevent empty values

The new parameters promoUrl, avatarUrl, and description are accepted without validation. To ensure data integrity, consider adding checks to validate that these strings are not empty and conform to expected formats.

Apply this diff to add validation:

+    if (bytes(promoUrl).length == 0) revert EmptyPromoUrl();
+    if (bytes(avatarUrl).length == 0) revert EmptyAvatarUrl();
+    if (bytes(description).length == 0) revert EmptyDescription();

Ensure to define the new error types accordingly.

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

Comment on lines +11 to +13
string public promoUrl;
string public avatarUrl;
string public description;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding length validation for metadata fields

The new public string variables could lead to excessive gas costs during deployment if the strings are too long. Consider adding length validation in the constructor.

+ error MetadataFieldTooLong();
+ uint256 private constant MAX_METADATA_LENGTH = 512; // Adjust as needed

  constructor(...) {
+     if (
+         bytes(promoUrl_).length > MAX_METADATA_LENGTH ||
+         bytes(avatarUrl_).length > MAX_METADATA_LENGTH ||
+         bytes(description_).length > MAX_METADATA_LENGTH
+     ) revert MetadataFieldTooLong();
      // existing code
  }

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

Comment on lines +27 to +29
const tx = instantRewardsFactory
.connect(owner)
.createInstantRewards(signer.address, start, end, name, "http://img.com", "http://avatar.com", "Description");
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage for metadata fields

The current tests only verify happy path scenarios with hardcoded values. Consider adding test cases for:

  • Empty strings
  • Maximum length validation
  • Special characters in URLs
  • Invalid URL formats

Example test structure:

it("Should revert when metadata exceeds maximum length", async () => {
  const longString = "a".repeat(1000);
  await expect(
    instantRewardsFactory.createInstantRewards(
      signer.address,
      start,
      end,
      name,
      longString,
      "http://avatar.com",
      "Description"
    )
  ).to.be.revertedWith("MetadataFieldTooLong");
});

Also applies to: 51-59, 70-78

GMaiolo
GMaiolo previously approved these changes Dec 10, 2024
Copy link
Collaborator

@GMaiolo GMaiolo left a comment

Choose a reason for hiding this comment

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

LGTM

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

🧹 Nitpick comments (2)
packages/zevm-app-contracts/scripts/explorer.helpers.ts (1)

7-18: Consider reducing code duplication in verification logic

The current implementation duplicates the run call with nearly identical parameters. Consider consolidating the logic to improve maintainability.

-    if (contract) {
-      await run("verify:verify", {
-        address: contractAddress,
-        constructorArguments,
-        contract,
-      });
-    } else {
-      await run("verify:verify", {
-        address: contractAddress,
-        constructorArguments,
-      });
-    }
+    await run("verify:verify", {
+      address: contractAddress,
+      constructorArguments,
+      ...(contract && { contract }),
+    });
packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (1)

23-24: Extract magic numbers into named constants

The timestamp calculations use magic numbers for time calculations. Consider extracting these into named constants for better readability and maintainability.

+const WEEK_IN_SECONDS = 60 * 60 * 24 * 7;
+const CAMPAIGN_START_DELAY = WEEK_IN_SECONDS;
+const CAMPAIGN_DURATION = WEEK_IN_SECONDS * 4;
-  const start = timestamp + 60 * 60 * 24 * 7; // 1 week from now
-  const end = start + 60 * 60 * 24 * 7 * 4; // 4 weeks from start
+  const start = timestamp + CAMPAIGN_START_DELAY;
+  const end = start + CAMPAIGN_DURATION;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 908d098 and ded93e7.

📒 Files selected for processing (5)
  • packages/zevm-app-contracts/contracts/instant-rewards/InstantRewards.sol (1 hunks)
  • packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsFactory.sol (4 hunks)
  • packages/zevm-app-contracts/data/addresses.json (2 hunks)
  • packages/zevm-app-contracts/scripts/explorer.helpers.ts (1 hunks)
  • packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/zevm-app-contracts/data/addresses.json
🔇 Additional comments (3)
packages/zevm-app-contracts/contracts/instant-rewards/InstantRewardsFactory.sol (2)

30-33: Add input validation for new URL and description parameters

The new parameters promoUrl, avatarUrl, and description are accepted without validation.


43-53: 🛠️ Refactor suggestion

Consider emitting event before external contract creation

The InstantRewardsCreated event is emitted after creating the new contract. Consider emitting it before to follow the checks-effects-interactions pattern and potentially save gas.

+        emit InstantRewardsCreated(address(instantRewards), owner(), name);
         InstantRewardsV2 instantRewards = new InstantRewardsV2(
             signerAddress,
             owner(),
             start,
             end,
             name,
             promoUrl,
             avatarUrl,
             description
         );
-        emit InstantRewardsCreated(address(instantRewards), owner(), name);
         return address(instantRewards);

Likely invalid or redundant comment.

packages/zevm-app-contracts/contracts/instant-rewards/InstantRewards.sol (1)

Line range hint 36-93: Implementation Review: Strong Security Foundations

The implementation demonstrates several security best practices:

  • Robust signature verification using EIP712
  • Proper reentrancy protection with nonReentrant modifier
  • Comprehensive event emissions for tracking
  • Clear error handling with custom errors
  • Appropriate access controls

@@ -1,10 +1,10 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security: Consider retaining Ownable2Step for enhanced ownership transfer safety

The change from Ownable2Step to Ownable removes the two-step ownership transfer safety mechanism. This could potentially lead to accidental transfers of ownership if the wrong address is provided.

-import "@openzeppelin/contracts/access/Ownable.sol";
+import "@openzeppelin/contracts/access/Ownable2Step.sol";

-contract InstantRewardsFactory is Ownable {
+contract InstantRewardsFactory is Ownable2Step {

Also applies to: 7-7

Comment on lines 11 to 14
const OWNERS = {
zeta_mainnet: "0xD7E8bD37db625a4856E056D2617C9d140dB99182",
zeta_testnet: "0xD7E8bD37db625a4856E056D2617C9d140dB99182",
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider moving OWNERS addresses to configuration file

Hardcoded addresses should be moved to a configuration file for better maintainability and to follow separation of concerns.

Consider creating a config.ts file to store network-specific configurations.

Comment on lines +36 to +38
const tx = await instantRewards.createInstantRewards(...params, {
gasLimit: 25000000,
});
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 hardcoding gas limit

The gas limit is hardcoded to 25000000. Consider making this configurable or estimating it dynamically.

-  const tx = await instantRewards.createInstantRewards(...params, {
-    gasLimit: 25000000,
-  });
+  const gasEstimate = await instantRewards.estimateGas.createInstantRewards(...params);
+  const tx = await instantRewards.createInstantRewards(...params, {
+    gasLimit: Math.ceil(gasEstimate * 1.2), // Add 20% buffer
+  });
📝 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 instantRewards.createInstantRewards(...params, {
gasLimit: 25000000,
});
const gasEstimate = await instantRewards.estimateGas.createInstantRewards(...params);
const tx = await instantRewards.createInstantRewards(...params, {
gasLimit: Math.ceil(gasEstimate * 1.2), // Add 20% buffer
});

Comment on lines +45 to +48
if (!event) throw new Error("InstantRewardsCreated event not found");
//@ts-ignore
const instantRewardsAddress = event.args[0];
if (!instantRewardsAddress) throw new Error("InstantRewards address not found");
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety in event handling

The code uses TypeScript ignores and unsafe type assertions. Consider using proper type guards and event parsing.

-  if (!event) throw new Error("InstantRewardsCreated event not found");
-  //@ts-ignore
-  const instantRewardsAddress = event.args[0];
-  if (!instantRewardsAddress) throw new Error("InstantRewards address not found");
+  if (!event || !event.args) throw new Error("InstantRewardsCreated event not found");
+  const [instantRewardsAddress, , ] = event.args;
+  if (!ethers.utils.isAddress(instantRewardsAddress)) {
+    throw new Error("Invalid InstantRewards address");
+  }
📝 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
if (!event) throw new Error("InstantRewardsCreated event not found");
//@ts-ignore
const instantRewardsAddress = event.args[0];
if (!instantRewardsAddress) throw new Error("InstantRewards address not found");
if (!event || !event.args) throw new Error("InstantRewardsCreated event not found");
const [instantRewardsAddress, , ] = event.args;
if (!ethers.utils.isAddress(instantRewardsAddress)) {
throw new Error("Invalid InstantRewards address");
}

@@ -2,12 +2,12 @@
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security Consideration: Removal of Two-Step Ownership Transfer

The change from Ownable2Step to Ownable removes an important security feature. The two-step ownership transfer pattern provides protection against accidental transfers to incorrect addresses.

Consider keeping Ownable2Step to maintain the safer two-step ownership transfer process:

-import "@openzeppelin/contracts/access/Ownable.sol";
+import "@openzeppelin/contracts/access/Ownable2Step.sol";
📝 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
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";

import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

contract InstantRewards is Ownable2Step, Pausable, ReentrancyGuard, EIP712 {
contract InstantRewards is Ownable, Pausable, ReentrancyGuard, EIP712 {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security Risk: Immediate Ownership Transfers

The inheritance change from Ownable2Step to Ownable makes ownership transfers immediate without the safety of a two-step process. This could be particularly risky for a contract handling financial rewards.

Restore the safer ownership model:

-contract InstantRewards is Ownable, Pausable, ReentrancyGuard, EIP712 {
+contract InstantRewards is Ownable2Step, Pausable, ReentrancyGuard, EIP712 {

Additionally, update the constructor:

-constructor(address signerAddress_, address owner) Ownable() EIP712("InstantRewards", "1") {
+constructor(address signerAddress_, address owner) Ownable2Step() EIP712("InstantRewards", "1") {

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

GMaiolo
GMaiolo previously approved these changes Dec 16, 2024
Copy link
Collaborator

@GMaiolo GMaiolo left a comment

Choose a reason for hiding this comment

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

utACK

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)
packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (3)

23-24: Extract time calculations to configuration

Time calculations are hardcoded. Consider moving these to configuration for better maintainability:

+const TIME_CONFIG = {
+  REWARD_START_DELAY: 7 * 24 * 60 * 60, // 1 week
+  REWARD_DURATION: 4 * 7 * 24 * 60 * 60, // 4 weeks
+};
+
-  const start = timestamp + 60 * 60 * 24 * 7; // 1 week from now
-  const end = start + 60 * 60 * 24 * 7 * 4; // 4 weeks from start
+  const start = timestamp + TIME_CONFIG.REWARD_START_DELAY;
+  const end = start + TIME_CONFIG.REWARD_DURATION;

64-66: Add error handling for contract deployment

Add proper error handling and deployment confirmation:

-  const instantRewards = await InstantRewardsFactory.deploy(owner);
-  await instantRewards.deployed();
+  const instantRewards = await InstantRewardsFactory.deploy(owner)
+    .catch((error) => {
+      console.error('Contract deployment failed:', error);
+      throw error;
+    });
+  
+  console.log('Waiting for deployment confirmation...');
+  await instantRewards.deployed()
+    .catch((error) => {
+      console.error('Contract deployment confirmation failed:', error);
+      throw error;
+    });

Line range hint 77-86: Enhance error handling with custom error types

Consider implementing custom error types for better error handling:

+class DeploymentError extends Error {
+  constructor(message: string, public readonly cause?: unknown) {
+    super(message);
+    this.name = 'DeploymentError';
+  }
+}

 const main = async () => {
   if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name");
   const instantRewards = await deployInstantRewards();
   await deployInstantRewardsSample(instantRewards);
 };

-main().catch((error) => {
-  console.error(error);
+main().catch((error: unknown) => {
+  if (error instanceof DeploymentError) {
+    console.error('Deployment failed:', error.message);
+    if (error.cause) console.error('Caused by:', error.cause);
+  } else {
+    console.error('Unexpected error:', error);
+  }
   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 ded93e7 and 75dbf0f.

📒 Files selected for processing (2)
  • packages/zevm-app-contracts/data/addresses.json (2 hunks)
  • packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/zevm-app-contracts/data/addresses.json
🔇 Additional comments (4)
packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (4)

11-14: Consider moving OWNERS addresses to configuration file

Hardcoded addresses should be moved to a configuration file for better maintainability and to follow separation of concerns.


36-38: Avoid hardcoding gas limit

The gas limit is hardcoded to 25000000. Consider making this configurable or estimating it dynamically.


45-48: Improve type safety in event handling

The code uses TypeScript ignores and unsafe type assertions. Consider using proper type guards and event parsing.


26-34: 🛠️ Refactor suggestion

Move metadata to configuration file

Static metadata like URLs and descriptions should be configuration-driven:

+interface RewardMetadata {
+  name: string;
+  promoUrl: string;
+  avatarUrl: string;
+  description: string;
+}
+
+const REWARD_METADATA: Record<string, RewardMetadata> = {
+  zeta_mainnet: {
+    name: "ZetaChain",
+    promoUrl: "https://zetachain.io",
+    avatarUrl: "https://zetachain.io/logo.png",
+    description: "ZetaChain description"
+  }
+};
+
+const metadata = REWARD_METADATA[networkName];
+if (!metadata) {
+  throw new Error(`No metadata configured for network: ${networkName}`);
+}
+
 const params = [
   owner,
   start,
   end,
-  "ZetaChain",
-  "https://zetachain.io",
-  "https://zetachain.io/logo.png",
-  "ZetaChain description",
+  metadata.name,
+  metadata.promoUrl,
+  metadata.avatarUrl,
+  metadata.description,
];

Likely invalid or redundant comment.

Comment on lines +16 to +17
//@ts-ignore
const owner = OWNERS[networkName];
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 @ts-ignore and implement proper type checking

Replace the unsafe type assertion with proper type checking:

-//@ts-ignore
-const owner = OWNERS[networkName];
+const owner = OWNERS[networkName as keyof typeof OWNERS];
+if (!owner) {
+  throw new Error(`No owner configured for network: ${networkName}`);
+}
📝 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
//@ts-ignore
const owner = OWNERS[networkName];
const owner = OWNERS[networkName as keyof typeof OWNERS];
if (!owner) {
throw new Error(`No owner configured for network: ${networkName}`);
}

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 (4)
packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (4)

11-14: 🛠️ Refactor suggestion

Move OWNERS addresses to configuration file

Hardcoded addresses in the source code reduce maintainability and violate separation of concerns.

Create a config.ts file to store network-specific configurations:

// config.ts
export const NETWORK_CONFIG = {
  zeta_mainnet: {
    owner: "0xD7E8bD37db625a4856E056D2617C9d140dB99182",
    // other network-specific config...
  },
  zeta_testnet: {
    owner: "0x1d24d94520B94B26351f6573de5ef9731c48531A",
    // other network-specific config...
  }
} as const;

16-17: ⚠️ Potential issue

Remove @ts-ignore and implement proper type checking

Replace the unsafe type assertion with proper type checking:

-//@ts-ignore
-const owner = OWNERS[networkName];
+const owner = OWNERS[networkName as keyof typeof OWNERS];
+if (!owner) {
+  throw new Error(`No owner configured for network: ${networkName}`);
+}

42-44: 🛠️ Refactor suggestion

Avoid hardcoded gas limit

Use dynamic gas estimation instead of hardcoded values:

-  const tx = await instantRewards.createInstantRewards(...params, {
-    gasLimit: 25000000,
-  });
+  const gasEstimate = await instantRewards.estimateGas.createInstantRewards(...params);
+  const tx = await instantRewards.createInstantRewards(...params, {
+    gasLimit: Math.ceil(gasEstimate * 1.2), // Add 20% buffer
+  });

51-54: ⚠️ Potential issue

Improve type safety in event handling

Replace unsafe type assertions with proper type handling:

-  if (!event) throw new Error("InstantRewardsCreated event not found");
-  //@ts-ignore
-  const instantRewardsAddress = event.args[0];
-  if (!instantRewardsAddress) throw new Error("InstantRewards address not found");
+  if (!event || !event.args) throw new Error("InstantRewardsCreated event not found");
+  const [instantRewardsAddress, , ] = event.args;
+  if (!ethers.utils.isAddress(instantRewardsAddress)) {
+    throw new Error("Invalid InstantRewards address");
+  }
🧹 Nitpick comments (2)
packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (2)

29-30: Extract time constants to configuration

Hardcoded time durations reduce maintainability and make the code less flexible.

Consider extracting these to configuration:

const TIME_CONFIG = {
  DEPLOYMENT_DELAY_DAYS: 7,
  REWARD_DURATION_WEEKS: 4,
} as const;

const start = timestamp + (TIME_CONFIG.DEPLOYMENT_DELAY_DAYS * 24 * 60 * 60);
const end = start + (TIME_CONFIG.REWARD_DURATION_WEEKS * 7 * 24 * 60 * 60);

78-79: Remove commented out code

Commented out code reduces readability and should be removed if no longer needed.

-  await verifyContract(instantRewards.address, [owner]);
-  // await verifyContract("0xAf5693bBC958e442462F411F46421e389c7A8602", [owner]);
+  await verifyContract(instantRewards.address, [owner]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 75dbf0f and de743de.

📒 Files selected for processing (2)
  • packages/zevm-app-contracts/data/addresses.json (2 hunks)
  • packages/zevm-app-contracts/scripts/instant-rewards/deploy-v2.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/zevm-app-contracts/data/addresses.json

Comment on lines +70 to +72
const instantRewards = await InstantRewardsFactory.deploy(owner);

await instantRewards.deployed();
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add proper error handling for contract deployment

The deployment process lacks proper error handling and deployment confirmation.

+  console.log("Deploying InstantRewardsFactory...");
   const instantRewards = await InstantRewardsFactory.deploy(owner);
+  console.log("Waiting for deployment confirmation...");
   await instantRewards.deployed();
+  const code = await ethers.provider.getCode(instantRewards.address);
+  if (code === "0x") {
+    throw new Error("Contract deployment failed - no code at address");
+  }
📝 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 instantRewards = await InstantRewardsFactory.deploy(owner);
await instantRewards.deployed();
console.log("Deploying InstantRewardsFactory...");
const instantRewards = await InstantRewardsFactory.deploy(owner);
console.log("Waiting for deployment confirmation...");
await instantRewards.deployed();
const code = await ethers.provider.getCode(instantRewards.address);
if (code === "0x") {
throw new Error("Contract deployment failed - no code at address");
}

Comment on lines +86 to +88
const instantRewards = await deployInstantRewards();
await deployInstantRewardsSample(instantRewards.address);
// await deployInstantRewardsSample("0x3A557fe83FD734f21DD35E98f546B9706d486F55");
Copy link

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 and remove commented code

The main function needs better error handling and cleanup of commented code.

-  const instantRewards = await deployInstantRewards();
-  await deployInstantRewardsSample(instantRewards.address);
-  // await deployInstantRewardsSample("0x3A557fe83FD734f21DD35E98f546B9706d486F55");
+  try {
+    console.log("Starting deployment process...");
+    const instantRewards = await deployInstantRewards();
+    console.log("Deploying sample rewards...");
+    await deployInstantRewardsSample(instantRewards.address);
+    console.log("Deployment completed successfully");
+  } catch (error) {
+    console.error("Deployment failed:", error);
+    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 instantRewards = await deployInstantRewards();
await deployInstantRewardsSample(instantRewards.address);
// await deployInstantRewardsSample("0x3A557fe83FD734f21DD35E98f546B9706d486F55");
try {
console.log("Starting deployment process...");
const instantRewards = await deployInstantRewards();
console.log("Deploying sample rewards...");
await deployInstantRewardsSample(instantRewards.address);
console.log("Deployment completed successfully");
} catch (error) {
console.error("Deployment failed:", error);
throw error;
}

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