Skip to content
Smart contracts Audit finding Intermediate

Neglect of exceptional redistribution amounts in withdraw_helper function

The withdraw_helper function calculates the new trove balance before calling charge, which may update the deposits map with exceptional redistribution amounts. As a result, the redistribution is overwritten and the user loses the added collateral.

Aymen0909 Follow with etherhood, bin2chen and 3 others

Originally disclosed on Code4rena

Submitted by Aymen0909, also found by etherhood, bin2chen, jasonxiale, minhquanym, and kodyvim

Lines of code

https://github.com/code-423n4/2024-01-opus/blob/main/src/core/shrine.cairo#L1382-L1392 https://github.com/code-423n4/2024-01-opus/blob/main/src/core/shrine.cairo#L1421-L1431

Description

The withdraw_helper function in the shrine contract handles withdrawal logic for both the withdraw and seize functions. It is responsible for updating trove balances, total yang balances, and charging interest for the trove via the charge function. However, there is an oversight in the current implementation:

fn withdraw_helper(ref self: ContractState, yang: ContractAddress, trove_id: u64, amount: Wad) {
    ...

    let new_trove_balance: Wad = trove_balance - amount;
    let new_total: Wad = self.yang_total.read(yang_id) - amount;

    self.charge(trove_id);

    //@audit will not account for exceptional redistribution added to deposits balance in `charge` call

    self.yang_total.write(yang_id, new_total);
    self.deposits.write((yang_id, trove_id), new_trove_balance);

    // Emit events
    self.emit(YangTotalUpdated { yang, total: new_total });
    self.emit(DepositUpdated { yang, trove_id, amount: new_trove_balance });
}

The issue in the code above is that the withdraw_helper function proceeds to update the storage variables yang_total and deposits using the previously calculated new_total and new_trove_balance values, without accounting for any new yang balance added to the trove after an exceptional redistribution. This results in neglecting any exceptional redistributions added to the deposits balance during the charge call :

fn charge(ref self: ContractState, trove_id: u64) {
    ...

    // If there was any exceptional redistribution, write updated yang amounts to trove
    if updated_trove_yang_balances.is_some() {
        let mut updated_trove_yang_balances = updated_trove_yang_balances.unwrap();
        loop {
            match updated_trove_yang_balances.pop_front() {
                Option::Some(yang_balance) => {
                    //@audit will updated the trove yang balance
                    self.deposits.write((*yang_balance.yang_id, trove_id), *yang_balance.amount);
                },
                Option::None => { break; },
            };
        };
    }

    ...
}

Because the trove deposits map is changed in the charge function but withdraw_helper uses directly the value new_trove_balance, which was calculated before the charge call, the exceptional redistribution added to deposits will be overridden and will be neglected in the trove yang balance.

This oversight could result in financial losses for all protocol users. When users withdraw yang amounts, any exceptional redistributions that should have been added to their trove balances will be neglected and lost.

Impact

Users are at risk of losing all yang exceptional redistribution amounts due to an error in the withdraw_helper function, which causes it to neglect any yang-added redistribution to the trove deposits map.

Proof of concept

Let’s take a simple scenario to highlight this issue:

  • Bob wants to withdraw a 100 amount of yang (yang_id) from his trove (trove_id) certain, we had the following state before the tx:

    deposits(yang_id, trove_id) = 1000

  • When Bob calls abbot.withdraw, withdraw_helper will be invoked under the hood in the shrine contract which will first calculate the new yang trove balance:

    new_trove_balance = trove_balance - amount = 1000 - 100 = 900

  • An exceptional redistribution did happen so when the charge function is called it will update the trove yang deposits balance, so now we have (suppose redistribution is 50 yang per trove, for example):

    deposits(yang_id, trove_id) = 1000 + 50 = 1050

  • After calling charge, the withdraw_helper function will set the trove yang balance, v, to the previously calculated new_trove_balance, so we will have:

    deposits(yang_id, trove_id) = 1000 - 100 = 900

  • We see that the yang amount added from exceptional redistribution is completely neglected as we should have:

    deposits(yang_id, trove_id) = 1000 - 100 + 50 = 950

Thus, as demonstrated in this simplified example, the issue will cause the loss of any exceptional redistribution amounts for the users resulting in a financial losses.

Tools Used

VS Code

Recommended Mitigation

To address this issue, the charge function should be called before calculating the new trove yang balance (new_trove_balance). This ensures that any exceptional redistributions are accounted for before updating the trove balance and total yang balance:

fn withdraw_helper(ref self: ContractState, yang: ContractAddress, trove_id: u64, amount: Wad) {
        let yang_id: u32 = self.get_valid_yang_id(yang);

        //@audit add exceptional redistribution before calculating `new_trove_balance`
++      self.charge(trove_id);

        // Fails if amount > amount of yang deposited in the given trove
        let trove_balance: Wad = self.deposits.read((yang_id, trove_id));
        assert(trove_balance >= amount, 'SH: Insufficient yang balance');

        let new_trove_balance: Wad = trove_balance - amount;
        let new_total: Wad = self.yang_total.read(yang_id) - amount;

--      self.charge(trove_id);

        self.yang_total.write(yang_id, new_total);
        self.deposits.write((yang_id, trove_id), new_trove_balance);

        // Emit events
        self.emit(YangTotalUpdated { yang, total: new_total });
        self.emit(DepositUpdated { yang, trove_id, amount: new_trove_balance });
    }

Assessed type

Context

tserg (Opus) confirmed and commented via duplicate issue #211:

This is valid - potentially fixed.

0xsomeone (judge) commented:

The warden has demonstrated how an exception trove redistribution will not be properly tracked by the withdrawal helper, resulting in an unsynchronized accounting state for the Opus system whereby the user will lose the collateral they acquired in the redistribution.

I believe a high-risk severity is appropriate as it details a scenario in which the collateral balances of users will potentially lose the full redistributed collateral.


The original report as published on Code4rena, by Aymen0909. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the order of operations: the new trove balance is computed before calling charge, which may update the deposits map, so the subsequent write overwrites the redistribution.

Impact

Users could lose the full amount of exceptional redistribution collateral that should have been added to their trove.

What the attacker needed

An exceptional redistribution occurs; user withdraws from affected trove

The fix

The charge function should be called before calculating the new trove balance, so that any redistribution is included.

How it was found

  1. Bob calls abbot.withdraw, which invokes withdraw_helper in the shrine contract.
  2. withdraw_helper calculates new_trove_balance as trove_balance minus amount.
  3. charge is called and updates the deposits map with an exceptional redistribution amount.
  4. withdraw_helper writes the previously calculated new_trove_balance to deposits, overwriting the redistribution.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

When a user withdraws collateral, the contract first calculates the new balance and then calls a function that may add extra collateral from a redistribution. Because the new balance was calculated before the addition, the extra collateral is overwritten and lost.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by Aymen0909

View all

22 more disclosed reports, best first.

More from Opus

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.