# Rebalancing breaks and can corrupt the accounting if amountToProtocol or amountToChain turn negative

Negative amountToProtocol/amountToChain from negative allocations get cast to uint, corrupting Derby vault accounting or blocking rebalancing.

- Payout: Contest reward
- Severity: medium
- Program: Derby
- Credited: XKET
- Disclosed: 2022-10-17
- Write-up quality: 6/10
- Original: https://github.com/sherlock-audit/2023-01-derby-judging/issues/408
- Library page: https://bugbountylibrary.com/r/sherlock%3A2023-01-derby%3AM-1
- Tags: domain:web3 impact:dos impact:integrity kind:contest platform:sherlock sev:medium tech:solidity technique:source-review vuln:accounting-error vuln:dos

**Target:** Derby yield optimiser Vault and XChainController rebalancing logic
**Root cause:** calcAmountToProtocol/calcAmountToChain can return negative int256 when currentAllocations or deltas go negative; these are explicitly cast to uint256 without a positivity check, yielding huge garbage values.
**Steps:**
1. Push negative deltaAllocations via receiveProtocolAllocations (onlyXProvider) or receiveProtocolAllocationsGuard (onlyGuardian) so currentAllocations[_protocol] becomes negative.
2. Trigger rebalance: rebalanceCheckProtocols calls calcAmountToProtocol, which returns negative amountToProtocol.
3. Observe `uint(amountToProtocol)` in amountToWithdraw computation producing a huge value, corrupting state or reverting.
4. Similarly, negative amountToChain in calcDepositWithdraw yields `uint256(_amountToChain)` garbage, reverting pushVaultAmounts or corrupting sendXChainAmount.
**How found:** Code reading of rebalanceCheckProtocols and calcDepositWithdraw noticed explicit int256-to-uint256 casts on values that can be negative given signed delta allocations.
**Exploitation:** A privileged XProvider or Guardian (or compromised game) submits negative deltas; on next rebalance the explicit int-to-uint casts produce huge values, either reverting rebalancing (DoS) or writing corrupted allocations that cannot be reversed.
**Insight:** In delta-based accounting systems, trace every signed intermediate (allocation deltas, amount-to-X) to its int-to-uint cast sites; a single missing positivity check turns a griefing input into permanent state corruption.
