Skip to content
Business logic Audit finding Intermediate

_harvestCore() roi calculation error

The _harvestCore() function subtracts the loss from the return on investment (roi) after already accounting for the loss when calculating the profit, causing the loss to be counted twice. This leads to incorrect reporting data and potentially incorrect debt calculations.

bin2chen Follow with rbserver

Originally disclosed on Code4rena

Submitted by bin2chen, also found by rbserver

_harvestCore() roi calculation error,may double

Proof of Concept

The _harvestCore() will calculate the roi and repayment values. The implementation code is as follows:

    function _harvestCore(uint256 _debt) internal override returns (int256 roi, uint256 repayment) {
        _claimRewards();
        uint256 numSteps = steps.length;
        for (uint256 i = 0; i < numSteps; i = i.uncheckedInc()) {
            address[2] storage step = steps[i];
            IERC20Upgradeable startToken = IERC20Upgradeable(step[0]);
            uint256 amount = startToken.balanceOf(address(this));
            if (amount == 0) {
                continue;
            }
            _swapVelo(step[0], step[1], amount, VELO_ROUTER);
        }

        uint256 allocated = IVault(vault).strategies(address(this)).allocated;
        uint256 totalAssets = balanceOf();
        uint256 toFree = _debt;

        if (totalAssets > allocated) {
            uint256 profit = totalAssets - allocated;
            toFree += profit;
            roi = int256(profit);
        } else if (totalAssets < allocated) {
            roi = -int256(allocated - totalAssets);
        }

        (uint256 amountFreed, uint256 loss) = _liquidatePosition(toFree);
        repayment = MathUpgradeable.min(_debt, amountFreed);
        roi -= int256(loss);//<------这个地方可能会导致重复
    }

The last line may cause double counting of losses For example, the current: vault.allocated = 9 vault.strategy.allocBPS = 9000 strategy.totalAssets = 9

Suppose that after some time, strategy loses 2, then: strategy.totalAssets = 9 - 2 = 7 Also the administrator sets vault.strategy.allocBPS = 0

This executes harvest()->_harvestCore(9) to get roi = 4 repayment = 7

The actual loss of 2, but roi = 4 (double), test code as follows:

add to test/starter-test.js ‘Vault Tests’

    it.only('test_roi', async function () {
      const {vault, strategy, wantHolder, strategist} = await loadFixture(deployVaultAndStrategyAndGetSigners);
      const depositAmount = toWantUnit('10');
      await vault.connect(wantHolder)['deposit(uint256)'](depositAmount);
      await strategy.harvest();

      const balanceOf = await strategy.balanceOf();
      console.log(`strategy balanceOf: ${balanceOf}`);
      // allocated = 9
      // 1.loss 2, left 7
      await strategy.lossFortest(toWantUnit('2'));
      // 2.modify bps=>0
      await vault.connect(strategist).updateStrategyAllocBPS(strategy.address, 0);
      // 3.so debt = 9
      await strategy.harvest();

      const {allocated, losses, allocBPS} = await vault.strategies(strategy.address);
      console.log(`losses: ${losses}`);
      console.log(`allocated: ${allocated}`);
      console.log(`allocBPS: ${allocBPS}`);
    });

add to ReaperStrategyGranarySupplyOnly.sol

    function lossFortest(uint256 amout) external{
        ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).withdraw(address(want), amout, address(1));
    }
$ npx hardhat test test/starter-test.js

  Vaults
    Vault Tests
strategy balanceOf: 900000000
losses: 400000000     <--------will double
allocated: 0
allocBPS: 0

The last vault’s allocated is correct, but the loss is wrong. Statistics and bpsChange of _reportLoss() will be wrong.

Recommended Mitigation Steps

remove roi -= int256(loss);

tess3rac7 (Ethos Reserve) disagreed with severity and commented:

Recommend low priority since it’s an edge case that would only affect reporting data.

Trust (judge) commented:

Reporting data is handled by the vault at: debt = IVault(vault).report(roi, repayment); We cannot rule out damage that may occur due to miscalculations on report / debt, so medium severity seems appropriate.

tess3rac7 (Ethos Reserve) confirmed


The original report as published on Code4rena, by bin2chen. 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 loss is already reflected in the difference between total assets and allocated amount, so subtracting it again from roi double-counts it.

Impact

The miscalculation could affect reporting data and potentially debt calculations, though the project initially considered it an edge case affecting only reporting.

What the attacker needed

Strategy incurs a loss; allocation basis points set to 0; harvest called

The fix

The recommended mitigation is to remove the line that subtracts the loss from roi.

How it was found

  1. Set up a vault and strategy with allocated 9 and strategy total assets 9.
  2. Simulate a loss of 2 so strategy total assets become 7.
  3. Set the strategy's allocation basis points to 0.
  4. Call harvest() on the strategy.
  5. Observe that the reported loss is 4 instead of 2.

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.

A smart contract calculates profit and loss when it harvests rewards. It mistakenly subtracts the same loss twice, so the reported loss is larger than it should be. This can make the system's records wrong and affect how much debt is assigned.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by bin2chen

View all

139 more disclosed reports, best first.

More from Ethos Reserve contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.