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 1 commit 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.
  • 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.

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/hardhat.config.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

TypeError: prettier.resolveConfig.sync is not a function
Occurred while linting /packages/zevm-app-contracts/hardhat.config.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

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

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. (Experiment)
  • @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

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

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