Skip to content
Verified contractPartialUNLICENSED

TokenomicsVaultV24F1

Address0x484f5436aeaa8da34cf20010ad6fa953fb147f76
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,396,968
Creation transaction
0xfae10ee8cd…adf7c0351b

94 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/tokenomics/v24f1/TokenomicsVaultV24F1.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.30;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IUnlockCallback} from "@uniswap/v4-core/src/interfaces/callback/IUnlockCallback.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {SqrtPriceMath} from "@uniswap/v4-core/src/libraries/SqrtPriceMath.sol";

import {TokenomicsMath} from "../TokenomicsMath.sol";
import {TokenomicsV23Math} from "../v23/TokenomicsV23Math.sol";
import {TokenomicsChainParams} from "../ITokenomics.sol";
import {TokenomicsV22Gas} from "../v22/ITokenomicsV22.sol";
import {TokenomicsVaultV24Base} from "../v24/TokenomicsVaultV24Base.sol";
import {GasSwapF1, ITokenomicsVaultF1GasSwap, ITokenomicsFactoryF1Routers} from "./GasSwapF1.sol";

/// @dev TK-COOLDOWN: the two buy-stage settings a TokenomicsFactoryV24F1's admin sets, read live by its vaults.
interface ITokenomicsFactoryV24F1Swap {
    function swapCooldown() external view returns (uint256);
    function impactCapBps() external view returns (uint256);
}

/// @title TokenomicsVaultV24 (version 2.4: v2.3's, but `execute` pushes only the wallets paid in the
///        pair token; a wallet paid in a token of its own is bought for by `buyWallet` -- see
///        TokenomicsVaultV24Base. v2.3's title follows.)
/// @notice (v2.3) TokenomicsVaultV23 (version 2.3: v2.2 with the buy stage, the swap, the liquidity add and
///        the refund in the pool's quote -- native exactly as v2.2, or a listed ERC-20 on either side)
/// @notice v2.2 = TokenomicsVaultV21 with the BURN TOKENS bucket (docs/tokenomics-v22-spec.md). In
///         this contract the one change is `_allocate` (TokenomicsVaultV24Base): six parts, the sixth
///         credited to the burn targets' buckets. `execute` never spends, clears or restores a burn
///         bucket (it only credits them; `buyBurn` and `rollBurnTarget` are guarded), so they are
///         not in its storage-refund snapshot. Its `gasOverhead` is v2.2's own, re-measured.
///         v2.1's notes (TokenomicsVaultV21) apply unchanged to everything else here: the
///         operator's execute, its refund, the fallback, the buy stage and the wallets' pushes.
///
/// This is the clones' implementation. It carries fees in (`receive`), `sync`, `execute` and the
/// swap's callbacks; every other function lives in TokenomicsVaultV24Module (and, behind it,
/// TokenomicsVaultV24BurnModule) and is reached through `fallback` by DELEGATECALL, over the same
/// storage (TokenomicsVaultV24Base).
/// @dev TK-COOLDOWN3: Arbitrum's ArbSys precompile (0x64): the L2 block number.
interface IArbSysF1 {
    function arbBlockNumber() external view returns (uint256);
}

/// @title TokenomicsVaultV24F1 (TK-COOLDOWN, owner 2026-10-29 "EVM tokenomics never queue"): TokenomicsVaultV24 with
///        TWO changes, both read LIVE from the factory (TokenomicsFactoryV24F1), whose admin sets them: the swap
///        cooldown is `factory.swapCooldown()` (default 0: back-to-back executes may each buy) instead of the
///        constant 15 minutes, and the buy stage's price-impact cap is `factory.impactCapBps()` when non-zero,
///        else the pool's fee (`feeBps`, v2.4's cap, the default). TK-COOLDOWN3 (D1 ruling on AUD-D1C M-1): the cap
///        is PER BLOCK, not per call: the limit is taken from the block's FIRST price the buy stage sees, and the
///        room from it is spent cumulatively by every execute in that block (any caller, the operator's too); the
///        next block starts afresh (on Arbitrum chains the L2 block, ArbSys's number). A run past the block's room
///        swaps nothing (`SwapSkipped(BlockRoomSpent)`) and its buckets stay due. Its storage: four fields APPENDED after TokenomicsVaultV24Base's layout (the
///        modules declare none, so the delegatecalls are unaffected). `diff src/tokenomics/v24/TokenomicsVaultV24.sol`
///        shows only this. v2.4's notes follow.
contract TokenomicsVaultV24F1 is TokenomicsVaultV24Base, IUnlockCallback {
    using SafeERC20 for IERC20;
    using PoolIdLibrary for PoolKey;

    uint256 internal constant LIQUIDITY_MARGIN_BPS = 9_990;
    uint256 internal constant ROOM_MARGIN_BPS = 9_900;

    /// @dev TokenomicsVaultV24Module: everything this contract does not carry.
    address internal immutable module;

    /// @dev TK-COOLDOWN3 (AUD-D1C M-1): the block the per-block impact cap is counted for, the room left in it,
    ///      and the pool's price the buy stage first saw in it (the cap's base). A block is its number AND its
    ///      timestamp (both fixed within a block on every chain, so this is exactly per block; the timestamp also
    ///      tells a test's warp without a roll apart). On an Arbitrum chain (Arbitrum, Robinhood) the number is
    ///      ArbSys's L2 block number (`block.number` there is the parent chain's, shared by many L2 blocks). The
    ///      block, its time and the room share a slot and the price has its own: neither is ever cleared to zero
    ///      (no EIP-3529 refund the operator's refund measurement would have to count).
    uint64 internal _capBlock;
    uint64 internal _capTime;
    uint128 internal _capLeft;
    uint160 internal _capSqrtP;

    /// @dev TK-COOLDOWN3: whether this chain is an Arbitrum chain (ArbSys answers). Decided at construction (the
    ///      clones run this code, so it is theirs), as in PangeaFastBridge.
    bool internal immutable arbitrum;

    /// @notice TK-COOLDOWN3: this block's impact-cap room is spent (a reason in `SwapSkipped`; the buckets
    ///         stay due for the next block).
    error BlockRoomSpent(uint256 blockNumber);

    constructor(
        TokenomicsChainParams memory p,
        address liquidityAdder_,
        address swapper_,
        TokenomicsV22Gas memory g,
        address module_
    ) TokenomicsVaultV24Base(p, liquidityAdder_, swapper_, g)
    {
        module = module_;
        (bool ok, bytes memory ret) =
            address(0x64).staticcall{gas: 50_000}(abi.encodeWithSelector(IArbSysF1.arbBlockNumber.selector));
        arbitrum = ok && ret.length == 32;
    }

    /// @notice Fees arrive from the splitter under its 50,000-gas cap, so this writes nothing for
    ///         them; the launch-fee collector's refunds are the owner's, booked as such.
    receive() external payable {
        if (msg.sender == collector) {
            ownerRefund += msg.value;
            emit RefundReceived(msg.value);
        }
    }

    /// @dev Every other function: the module's code, run on this vault's storage.
    fallback() external payable {
        address m = module;
        assembly ("memory-safe") {
            let p := mload(0x40)
            calldatacopy(p, 0, calldatasize())
            let ok := delegatecall(gas(), m, p, calldatasize(), 0, 0)
            returndatacopy(p, 0, returndatasize())
            if iszero(ok) { revert(p, returndatasize()) }
            return(p, returndatasize())
        }
    }

    /// @dev GAS-REPAY-SWAP: the operator's repay: native as before; an ERC-20 quote by the burn module's `gasRepay`
    ///      self-call (swap to native through the allowed router, the operator paid the gas owed). False = none.
    function _repayF1(uint256 amount) internal returns (bool) {
        if (quote == address(0)) return _sendQuote(msg.sender, amount, gasleft());
        (bool ok, bytes memory r) = address(this).call(abi.encodeCall(ITokenomicsVaultF1GasSwap.gasRepay, (amount, msg.sender)));
        return ok && r.length == 32 && abi.decode(r, (bool));
    }

    /// @notice Pull what the hook and the splitter hold for this vault and allocate it. Anyone.
    function sync() external nonReentrant {
        _requireBound();
        _pull();
        _allocate();
    }

    // ------------------------------------------------------------------------------ execute

    struct Run {
        uint256[3] spend;
        uint256 coinsBurned;
        uint256 coinsToTreasury;
    }

    /// @dev One run's parts: index 0..2 the buckets (BURN, BUY_HOLD, LIQUIDITY), 3 + w wallet w.
    struct Parts {
        /// What each part is due this run (zero: not run).
        uint256[13] due;
        /// What is held back from it for the operator's refund (operator runs only).
        uint256[13] held;
        /// What it actually paid out: a bucket's spend, a wallet's push.
        uint256[13] paid;
        uint256 dueTotal;
        uint256 paidTotal;
        /// Repaid operator runs only (audit TK21-E2 follow-up): the slots execute can clear or
        /// restore, read at its start (`o`), after the fee pull and allocation (`a`) and at the end
        /// of the measurement (`f`). Index 0..2 the buckets, 3 + w wallet w's accrual, 13
        /// `walletsTotal`, 14 `liquidityCoins`, 15 this vault's balance of the coin; the fee pull's
        /// slots: 16, 17 the hook's `owed` for this pool (native, coin), 18, 19 the hook's ERC-6909
        /// claims in the pool manager (native, coin), 20 the splitter's `unclaimedNative` for this
        /// vault, 21 its `reservedNative`; 22, 23 the coin balances of the owner and the treasury
        /// (as they were at the start), which the run fills (forwarded coins, the buy & hold) before
        /// the pushes and a wallet with code -- the owner, the treasury, or one they approved --
        /// could empty inside its push; the pool's slots a swap can clear by crossing its range's
        /// edge: 24 the pool's active liquidity, 25, 26 the lower tick's fee growth outside (0, 1),
        /// 27, 28 the upper tick's, 29 the pool manager's balance of the coin.
        uint256[30] o;
        uint256[30] a;
        uint256[30] f;
        /// The owner and the treasury at the start (zero: not read -- this vault, or the same slot).
        address ownerAt;
        address treasuryAt;
        /// Which slot holds the treasury's coin balance: 23 its own, 22 when the treasury is the
        /// owner, 15 when it is this vault -- the one `_treasuryFilled` marks changed.
        uint256 treSlot;
        /// Bit i: slot i (16..21) could not be read at one of the three points.
        uint256 unreadable;
        /// The gas the run's native pushes to wallets WITH CODE spent (each call, whole): what such a
        /// recipient can earn back inside it (EIP-3529 refunds are never more than the writes that
        /// earn them cost) is taken out of the repaid units with the storage refund.
        uint256 recipientGas;
    }

    /// @notice Spend every bucket that has reached the minimum and push the wallets.
    ///
    /// v2.1 (owner 2026-10-27, option d): the OPERATOR's (`factory.operator()`), and anyone's only
    /// once this vault has seen no operator run for `factory.fallbackDelay()`. A fallback run is
    /// repaid nothing and pays every part in full. An operator run is repaid its own gas -- what this
    /// call measures, plus the chain's overhead, at most `maxGasUnits`, at the gas price capped at
    /// base fee + `maxPriorityFeeWei` -- times (1 + `factory.refundMarginBps()`), and never more than
    /// `factory.refundCapBps()` of what the run pays out: a run whose refund would be more REVERTS
    /// (`RefundAboveCap`), so it is not run. No fixed reserve: before paying, each part holds back
    /// its share of the refund the operator estimates (`gasHint` gas units at the capped price and
    /// margin; at most the cap), and after, each is charged at most the refund times its share of
    /// what the run paid out -- never more than it held back -- and keeps the rest of what it held
    /// (a bucket keeps it, a wallet's is re-credited to its accrual, paid next run or by
    /// `claimWallet`). A `gasHint` too low only under-repays the operator; too high holds back more
    /// for one run and returns all of it unused; above `maxGasUnits` it counts as `maxGasUnits`.
    /// A `gasHint` of ZERO is the operator opting out of the refund for this run (audit TK21-E2 M-1:
    /// a thin pool or a skipped swap can leave a run's payout below the cap of any refund): nothing
    /// is held back, nothing is charged, the cap is not checked, and the run still counts as the
    /// operator's (it resets the fallback clock). With `refundCapBps` at 0 the operator can only
    /// run this way.
    /// The refund measures this call's execution gas plus `gasOverhead`, less the gas the
    /// transaction gets back for the storage this run clears or restores (EIP-3529; see
    /// `_clearsCredit`), at most a fifth of it as the receipt allows; it does not see an L2's L1
    /// data fee (audit TK21-E2 L-2, accepted: the executor counts it apart).
    /// @param gasHint The operator's estimate of this call's gas units, or 0 for no refund (ignored on
    ///        a fallback run).
    function execute(uint256 gasHint) external nonReentrant {
        uint256 gasStart = gasleft();
        _requireBound();
        bool operatorRun = _executeGate();
        Parts memory pt;
        if (operatorRun && gasHint != 0) _snapStart(pt);
        _forwardCoins();
        _pull();
        _allocate();
        if (operatorRun && gasHint != 0) _snap(pt, pt.a);

        uint256 minimum = GasSwapF1.q(_roles().minExecuteWei(), quote); // GAS-REPAY-SWAP: no admin rate (none outside withGasSwap)

        // The due parts. A bucket waiting out the swap cooldown is not due this run.
        // TK-COOLDOWN: the factory admin's cooldown (default 0), read once.
        uint256 coolEnd = uint256(lastSwap) + ITokenomicsFactoryV24F1Swap(factory).swapCooldown();
        bool coolingDown = block.timestamp < coolEnd;
        for (uint256 i = 0; i < NUM_BUCKETS; i++) {
            uint256 b = _buckets[i];
            if (b <= DUST || b < minimum) continue; // a charge's leftover (<= 2 wei) is not due
            if (i == LIQUIDITY && !hook.isLiquidityAdder(address(liquidityAdder))) continue;
            if (coolingDown) continue;
            pt.due[i] = b;
            pt.dueTotal += b;
        }
        if (coolingDown && (_buckets[BURN] != 0 || _buckets[BUY_HOLD] != 0 || _buckets[LIQUIDITY] != 0)) {
            emit SwapSkipped(abi.encodeWithSelector(TooSoon.selector, coolEnd));
        }
        uint256 n = walletCount;
        {
            // v2.4: a wallet paid in a token keeps its accrual for `buyWallet` (or its own `claimWallet`)
            // while the operator buys it; one not bought for `fallbackDelay` (since the bind or its last
            // buy) is pushed in the quote by any run, the operator's or the fallback (audit v2.4 r2 L2,
            // r3 M1/L1): never stranded, never overridden while it is being bought.
            uint256 pushable;
            uint256 swaps;
            uint256 delay = n == 0 ? 0 : _roles().fallbackDelay();
            for (uint256 w = 0; w < n; w++) {
                if (_walletHeld(w, delay)) swaps |= 1 << w;
                else pushable += _walletAccrued[w];
            }
            if (pushable >= minimum && pushable != 0) {
                for (uint256 w = 0; w < n; w++) {
                    uint256 acc = _walletAccrued[w];
                    if (acc <= DUST || swaps & (1 << w) != 0) continue;
                    pt.due[NUM_BUCKETS + w] = acc;
                    pt.dueTotal += acc;
                }
            }
        }
        if (pt.dueTotal == 0) revert NothingToExecute();

        // The hold-back (operator runs only; a hint of zero opts out: no hold-back, no refund).
        if (operatorRun && gasHint != 0) _holdBack(pt, n, gasHint);

        // The buckets: one capped swap for the three buying buckets, then burn, treasury, liquidity.
        Run memory run;
        if (pt.due[BURN] != 0 || pt.due[BUY_HOLD] != 0 || pt.due[LIQUIDITY] != 0) {
            _buyStage(
                run,
                pt.due[BURN] - pt.held[BURN],
                pt.due[BUY_HOLD] - pt.held[BUY_HOLD],
                pt.due[LIQUIDITY] - pt.held[LIQUIDITY]
            );
        }
        for (uint256 i = 0; i < NUM_BUCKETS; i++) {
            uint256 s = run.spend[i];
            if (s == 0) continue;
            _buckets[i] -= s; // what it held back stays in it
            _spent[i] += s;
            pt.paid[i] = s;
            pt.paidTotal += s;
            emit Spent(i, s);
        }

        // The wallets: each pushed its accrual less what it holds back, which stays credited to it.
        // `walletsTotal` is written ONCE, by the sum, before the pushes: a running decrement could pass
        // through its start value (a restore the measurement cannot see). (Views read during the
        // pushes see the wallets' accruals not yet decremented: high until the loop ends.)
        {
            uint256 pushed;
            for (uint256 w = 0; w < n; w++) {
                uint256 x = NUM_BUCKETS + w;
                pt.paid[x] = pt.due[x] - pt.held[x];
                pushed += pt.paid[x];
            }
            if (pushed != 0) walletsTotal -= pushed;
        }
        for (uint256 w = 0; w < n; w++) {
            uint256 a = pt.paid[NUM_BUCKETS + w];
            if (a == 0) continue;
            _walletAccrued[w] -= a;
            // v2.4 (audit r5 M1): a token wallet pushed in the quote (its clock lapsed) gets a new window to
            // be bought in -- a lapse is a week's fallback, never the end of its choice.
            if (_walletSwaps(w)) _walletLastBuy[w] = uint40(block.timestamp);
            pt.paidTotal += a;
            _push(pt, w, a);
        }
        if (pt.paidTotal == 0) revert NothingToExecute();
        totalCoinBurned += run.coinsBurned;
        totalCoinToTreasury += run.coinsToTreasury;

        if (operatorRun) {
            lastOperatorRun = uint40(block.timestamp);
            if (gasHint != 0) _refund(gasStart, pt, n);
        }
    }

    /// @dev One wallet push. A recipient with code runs inside it and can earn storage refunds there
    ///      (its own slots, or this vault's through a non-guarded call such as proposeWallet then
    ///      acceptWallet): the whole call's gas is counted for the refund's deduction (audit TK21-E2
    ///      follow-up L-2), so no recipient can make the operator be repaid more than it spent. An
    ///      account without code runs nothing (the call's own cost is not counted).
    function _push(Parts memory pt, uint256 w, uint256 a) internal {
        address to = _wallets[w];
        uint256 g = gasleft();
        bool ok = _payOut(to, a);
        if (to.code.length != 0) pt.recipientGas += g - gasleft();
        if (ok) emit WalletPaid(w, to, a);
    }

    /// @dev The hold-back: the operator's estimate -- `gasHint` gas units, at most `maxGasUnits`, at
    ///      the capped price, times (1 + margin) -- at most the cap of what is due, shared pro rata
    ///      over the due parts.
    function _holdBack(Parts memory pt, uint256 n, uint256 gasHint) internal view {
        uint256 units = gasHint > maxGasUnits ? maxGasUnits : gasHint;
        uint256 hold = GasSwapF1.q(FullMath.mulDiv(units * _cappedGasPrice(), BPS + _refundMarginBps(), BPS), quote);
        uint256 capHold = FullMath.mulDiv(pt.dueTotal, _refundCapBps(), BPS);
        if (hold > capHold) hold = capHold;
        if (hold == 0) return;
        for (uint256 x = 0; x < NUM_BUCKETS + n; x++) {
            if (pt.due[x] != 0) pt.held[x] = FullMath.mulDiv(hold, pt.due[x], pt.dueTotal);
        }
    }

    /// @dev The operator's refund: this call's gas at the capped price, times (1 + margin) -- above
    ///      `refundCapBps` of what the run paid out the whole run reverts. Each part is charged at
    ///      most the refund times its share of the payout, and never more than it held back; the
    ///      operator gets the sum of the charges (rounding down, never more than the refund).
    ///      The gas is what the call measured plus `gasOverhead`, less what the transaction gets back
    ///      for the storage this run clears or restores (audit TK21-E2 follow-up): the slots the run
    ///      itself left cleared or restored (`_clearsCredit`) and the gas of the pushes to wallets with
    ///      code (`_push`); the charges, after the measurement, never clear or restore a slot (see
    ///      `_charges`), so they earn nothing to count. In all at most a fifth of the measured gas --
    ///      the receipt's own cap on refunds (EIP-3529), applied to the gas this run can see. Only ever subtracted: the refund is never larger for it, and the units never
    ///      below zero. `Reimbursed.gasUnits` is these NET units (what is repaid, x price x margin).
    function _refund(uint256 gasStart, Parts memory pt, uint256 n) internal {
        uint256 credit = _clearsCredit(pt) + pt.recipientGas;
        (uint256 units,) = _netUnits(gasStart - gasleft() + gasOverhead, credit);
        if (units > maxGasUnits) units = maxGasUnits;
        uint256 price = _cappedGasPrice();
        uint256[13] memory charge;
        uint256 refund = GasSwapF1.q(FullMath.mulDiv(units * price, BPS + _refundMarginBps(), BPS), quote);
        uint256 total = _charges(pt, n, refund, charge);
        uint256 cap = FullMath.mulDiv(pt.paidTotal, _refundCapBps(), BPS);
        if (refund > cap) revert RefundAboveCap(refund, cap);
        if (refund == 0 || total == 0) return;
        bool ok = _repayF1(total); // GAS-REPAY-SWAP: an ERC-20 quote by the swap (failed: nothing charged)
        if (!ok) return; // nothing charged: every part keeps what it held back
        uint256 walletCharges;
        for (uint256 x = 0; x < NUM_BUCKETS + n; x++) {
            uint256 c = charge[x];
            if (c == 0) continue;
            if (x < NUM_BUCKETS) {
                _buckets[x] -= c;
            } else {
                _walletAccrued[x - NUM_BUCKETS] -= c;
                walletCharges += c;
            }
        }
        if (walletCharges != 0) walletsTotal -= walletCharges; // once (see `_charges`)
        totalReimbursed += total;
        emit Reimbursed(msg.sender, total, units, price);
    }

    /// @dev Each part's charge for `refund`: its share of what the run paid out, at most what it held
    ///      back -- and never the whole of its slot, nor what would put the slot back on its start
    ///      value: a charge leaves at least 1 wei, and 1 wei off a start-value landing. The charges
    ///      run after the measurement, so a slot they cleared or restored would earn the transaction
    ///      a storage refund the repaid gas cannot see (audit TK21-E2 follow-up); this way they earn
    ///      none, at the cost of a wei or two a part left credited to it. Writes every entry of
    ///      `charge`; returns their sum.
    function _charges(Parts memory pt, uint256 n, uint256 refund, uint256[13] memory charge)
        internal
        pure
        returns (uint256 total)
    {
        for (uint256 x = 0; x < NUM_BUCKETS + n; x++) {
            uint256 c;
            if (refund != 0 && pt.paid[x] != 0 && pt.held[x] != 0) {
                c = FullMath.mulDiv(refund, pt.paid[x], pt.paidTotal);
                if (c > pt.held[x]) c = pt.held[x];
                uint256 f = pt.f[x];
                if (c >= f) c = f == 0 ? 0 : f - 1;
                if (c != 0 && f - c == pt.o[x]) c -= 1;
            }
            charge[x] = c;
            total += c;
        }
        // `walletsTotal` ends at its value less the wallets' charges: never zero (every charged wallet
        // keeps a wei), and never its start value -- 1 wei (2, if 1 would land that wallet on its own
        // start value) off the last charged wallet.
        uint256 wc;
        uint256 last;
        for (uint256 x = NUM_BUCKETS; x < NUM_BUCKETS + n; x++) {
            if (charge[x] != 0) {
                wc += charge[x];
                last = x;
            }
        }
        if (wc != 0 && pt.f[13] - wc == pt.o[13]) {
            uint256 k = pt.f[last] - charge[last] + 1 == pt.o[last] ? 2 : 1;
            if (k > charge[last]) k = charge[last];
            charge[last] -= k;
            total -= k;
        }
    }

    // ---------------------------------------------------------------- the storage refund (EIP-3529)
    //
    // Net gas metering (EIP-2200 with EIP-3529's values) refunds a slot, over a transaction, by its
    // value at the transaction's start (o) and at its end (f) alone, once it was changed in between:
    //   o != 0, f == 0: 4,800;   f == o != 0: 2,800;   f == o == 0 (set, then cleared): 19,900;   else 0.
    // Two exceptions to "the start and the end alone", both earning MORE than the rule says: a slot
    // set from zero and cleared twice earns 19,900 twice, and a slot restored to its start value and
    // then cleared earns 2,800 + 4,800. Neither happens to this vault's own slots within the
    // measurement (each moves one way after the allocation), and the charges after it touch no
    // slot's zero or start value (`_charges`). The owner's and the treasury's coin balances (22, 23)
    // do not move one way: a wallet with code can fill and empty them inside its push -- but a
    // pass-through then a clear needs at least two transfers there (13k+ gas), all of it deducted
    // with that push (`_push`), more than the 2,800 the rule leaves uncounted. Left uncounted, rare: the coin balance passing through its start
    // value and then emptied in one swap run (at most 2,800 over). `walletsTotal` is written once by
    // the pushes and once by the charges, and the charges keep it off zero and its start value.
    //
    // This vault reads o at the start of its execute: in the executor's transaction, one execute
    // alone, that IS the transaction's start. Several executes of one vault in ONE transaction are
    // counted as if each were its own; only the operator can send that (execute is the operator's,
    // the fallback is repaid nothing), so its effect is the operator's own.
    //
    // The slots an execute can clear or restore: its buckets, each wallet's accrual, `walletsTotal`,
    // `liquidityCoins`, its balance of the coin (one slot of the coin's ERC-20 storage), the coin's
    // allowance for the liquidity adder (zero at every transaction's start: set before each add and
    // cleared after it), and the fee pull's: the hook's `owed` for this pool, which `redeem` clears,
    // and its ERC-6909 claims in the pool manager, which the redeem's burn can empty; the splitter's
    // `unclaimedNative` for this vault and its `reservedNative`, which `claimNative` can clear. A
    // pull slot that cannot be read is counted as cleared (4,800): over-counted is under-repaid.
    // The owner's and the treasury's coin balances (filled before the pushes: forwarded coins, the
    // buy & hold) are counted too: a wallet with code that is, or is approved by, either could
    // empty them inside its push. Other slots the run fills before the pushes are not a recipient's
    // to clear (the dead address, the pool manager's, the hook's, the splitter's).
    //
    // A swap that crosses the launch position's range edge (a pool sold out to that edge) can clear
    // the pool's active liquidity, the edge tick's fee growth outside and the pool manager's coin
    // balance: those slots are counted too (24..29).
    // Every other slot it writes only grows (`_spent`, the totals, the holders' pots and budgets,
    // `deferred`, the adder's `liquidityOf`), or is a timestamp, or is transient (both reentrancy
    // guards, the adder's `_adding`, the pool manager's deltas).

    // REFUND_* and `_slotRefund` (virtual) are TokenomicsVaultV24Base's.

    /// @dev The slots, read into `s` (see `Parts.o`); a pull slot that cannot be read sets its bit.
    function _snap(Parts memory pt, uint256[30] memory s) internal view {
        uint256 n = walletCount;
        for (uint256 i = 0; i < NUM_BUCKETS; i++) {
            s[i] = _buckets[i];
        }
        for (uint256 w = 0; w < n; w++) {
            s[NUM_BUCKETS + w] = _walletAccrued[w];
        }
        s[13] = walletsTotal;
        s[14] = liquidityCoins;
        s[15] = IERC20(coin).balanceOf(address(this));
        PoolId id = _key().toId();
        address c = coin;
        address q = quote;
        _read(pt, s, 16, address(hook), abi.encodeWithSignature("owed(bytes32,address)", PoolId.unwrap(id), q));
        _read(pt, s, 17, address(hook), abi.encodeWithSignature("owed(bytes32,address)", PoolId.unwrap(id), c));
        _read(pt, s, 18, address(poolManager), abi.encodeWithSignature("balanceOf(address,uint256)", address(hook), uint256(uint160(q))));
        _read(pt, s, 19, address(poolManager), abi.encodeWithSignature("balanceOf(address,uint256)", address(hook), uint256(uint160(c))));
        if (q == address(0)) {
            _read(pt, s, 20, splitter, abi.encodeWithSignature("unclaimedNative(address)", address(this)));
            _read(pt, s, 21, splitter, abi.encodeWithSignature("reservedNative()"));
        } else {
            _read(pt, s, 20, splitter, abi.encodeWithSignature("unclaimedToken(address,address)", q, address(this)));
            _read(pt, s, 21, splitter, abi.encodeWithSignature("reservedToken(address)", q));
        }
        if (pt.ownerAt != address(0)) s[22] = IERC20(c).balanceOf(pt.ownerAt);
        if (pt.treasuryAt != address(0)) s[23] = IERC20(c).balanceOf(pt.treasuryAt);
        s[24] = StateLibrary.getLiquidity(poolManager, id);
        (s[25], s[26]) = StateLibrary.getTickFeeGrowthOutside(poolManager, id, tickLower);
        (s[27], s[28]) = StateLibrary.getTickFeeGrowthOutside(poolManager, id, tickUpper);
        s[29] = IERC20(c).balanceOf(address(poolManager));
    }

    /// @dev One pull slot, read by a gas-capped static call; unreadable: its bit in `pt.unreadable`.
    function _read(Parts memory pt, uint256[30] memory s, uint256 i, address target, bytes memory data) internal view {
        (bool ok, bytes memory ret) = target.staticcall{gas: READ_GAS}(data);
        if (ok && ret.length >= 32) s[i] = abi.decode(ret, (uint256));
        else pt.unreadable |= 1 << i;
    }

    uint256 internal constant READ_GAS = 30_000;

    /// @dev The start's snapshot, and the run's two flags reset (two executes in one transaction).
    function _snapStart(Parts memory pt) internal {
        address own = owner;
        address tre = treasury;
        if (own != address(this)) pt.ownerAt = own;
        if (tre == address(this)) {
            pt.treSlot = 15;
        } else if (tre == own) {
            pt.treSlot = 22;
        } else {
            pt.treSlot = 23;
            pt.treasuryAt = tre;
        }
        _snap(pt, pt.o);
        _coinsTaken = false;
        _adderApproved = false;
        _quoteApproved = false;
        _treasuryFilled = false;
    }

    /// @dev What the slots this run left cleared or restored earn back, at the end of the
    ///      measurement (`pt.f` is read here). A slot changed if its value moved at the allocation or
    ///      after it -- except the coin balance, which the swap can fill and empty back to the same
    ///      value (`_coinsTaken`). Plus the adder's allowance: set from zero and cleared, when an add
    ///      approved a non-zero amount (`_adderApproved`).
    function _clearsCredit(Parts memory pt) internal virtual returns (uint256 credit) {
        _snap(pt, pt.f);
        for (uint256 i = 0; i < 30; i++) {
            if (pt.unreadable & (1 << i) != 0) {
                credit += REFUND_CLEAR; // could not be read: counted as cleared
                continue;
            }
            // The coin balance and the treasury's can be filled and emptied back between the
            // allocation and the end (the swap; the buy & hold, then a wallet with code): flagged.
            // The pool manager's coin balance (29) can be taken from by the swap and settled back to
            // the same value by the add: flagged when either ran (over-counted only if neither wrote it).
            bool changed = pt.o[i] != pt.a[i] || pt.a[i] != pt.f[i] || (i == 15 && _coinsTaken)
                || (i == pt.treSlot && _treasuryFilled) || (i == 29 && (_coinsTaken || _adderApproved));
            credit += _slotRefund(pt.o[i], pt.f[i], changed);
        }
        if (_adderApproved) credit += REFUND_SET_CLEAR;
        if (_quoteApproved) credit += REFUND_SET_CLEAR; // v2.3: the adder's quote allowance, set and cleared
    }

    /// @dev TK-COOLDOWN3 (D1 ruling on AUD-D1C M-1): the impact cap per BLOCK. At the block's first look the cap's
    ///      base is the live price and the block's room is computed from it (v2.4's room) and recorded; every
    ///      execute in the block (any caller, the operator's too) then spends from what is left, and the next block
    ///      starts afresh: looped calls in one transaction cannot each move the price another cap from where the
    ///      previous one left it. A later call's room is also never more than what moves the LIVE price to the
    ///      block's limit (the swap's own price limit). A zero room skips the swap (`SwapSkipped`: `BlockRoomSpent`
    ///      after the block's first look, else v2.4's `NoRoomToSwap`); the buckets keep it all and stay due.
    /// @return limit The swap's price limit: the block's first price moved by the cap.
    /// @return room The gross quote this run may swap.
    /// @return left The block's room left before this run (room <= left).
    function _blockRoom(uint160 sqrtP, uint128 poolLiquidity, bool q0)
        internal
        returns (uint160 limit, uint256 room, uint256 left)
    {
        uint64 bn = uint64(arbitrum ? IArbSysF1(address(0x64)).arbBlockNumber() : block.number);
        bool fresh = _capBlock != bn || _capTime != uint64(block.timestamp);
        uint160 startP = fresh ? sqrtP : _capSqrtP;
        // TK-COOLDOWN: the factory admin's impact cap; 0 = the pool's fee (v2.4's cap).
        uint256 capBps = ITokenomicsFactoryV24F1Swap(factory).impactCapBps();
        limit = TokenomicsV23Math.limit(startP, capBps == 0 ? feeBps : capBps, q0);
        room = TokenomicsMath.grossForNet(TokenomicsV23Math.quoteToReach(sqrtP, limit, poolLiquidity, q0), feeBps)
            * ROOM_MARGIN_BPS / BPS;
        if (fresh) {
            if (room > type(uint128).max) room = type(uint128).max;
            left = room;
            _capBlock = bn;
            _capTime = uint64(block.timestamp);
            _capLeft = uint128(room);
            _capSqrtP = sqrtP;
        } else {
            left = _capLeft;
            if (room > left) room = left;
        }
        if (room == 0) {
            emit SwapSkipped(
                fresh
                    ? abi.encodeWithSelector(NoRoomToSwap.selector)
                    : abi.encodeWithSelector(BlockRoomSpent.selector, uint256(bn))
            );
        }
    }

    /// @dev v1's buy stage, unchanged but for the bucket names: one capped swap at the market price
    ///      for the three buying buckets, then burn, send to the treasury and add liquidity.
    function _buyStage(Run memory run, uint256 burnBudget, uint256 backBudget, uint256 liqBudget) internal {
        PoolKey memory key = _key();
        PoolId id = key.toId();
        (uint160 sqrtP,,,) = StateLibrary.getSlot0(poolManager, id);
        bool q0 = quoteIs0;
        // TK-COOLDOWN3 (D1 ruling, AUD-D1C M-1): the cap is per BLOCK (`_blockRoom`).
        uint128 poolLiquidity = StateLibrary.getLiquidity(poolManager, id);
        (uint160 limit, uint256 room, uint256 left) = _blockRoom(sqrtP, poolLiquidity, q0);
        if (room == 0) return;

        uint160 sqrtA = TickMath.getSqrtPriceAtTick(tickLower);
        uint160 sqrtB = TickMath.getSqrtPriceAtTick(tickUpper);
        uint256 liqSwap;
        if (liqBudget != 0) {
            uint256 first =
                burnBudget + backBudget + FullMath.mulDiv(liqBudget, TokenomicsV23Math.coinShare(sqrtP, sqrtA, sqrtB, q0), 1e18);
            if (first > room) first = room;
            uint160 ends = first == 0
                ? sqrtP
                : TokenomicsV23Math.priceAfter(sqrtP, poolLiquidity, first - (first * feeBps) / BPS, q0);
            uint256 heldValue = TokenomicsV23Math.quoteValue(liquidityCoins, ends, q0);
            uint256 coinTarget =
                FullMath.mulDiv(liqBudget + heldValue, TokenomicsV23Math.coinShare(ends, sqrtA, sqrtB, q0), 1e18);
            liqSwap = coinTarget > heldValue ? coinTarget - heldValue : 0;
            if (liqSwap > liqBudget) liqSwap = liqBudget;
        }
        uint256 liqKeep = liqBudget - liqSwap;

        uint256 want = burnBudget + backBudget + liqSwap;
        if (want == 0) {
            if (liqBudget != 0 && liquidityCoins != 0) {
                uint256 held = liquidityCoins;
                (uint256 nativeIn, uint256 coinIn) = _addLiquidity(key, id, sqrtA, sqrtB, liqBudget, held);
                run.spend[LIQUIDITY] = nativeIn;
                liquidityCoins = held - coinIn;
                if (nativeIn != 0 || coinIn != 0) lastSwap = uint64(block.timestamp);
            }
            return;
        }
        if (want > room) {
            burnBudget = FullMath.mulDiv(burnBudget, room, want);
            backBudget = FullMath.mulDiv(backBudget, room, want);
            liqSwap = FullMath.mulDiv(liqSwap, room, want);
            liqKeep = FullMath.mulDiv(liqKeep, room, want);
        }
        uint256 gross = burnBudget + backBudget + liqSwap;
        if (gross == 0) return;
        // TK-COOLDOWN3: what this run takes of the block's room -- all of it when the buckets wanted more (the
        // scaling's rounding leaves no wei-sized room for a looped call), else what it swaps.
        want = want > room ? room : gross;

        uint256 coins;
        try this.swapFromSelf(gross, limit) returns (uint256 out) {
            coins = out;
        } catch (bytes memory reason) {
            emit SwapSkipped(reason);
            return;
        }
        lastSwap = uint64(block.timestamp);
        _capLeft = uint128(left - want); // TK-COOLDOWN3: this block's room taken (want <= room <= left < 2^128)
        if (coins != 0) _coinsTaken = true;
        {
            (uint160 sqrtAfter,,,) = StateLibrary.getSlot0(poolManager, id);
            emit Swapped(gross, coins, sqrtP, sqrtAfter);
        }

        uint256 coinsBurn = FullMath.mulDiv(coins, burnBudget, gross);
        uint256 coinsBack = FullMath.mulDiv(coins, backBudget, gross);
        uint256 coinsLiq = FullMath.mulDiv(coins, liqSwap, gross);
        {
            uint256 dust = coins - coinsBurn - coinsBack - coinsLiq;
            if (burnBudget != 0) coinsBurn += dust;
            else if (backBudget != 0) coinsBack += dust;
            else coinsLiq += dust;
        }

        run.spend[BURN] = burnBudget;
        run.spend[BUY_HOLD] = backBudget;
        run.spend[LIQUIDITY] = liqSwap;

        if (coinsBack != 0) {
            IERC20(coin).safeTransfer(treasury, coinsBack);
            _treasuryFilled = true;
            run.coinsToTreasury = coinsBack;
            emit SentToTreasury(treasury, coinsBack);
        }
        if (liqBudget != 0) {
            uint256 forAdd = coinsLiq + liquidityCoins;
            if (forAdd != 0) {
                (uint256 nativeIn, uint256 coinIn) = _addLiquidity(key, id, sqrtA, sqrtB, liqKeep, forAdd);
                run.spend[LIQUIDITY] += nativeIn;
                liquidityCoins = forAdd - coinIn;
            }
        }
        if (coinsBurn != 0) {
            IERC20(coin).safeTransfer(DEAD, coinsBurn);
            run.coinsBurned = coinsBurn;
            emit Burned(coinsBurn);
        }
    }

    function _addLiquidity(
        PoolKey memory key,
        PoolId id,
        uint160 sqrtA,
        uint160 sqrtB,
        uint256 nativeAmt,
        uint256 coinAmt
    ) internal returns (uint256 nativeIn, uint256 coinIn) {
        (uint160 sqrtP,,,) = StateLibrary.getSlot0(poolManager, id);
        bool q0 = quoteIs0;
        address q = quote;
        uint128 l = TokenomicsV23Math.liquidityFor(sqrtP, sqrtA, sqrtB, nativeAmt, coinAmt, q0);
        l = uint128(FullMath.mulDiv(l, LIQUIDITY_MARGIN_BPS, BPS));
        if (l == 0) {
            emit LiquiditySkipped("");
            return (0, 0);
        }
        IERC20(coin).forceApprove(address(liquidityAdder), coinAmt);
        if (coinAmt != 0) _adderApproved = true;
        uint256 value = nativeAmt;
        if (q != address(0)) {
            // v2.3: an ERC-20 quote is approved, as the coin is, and cleared after.
            value = 0;
            IERC20(q).forceApprove(address(liquidityAdder), nativeAmt);
            if (nativeAmt != 0) _quoteApproved = true;
        }
        try liquidityAdder.add{value: value}(key, tickLower, tickUpper, l, q0) returns (uint256 n, uint256 c) {
            (nativeIn, coinIn) = (n, c);
            emit LiquidityAdded(l, n, c);
        } catch (bytes memory reason) {
            emit LiquiditySkipped(reason);
        }
        IERC20(coin).forceApprove(address(liquidityAdder), 0);
        if (q != address(0)) IERC20(q).forceApprove(address(liquidityAdder), 0);
    }

    /// @notice The swap itself: callable only by this vault, from `execute`'s try/catch.
    function swapFromSelf(uint256 amountIn, uint160 limit) external returns (uint256 coins) {
        if (msg.sender != address(this)) revert NotSelf();
        _swapping = true;
        coins = abi.decode(poolManager.unlock(abi.encode(amountIn, limit)), (uint256));
        _swapping = false;
    }

    /// @inheritdoc IUnlockCallback
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != address(poolManager) || !_swapping) revert NotPoolManager();
        (uint256 amountIn, uint160 limit) = abi.decode(data, (uint256, uint160));
        PoolKey memory key = _key();
        bool q0 = quoteIs0;
        BalanceDelta d = poolManager.swap(
            key,
            SwapParams({
                zeroForOne: q0,
                amountSpecified: -int256(amountIn),
                sqrtPriceLimitX96: q0 ? TickMath.MIN_SQRT_PRICE + 1 : TickMath.MAX_SQRT_PRICE - 1
            }),
            ""
        );
        (uint160 sqrtAfter,,,) = StateLibrary.getSlot0(poolManager, key.toId());
        if (q0 ? sqrtAfter < limit : sqrtAfter > limit) revert PriceMovedTooFar(sqrtAfter, limit);
        int128 coinDelta = q0 ? d.amount1() : d.amount0();
        if (coinDelta <= 0) revert NothingBought();
        uint256 paid = uint256(uint128(-(q0 ? d.amount0() : d.amount1())));
        if (paid != amountIn) revert WrongAmountPaid(paid, amountIn);
        address q = quote;
        poolManager.sync(Currency.wrap(q));
        if (q == address(0)) {
            poolManager.settle{value: paid}();
        } else {
            IERC20(q).safeTransfer(address(poolManager), paid);
            poolManager.settle();
        }
        uint256 coins = uint256(uint128(coinDelta));
        poolManager.take(q0 ? key.currency1 : key.currency0, address(this), coins);
        return abi.encode(coins);
    }

}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@layerzerolabs/oft-evm/=lib/layerzero/oft-evm/",
    "@layerzerolabs/oapp-evm/=lib/layerzero/oapp-evm/",
    "@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero/protocol-v2/",
    "@uniswap/v4-core/=lib/uniswap-v4-core/",
    "solmate/=lib/solmate/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "layerzero/=lib/layerzero/",
    "uniswap-v4-core/=lib/uniswap-v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.