Skip to content

Conversation

@lirona
Copy link
Collaborator

@lirona lirona commented Apr 28, 2025

Summary by CodeRabbit

  • New Features

    • Added the ability for managers to withdraw funds and set rewards.
    • Introduced functions to pause and unpause contracts with appropriate role restrictions.
    • Added new user actions for staking, unstaking, and claiming rewards, with enhanced validation and support for both ERC20 and native tokens.
    • Provided new view functions to check reward calculations, claim status, and stake/round information.
    • Enabled combined project creation (Hyperfund and Hyperstaker) in one step.
  • Documentation

    • Improved and expanded user-facing documentation and descriptions across all major functions for better clarity.

@lirona lirona linked an issue Apr 28, 2025 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented Apr 28, 2025

Walkthrough

The changes introduce significant refactoring, documentation, and feature additions to the Hyperfund, HyperfundFactory, and Hyperstaker contracts. In Hyperfund, functions are reorganized for clarity, with enhanced NatSpec comments, stricter access control, helper functions for unit conversions, and a new withdrawal function for managers. HyperfundFactory gains a new createProject method for combined deployment of Hyperfund and Hyperstaker, alongside improved documentation. Hyperstaker is expanded with administrative controls, user staking and reward functions, detailed NatSpec comments, and new view and helper methods for querying and managing stake and reward data.

Changes

File(s) Change Summary
src/Hyperfund.sol Refactored function organization and comments, enhanced NatSpec documentation, stricter manager-only access for nonfinancial contributions, new helper functions for unit conversion, explicit withdrawal and pausing functions, and improved parameter naming and validation.
src/HyperfundFactory.sol Added createProject function to deploy both Hyperfund and Hyperstaker together, introduced NatSpec documentation for public functions, and removed outdated comments.
src/Hyperstaker.sol Added admin functions for reward management and pausing, reorganized user functions with NatSpec comments, introduced staking, unstaking, and reward claiming with explicit checks, and new view/helper functions for stake and round queries.

Sequence Diagram(s)

sequenceDiagram
    participant Manager
    participant HyperfundFactory
    participant Hyperfund
    participant Hyperstaker

    Manager->>HyperfundFactory: createProject(hypercertTypeId, admin, manager, pauser, upgrader)
    HyperfundFactory->>Hyperfund: deploy(hypercertTypeId, admin, manager, pauser, upgrader)
    HyperfundFactory->>Hyperstaker: deploy(hypercertTypeId, admin, manager, pauser, upgrader)
    HyperfundFactory-->>Manager: return (Hyperfund, Hyperstaker addresses)
Loading
sequenceDiagram
    participant Manager
    participant Hyperfund

    Manager->>Hyperfund: nonfinancialContribution(contributor, units)
    Hyperfund->>Hyperfund: _nonfinancialContribution(contributor, units)
    Hyperfund->>Hyperfund: _mintFraction(contributor, units)
    Hyperfund-->>Manager: Hypercert fraction issued
Loading
sequenceDiagram
    participant User
    participant Hyperstaker

    User->>Hyperstaker: stake(hypercertId)
    Hyperstaker->>Hyperstaker: record stake

    User->>Hyperstaker: claimReward(hypercertId, roundId)
    Hyperstaker->>Hyperstaker: check eligibility and claim status
    Hyperstaker->>User: transfer reward
Loading

Possibly related PRs

Poem

In fields of code where carrots grow,
Hyperfund and friends now steal the show!
With roles and docs all neat and clear,
New projects bloom—spring is here!
Stake and claim, rewards abound,
Factory magic spins around.
🥕 Cheers to contracts, crisp and bright—
The blockchain garden feels just right!


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@lirona lirona merged commit cea4bca into main Apr 28, 2025
0 of 3 checks passed
@lirona lirona deleted the 23-documentation branch April 28, 2025 12:30
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: 0

🔭 Outside diff range comments (6)
src/HyperfundFactory.sol (2)

62-79: ⚠️ Potential issue

Validate all role addresses, not just manager

Only manager is checked against address(0). Supplying a zero address for admin, pauser, or upgrader would brick their respective functionality and make the proxy undeployable if an upgrade or pause is ever required.

-        require(manager != address(0), InvalidAddress());
+        require(
+            admin != address(0) &&
+                manager != address(0) &&
+                pauser != address(0) &&
+                upgrader != address(0),
+            InvalidAddress()
+        );

125-150: 🛠️ Refactor suggestion

createProject misses two critical checks & one approval call

  1. hyperstakers[hypercertTypeId] is not verified before deployment – you can overwrite an existing Hyperstaker.
  2. The Hyperfund created inside this helper never receives setApprovalForAll, leaving it unable to split/burn Hypercerts.
  3. Same zero-address discussion as in createHyperfund.
-        require(hyperfunds[hypercertTypeId] == false, AlreadyDeployed());
+        require(
+            hyperfunds[hypercertTypeId] == false &&
+                hyperstakers[hypercertTypeId] == false,
+            AlreadyDeployed()
+        );
...
-        hyperfund = address(hyperfundProxy);
+        IHypercertToken(hypercertMinter).setApprovalForAll(
+            address(hyperfundProxy),
+            true
+        );
+        hyperfund = address(hyperfundProxy);
src/Hyperstaker.sol (2)

102-118: ⚠️ Potential issue

Guard against zero reward & duplicate native/ERC20 mismatch

  • setReward allows _rewardAmount == 0, creating a round that every staker can claim for zero value but still paying gas.
  • Native branch: a malicious caller can send native value and specify an ERC20 token to lock user ether inside the contract forever (or vice-versa).
         function setReward(address _rewardToken, uint256 _rewardAmount) external payable onlyRole(MANAGER_ROLE) {
+        require(_rewardAmount > 0, IncorrectRewardAmount(0, 1));
+        require(
+            (_rewardToken == address(0) && msg.value == _rewardAmount) ||
+                (_rewardToken != address(0) && msg.value == 0),
+            IncorrectRewardAmount(msg.value, _rewardAmount)
+        );

160-178: 🛠️ Refactor suggestion

claimReward: missing round-index & bitmap bounds checks

Accessing rounds[_roundId] reverts for out-of-range indices, but the error will be a generic VM revert.
Additionally, bit-shifting 1 << _roundId silently returns 0 for _roundId >= 256, breaking the claimed-rounds logic.

         function claimReward(uint256 _hypercertId, uint256 _roundId) external whenNotPaused {
+        require(_roundId < rounds.length, RoundNotSet());
+        require(_roundId < 256, "Round id exceeds bitmap size");
src/Hyperfund.sol (2)

154-172: ⚠️ Potential issue

Prevent zero-unit mints & require allow-listed token in fund

If multiplier < 0 and _amount < abs(multiplier) the computed units becomes 0, yet the user’s tokens are accepted and an empty split occurs.
Also redeem expects the same token to be allow-listed; fund should enforce it.

-        uint256 units = _tokenAmountToUnits(_token, _amount);
+        require(tokenMultipliers[_token] != 0, TokenNotAllowlisted());
+        uint256 units = _tokenAmountToUnits(_token, _amount);
+        require(units != 0, InvalidAmount());

179-195: 🛠️ Refactor suggestion

redeem does not validate token allow-listing

A user can pass an un-listed token, receive tokenAmount == 0, burn their fraction and lose units.

-        uint256 tokenAmount = _unitsToTokenAmount(_token, units);
+        require(tokenMultipliers[_token] != 0, TokenNotAllowlisted());
+        uint256 tokenAmount = _unitsToTokenAmount(_token, units);
🧹 Nitpick comments (2)
src/HyperfundFactory.sol (1)

15-18: Store addresses, not booleans, for easier discovery

mapping(uint256 => bool) public hyperfunds / hyperstakers provides no way for off-chain callers to retrieve the deployed instance without reading events or off-chain indexing.
Switch to mapping(uint256 => address) (zero address = not deployed) for free discovery and contract-to-contract calls.

src/Hyperfund.sol (1)

106-113: withdrawFunds should reject zero recipient & use call for native transfers

Sending to address(0) burns funds.
Using .transfer imposes the 2300-gas stipend and may break with EIP-1884-like gas increases.

-        if (_token == address(0)) {
-            payable(_to).transfer(_amount);
+        require(_to != address(0), InvalidAddress());
+        if (_token == address(0)) {
+            (bool success, ) = payable(_to).call{value: _amount}("");
+            require(success, TransferFailed());
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4fcc33b and 61bad34.

📒 Files selected for processing (3)
  • src/Hyperfund.sol (9 hunks)
  • src/HyperfundFactory.sol (3 hunks)
  • src/Hyperstaker.sol (6 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
src/Hyperfund.sol

[error] 115-119: Prettier/forge fmt formatting check failed. Function signature formatting does not match expected style. Run 'forge fmt' to fix code style issues.

🔇 Additional comments (2)
src/Hyperstaker.sol (1)

186-195: Overflow & division-by-zero risks in calculateReward

round.totalRewards * units * stakeDuration can overflow uint256 for large numbers.
Also round.duration may be 0 (stake and setReward in same block) leading to division-by-zero.

Consider using mulDiv from PRBMath or an equivalent checked-mul-div helper and guard round.duration != 0.

src/Hyperfund.sol (1)

224-231: Division by zero possible in _tokenAmountToUnits & _unitsToTokenAmount

If _multiplier is 0 (should never happen after checks) or -1, the division path can revert or silently succeed with unintended values. Add an explicit multiplier != 0 requirement or guard upstream (see fund/redeem fixes).

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.

Doc: full documentation on all functions

2 participants