Part 2

Zaros
PerpetualsDEXFoundrySolidity
70,000 USDC
View results
Submission Details
Severity: high
Valid

Inefficient Conditional Logic in `settleVaultsDebt` Function

Summary

The CreditDelegationBranch::settleVaultsDebt function uses an if-else structure to handle vaults in debt or credit. However, this approach is inefficient because it does not explicitly skip vaults with zero unsettled debt (vaultUnsettledRealizedDebtUsdX18 == 0). This results in unnecessary computations and gas consumption for vaults that do not require any settlement.


Issue Description

The current implementation uses an if-else structure to determine whether a vault is in debt or credit:

https://github.com/Cyfrin/2025-01-zaros-part-2/blob/35deb3e92b2a32cd304bf61d27e6071ef36e446d/src/market-making/branches/CreditDelegationBranch.sol#L408

if (ctx.vaultUnsettledRealizedDebtUsdX18.lt(SD59x18_ZERO)) {
// Handle debt (swap assets to USDC)
} else {
// Handle credit (swap USDC to assets)
}

This structure does not explicitly handle the case where vaultUnsettledRealizedDebtUsdX18 == 0. As a result:

  • Vaults with zero unsettled debt still undergo unnecessary checks and computations.

  • This inefficiency increases gas costs and reduces the overall performance of the function.


Impact

  1. Unnecessary Computations:

    • Vaults with zero unsettled debt are still processed, leading to wasted computational resources.

  2. Increased Gas Costs:

    • The additional computations for vaults with zero unsettled debt increase the gas cost of the function.

    • This can make the function more expensive to execute, especially in scenarios with many vaults.


Root Cause

The root cause is the use of an if-else structure that does not explicitly skip vaults with zero unsettled debt. Instead, the function should use separate if conditions to handle each case (vaultUnsettledRealizedDebtUsdX18 < 0, vaultUnsettledRealizedDebtUsdX18 > 0, and vaultUnsettledRealizedDebtUsdX18 == 0).


Recommended Fix

The function should be refactored to use separate if conditions for each case, explicitly skipping vaults with zero unsettled debt. The improved structure is as follows:

if (ctx.vaultUnsettledRealizedDebtUsdX18.gt(SD59x18_ZERO)) {
// Handle debt (swap assets to USDC)
} else if (ctx.vaultUnsettledRealizedDebtUsdX18.lt(SD59x18_ZERO)) {
// Handle credit (swap USDC to assets)
}

This ensures that:

  • Vaults with zero unsettled debt are skipped, avoiding unnecessary computations.

  • The function only processes vaults that require settlement, improving efficiency and reducing gas costs.

Updates

Lead Judging Commences

inallhonesty Lead Judge 10 months ago
Submission Judgement Published
Validated
Assigned finding tags:

settleVaultDebt functions in opposite direction because of `ctx.vaultUnsettledRealizedDebtUsdX18.lt(SD59x18_ZERO)` having an inversed comparator (should have been gt)

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!