Skip to content
Verified contractExactMIT

HookEthFeeEscrow

Address0xe69fd76af1898d5c9c523a2b3daef499500dfb51
Balance

0.036691 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 50 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,469,223
Creation transaction
0x52c1a2c4eb…13a28f1ef2

src/core/HookEthFeeEscrow.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {HookEthTypes} from "../interfaces/IHookEthTypes.sol";
import {IHookEthFeeEscrow} from "../interfaces/IHookEthVaults.sol";

/// @title HookEthFeeEscrow
/// @notice Custody & distribution engine for 60/30/10 base fees, Creator Vesting, Holder Airdrops,
///         Velocity Cashback, Boss Raid loot pots, NFT Strategy vaults, and Plugin Builder cuts.
contract HookEthFeeEscrow is ReentrancyGuard, IHookEthFeeEscrow {
    using SafeERC20 for IERC20;

    struct PoolEscrow {
        address token;
        address quoteCurrency;
        address creator;
        address feeRecipient;
        uint32 moduleMask;
        // Creator fees & Buyback Vesting
        uint256 creatorAccrued;
        uint256 creatorClaimed;
        uint64 vestingStart;
        uint32 vestingDuration;
        uint256 vestingFdvTargetWei;
        // Holder Airdrop (epoch-based pro-rata dividend pool)
        uint32 airdropInterval;
        uint256 currentEpoch;
        uint64 epochStartedAt;
        uint256 pendingAirdropPot;
        // Boss Raid state
        uint256 bossHpTarget;
        uint256 bossDamageDealt;
        uint256 bossLootPot;
        uint16 bossLastHitBonusBps;
        uint256 bossRound;
        // NFT Strategy vault
        address nftCollection;
        bool nftResaleMode;
        uint256 nftSweepPot;
        // Velocity Cashback reserve
        uint256 velocityCashbackPot;
        bool initialized;
    }

    struct AirdropEpoch {
        uint256 totalReward;
        uint256 snapshotSupply;
        uint64 finalizedAt;
    }

    struct BossRoundResult {
        uint256 totalLoot;
        uint256 totalDamage;
        address lastHitter;
        uint256 lastHitBonus;
        bool killed;
    }

    address public immutable hook;
    address public immutable factory;
    address public protocolTreasury;
    address public stakerRewardsVault;

    mapping(bytes32 => PoolEscrow) public escrows;
    // Protocol & Staker balances by quoteCurrency
    mapping(address => uint256) public protocolBalances;
    mapping(address => uint256) public stakerBalances;
    // Builder balances: builder => quoteCurrency => amount
    mapping(address => mapping(address => uint256)) public builderBalances;
    // Holder Airdrop epochs: poolId => epoch => AirdropEpoch
    mapping(bytes32 => mapping(uint256 => AirdropEpoch)) public airdropEpochs;
    mapping(bytes32 => mapping(uint256 => mapping(address => bool))) public airdropClaimed;
    // Velocity Cashback: poolId => trader => claimable quote
    mapping(bytes32 => mapping(address => uint256)) public velocityCashback;
    // Boss Raid: poolId => round => BossRoundResult & raider damage
    mapping(bytes32 => mapping(uint256 => BossRoundResult)) public bossRounds;
    mapping(bytes32 => mapping(uint256 => mapping(address => uint256))) public raiderDamage;
    mapping(bytes32 => mapping(uint256 => mapping(address => bool))) public raiderClaimed;

    event CreatorFeeRecipientUpdated(bytes32 indexed poolId, address indexed newRecipient);
    event CreatorFeesClaimed(bytes32 indexed poolId, address indexed recipient, uint256 amount);
    event AirdropEpochFinalized(bytes32 indexed poolId, uint256 indexed epoch, uint256 totalReward);
    event AirdropClaimed(bytes32 indexed poolId, uint256 indexed epoch, address indexed holder, uint256 amount);
    event VelocityCashbackClaimed(bytes32 indexed poolId, address indexed trader, uint256 amount);
    event BossHit(bytes32 indexed poolId, uint256 indexed round, address indexed raider, uint256 damage, uint256 totalDamage);
    event BossKilled(bytes32 indexed poolId, uint256 indexed round, address indexed lastHitter, uint256 totalLoot);
    event BossLootClaimed(bytes32 indexed poolId, uint256 indexed round, address indexed raider, uint256 payout);
    event NftStrategyFunded(bytes32 indexed poolId, uint256 amount, uint256 totalPot);
    event BuilderFeesClaimed(address indexed builder, address indexed quoteCurrency, uint256 amount);

    error OnlyHookOrFactory();
    error OnlyCreator();
    error NothingToClaim();
    error EpochNotReady();
    error AlreadyClaimed();
    error BossNotKilled();
    error InvalidRecipient();
    error NativeTransferFailed();
    error IncorrectValue();

    modifier onlyHookOrFactory() {
        if (msg.sender != hook && msg.sender != factory) revert OnlyHookOrFactory();
        _;
    }

    constructor(
        address hook_,
        address factory_,
        address protocolTreasury_,
        address stakerRewardsVault_
    ) {
        hook = hook_;
        factory = factory_;
        protocolTreasury = protocolTreasury_;
        stakerRewardsVault = stakerRewardsVault_;
    }

    receive() external payable {}

    function registerPool(
        bytes32 poolId,
        address token,
        address quoteCurrency,
        address creator,
        address feeRecipient,
        uint32 moduleMask,
        HookEthTypes.CreatorAndSpecialParams calldata special
    ) external override onlyHookOrFactory {
        address recipient = feeRecipient == address(0) ? creator : feeRecipient;
        escrows[poolId] = PoolEscrow({
            token: token,
            quoteCurrency: quoteCurrency,
            creator: creator,
            feeRecipient: recipient,
            moduleMask: moduleMask,
            creatorAccrued: 0,
            creatorClaimed: 0,
            vestingStart: uint64(block.timestamp),
            vestingDuration: special.vestingDuration,
            vestingFdvTargetWei: special.vestingFdvTargetWei,
            airdropInterval: special.airdropInterval == 0 ? 1 days : special.airdropInterval,
            currentEpoch: 1,
            epochStartedAt: uint64(block.timestamp),
            pendingAirdropPot: 0,
            bossHpTarget: special.bossHpQuoteWei == 0 ? 5 ether : special.bossHpQuoteWei,
            bossDamageDealt: 0,
            bossLootPot: 0,
            bossLastHitBonusBps: special.bossLastHitBonusBps == 0 ? 2_000 : special.bossLastHitBonusBps,
            bossRound: 1,
            nftCollection: special.nftCollection,
            nftResaleMode: special.nftResaleMode,
            nftSweepPot: 0,
            velocityCashbackPot: 0,
            initialized: true
        });
    }

    function creditBaseFees(
        bytes32 poolId,
        address quoteCurrency,
        uint256 creatorAmount,
        uint256 protocolAmount,
        uint256 stakerAmount
    ) external payable override onlyHookOrFactory {
        uint256 total = creatorAmount + protocolAmount + stakerAmount;
        if (total == 0) return;
        _pullFunds(quoteCurrency, total);

        if (creatorAmount > 0) {
            escrows[poolId].creatorAccrued += creatorAmount;
        }
        if (protocolAmount > 0) {
            protocolBalances[quoteCurrency] += protocolAmount;
        }
        if (stakerAmount > 0) {
            stakerBalances[quoteCurrency] += stakerAmount;
        }
    }

    function creditPotAllocations(
        bytes32 poolId,
        address quoteCurrency,
        address trader,
        bool isBuy,
        uint256 buyQuoteNotional,
        uint256 airdropAmount,
        uint256 creatorAmount,
        uint256 nftStrategyAmount,
        uint256 bossRaidAmount,
        uint256 velocityCashbackReserve
    ) external payable override onlyHookOrFactory {
        uint256 total = airdropAmount + creatorAmount + nftStrategyAmount + bossRaidAmount + velocityCashbackReserve;
        if (total > 0) {
            _pullFunds(quoteCurrency, total);
        }

        PoolEscrow storage e = escrows[poolId];
        if (airdropAmount > 0) {
            e.pendingAirdropPot += airdropAmount;
        }
        if (creatorAmount > 0) {
            e.creatorAccrued += creatorAmount;
        }
        if (nftStrategyAmount > 0) {
            e.nftSweepPot += nftStrategyAmount;
            emit NftStrategyFunded(poolId, nftStrategyAmount, e.nftSweepPot);
        }
        if (velocityCashbackReserve > 0) {
            e.velocityCashbackPot += velocityCashbackReserve;
        }

        // Boss Raid progression on buys
        if (bossRaidAmount > 0) {
            e.bossLootPot += bossRaidAmount;
        }
        if ((e.moduleMask & HookEthTypes.MOD_BOSS_RAID) != 0 && isBuy && buyQuoteNotional > 0 && trader != address(0)) {
            uint256 round = e.bossRound;
            raiderDamage[poolId][round][trader] += buyQuoteNotional;
            e.bossDamageDealt += buyQuoteNotional;
            emit BossHit(poolId, round, trader, buyQuoteNotional, e.bossDamageDealt);

            if (e.bossDamageDealt >= e.bossHpTarget && e.bossLootPot > 0) {
                uint256 loot = e.bossLootPot;
                uint256 lastBonus = FullMath.mulDiv(loot, e.bossLastHitBonusBps, HookEthTypes.BPS_DENOMINATOR);
                bossRounds[poolId][round] = BossRoundResult({
                    totalLoot: loot,
                    totalDamage: e.bossDamageDealt,
                    lastHitter: trader,
                    lastHitBonus: lastBonus,
                    killed: true
                });
                e.bossLootPot = 0;
                e.bossDamageDealt = 0;
                e.bossRound = round + 1;
                emit BossKilled(poolId, round, trader, loot);
            }
        }
    }

    function creditVelocityCashback(bytes32 poolId, address trader, uint256 amount) external payable override onlyHookOrFactory {
        if (amount == 0 || trader == address(0)) return;
        PoolEscrow storage e = escrows[poolId];
        if (msg.value > 0 || amount > e.velocityCashbackPot) {
            _pullFunds(e.quoteCurrency, amount);
            velocityCashback[poolId][trader] += amount;
        } else {
            e.velocityCashbackPot -= amount;
            velocityCashback[poolId][trader] += amount;
        }
    }

    function creditBuilderCut(address builder, address quoteCurrency, uint256 amount) external payable override onlyHookOrFactory {
        if (amount == 0 || builder == address(0)) return;
        _pullFunds(quoteCurrency, amount);
        builderBalances[builder][quoteCurrency] += amount;
    }

    // -------------------------------------------------------------------------
    // Creator Fee Management & Buyback Vesting
    // -------------------------------------------------------------------------

    function setFeeRecipient(bytes32 poolId, address newRecipient) external {
        PoolEscrow storage e = escrows[poolId];
        if (msg.sender != e.creator) revert OnlyCreator();
        if (newRecipient == address(0)) revert InvalidRecipient();
        e.feeRecipient = newRecipient;
        emit CreatorFeeRecipientUpdated(poolId, newRecipient);
    }

    function claimableCreatorFees(bytes32 poolId) public view returns (uint256) {
        PoolEscrow storage e = escrows[poolId];
        if (e.creatorAccrued <= e.creatorClaimed) return 0;

        uint256 unlocked = e.creatorAccrued;
        if ((e.moduleMask & HookEthTypes.MOD_BUYBACK_VESTING) != 0 && e.vestingDuration > 0) {
            uint256 elapsed = block.timestamp > e.vestingStart ? block.timestamp - e.vestingStart : 0;
            if (elapsed < e.vestingDuration) {
                unlocked = FullMath.mulDiv(e.creatorAccrued, elapsed, e.vestingDuration);
            }
        }
        return unlocked > e.creatorClaimed ? unlocked - e.creatorClaimed : 0;
    }

    function claimCreatorFees(bytes32 poolId) external nonReentrant returns (uint256 amount) {
        PoolEscrow storage e = escrows[poolId];
        if (msg.sender != e.creator && msg.sender != e.feeRecipient) revert OnlyCreator();
        amount = claimableCreatorFees(poolId);
        if (amount == 0) revert NothingToClaim();

        e.creatorClaimed += amount;
        _payout(e.quoteCurrency, e.feeRecipient, amount);
        emit CreatorFeesClaimed(poolId, e.feeRecipient, amount);
    }

    // -------------------------------------------------------------------------
    // Holder Airdrop Epoch Finalization & Claims
    // -------------------------------------------------------------------------

    function finalizeAirdropEpoch(bytes32 poolId) external {
        PoolEscrow storage e = escrows[poolId];
        if (block.timestamp < e.epochStartedAt + e.airdropInterval) revert EpochNotReady();
        if (e.pendingAirdropPot == 0) revert NothingToClaim();

        uint256 epoch = e.currentEpoch;
        uint256 reward = e.pendingAirdropPot;
        uint256 supply = IERC20(e.token).totalSupply();

        airdropEpochs[poolId][epoch] = AirdropEpoch({
            totalReward: reward,
            snapshotSupply: supply,
            finalizedAt: uint64(block.timestamp)
        });

        e.pendingAirdropPot = 0;
        e.currentEpoch = epoch + 1;
        e.epochStartedAt = uint64(block.timestamp);

        emit AirdropEpochFinalized(poolId, epoch, reward);
    }

    function claimAirdrop(bytes32 poolId, uint256 epoch) external nonReentrant returns (uint256 payout) {
        if (airdropClaimed[poolId][epoch][msg.sender]) revert AlreadyClaimed();
        AirdropEpoch storage ep = airdropEpochs[poolId][epoch];
        if (ep.totalReward == 0 || ep.snapshotSupply == 0) revert NothingToClaim();

        PoolEscrow storage e = escrows[poolId];
        uint256 holderBal = IERC20(e.token).balanceOf(msg.sender);
        if (holderBal == 0) revert NothingToClaim();

        payout = FullMath.mulDiv(ep.totalReward, holderBal, ep.snapshotSupply);
        if (payout == 0) revert NothingToClaim();

        airdropClaimed[poolId][epoch][msg.sender] = true;
        _payout(e.quoteCurrency, msg.sender, payout);
        emit AirdropClaimed(poolId, epoch, msg.sender, payout);
    }

    // -------------------------------------------------------------------------
    // Velocity Dip-Buy Cashback Claims
    // -------------------------------------------------------------------------

    function claimVelocityCashback(bytes32 poolId) external nonReentrant returns (uint256 amount) {
        amount = velocityCashback[poolId][msg.sender];
        if (amount == 0) revert NothingToClaim();
        velocityCashback[poolId][msg.sender] = 0;
        _payout(escrows[poolId].quoteCurrency, msg.sender, amount);
        emit VelocityCashbackClaimed(poolId, msg.sender, amount);
    }

    // -------------------------------------------------------------------------
    // Boss Raid Loot Claims
    // -------------------------------------------------------------------------

    function claimBossLoot(bytes32 poolId, uint256 round) external nonReentrant returns (uint256 payout) {
        if (raiderClaimed[poolId][round][msg.sender]) revert AlreadyClaimed();
        BossRoundResult storage res = bossRounds[poolId][round];
        if (!res.killed || res.totalDamage == 0) revert BossNotKilled();

        uint256 dmg = raiderDamage[poolId][round][msg.sender];
        if (dmg == 0) revert NothingToClaim();

        uint256 sharedPool = res.totalLoot - res.lastHitBonus;
        payout = FullMath.mulDiv(sharedPool, dmg, res.totalDamage);
        if (msg.sender == res.lastHitter) {
            payout += res.lastHitBonus;
        }

        raiderClaimed[poolId][round][msg.sender] = true;
        _payout(escrows[poolId].quoteCurrency, msg.sender, payout);
        emit BossLootClaimed(poolId, round, msg.sender, payout);
    }

    // -------------------------------------------------------------------------
    // Protocol, Stakers, and Workshop Plugin Builder Withdrawals
    // -------------------------------------------------------------------------

    function claimProtocolFees(address quoteCurrency) external nonReentrant returns (uint256 amount) {
        amount = protocolBalances[quoteCurrency];
        if (amount == 0) revert NothingToClaim();
        protocolBalances[quoteCurrency] = 0;
        _payout(quoteCurrency, protocolTreasury, amount);
    }

    function claimStakerFees(address quoteCurrency) external nonReentrant returns (uint256 amount) {
        amount = stakerBalances[quoteCurrency];
        if (amount == 0) revert NothingToClaim();
        stakerBalances[quoteCurrency] = 0;
        _payout(quoteCurrency, stakerRewardsVault, amount);
    }

    function claimBuilderFees(address quoteCurrency) external nonReentrant returns (uint256 amount) {
        amount = builderBalances[msg.sender][quoteCurrency];
        if (amount == 0) revert NothingToClaim();
        builderBalances[msg.sender][quoteCurrency] = 0;
        _payout(quoteCurrency, msg.sender, amount);
    }

    function _pullFunds(address quoteCurrency, uint256 amount) internal {
        if (quoteCurrency == address(0)) {
            if (msg.value < amount) revert IncorrectValue();
        } else {
            IERC20(quoteCurrency).safeTransferFrom(msg.sender, address(this), amount);
        }
    }

    function _payout(address currency, address to, uint256 amount) internal {
        if (amount == 0) return;
        if (currency == address(0)) {
            (bool ok, ) = to.call{value: amount}("");
            if (!ok) revert NativeTransferFailed();
        } else {
            IERC20(currency).safeTransfer(to, amount);
        }
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

@openzeppelin/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

@openzeppelin/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

@openzeppelin/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

@uniswap/v4-core/src/libraries/FullMath.sol

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

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the preconditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}

src/interfaces/IHookEthTypes.sol

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

/// @title HookEthTypes
/// @notice Shared module bitmasks, fee constants, and launch configuration structs for HookETH (hooketh.fun).
library HookEthTypes {
    // -------------------------------------------------------------------------
    // Protocol Fee & Cap Constants (Basis Points, 10_000 = 100%)
    // -------------------------------------------------------------------------
    uint16 internal constant BPS_DENOMINATOR         = 10_000;
    uint16 internal constant BASE_FEE_BPS            = 100;   // 1.00% base swap fee (quote-only)
    uint16 internal constant MAX_TOTAL_FEE_BPS       = 1_000; // 10.00% hard ceiling (base + hook tax + surcharges)
    uint16 internal constant MAX_HOOK_TAX_BPS        = 900;   // 9.00% max creator-configured hook tax

    // Base 1% fee split: 60% Creator / 30% Protocol Buybacks / 10% Stakers
    uint16 internal constant BASE_CREATOR_SHARE_BPS  = 6_000; // 60%
    uint16 internal constant BASE_PROTOCOL_SHARE_BPS = 3_000; // 30%
    uint16 internal constant BASE_STAKERS_SHARE_BPS  = 1_000; // 10%

    // Max Tx bounds: 0.10% (10 bps) to 2.50% (250 bps) of total supply
    uint16 internal constant MIN_MAX_TX_BPS          = 10;
    uint16 internal constant MAX_MAX_TX_BPS          = 250;

    // Floor Loan duration bounds: 7 to 90 days
    uint32 internal constant MIN_LOAN_DURATION       = 7 days;
    uint32 internal constant MAX_LOAN_DURATION       = 90 days;

    // Evolve / DAO timelock notice for fee/split increases
    uint32 internal constant EVOLVE_NOTICE_DELAY     = 1 hours;
    uint32 internal constant DAO_VOTE_DURATION       = 6 hours;

    // -------------------------------------------------------------------------
    // Direct Uniswap v4 Hook Module Bitmasks (21 Native Modules)
    // -------------------------------------------------------------------------
    // Protection (5)
    uint32 internal constant MOD_ANTI_MEV         = 1 << 0;  // Blocks same-block opposing swaps / cooldown
    uint32 internal constant MOD_ANTI_SNIPE       = 1 << 1;  // Decaying opening buy tax into hook pot
    uint32 internal constant MOD_MAX_TX           = 1 << 2;  // Fixed max swap cap (0.1% - 2.5% supply)
    uint32 internal constant MOD_GATED_BUY        = 1 << 3;  // Launch window allowlist / token / NFT buy gate
    uint32 internal constant MOD_AI_AGENT_ONLY    = 1 << 4;  // Launch window Agent Pass / ERC-8004 buy gate

    // Trading Fees (3)
    uint32 internal constant MOD_FIXED_FEES       = 1 << 5;  // Flat extra quote-only hook tax
    uint32 internal constant MOD_DYNAMIC_FEES     = 1 << 6;  // Depth-relative fee scaling (no oracle)
    uint32 internal constant MOD_VELOCITY_FEE     = 1 << 7;  // Extra fee on dumps < 4h TWAP; cashback on dips

    // Burn & Floor (4)
    uint32 internal constant MOD_BACKED_FLOOR     = 1 << 8;  // Accrues quote backing; zero-slippage redeemFloor
    uint32 internal constant MOD_FLOOR_LOAN       = 1 << 9;  // 7-90d zero-liquidation loans against floor
    uint32 internal constant MOD_AUTO_BURN        = 1 << 10; // Buys & permanently burns tokens from v4 pool
    uint32 internal constant MOD_DEEPEN_LPS       = 1 << 11; // Mints extra locked liquidity into v4 pool

    // Rewards (1)
    uint32 internal constant MOD_HOLDER_AIRDROP   = 1 << 12; // Accrues quote rewards for holder claims

    // Creator (3)
    uint32 internal constant MOD_HOOK_TO_CREATOR  = 1 << 13; // Routes % of hook pot to creator escrow
    uint32 internal constant MOD_CREATOR_TO_HOOK  = 1 << 14; // Routes creator 60% base fee into hook pot
    uint32 internal constant MOD_BUYBACK_VESTING  = 1 << 15; // Vests creator proceeds by timer or FDV target

    // Special (2)
    uint32 internal constant MOD_NFT_STRATEGY     = 1 << 16; // Sweeps NFT floor into vault (raffle or 1.2x resale)
    uint32 internal constant MOD_BOSS_RAID        = 1 << 17; // Qualifying buys deal boss damage; kill splits loot

    // Evolving & AI Hooks (3)
    uint32 internal constant MOD_EVOLVE           = 1 << 18; // Creator can adjust fee/splits (cuts now, raises 1h)
    uint32 internal constant MOD_DAO              = 1 << 19; // Holder-voted Evolve (1 token = 1 vote, 6h window)
    uint32 internal constant MOD_MEMORY           = 1 << 20; // Agent-written on-chain wallet rules & ally rebates

    // -------------------------------------------------------------------------
    // Pot Split Allocation (must sum to 10_000 when hook pot receives funds)
    // -------------------------------------------------------------------------
    struct PotSplit {
        uint16 autoBurnBps;
        uint16 backedFloorBps;
        uint16 deepenLpBps;
        uint16 holderAirdropBps;
        uint16 hookToCreatorBps;
        uint16 nftStrategyBps;
        uint16 bossRaidBps;
        uint16 pluginBps;
    }

    // -------------------------------------------------------------------------
    // Per-Module Parameters
    // -------------------------------------------------------------------------
    struct ProtectionParams {
        uint16 antiSnipeStartBps;     // e.g. 800 (8%) decaying to 0
        uint32 antiSnipeDuration;     // seconds after launch
        uint16 maxTxBps;              // 10..250 bps of totalSupply
        uint32 gateDuration;          // seconds for Gated Buy / AI Agent Only
        address gateToken;            // optional ERC20 or ERC721 required to buy during gate
        uint256 gateMinBalance;       // minimum balance of gateToken (default 1)
        address[] allowlist;          // initial allowlisted buyers for Gated Buy
    }

    struct FeeParams {
        uint16 hookTaxBps;            // 0..900 bps flat extra quote fee
        uint16 dynamicMaxAddBps;      // max extra fee for large depth-consuming swaps
        uint16 velocityDumpMalusBps;  // extra fee on sells below 4h TWAP (max 300 bps)
        uint16 velocityDipRebateBps;  // cashback bps from pot on dip buys
    }

    struct CreatorAndSpecialParams {
        address feeRecipient;         // wallet receiving creator fees (defaults to msg.sender)
        uint32 vestingDuration;       // seconds for Buyback Vesting (0 if FDV-only)
        uint256 vestingFdvTargetWei;  // optional FDV threshold in quote wei
        uint16 loanOriginationFeeBps; // one-off fee sent to floor (e.g. 200 = 2%)
        address nftCollection;        // target Mainnet ERC721 collection for NFT Strategy
        bool nftResaleMode;           // false = raffle to holders, true = 1.2x resale buyback & burn
        uint256 bossHpQuoteWei;       // cumulative buy volume in quote wei to kill Boss
        uint16 bossLastHitBonusBps;   // bonus share of loot for killing blow (e.g. 2000 = 20%)
        uint32 airdropInterval;       // seconds per Holder Airdrop epoch
        address agentOperator;        // AI agent address authorized for Memory / Evolve
    }

    struct PluginAttachment {
        uint256 moduleId;             // Registered plugin ID in HookEthModuleRegistry
        uint16 shareBps;              // Share of pluginBps allocation
        bytes initData;               // Up to 1,024 bytes passed to plugin.onLaunch()
    }

    /// @notice Full input payload for launching a direct Uniswap v4 pool on HookETH.
    struct LaunchParams {
        string name;
        string symbol;
        string metadataURI;           // IPFS / Arweave / on-chain JSON with logo, banner, socials
        uint256 totalSupply;          // e.g. 1_000_000_000e18
        address quoteCurrency;        // address(0) for Native ETH, or WETH/USDC/USDT
        int24 initialTick;            // Starting tick for single-sided concentrated LP
        int24 tickUpper;              // Upper bound tick for single-sided LP
        int24 tickSpacing;            // e.g. 60 or 200
        uint32 moduleMask;            // Bitmask of enabled MOD_* modules
        PotSplit potSplit;            // Must sum to 10_000 if any pot-spending module is active
        ProtectionParams protection;
        FeeParams fees;
        CreatorAndSpecialParams special;
        PluginAttachment[] plugins;   // Optional Workshop community plugins
        uint16 devBuyBps;             // Optional atomic first-block dev buy (0..500 bps)
        bytes32 salt;                 // User salt for deterministic CREATE2 token address
    }

    /// @notice Stored on-chain configuration for every launched Uniswap v4 pool.
    struct PoolConfig {
        address token;
        address quoteCurrency;
        address creator;
        address feeRecipient;
        address agentOperator;
        uint256 totalSupply;
        uint64 launchedAt;
        int24 tickLower;
        int24 tickUpper;
        uint32 moduleMask;
        uint16 hookTaxBps;
        uint16 antiSnipeStartBps;
        uint32 antiSnipeDuration;
        uint16 maxTxBps;
        uint32 gateEndsAt;
        address gateToken;
        uint256 gateMinBalance;
        uint16 dynamicMaxAddBps;
        uint16 velocityDumpMalusBps;
        uint16 velocityDipRebateBps;
        PotSplit potSplit;
        bool initialized;
    }
}

src/interfaces/IHookEthVaults.sol

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

import {HookEthTypes} from "./IHookEthTypes.sol";

interface IHookEthFloorVault {
    function registerPool(
        bytes32 poolId,
        address token,
        address quoteCurrency,
        bool loansEnabled,
        uint16 originationFeeBps
    ) external;

    function fundFloor(bytes32 poolId, uint256 amount) external payable;
    function floorPricePerToken(bytes32 poolId) external view returns (uint256);
    function floorReserve(bytes32 poolId) external view returns (uint256);
    function redeemFloor(bytes32 poolId, uint256 tokenAmount, uint256 minQuoteOut) external returns (uint256 quoteOut);
    function borrowAgainstFloor(bytes32 poolId, uint256 tokenAmount, uint32 duration) external returns (uint256 loanId, uint256 principal);
    function repayLoan(uint256 loanId) external payable;
}

interface IHookEthFeeEscrow {
    function registerPool(
        bytes32 poolId,
        address token,
        address quoteCurrency,
        address creator,
        address feeRecipient,
        uint32 moduleMask,
        HookEthTypes.CreatorAndSpecialParams calldata special
    ) external;

    function creditBaseFees(
        bytes32 poolId,
        address quoteCurrency,
        uint256 creatorAmount,
        uint256 protocolAmount,
        uint256 stakerAmount
    ) external payable;

    function creditPotAllocations(
        bytes32 poolId,
        address quoteCurrency,
        address trader,
        bool isBuy,
        uint256 buyQuoteNotional,
        uint256 airdropAmount,
        uint256 creatorAmount,
        uint256 nftStrategyAmount,
        uint256 bossRaidAmount,
        uint256 velocityCashbackReserve
    ) external payable;

    function creditVelocityCashback(bytes32 poolId, address trader, uint256 amount) external payable;
    function creditBuilderCut(address builder, address quoteCurrency, uint256 amount) external payable;
}

interface IHookEthModuleRegistry {
    struct ModuleEntry {
        address plugin;
        address builder;
        bytes32 codehash;
        uint32 capabilities;
        uint32 gasLimit;
        uint16 maxSurchargeBps;
        bool active;
        bool halted;
    }

    function moduleEntry(uint256 moduleId) external view returns (ModuleEntry memory);
    function isModuleActive(uint256 moduleId) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 50,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.