Skip to content
Verified contractExactMIT

WithdrawHelper

Address0x0f9927b8970f9eab665eacd89458bcacf587ff5d
Balance

0 ETH

 

Transactions

11

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,473,278
Creation transaction
0xd86c68d4b7…4c32b8a4d1

contracts/WithdrawHelper.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

/// @dev Morpho Blue market parameters (same layout as in morpho-blue/src/interfaces/IMorpho.sol).
struct MarketParams {
    address loanToken;
    address collateralToken;
    address oracle;
    address irm;
    uint256 lltv;
}

/// @dev Minimal subset of the Morpho Blue interface used by the helper.
interface IMorphoMinimal {
    function idToMarketParams(bytes32 id)
        external
        view
        returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);

    function market(bytes32 id)
        external
        view
        returns (
            uint128 totalSupplyAssets,
            uint128 totalSupplyShares,
            uint128 totalBorrowAssets,
            uint128 totalBorrowShares,
            uint128 lastUpdate,
            uint128 fee
        );

    function position(bytes32 id, address user)
        external
        view
        returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);

    function accrueInterest(MarketParams memory marketParams) external;

    function withdraw(
        MarketParams memory marketParams,
        uint256 assets,
        uint256 shares,
        address onBehalf,
        address receiver
    ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
}

/// @title WithdrawHelper
/// @notice Withdraws USER's own supply from ONE Morpho Blue market to ONE immutable RECEIVER address,
///         and pays the block builder only if the withdrawal actually happened.
///
/// Security model:
///  - USER calls `morpho.setAuthorization(helper, true)` once from the main wallet. The main wallet key is
///    never given to the bot.
///  - Only `bot` (a hot key with gas money only) can trigger `withdrawAvailable`.
///  - Funds can only go to RECEIVER (immutable). The only Morpho call is `withdraw` on MARKET_ID with
///    onBehalf = USER and receiver = RECEIVER. No borrow, no withdrawCollateral, no delegatecall, no proxy.
///  - Builder tips are paid from this contract's ETH balance, are proportional to the withdrawn amount and
///    are bounded by on-chain limits that only USER can change. A leaked bot key therefore cannot redirect
///    funds; at worst it can spend the helper's ETH on tips for real withdrawals within those limits.
///  - USER can rotate the bot key, pause the helper, withdraw ETH, and finally revoke the Morpho
///    authorization (`morpho.setAuthorization(helper, false)`).
contract WithdrawHelper {
    /* ----------------------------------------------------------------------------------------------------- */
    /*                                               CONSTANTS                                               */
    /* ----------------------------------------------------------------------------------------------------- */

    /// @dev Same virtual offsets as Morpho Blue SharesMathLib.
    uint256 internal constant VIRTUAL_SHARES = 1e6;
    uint256 internal constant VIRTUAL_ASSETS = 1;

    /// @dev Tip rates are expressed in wei per RATE_SCALE base units of the loan token
    ///      (for USDC with 6 decimals: wei per 1 USDC).
    uint256 public constant RATE_SCALE = 1e6;

    /* ----------------------------------------------------------------------------------------------------- */
    /*                                               IMMUTABLES                                              */
    /* ----------------------------------------------------------------------------------------------------- */

    IMorphoMinimal public immutable MORPHO;
    bytes32 public immutable MARKET_ID;
    address public immutable USER;
    address public immutable RECEIVER;

    /* ----------------------------------------------------------------------------------------------------- */
    /*                                                STORAGE                                                */
    /* ----------------------------------------------------------------------------------------------------- */

    /// @notice The only address allowed to trigger withdrawals.
    address public bot;
    /// @notice When true, withdrawals are disabled.
    bool public paused;
    /// @notice Upper bound on the tip rate the bot may request (wei per RATE_SCALE units withdrawn).
    uint256 public maxTipWeiPerUnit;
    /// @notice Upper bound on a single tip, in wei.
    uint256 public maxTipPerCall;

    /* ----------------------------------------------------------------------------------------------------- */
    /*                                             EVENTS/ERRORS                                             */
    /* ----------------------------------------------------------------------------------------------------- */

    event Withdrawn(uint256 assets, uint256 shares, uint256 tip, uint256 depositBefore, uint256 liquidityBefore);
    event BotSet(address indexed bot);
    event PausedSet(bool paused);
    event TipLimitsSet(uint256 maxTipWeiPerUnit, uint256 maxTipPerCall);
    event EthWithdrawn(uint256 amount);

    error NotBot();
    error NotUser();
    error IsPaused();
    error ZeroAddress();
    error UnknownMarket();
    error TipRateTooHigh(uint256 requested, uint256 max);
    error BelowMin(uint256 available, uint256 minAssets);
    error TipTransferFailed();
    error EthTransferFailed();

    /* ----------------------------------------------------------------------------------------------------- */
    /*                                              CONSTRUCTOR                                              */
    /* ----------------------------------------------------------------------------------------------------- */

    constructor(
        address morpho,
        bytes32 marketId,
        address user,
        address receiver,
        address bot_,
        uint256 maxTipWeiPerUnit_,
        uint256 maxTipPerCall_
    ) {
        if (morpho == address(0) || user == address(0) || receiver == address(0) || bot_ == address(0)) {
            revert ZeroAddress();
        }
        MORPHO = IMorphoMinimal(morpho);
        MARKET_ID = marketId;
        USER = user;
        RECEIVER = receiver;

        (address loanToken,,,,) = IMorphoMinimal(morpho).idToMarketParams(marketId);
        if (loanToken == address(0)) revert UnknownMarket();

        bot = bot_;
        maxTipWeiPerUnit = maxTipWeiPerUnit_;
        maxTipPerCall = maxTipPerCall_;
        emit BotSet(bot_);
        emit TipLimitsSet(maxTipWeiPerUnit_, maxTipPerCall_);
    }

    receive() external payable {}

    modifier onlyUser() {
        if (msg.sender != USER) revert NotUser();
        _;
    }

    /* ----------------------------------------------------------------------------------------------------- */
    /*                                             BOT ENTRYPOINT                                            */
    /* ----------------------------------------------------------------------------------------------------- */

    /// @notice Withdraws min(USER deposit, free market liquidity) to RECEIVER and tips block.coinbase.
    /// @param minAssets Revert if less than this can be withdrawn (the bundle then simply doesn't land).
    /// @param tipWeiPerUnit Tip rate in wei per RATE_SCALE units actually withdrawn.
    /// @param maxTipWei Absolute cap on this call's tip (e.g. remaining daily budget).
    /// @return assets Amount withdrawn (loan token base units).
    /// @return tip Amount paid to block.coinbase (wei).
    function withdrawAvailable(uint256 minAssets, uint256 tipWeiPerUnit, uint256 maxTipWei)
        external
        returns (uint256 assets, uint256 tip)
    {
        if (msg.sender != bot) revert NotBot();
        if (paused) revert IsPaused();
        if (tipWeiPerUnit > maxTipWeiPerUnit) revert TipRateTooHigh(tipWeiPerUnit, maxTipWeiPerUnit);

        MarketParams memory mp = marketParams();
        MORPHO.accrueInterest(mp);

        (uint256 shares, uint256 deposit, uint256 liquidity) = _state();

        uint256 sharesWithdrawn;
        if (deposit <= liquidity) {
            // Whole position fits: withdraw by shares so no dust is left behind.
            if (deposit == 0 || deposit < minAssets) revert BelowMin(deposit, minAssets);
            (assets, sharesWithdrawn) = MORPHO.withdraw(mp, 0, shares, USER, RECEIVER);
        } else {
            // Partial: take all free liquidity. toSharesUp(liquidity) <= shares because liquidity < deposit.
            if (liquidity == 0 || liquidity < minAssets) revert BelowMin(liquidity, minAssets);
            (assets, sharesWithdrawn) = MORPHO.withdraw(mp, liquidity, 0, USER, RECEIVER);
        }

        tip = (assets * tipWeiPerUnit) / RATE_SCALE;
        if (tip > maxTipWei) tip = maxTipWei;
        if (tip > maxTipPerCall) tip = maxTipPerCall;
        if (tip > address(this).balance) tip = address(this).balance;

        // Emit before the external ETH transfer (checks-effects-interactions). If the tip transfer
        // fails the whole call reverts, so the event can never describe a withdrawal that didn't happen.
        emit Withdrawn(assets, sharesWithdrawn, tip, deposit, liquidity);

        if (tip != 0) {
            (bool ok,) = block.coinbase.call{value: tip}("");
            if (!ok) revert TipTransferFailed();
        }
    }

    /// @notice Lets the bot (or USER) stop the helper instantly. Only USER can unpause.
    function pause() external {
        if (msg.sender != bot && msg.sender != USER) revert NotBot();
        paused = true;
        emit PausedSet(true);
    }

    /* ----------------------------------------------------------------------------------------------------- */
    /*                                             USER CONTROLS                                             */
    /* ----------------------------------------------------------------------------------------------------- */

    function setBot(address newBot) external onlyUser {
        if (newBot == address(0)) revert ZeroAddress();
        bot = newBot;
        emit BotSet(newBot);
    }

    function setPaused(bool p) external onlyUser {
        paused = p;
        emit PausedSet(p);
    }

    function setTipLimits(uint256 maxTipWeiPerUnit_, uint256 maxTipPerCall_) external onlyUser {
        maxTipWeiPerUnit = maxTipWeiPerUnit_;
        maxTipPerCall = maxTipPerCall_;
        emit TipLimitsSet(maxTipWeiPerUnit_, maxTipPerCall_);
    }

    /// @notice ETH can only ever go back to USER.
    function withdrawEth(uint256 amount) external onlyUser {
        emit EthWithdrawn(amount);
        (bool ok,) = USER.call{value: amount}("");
        if (!ok) revert EthTransferFailed();
    }

    /* ----------------------------------------------------------------------------------------------------- */
    /*                                                 VIEWS                                                 */
    /* ----------------------------------------------------------------------------------------------------- */

    function marketParams() public view returns (MarketParams memory mp) {
        (mp.loanToken, mp.collateralToken, mp.oracle, mp.irm, mp.lltv) = MORPHO.idToMarketParams(MARKET_ID);
    }

    /// @notice Snapshot without interest accrual (slightly stale; for monitoring only).
    function preview() external view returns (uint256 deposit, uint256 liquidity, uint256 withdrawable) {
        (, deposit, liquidity) = _state();
        withdrawable = deposit < liquidity ? deposit : liquidity;
    }

    function _state() internal view returns (uint256 shares, uint256 deposit, uint256 liquidity) {
        (uint128 totalSupplyAssets, uint128 totalSupplyShares, uint128 totalBorrowAssets,,,) = MORPHO.market(MARKET_ID);
        (shares,,) = MORPHO.position(MARKET_ID, USER);
        // SharesMathLib.toAssetsDown
        deposit = (shares * (uint256(totalSupplyAssets) + VIRTUAL_ASSETS)) / (uint256(totalSupplyShares) + VIRTUAL_SHARES);
        liquidity = totalSupplyAssets > totalBorrowAssets ? uint256(totalSupplyAssets - totalBorrowAssets) : 0;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.