Skip to content

feat: add withdraw rate to one way vault#356

Merged
keyleu merged 3 commits into
mainfrom
keyne/add-withdraw-rate
May 26, 2025
Merged

feat: add withdraw rate to one way vault#356
keyleu merged 3 commits into
mainfrom
keyne/add-withdraw-rate

Conversation

@keyleu

@keyleu keyleu commented May 23, 2025

Copy link
Copy Markdown
Contributor

Adds a withdrawalFeeBps to the OneWayVault.

How it works is simple: every time someone withdraws, we burn all the shares but we only store the shares equivalent to the net assets after charging the fee.

Summary by CodeRabbit

  • New Features

    • Introduced a withdrawal fee parameter (withdrawRateBps) in vault configuration.
    • Added a public function to compute withdrawal fees based on the fee rate.
    • Enhanced withdrawal and redemption processes to deduct and track withdrawal fees separately.
    • Updated fee distribution to include accrued withdrawal fees.
  • Bug Fixes

    • Ensured accurate calculation, deduction, and accumulation of withdrawal fees during user operations.
  • Tests

    • Expanded tests to validate withdrawal fee calculation, enforcement, and proper fee distribution.

@coderabbitai

coderabbitai Bot commented May 23, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces a withdrawal fee mechanism to the OneWayVault contract, adding a fee parameter, calculation, and accounting logic. It modifies withdrawal and redemption functions to deduct fees, track accrued fees, and emit relevant events, with comprehensive tests validating the new behavior.

Changes

File(s) Change Summary
solidity/src/vaults/OneWayVault.sol Added withdrawRateBps to config, calculateWithdrawalFee() function, updated _withdraw() signature, modified withdraw() and redeem() to handle fees, renamed feesOwedInAsset to feesAccruedInAsset, and updated fee distribution logic.
solidity/test/vaults/OneWayVault.t.sol Added tests for withdrawRateBps, validation, fee calculations, and integration with deposit/withdrawal flows, ensuring correct fee accrual and distribution.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Vault
    participant FeeCollector

    User->>Vault: withdraw(assets, receiver, owner)
    Vault->>Vault: calculateWithdrawalFee(assets)
    Vault->>Vault: determine sharesToBurn and sharesForRequest
    Vault->>FeeCollector: accrue withdrawal fee
    Vault->>User: emit WithdrawRequested(gross shares burned)
Loading

Possibly related PRs

Suggested reviewers

  • bekauz

Poem

In the vault where assets flow,
A new fee joins the show!
Withdrawals now pay their share,
With careful tests to ensure it's fair.
Rabbits hop and contracts gleam,
As fees are tracked in every stream.
🐇💰✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f81cddf and 871e449.

📒 Files selected for processing (2)
  • solidity/src/vaults/OneWayVault.sol (10 hunks)
  • solidity/test/vaults/OneWayVault.t.sol (29 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: setup-local-ic
  • GitHub Check: solidity contracts
  • GitHub Check: build-and-deploy
🔇 Additional comments (16)
solidity/test/vaults/OneWayVault.t.sol (8)

28-28: LGTM! Reasonable withdrawal fee rate.

The 0.5% withdrawal fee rate is reasonable and consistent with the deposit fee setup pattern.


267-283: LGTM! Proper validation test for withdrawal fee limits.

The test correctly validates that withdrawal fees cannot exceed 100%, mirroring the deposit fee validation pattern. This ensures users can't be charged more than 100% of their withdrawal amount.


333-333: LGTM! Consistent variable renaming throughout tests.

The renaming from feesOwedInAsset to feesAccruedInAsset improves clarity and is consistently applied across all test assertions.

Also applies to: 376-376, 441-441, 546-546, 557-557


642-688: LGTM! Comprehensive test for zero withdrawal fee scenario.

This test properly validates the edge case where withdrawal fees are set to zero, ensuring:

  • No additional fees are accumulated
  • Gross shares equal net shares in withdrawal requests
  • User shares are correctly burned without fee deduction

This provides good coverage for the withdrawal fee feature.


812-844: LGTM! Thorough withdrawal fee calculation test.

The test validates both non-zero and zero fee scenarios, properly testing the calculateWithdrawalFee function with expected fee calculations using basis points.


846-890: LGTM! Comprehensive withdrawal fee distribution test.

This test validates the complete flow of withdrawal fee collection and distribution:

  1. Deposit generates deposit fees
  2. Withdrawal generates withdrawal fees
  3. Rate update triggers fee distribution
  4. Both fee types are properly distributed to strategist and platform accounts

The test provides excellent coverage for the integrated fee system.


1177-1243: LGTM! Updated integration test properly handles withdrawal fees.

The full lifecycle test is correctly updated to account for withdrawal fees in the redemption logic. The test properly validates that:

  • Shares are burned correctly (full amount requested)
  • Net shares (after fees) are stored in withdrawal requests
  • Fee distribution includes both deposit and withdrawal fees

This provides comprehensive integration testing for the withdrawal fee feature.


593-640:

Details

✅ Verification successful

Verify withdrawal fee calculation logic in redeem test.

The test logic correctly handles the withdrawal fee mechanism where:

  1. Full redeemShares are burned from user
  2. Withdrawal fee is calculated on gross assets
  3. Net shares (after fee) are stored in withdrawal request
  4. Both deposit and withdrawal fees are accumulated

However, ensure the fee calculations align with the main contract implementation.


🏁 Script executed:

#!/bin/bash
# Verify withdrawal fee calculation consistency between test and contract
rg -A 5 -B 5 "calculateWithdrawalFee" --type sol

Length of output: 76


🏁 Script executed:

#!/bin/bash
# Search all Solidity files for the withdrawal fee function and its usage
rg -g '*.sol' -n "calculateWithdrawalFee"
rg -g '*.sol' -C3 "function calculateWithdrawalFee"

# Cross-check the deposit fee function to mirror the approach
rg -g '*.sol' -n "calculateDepositFee"
rg -g '*.sol' -C3 "function calculateDepositFee"

Length of output: 3936


Withdrawal Fee Logic Verified
The test’s fee calculations mirror the on-chain implementation—both deposit and withdrawal fees use the same calculateDepositFee/calculateWithdrawalFee logic (basis-points on the gross asset amount, rounded down). No changes needed.

solidity/src/vaults/OneWayVault.sol (8)

122-122: LGTM! Well-documented addition to config struct.

The withdrawRateBps field is properly added to the config struct with clear documentation indicating it represents withdrawal fees in basis points.


275-277: LGTM! Proper validation for withdrawal fee limits.

The validation correctly ensures withdrawal fees cannot exceed 100%, preventing users from being charged more than their withdrawal amount. This mirrors the deposit fee validation pattern.


179-179: LGTM! Improved variable naming for clarity.

The renaming from feesOwedInAsset to feesAccruedInAsset better reflects the purpose of tracking accumulated fees rather than implying an obligation.


491-506: LGTM! Robust withdrawal fee calculation function.

The implementation follows the same pattern as calculateDepositFee with proper:

  • Early return for zero fees (gas optimization)
  • Rounding up to prevent dust losses
  • Consistent basis point calculations

The function is well-documented and handles edge cases appropriately.


529-546: LGTM! Correct withdrawal fee implementation in withdraw function.

The withdrawal logic properly implements the fee mechanism:

  1. Calculates withdrawal fee from gross assets
  2. Determines net assets after fee deduction
  3. Burns shares based on full asset amount (including fee)
  4. Stores net shares in withdrawal request
  5. Accumulates fees for distribution

This ensures users pay the fee but the cross-chain processing uses the correct net amount.


569-587: LGTM! Consistent redeem implementation with withdrawal fees.

The redeem function mirrors the withdraw logic correctly:

  • Calculates gross assets from shares
  • Applies withdrawal fee calculation
  • Burns the full requested shares
  • Stores net shares for cross-chain processing
  • Accumulates fees properly

The implementation is consistent with the withdraw function pattern.


597-624: LGTM! Well-designed internal withdrawal function with improved parameters.

The updated _withdraw function signature clearly separates concerns:

  • sharesToBurn: Full shares to burn from user (including fee portion)
  • postFeeShares: Net shares to store in withdrawal request

This design ensures accurate accounting for both local burning and cross-chain processing. The event emission uses postFeeShares which correctly represents the net shares being withdrawn.


666-681: LGTM! Updated fee distribution using renamed variable.

The fee distribution logic correctly uses the renamed feesAccruedInAsset variable and properly resets it after distribution. This ensures both deposit and withdrawal fees are distributed together.


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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

@keyleu keyleu requested a review from bekauz May 23, 2025 12:11

@bekauz bekauz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

mostly lgtm, just have some confusion about the distinction between shares to burn and shares that are to be accounted for

revert("Deposit fee cannot exceed 100%");
}

if (decodedConfig.withdrawRateBps > BASIS_POINTS) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I know that here BASIS_POINTS means 10_000 but maybe we can clarify that in either the const naming or make it obvious in some other way?

@keyleu keyleu May 26, 2025

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

   /*
    * @dev Constant for basis point calculations (100% = 10000)
    */

it's there on the const

Comment thread solidity/src/vaults/OneWayVault.sol
Comment thread solidity/src/vaults/OneWayVault.sol Outdated
Comment thread solidity/src/vaults/OneWayVault.sol Outdated
Comment thread solidity/src/vaults/OneWayVault.sol Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
solidity/src/vaults/OneWayVault.sol (1)

569-588: Verify the rounding mode choice for share calculation.

The implementation correctly handles withdrawal fees in the redeem function. However, at line 579, _convertToShares(netAssets, Math.Rounding.Ceil) rounds up when calculating shares for the request. This means users might receive slightly fewer assets than the exact net amount due to rounding.

While this protects the protocol from rounding errors, it's worth documenting this behavior or considering if Math.Rounding.Floor would be more user-friendly while still maintaining protocol safety.

Consider adding a comment explaining the rounding choice:

        // Calculate shares for request based on net assets (what will be processed)
+       // Round up to ensure protocol doesn't lose value due to rounding errors
        uint256 sharesForRequest = _convertToShares(netAssets, Math.Rounding.Ceil);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b52697 and f81cddf.

📒 Files selected for processing (2)
  • solidity/src/vaults/OneWayVault.sol (10 hunks)
  • solidity/test/vaults/OneWayVault.t.sol (29 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-and-deploy
  • GitHub Check: solidity contracts
  • GitHub Check: setup-local-ic
🔇 Additional comments (4)
solidity/test/vaults/OneWayVault.t.sol (1)

615-619: LGTM! The test correctly verifies the WithdrawRequested event emission.

The comment and test properly verify that the event emits the gross shares burned (redeemShares), not the net shares stored in the withdrawal request. This aligns with the implementation and addresses past review feedback.

solidity/src/vaults/OneWayVault.sol (3)

491-507: LGTM! Well-implemented withdrawal fee calculation.

The function correctly:

  • Uses basis points for fee calculation
  • Rounds up to prevent dust losses
  • Optimizes gas by returning 0 early when no fee is configured
  • Follows the same pattern as calculateDepositFee for consistency

529-547: LGTM! Withdrawal fee logic correctly implemented.

The implementation properly:

  • Calculates fees on the gross withdrawal amount
  • Burns shares for the full amount (ensuring users can't avoid fees)
  • Stores net shares in the withdrawal request for cross-chain processing
  • Accumulates fees for later distribution

This aligns perfectly with the PR objective of charging withdrawal fees while maintaining proper accounting.


597-626: LGTM! The refactored _withdraw function properly handles the dual share amounts.

The implementation correctly:

  • Uses descriptive parameter names (sharesToBurn and sharesForRequest) as suggested in past reviews
  • Burns the full share amount from the user's balance
  • Stores the net share amount in the withdrawal request
  • Emits the gross shares burned in the WithdrawRequested event

This provides clear separation between what the user pays (gross shares) and what they receive (net shares after fees).

@keyleu keyleu requested a review from bekauz May 26, 2025 11:29
@keyleu keyleu merged commit 649a61f into main May 26, 2025
19 checks passed
@keyleu keyleu deleted the keyne/add-withdraw-rate branch May 26, 2025 14:50
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