Skip to content
Verified contractPartialMIT

YieldVaultMechanicV2

Address0xb9b8229b8ab1fdaad550aa6f0657ba9078d4e25f
Balance

0 ETH

 

Transactions

3

 

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
25,369,057
Creation transaction
0x21a9833796…a03b737800

src/mechanics/YieldVaultMechanicV2.sol

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

import {PoolId} from "v4-core/src/types/PoolId.sol";
import {BaseMechanic} from "./BaseMechanic.sol";

interface IWETH {
    function deposit() external payable;
    function withdraw(uint256) external;
    function approve(address, uint256) external returns (bool);
    function transfer(address, uint256) external returns (bool);
    function balanceOf(address) external view returns (uint256);
}

/// Minimal Aave v3 Pool surface.
interface IAavePool {
    function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
    function withdraw(address asset, uint256 amount, address to) external returns (uint256);
}

interface IERC20Bal {
    function balanceOf(address) external view returns (uint256);
}

interface IRewardDistributor {
    function openEpoch(PoolId id, uint64 epoch, address rewardToken, uint256 amount) external;
}

/// @title YieldVaultMechanicV2 — real ETH yield on a coin's trade-fee reserve, streamed to holders.
/// @notice A fixed per-trade tax (`extraFeeBps`) accrues ETH into the pool's vault. The operator calls
///         `invest` to wrap it to WETH and supply it to Aave v3 — the reserve then earns lending yield
///         forever (the principal stays invested; this is the coin's perpetual productive reserve).
///         `harvest` pulls only the *yield* (aWETH balance above principal) back out as WETH, hands it
///         to the Merkle `RewardDistributorV2`, and opens an epoch; the keeper posts a holder-shares
///         root and holders claim their pro-rata WETH. "Hold the coin → its reserve earns ETH yield →
///         that yield flows to you."
///
/// Per-pool attribution over the single shared aWETH position uses ERC4626-style shares: a pool that
/// supplies later is priced against the already-grown reserve, so yield is split fairly by both size
/// AND time invested — never overcrediting a late joiner. aWETH rebases ~1:1 with WETH (the aToken
/// balance grows in place), so "assets" == this contract's aWETH balance.
///
/// Combinable (ETH-side fee only, no token burn, no refund window). `extraFeeBps` is immutable per
/// deployment — deploy multiple instances for multiple rates, exactly like the dividend mechanics.
contract YieldVaultMechanicV2 is BaseMechanic {
    address public immutable weth;
    address public immutable aavePool;
    address public immutable aWeth;     // Aave v3 aToken for WETH (rebasing 1:1)
    uint16 internal immutable _feeBps;

    address public owner;
    address public operator;            // keeper allowed to invest / harvest
    IRewardDistributor public distributor;

    uint256 public totalShares;                  // sum of all pools' shares of the aWETH position
    mapping(PoolId => uint256) public sharesOf;  // a pool's share of the position
    mapping(PoolId => uint256) public principalOf; // WETH still invested for this pool (yield = assets - principal)

    event Invested(PoolId indexed id, uint256 ethIn, uint256 sharesMinted);
    event Harvested(PoolId indexed id, uint64 indexed epoch, uint256 yieldWeth, uint256 sharesBurned);
    event EmergencyExited(PoolId indexed id, uint256 ethReturned);
    event OwnerSet(address owner);
    event OperatorSet(address operator);
    event DistributorSet(address distributor);

    error NotOwner();
    error NotOperator();
    error NoDistributor();
    error NothingToInvest();
    error NothingToHarvest();
    error TransferFailed();

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

    constructor(address _hook, address _weth, address _aavePool, address _aWeth, uint16 feeBps_, address owner_)
        BaseMechanic(_hook)
    {
        weth = _weth;
        aavePool = _aavePool;
        aWeth = _aWeth;
        _feeBps = feeBps_;
        owner = owner_;
        operator = owner_;
        emit OwnerSet(owner_);
    }

    function extraFeeBps() external view returns (uint16) { return _feeBps; }

    function setOwner(address o) external onlyOwner { owner = o; emit OwnerSet(o); }
    function setOperator(address o) external onlyOwner { operator = o; emit OperatorSet(o); }
    function setDistributor(address d) external onlyOwner { distributor = IRewardDistributor(d); emit DistributorSet(d); }

    /// @notice Wrap this pool's accrued ETH and supply it to Aave; mint the pool ERC4626-style shares.
    function invest(PoolId id) external onlyOperator nonReentrant returns (uint256 shares) {
        _flush(id);                       // pull any unflushed hook fees into vault[id]
        uint256 amt = vault[id];
        if (amt == 0) revert NothingToInvest();
        vault[id] = 0;

        IWETH(weth).deposit{value: amt}();
        IWETH(weth).approve(aavePool, amt);
        // assets = our aWETH balance BEFORE this supply (donations while totalShares==0 are ignored
        // by the 1:1 branch and simply gifted to the first pool — never a theft vector since only the
        // trusted operator can mint shares, and pools are not adversarial external depositors).
        uint256 assetsBefore = IERC20Bal(aWeth).balanceOf(address(this));
        IAavePool(aavePool).supply(weth, amt, address(this), 0);

        shares = totalShares == 0 ? amt : (amt * totalShares) / assetsBefore;
        sharesOf[id] += shares;
        totalShares += shares;
        principalOf[id] += amt;
        emit Invested(id, amt, shares);
    }

    /// @notice A pool's currently-claimable yield = its share of the aWETH position minus its principal.
    function pendingYield(PoolId id) public view returns (uint256) {
        uint256 s = sharesOf[id];
        if (s == 0) return 0;
        uint256 assets = (s * IERC20Bal(aWeth).balanceOf(address(this))) / totalShares;
        uint256 p = principalOf[id];
        return assets > p ? assets - p : 0;
    }

    /// @notice Withdraw a pool's yield (principal stays invested), fund the distributor, open an epoch.
    ///         Burning `y`-worth of shares before withdrawing keeps every other pool's assets unchanged.
    function harvest(PoolId id, uint64 epoch) external onlyOperator nonReentrant returns (uint256 got) {
        if (address(distributor) == address(0)) revert NoDistributor();
        uint256 y = pendingYield(id);
        if (y == 0) revert NothingToHarvest();

        uint256 burn = (y * totalShares) / IERC20Bal(aWeth).balanceOf(address(this));
        sharesOf[id] -= burn;
        totalShares -= burn;

        got = IAavePool(aavePool).withdraw(weth, y, address(this)); // WETH to this contract (~= y)
        if (!IWETH(weth).transfer(address(distributor), got)) revert TransferFailed();
        distributor.openEpoch(id, epoch, weth, got);
        emit Harvested(id, epoch, got, burn);
    }

    /// @notice Owner safety valve (e.g. Aave deprecation/risk): pull a pool's FULL position out of Aave,
    ///         unwrap to ETH, and credit it back to the pool's vault for re-deployment. Yield earned to
    ///         date comes back with the principal — nothing is stranded.
    function emergencyExitToVault(PoolId id) external onlyOwner nonReentrant returns (uint256 got) {
        uint256 s = sharesOf[id];
        if (s == 0) return 0;
        uint256 assets = (s * IERC20Bal(aWeth).balanceOf(address(this))) / totalShares;
        sharesOf[id] = 0;
        totalShares -= s;
        principalOf[id] = 0;
        got = IAavePool(aavePool).withdraw(weth, assets, address(this));
        IWETH(weth).withdraw(got);
        vault[id] += got;
        emit EmergencyExited(id, got);
    }

    receive() external payable {} // WETH.withdraw unwrap lands here; hook funds via fundVault()
}

lib/v4-core/src/interfaces/IHooks.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

lib/v4-core/src/interfaces/external/IERC20Minimal.sol

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

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

lib/v4-core/src/libraries/CustomRevert.sol

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

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

lib/v4-core/src/libraries/SafeCast.sol

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

import {CustomRevert} from "./CustomRevert.sol";

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return y The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256 y) {
        y = int256(x);
        if (y < 0) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
        return int128(int256(x));
    }
}

lib/v4-core/src/types/BalanceDelta.sol

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

import {SafeCast} from "../libraries/SafeCast.sol";

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

lib/v4-core/src/types/BeforeSwapDelta.sol

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

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

lib/v4-core/src/types/Currency.sol

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

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

lib/v4-core/src/types/PoolId.sol

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

import {PoolKey} from "./PoolKey.sol";

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

lib/v4-core/src/types/PoolKey.sol

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

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

lib/v4-core/src/types/PoolOperation.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";

/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
    // the lower and upper tick of the position
    int24 tickLower;
    int24 tickUpper;
    // how to modify the liquidity
    int256 liquidityDelta;
    // a value to set if you want unique liquidity positions at the same range
    bytes32 salt;
}

/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
    /// Whether to swap token0 for token1 or vice versa
    bool zeroForOne;
    /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
    int256 amountSpecified;
    /// The sqrt price at which, if reached, the swap will stop executing
    uint160 sqrtPriceLimitX96;
}

src/interfaces/IMechanic.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {PoolId} from "v4-core/src/types/PoolId.sol";

/// Mechanics are singletons: one deployment serves all pools, keyed by PoolId,
/// mirroring the one-hook-many-pools pattern. Vault balances are isolated per PoolId —
/// a bug in one pool's accounting must never touch another pool's funds.
/// The mechanic address is frozen into PoolState at launch; registry changes never
/// affect live pools.
///
/// CALLBACK FAILURE POLICY (resolved asymmetry, see README P5):
///   - beforeTrade MAY revert by design (gating, e.g. HEARTBEAT death blocks buys).
///     A revert here blocks the trade in BOTH phases. This is the mechanic's contract.
///   - afterTrade reverts PROPAGATE during CURVE/REFUND_WINDOW (a broken mechanic halts
///     its own pool early, before deep liquidity; MONEYBACK correctness depends on
///     afterTrade recording entries, so silent failure would corrupt refunds).
///   - afterTrade reverts are CAUGHT during AMM phase (gas-capped try/catch + event):
///     a graduated pool must NEVER be strandable by its mechanic.
///   - fundVault follows the same policy (propagate in CURVE, catch in AMM; on AMM
///     failure the ETH is credited to protocol fees instead, with an event).
interface IMechanic {
    /// Extra fee (bps of ETH side) skimmed on every trade into this mechanic's
    /// per-pool vault, on top of the platform 1%. 0 for PLAIN/STREAK-style mechanics.
    /// Cached by the hook at register; MUST be constant per mechanic.
    function extraFeeBps() external view returns (uint16);

    /// If true, the extra fee on BUYS is taken on the TOKEN side (skimmed from tokensOut)
    /// and burned by the hook (HALVING). Sells still take the extra fee in ETH -> vault.
    /// Token-side burn never touches ETH custody and cannot reenter the PoolManager.
    /// Cached by the hook at register; MUST be constant per mechanic.
    function buySkimInTokens() external view returns (bool);

    /// If true, graduation routes through the 72h REFUND_WINDOW phase (MONEYBACK).
    /// Cached by the hook at register; MUST be constant per mechanic.
    function usesRefundWindow() external view returns (bool);

    /// If true, this mechanic must be the ONLY mechanic on a pool — it cannot be combined.
    /// Mechanics that take the buy-side fee in tokens (buySkimInTokens) or route graduation
    /// through the refund window (usesRefundWindow) are exclusive implicitly; a mechanic may
    /// also opt in here if its composition with any other is unsafe. Combinable mechanics
    /// (exclusive == false, ETH-side fee only) share one pool by SUMMING their extraFeeBps
    /// under MAX_EXTRA_FEE_BPS, each routing its slice to its own isolated per-pool vault.
    /// Cached by the hook at register; MUST be constant per mechanic.
    function exclusive() external view returns (bool);

    /// Called once by the hook at launch. params = creator-chosen config (abi-encoded).
    function onLaunch(PoolId id, bytes calldata params) external;

    /// Gate. MUST revert to block a trade (e.g. HEARTBEAT death blocks buys).
    /// Runs in BOTH phases. Keep view-cheap.
    function beforeTrade(PoolId id, address trader, bool isBuy, uint8 phase) external;

    /// State update after a trade settles. BOTH phases. <= ~2 cold SSTOREs (L1 gas budget).
    /// ethAmount = the ETH side of the swap at the pool: net of fee-on-input (buys),
    /// gross before fee-on-output (sells). tokenAmount = tokens actually to/from trader.
    function afterTrade(PoolId id, address trader, bool isBuy, uint256 ethAmount, uint256 tokenAmount, uint8 phase) external;

    /// Hook pushes vault ETH here tagged by pool.
    function fundVault(PoolId id) external payable;
}

/// Implemented ONLY by MoneybackMechanicV2. The hook routes REFUND_WINDOW sell pricing here.
interface IRefundPricing {
    /// ETH owed for refunding `tokenAmount` at the wallet's average entry. Caps at the
    /// wallet's remaining refundable position. Hook settles from escrowed realEth.
    function quoteRefund(PoolId id, address trader, uint256 tokenAmount) external view returns (uint256 ethOut, uint256 tokensConsumed);
    function recordRefund(PoolId id, address trader, uint256 tokenAmount, uint256 ethOut) external;
}

src/mechanics/BaseMechanic.sol

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

import {PoolId} from "v4-core/src/types/PoolId.sol";
import {IMechanic} from "../interfaces/IMechanic.sol";

interface IHookViews {
    function tokenOf(PoolId id) external view returns (address);
    function phaseOf(PoolId id) external view returns (uint8);
    function ethPerToken1e18(PoolId id) external view returns (uint256 price, uint48 window);
    function factory() external view returns (address);
    function pendingMechanicFees(PoolId id) external view returns (uint256);
    function pendingMechanicFeesFor(PoolId id, address mechanic) external view returns (uint256);
    function flushMechanicFees(PoolId id) external;
}

interface IERC20View {
    function balanceOf(address) external view returns (uint256);
    function totalSupply() external view returns (uint256);
}

/// Shared plumbing for all sa1t mechanics; per-pool vaults keyed by PoolId.
abstract contract BaseMechanic is IMechanic {
    address public immutable hook;
    mapping(PoolId => uint256) public vault;

    error OnlyHook();
    error EthTransferFailed();
    error MechReentrancy();

    uint256 private _flushLock = 1;

    modifier onlyHook() { if (msg.sender != hook) revert OnlyHook(); _; }
    modifier nonReentrant() {
        if (_flushLock != 1) revert MechReentrancy();
        _flushLock = 2;
        _;
        _flushLock = 1;
    }

    constructor(address _hook) { hook = _hook; }

    function buySkimInTokens() external view virtual returns (bool) { return false; }
    function usesRefundWindow() external view virtual returns (bool) { return false; }
    function exclusive() external view virtual returns (bool) { return false; }
    function onLaunch(PoolId, bytes calldata) external virtual onlyHook {}
    function beforeTrade(PoolId, address, bool, uint8) external virtual onlyHook {}
    function afterTrade(PoolId, address, bool, uint256, uint256, uint8) external virtual onlyHook {}

    function fundVault(PoolId id) external payable virtual onlyHook {
        vault[id] += msg.value;
    }

    /// Pull this pool's accrued-but-unflushed fees from the hook into the vault.
    function _flush(PoolId id) internal {
        IHookViews(hook).flushMechanicFees(id);
    }

    /// @notice Vault plus this mechanic's share of fees not yet flushed from the hook.
    function effectiveVault(PoolId id) public view returns (uint256) {
        return vault[id] + IHookViews(hook).pendingMechanicFeesFor(id, address(this));
    }

    function _sendEth(address to, uint256 amount) internal {
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert EthTransferFailed();
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@prb/math/=lib/prb-math/",
    "v4-core/=lib/v4-core/",
    "@uniswap/v4-core/=lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "solmate/=lib/solmate/",
    "forge-std/=lib/forge-std/src/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "prb-math/=lib/prb-math/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.