Skip to content
Verified contractExactUNLICENSED

TokenomicsVaultV23BurnModule

Address0xd114ef71b97e7df568a9be4f240f98779f8ed97e
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
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,330,575
Creation transaction
0x0dc92a4a17…69f8119ff6

78 files

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

src/tokenomics/v23/TokenomicsVaultV23BurnModule.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 {IRewardSwapperV23, ITokenomicsFactoryV23Roles} from "./ITokenomicsV23.sol";

import {TokenomicsChainParams} from "../ITokenomics.sol";
import {WalletView, RewardView} from "../v2/ITokenomicsV2.sol";
import {IRewardSwapperV22, TokenomicsV22Gas, BurnTargetView, LegViewV22} from "../v22/ITokenomicsV22.sol";
import {TokenomicsVaultV23Base} from "./TokenomicsVaultV23Base.sol";

/// @title TokenomicsVaultV23BurnModule (version 2.3: v2.2's, with `buyBurn` spending the pool's
///        quote -- native, or a listed ERC-20 through the swapper's `swapIn` -- and a burn target that
///        is the quote itself treated as one that is the coin: never bought, rollable at once.)
/// v2.2: TokenomicsVaultV22BurnModule (version 2.2)
/// @notice The BURN TOKENS bucket's functions (docs/tokenomics-v22-spec.md sections 3-6), run by
///         DELEGATECALL on the vault's storage: the implementation's `fallback` reaches
///         TokenomicsVaultV23Module, whose own `fallback` reaches this. Never a vault itself.
///
/// BUY & BURN. The OPERATOR buys a target with `buyBurn` through the chain's V22 swapper, which
/// sends what it bought straight to the dead address: the vault never holds a target token. The
/// vault checks the dead address's balance rose by at least `minOut` (post-fee: a fee-on-transfer
/// token is measured by what arrived). A route or token that reverts -- a honeypot, a blocklist, a
/// hook -- reverts the whole buy and nothing is spent.
///
/// THE TARGETS ARE THE ADMIN'S AFTER LAUNCH. The creator chose them in the config (its hash commits
/// to them); nobody but the platform admin (`factory.admin()`) can change or disable one
/// (`setBurnTarget`), and a change keeps the slot's bucket.
///
/// THE ROLLOVER IS ANYONE'S. A target not bought for 30 days, a disabled one, or one that turns out
/// to be the coin itself, can be rolled by anyone into the own-coin BURN bucket (`rollBurnTarget`).
contract TokenomicsVaultV23BurnModule is TokenomicsVaultV23Base {
    using SafeERC20 for IERC20;

    constructor(TokenomicsChainParams memory p, address liquidityAdder_, address swapper_, TokenomicsV22Gas memory g)
        TokenomicsVaultV23Base(p, liquidityAdder_, swapper_, g)
    {}

    // ------------------------------------------------------------------------------ buy & burn

    /// @notice Buy burn target `j` with `amountIn` of its bucket and send it all to the dead
    ///         address. The OPERATOR only. Pulls and allocates first. `target` and `data` are the
    ///         route the swapper calls (never one of this vault's own contracts: `BadTarget`). The
    ///         dead address's balance of the token must rise by at least `minOut`. Native the
    ///         swapper hands back returns to the bucket (at most `amountIn`).
    ///         The operator is repaid its measured gas plus `gasOverheadBurn` and its arguments' calldata
    ///         gas (`_routeDataGas`: the head and the route data), less the pull's whole
    ///         gas, the whole gas of every call into the token and the swapper, and the bucket's
    ///         storage refund (at most a fifth), at the capped price, times (1 + `refundMarginBps`),
    ///         from this target's bucket -- and the call REVERTS above `refundCapBps` of the native the
    ///         route kept (`RefundAboveCap`); with `refundCapBps` 0 it is repaid nothing instead. Leave
    ///         the repay's room in the bucket (amountIn below the bucket): the charge is at most what
    ///         the bucket holds after the buy, less a wei.
    function buyBurn(uint8 j, uint256 amountIn, uint256 minOut, address target, bytes calldata data)
        external
        nonReentrant
    {
        uint256 gasStart = gasleft();
        if (msg.sender != _operator()) revert NotOperator();
        if (j >= burnCount) revert BadIndex();
        if (burnDisabled & (1 << j) != 0) revert BurnTargetDisabled(j);
        address token = _burnTokens[j];
        if (token == coin) revert BurnTargetIsCoin(j);
        if (token == quote && token != address(0)) revert BurnTargetIsQuote(j);
        Src memory sb = Src(_burnBucket[j], 0);
        uint256 credit = _syncMeasured();
        uint256 bucket = _burnBucket[j];
        if (amountIn == 0 || amountIn > bucket) revert OverBudget(amountIn, bucket);
        if (minOut == 0) revert MinOutZero();
        _checkTarget(target);

        _burnBucket[j] = bucket - amountIn;
        uint256 refund;
        uint256 rise;
        {
            // Credited whole: EVERY call into the token (both balance reads, which can warm its slots)
            // and the swapper call (the route and the token's transfer, which can clear them) --
            // audit v2.2 round 1 Low-1: no token or route code runs outside the credited window.
            uint256 g = gasleft();
            uint256 deadBefore = IERC20(token).balanceOf(DEAD);
            address q = quote;
            if (q == address(0)) {
                (, refund) = IRewardSwapperV22(swapper).swapTo{value: amountIn}(token, target, data, DEAD);
            } else {
                IERC20(q).safeTransfer(swapper, amountIn);
                (, refund) = IRewardSwapperV23(swapper).swapIn(q, amountIn, token, target, data, DEAD);
            }
            uint256 deadAfter = IERC20(token).balanceOf(DEAD);
            credit += g - gasleft();
            rise = deadAfter > deadBefore ? deadAfter - deadBefore : 0;
        }
        if (rise < minOut) revert TooLittleOut(rise, minOut);
        if (refund > amountIn) refund = amountIn;
        sb.f = bucket - amountIn + refund;
        _burnBucket[j] = sb.f;
        uint256 spent = amountIn - refund;
        _burnSpent[j] += spent;
        _burnBought[j] += rise;
        _burnLastBuy[j] = uint40(block.timestamp);
        emit BurnTokensBought(j, token, spent, rise);
        (uint256 charge, uint256 units, uint256 price) =
            _buyRefund(gasStart, gasOverheadBurn + _routeDataGas(), credit, spent, sb, Src(0, type(uint256).max));
        if (_payOperator(charge, units, price)) _burnBucket[j] = sb.f - charge;
    }

    // --------------------------------------------------------------- the admin's target setter

    /// @notice ADMIN: set burn target `j` to `token`, enabled or disabled. Only an existing slot
    ///         (`j < burnCount`: the shares are fixed by the config hash). The token: not zero, not
    ///         the native placeholder, not the coin, not this vault, not another slot's token. The
    ///         slot's bucket, spent and bought totals are KEPT (the new token is bought with the same
    ///         bucket). A changed token, or a re-enable, restarts the slot's 30-day rollover clock. A
    ///         disabled slot is still credited by every allocation and can be rolled by anyone.
    function setBurnTarget(uint8 j, address token, bool enabled) external nonReentrant {
        if (msg.sender != _admin()) revert NotAdmin();
        uint256 n = burnCount;
        if (j >= n) revert BadIndex();
        if (
            token == address(0) || token == NATIVE_PLACEHOLDER || token == coin || token == address(this)
                || token == quote
        ) {
            revert BadBurnToken(token);
        }
        for (uint256 k = 0; k < n; k++) {
            if (k != j && _burnTokens[k] == token) revert BadBurnToken(token);
        }
        address prev = _burnTokens[j];
        uint8 bit = uint8(1 << j);
        bool wasEnabled = burnDisabled & bit == 0;
        _burnTokens[j] = token;
        if (enabled) {
            burnDisabled &= ~bit;
            if (token != prev || !wasEnabled) _burnLastBuy[j] = uint40(block.timestamp);
        } else {
            burnDisabled |= bit;
        }
        emit BurnTargetSet(j, prev, token, enabled);
    }

    // ------------------------------------------------------------------------------- rollover

    /// @notice Move burn target `j`'s whole bucket into the own-coin BURN bucket. ANYONE, once the
    ///         target has gone 30 days without a buy (from the bind, its last buy or the admin's last
    ///         change), at once when it is disabled or is the coin itself. Repaid nothing (the
    ///         operator's repaid path is `rollBurnTargetRepaid`; this one is the fallback).
    function rollBurnTarget(uint8 j) external nonReentrant {
        _roll(j);
    }

    /// @notice The OPERATOR's rollover: the same roll, under the same conditions, repaid its measured
    ///         gas plus `gasOverheadRoll` (less the bucket's storage refund: the roll clears it), at
    ///         the capped price, times (1 + `refundMarginBps`), out of the rolled amount -- the own-coin
    ///         BURN bucket gets the rest. Above `refundCapBps` of the rolled amount it REVERTS
    ///         (`RefundAboveCap`): the bucket waits for more fees, or for anyone's unrepaid roll. With
    ///         `refundCapBps` 0 it rolls the whole amount, repaid nothing.
    ///         The charge never clears the BURN bucket nor puts it back on its start value.
    function rollBurnTargetRepaid(uint8 j) external nonReentrant {
        uint256 gasStart = gasleft();
        if (msg.sender != _operator()) revert NotOperator();
        uint256 b0 = _buckets[BURN];
        uint256 amount = _roll(j);
        // The bucket went from `amount` (its value at the transaction's start: nothing earlier in this
        // call wrote it) to zero: its EIP-3529 refund is counted. The BURN bucket only grew.
        Src memory sb = Src(b0, b0 + amount);
        (uint256 charge, uint256 units, uint256 price) = _buyRefund(
            gasStart, gasOverheadRoll, _slotRefund(amount, 0, true), amount, sb, Src(0, type(uint256).max)
        );
        if (_payOperator(charge, units, price)) _buckets[BURN] = sb.f - charge;
    }

    /// @dev The roll itself: the conditions, the move, the event. Returns the amount rolled.
    function _roll(uint8 j) internal returns (uint256 amount) {
        if (j >= burnCount) revert BadIndex();
        address token = _burnTokens[j];
        uint256 notBefore = uint256(_burnLastBuy[j]) + BURN_ROLL_AFTER;
        if (burnDisabled & (1 << j) == 0 && token != coin && !_isQuote(token) && block.timestamp < notBefore) {
            revert NotRollable(j, notBefore);
        }
        amount = _burnBucket[j];
        if (amount == 0) revert NothingToRoll();
        _burnBucket[j] = 0;
        _buckets[BURN] += amount;
        totalBurnRolled += amount;
        emit BurnRolledToOwnBurn(j, token, amount);
    }

    /// @dev v2.3: a stock vault's quote (never true in a native vault).
    function _isQuote(address token) internal view returns (bool) {
        return token == quote && token != address(0);
    }

    function _rollable(uint256 j) internal view returns (bool) {
        return burnDisabled & (1 << j) != 0 || _burnTokens[j] == coin || _isQuote(_burnTokens[j])
            || block.timestamp >= uint256(_burnLastBuy[j]) + BURN_ROLL_AFTER;
    }

    // ---------------------------------------------------------------------------------- reads

    function leg() external view returns (LegViewV22 memory v) {
        v.burnBps = _bps[0];
        v.buyHoldBps = _bps[1];
        v.liquidityBps = _bps[2];
        v.holdersBps = _bps[3];
        v.burnTargetsBps = burnTargetsBps;
        v.treasury = treasury;
        v.pendingTreasury = pendingTreasury;
        uint256 n = walletCount;
        v.wallets = new WalletView[](n);
        for (uint256 i = 0; i < n; i++) {
            v.wallets[i] = WalletView(_wallets[i], _pendingWallets[i], _walletBps[i], _walletAccrued[i]);
        }
        n = rewardCount;
        v.rewards = new RewardView[](n);
        for (uint256 i = 0; i < n; i++) {
            v.rewards[i] = RewardView(_rewardTokens[i], _rewardBps[i], _pot[i], _budget[i], _paidTotal[i]);
        }
        n = burnCount;
        v.burnTargets = new BurnTargetView[](n);
        for (uint256 i = 0; i < n; i++) {
            v.burnTargets[i] = BurnTargetView(
                _burnTokens[i],
                _burnTokenBps[i],
                burnDisabled & (1 << i) == 0,
                _burnBucket[i],
                _burnSpent[i],
                _burnBought[i],
                _burnLastBuy[i]
            );
        }
    }

    /// @notice What `execute` would spend now (before any pull) -- BURN, BUY_HOLD, LIQUIDITY,
    ///         WALLETS, as v2.1 -- then per burn target whether `buyBurn` may buy it (enabled, not the
    ///         coin, its bucket above dust and the minimum) and whether `rollBurnTarget` may roll it.
    function due() external view returns (bool[4] memory out, bool[5] memory burnBuy, bool[5] memory burnRoll) {
        uint256 m = _minExecuteWei();
        for (uint256 i = 0; i < NUM_BUCKETS; i++) {
            out[i] = _buckets[i] > DUST && _buckets[i] >= m;
        }
        if (walletsTotal != 0 && walletsTotal >= m) {
            uint256 n = walletCount;
            for (uint256 w = 0; w < n; w++) {
                if (_walletAccrued[w] > DUST) {
                    out[3] = true;
                    break;
                }
            }
        }
        uint256 nb = burnCount;
        for (uint256 j = 0; j < nb; j++) {
            uint256 b = _burnBucket[j];
            burnBuy[j] = burnDisabled & (1 << j) == 0 && _burnTokens[j] != coin && !_isQuote(_burnTokens[j]) && b > DUST
                && b >= m;
            burnRoll[j] = b != 0 && _rollable(j);
        }
    }

    /// @notice The rest of the books, for the coin page and the executor: v2.1's nine values,
    ///         unchanged (the burn targets' are `burnBooks`).
    function books()
        external
        view
        returns (
            uint256 walletsTotal_,
            uint256 holdersNative_,
            uint256 ownerRefund_,
            uint256 totalDeferred_,
            uint256 liquidityCoins_,
            uint256 totalReceived_,
            uint256 totalCoinBurned_,
            uint256 totalCoinToTreasury_,
            uint256 totalReimbursed_
        )
    {
        return (
            walletsTotal,
            holdersNative,
            ownerRefund,
            totalDeferred,
            liquidityCoins,
            totalReceived,
            totalCoinBurned,
            totalCoinToTreasury,
            totalReimbursed
        );
    }

    /// @notice v2.2's books: the burn targets' buckets summed (native the vault holds for them), the
    ///         native spent buying them, and the native rolled into the own-coin burn, in total.
    function burnBooks() external view returns (uint256 held, uint256 spent_, uint256 rolled) {
        uint256 n = burnCount;
        for (uint256 j = 0; j < n; j++) {
            spent_ += _burnSpent[j];
        }
        return (_burnHeld(), spent_, totalBurnRolled);
    }

    function burnBuckets() external view returns (uint256[5] memory) {
        return _burnBucket;
    }

    // ------------------------------------------- v2.3: reads moved from the module (EIP-170)

    function paidOf(uint8 i, address holder) external view returns (uint256) {
        return _paid[i][holder];
    }

    function eligibility() external view returns (uint16, uint8, uint32) {
        return (minHolderBps, selectMode, selectCount);
    }

    function operator() external view returns (address) {
        return _operator();
    }

    function admin() external view returns (address) {
        return _admin();
    }

    function unallocated() external view returns (uint256) {
        return _unallocated();
    }

    function buckets() external view returns (uint256[3] memory) {
        return _buckets;
    }

    function spent() external view returns (uint256[3] memory) {
        return _spent;
    }

    /// @notice The vault's launch and roles, in one read.
    function info()
        external
        view
        returns (
            bytes32 launchId_,
            address owner_,
            address pendingOwner_,
            address launchCreator_,
            address coin_,
            address splitter_,
            address launchFactory_,
            uint64 createdAt_,
            uint64 lastSwap_
        )
    {
        return (launchId, owner, pendingOwner, launchCreator, coin, splitter, launchFactory, createdAt, lastSwap);
    }

    function deferredOf(address a) external view returns (uint256) {
        return deferred[a];
    }

    /// @notice The chain wiring this vault runs with.
    function wiring()
        external
        view
        returns (
            address factory_,
            address poolManager_,
            address hook_,
            address locker_,
            address collector_,
            address liquidityAdder_,
            address swapper_,
            uint32 localEid_,
            uint256 minExecuteWei_
        )
    {
        return (
            factory,
            address(poolManager),
            address(hook),
            locker,
            collector,
            address(liquidityAdder),
            swapper,
            localEid,
            _minExecuteWei()
        );
    }

    /// @notice v2.1: who may run `execute` now -- the operator always; anyone (unrepaid) from
    ///         `fallbackOpensAt` -- and when the operator last ran it.
    function executeGate() external view returns (address operator_, uint40 lastOperatorRun_, uint256 fallbackOpensAt) {
        ITokenomicsFactoryV23Roles f = ITokenomicsFactoryV23Roles(factory);
        return (f.operator(), lastOperatorRun, uint256(lastOperatorRun) + f.fallbackDelay());
    }

    /// @notice The pool's position range and fee, as bound.
    function pool() external view returns (uint16 feeBps_, int24 tickSpacing_, int24 tickLower_, int24 tickUpper_) {
        return (feeBps, tickSpacing, tickLower, tickUpper);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero/protocol-v2/",
    "@layerzerolabs/oapp-evm/=lib/layerzero/oapp-evm/",
    "@layerzerolabs/oft-evm/=lib/layerzero/oft-evm/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@uniswap/v4-core/=lib/uniswap-v4-core/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "layerzero/=lib/layerzero/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/solmate/",
    "uniswap-v4-core/=lib/uniswap-v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.