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

delete three offers bugs #64

Closed
wants to merge 1 commit into from
Closed

Conversation

aazhou1
Copy link

@aazhou1 aazhou1 commented Oct 7, 2024

Summary by CodeRabbit

  • New Features

    • Improved logic for removing completed auction offers, ensuring proper iteration through the list.
    • Added constants for time and rate precision in auction calculations.
  • Tests

    • Introduced a new test for deleting auction offers, verifying management permissions and state integrity after deletions.

Copy link

coderabbitai bot commented Oct 7, 2024

Walkthrough

The changes in this pull request focus on the removeCompleted function within the TermAuctionList library in src/TermAuctionList.sol, where a line was added to update the current variable after a node is removed. This adjustment ensures proper iteration through the linked list. Additionally, a new test function testDeleteThreeOffers was introduced in src/test/TestUSDCOffers.t.sol to validate the deletion of auction offers, confirming that only management can delete offers and that the state remains consistent post-deletion.

Changes

File Change Summary
src/TermAuctionList.sol Modified removeCompleted function to update current after a node removal.
src/test/TestUSDCOffers.t.sol Added testDeleteThreeOffers method; declared constants THREESIXTY_DAYCOUNT_SECONDS and RATE_PRECISION.

Possibly related issues

Possibly related PRs

  • Fix edit offer #4: Relevant due to modifications in the insertPending function, which also involves linked list handling.
  • Fixes to the list insert functions #46: Addresses issues in the TermAuctionList related to linked list node insertion, aligning with the changes made in this PR.

Poem

🐰 In the land of offers, where bids take flight,
A function was fixed, now it works just right.
With tests to ensure that all's well in the game,
The rabbits rejoice, for we've changed the name!
Hopping through lists, no nodes left behind,
In the world of auctions, our code is refined! 🌟


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

🧹 Outside diff range and nitpick comments (1)
src/TermAuctionList.sol (1)

Line range hint 150-211: Suggestions for improving the removeCompleted function

While the recent change fixes a critical issue, there are several areas where the removeCompleted function could be further improved:

  1. Error Handling: Consider adding try-catch blocks around external calls to offer.offerLocker.lockedOffer(current).amount and offer.termAuction.auctionCompleted() to handle potential reverts gracefully.

  2. Gas Optimization: The function performs multiple storage reads and writes. Consider caching frequently accessed storage variables in memory to reduce gas costs.

  3. Reentrancy Protection: The function modifies state after making external calls. While it doesn't appear to be vulnerable to reentrancy in its current form, it's a good practice to implement a reentrancy guard or follow the checks-effects-interactions pattern more strictly.

  4. Complexity: The function is quite long and handles multiple responsibilities. Consider breaking it down into smaller, more focused functions to improve readability and maintainability.

  5. Event Emission: Consider emitting events when offers are removed or when significant state changes occur. This can aid in off-chain tracking and debugging.

Would you like me to provide a code snippet demonstrating these improvements?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 13341d0 and aeb6db0.

📒 Files selected for processing (2)
  • src/TermAuctionList.sol (1 hunks)
  • src/test/TestUSDCOffers.t.sol (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
src/test/TestUSDCOffers.t.sol (1)

Line range hint 1-391: Overall assessment of changes in TestUSDCOffers.t.sol

The additions to this file, including the new test function testDeleteThreeOffers() and the constants THREESIXTY_DAYCOUNT_SECONDS and RATE_PRECISION, contribute to improved test coverage and calculation precision. These changes align well with the PR objective of addressing "delete three offers bugs".

However, there are opportunities to further enhance the test coverage and improve code organization:

  1. The testDeleteThreeOffers() function could be expanded to cover more scenarios and edge cases.
  2. The placement and visibility of the new constants could be optimized for better readability and encapsulation.

Consider implementing the suggested improvements to make the tests more robust and the code more maintainable. These enhancements will contribute to a more comprehensive test suite and clearer code structure.

src/TermAuctionList.sol (1)

209-210: Approve: Critical fix for offer processing

This change is crucial for the correct functioning of the removeCompleted function. By setting current = prev; after removing a node, it ensures that no offers are skipped during the removal process.

Before this fix, if a node was removed, the next iteration would skip the node that was originally after the removed node. This could lead to some offers not being properly processed or removed.

With this change, the function will correctly process all offers in the list, maintaining the integrity of the offer removal process.

Comment on lines +112 to +134
function testDeleteThreeOffers() public {
bytes32 offerId1 = _submitOffer(bytes32("offer id hash 1"), 1e6);
bytes32 offerId2 = _submitOffer(bytes32("offer id hash 2"), 1e6);
bytes32 offerId3 = _submitOffer(bytes32("offer id hash 3"), 1e6);

bytes32[] memory offerIds = new bytes32[](3);
offerIds[0] = offerId1;
offerIds[1] = offerId2;
offerIds[2] = offerId3;

vm.expectRevert("!management");
termStrategy.deleteAuctionOffers(address(repoToken1WeekAuction), offerIds);

vm.prank(management);
termStrategy.deleteAuctionOffers(address(repoToken1WeekAuction), offerIds);

bytes32[] memory offers = termStrategy.pendingOffers();

assertEq(offers.length, 0);

assertEq(termStrategy.totalLiquidBalance(), initialState.totalLiquidBalance);
assertEq(termStrategy.totalAssetValue(), termStrategy.totalLiquidBalance());
}
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 and assertions in testDeleteThreeOffers()

The test function effectively covers the basic scenario of deleting three offers. However, consider the following improvements to make it more robust:

  1. Add assertions to verify the state after submitting the offers and before deletion.
  2. Test partial deletion of offers (e.g., delete only two out of three offers).
  3. Use a more specific error message in the revert check, such as "Caller is not the management".
  4. Add a test case for deleting non-existent offers.

Here's an example of how you could enhance the test:

function testDeleteThreeOffers() public {
    bytes32 offerId1 = _submitOffer(bytes32("offer id hash 1"), 1e6);
    bytes32 offerId2 = _submitOffer(bytes32("offer id hash 2"), 1e6);
    bytes32 offerId3 = _submitOffer(bytes32("offer id hash 3"), 1e6);

    // Assert state after submitting offers
    assertEq(termStrategy.pendingOffers().length, 3);
    assertEq(termStrategy.totalLiquidBalance(), initialState.totalLiquidBalance - 3e6);

    bytes32[] memory offerIds = new bytes32[](3);
    offerIds[0] = offerId1;
    offerIds[1] = offerId2;
    offerIds[2] = offerId3;

    vm.expectRevert("Caller is not the management");
    termStrategy.deleteAuctionOffers(address(repoToken1WeekAuction), offerIds);

    // Test partial deletion
    bytes32[] memory partialOfferIds = new bytes32[](2);
    partialOfferIds[0] = offerId1;
    partialOfferIds[1] = offerId2;

    vm.prank(management);
    termStrategy.deleteAuctionOffers(address(repoToken1WeekAuction), partialOfferIds);

    assertEq(termStrategy.pendingOffers().length, 1);
    assertEq(termStrategy.totalLiquidBalance(), initialState.totalLiquidBalance - 1e6);

    // Delete remaining offer
    vm.prank(management);
    termStrategy.deleteAuctionOffers(address(repoToken1WeekAuction), new bytes32[](1));

    bytes32[] memory offers = termStrategy.pendingOffers();        
    assertEq(offers.length, 0);
    assertEq(termStrategy.totalLiquidBalance(), initialState.totalLiquidBalance);
    assertEq(termStrategy.totalAssetValue(), termStrategy.totalLiquidBalance());

    // Test deleting non-existent offers
    vm.prank(management);
    termStrategy.deleteAuctionOffers(address(repoToken1WeekAuction), offerIds);
    // Assert that no changes occur when deleting non-existent offers
    assertEq(termStrategy.totalLiquidBalance(), initialState.totalLiquidBalance);
    assertEq(termStrategy.totalAssetValue(), termStrategy.totalLiquidBalance());
}

These enhancements will provide more comprehensive coverage and help catch potential edge cases.

Comment on lines +136 to 137

uint256 public constant THREESIXTY_DAYCOUNT_SECONDS = 360 days;
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 constant declarations and placement

The newly added constants THREESIXTY_DAYCOUNT_SECONDS and RATE_PRECISION are well-named and their values are appropriate for their intended use. However, consider the following improvements:

  1. Change the visibility to internal instead of public as these are test constants:

    uint256 internal constant THREESIXTY_DAYCOUNT_SECONDS = 360 days;
    uint256 internal constant RATE_PRECISION = 1e18;
  2. Move these constants to the top of the contract, just after the contract declaration, to improve readability and follow common conventions:

    contract TestUSDCSubmitOffer is Setup {
        uint256 internal constant THREESIXTY_DAYCOUNT_SECONDS = 360 days;
        uint256 internal constant RATE_PRECISION = 1e18;
    
        // ... rest of the contract code ...
    }
  3. Add a comment explaining the use of 360 days instead of 365 days for THREESIXTY_DAYCOUNT_SECONDS:

    // Using 360 days for financial year calculations (30/360 day count convention)
    uint256 internal constant THREESIXTY_DAYCOUNT_SECONDS = 360 days;

These changes will improve the overall structure and clarity of the contract.

@@ -206,6 +206,8 @@ library TermAuctionList {
listData.nodes[prev].next = next;
delete listData.nodes[current];
delete listData.offers[current];
current = prev;

Copy link
Collaborator

Choose a reason for hiding this comment

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

I suggest the following optimization to avoid useless assignments:

    if (removeNode) {
        // Update the list to remove the current node
        delete listData.nodes[current];
        delete listData.offers[current];
        if (current == listData.head) {
            listData.head = next;
        } else {
            listData.nodes[prev].next = next;
            current = prev;
        }
   }

@aazhou1 aazhou1 closed this Oct 8, 2024
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