Skip to content
Verified contractPartialMIT

DarkPool

Address0x37b1336d4a36fac89479f3bcfe0ff1903240a5f0
Balance

1.989615 ETH

 

Transactions

191

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,320,788
Creation transaction
0xe07e34174a…ca42ac6832

contracts/DarkPool.sol

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

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./DailyDynamicExitTax.sol";

// Interface for SolvencyScript NFT contract
interface IERC721Balance {
    function balanceOf(address owner) external view returns (uint256);
}

// Interface for staking contract to check if user has staked NFTs
interface IStakingContract {
    function getUserStakedTokens(address user) external view returns (uint256[] memory);
}

/// @notice Custom errors
error NotPourAuthorized();
error ZeroAmount();
error ETHTransferFailed();
error AlreadyMinted();
error RecipientMustOwnNFT();
error OnlyNFTContract();
error NoSupply();

/**
 * @title DarkPool
 * @notice ERC20 token - transfers only allowed to wallets that own a SolvencyScript NFT
 * @dev Total supply: 10,000,000,000 tokens (1,000,000 per NFT * 10,000 NFTs)
 * @dev Exit tax applied on redeem; tax defends remaining monthly cycle reserve
 * @dev Key addresses (NFT contract, staking contract) are exempt from NFT requirement
 */
contract DarkPool is ERC20, DailyDynamicExitTax, ReentrancyGuard {
    /* ========== STATE VARIABLES ========== */

    uint256 public constant TOTAL_SUPPLY = 10_000_000_000 * 1e18; // 10 billion tokens

    bool public minted;
    address public nftContract; // SolvencyScript NFT contract - check balanceOf for ownership
    address public stakingContract; // Staking contract - check getUserStakedTokens for staked NFTs

    // Addresses exempt from NFT requirement (can receive without owning NFT)
    mapping(address => bool) public isExemptFromNFTRequirement;

    // Addresses authorized to call pour() - only these can start new cycles
    mapping(address => bool) public isPourAuthorized;

    /* ========== EVENTS ========== */

    event NFTContractUpdated(address indexed oldContract, address indexed newContract);
    event StakingContractUpdated(address indexed oldContract, address indexed newContract);
    event NFTRequirementExemptionUpdated(address indexed account, bool exempt);
    event Poured(address indexed from, uint256 amount, uint256 timestamp);
    event PourAuthorizedUpdated(address indexed account, bool authorized);

    /* ========== CONSTRUCTOR ========== */

    constructor() ERC20("Pink Sheet Apes", "PINK") DailyDynamicExitTax(msg.sender) {
        // Owner is exempt from NFT requirement
        isExemptFromNFTRequirement[msg.sender] = true;
        // Contract itself is exempt (receives tokens on redeem)
        isExemptFromNFTRequirement[address(this)] = true;
    }

    /* ========== POUR ========== */

    /**
     * @notice Pour ETH into the contract and start a new monthly cycle
     * @dev Only callable by addresses in isPourAuthorized
     * @dev This is the ONLY way to start a new cycle - owner cannot call startNewCycle directly
     */
    function pour() external payable {
        if (!isPourAuthorized[msg.sender]) revert NotPourAuthorized();
        if (msg.value == 0) revert ZeroAmount();

        _startNewCycle(msg.value);
        emit Poured(msg.sender, msg.value, block.timestamp);
    }

    /**
     * @notice Set pour authorization for an address
     * @param account Address to update
     * @param authorized Whether the address can call pour()
     */
    function setPourAuthorized(address account, bool authorized) external onlyOwner {
        if (account == address(0)) revert InvalidAddress();
        isPourAuthorized[account] = authorized;
        emit PourAuthorizedUpdated(account, authorized);
    }

    /* ========== MINTING ========== */

    /**
     * @notice Mint entire supply to NFT contract (one-time only)
     * @param nftContractAddress Address of the NFT contract that will hold all tokens
     */
    function mintToNFTContract(address nftContractAddress) external onlyOwner {
        if (minted) revert AlreadyMinted();
        if (nftContractAddress == address(0)) revert InvalidAddress();

        minted = true;

        // NFT contract is exempt (holds locked tokens)
        isExemptFromNFTRequirement[nftContractAddress] = true;

        _mint(nftContractAddress, TOTAL_SUPPLY);
    }

    /* ========== TRANSFER LOGIC ========== */

    /**
     * @dev Override _update to enforce NFT requirement for recipients
     * @dev Recipients must own at least 1 SolvencyScript NFT (in wallet or staked) unless exempt
     */
    function _update(address from, address to, uint256 amount) internal virtual override {
        // Skip NFT requirement check on mints, burns, or if recipient is exempt
        if (from != address(0) && to != address(0) && !isExemptFromNFTRequirement[to]) {
            if (!_hasNFT(to)) revert RecipientMustOwnNFT();
        }

        super._update(from, to, amount);
    }

    /**
     * @dev Check if a user owns at least 1 SolvencyScript NFT (in wallet or staked)
     * @param user Address to check
     * @return True if user has at least 1 NFT
     */
    function _hasNFT(address user) internal view returns (bool) {
        // Check balance in wallet (NFTs not staked)
        if (nftContract != address(0)) {
            try IERC721Balance(nftContract).balanceOf(user) returns (uint256 balance) {
                if (balance > 0) return true;
            } catch { /* ignore */ }
        }

        // Check staked NFTs
        if (stakingContract != address(0)) {
            try IStakingContract(stakingContract).getUserStakedTokens(user) returns (uint256[] memory stakedTokens) {
                if (stakedTokens.length > 0) return true;
            } catch { /* ignore */ }
        }

        return false;
    }

    /* ========== ADMIN FUNCTIONS ========== */

    /**
     * @notice Set the SolvencyScript NFT contract address
     * @param _nftContract Address of the SolvencyScript NFT contract
     */
    function setNFTContract(address _nftContract) external onlyOwner {
        address oldContract = nftContract;
        nftContract = _nftContract;

        if (_nftContract != address(0)) {
            isExemptFromNFTRequirement[_nftContract] = true;
        }

        emit NFTContractUpdated(oldContract, _nftContract);
    }

    /**
     * @notice Set the staking contract address (BananaVault)
     * @param _stakingContract Address of the NFT staking contract
     * @dev Also sets taxRecipient so exit tax routes to BananaVault
     */
    function setStakingContract(address _stakingContract) external onlyOwner {
        address oldContract = stakingContract;
        stakingContract = _stakingContract;

        if (_stakingContract != address(0)) {
            isExemptFromNFTRequirement[_stakingContract] = true;
            // PSA V1 immutable-core: taxRecipient is one-way settable. Only
            // the FIRST non-zero set of taxRecipient (here OR via
            // setTaxRecipient) ever writes to it; subsequent
            // setStakingContract calls leave it permanently locked. This
            // prevents the exit tax from being silently re-routed away from
            // the BananaVault sink.
            if (taxRecipient == address(0)) {
                taxRecipient = _stakingContract;
                emit TaxRecipientUpdated(address(0), _stakingContract);
            }
        }

        emit StakingContractUpdated(oldContract, _stakingContract);
    }

    /**
     * @notice Set NFT requirement exemption status for address(es)
     * @param accounts Array of addresses to update (use [addr] for single)
     * @param exempt Whether the addresses should be exempt from NFT requirement
     */
    function setNFTRequirementExemption(address[] calldata accounts, bool exempt) external onlyOwner {
        for (uint256 i = 0; i < accounts.length; i++) {
            if (accounts[i] == address(0)) revert InvalidAddress();
            isExemptFromNFTRequirement[accounts[i]] = exempt;
            emit NFTRequirementExemptionUpdated(accounts[i], exempt);
        }
    }

    /**
     * @notice Receive ETH directly sent to the contract
     * @dev Allows the contract to accept ETH transfers (e.g. from mints)
     */
    receive() external payable {
        // ETH is accepted and stored in the contract
    }

    /* ========== REDEEM (with health-based tax) ========== */

    /**
     * @notice Redeem DarkPool tokens for ETH (callable only by NFT contract).
     *
     * Pricing: batch curve  grossEthOut = q * L0 / (B + q/2)
     *   - q  = tokenAmount
     *   - L0 = ETH balance snapshotted at the top of this call
     *   - B  = pricingBase (lockToken balance of SolvencyScript, passed from caller)
     *
     * Tax: three-factor health model (see DailyDynamicExitTax).
     *   P_last and S_eff are supplied by the user as a Merkle proof verified here.
     *   H_liq is always computed on-chain from L0.
     *
     * @param tokenAmount      Amount of PINK tokens to redeem (already sent to this contract)
     * @param ethRecipient     Address to receive net ETH
     * @param pricingBase      B — total PINK indexed in SolvencyScript (lockToken.balanceOf(solvencyScript))
     * @param pLastWei         Productive value from health snapshot (H_prod input)
     * @param sEffWei          Solvency support from health snapshot (H_solv input)
     * @param snapshotId       Monotonically increasing snapshot identifier
     * @param snapshotTimestamp Unix timestamp when the snapshot was computed off-chain
     * @param proof            Merkle proof for the health snapshot leaf
     */
    function redeem(
        uint256 tokenAmount,
        address ethRecipient,
        uint256 pricingBase,
        uint256 pLastWei,
        uint256 sEffWei,
        uint256 snapshotId,
        uint256 snapshotTimestamp,
        bytes32[] calldata proof
    ) external nonReentrant {
        // PSA V1 immutable-core: redemption has no pause gate. Core mechanics
        // cannot be turned off; only access (caller must be NFT contract) and
        // input validity are enforced.
        if (msg.sender != nftContract) revert OnlyNFTContract();
        if (tokenAmount == 0) revert ZeroAmount();
        if (ethRecipient == address(0)) revert InvalidAddress();
        if (pricingBase == 0) revert ZeroAmount();

        // ── PSA V1 redemption-state ordering ────────────────────────────────
        // Spec: snapshot quote-time values ONCE → compute gross → compute
        // tax/net → transfer PINK to NFT contract → pay net ETH → update
        // extraction state → refresh liquidity/solvency → recompute health →
        // re-index returned tokens. Snapshot must be stable mid-execution and
        // every later redemption in the same cycle MUST see a strictly weaker
        // state.

        // 1. Snapshot L0 (effectiveLiquidityEth) ONCE before any state change.
        //    pricingBase B and (pLastWei, sEffWei) are caller / Merkle inputs
        //    captured at the same logical instant.
        uint256 L0 = address(this).balance;
        if (L0 == 0) revert NoSupply();

        // 2. Batch curve gross price: q * L0 / (B + q/2)
        uint256 grossEthOut = (tokenAmount * L0) / (pricingBase + tokenAmount / 2);

        // 3. Verify health snapshot freshness and Merkle proof BEFORE we
        //    touch any state. _applyExitTax internally adjusts pLastWei /
        //    sEffWei by the cumulative cycle extraction so this redemption
        //    sees the depleted state left by all earlier redemptions.
        _verifyHealthSnapshot(snapshotId, snapshotTimestamp, pLastWei, sEffWei, proof);

        // 4. Compute tax / net using the SAME L0, B, and effective health
        //    inputs. Health score returned is the quote-time score (post any
        //    earlier in-cycle extraction, pre this trade).
        (uint256 taxAmount, uint256 netEth, uint256 healthScoreBps) = _applyExitTax(
            grossEthOut, ethRecipient, ethRecipient, L0, pLastWei, sEffWei
        );

        // 5. Emit the frozen quote snapshot before any pay-out so off-chain
        //    consumers can reproduce the math from a single event. The
        //    snapshot logs the RAW Merkle-supplied pLastWei / sEffWei (the
        //    spec-literal H_x = X / (X + E_curr) inputs); E_curr is recorded
        //    in the post-trade event below so consumers can recompute every
        //    factor exactly without state-walking.
        emit RedemptionQuoteSnapshot(
            ethRecipient,
            cycleNonce,
            tokenAmount,
            L0,
            pricingBase,
            pLastWei,
            sEffWei,
            grossEthOut,
            healthScoreBps
        );

        // 6. Transfer redeemed PINK to the NFT contract first (CEI: token
        //    accounting before ETH out). NFT contract re-indexes them to
        //    staked NFTs only.
        _transfer(address(this), nftContract, tokenAmount);

        // 7. Pay net ETH to redeemer.
        if (netEth > 0) {
            (bool ok,) = payable(ethRecipient).call{value: netEth}("");
            if (!ok) revert ETHTransferFailed();
        }

        // 8. Route tax ETH to the BananaVault (still inside the system).
        if (taxAmount > 0 && taxRecipient != address(0)) {
            (bool ok,) = payable(taxRecipient).call{value: taxAmount}("");
            if (!ok) revert ETHTransferFailed();
        }

        // 9. Update cycle extraction state AFTER pay-out so that the NEXT
        //    redemption sees a strictly-weaker H_prod / H_solv. Gross drains
        //    productive value; only net leaves the system entirely.
        _recordExtraction(grossEthOut, netEth);

        // 10. Emit post-trade state. address(this).balance reflects refreshed
        //     liquidity (L0 - grossEthOut). Off-chain monitors can verify the
        //     monotonic-decay invariant directly from this event stream.
        emit RedemptionPostTradeState(
            ethRecipient,
            cycleNonce,
            currentCycleGrossExtractionEth,
            currentCycleNetExtractionEth,
            address(this).balance
        );
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)

pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

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

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/cryptography/Hashes.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

@openzeppelin/contracts/utils/cryptography/MerkleProof.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     * @dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = Hashes.commutativeKeccak256(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = hasher(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = Hashes.commutativeKeccak256(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        if (proofFlagsLen > 0) {
            // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
            // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
            bytes32[] memory hashes = new bytes32[](proofFlagsLen);
            uint256 leafPos = 0;
            uint256 hashPos = 0;
            uint256 proofPos = 0;
            // At each step, we compute the next hash using two values:
            // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
            //   get the next hash.
            // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
            //   `proof` array.
            for (uint256 i = 0; i < proofFlagsLen; i++) {
                bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
                bytes32 b = proofFlags[i]
                    ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                    : proof[proofPos++];
                hashes[i] = hasher(a, b);
            }
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

contracts/DailyDynamicExitTax.sol

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

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

/// @title DailyDynamicExitTax
/// @notice Three-factor health-based exit tax with Merkle-committed external inputs.
/// @dev Tax is a linear function of ecosystem health stress. Two health inputs (P_last,
///      S_eff) are supplied by users as Merkle proofs against a root published by the owner.
///      L_eff is always supplied by the redemption path as the snapshotted ETH balance
///      taken ONCE at the top of the call (so it cannot drift mid-execution).
///
///      Health formula (PSA V1 spec, literal):
///        E_curr = currentCycleGrossExtractionEth   ← cumulative pre-this-trade
///        H_prod = P_last / (P_last + E_curr)
///        H_liq  = L_eff  / (L_eff  + E_curr)
///        H_solv = S_eff  / (S_eff  + E_curr)
///        healthScore = floor((H_prod*4000 + H_liq*3500 + H_solv*2500) / 10_000)
///
///      The first redemption in a cycle therefore sees E_curr = 0 → all factors = 1.0
///      → healthScore = 10_000 → dailyStress = 0. Each subsequent redemption sees a
///      strictly weaker (smaller) score, the spec-required "later redemptions see
///      weaker state" property.
///
///      Tax formula:
///        dailyStress = 10_000 - healthScore
///        shareStress = grossEthOut * 10_000 / L_eff
///        taxBps = minTaxBps
///               + (dailyStress * dailyWeightBps / 10_000)
///               + (shareStress * shareWeightBps / 10_000)
///               + whaleSurchargeIfNeeded
///        taxBps is capped at maxTaxBps
abstract contract DailyDynamicExitTax is Ownable {
    /* ========== CONSTANTS ========== */

    uint256 public constant BPS = 10_000;

    /// @notice Hard bounds on the health-snapshot freshness window. PSA V1
    ///         immutable-core: setMaxSnapshotAge MUST keep the proof window
    ///         within `[MIN_SNAPSHOT_AGE, MAX_SNAPSHOT_AGE]` so the owner can
    ///         neither (a) effectively disable the freshness check by setting
    ///         it to centuries, nor (b) brick redemptions by setting it below
    ///         the off-chain attestor's publish cadence.
    uint256 public constant MIN_SNAPSHOT_AGE = 1 hours;
    uint256 public constant MAX_SNAPSHOT_AGE = 7 days;

    /* ========== CUSTOM ERRORS ========== */

    error InvalidAllocation();
    error InvalidAddress();
    error InvalidBps();
    error WeightSumInvalid();
    error HealthRootNotSet();
    error StaleHealthSnapshot();
    error InvalidHealthProof();
    /// @notice Reverts when an owner tries to overwrite a previously-set
    ///         taxRecipient. Tax recipient is one-way settable (immutable
    ///         after first non-zero set) so the redemption tax can never be
    ///         redirected away from the BananaVault sink mid-life.
    error TaxRecipientAlreadySet();
    /// @notice Reverts when setMaxSnapshotAge is called outside the
    ///         immutable [MIN_SNAPSHOT_AGE, MAX_SNAPSHOT_AGE] band.
    error InvalidSnapshotAge();

    /* ========== CYCLE STATE ========== */

    /// @notice ETH allocation for the active monthly cycle (set by pour)
    uint256 public cycleAllocation;

    /// @notice Cumulative gross ETH extracted from the redemption pool during the
    ///         CURRENT monthly cycle (sum of grossEthOut across all redemptions
    ///         since the last `_startNewCycle`). Used to weaken H_prod for later
    ///         redemptions in the same cycle: every later redemption sees a
    ///         depleted productive value, even though pLastWei is a stale Merkle
    ///         snapshot. PSA spec: "later redemptions in same cycle MUST see
    ///         weaker state".
    uint256 public currentCycleGrossExtractionEth;

    /// @notice Cumulative NET ETH paid to redeemers during the CURRENT cycle
    ///         (gross minus tax). Used to weaken H_solv: only the tax portion
    ///         remains economically available (it routes to the BananaVault,
    ///         outside the redemption pool but still inside the system); the
    ///         net portion has fully exited.
    uint256 public currentCycleNetExtractionEth;
    /// @notice Monotonically increasing cycle counter. Bumped in `_startNewCycle`
    ///         so off-chain consumers can correlate snapshot/settlement events
    ///         with a specific cycle even across same-block pours.
    uint256 public cycleNonce;

    /* ========== TAX CONFIG ========== */

    /// @notice Floor tax applied to every redemption (basis points)
    uint256 public minTaxBps;

    /// @notice Hard cap on total exit tax (basis points)
    uint256 public maxTaxBps;

    /// @notice Receives the collected exit tax (set to BananaVault via setStakingContract)
    address public taxRecipient;

    /// @notice Basis-point weight for the health (daily) stress component
    /// @dev Must sum to BPS with shareWeightBps
    uint256 public dailyWeightBps;

    /// @notice Basis-point weight for the share (size) stress component
    /// @dev Must sum to BPS with dailyWeightBps
    uint256 public shareWeightBps;

    /// @notice shareStressBps must reach this threshold to trigger whale surcharge
    uint256 public whaleThresholdBps;

    /// @notice Extra basis points added when whale threshold is exceeded
    uint256 public whaleSurchargeBps;

    /// @notice PSA V1 immutable-core: whale surcharge is ALWAYS-ON. There is
    ///         no enable/disable flag. Threshold and surcharge magnitude are
    ///         configurable via `setWhaleSurcharge`, but the disable path has
    ///         been removed so the owner cannot quietly switch off whale
    ///         protection mid-cycle. Kept as a public constant `true` so any
    ///         off-chain consumer reading the legacy flag receives the
    ///         (now-permanent) value.
    bool public constant whaleSurchargeEnabled = true;

    /// @notice Immutable spec floor / ceiling for exit tax (PSA core: 3% – 30%).
    ///         setMinTaxBps / setMaxTaxBps cannot move outside this band.
    uint256 public constant SPEC_MIN_TAX_FLOOR_BPS = 300;   // 3%
    uint256 public constant SPEC_MAX_TAX_CEIL_BPS  = 3000;  // 30%

    /* ========== HEALTH ORACLE STATE ========== */

    /// @notice Merkle root committing the current health snapshot (set by owner)
    bytes32 public healthSnapshotRoot;

    /// @notice Maximum age of a snapshot proof before redemption reverts (seconds)
    uint256 public maxSnapshotAge;

    /* ========== EVENTS ========== */

    event CycleStarted(uint256 indexed cycleId, uint256 allocation, uint256 timestamp);
    event CycleAllocationSet(uint256 oldAllocation, uint256 newAllocation);
    event MaxTaxBpsUpdated(uint256 oldBps, uint256 newBps);
    event MinTaxBpsUpdated(uint256 oldBps, uint256 newBps);
    event TaxRecipientUpdated(address indexed oldRecipient, address indexed newRecipient);
    event TaxWeightsUpdated(uint256 dailyWeightBps, uint256 shareWeightBps);
    event WhaleSurchargeConfigUpdated(uint256 thresholdBps, uint256 surchargeBps);
    event HealthSnapshotRootUpdated(bytes32 oldRoot, bytes32 newRoot);
    event MaxSnapshotAgeUpdated(uint256 oldAge, uint256 newAge);
    event RedemptionTaxApplied(
        address indexed from,
        uint256 grossEthOut,
        uint256 taxBps,
        uint256 taxAmount,
        uint256 netEthOut,
        uint256 healthScoreBps,
        uint256 dailyStressBps,
        uint256 shareStressBps,
        bool whaleSurchargeApplied
    );

    /// @notice Emitted at the START of a redemption with the exact quote-time
    ///         inputs frozen for the calculation. Off-chain consumers can replay
    ///         the math from this event alone — pLastWei / sEffWei are the RAW
    ///         Merkle-supplied values; combine with E_curr (post-trade event)
    ///         to recompute H_prod / H_solv exactly.
    event RedemptionQuoteSnapshot(
        address indexed from,
        uint256 indexed cycleNonce,
        uint256 tokenAmount,
        uint256 lEffWei,
        uint256 pricingBaseB,
        uint256 pLastWei,
        uint256 sEffWei,
        uint256 grossEthOut,
        uint256 healthScoreBps
    );

    /// @notice Emitted AFTER pay-out and extraction-state update with the
    ///         post-trade state of the cycle. Lets later actors observe that
    ///         "later redemptions see weaker state" is actually enforced.
    event RedemptionPostTradeState(
        address indexed from,
        uint256 indexed cycleNonce,
        uint256 currentCycleGrossExtractionEth,
        uint256 currentCycleNetExtractionEth,
        uint256 postTradeBalanceWei
    );

    /* ========== CONSTRUCTOR ========== */

    constructor(address _owner) Ownable(_owner) {
        if (_owner == address(0)) revert InvalidAddress();

        minTaxBps = 300;          // 3% floor (PSA immutable-core target range 3%–30%)
        maxTaxBps = 3000;         // 30% hard cap
        dailyWeightBps = 7000;    // 70% weight on health stress
        shareWeightBps = 3000;    // 30% weight on share (size) stress
        whaleThresholdBps = 1000; // 10% shareStress triggers whale (always-on)
        whaleSurchargeBps = 300;  // +3% surcharge
        // Default within the immutable [MIN_SNAPSHOT_AGE, MAX_SNAPSHOT_AGE]
        // band; owner can move it inside that band but never outside.
        maxSnapshotAge = MAX_SNAPSHOT_AGE;
    }

    /* ========== CYCLE ADMIN ========== */

    /// @notice Start a new monthly cycle (internal — only callable via pour).
    ///         CRITICAL: resets the per-cycle extraction accumulators so the
    ///         "later redemptions see weaker state" rule is bounded to a single
    ///         cycle. Without this reset, stress would compound forever.
    function _startNewCycle(uint256 newAllocation) internal {
        if (newAllocation == 0) revert InvalidAllocation();

        uint256 oldAllocation = cycleAllocation;
        cycleAllocation = newAllocation;
        currentCycleGrossExtractionEth = 0;
        currentCycleNetExtractionEth = 0;
        unchecked { cycleNonce += 1; }

        emit CycleStarted(block.timestamp / 30 days, newAllocation, block.timestamp);
        emit CycleAllocationSet(oldAllocation, newAllocation);
    }

    /// @dev Record extraction outflow AFTER pay-out (CEI-compliant: caller has
    ///      already done balance-mutating sends and the tx will return).
    ///      Both accumulators monotonically increase within a cycle. The next
    ///      redemption in the same cycle reads `currentCycleGrossExtractionEth`
    ///      as `E_curr`, weakening its health score per spec.
    function _recordExtraction(uint256 grossEthOut, uint256 netEthOut) internal {
        if (grossEthOut == 0) return;
        currentCycleGrossExtractionEth += grossEthOut;
        currentCycleNetExtractionEth += netEthOut;
    }

    /// @notice Mid-cycle allocation top-up (does not reset anything else)
    function setCycleAllocation(uint256 newAllocation) external onlyOwner {
        if (newAllocation == 0) revert InvalidAllocation();
        uint256 old = cycleAllocation;
        cycleAllocation = newAllocation;
        emit CycleAllocationSet(old, newAllocation);
    }

    /* ========== HEALTH COMPUTATION ========== */

    /// @dev Three-factor weighted health score in basis points (0–10000).
    ///      Higher score = healthier ecosystem = lower tax.
    ///      Spec-literal formula: H_x = X / (X + E_curr), where E_curr is the
    ///      pre-this-trade cumulative gross extraction within the current cycle.
    ///      The first redemption in a cycle therefore sees E_curr=0 and a score
    ///      of 10_000 (max health, zero daily stress); later redemptions
    ///      degrade monotonically as E_curr grows. Weights: P=40%, L=35%, S=25%.
    function _computeHealthScoreBps(
        uint256 pLastWei,
        uint256 lEffWei,
        uint256 sEffWei,
        uint256 eCurr
    ) internal pure returns (uint256) {
        // If denominator is 0 the factor contributes 0 (maximum stress for that dimension)
        uint256 hProd = (pLastWei + eCurr == 0) ? 0 : (pLastWei * BPS) / (pLastWei + eCurr);
        uint256 hLiq  = (lEffWei  + eCurr == 0) ? 0 : (lEffWei  * BPS) / (lEffWei  + eCurr);
        uint256 hSolv = (sEffWei  + eCurr == 0) ? 0 : (sEffWei  * BPS) / (sEffWei  + eCurr);
        return (hProd * 4000 + hLiq * 3500 + hSolv * 2500) / BPS;
    }

    /* ========== MERKLE SNAPSHOT VERIFICATION ========== */

    /// @dev Verifies a health snapshot Merkle proof and checks freshness.
    ///      Leaf encoding (OZ StandardMerkleTree compatible):
    ///        keccak256(bytes.concat(keccak256(abi.encode(snapshotId, snapshotTimestamp, pLastWei, sEffWei))))
    ///      The snapshotTimestamp is committed inside the leaf, so the contract can verify
    ///      age without trusting the caller's snapshotTimestamp argument.
    function _verifyHealthSnapshot(
        uint256 snapshotId,
        uint256 snapshotTimestamp,
        uint256 pLastWei,
        uint256 sEffWei,
        bytes32[] calldata proof
    ) internal view {
        if (healthSnapshotRoot == bytes32(0)) revert HealthRootNotSet();
        if (block.timestamp > snapshotTimestamp + maxSnapshotAge) revert StaleHealthSnapshot();

        bytes32 leaf = keccak256(
            bytes.concat(keccak256(abi.encode(snapshotId, snapshotTimestamp, pLastWei, sEffWei)))
        );
        if (!MerkleProof.verify(proof, healthSnapshotRoot, leaf)) revert InvalidHealthProof();
    }

    /* ========== TAX COMPUTATION ========== */

    /// @dev Compute tax bps for a redemption given pre-verified health inputs.
    ///      shareStressBps = grossEthOut * BPS / L0  (fraction of pool taken)
    ///      dailyStressBps = BPS - healthScoreBps    (inverse of health)
    ///
    ///      Health uses the spec-literal formula H_x = X / (X + E_curr) with
    ///      E_curr = currentCycleGrossExtractionEth — the *cumulative pre-this-trade*
    ///      gross extraction. So the first redemption sees E_curr=0 and the cycle
    ///      decays only as E_curr grows. The Merkle-supplied pLastWei / sEffWei are
    ///      static within a cycle (off-chain snapshot); the cycle's monotonic decay
    ///      comes entirely from E_curr.
    function _computeTaxBps(
        uint256 grossEthOut,
        uint256 L0,
        uint256 pLastWei,
        uint256 sEffWei
    )
        internal
        view
        returns (
            uint256 taxBps,
            uint256 healthScoreBps,
            uint256 dailyStressBps,
            uint256 shareStressBps,
            bool whaleApplied
        )
    {
        uint256 eCurr = currentCycleGrossExtractionEth;
        healthScoreBps = _computeHealthScoreBps(pLastWei, L0, sEffWei, eCurr);
        dailyStressBps = BPS - healthScoreBps;
        shareStressBps = L0 == 0 ? BPS : (grossEthOut * BPS) / L0;

        taxBps = minTaxBps
            + (dailyStressBps * dailyWeightBps) / BPS
            + (shareStressBps * shareWeightBps) / BPS;

        // PSA V1 immutable-core: whale surcharge is unconditional once the
        // share-stress threshold is crossed. There is no enable/disable flag.
        if (shareStressBps >= whaleThresholdBps) {
            taxBps += whaleSurchargeBps;
            whaleApplied = true;
        }

        if (taxBps > maxTaxBps) taxBps = maxTaxBps;
    }

    /* ========== EXIT TAX APPLICATION ========== */

    /// @notice Compute and apply exit tax. Call from the redemption path after proof verification.
    /// @param grossEthOut Gross ETH computed from batch curve
    /// @param from Seller (for tax exemption check)
    /// @param lEffWei L0 — ETH balance snapshotted before this redemption (H_liq input)
    /// @param pLastWei Productive value from Merkle snapshot (H_prod input)
    /// @param sEffWei Solvency support from Merkle snapshot (H_solv input)
    function _applyExitTax(
        uint256 grossEthOut,
        address from,
        address /* to */,
        uint256 lEffWei,
        uint256 pLastWei,
        uint256 sEffWei
    ) internal returns (uint256 taxAmount, uint256 netAmount, uint256 healthScoreBps) {
        if (grossEthOut == 0) return (0, 0, 0);

        (
            uint256 taxBps,
            uint256 hScore,
            uint256 dailyStressBps,
            uint256 shareStressBps,
            bool whaleApplied
        ) = _computeTaxBps(grossEthOut, lEffWei, pLastWei, sEffWei);

        taxAmount = (grossEthOut * taxBps) / BPS;
        netAmount = grossEthOut - taxAmount;
        healthScoreBps = hScore;

        emit RedemptionTaxApplied(
            from,
            grossEthOut,
            taxBps,
            taxAmount,
            netAmount,
            healthScoreBps,
            dailyStressBps,
            shareStressBps,
            whaleApplied
        );
    }

    /* ========== VIEW HELPERS ========== */

    /// @notice Preview tax for a redemption without modifying state.
    ///         Does NOT verify the Merkle proof — intended for UI estimation only.
    ///         Uses address(this).balance for L0, so call this on the DarkPool instance.
    /// @param tokenAmount Amount of PINK tokens to redeem
    /// @param pricingBase B — total PINK indexed in SolvencyScript at quote time
    /// @param pLastWei Productive value (from health snapshot)
    /// @param sEffWei Solvency support (from health snapshot)
    function previewExitTax(
        uint256 tokenAmount,
        address /* from */,
        uint256 pricingBase,
        uint256 pLastWei,
        uint256 sEffWei
    ) external view returns (uint256 taxAmount, uint256 netAmount, uint256 taxBps, uint256 healthScoreBps) {
        uint256 L0 = address(this).balance;
        if (tokenAmount == 0 || pricingBase == 0 || L0 == 0) return (0, 0, 0, 0);

        // Batch curve: grossEthOut = q * L0 / (B + q/2)
        uint256 grossEthOut = (tokenAmount * L0) / (pricingBase + tokenAmount / 2);

        (taxBps, healthScoreBps,,,) = _computeTaxBps(grossEthOut, L0, pLastWei, sEffWei);
        taxAmount = (grossEthOut * taxBps) / BPS;
        netAmount = grossEthOut - taxAmount;
    }

    /* ========== ADMIN CONFIG ========== */

    /// @notice Publish a new health snapshot Merkle root.
    ///         Call after running `node eth/merkle/generate.js` off-chain.
    function setHealthSnapshotRoot(bytes32 root) external onlyOwner {
        bytes32 old = healthSnapshotRoot;
        healthSnapshotRoot = root;
        emit HealthSnapshotRootUpdated(old, root);
    }

    /// @notice Set the tax weights. Must sum to BPS (10 000).
    function setTaxWeights(uint256 _dailyWeightBps, uint256 _shareWeightBps) external onlyOwner {
        if (_dailyWeightBps + _shareWeightBps != BPS) revert WeightSumInvalid();
        dailyWeightBps = _dailyWeightBps;
        shareWeightBps = _shareWeightBps;
        emit TaxWeightsUpdated(_dailyWeightBps, _shareWeightBps);
    }

    /// @notice Set the floor (minimum) exit tax.
    /// @dev    Immutable-core hardening: must remain within the PSA spec band
    ///         [SPEC_MIN_TAX_FLOOR_BPS, maxTaxBps). Owner can never lower the
    ///         3% floor or invert the band.
    function setMinTaxBps(uint256 bps) external onlyOwner {
        if (bps < SPEC_MIN_TAX_FLOOR_BPS || bps >= maxTaxBps) revert InvalidBps();
        uint256 old = minTaxBps;
        minTaxBps = bps;
        emit MinTaxBpsUpdated(old, bps);
    }

    /// @notice Set the hard cap on exit tax.
    /// @dev    Immutable-core hardening: must remain within the PSA spec band
    ///         (minTaxBps, SPEC_MAX_TAX_CEIL_BPS]. Owner can never raise above
    ///         the 30% ceiling or invert the band.
    function setMaxTaxBps(uint256 bps) external onlyOwner {
        if (bps > SPEC_MAX_TAX_CEIL_BPS || bps <= minTaxBps) revert InvalidBps();
        uint256 old = maxTaxBps;
        maxTaxBps = bps;
        emit MaxTaxBpsUpdated(old, bps);
    }

    /// @notice Set maximum acceptable age for a health snapshot proof (in seconds).
    /// @dev    Immutable-core hardening: bounded to [MIN_SNAPSHOT_AGE, MAX_SNAPSHOT_AGE]
    ///         so the owner cannot effectively disable freshness checks (overly
    ///         long window) or brick redemptions (window shorter than the
    ///         attestor's publish cadence).
    function setMaxSnapshotAge(uint256 seconds_) external onlyOwner {
        if (seconds_ < MIN_SNAPSHOT_AGE || seconds_ > MAX_SNAPSHOT_AGE) revert InvalidSnapshotAge();
        uint256 old = maxSnapshotAge;
        maxSnapshotAge = seconds_;
        emit MaxSnapshotAgeUpdated(old, seconds_);
    }

    /// @notice Set the redemption-tax recipient ONCE.
    /// @dev    Immutable-core hardening: after the first non-zero set
    ///         (whether via this function or via DarkPool.setStakingContract)
    ///         the recipient is permanently locked. Owner cannot redirect the
    ///         exit tax mid-life. Use the smallest safe pattern: a single
    ///         non-zero check on the existing storage slot.
    function setTaxRecipient(address recipient) external onlyOwner {
        if (recipient == address(0)) revert InvalidAddress();
        if (taxRecipient != address(0)) revert TaxRecipientAlreadySet();
        taxRecipient = recipient;
        emit TaxRecipientUpdated(address(0), recipient);
    }

    /// @notice Configure the (always-on) whale surcharge.
    /// @dev    PSA V1 immutable-core: the enable/disable bool has been removed.
    ///         Threshold and surcharge magnitude remain configurable so the
    ///         owner can tune sizing parameters as the market matures, but the
    ///         surcharge can never be switched off.
    function setWhaleSurcharge(uint256 thresholdBps, uint256 surchargeBps) external onlyOwner {
        if (thresholdBps > BPS || surchargeBps > BPS) revert InvalidBps();
        whaleThresholdBps = thresholdBps;
        whaleSurchargeBps = surchargeBps;
        emit WhaleSurchargeConfigUpdated(thresholdBps, surchargeBps);
    }

    /// @notice Tax exemption is intentionally not configurable.
    /// @dev    Immutable-core hardening: setTaxExempt has been removed so the
    ///         owner can never grant arbitrary addresses zero-tax exits, which
    ///         would otherwise undermine the credible 3% – 30% exit tax band.

    /// @notice PSA V1 immutable-core: pause / unpause have been REMOVED.
    ///         Redemption is a core mechanic and cannot be turned off.
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.