Skip to content
Verified contractPartialMIT

EngineHub

Address0x8a51138ca062dc881e4c09c74e1701c53273e5e1
Balance

0 ETH

 

Transactions

79

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,129,286
Creation transaction
0x6bc082750d…4df36fcba7

src/pad/engine/EngineHub.sol

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

import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

import {TransientLock} from "../../base/TransientLock.sol";
import {TwoStepOwned} from "../../base/TwoStepOwned.sol";

interface IHubEngine {
    function XAUT() external view returns (address);
    function retired() external view returns (bool);
    function funded() external view returns (uint256);
    function fund(uint256 amount) external;
}

interface IHubToken {
    function approve(address spender, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
}

/// @title EngineHub
/// @notice Sits behind EngineReserve (FeeRouterV2's engine leg). The reserve is bound to the hub; the hub receives the XAUT
///         through a trivial `fund()` and `settle()` (permissionless) splits it across up to 6 registered engines by weight.
///         Engine #0 is the GoldEngine and always keeps at least MIN_GOLD_BPS of the weight.
/// @dev    XAUT leaves ONLY into a registered engine's `fund()` by an exact allowance that is reset to 0. No withdraw, no
///         arbitrary transfer, no delegatecall, no upgrade. Every engine leg is a gas-capped raw call (no return-data copy);
///         a failing / reverting / gas-burning / reentrant engine never blocks the others or `settle()`; its share stays
///         here for the next settle. All parameter changes: propose -> 24 h -> execute (anyone), only pause is instant.
///         Mimics GoldEngine's getters so EngineReserve._check passes (XAUT, AAVE, retired, SINK).
contract EngineHub is TwoStepOwned, TransientLock {
    using SafeTransferLib for address;

    uint256 public constant MAX_ENGINES = 6;
    uint256 public constant BPS = 10_000;
    uint256 public constant MIN_GOLD_BPS = 4000;
    uint256 public constant DELAY = 24 hours;
    uint256 public constant GRACE = 7 days; // a proposal can be executed from eta until eta + GRACE
    uint256 public constant LEG_GAS = 700_000; // cap per engine fund() (GoldEngine needs ~310K cold)
    uint256 internal constant VIEW_GAS = 50_000; // cap for funded() reads
    uint256 internal constant GAS_MARGIN = 60_000;

    // --- GoldEngine getter mimicry (EngineReserve._check)
    address public immutable XAUT;
    address public immutable AAVE;
    address public immutable SINK;
    address public immutable GUARDIAN;

    struct Engine {
        address addr;
        uint16 weightBps;
        bool paused;
        uint256 cap; // max principal (raw XAUT); type(uint256).max = uncapped, 0 = closed
        uint256 sent; // XAUT the hub itself pushed into this engine
    }

    Engine[] internal _engines;
    uint256 public totalSent;
    uint256 public epoch; // bumps on every change of the engine list (kills pending weights / caps proposals)

    struct AddProposal {
        address engine;
        uint256 cap;
        uint64 eta;
    }

    struct WeightsProposal {
        uint16[6] weights;
        uint8 n;
        uint32 epoch;
        uint64 eta;
    }

    struct CapsProposal {
        uint256[6] caps;
        uint8 n;
        uint32 epoch;
        uint64 eta;
    }

    AddProposal internal _pAdd;
    WeightsProposal internal _pWeights;
    CapsProposal internal _pCaps;

    event Funded(address indexed from, uint256 amount);
    event Leg(uint256 indexed index, address indexed engine, uint256 amount);
    event LegFailed(uint256 indexed index, address indexed engine, uint256 share);
    event AutoPaused(uint256 indexed index, address indexed engine);
    event AddProposed(address indexed engine, uint256 cap, uint64 eta);
    event EngineAdded(uint256 indexed index, address indexed engine, uint256 cap);
    event WeightsProposed(uint64 eta);
    event WeightsSet();
    event CapsProposed(uint64 eta);
    event CapsSet();
    event ProposalCancelled(uint8 kind, address indexed by); // 0 add, 1 weights, 2 caps
    event EnginePaused(uint256 indexed index, address indexed engine, address indexed by);
    event EngineUnpaused(uint256 indexed index, address indexed engine);
    event EngineRemoved(uint256 indexed index, address indexed engine);

    error NotOwnerOrGuardian();
    error BadEngine();
    error TooManyEngines();
    error Duplicate();
    error NothingPending();
    error TooEarly();
    error Expired();
    error StaleProposal();
    error BadWeights();
    error BadIndex();
    error NotRemovable();
    error NotEnoughGas();

    constructor(address owner_, address guardian, address xaut, address aave, address engine0) TwoStepOwned(owner_) {
        if (guardian == address(0) || xaut == address(0) || aave == address(0) || engine0 == address(0)) {
            revert ZeroAddress();
        }
        GUARDIAN = guardian;
        XAUT = xaut;
        AAVE = aave;
        _checkEngine(engine0, xaut);
        // engine #0 must look like the GoldEngine: same Aave pool, and a sink with code
        (bool ok, bytes memory r) = engine0.staticcall(abi.encodeWithSignature("AAVE()"));
        if (!ok || r.length != 32 || abi.decode(r, (address)) != aave) revert BadEngine();
        (ok, r) = engine0.staticcall(abi.encodeWithSignature("SINK()"));
        if (!ok || r.length != 32) revert BadEngine();
        address sink = abi.decode(r, (address));
        if (sink.code.length == 0) revert BadEngine();
        SINK = sink;
        _engines.push(Engine({addr: engine0, weightBps: uint16(BPS), paused: false, cap: type(uint256).max, sent: 0}));
        epoch = 1;
        emit EngineAdded(0, engine0, type(uint256).max);
    }

    /// GoldEngine getter mimicry: the hub is never retired
    function retired() external pure returns (bool) {
        return false;
    }

    // ------------------------------------------------------------------ inflow (called by EngineReserve, 600K gas cap)

    /// @notice Pull `amount` XAUT from the caller (needs its allowance). Nothing else.
    function fund(uint256 amount) external {
        if (amount == 0) return;
        XAUT.safeTransferFrom(msg.sender, address(this), amount);
        emit Funded(msg.sender, amount);
    }

    // ------------------------------------------------------------------ settle

    /// @notice Split the hub's XAUT across the eligible engines by weight. Permissionless. Returns the XAUT moved.
    function settle() external nonReentrant returns (uint256 moved) {
        uint256 bal = XAUT.balanceOf(address(this));
        if (bal == 0) return 0;
        uint256 n = _engines.length;
        uint256[6] memory room;
        uint256 total;
        for (uint256 i; i < n; ++i) {
            Engine storage e = _engines[i];
            uint16 w = e.weightBps;
            if (e.paused || w == 0) continue;
            uint256 eff = _funded(e.addr);
            uint256 s = e.sent;
            if (s > eff) eff = s;
            uint256 cap = e.cap;
            if (eff >= cap) continue; // capped: its share goes to the others
            room[i] = cap - eff;
            total += w;
        }
        if (total == 0) return 0;
        for (uint256 i; i < n; ++i) {
            if (room[i] == 0) continue;
            uint256 share = bal * _engines[i].weightBps / total;
            if (share > room[i]) share = room[i];
            if (share == 0) continue;
            moved += _leg(i, share);
        }
    }

    function _leg(uint256 i, uint256 share) internal returns (uint256 sentNow) {
        address t = _engines[i].addr;
        // the caller must supply the gas up front: nobody can fake an engine failure by starving the leg
        if (gasleft() < LEG_GAS * 64 / 63 + GAS_MARGIN) revert NotEnoughGas();
        XAUT.safeApprove(t, share);
        uint256 before = XAUT.balanceOf(address(this));
        bool ok = _callFund(t, share);
        uint256 afterBal = XAUT.balanceOf(address(this));
        _resetAllowance(t);
        // a residual allowance that cannot be cleaned (token refuses approve(0)) auto-pauses the engine
        if (_allowance(XAUT, t) != 0) {
            _engines[i].paused = true;
            emit AutoPaused(i, t);
        }
        if (!ok) {
            emit LegFailed(i, t, share);
        } else if (afterBal < before) {
            sentNow = before - afterBal;
            _engines[i].sent += sentNow;
            totalSent += sentNow;
            emit Leg(i, t, sentNow);
        }
    }

    /// gas-capped raw call; the return data is never copied (no return bomb), the result is only success / failure
    function _callFund(address t, uint256 share) internal returns (bool ok) {
        bytes4 sel = IHubEngine.fund.selector;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), share)
            ok := call(LEG_GAS, t, 0, m, 36, 0, 0)
        }
    }

    /// best effort, never reverts
    function _resetAllowance(address t) internal {
        bytes4 sel = IHubToken.approve.selector;
        address x = XAUT;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), t)
            mstore(add(m, 36), 0)
            pop(call(100000, x, 0, m, 68, 0, 0))
        }
    }

    function _allowance(address token, address spender) internal view returns (uint256 a) {
        bool ok;
        bytes4 sel = IHubToken.allowance.selector;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            mstore(add(m, 4), address())
            mstore(add(m, 36), spender)
            ok := staticcall(100000, token, m, 68, 0, 32)
            a := mload(0)
            if iszero(and(ok, iszero(lt(returndatasize(), 32)))) { a := not(0) } // unknown: treat as dangling
        }
    }

    /// engine.funded() through a gas-capped staticcall; 0 on any failure (the hub's own `sent` counter backs it up)
    function _funded(address t) internal view returns (uint256 v) {
        bytes4 sel = IHubEngine.funded.selector;
        assembly ("memory-safe") {
            mstore(0, sel)
            let ok := staticcall(VIEW_GAS, t, 0, 4, 0, 32)
            v := mload(0)
            if iszero(and(ok, iszero(lt(returndatasize(), 32)))) { v := 0 }
        }
    }

    // ------------------------------------------------------------------ governance: add an engine

    function proposeAddEngine(address e, uint256 cap) external onlyOwner nonReentrant {
        _validateNew(e);
        uint64 eta = uint64(block.timestamp + DELAY);
        _pAdd = AddProposal(e, cap, eta);
        emit AddProposed(e, cap, eta);
    }

    function executeAddEngine() external nonReentrant {
        AddProposal memory p = _pAdd;
        if (p.engine == address(0)) revert NothingPending();
        _due(p.eta);
        _validateNew(p.engine); // re-checked
        delete _pAdd;
        _engines.push(Engine({addr: p.engine, weightBps: 0, paused: false, cap: p.cap, sent: 0}));
        ++epoch;
        emit EngineAdded(_engines.length - 1, p.engine, p.cap);
    }

    function _validateNew(address e) internal view {
        if (_engines.length >= MAX_ENGINES) revert TooManyEngines();
        if (e == address(this) || e == XAUT || e == address(0)) revert BadEngine();
        for (uint256 i; i < _engines.length; ++i) {
            if (_engines[i].addr == e) revert Duplicate();
        }
        _checkEngine(e, XAUT);
    }

    function _checkEngine(address e, address xaut) internal view {
        if (e.code.length == 0) revert BadEngine();
        try IHubEngine(e).XAUT{gas: VIEW_GAS}() returns (address x) {
            if (x != xaut) revert BadEngine();
        } catch {
            revert BadEngine();
        }
        try IHubEngine(e).retired{gas: VIEW_GAS}() returns (bool r) {
            if (r) revert BadEngine();
        } catch {
            revert BadEngine();
        }
    }

    // ------------------------------------------------------------------ governance: weights and caps

    /// @param w one weight per registered engine (length == engineCount()), sum 10000, w[0] >= MIN_GOLD_BPS
    function proposeWeights(uint16[] calldata w) external onlyOwner nonReentrant {
        WeightsProposal memory p;
        p.n = uint8(_engines.length);
        if (w.length != p.n) revert BadWeights();
        for (uint256 i; i < w.length; ++i) {
            p.weights[i] = w[i];
        }
        _validateWeights(p.weights, p.n);
        p.epoch = uint32(epoch);
        p.eta = uint64(block.timestamp + DELAY);
        _pWeights = p;
        emit WeightsProposed(p.eta);
    }

    function executeWeights() external nonReentrant {
        WeightsProposal memory p = _pWeights;
        if (p.eta == 0) revert NothingPending();
        _due(p.eta);
        if (p.epoch != epoch || p.n != _engines.length) revert StaleProposal();
        _validateWeights(p.weights, p.n);
        delete _pWeights;
        for (uint256 i; i < p.n; ++i) {
            _engines[i].weightBps = p.weights[i];
        }
        emit WeightsSet();
    }

    function _validateWeights(uint16[6] memory w, uint256 n) internal pure {
        uint256 sum;
        for (uint256 i; i < 6; ++i) {
            if (i >= n && w[i] != 0) revert BadWeights();
            sum += w[i];
        }
        if (sum != BPS || w[0] < MIN_GOLD_BPS) revert BadWeights();
    }

    function proposeCaps(uint256[] calldata c) external onlyOwner nonReentrant {
        CapsProposal memory p;
        p.n = uint8(_engines.length);
        if (c.length != p.n) revert BadWeights();
        for (uint256 i; i < c.length; ++i) {
            p.caps[i] = c[i];
        }
        p.epoch = uint32(epoch);
        p.eta = uint64(block.timestamp + DELAY);
        _pCaps = p;
        emit CapsProposed(p.eta);
    }

    function executeCaps() external nonReentrant {
        CapsProposal memory p = _pCaps;
        if (p.eta == 0) revert NothingPending();
        _due(p.eta);
        if (p.epoch != epoch || p.n != _engines.length) revert StaleProposal();
        delete _pCaps;
        for (uint256 i; i < p.n; ++i) {
            _engines[i].cap = p.caps[i];
        }
        emit CapsSet();
    }

    function _due(uint64 eta) internal view {
        if (block.timestamp < eta) revert TooEarly();
        if (block.timestamp > uint256(eta) + GRACE) revert Expired();
    }

    /// @param kind 0 add, 1 weights, 2 caps. Owner or guardian.
    function cancelProposal(uint8 kind) external nonReentrant {
        if (msg.sender != owner && msg.sender != GUARDIAN) revert NotOwnerOrGuardian();
        if (kind == 0) {
            if (_pAdd.engine == address(0)) revert NothingPending();
            delete _pAdd;
        } else if (kind == 1) {
            if (_pWeights.eta == 0) revert NothingPending();
            delete _pWeights;
        } else if (kind == 2) {
            if (_pCaps.eta == 0) revert NothingPending();
            delete _pCaps;
        } else {
            revert NothingPending();
        }
        emit ProposalCancelled(kind, msg.sender);
    }

    // ------------------------------------------------------------------ pause / remove

    /// @notice Owner or guardian: skip this engine in settle (its share goes to the others by weight). Instant.
    function pauseEngine(uint256 i) external nonReentrant {
        if (msg.sender != owner && msg.sender != GUARDIAN) revert NotOwnerOrGuardian();
        if (i >= _engines.length) revert BadIndex();
        _engines[i].paused = true;
        emit EnginePaused(i, _engines[i].addr, msg.sender);
    }

    function unpauseEngine(uint256 i) external onlyOwner nonReentrant {
        if (i >= _engines.length) revert BadIndex();
        _engines[i].paused = false;
        emit EngineUnpaused(i, _engines[i].addr);
    }

    /// @notice Owner: drop an engine that is paused or has weight 0. Never index 0. Its weight moves to engine #0.
    function removeEngine(uint256 i) external onlyOwner nonReentrant {
        uint256 n = _engines.length;
        if (i == 0 || i >= n) revert BadIndex();
        Engine storage e = _engines[i];
        if (!e.paused && e.weightBps != 0) revert NotRemovable();
        address a = e.addr;
        _engines[0].weightBps += e.weightBps;
        if (i != n - 1) _engines[i] = _engines[n - 1];
        _engines.pop();
        ++epoch; // pending weights / caps no longer match the list
        emit EngineRemoved(i, a);
    }

    // ------------------------------------------------------------------ views

    function engineCount() external view returns (uint256) {
        return _engines.length;
    }

    /// @return addr the engine, weightBps its weight, paused, funded the engine's own funded() (0 if unreadable), cap
    function engineInfo(uint256 i)
        external
        view
        returns (address addr, uint16 weightBps, bool paused, uint256 funded, uint256 cap)
    {
        if (i >= _engines.length) revert BadIndex();
        Engine storage e = _engines[i];
        return (e.addr, e.weightBps, e.paused, _funded(e.addr), e.cap);
    }

    /// XAUT the hub itself has pushed into engine i
    function engineSent(uint256 i) external view returns (uint256) {
        if (i >= _engines.length) revert BadIndex();
        return _engines[i].sent;
    }

    /// total XAUT the hub has pushed into engines (its own counter, not engine-reported)
    function totalFunded() external view returns (uint256) {
        return totalSent;
    }

    function pendingAdd() external view returns (address engine, uint256 cap, uint64 eta) {
        AddProposal memory p = _pAdd;
        return (p.engine, p.cap, p.eta);
    }

    function pendingWeights() external view returns (uint16[6] memory weights, uint8 n, uint64 eta, bool stale) {
        WeightsProposal memory p = _pWeights;
        return (p.weights, p.n, p.eta, p.eta != 0 && (p.epoch != epoch || p.n != _engines.length));
    }

    function pendingCaps() external view returns (uint256[6] memory caps, uint8 n, uint64 eta, bool stale) {
        CapsProposal memory p = _pCaps;
        return (p.caps, p.n, p.eta, p.eta != 0 && (p.epoch != epoch || p.n != _engines.length));
    }
}

lib/solady/src/utils/SafeTransferLib.sol

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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) {
                    revert(codesize(), codesize())
                } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {

            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount := mul( // The arguments of `mul` are evaluated from right to left.
                mload(0x20),
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` implements `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented := and( // The arguments of `and` are evaluated from right to left.
                gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
            )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
                mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
            ) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

src/base/TransientLock.sol

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

/// @title TransientLock
/// @notice One reentrancy lock per contract plus transient "callback expected" flags (EIP-1153, Cancun).
/// @dev Slots are fixed random constants so they cannot collide with anything else a contract stores in transient
///      storage. Every flag is set immediately before the external call that must call us back and cleared right after.
abstract contract TransientLock {
    error Reentrancy();
    error UnexpectedCallback();

    /// keccak256("kineko.transient.lock") - 1
    uint256 internal constant LOCK_SLOT = 0x1c8f6d4b0f1f86e4a2b0f7c7b1b3f8c5d0a8a3c6e1b8f5a2c7d4e9f0a1b2c3d4;

    modifier nonReentrant() {
        if (_tload(LOCK_SLOT) != 0) revert Reentrancy();
        _tstore(LOCK_SLOT, 1);
        _;
        _tstore(LOCK_SLOT, 0);
    }

    function _isLocked() internal view returns (bool) {
        return _tload(LOCK_SLOT) != 0;
    }

    function _tload(uint256 slot) internal view returns (uint256 v) {
        assembly ("memory-safe") {
            v := tload(slot)
        }
    }

    function _tstore(uint256 slot, uint256 v) internal {
        assembly ("memory-safe") {
            tstore(slot, v)
        }
    }

    /// @dev Reverts unless `msg.sender == expected` and the flag at `slot` is set; clears the flag so the same
    ///      expectation can be consumed only once.
    function _consumeCallback(uint256 slot, address expected) internal {
        if (msg.sender != expected || _tload(slot) == 0) revert UnexpectedCallback();
        _tstore(slot, 0);
    }
}

src/base/TwoStepOwned.sol

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

/// @title TwoStepOwned
/// @notice Minimal two-step ownership. The owner is expected to be a multisig (behind a timelock on mainnet).
abstract contract TwoStepOwned {
    error NotOwner();
    error NotPendingOwner();
    error ZeroAddress();

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    address public owner;
    address public pendingOwner;

    constructor(address owner_) {
        if (owner_ == address(0)) revert ZeroAddress();
        owner = owner_;
        emit OwnershipTransferred(address(0), owner_);
    }

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    function transferOwnership(address newOwner) external onlyOwner {
        pendingOwner = newOwner; // zero cancels a pending transfer
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        pendingOwner = address(0);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "morpho-blue/=lib/morpho-blue/src/",
    "metamorpho/=lib/metamorpho-v1.1/src/",
    "solady/=lib/solady/src/",
    "v4-core/=lib/v4-core/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
    "lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
    "lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
    "lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
    "lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "metamorpho-v1.1/=lib/metamorpho-v1.1/",
    "morpho-blue-irm/=lib/metamorpho-v1.1/lib/morpho-blue-irm/src/",
    "openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
    "solmate/=lib/v4-core/lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.