Skip to content
Smart contracts Audit finding Intermediate

Users may encounter losses on assets deposited through StrategySupplyERC4626

The StrategySupplyERC4626 contract's deploy, undeploy, and balance functions returned share amounts instead of underlying asset amounts, causing incorrect asset calculations in BakerFi vaults. This could lead to a portion of user assets being permanently locked in the vault.

0xpiken Follow with 0xlemon, klau5 and 3 others

Originally disclosed on Code4rena

Submitted by 0xpiken, also found by 0xlemon, klau5, klau5, MrPotatoMagic, and shaflow2

https://github.com/code-423n4/2024-12-bakerfi/blob/main/contracts/core/strategies/StrategySupplyERC4626.sol#L44

https://github.com/code-423n4/2024-12-bakerfi/blob/main/contracts/core/strategies/StrategySupplyERC4626.sol#L51

https://github.com/code-423n4/2024-12-bakerfi/blob/main/contracts/core/strategies/StrategySupplyERC4626.sol#L58

Finding description and impact

The _deploy(), _undeploy(), and _getBalance() functions of StrategySupplyERC4626 currently return the amount of shares instead of the amount of the underlying asset. This mistake leads to incorrect calculations of user assets within any BakerFi Vault that utilizes StrategySupplyERC4626.

Proof of Concept

When a user deposits a certain amount of asset (deployedAmount) into a BakerFi vault, it is deployed into the vault’s underlying strategies. In return, the user receives a corresponding number of shares:

    function _depositInternal(uint256 assets, address receiver) private returns (uint256 shares) {
        if (receiver == address(0)) revert InvalidReceiver();
        // Fetch price options from settings
        // Get the total assets and total supply
        Rebase memory total = Rebase(totalAssets(), totalSupply());

        // Check if the Rebase is uninitialized or both base and elastic are positive
        if (!((total.elastic == 0 && total.base == 0) || (total.base > 0 && total.elastic > 0))) {
            revert InvalidAssetsState();
        }

        // Check if deposit exceeds the maximum allowed per wallet
        uint256 maxDepositLocal = getMaxDeposit();
        if (maxDepositLocal > 0) {
            uint256 depositInAssets = (balanceOf(msg.sender) * _ONE) / tokenPerAsset();
            uint256 newBalance = assets + depositInAssets;
            if (newBalance > maxDepositLocal) revert MaxDepositReached();
        }

@>      uint256 deployedAmount = _deploy(assets);

        // Calculate shares to mint
@>      shares = total.toBase(deployedAmount, false);

        // Prevent inflation attack for the first deposit
        if (total.base == 0 && shares < _MINIMUM_SHARE_BALANCE) {
            revert InvalidShareBalance();
        }

        // Mint shares to the receiver
        _mint(receiver, shares);

        // Emit deposit event
        emit Deposit(msg.sender, receiver, assets, shares);
    }

To withdraw their deployed assets from a BakerFi vault, users must burn a corresponding number of shares to receive a certain amount of assets:

    function _redeemInternal(
        uint256 shares,
        address receiver,
        address holder,
        bool shouldRedeemETH
    ) private returns (uint256 retAmount) {
        if (shares == 0) revert InvalidAmount();
        if (receiver == address(0)) revert InvalidReceiver();
        if (balanceOf(holder) < shares) revert NotEnoughBalanceToWithdraw();

        // Transfer shares to the contract if sender is not the holder
        if (msg.sender != holder) {
            if (allowance(holder, msg.sender) < shares) revert NoAllowance();
            transferFrom(holder, msg.sender, shares);
        }

        // Calculate the amount to withdraw based on shares
        uint256 withdrawAmount = (shares * totalAssets()) / totalSupply();
        if (withdrawAmount == 0) revert NoAssetsToWithdraw();

@>      uint256 amount = _undeploy(withdrawAmount);
        uint256 fee = 0;
        uint256 remainingShares = totalSupply() - shares;

        // Ensure a minimum number of shares are maintained to prevent ratio distortion
        if (remainingShares < _MINIMUM_SHARE_BALANCE && remainingShares != 0) {
            revert InvalidShareBalance();
        }

@>      _burn(msg.sender, shares);

        // Calculate and handle withdrawal fees
        if (getWithdrawalFee() != 0 && getFeeReceiver() != address(0)) {
            fee = amount.mulDivUp(getWithdrawalFee(), PERCENTAGE_PRECISION);

            if (shouldRedeemETH && _asset() == wETHA()) {
                unwrapETH(amount);
                payable(receiver).sendValue(amount - fee);
                payable(getFeeReceiver()).sendValue(fee);
            } else {
                IERC20Upgradeable(_asset()).transfer(receiver, amount - fee);
                IERC20Upgradeable(_asset()).transfer(getFeeReceiver(), fee);
            }
        } else {
            if (shouldRedeemETH) {
                unwrapETH(amount);
                payable(receiver).sendValue(amount);
            } else {
                IERC20Upgradeable(_asset()).transfer(receiver, amount);
            }
        }

        emit Withdraw(msg.sender, receiver, holder, amount - fee, shares);
        retAmount = amount - fee;
    }

As we can see, the return values of _deploy() and _undeploy() should represent the amount of asset. In addition, _totalAssets() should also return the amount of asset. The implementation of the above functions within the Vault contract is as follows:

    function _deploy(uint256 assets) internal virtual override returns (uint256 deployedAmount) {
        // Approve the strategy to spend assets
        IERC20Upgradeable(_strategyAsset).safeApprove(address(_strategy), assets);
        // Deploy assets via the strategy
        deployedAmount = _strategy.deploy(assets); // Calls the deploy function of the strategy
    }

    function _undeploy(uint256 assets) internal virtual override returns (uint256 retAmount) {
        retAmount = _strategy.undeploy(assets); // Calls the undeploy function of the strategy
    }

    function _totalAssets() internal view virtual override returns (uint256 amount) {
        amount = _strategy.totalAssets(); // Calls the totalAssets function of the strategy
    }

It is obvious that the return value should represent the amount of assets when _strategy.deploy(), _strategy.undeploy() or _strategy.totalAssets() is called.

However, the functions in StrategySupplyERC4626 mistakenly return the number of shares other than the amount of underlying asset:

    /**
     * @inheritdoc StrategySupplyBase
     */
    function _deploy(uint256 amount) internal override returns (uint256) {
        return _vault.deposit(amount, address(this));
    }

    /**
     * @inheritdoc StrategySupplyBase
     */
    function _undeploy(uint256 amount) internal override returns (uint256) {
        return _vault.withdraw(amount, address(this), address(this));
    }

    /**
     * @inheritdoc StrategySupplyBase
     */
    function _getBalance() internal view override returns (uint256) {
        return _vault.balanceOf(address(this));
    }

This issue could lead to a scenario where a portion of user assets are permanently locked within the BakerFi vault. Create ERC4626Mock contract with below codes:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract ERC4626Mock is ERC4626 {
    constructor(IERC20 asset_) ERC4626(asset_) ERC20("Mock Vault", "MV") {
    }
}

Create StrategySupplyERC4626.ts with below codes and run npm run test:

import { describeif } from '../../common';

import '@nomicfoundation/hardhat-ethers';
import { loadFixture } from '@nomicfoundation/hardhat-network-helpers';
import { expect } from 'chai';
import { ethers, network } from 'hardhat';
import {
  deployVaultRegistry,
  deployStEth,
  deployAaveV3,
  deployWETH,
  deployVault
} from '../../../scripts/common';
describeif(network.name === 'hardhat')('Strategy Supply ERC4626', function () {
  // Fixture to deploy contracts before each test
  async function deployStrategySupplyERC4626() {
    const [owner, otherAccount] = await ethers.getSigners();

    const BakerFiProxyAdmin = await ethers.getContractFactory('BakerFiProxyAdmin');
    const proxyAdmin = await BakerFiProxyAdmin.deploy(owner.address);
    await proxyAdmin.waitForDeployment();

    const MAX_SUPPLY = ethers.parseUnits('1000000000');
    const WETH = await ethers.getContractFactory('WETH');
    const weth = await WETH.deploy();
    await weth.waitForDeployment();
    // Deposit ETH
    await weth.deposit?.call('', { value: ethers.parseUnits('100', 18) });
    const ERC4626Vault = await ethers.getContractFactory("ERC4626Mock");
    const erc4626Vault = await ERC4626Vault.deploy(weth.getAddress());
    await erc4626Vault.waitForDeployment();

    // Deploy StrategySupply contract
    const StrategySupply = await ethers.getContractFactory('StrategySupplyERC4626');
    const strategy = await StrategySupply.deploy(
      owner.address,
      await weth.getAddress(),
      await erc4626Vault.getAddress(),
    );
    await strategy.waitForDeployment();

    const { proxy: vaultProxy } = await deployVault(
        owner.address,
        'Bread ETH',
        'brETH',
        await strategy.getAddress(),
        await weth.getAddress(),
        proxyAdmin,
    );
    await strategy.transferOwnership(await vaultProxy.getAddress());
    const vault = await ethers.getContractAt('Vault', await vaultProxy.getAddress());
    return { weth, strategy, owner, otherAccount, erc4626Vault, vault};
  }

  it.only('Deposit 10 ether but 5 ether can be withdrawn', async () => {
    const { weth, strategy, owner, otherAccount, erc4626Vault, vault } = await loadFixture(deployStrategySupplyERC4626);
    const tenEther  = ethers.parseEther('10');
    const fiveEther = ethers.parseEther('5');
    //@audit-info owner deposits 10e18 WETH into erc4626Vault
    await weth.approve(erc4626Vault.getAddress(), tenEther);
    await erc4626Vault.deposit(tenEther, owner.address);
    //@audit-info 10e18 shares are minted to owner
    expect(await erc4626Vault.balanceOf(owner.address)).to.equal(tenEther);
    //@audit-info transfer 10e18 WETH to erc4626Vault
    await weth.transfer(erc4626Vault.getAddress(), tenEther);
    //@audit-info erc4646Vault has 20e18 WETH with total supply of 10e18 shares
    expect(await weth.balanceOf(erc4626Vault.getAddress())).to.equal(ethers.parseEther('20'));
    expect(await erc4626Vault.totalSupply()).to.equal(ethers.parseEther('10'));
    //@audit-info owner deposits 10e18 WETH into vault
    await vault.enableAccount(owner.address, true);
    await weth.approve(vault.getAddress(), tenEther);
    await vault.deposit(tenEther, owner.address);
    //@audit-info however, only 5e18 WETH can be withdrawn, the rest 5e18 WETH will be locked forever
    expect(await vault.maxWithdraw(owner.address)).to.equal(fiveEther);
  });
});

As we can see that only 5e18 WETH can be withdrawn within 10e18 WETH deployed. The rest 5e18 WETH are permanently locked within the BakerFi vault. The amount of locked asset can be calculated as below:

Note: please see scenario in warden’s original submission.

Recommended mitigation steps

Update StrategySupplyERC4626 to return correct value:

    function _deploy(uint256 amount) internal override returns (uint256) {
-       return _vault.deposit(amount, address(this));
+      _vault.deposit(amount, address(this));
+      return amount;
    }

    /**
     * @inheritdoc StrategySupplyBase
     */
    function _undeploy(uint256 amount) internal override returns (uint256) {
-       return _vault.withdraw(amount, address(this), address(this));
+       _vault.withdraw(amount, address(this), address(this));
+       return amount;
    }

    /**
     * @inheritdoc StrategySupplyBase
     */
    function _getBalance() internal view override returns (uint256) {
-       return _vault.balanceOf(address(this));
+       return _vault.convertToAssets(_vault.balanceOf(address(this)));
    }

chefkenji (BakerFi) confirmed

BakerFi mitigated:

PR-17

Status: Mitigation confirmed. Full details in reports from shaflow2 and 0xlemon.


The original report as published on Code4rena, by 0xpiken. 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

The strategy's functions returned share counts rather than converting them to the underlying asset amount, while the vault expected asset amounts.

Impact

A portion of user assets could be permanently locked within the BakerFi vault, as demonstrated by only half of a deposit being withdrawable in the proof of concept.

What the attacker needed

A BakerFi vault using StrategySupplyERC4626; user deposits assets into the vault

The fix

The strategy's deploy and undeploy functions should return the asset amount, and the balance function should convert shares to assets; the project mitigated this via a pull request.

How it was found

  1. Deploy an ERC4626 mock vault and a StrategySupplyERC4626 strategy.
  2. Deploy a BakerFi vault using the strategy.
  3. Deposit 10 ether into the ERC4626 vault and transfer an additional 10 ether to it, so each share is worth 2 ether.
  4. Deposit 10 ether into the BakerFi vault.
  5. Observe that only 5 ether can be withdrawn, with the remaining 5 ether locked.

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 vault is a smart contract that holds user deposits and invests them through strategies. This strategy mistakenly reported the number of shares it held instead of the actual value of those shares in the underlying token, so the vault miscalculated how much users could withdraw. As a result, some funds could become stuck.

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

View all

29 more disclosed reports, best first.

More from BakerFi Invitational

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.