-
Notifications
You must be signed in to change notification settings - Fork 2
Description
Severity: Medium
Files Affected
cadence/contracts/FlowALPv1.cdc
Description
In fundsAvailableAboveTargetHealthAfterDepositing (lines 2333–2375), when depositType == withdrawType and depositAmount > 0, the function takes a shortcut (lines 2344–2355): if depositType == withdrawType && depositAmount > 0.0 { let fundsAvailable = self.fundsAvailableAboveTargetHealth( pid: pid, type: withdrawType, targetHealth: targetHealth ) return fundsAvailable + depositAmount } This assumes that depositing X tokens of a type and withdrawing Y tokens of the same type is equivalent to just withdrawing (Y - X) tokens. Therefore maxWithdrawAfterDeposit = maxWithdrawWithoutDeposit + depositAmount. This is mathematically incorrect when the position holds a debit balance in the deposit/withdraw token. In that case, a deposit first reduces debt (scaled by borrowFactor), and only the excess beyond the debt becomes collateral (scaled by collateralFactor). These two operations have different impacts on health: Debt repayment: effective debt decreases by amount * price / borrowFactor Collateral addition: effective collateral increases by amount * price * collateralFactor The shortcut treats both as a simple additive offset, ignoring the different factor scaling during the direction flip. Example: Position has 50 debt in token A, borrowFactor = 0.8, collateralFactor = 0.9, price = 1.0 fundsAvailableAboveTargetHealth returns 0 (can't withdraw without going below target) User deposits 100 of token A Shortcut returns: 0 + 100 = 100 Reality: First 50 repays debt (effective debt decreases by 50/0.8 = 62.5), remaining 50 becomes collateral (effective collateral increases by 50*0.9 = 45). The actual health change is different from adding 100 to collateral, so the true available withdrawal is not 100. The non-shortcut path (lines 2357–2374) handles this correctly by first simulating the deposit via computeAdjustedBalancesAfterDeposit (which accounts for debt repayment and direction flips), then computing available withdrawal against the adjusted balance sheet.
Recommendation
Remove the shortcut and use the full computation path for all cases, consistent with how fundsRequiredForTargetHealthAfterWithdrawing works.
Parent Issue: #209