Skip to content
Verified contractPartialMIT

DELTA

Address0x0000b03edc2bee389f70288b2fb55092ad4dbebd
Balance

0 ETH

 

Transactions

9

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
Via IR
yes
License
MIT
Match
Partialcreation code: no, runtime code: yes
Verified on Sourcify
Created in block
25,067,660
Creation transaction
0xece5f13acd…20630307c5

2 files

DELTA.sol

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

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address) external view returns (uint256);
    function transfer(address, uint256) external returns (bool);
    function allowance(address, address) external view returns (uint256);
    function approve(address, uint256) external returns (bool);
    function transferFrom(address, address, uint256) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

/// @title DELTA token — minimal ERC20 paired with V4 dynamic-tax hook
/// @notice Tax/dip/ATH logic lives in the hook. Token has no transfer hooks.
contract DELTA is IERC20 {
    string  public constant name = "DeltaTest";
    string  public constant symbol = "DLTT";
    uint8   public constant decimals = 18;
    uint256 private constant _totalSupply = 1_000_000_000 * 10**18;

    /// Required low-14-bits of the V4 hook address. Mirrors
    /// DeltaHook.REQUIRED_HOOK_BITS — bumped to 0x20CC to include
    /// AFTER_SWAP_RETURNS_DELTA. Defence-in-depth: the deploy script is the
    /// real gate (CREATE2 salt mining), but `setHook` rejects any address
    /// whose lower bits don't match this constant so a misconfigured token
    /// can't quietly bind to a hook that won't actually fire.
    uint256 private constant REQUIRED_HOOK_BITS = 0x20CC;

    address public hook;
    address public deployer;

    mapping(address => uint256) private _bal;
    mapping(address => mapping(address => uint256)) private _allow;

    error HookAlreadySet();
    error HookNotSet();
    error BadHookBits();
    error OnlyDeployer();
    error ZeroAddress();
    error InsufficientBalance();
    error InsufficientAllowance();

    event HookSet(address indexed hook);
    event DeployerRenounced();

    /// @param _deployer The EOA that signs the deploy tx and gets the
    /// one-shot `setHook` + `renounceDeployer` rights plus the full 1B
    /// supply. Required because CREATE2 deployment via the factory makes
    /// `msg.sender` the factory, not the EOA. The constructor enforces
    /// `_deployer == tx.origin` as defence-in-depth so the deployer slot
    /// can never be set to the factory, a contract, or anyone other than
    /// the EOA that signed the originating tx.
    constructor(address _deployer) {
        if (_deployer == address(0)) revert ZeroAddress();
        if (_deployer != tx.origin) revert OnlyDeployer();
        deployer = _deployer;
        _bal[_deployer] = _totalSupply;
        emit Transfer(address(0), _deployer, _totalSupply);
    }

    function setHook(address _hook) external {
        if (msg.sender != deployer) revert OnlyDeployer();
        if (hook != address(0)) revert HookAlreadySet();
        if (_hook == address(0)) revert ZeroAddress();
        if (uint160(_hook) & 0x3FFF != REQUIRED_HOOK_BITS) revert BadHookBits();
        hook = _hook;
        emit HookSet(_hook);
    }

    /// @dev Infinite-approval optimization: when allowance is `type(uint256).max`,
    /// `transferFrom` does NOT decrement it. Saves an SSTORE per transfer.

    /// @notice Zero out the deployer slot. Callable only after `setHook` so the
    /// hook is permanently locked first. After this, no further admin actions
    /// remain on the token (no mint, no pause, no second setHook).
    function renounceDeployer() external {
        if (msg.sender != deployer) revert OnlyDeployer();
        if (hook == address(0)) revert HookNotSet();
        deployer = address(0);
        emit DeployerRenounced();
    }

    function totalSupply() external pure returns (uint256) { return _totalSupply; }
    function balanceOf(address a) external view returns (uint256) { return _bal[a]; }
    function allowance(address o, address s) external view returns (uint256) { return _allow[o][s]; }

    function approve(address s, uint256 a) external returns (bool) {
        _allow[msg.sender][s] = a;
        emit Approval(msg.sender, s, a);
        return true;
    }

    function transfer(address to, uint256 amt) external returns (bool) {
        _transfer(msg.sender, to, amt);
        return true;
    }

    /// @inheritdoc IERC20
    function transferFrom(address from, address to, uint256 amt) external returns (bool) {
        uint256 x = _allow[from][msg.sender];
        if (x != type(uint256).max) {
            if (x < amt) revert InsufficientAllowance();
            _allow[from][msg.sender] = x - amt;
        }
        _transfer(from, to, amt);
        return true;
    }

    function _transfer(address from, address to, uint256 amt) internal {
        if (from == address(0) || to == address(0)) revert ZeroAddress();
        uint256 fromBal = _bal[from];
        if (fromBal < amt) revert InsufficientBalance();
        unchecked {
            _bal[from] = fromBal - amt;
            _bal[to] += amt;
        }
        emit Transfer(from, to, amt);
    }
}

DeltaHook.sol

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

// ─── Vendored minimal V4 types ───
struct PoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

struct SwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

type BeforeSwapDelta is int256;
type BalanceDelta is int256;

// Canonical V4 BeforeSwapDelta packer: (specified << 128) | (unspecified & 0xff..ff128).
function toBeforeSwapDelta(int128 specified, int128 unspecified) pure returns (BeforeSwapDelta r) {
    assembly { r := or(shl(128, specified), and(sub(shl(128, 1), 1), unspecified)) }
}

// BalanceDelta accessors. Convention from v4-core: amount0 in high 128, amount1 in low 128.
// Sign is the *swapper's* perspective: negative = swapper paid, positive = swapper received.
function amount0(BalanceDelta d) pure returns (int128) { return int128(BalanceDelta.unwrap(d) >> 128); }
function amount1(BalanceDelta d) pure returns (int128) { return int128(BalanceDelta.unwrap(d)); }

interface IPoolManager {
    function take(address currency, address to, uint256 amount) external;
    function extsload(bytes32 slot) external view returns (bytes32);
}

/// @title DeltaHook — wave-tax (final, post-FIXES.md)
/// @notice Always takes a baseline tax in beforeSwap (when ETH is the specified
///         currency) or in afterSwap (when token is specified). Refunds extra
///         in afterSwap when buying in rebate zones. Sells always taxed.
///           ≥ 95% peak  : buy -3% (3% tax + 6% refund), sell +6%
///           85–95% mid  : buy +3%, sell +3%
///           < 85% dip   : buy -6% (3% tax + 9% refund), sell +12%  (also marks new ATH)
///
///         Plus a launch-tax decay: starting at 30% on both buys + sells, the
///         tax decays by 1% per minute for 30 minutes, then settles into the
///         zone-based rates above. Wallets in `launchExempt` (set in the
///         constructor — typically the bundle wallets) bypass the launch tax
///         and use zone rates from block 0. Rebates are suppressed for any
///         non-exempt wallet while the launch tax is still elevated above the
///         steady 3% baseline.
///
///         Every wei of every taxed swap stays in the hook as rebate budget.
///         There is no dev fee on swaps — the dev's only ETH lever is the
///         admin-gated `emergencyWithdraw` (break-glass for a dead token).
///         Transfer tax is also zero — the token has no transfer hook.
contract DeltaHook {
    // ──────────────────────────────────────────────────────────────────
    // CONFIG (effective rates, in bps)
    // ──────────────────────────────────────────────────────────────────
    uint256 public constant STEADY_TAX_BPS = 300;     // 3% baseline buy tax + mid sell tax
    uint256 public constant PEAK_SELL_BPS = 600;      // 6% sell tax in peak (was 300; bumped to discourage topping)
    uint256 public constant DIP_SELL_BPS = 1200;      // 12% sell tax in deep dip

    uint256 public constant PEAK_BONUS_BPS = 300;     // -3% effective at peak
    uint256 public constant DIP_BONUS_BPS = 600;      // -6% effective in deep dip

    // No dev fee — every wei of every taxed swap goes to the rebate vault.
    // The dev's only ETH lever on the hook is `emergencyWithdraw` (break-glass).

    uint256 public constant ATH_ZONE_BPS = 9500;      // ≥95% of zoneRef = peak rebate zone
    uint256 public constant DIP_ZONE_BPS = 8500;      // <85% of zoneRef = deep dip rebate zone
    uint256 public constant DIP_TRIGGER_BPS = 8500;   // 15% drop = DipFormed → markedATH ratchets

    uint256 public constant PER_BLOCK_REBATE_CAP_BPS = 500; // 5% of vault per block (shared across all rebates that block)

    // Launch-tax decay (anti-snipe): 30% on both directions at launch,
    // declines linearly by 1%/minute, hits 0 at 30 minutes. From minute ~27
    // onward the launch tax is at/below the 3% steady baseline so normal
    // mechanics resume. Bundle wallets in `launchExempt` always bypass.
    uint256 public constant LAUNCH_TAX_START_BPS = 3000;
    uint256 public constant LAUNCH_TAX_DECAY_BPS_PER_MIN = 100;

    // Flags: BEFORE_INITIALIZE (0x2000) | BEFORE_SWAP (0x80) | AFTER_SWAP (0x40)
    //      | BEFORE_SWAP_RETURNS_DELTA (0x08) | AFTER_SWAP_RETURNS_DELTA (0x04)
    // The AFTER_SWAP_RETURNS_DELTA bit is critical: without it, the int128
    // returned from afterSwap is ignored, so any take() inside afterSwap goes
    // unsettled and the swap reverts with CurrencyNotSettled().
    uint256 public constant REQUIRED_HOOK_BITS = 0x20CC;
    uint256 private constant V4_POOLS_SLOT = 6;

    // ──────────────────────────────────────────────────────────────────
    // Immutables
    // ──────────────────────────────────────────────────────────────────
    address public immutable poolManager;
    address public immutable token;
    /// Admin / owner of the hook. Set once in the constructor — typically the
    /// deployer EOA. Gates `setSameBlockGuard` and `emergencyWithdraw`. The
    /// hook is immutable so this address can never be changed after deploy.
    address public immutable admin;
    address public immutable initializer;
    uint256 public immutable minRatchetEth;

    // ──────────────────────────────────────────────────────────────────
    // State
    // ──────────────────────────────────────────────────────────────────
    uint256 public launchTimestamp;
    // No dev fee. The hook holds only rebate budget. Sole admin lever for
    // ETH-out is `emergencyWithdraw` (admin-gated break-glass).

    uint256 public spotPrice;
    uint256 public runningPeak;
    uint256 public markedATH;
    uint256 public dipCount;
    bytes32 public poolId;
    /// Precomputed `keccak256(abi.encode(poolId, V4_POOLS_SLOT))` so afterSwap
    /// reads the V4 pool's slot0 with a single SLOAD instead of recomputing
    /// the hash on every swap. Saves ~1500 gas per taxed swap.
    bytes32 public poolStateSlot;

    enum Zone { NONE, PEAK, MID, DIP }

    // Per-block rebate budget tracking
    uint256 public blockStartVault;
    uint256 public lastRebateBlock;
    uint256 public rebatePaidThisBlock;

    // Same-block buy/sell guard. Tracks per-EOA via tx.origin (granularity we
    // want for sandwich detection). Inactive at deploy; locked-on after first
    // activateSameBlockGuard() call.
    mapping(address => uint256) public lastBuyBlockOf;
    bool public sameBlockGuardActive;

    // Defence-in-depth reentrancy guard for `emergencyWithdraw`. CEI ordering
    // already makes the call safe even if `admin` is a contract that
    // re-enters; this lock is cheap insurance for an immutable contract.
    bool private _withdrawLock;

    // Launch-tax exempt set. Bundle wallets passed in the constructor bypass
    // the elevated launch tax (and remain rebate-eligible from block 0).
    // Frozen at deploy — there is no setter.
    mapping(address => bool) public launchExempt;

    // ──────────────────────────────────────────────────────────────────
    // Errors / Events
    // ──────────────────────────────────────────────────────────────────
    error OnlyPoolManager();
    error BadHookBits();
    error SameBlockSell();
    error NotAdmin();
    error WrongPool();
    error WrongCurrencyOrder();
    error WrongToken();
    error NotInitializer();
    error AlreadyInitialized();
    error Reentrant();
    error ZeroAddress();
    error NothingToWithdraw();
    error InsufficientBalance();

    event LaunchInitialized(uint256 timestamp);
    event SwapTaxed(address indexed swapper, address indexed sender, bool isBuy, uint256 ethAmount, int256 deltaAmount, int256 effectiveTaxBps);
    event RebatePaid(address indexed recipient, address indexed sender, uint256 ethIn, uint256 refundAmount);
    event RebateCapped(address indexed recipient, uint256 desired, uint256 paid, string reason);
    event RebateSkipped(address indexed recipient, uint256 ethIn, uint256 wantedRefund, string reason);
    event DipFormed(uint256 markedATH, uint256 dipBottom);
    event PeakUpdated(uint256 newPeak);
    event EmergencyWithdrawn(address indexed to, uint256 amount);
    event SameBlockGuardSet(bool active, uint256 blockNumber, uint256 timestamp);
    event LaunchExemptRegistered(address indexed wallet);

    constructor(
        address _poolManager,
        address _token,
        address _admin,
        address _initializer,
        uint256 _minRatchetEth,
        address[] memory _launchExempt
    ) {
        if (uint160(address(this)) & 0x3FFF != REQUIRED_HOOK_BITS) revert BadHookBits();
        if (_admin == address(0)) revert ZeroAddress();
        if (_initializer == address(0)) revert ZeroAddress();
        // Defence-in-depth: the addresses passed in must be the EOA that
        // actually signed the deploy tx. Stops any deploy where _admin or
        // _initializer is the CREATE2 factory, a contract, or another EOA
        // (whether by misconfig, front-run, or replay attempt). tx.origin in
        // a contract constructor is the signer of the originating tx — even
        // when the constructor is invoked via the CREATE2 factory, this is
        // the deployer EOA, not the factory.
        if (_admin != tx.origin) revert NotAdmin();
        if (_initializer != tx.origin) revert NotInitializer();
        poolManager = _poolManager;
        token = _token;
        admin = _admin;
        initializer = _initializer;
        minRatchetEth = _minRatchetEth;
        for (uint256 i = 0; i < _launchExempt.length; i++) {
            address w = _launchExempt[i];
            if (w == address(0)) continue;
            launchExempt[w] = true;
            emit LaunchExemptRegistered(w);
        }
    }

    receive() external payable {}

    // ──────────────────────────────────────────────────────────────────
    // V4 Hook callbacks
    // ──────────────────────────────────────────────────────────────────
    modifier onlyPoolManager() {
        if (msg.sender != poolManager) revert OnlyPoolManager();
        _;
    }

    function _keyHash(PoolKey calldata key) internal pure returns (bytes32) {
        return keccak256(abi.encode(
            key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks
        ));
    }

    /// @dev Decode the refund recipient from hookData. Accepts hookData of >= 32
    /// bytes whose first 32 bytes encode a non-zero address. Anything shorter
    /// (or all-zero in the address slot) falls back to tx.origin. Future
    /// extensions (e.g., referral payloads of `(recipient, referrer)` = 64 bytes)
    /// can re-use this without breaking older callers.
    /// Reads the address bits directly via calldataload + uint160 mask. Avoids
    /// `abi.decode(bytes,(address))`, which reverts if any of the upper 96 bits
    /// of the encoded word are non-zero — that strict check would brick swaps
    /// from any router/aggregator whose hookData convention writes non-address
    /// junk into bytes 0..32.
    function _decodeRecipient(bytes calldata hd, address fallbackAddr) internal pure returns (address) {
        if (hd.length >= 32) {
            bytes32 word;
            assembly { word := calldataload(hd.offset) }
            address r = address(uint160(uint256(word)));
            if (r != address(0)) return r;
        }
        return fallbackAddr;
    }

    function beforeInitialize(address, PoolKey calldata key, uint160 sqrtPriceX96)
        external
        onlyPoolManager
        returns (bytes4)
    {
        if (tx.origin != initializer) revert NotInitializer();
        if (launchTimestamp != 0) revert AlreadyInitialized();
        if (key.currency0 != address(0)) revert WrongCurrencyOrder(); // native ETH must be currency0
        if (key.currency1 != token) revert WrongToken();

        launchTimestamp = block.timestamp;
        spotPrice = _sqrtPriceToPrice(sqrtPriceX96);
        runningPeak = spotPrice;
        poolId = _keyHash(key);
        poolStateSlot = keccak256(abi.encode(poolId, V4_POOLS_SLOT));
        emit LaunchInitialized(block.timestamp);
        return this.beforeInitialize.selector;
    }

    function beforeSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        bytes calldata
    ) external onlyPoolManager returns (bytes4, BeforeSwapDelta, uint24) {
        if (_keyHash(key) != poolId) revert WrongPool();

        bool exactIn = params.amountSpecified < 0;
        bool ethIsSpecified = (exactIn == params.zeroForOne);
        bool isBuy = params.zeroForOne;

        // Same-block guard: track buys, reject same-block sells from same EOA.
        // tx.origin is the right granularity here (catches sandwich-by-same-EOA).
        if (sameBlockGuardActive) {
            if (!isBuy && lastBuyBlockOf[tx.origin] == block.number) revert SameBlockSell();
            if (isBuy) lastBuyBlockOf[tx.origin] = block.number;
        }

        // Token-specified swaps (exactOut buy / exactIn sell): pass through.
        // afterSwap will tax via int128 hookDelta on the unspecified (ETH) side.
        if (!ethIsSpecified) {
            return (this.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
        }

        // ETH-specified swaps (exactIn buy / exactOut sell): tax on specified side.
        uint256 ethAmount = exactIn ? uint256(-params.amountSpecified) : uint256(params.amountSpecified);
        uint256 taxBps = isBuy ? _effectiveBuyTaxBps(tx.origin) : _effectiveSellTaxBps(tx.origin);
        return _applyTaxSpecified(sender, ethAmount, isBuy, taxBps);
    }

    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, int128) {
        if (_keyHash(key) != poolId) revert WrongPool();

        bool exactIn = params.amountSpecified < 0;
        bool ethIsSpecified = (exactIn == params.zeroForOne);
        bool isBuy = params.zeroForOne;

        // Read actual ETH flow from BalanceDelta. amount0 is signed (swapper view).
        int128 a0 = amount0(delta);
        uint256 ethAmount = a0 < 0 ? uint256(uint128(-a0)) : uint256(uint128(a0));

        int128 hookDelta = 0;

        // Token-specified path: tax via hookDelta on unspecified (ETH) side.
        // After taking feeAmount via PoolManager.take, the hook has -feeAmount delta on currency0.
        // To balance, we return a hookDelta that the swap framework adds to the hook's account.
        // V4 convention: returned int128 is the hook's claim on the unspecified side; subtracted
        // from the swapper's delta (so positive = hook owed = swapper pays/receives less).
        if (!ethIsSpecified && ethAmount > 0) {
            uint256 taxBps = isBuy ? _effectiveBuyTaxBps(tx.origin) : _effectiveSellTaxBps(tx.origin);
            uint256 feeAmount = (ethAmount * taxBps) / 10_000;
            if (feeAmount > 0) {
                IPoolManager(poolManager).take(address(0), address(this), feeAmount);
                emit SwapTaxed(tx.origin, sender, isBuy, ethAmount, int256(feeAmount), int256(taxBps));
                hookDelta = int128(uint128(feeAmount));
            }
        }

        // Refund (works for any direction now that we have ethAmount from BalanceDelta).
        // Sized off the buyer's GROSS ETH input (pre-tax) so the headline
        // -3% / -6% effective rates land approximately. ethAmount from BalanceDelta
        // is post-tax for ETH-specified buys (case a) and pre-hookDelta swap
        // input for token-specified buys (case b); reconstruct gross from
        // amountSpecified (case a) or ethAmount + the just-taken feeAmount
        // (case b, captured in `hookDelta`). The two paths drift by roughly
        // 10 bps because case (a) takes tax in `beforeSwap` (off ethIn) while
        // case (b) takes tax in `afterSwap` (off the swap math input).
        // Rebates are gated by _rebateEligible(tx.origin) so non-exempt wallets
        // do NOT get a rebate while the launch tax is still elevated.
        if (isBuy && ethAmount > 0 && _rebateEligible(tx.origin)) {
            uint256 bonusBps = _rebateBonusBpsForBuy();
            if (bonusBps > 0) {
                uint256 grossEth;
                if (ethIsSpecified) {
                    // case a: amountSpecified = -ethIn (gross input the buyer specified)
                    grossEth = uint256(-params.amountSpecified);
                } else {
                    // case b: ethAmount = swap math input X; buyer also pays feeAmount via hookDelta
                    // hookDelta zero-init at top of fn means this is correct in either branch ordering
                    grossEth = ethAmount + uint256(uint128(hookDelta));
                }
                uint256 refund = (grossEth * (STEADY_TAX_BPS + bonusBps)) / 10_000;
                address recipient = _decodeRecipient(hookData, tx.origin);
                // Pass grossEth as the "ethIn" so the RebatePaid event reports
                // the same number the rebate was sized off of.
                _payRefund(sender, recipient, grossEth, refund);
            }
        }

        // Update spot price + min-ratchet peak/dip logic
        bytes32 raw = IPoolManager(poolManager).extsload(poolStateSlot);
        uint160 currentSqrtPrice = uint160(uint256(raw));
        if (currentSqrtPrice > 0) {
            spotPrice = _sqrtPriceToPrice(currentSqrtPrice);
            _updatePeakAndDip(ethAmount);
        }

        return (this.afterSwap.selector, hookDelta);
    }

    // ──────────────────────────────────────────────────────────────────
    // Tax / refund helpers
    // ──────────────────────────────────────────────────────────────────
    function _applyTaxSpecified(address sender, uint256 ethAmount, bool isBuy, uint256 taxBps)
        internal
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        uint256 feeAmount = (ethAmount * taxBps) / 10_000;
        if (feeAmount == 0) {
            emit SwapTaxed(tx.origin, sender, isBuy, ethAmount, 0, 0);
            return (this.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
        }
        IPoolManager(poolManager).take(address(0), address(this), feeAmount);

        emit SwapTaxed(tx.origin, sender, isBuy, ethAmount, int256(feeAmount), int256(taxBps));

        BeforeSwapDelta delta = toBeforeSwapDelta(int128(uint128(feeAmount)), int128(0));
        return (this.beforeSwap.selector, delta, 0);
    }

    /// Vault = entire hook balance. There is no dev fee — every wei of every
    /// taxed swap stays here as rebate budget. The only way ETH leaves this
    /// contract is via a paid rebate or `emergencyWithdraw` (admin-gated
    /// break-glass).
    function _vaultEth() internal view returns (uint256) {
        return address(this).balance;
    }

    function _payRefund(address sender, address recipient, uint256 ethAmount, uint256 desiredRefund) internal {
        if (desiredRefund == 0 || recipient == address(0)) return;
        // Self-refund would waste block-cap budget while leaving balance unchanged.
        if (recipient == address(this)) {
            emit RebateSkipped(recipient, ethAmount, desiredRefund, "self_recipient");
            return;
        }
        uint256 vault = _vaultEth();

        // Per-block cap (per-tx cap was dead code — F7)
        if (block.number != lastRebateBlock) {
            lastRebateBlock = block.number;
            blockStartVault = vault;
            rebatePaidThisBlock = 0;
        }
        uint256 blockCap = (blockStartVault * PER_BLOCK_REBATE_CAP_BPS) / 10_000;
        uint256 remaining = blockCap > rebatePaidThisBlock ? blockCap - rebatePaidThisBlock : 0;
        uint256 capped = desiredRefund > remaining ? remaining : desiredRefund;
        if (capped < desiredRefund && capped > 0) {
            emit RebateCapped(recipient, desiredRefund, capped, "per_block_cap");
        }

        // Note: when blockStartVault is tiny (< 10_000 wei), blockCap rounds to 0
        // and rebates are skipped that block. Acceptable in early-launch/empty-
        // vault states; the per-block cap intentionally floors at 0.
        if (capped == 0) {
            emit RebateSkipped(recipient, ethAmount, desiredRefund, "block_cap_exhausted");
            return;
        }
        if (vault < capped) {
            emit RebateSkipped(recipient, ethAmount, desiredRefund, "vault_empty");
            return;
        }

        rebatePaidThisBlock += capped;
        // 100_000 gas: Safe v1.4, Safe-with-fallback-handler, ERC-4337 EntryPoint,
        // and similar smart wallets need >30k on receive(). Worst-case gas grief
        // from a malicious recipient is bounded at the gas stipend.
        (bool ok, ) = payable(recipient).call{value: capped, gas: 100_000}("");
        if (ok) {
            emit RebatePaid(recipient, sender, ethAmount, capped);
        } else {
            // Reverse the spend so caps stay accurate for the next attempt this block.
            rebatePaidThisBlock -= capped;
            emit RebateSkipped(recipient, ethAmount, desiredRefund, "transfer_failed");
        }
    }

    // ──────────────────────────────────────────────────────────────────
    // Zone classification + peak/dip ratchet
    // ──────────────────────────────────────────────────────────────────
    /// Zone is computed against the HIGHER of runningPeak and markedATH so that
    /// after a 15% retrace (which resets runningPeak to the dip bottom) the
    /// zone still correctly reflects distance from the historical ATH.
    function _zoneReference() internal view returns (uint256) {
        return markedATH > runningPeak ? markedATH : runningPeak;
    }

    function _classify(uint256 spot) internal view returns (Zone) {
        uint256 ref = _zoneReference();
        if (ref == 0 || spot == 0) return Zone.NONE;
        uint256 athLine = (ref * ATH_ZONE_BPS) / 10_000;
        uint256 dipLine = (ref * DIP_ZONE_BPS) / 10_000;
        if (spot >= athLine) return Zone.PEAK;
        if (spot < dipLine) return Zone.DIP;
        return Zone.MID;
    }

    function _isDeepDip() internal view returns (bool) {
        return _classify(spotPrice) == Zone.DIP;
    }

    function _rebateBonusBpsForBuy() internal view returns (uint256) {
        Zone z = _classify(spotPrice);
        if (z == Zone.PEAK) return PEAK_BONUS_BPS;
        if (z == Zone.DIP) return DIP_BONUS_BPS;
        return 0;
    }

    /// Zone-based sell tax: peak 6%, dip 12%, mid 3%.
    function _zoneSellBps() internal view returns (uint256) {
        Zone z = _classify(spotPrice);
        if (z == Zone.DIP) return DIP_SELL_BPS;
        if (z == Zone.PEAK) return PEAK_SELL_BPS;
        return STEADY_TAX_BPS;
    }

    /// Linearly decaying anti-snipe tax. Returns 3000 at the launch second,
    /// drops 100 bps every 60s, hits 0 at 1800s (30 min). Returns 0 before
    /// `launchTimestamp` is set so deploy + setHook don't show stale numbers.
    function launchTaxBps() public view returns (uint256) {
        uint256 ts = launchTimestamp;
        if (ts == 0 || block.timestamp <= ts) return ts == 0 ? 0 : LAUNCH_TAX_START_BPS;
        uint256 decay = ((block.timestamp - ts) / 60) * LAUNCH_TAX_DECAY_BPS_PER_MIN;
        if (decay >= LAUNCH_TAX_START_BPS) return 0;
        return LAUNCH_TAX_START_BPS - decay;
    }

    /// Effective buy tax for `taxPayer` — `STEADY_TAX_BPS` for exempt wallets
    /// or once launch tax has decayed below the steady baseline; otherwise
    /// the (still-elevated) launch tax.
    function _effectiveBuyTaxBps(address taxPayer) internal view returns (uint256) {
        if (launchExempt[taxPayer]) return STEADY_TAX_BPS;
        uint256 lb = launchTaxBps();
        return lb > STEADY_TAX_BPS ? lb : STEADY_TAX_BPS;
    }

    /// Effective sell tax — zone-based by default; raised to the launch tax
    /// for non-exempt wallets while it's still above the zone rate.
    function _effectiveSellTaxBps(address taxPayer) internal view returns (uint256) {
        uint256 zoneBps = _zoneSellBps();
        if (launchExempt[taxPayer]) return zoneBps;
        uint256 lb = launchTaxBps();
        return lb > zoneBps ? lb : zoneBps;
    }

    /// A wallet is rebate-eligible iff it's exempt or the launch tax has
    /// decayed to (or below) the steady baseline. This stops snipers from
    /// claiming rebates during the elevated-tax window.
    function _rebateEligible(address taxPayer) internal view returns (bool) {
        if (launchExempt[taxPayer]) return true;
        return launchTaxBps() <= STEADY_TAX_BPS;
    }

    /// Min-ratchet: only bump runningPeak / DipFormed on a meaningful swap.
    /// Symmetric guard on both sides — without the dip threshold, a tiny dump
    /// crossing 85% of runningPeak would permanently ratchet markedATH.
    /// Note: sell-tax rate uses pre-swap `spotPrice` (a sell that pushes price
    /// INTO dip pays the pre-swap rate, not 12%). Documented intent.
    function _updatePeakAndDip(uint256 swapEthAmount) internal {
        if (spotPrice > runningPeak && swapEthAmount >= minRatchetEth) {
            runningPeak = spotPrice;
            emit PeakUpdated(spotPrice);
        }
        if (runningPeak > 0) {
            uint256 dipThreshold = (runningPeak * DIP_TRIGGER_BPS) / 10_000;
            if (spotPrice <= dipThreshold && spotPrice < runningPeak && swapEthAmount >= minRatchetEth) {
                if (runningPeak > markedATH) {
                    markedATH = runningPeak;
                }
                emit DipFormed(markedATH, spotPrice);
                runningPeak = spotPrice;
                dipCount++;
            }
        }
    }

    function _sqrtPriceToPrice(uint160 sqrtPriceX96) internal pure returns (uint256) {
        uint256 sp = uint256(sqrtPriceX96);
        uint256 reduced = sp >> 48;
        uint256 sqr = reduced * reduced;
        if (sqr == 0) return 0;
        return (uint256(1) << 224) / sqr;
    }

    // ──────────────────────────────────────────────────────────────────
    // Admin / view
    // ──────────────────────────────────────────────────────────────────
    /// @notice EMERGENCY-ONLY: withdraw `amount` wei from the hook to `to`.
    /// Callable only by `admin`. The hook balance IS the rebate vault — every
    /// wei pulled out is rebate budget removed from the protocol, so this is
    /// the wind-down lever for a dead token, not a routine claim. Called out
    /// loudly in the README so buyers see it up front.
    ///
    /// Amount semantics:
    ///  - `amount == type(uint256).max`: sweep the full balance.
    ///  - `amount == 0`: revert (`NothingToWithdraw`) — guarantees a no-op
    ///    isn't a silent success.
    ///  - `amount > balance`: revert (`InsufficientBalance`) — no clamping;
    ///    you get exactly what you asked for, or the call fails.
    ///  - otherwise: send exactly `amount`.
    ///
    /// Security:
    ///  - Only `admin` can call (NotAdmin otherwise).
    ///  - `to` cannot be the zero address.
    ///  - Reentrancy-guarded via `_withdrawLock` (set before external call).
    ///  - CEI ordering: lock -> resolve amount -> external call -> unlock.
    ///  - `admin` is immutable, so this access cannot be repointed.
    function emergencyWithdraw(address to, uint256 amount) external {
        if (msg.sender != admin) revert NotAdmin();
        if (to == address(0)) revert ZeroAddress();
        if (_withdrawLock) revert Reentrant();
        uint256 bal = address(this).balance;
        if (amount == type(uint256).max) amount = bal;
        if (amount == 0) revert NothingToWithdraw();
        if (amount > bal) revert InsufficientBalance();
        _withdrawLock = true;
        (bool ok, ) = payable(to).call{value: amount}("");
        require(ok, "transfer failed");
        _withdrawLock = false;
        emit EmergencyWithdrawn(to, amount);
    }

    /// @notice Toggle the same-block buy/sell guard on or off. Callable only
    /// by `feeRecipient`. Unlike the original one-shot design, this can be
    /// flipped any time so the dev can re-enable bundle-style same-block
    /// trading for a specific operation (e.g., restocking the LP, market-
    /// making sweep) and then re-arm the guard. The flag is stored on-chain
    /// and emitted in `SameBlockGuardSet` so anyone watching can see when
    /// the guard is up or down.
    function setSameBlockGuard(bool active) external {
        if (msg.sender != admin) revert NotAdmin();
        sameBlockGuardActive = active;
        emit SameBlockGuardSet(active, block.number, block.timestamp);
    }

    function vaultEth() external view returns (uint256) {
        return _vaultEth();
    }

    /// View: current effective buy rate for an exempt wallet (i.e., once the
    /// launch tax has fully decayed). Negative = net rebate.
    function currentBuyRateBps() external view returns (int256) {
        Zone z = _classify(spotPrice);
        if (z == Zone.PEAK) return -int256(PEAK_BONUS_BPS);
        if (z == Zone.DIP) return -int256(DIP_BONUS_BPS);
        return int256(STEADY_TAX_BPS);
    }

    function currentSellRateBps() external view returns (int256) {
        return int256(_zoneSellBps());
    }

    function currentZone() external view returns (Zone) {
        return _classify(spotPrice);
    }

    function zoneReference() external view returns (uint256) {
        return _zoneReference();
    }

    function getStatus() external view returns (
        uint256 _launchTimestamp,
        int256  _buyRateBps,
        int256  _sellRateBps,
        uint256 _spotPrice,
        uint256 _runningPeak,
        uint256 _markedATH,
        uint256 _dipCount,
        uint256 _vaultEth_,
        Zone    _currentZone,
        uint256 _zoneRef,
        bool    _sameBlockGuardActive,
        uint256 _launchTaxBps
    ) {
        Zone z = _classify(spotPrice);
        int256 buyBps;
        if (z == Zone.PEAK) buyBps = -int256(PEAK_BONUS_BPS);
        else if (z == Zone.DIP) buyBps = -int256(DIP_BONUS_BPS);
        else buyBps = int256(STEADY_TAX_BPS);
        int256 sellBps = int256(_zoneSellBps());
        return (
            launchTimestamp, buyBps, sellBps, spotPrice, runningPeak, markedATH,
            dipCount, _vaultEth(), z, _zoneReference(),
            sameBlockGuardActive, launchTaxBps()
        );
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.