Reach out for an audit or to learn more about Macro
or Message on Telegram

Sommelier A-5

Security Audit

February 20, 2023

Version 1.0.0

Presented by 0xMacro

Table of Contents

Introduction

This document includes the results of the security audit for Sommelier's smart contract code as found in the section titled ‘Source Code’. The security audit was performed by the Macro security team from February 6, 2023 to February 10, 2023.

The purpose of this audit is to review the source code of certain Sommelier Solidity contracts, and provide feedback on the design, architecture, and quality of the source code with an emphasis on validating the correctness and security of the software in its entirety.

Disclaimer: While Macro’s review is comprehensive and has surfaced some changes that should be made to the source code, this audit should not solely be relied upon for security, as no single audit is guaranteed to catch all possible bugs.

Overall Assessment

The following is an aggregation of issues found by the Macro Audit team:

Severity Count Acknowledged Won't Do Addressed
High 2 1 - 1
Code Quality 2 - - 2

Sommelier was quick to respond to these issues.

Specification

Our understanding of the specification was based on the following sources:

Source Code

The following source code was reviewed during the audit:

Specifically, we audited the following contracts within this repository:

Source Code SHA256
src/modules/adaptors/Euler/EulerDebtTokenAdaptor.sol

f412adc45a6d0272505c06a137b593fa1e2685ebe6fc03d9a5431bf84a38a0ba

src/modules/adaptors/Euler/EulerETokenAdaptor.sol

b6e893943beb1dc0dc10224106d41f7a5f4828cb19682e184ec5d8919d2788c9

Issue Descriptions and Recommendations

Click on an issue to jump to it, or scroll down to see them all.

Security Level Reference

We quantify issues in three parts:

  1. The high/medium/low/spec-breaking impact of the issue:
    • How bad things can get (for a vulnerability)
    • The significance of an improvement (for a code quality issue)
    • The amount of gas saved (for a gas optimization)
  2. The high/medium/low likelihood of the issue:
    • How likely is the issue to occur (for a vulnerability)
  3. The overall critical/high/medium/low severity of the issue.

This third part – the severity level – is a summary of how much consideration the client should give to fixing the issue. We assign severity according to the table of guidelines below:

Severity Description
(C-x)
Critical

We recommend the client must fix the issue, no matter what, because not fixing would mean significant funds/assets WILL be lost.

(H-x)
High

We recommend the client must address the issue, no matter what, because not fixing would be very bad, or some funds/assets will be lost, or the code’s behavior is against the provided spec.

(M-x)
Medium

We recommend the client to seriously consider fixing the issue, as the implications of not fixing the issue are severe enough to impact the project significantly, albiet not in an existential manner.

(L-x)
Low

The risk is small, unlikely, or may not relevant to the project in a meaningful way.

Whether or not the project wants to develop a fix is up to the goals and needs of the project.

(Q-x)
Code Quality

The issue identified does not pose any obvious risk, but fixing could improve overall code quality, on-chain composability, developer ergonomics, or even certain aspects of protocol design.

(I-x)
Informational

Warnings and things to keep in mind when operating the protocol. No immediate action required.

(G-x)
Gas Optimizations

The presented optimization suggestion would save an amount of gas significant enough, in our opinion, to be worth the development cost of implementing it.

Issue Details

H-1

Incorrect health check when exiting a market

Topic
Insolvency
Impact
High
Likelihood
High

EulerETokenAdaptor:exitMarket allows Strategist to declare a collateral as non-collateral.

function exitMarket(IEulerEToken eToken, uint256 subAccountId) public {
    markets().exitMarket(subAccountId, eToken.underlyingAsset());
    // AUDIT: Note address(this)is being passed as account.
    uint256 healthFactor = _calculateHF(address(this));
    if (healthFactor < HFMIN()) revert EulerETokenAdaptor__HealthFactorTooLow();
}

However, observe that markets().exitMarket() is called on the sub account, but the health check is called on the primary account. This means the primary account’s health factor instead of the sub account’s health factor is compared to HFMIN().

Suppose:

  1. HFMIN() is 1.01
  2. markets().exitMarket() executes successfully and leaves the sub account’s healthFactor at 1.0
  3. But the primary account has health factor of 1.2

Then 1.2 is incorrectly used to compared with HFMIN(). The call does not revert when it should.

Remediation

Consider changing _calculateHF(address(this)) to _calculateHF(_getSubAccount(address(this), subAccountId))

H-2

Entering a market can block Cellar share redemption

Topic
Withdrawal
Status
Acknowledged
Impact
High
Likelihood
Medium

Redemption of Cellar shares are intended to always be available to LPs.

However, when a Cellar has an eToken position as the only position [1] the Strategist can enter the eTokens as Euler collateral; consequently the redemption of Cellar shares will be blocked. Collateralized eTokens cannot be withdrawn because withdrawableFrom value is reduced. [2]

// EulerETokenAdaptor

function withdrawableFrom(bytes memory adaptorData, bytes memory) public view override returns (uint256) {
    (IEulerEToken eToken, uint256 subAccountId) = abi.decode(adaptorData, (IEulerEToken, uint256));
    ERC20 underlying = ERC20(eToken.underlyingAsset());

    bool marketEntered;
    address subAccount = _getSubAccount(msg.sender, subAccountId);a

    address[] memory entered = markets().getEnteredMarkets(subAccount);
    for (uint256 i; i < entered.length; ++i) {
        if (entered[i] == address(underlying)) {
            marketEntered = true;
            break;
        }
    }
    // AUDIT: Note the 0 being returned.
    return marketEntered ? 0 : eToken.balanceOfUnderlying(subAccount);
}

This grants the Strategists managing Cellars with sole eToken position the privilege to block share redemption.

Two example problems:

  1. After blocking withdrawals, a Strategist starts doing dangerous trades but LPs will have no exit.
  2. A chain of Cellars depend on a malicious Cellar; withdrawableFrom of which can be maliciously lowered to lower this chain of dependent Cellars’ withdrawableFrom values.

Remediation

Consider persisting Cellar:assetsBeforeAdaptorCall so an adaptor can query a tamper-proof Cellar TVL. Revert if the eToken position accounts for more than X%, say 50%, of Cellar TVL to avoid excessively lowering withdrawableFrom. We can reduce the cost of persisting by persisting only when current-TVL ≥ (1 + abs(delta)) * persisted-TVL.

Notes

[1] The eToken position can alternatively be a large position instead of a sole eToken position - the larger the eToken position, the larger the impact.

[2] Then Cellar:_withdrawInOrder(…) will skip this eToken position as it has 0 withdrawable balance.

Response by Sommelier

It is in a strategists best interest to keep enough liquid positions to facilitate withdraws. If a strategist is maliciously blocking withdraws by moving all assets to an illiquid position(like an Euler position or UniV3 Position), Somm Governance will remove them and replace them with a strategist who will properly run the cellar.

Q-1

Redundant implementations

Topic
Redundancy
Quality Impact
Medium
  1. Consider defining the following in a base contract EulerTokenBase.sol to avoid duplication of logic:
  • market
  • exec
  • euler
  • HFMIN
  • _calculateHF
  • _getSubAccount
  1. EulerETokenAdaptor:depositToEuler and EulerETokenAdaptor:deposit can be merged into one implementation:
function deposit(
    uint256 assets,
    bytes memory adaptorData,
    bytes memory
) public override {
    (IEulerEToken eToken, uint256 subAccountId) = abi.decode(adaptorData, (IEulerEToken, uint256));
    // AUDIT: note this call
    depositToEuler(eToken, subAccountId, assets);
}

function depositToEuler(
    IEulerEToken tokenToDeposit,
    uint256 subAccountId,
    uint256 amountToDeposit
) public {
    ERC20 underlying = ERC20(tokenToDeposit.underlyingAsset());
    underlying.safeApprove(euler(), amountToDeposit);
    tokenToDeposit.deposit(subAccountId, amountToDeposit);
}
Q-2

Documentation inaccuracy: EulerDebtTokenAdatpor:balanceOf

Topic
Documentation
Quality Impact
Medium

The comment on line 140 of EulerDebtTokenAdaptor.sol states:

/**
 * @notice Returns the cellars balance of the positions debtToken.
 */
function balanceOf...

However, it is the underlying token’s balance that is being returned. [Ref]

Consider changing to:

/**
 * @notice Returns the cellar's balance in terms of the debtToken's underlying asset.
 */
function balanceOf...

(H-1) Proof of Concept

pragma solidity 0.8.16;

// source .env; forge test --fork-block-number 15000000 --fork-url $ETH_RPC_URL --match-path test/somm5.h1.t.sol -vvvvvv

import { MockCellar, ERC4626, ERC20, SafeTransferLib } from "src/mocks/MockCellar.sol";
import { Cellar } from "src/base/Cellar.sol";
import { EulerETokenAdaptor } from "src/modules/adaptors/Euler/EulerETokenAdaptor.sol";
import { IEuler, IEulerMarkets, IEulerExec, IEulerEToken, IEulerDToken } from "src/interfaces/external/IEuler.sol";
import { EulerDebtTokenAdaptor, BaseAdaptor } from "src/modules/adaptors/Euler/EulerDebtTokenAdaptor.sol";
import { Registry } from "src/Registry.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";
import { SwapRouter } from "src/modules/swap-router/SwapRouter.sol";
import { IUniswapV2Router02 as IUniswapV2Router } from "src/interfaces/external/IUniswapV2Router02.sol";
import { IUniswapV3Router } from "src/interfaces/external/IUniswapV3Router.sol";
import { ERC20Adaptor } from "src/modules/adaptors/ERC20Adaptor.sol";
import { IChainlinkAggregator } from "src/interfaces/external/IChainlinkAggregator.sol";

import { Test, stdStorage, console, StdStorage, stdError } from "@forge-std/Test.sol";
import { Math } from "src/utils/Math.sol";

contract CellarEulerTest is Test {
    using SafeTransferLib for ERC20;
    using Math for uint256;
    using stdStorage for StdStorage;

    EulerETokenAdaptor private eulerETokenAdaptor;
    EulerDebtTokenAdaptor private eulerDebtTokenAdaptor;
    ERC20Adaptor private erc20Adaptor;
    Cellar private cellar;
    PriceRouter private priceRouter;
    Registry private registry;
    SwapRouter private swapRouter;

    address private immutable strategist = vm.addr(0xBEEF);

    uint8 private constant CHAINLINK_DERIVATIVE = 1;

    ERC20 private USDC = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
    ERC20 private DAI = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
    ERC20 private USDT = ERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
    ERC20 private WETH = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
    ERC20 private WBTC = ERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);

    IEulerMarkets private markets = IEulerMarkets(0x3520d5a913427E6F0D6A83E07ccD4A4da316e4d3);
    address private euler = 0x27182842E098f60e3D576794A5bFFb0777E025d3;
    IEulerExec private exec = IEulerExec(0x59828FdF7ee634AaaD3f58B19fDBa3b03E2D9d80);

    IEulerEToken private eUSDC;
    IEulerEToken private eDAI;
    IEulerEToken private eUSDT;
    IEulerEToken private eWETH;
    IEulerEToken private eWBTC;

    IEulerDToken private dUSDC;
    IEulerDToken private dDAI;
    IEulerDToken private dUSDT;
    IEulerDToken private dWETH;
    IEulerDToken private dWBTC;

    address private constant uniV3Router = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
    address private constant uniV2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

    // Chainlink PriceFeeds
    address private WETH_USD_FEED = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
    address private USDC_USD_FEED = 0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6;
    address private USDT_USD_FEED = 0x3E7d1eAB13ad0104d2750B8863b489D65364e32D;
    address private DAI_USD_FEED = 0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9;
    // Note this is the BTC USD data feed, but we assume the risk that WBTC depegs from BTC.
    address private WBTC_USD_FEED = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c;

    uint32 private usdcPosition;
    uint32 private usdtPosition;
    uint32 private eUSDCPosition1;
    uint32 private eUSDTPosition1;
    uint32 private debtUSDCPosition1;
    uint32 private debtUSDTPosition1;

    function setUp() external {
        eulerETokenAdaptor = new EulerETokenAdaptor();
        eulerDebtTokenAdaptor = new EulerDebtTokenAdaptor();
        erc20Adaptor = new ERC20Adaptor();
        priceRouter = new PriceRouter();

        eUSDC = IEulerEToken(markets.underlyingToEToken(address(USDC)));
        eDAI = IEulerEToken(markets.underlyingToEToken(address(DAI)));
        eUSDT = IEulerEToken(markets.underlyingToEToken(address(USDT)));
        eWETH = IEulerEToken(markets.underlyingToEToken(address(WETH)));
        eWBTC = IEulerEToken(markets.underlyingToEToken(address(WBTC)));

        dUSDC = IEulerDToken(markets.underlyingToDToken(address(USDC)));
        dDAI = IEulerDToken(markets.underlyingToDToken(address(DAI)));
        dUSDT = IEulerDToken(markets.underlyingToDToken(address(USDT)));
        dWETH = IEulerDToken(markets.underlyingToDToken(address(WETH)));
        dWBTC = IEulerDToken(markets.underlyingToDToken(address(WBTC)));

        swapRouter = new SwapRouter(IUniswapV2Router(uniV2Router), IUniswapV3Router(uniV3Router));

        registry = new Registry(address(this), address(swapRouter), address(priceRouter));

        PriceRouter.ChainlinkDerivativeStorage memory stor;

        PriceRouter.AssetSettings memory settings;

        uint256 price = uint256(IChainlinkAggregator(WETH_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, WETH_USD_FEED);
        priceRouter.addAsset(WETH, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(USDC_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, USDC_USD_FEED);
        priceRouter.addAsset(USDC, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(DAI_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, DAI_USD_FEED);
        priceRouter.addAsset(DAI, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(USDT_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, USDT_USD_FEED);
        priceRouter.addAsset(USDT, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(WBTC_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, WBTC_USD_FEED);
        priceRouter.addAsset(WBTC, settings, abi.encode(stor), price);

        // Setup Cellar:
        // Cellar positions array.
        uint32[] memory positions = new uint32[](4);
        uint32[] memory debtPositions = new uint32[](2);

        // Add adaptors and positions to the registry.
        registry.trustAdaptor(address(erc20Adaptor), 0, 0);
        registry.trustAdaptor(address(eulerETokenAdaptor), 0, 0);
        registry.trustAdaptor(address(eulerDebtTokenAdaptor), 0, 0);

        usdcPosition = registry.trustPosition(address(erc20Adaptor), abi.encode(USDC), 0, 0);
        eUSDCPosition1 = registry.trustPosition(address(eulerETokenAdaptor), abi.encode(eUSDC, 1), 0, 0);
        usdtPosition = registry.trustPosition(address(erc20Adaptor), abi.encode(USDT), 0, 0);
        eUSDTPosition1 = registry.trustPosition(address(eulerETokenAdaptor), abi.encode(eUSDT, 1), 0, 0);
        debtUSDCPosition1 = registry.trustPosition(address(eulerDebtTokenAdaptor), abi.encode(dUSDC, 1), 0, 0);
        debtUSDTPosition1 = registry.trustPosition(address(eulerDebtTokenAdaptor), abi.encode(dUSDT, 1), 0, 0);

        positions[0] = usdcPosition;
        positions[1] = eUSDCPosition1;
        positions[2] = usdtPosition;
        positions[3] = eUSDTPosition1;

        debtPositions[0] = debtUSDCPosition1;
        debtPositions[1] = debtUSDTPosition1;

        bytes[] memory positionConfigs = new bytes[](4);
        bytes[] memory debtConfigs = new bytes[](2);

        cellar = new Cellar(
            registry,
            USDC,
            "Euler Cellar",
            "EULER-CLR",
            abi.encode(
                positions,
                debtPositions,
                positionConfigs,
                debtConfigs,
                eUSDCPosition1,
                address(0),
                type(uint128).max,
                type(uint128).max
            )
        );

        cellar.setupAdaptor(address(eulerETokenAdaptor));
        cellar.setupAdaptor(address(eulerDebtTokenAdaptor));

        USDC.safeApprove(address(cellar), type(uint256).max);

        // Manipulate test contracts storage so that minimum shareLockPeriod is zero blocks.
        stdstore.target(address(cellar)).sig(cellar.shareLockPeriod.selector).checked_write(uint256(0));
    }

    function testH1() external {
        // Deposit USDC
        uint256 assets = 100e6;
        deal(address(USDC), address(this), assets);
        cellar.deposit(assets, address(this));

        // Enter USDC
        {
            Cellar.AdaptorCall[] memory data = new Cellar.AdaptorCall[](1);
            bytes[] memory adaptorCalls0 = new bytes[](1);
            adaptorCalls0[0] = _createBytesDataToEnterMarket(eUSDC, 1);
            data[0] = Cellar.AdaptorCall({ adaptor: address(eulerETokenAdaptor), callData: adaptorCalls0 });
            cellar.callOnAdaptor(data);
        }

        // Deposit and enter USDT
        deal(address(USDT), address(cellar), assets);

        {
            Cellar.AdaptorCall[] memory data = new Cellar.AdaptorCall[](2);
            bytes[] memory adaptorCalls0 = new bytes[](1);
            adaptorCalls0[0] = _createBytesDataToDeposit(eUSDT, 1, assets);
            bytes[] memory adaptorCalls1 = new bytes[](1);
            adaptorCalls1[0] = _createBytesDataToEnterMarket(eUSDT, 1);
            data[0] = Cellar.AdaptorCall({ adaptor: address(eulerETokenAdaptor), callData: adaptorCalls0 });
            data[1] = Cellar.AdaptorCall({ adaptor: address(eulerETokenAdaptor), callData: adaptorCalls1 });
            cellar.callOnAdaptor(data);
        }

        // Borrow USDT
        {
            Cellar.AdaptorCall[] memory data = new Cellar.AdaptorCall[](1);
            bytes[] memory adaptorCalls0 = new bytes[](1);
            adaptorCalls0[0] = _createBytesDataToBorrow(dUSDT, 1, 95 * assets / 100);

            data[0] = Cellar.AdaptorCall({ adaptor: address(eulerDebtTokenAdaptor), callData: adaptorCalls0 });
            cellar.callOnAdaptor(data);
        }

        // Exit market
        {
            Cellar.AdaptorCall[] memory data = new Cellar.AdaptorCall[](1);
            bytes[] memory adaptorCalls = new bytes[](1);
            adaptorCalls[0] = _createBytesDataToExitMarket(eUSDC, 1);

            data[0] = Cellar.AdaptorCall({ adaptor: address(eulerETokenAdaptor), callData: adaptorCalls });
            cellar.callOnAdaptor(data);
        }

        IEulerExec.LiquidityStatus memory status = IEulerExec(0x59828FdF7ee634AaaD3f58B19fDBa3b03E2D9d80).liquidity(_getSubAccount(address(cellar), 1));

        console.log("HFMIN=1.01; HF=%s", status.collateralValue.mulDivDown(1e18, status.liabilityValue));
    }


    function _createBytesDataToEnterMarket(IEulerEToken eToken, uint256 subAccountId)
        internal
        pure
        returns (bytes memory)
    {
        return abi.encodeWithSelector(EulerETokenAdaptor.enterMarket.selector, eToken, subAccountId);
    }

    function _createBytesDataToExitMarket(IEulerEToken eToken, uint256 subAccountId)
        internal
        pure
        returns (bytes memory)
    {
        return abi.encodeWithSelector(EulerETokenAdaptor.exitMarket.selector, eToken, subAccountId);
    }

    function _createBytesDataToDeposit(
        IEulerEToken tokenToDeposit,
        uint256 subAccountId,
        uint256 amountToDeposit
    ) internal pure returns (bytes memory) {
        return
            abi.encodeWithSelector(
                EulerETokenAdaptor.depositToEuler.selector,
                tokenToDeposit,
                subAccountId,
                amountToDeposit
            );
    }

    function _createBytesDataToBorrow(
        IEulerDToken debtTokenToBorrow,
        uint256 subAccountId,
        uint256 amountToBorrow
    ) internal pure returns (bytes memory) {
        return
            abi.encodeWithSelector(
                EulerDebtTokenAdaptor.borrowFromEuler.selector,
                debtTokenToBorrow,
                subAccountId,
                amountToBorrow
            );
    }

    function _createBytesDataToRepay(
        IEulerDToken debtTokenToRepay,
        uint256 subAccountId,
        uint256 amountToRepay
    ) internal pure returns (bytes memory) {
        return
            abi.encodeWithSelector(
                EulerDebtTokenAdaptor.repayEulerDebt.selector,
                debtTokenToRepay,
                subAccountId,
                amountToRepay
            );
    }

    function _getSubAccount(address primary, uint256 subAccountId) internal pure returns (address) {
        require(subAccountId < 256, "e/sub-account-id-too-big");
        return address(uint160(primary) ^ uint160(subAccountId));
    }


}

(H-2) Proof of Concept

pragma solidity 0.8.16;

// clear; source .env; forge test --fork-block-number 15000000 --fork-url $ETH_RPC_URL --match-path test/somm5.h2.t.sol -vvvvv

import { MockCellar, ERC4626, ERC20, SafeTransferLib } from "src/mocks/MockCellar.sol";
import { Cellar } from "src/base/Cellar.sol";
import { EulerETokenAdaptor } from "src/modules/adaptors/Euler/EulerETokenAdaptor.sol";
import { IEuler, IEulerMarkets, IEulerExec, IEulerEToken, IEulerDToken } from "src/interfaces/external/IEuler.sol";
import { EulerDebtTokenAdaptor, BaseAdaptor } from "src/modules/adaptors/Euler/EulerDebtTokenAdaptor.sol";
import { Registry } from "src/Registry.sol";
import { PriceRouter } from "src/modules/price-router/PriceRouter.sol";
import { SwapRouter } from "src/modules/swap-router/SwapRouter.sol";
import { IUniswapV2Router02 as IUniswapV2Router } from "src/interfaces/external/IUniswapV2Router02.sol";
import { IUniswapV3Router } from "src/interfaces/external/IUniswapV3Router.sol";
import { ERC20Adaptor } from "src/modules/adaptors/ERC20Adaptor.sol";
import { IChainlinkAggregator } from "src/interfaces/external/IChainlinkAggregator.sol";

import { Test, stdStorage, console, StdStorage, stdError } from "@forge-std/Test.sol";
import { Math } from "src/utils/Math.sol";

contract CellarEulerTest is Test {
    using SafeTransferLib for ERC20;
    using Math for uint256;
    using stdStorage for StdStorage;

    EulerETokenAdaptor private eulerETokenAdaptor;
    EulerDebtTokenAdaptor private eulerDebtTokenAdaptor;
    ERC20Adaptor private erc20Adaptor;
    Cellar private cellar;
    PriceRouter private priceRouter;
    Registry private registry;
    SwapRouter private swapRouter;

    address private immutable strategist = vm.addr(0xBEEF);

    uint8 private constant CHAINLINK_DERIVATIVE = 1;

    ERC20 private USDC = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
    ERC20 private DAI = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
    ERC20 private USDT = ERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
    ERC20 private WETH = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
    ERC20 private WBTC = ERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);

    IEulerMarkets private markets = IEulerMarkets(0x3520d5a913427E6F0D6A83E07ccD4A4da316e4d3);
    address private euler = 0x27182842E098f60e3D576794A5bFFb0777E025d3;
    IEulerExec private exec = IEulerExec(0x59828FdF7ee634AaaD3f58B19fDBa3b03E2D9d80);

    IEulerEToken private eUSDC;
    IEulerEToken private eDAI;
    IEulerEToken private eUSDT;
    IEulerEToken private eWETH;
    IEulerEToken private eWBTC;

    IEulerDToken private dUSDC;
    IEulerDToken private dDAI;
    IEulerDToken private dUSDT;
    IEulerDToken private dWETH;
    IEulerDToken private dWBTC;

    address private constant uniV3Router = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
    address private constant uniV2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;

    // Chainlink PriceFeeds
    address private WETH_USD_FEED = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
    address private USDC_USD_FEED = 0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6;
    address private USDT_USD_FEED = 0x3E7d1eAB13ad0104d2750B8863b489D65364e32D;
    address private DAI_USD_FEED = 0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9;
    // Note this is the BTC USD data feed, but we assume the risk that WBTC depegs from BTC.
    address private WBTC_USD_FEED = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c;

    uint32 private usdcPosition;
    uint32 private usdtPosition;
    uint32 private eUSDCPosition1;
    uint32 private eUSDTPosition1;
    uint32 private debtUSDCPosition1;
    uint32 private debtUSDTPosition1;

    function setUp() external {
        eulerETokenAdaptor = new EulerETokenAdaptor();
        eulerDebtTokenAdaptor = new EulerDebtTokenAdaptor();
        erc20Adaptor = new ERC20Adaptor();
        priceRouter = new PriceRouter();

        eUSDC = IEulerEToken(markets.underlyingToEToken(address(USDC)));
        eDAI = IEulerEToken(markets.underlyingToEToken(address(DAI)));
        eUSDT = IEulerEToken(markets.underlyingToEToken(address(USDT)));
        eWETH = IEulerEToken(markets.underlyingToEToken(address(WETH)));
        eWBTC = IEulerEToken(markets.underlyingToEToken(address(WBTC)));

        dUSDC = IEulerDToken(markets.underlyingToDToken(address(USDC)));
        dDAI = IEulerDToken(markets.underlyingToDToken(address(DAI)));
        dUSDT = IEulerDToken(markets.underlyingToDToken(address(USDT)));
        dWETH = IEulerDToken(markets.underlyingToDToken(address(WETH)));
        dWBTC = IEulerDToken(markets.underlyingToDToken(address(WBTC)));

        swapRouter = new SwapRouter(IUniswapV2Router(uniV2Router), IUniswapV3Router(uniV3Router));

        registry = new Registry(address(this), address(swapRouter), address(priceRouter));

        PriceRouter.ChainlinkDerivativeStorage memory stor;

        PriceRouter.AssetSettings memory settings;

        uint256 price = uint256(IChainlinkAggregator(WETH_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, WETH_USD_FEED);
        priceRouter.addAsset(WETH, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(USDC_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, USDC_USD_FEED);
        priceRouter.addAsset(USDC, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(DAI_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, DAI_USD_FEED);
        priceRouter.addAsset(DAI, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(USDT_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, USDT_USD_FEED);
        priceRouter.addAsset(USDT, settings, abi.encode(stor), price);

        price = uint256(IChainlinkAggregator(WBTC_USD_FEED).latestAnswer());
        settings = PriceRouter.AssetSettings(CHAINLINK_DERIVATIVE, WBTC_USD_FEED);
        priceRouter.addAsset(WBTC, settings, abi.encode(stor), price);

        // Setup Cellar:
        // Cellar positions array.
        uint32[] memory positions = new uint32[](4);
        uint32[] memory debtPositions = new uint32[](2);

        // Add adaptors and positions to the registry.
        registry.trustAdaptor(address(erc20Adaptor), 0, 0);
        registry.trustAdaptor(address(eulerETokenAdaptor), 0, 0);
        registry.trustAdaptor(address(eulerDebtTokenAdaptor), 0, 0);

        usdcPosition = registry.trustPosition(address(erc20Adaptor), abi.encode(USDC), 0, 0);
        eUSDCPosition1 = registry.trustPosition(address(eulerETokenAdaptor), abi.encode(eUSDC, 1), 0, 0);
        usdtPosition = registry.trustPosition(address(erc20Adaptor), abi.encode(USDT), 0, 0);
        eUSDTPosition1 = registry.trustPosition(address(eulerETokenAdaptor), abi.encode(eUSDT, 1), 0, 0);
        debtUSDCPosition1 = registry.trustPosition(address(eulerDebtTokenAdaptor), abi.encode(dUSDC, 1), 0, 0);
        debtUSDTPosition1 = registry.trustPosition(address(eulerDebtTokenAdaptor), abi.encode(dUSDT, 1), 0, 0);

        positions[0] = usdcPosition;
        positions[1] = eUSDCPosition1;
        positions[2] = usdtPosition;
        positions[3] = eUSDTPosition1;

        debtPositions[0] = debtUSDCPosition1;
        debtPositions[1] = debtUSDTPosition1;

        bytes[] memory positionConfigs = new bytes[](4);
        bytes[] memory debtConfigs = new bytes[](2);

        cellar = new Cellar(
            registry,
            USDC,
            "Euler Cellar",
            "EULER-CLR",
            abi.encode(
                positions,
                debtPositions,
                positionConfigs,
                debtConfigs,
                eUSDCPosition1,
                address(0),
                type(uint128).max,
                type(uint128).max
            )
        );

        cellar.setupAdaptor(address(eulerETokenAdaptor));
        cellar.setupAdaptor(address(eulerDebtTokenAdaptor));

        USDC.safeApprove(address(cellar), type(uint256).max);

        // Manipulate test contracts storage so that minimum shareLockPeriod is zero blocks.
        stdstore.target(address(cellar)).sig(cellar.shareLockPeriod.selector).checked_write(uint256(0));
    }

    function testH2() external {
        // Deposit into Euler.
        uint256 assets = 100e6;
        deal(address(USDC), address(this), assets);
        cellar.deposit(assets, address(this));

        // Enter USDC 
        {
            Cellar.AdaptorCall[] memory data = new Cellar.AdaptorCall[](1);
            bytes[] memory adaptorCalls0 = new bytes[](1);
            adaptorCalls0[0] = _createBytesDataToEnterMarket(eUSDC, 1);
            data[0] = Cellar.AdaptorCall({ adaptor: address(eulerETokenAdaptor), callData: adaptorCalls0 });
            cellar.callOnAdaptor(data);
        }

        // Logs: shares value in terms of assets: 99999999
        console.log("shares value in terms of assets: %s", cellar.convertToAssets(cellar.balanceOf(address(this))));

        // Reverts
        cellar.redeem(cellar.balanceOf(address(this)), address(this), address(this));
    }

    function _createBytesDataToEnterMarket(IEulerEToken eToken, uint256 subAccountId)
        internal
        pure
        returns (bytes memory)
    {
        return abi.encodeWithSelector(EulerETokenAdaptor.enterMarket.selector, eToken, subAccountId);
    }

    function _getSubAccount(address primary, uint256 subAccountId) internal pure returns (address) {
        require(subAccountId < 256, "e/sub-account-id-too-big");
        return address(uint160(primary) ^ uint160(subAccountId));
    }
}

Disclaimer

Macro makes no warranties, either express, implied, statutory, or otherwise, with respect to the services or deliverables provided in this report, and Macro specifically disclaims all implied warranties of merchantability, fitness for a particular purpose, noninfringement and those arising from a course of dealing, usage or trade with respect thereto, and all such warranties are hereby excluded to the fullest extent permitted by law.

Macro will not be liable for any lost profits, business, contracts, revenue, goodwill, production, anticipated savings, loss of data, or costs of procurement of substitute goods or services or for any claim or demand by any other party. In no event will Macro be liable for consequential, incidental, special, indirect, or exemplary damages arising out of this agreement or any work statement, however caused and (to the fullest extent permitted by law) under any theory of liability (including negligence), even if Macro has been advised of the possibility of such damages.

The scope of this report and review is limited to a review of only the code presented by the Sommelier team and only the source code Macro notes as being within the scope of Macro’s review within this report. This report does not include an audit of the deployment scripts used to deploy the Solidity contracts in the repository corresponding to this audit. Specifically, for the avoidance of doubt, this report does not constitute investment advice, is not intended to be relied upon as investment advice, is not an endorsement of this project or team, and it is not a guarantee as to the absolute security of the project. In this report you may through hypertext or other computer links, gain access to websites operated by persons other than Macro. Such hyperlinks are provided for your reference and convenience only, and are the exclusive responsibility of such websites’ owners. You agree that Macro is not responsible for the content or operation of such websites, and that Macro shall have no liability to your or any other person or entity for the use of third party websites. Macro assumes no responsibility for the use of third party software and shall have no liability whatsoever to any person or entity for the accuracy or completeness of any outcome generated by such software.