Skip to content
Verified contractPartialMIT

WishGarden

Address0xafb4025952b36207ceae8c564f91bd04f9dcd24e
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,427,600
Creation transaction
0x5fe55a3d2e…1b04c4a62c

src/WishGarden.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {GardenEconomy} from "./GardenEconomy.sol";
import {WishGardenTreasury} from "./WishGardenTreasury.sol";
import {WishText} from "./WishText.sol";

/// @notice Paid-only permanent candles. Legacy remains the sole lifetime free-claim ledger.
contract WishGarden is GardenEconomy, Ownable2Step, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using SafeCast for uint256;
    address public constant LEGACY_GARDEN = 0xAaBd6A747359F5478803EFA7B51E929e62EC4cA2;
    uint8 public constant STYLE_COUNT = 7;
    uint256 public constant MAX_PAGE_SIZE = 100;
    uint256 public constant CANDLE_ID_BASE = 1 << 255;

    struct Candle {
        address purchaser;
        uint64 createdAt;
        uint8 style;
        bool freeClaim;
        uint256 position;
        uint256 nftTokenId;
    }
    WishGardenTreasury public immutable treasury;
    uint256 public totalCandles;
    uint256 public paidCandles;
    mapping(uint256 => Candle) private _candles;
    mapping(address => uint256[]) private _purchaserCandles;
    // One immutable full text per purchase, referenced by every candle in that batch.
    mapping(uint256 => string) private _batchWishes;
    mapping(uint256 => uint256) public wishBatch;
    error InvalidStyle(uint8 style);
    error PurchasesDisabled();
    error CandleNotFound(uint256 candleId);
    error InvalidPage();
    error NamespaceExhausted();
    error OwnershipRequired();
    event CandleCreated(
        uint256 indexed candleId,
        address indexed purchaser,
        uint256 position,
        uint8 style,
        uint64 createdAt,
        bool freeClaim,
        uint256 nftTokenId
    );
    event CandlesPurchased(
        address indexed purchaser,
        uint256 indexed firstCandleId,
        uint256 quantity,
        uint8 style,
        uint256 totalIMD
    );
    event WishPublished(uint256 indexed firstCandleId, address indexed author, uint256 quantity, string text);

    constructor(address owner_, address treasury_) Ownable(owner_) {
        if (treasury_ == address(0) || treasury_ == address(this)) revert InvalidAddress();
        treasury = WishGardenTreasury(treasury_);
    }

    function buyCandles(uint256 quantity, uint8 style) external nonReentrant returns (uint256 firstCandleId) {
        return _buy(quantity, style, "", false);
    }

    /// @notice All candles in this purchase receive the same optional immutable wish. Use separate purchases for different texts.
    function buyCandlesWithWish(
        uint256 quantity,
        uint8 style,
        string calldata text,
        bool publicForeverAcknowledged
    ) external nonReentrant returns (uint256 firstCandleId) {
        return _buy(quantity, style, text, publicForeverAcknowledged);
    }

    function _buy(uint256 quantity, uint8 style, string memory text, bool acknowledged)
        private
        returns (uint256 firstCandleId)
    {
        _checkQuantity(quantity);
        if (style >= STYLE_COUNT) revert InvalidStyle(style);
        WishText.validate(text, acknowledged);
        _requireIMD();
        if (
            address(treasury).code.length == 0 || treasury.garden() != address(this)
                || !treasury.purchasesEnabled()
        ) {
            revert PurchasesDisabled();
        }
        // Reserve the final uint256 value for an exclusive pagination cursor.
        if (totalCandles + quantity >= CANDLE_ID_BASE - 1) revert NamespaceExhausted();
        uint256 payment = CANDLE_PRICE * quantity;
        firstCandleId = CANDLE_ID_BASE + totalCandles + 1;
        paidCandles += quantity;
        uint64 createdAt = block.timestamp.toUint64();
        bool hasWish = bytes(text).length != 0;
        if (hasWish) _batchWishes[firstCandleId] = text;
        for (uint256 i; i < quantity; ++i) {
            uint256 id = CANDLE_ID_BASE + ++totalCandles;
            _candles[id] = Candle(msg.sender, createdAt, style, false, id - 1, 0);
            _purchaserCandles[msg.sender].push(id);
            if (hasWish) wishBatch[id] = firstCandleId;
            emit CandleCreated(id, msg.sender, id - 1, style, createdAt, false, 0);
        }
        IERC20 token = IERC20(IMD);
        uint256 gardenBefore = token.balanceOf(address(this));
        uint256 purchaserBefore = token.balanceOf(msg.sender);
        token.safeTransferFrom(msg.sender, address(this), payment);
        if (
            token.balanceOf(address(this)) != gardenBefore + payment
                || token.balanceOf(msg.sender) + payment != purchaserBefore
        ) {
            revert InexactTransfer();
        }
        uint256 treasuryBefore = token.balanceOf(address(treasury));
        token.safeTransfer(address(treasury), payment);
        if (
            token.balanceOf(address(this)) != gardenBefore
                || token.balanceOf(address(treasury)) != treasuryBefore + payment
        ) {
            revert InexactTransfer();
        }
        treasury.recordPayment(msg.sender, firstCandleId, quantity);
        emit CandlesPurchased(msg.sender, firstCandleId, quantity, style, payment);
        if (hasWish) emit WishPublished(firstCandleId, msg.sender, quantity, text);
    }

    function getCandle(uint256 candleId) public view returns (Candle memory) {
        _requireCandle(candleId);
        return _candles[candleId];
    }

    function wishOf(uint256 candleId) external view returns (address author, string memory text) {
        _requireCandle(candleId);
        return (_candles[candleId].purchaser, _batchWishes[wishBatch[candleId]]);
    }

    /// @notice Canonical global identifier; clients MUST also namespace legacy records by their contract address.
    function candleKey(uint256 candleId) external view returns (bytes32) {
        _requireCandle(candleId);
        return keccak256(abi.encode(CHAIN_ID, address(this), candleId));
    }

    function candleCountOf(address purchaser) external view returns (uint256) {
        return _purchaserCandles[purchaser].length;
    }

    function candleIdsOf(address purchaser, uint256 offset, uint256 limit)
        external
        view
        returns (uint256[] memory ids, uint256 nextOffset)
    {
        uint256 length = _purchaserCandles[purchaser].length;
        if (limit == 0 || limit > MAX_PAGE_SIZE || offset > length) revert InvalidPage();
        uint256 count = length - offset;
        if (count > limit) count = limit;
        ids = new uint256[](count);
        for (uint256 i; i < count; ++i) {
            ids[i] = _purchaserCandles[purchaser][offset + i];
        }
        nextOffset = offset + count;
    }

    /// @notice Start at CANDLE_ID_BASE + 1; nextId is an exclusive cursor, not a count.
    function getCandles(uint256 firstId, uint256 limit)
        external
        view
        returns (Candle[] memory records, uint256 nextId)
    {
        uint256 end = CANDLE_ID_BASE + totalCandles + 1;
        if (limit == 0 || limit > MAX_PAGE_SIZE || firstId <= CANDLE_ID_BASE || firstId > end) {
            revert InvalidPage();
        }
        uint256 count = end - firstId;
        if (count > limit) count = limit;
        records = new Candle[](count);
        for (uint256 i; i < count; ++i) {
            records[i] = _candles[firstId + i];
        }
        nextId = firstId + count;
    }

    function renounceOwnership() public view override onlyOwner {
        revert OwnershipRequired();
    }

    function _requireCandle(uint256 id) private view {
        if (id <= CANDLE_ID_BASE || id - CANDLE_ID_BASE > totalCandles) revert CandleNotFound(id);
    }
}

base/src/BaseBurnReceiver.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
    IBurnableIMD,
    IBaseIMDRestrictions,
    IIMDOFT,
    IBridgeEndpoint,
    MessagingParams,
    MessagingFee,
    MessagingReceipt
} from "../../src/bridge/IMDBridgeInterfaces.sol";
import {BridgeMessages} from "../../src/bridge/BridgeMessages.sol";

/// @notice BASE ONLY. Fixed official OFT credits can ONLY be burned. No owner, approval, transfer or rescue.
/// @dev Deploy separately through the deterministic CREATE2 deployer with the salt frozen on Ethereum, so the
///      address equals the one the Ethereum treasury derived from this exact code. Never put this in the
///      Ethereum manifest.
contract BaseBurnReceiver is ReentrancyGuard {
    address public constant IMD = 0xFF0C532FDB8Cd566Ae169C1CB157ff2Bdc83E105;
    address public constant ETHEREUM_IMD = 0xD34a99Bc0f67aE1bbd63C660e6d0b0dd03E263B7;
    uint256 public constant CHAIN_ID = 8453;
    /// @notice Lower bound of `maxBatch` (one candle's burn share, the Ethereum queue's minimum batch).
    uint256 public constant MIN_CREDIT = 0.3e18;
    address public immutable endpoint;
    address public immutable baseOFT;
    address public immutable ethereumQueue;
    uint32 public immutable ethereumEid;
    uint32 public immutable baseEid;
    uint128 public immutable acknowledgementGas;
    /// @notice Largest single batch the Ethereum queue may dispatch. Frozen there and part of this address's
    ///         derivation, so readiness is only signalled while one such credit can actually land here.
    uint256 public immutable maxBatch;
    /// @notice IMD burned for authenticated batches.
    uint256 public totalBurned;
    /// @notice IMD this receiver burned outside a batch compose and not attributed to a batch: direct
    ///         transfers ("donations"), plus any batch credit burned by `burnSurplus` before its compose ran,
    ///         which that compose then draws back out. Real burns by this contract equal
    ///         `totalBurned + surplusBurned`, so `totalBurned` never exceeds what was actually destroyed.
    uint256 public surplusBurned;

    struct Burn {
        bytes32 guid;
        uint256 amount;
    }
    mapping(uint256 => Burn) public burns;
    mapping(bytes32 => bool) public consumedGuid;
    error InvalidConfiguration();
    error WrongChain();
    error UnauthenticatedCompose();
    error InvalidCompose();
    error DuplicateBurn();
    error InexactBurn();
    error UnknownBatch();
    error IncorrectNativeFee();
    error CreditRestricted();
    event IMDBurned(
        uint256 indexed batchId,
        bytes32 indexed guid,
        uint256 amount,
        uint256 supplyBefore,
        uint256 supplyAfter
    );
    event AcknowledgementSent(uint256 indexed batchId, bytes32 indexed messageGuid);
    event SurplusBurned(address indexed caller, uint256 amount, uint256 supplyBefore, uint256 supplyAfter);

    constructor(
        address endpoint_,
        address baseOFT_,
        address ethereumQueue_,
        uint32 ethereumEid_,
        uint32 baseEid_,
        uint128 acknowledgementGas_,
        uint256 maxBatch_
    ) {
        if (
            endpoint_ == address(0) || baseOFT_ == address(0) || ethereumQueue_ == address(0)
                || baseOFT_ == IMD || baseOFT_ == address(this) || ethereumEid_ == 0 || baseEid_ == 0
                || ethereumEid_ == baseEid_ || acknowledgementGas_ < 100_000
                || acknowledgementGas_ > 5_000_000 || maxBatch_ < MIN_CREDIT
        ) {
            revert InvalidConfiguration();
        }
        endpoint = endpoint_;
        baseOFT = baseOFT_;
        ethereumQueue = ethereumQueue_;
        ethereumEid = ethereumEid_;
        baseEid = baseEid_;
        acknowledgementGas = acknowledgementGas_;
        maxBatch = maxBatch_;
    }

    /// @notice LayerZero OFTComposeMsgCodec v1: nonce(8), srcEid(4), amountLD(32), composeFrom(32), payload(96).
    function lzCompose(address from, bytes32 guid, bytes calldata message, address, bytes calldata)
        external
        payable
        nonReentrant
    {
        _requireBase();
        if (msg.sender != endpoint || from != baseOFT) revert UnauthenticatedCompose();
        if (msg.value != 0 || guid == bytes32(0) || message.length != 172) revert InvalidCompose();
        if (
            uint32(bytes4(message[8:12])) != ethereumEid
                || bytes32(message[44:76]) != BridgeMessages.addressWord(ethereumQueue)
        ) {
            revert UnauthenticatedCompose();
        }
        uint256 creditedAmount = uint256(bytes32(message[12:44]));
        (uint256 version, uint256 batchId, uint256 expectedAmount) =
            abi.decode(message[76:], (uint256, uint256, uint256));
        if (
            version != BridgeMessages.VERSION || batchId == 0 || expectedAmount == 0
                || expectedAmount != creditedAmount
        ) {
            revert InvalidCompose();
        }
        if (consumedGuid[guid] || burns[batchId].amount != 0) revert DuplicateBurn();
        // CEI plus guard. A shortage, false burn, revert or OOG rolls back consumption and permits exact retry.
        consumedGuid[guid] = true;
        burns[batchId] = Burn(guid, creditedAmount);
        totalBurned += creditedAmount;
        // The adapter credits this receiver before it queues the compose. If `burnSurplus` already burned
        // part of that credit, the shortfall is taken from `surplusBurned` (really burned, not yet attributed);
        // nothing else can cover a shortage, so a compose without its credit still reverts.
        uint256 held = IERC20(IMD).balanceOf(address(this));
        uint256 fromBalance = held < creditedAmount ? held : creditedAmount;
        uint256 alreadyBurned = creditedAmount - fromBalance;
        if (alreadyBurned > surplusBurned) revert InexactBurn();
        surplusBurned -= alreadyBurned;
        (uint256 beforeSupply, uint256 afterSupply) = _burnExact(fromBalance);
        emit IMDBurned(batchId, guid, creditedAmount, beforeSupply, afterSupply);
    }

    /// @notice Anyone may burn every IMD this receiver holds. Nothing can leave it any other way.
    /// @dev A direct transfer to the receiver would otherwise sit here forever and use up the Base token's
    ///      max-wallet headroom, blocking readiness and every later adapter credit. Burning it frees the
    ///      headroom and makes the donation a real supply burn. Burning a batch credit before its compose is
    ///      harmless: the amount is remembered in `surplusBurned` and that compose completes from it.
    function burnSurplus() external nonReentrant returns (uint256 amount) {
        _requireBase();
        amount = _burnHeld();
        if (amount == 0) revert InexactBurn();
    }

    /// @notice batchId 0 is a readiness handshake; positive IDs acknowledge already completed burns only.
    function quoteAcknowledgement(uint256 batchId) external view returns (uint256 nativeFee) {
        _requireBase();
        MessagingFee memory fee = IBridgeEndpoint(endpoint).quote(_ackParams(batchId), address(this));
        if (fee.lzTokenFee != 0) revert IncorrectNativeFee();
        return fee.nativeFee;
    }

    /// @notice Permissionless fee-funded maintenance. Failed/repeated acknowledgements never burn again.
    function sendAcknowledgement(uint256 batchId)
        external
        payable
        nonReentrant
        returns (bytes32 messageGuid)
    {
        _requireBase();
        if (batchId == 0) {
            // Burn whatever is held first (also proves the public burn selector is callable, even for zero),
            // so a donation can never keep the credit headroom below one maximum batch.
            _burnHeld();
            _checkDependencies();
        }
        MessagingParams memory params = _ackParams(batchId);
        MessagingFee memory fee = IBridgeEndpoint(endpoint).quote(params, address(this));
        if (fee.lzTokenFee != 0 || msg.value != fee.nativeFee) revert IncorrectNativeFee();
        MessagingReceipt memory receipt = IBridgeEndpoint(endpoint).send{value: msg.value}(params, msg.sender);
        if (
            receipt.guid == bytes32(0) || receipt.fee.nativeFee != fee.nativeFee
                || receipt.fee.lzTokenFee != 0
        ) {
            revert IncorrectNativeFee();
        }
        emit AcknowledgementSent(batchId, receipt.guid);
        return receipt.guid;
    }

    function _ackParams(uint256 batchId) private view returns (MessagingParams memory) {
        bytes memory message;
        if (batchId == 0) {
            message =
                abi.encode(BridgeMessages.READY, uint256(0), BridgeMessages.addressWord(baseOFT), CHAIN_ID);
        } else {
            Burn memory burned = burns[batchId];
            if (burned.amount == 0) revert UnknownBatch();
            message = abi.encode(BridgeMessages.BURNED, batchId, burned.guid, burned.amount);
        }
        return MessagingParams(
            ethereumEid,
            BridgeMessages.addressWord(ethereumQueue),
            message,
            BridgeMessages.receiveOptions(acknowledgementGas),
            false
        );
    }

    /// @notice Largest single adapter credit the Base token's transfer limits allow this receiver right now.
    /// @dev Unlimited while limits are off. While they are on: zero if trading is not active and neither the
    ///      adapter nor this receiver is fee-excluded (the token then rejects the transfer); unlimited if the
    ///      receiver is max-transaction excluded; otherwise maxWallet headroom, which `burnSurplus` restores
    ///      to the whole maxWallet. Credits above it revert in the adapter's lzReceive and stay retryable.
    function maxCredit() public view returns (uint256) {
        IBaseIMDRestrictions token = IBaseIMDRestrictions(IMD);
        if (!token.limitsInEffect()) return type(uint256).max;
        if (
            !token.tradingActive() && !token.isExcludedFromFees(baseOFT)
                && !token.isExcludedFromFees(address(this))
        ) return 0;
        if (token._isExcludedMaxTransactionAmount(address(this))) return type(uint256).max;
        uint256 wallet = token.maxWallet();
        uint256 held = IERC20(IMD).balanceOf(address(this));
        return wallet > held ? wallet - held : 0;
    }

    function _checkDependencies() private view {
        IIMDOFT adapter = IIMDOFT(baseOFT);
        (bytes4 interfaceId, uint64 version) = adapter.oftVersion();
        if (
            endpoint.code.length == 0 || IMD.code.length == 0 || IBridgeEndpoint(endpoint).eid() != baseEid
                || adapter.endpoint() != endpoint || adapter.token() != IMD || !adapter.approvalRequired()
                || adapter.peers(ethereumEid) != BridgeMessages.addressWord(ETHEREUM_IMD)
                || adapter.decimalConversionRate() != 1e12 || adapter.sharedDecimals() != 6
                || IERC20Metadata(IMD).decimals() != 18 || interfaceId != 0x02e49c2c || version != 1
        ) {
            revert InvalidConfiguration();
        }
        // A blacklisted receiver or adapter, inactive trading, or a max-wallet below one maximum batch makes
        // credits revert even though burn(0) succeeds. Readiness must not be signalled then.
        IBaseIMDRestrictions token = IBaseIMDRestrictions(IMD);
        if (token.isBlacklisted(address(this)) || token.isBlacklisted(baseOFT) || maxCredit() < maxBatch) {
            revert CreditRestricted();
        }
    }

    function _burnHeld() private returns (uint256 amount) {
        amount = IERC20(IMD).balanceOf(address(this));
        surplusBurned += amount;
        (uint256 beforeSupply, uint256 afterSupply) = _burnExact(amount);
        if (amount != 0) emit SurplusBurned(msg.sender, amount, beforeSupply, afterSupply);
    }

    function _burnExact(uint256 amount) private returns (uint256 beforeSupply, uint256 afterSupply) {
        IERC20 token = IERC20(IMD);
        uint256 beforeBalance = token.balanceOf(address(this));
        beforeSupply = token.totalSupply();
        if (beforeBalance < amount || beforeSupply < amount) revert InexactBurn();
        IBurnableIMD(IMD).burn(amount);
        afterSupply = token.totalSupply();
        if (token.balanceOf(address(this)) != beforeBalance - amount || afterSupply != beforeSupply - amount)
        {
            revert InexactBurn();
        }
    }

    function _requireBase() private view {
        if (block.chainid != CHAIN_ID) revert WrongChain();
    }
}

lib/openzeppelin-contracts/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);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data)
        external
        returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @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);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(
        address spender, uint256 currentAllowance, uint256 requestedDecrease
    );

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts/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;
    }
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @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].
 */
abstract contract ReentrancyGuard {
    // 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;

    uint256 private _status;

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

    constructor() {
        _status = 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();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = 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 _status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

src/GardenEconomy.sol

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

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

/// @notice Fixed Ethereum IMD economy shared by the garden and its treasury.
abstract contract GardenEconomy {
    address public constant IMD = 0xD34a99Bc0f67aE1bbd63C660e6d0b0dd03E263B7;
    uint256 public constant CHAIN_ID = 1;
    uint8 public constant IMD_DECIMALS = 18;
    uint256 public constant CANDLE_PRICE = 1e18;
    uint256 public constant MAX_BATCH_SIZE = 50;
    uint256 public constant BURN_ALLOCATION_PER_CANDLE = 0.3e18;
    uint256 public constant ECOSYSTEM_PER_CANDLE = 0.5e18;
    uint256 public constant OPERATIONS_PER_CANDLE = 0.1e18;
    uint256 public constant FOUNDER_PER_CANDLE = 0.1e18;

    error WrongChain(uint256 actualChainId);
    error IMDUnavailable();
    error UnexpectedIMDDecimals(uint8 actualDecimals);
    error InvalidQuantity(uint256 quantity);
    error InexactTransfer();
    error InvalidAddress();

    function _requireEthereum() internal view {
        if (block.chainid != CHAIN_ID) revert WrongChain(block.chainid);
    }

    function _requireIMD() internal view {
        _requireEthereum();
        if (IMD.code.length == 0) revert IMDUnavailable();
        uint8 decimals = IERC20Metadata(IMD).decimals();
        if (decimals != IMD_DECIMALS) revert UnexpectedIMDDecimals(decimals);
    }

    function _checkQuantity(uint256 quantity) internal pure {
        if (quantity == 0 || quantity > MAX_BATCH_SIZE) revert InvalidQuantity(quantity);
    }
}

src/WishGardenTreasury.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IMDBurnQueue} from "./bridge/IMDBurnQueue.sol";
import {IWishGarden} from "./interfaces/IWishGarden.sol";

/// @notice Segregated 30/50/10/10 ledger. Burn funds can leave only through the fixed official OFT route.
contract WishGardenTreasury is IMDBurnQueue {
    using SafeERC20 for IERC20;
    enum Bucket {
        Ecosystem,
        Operations,
        Founder
    }
    address public garden;
    uint256 public ecosystemBalance;
    uint256 public operationsBalance;
    uint256 public founderBalance;
    uint256 public totalPayments;
    uint256 public totalEcosystemWithdrawn;
    uint256 public totalOperationsWithdrawn;
    uint256 public totalFounderWithdrawn;

    error GardenAlreadyBound();
    error InvalidGarden();
    error OnlyGarden();
    error InsufficientFunding();
    error InsufficientBucketBalance();
    error InvalidWithdrawal();
    event GardenBound(address indexed garden);
    event PaymentAllocated(
        address indexed purchaser,
        uint256 indexed firstCandleId,
        uint256 quantity,
        uint256 payment,
        uint256 pendingBurn,
        uint256 ecosystem,
        uint256 operations,
        uint256 founder
    );
    event BucketWithdrawn(
        Bucket indexed bucket, address indexed caller, address indexed destination, uint256 amount
    );

    constructor(address owner_) IMDBurnQueue(owner_) {}

    function bindGarden(address garden_) external onlyOwner nonReentrant {
        _requireEthereum();
        if (garden != address(0)) revert GardenAlreadyBound();
        if (garden_.code.length == 0 || garden_ == address(this)) revert InvalidGarden();
        IWishGarden candidate = IWishGarden(garden_);
        if (candidate.treasury() != address(this) || candidate.owner() != owner() || candidate.IMD() != IMD) {
            revert InvalidGarden();
        }
        garden = garden_;
        emit GardenBound(garden_);
    }

    function recordPayment(address purchaser, uint256 firstCandleId, uint256 quantity) external nonReentrant {
        if (msg.sender != garden || garden == address(0)) revert OnlyGarden();
        if (!purchasesEnabled) revert BridgeNotReady();
        _checkBridge();
        if (purchaser == address(0) || firstCandleId == 0) revert InvalidAddress();
        _checkQuantity(quantity);
        uint256 payment = CANDLE_PRICE * quantity;
        if (IERC20(IMD).balanceOf(address(this)) < accountedBalance() + payment) {
            revert InsufficientFunding();
        }
        uint256 burn = BURN_ALLOCATION_PER_CANDLE * quantity;
        uint256 ecosystem = ECOSYSTEM_PER_CANDLE * quantity;
        uint256 operations = OPERATIONS_PER_CANDLE * quantity;
        uint256 founder = FOUNDER_PER_CANDLE * quantity;
        ecosystemBalance += ecosystem;
        operationsBalance += operations;
        founderBalance += founder;
        totalPayments += payment;
        pendingBurn += burn;
        totalBurnAllocated += burn;
        emit PaymentAllocated(
            purchaser, firstCandleId, quantity, payment, burn, ecosystem, operations, founder
        );
    }

    function withdrawEcosystem(address destination, uint256 amount) external onlyOwner nonReentrant {
        if (amount > ecosystemBalance) revert InsufficientBucketBalance();
        ecosystemBalance -= amount;
        totalEcosystemWithdrawn += amount;
        _withdraw(Bucket.Ecosystem, destination, amount);
    }

    function withdrawOperations(address destination, uint256 amount) external onlyOwner nonReentrant {
        if (amount > operationsBalance) revert InsufficientBucketBalance();
        operationsBalance -= amount;
        totalOperationsWithdrawn += amount;
        _withdraw(Bucket.Operations, destination, amount);
    }

    function withdrawFounder(address destination, uint256 amount) external onlyOwner nonReentrant {
        if (amount > founderBalance) revert InsufficientBucketBalance();
        founderBalance -= amount;
        totalFounderWithdrawn += amount;
        _withdraw(Bucket.Founder, destination, amount);
    }

    function revenueBalance() public view returns (uint256) {
        return ecosystemBalance + operationsBalance + founderBalance;
    }

    function accountedBalance() public view returns (uint256) {
        return pendingBurn + revenueBalance();
    }

    function unallocatedBalance() external view returns (uint256) {
        uint256 held = IERC20(IMD).balanceOf(address(this));
        uint256 accounted = accountedBalance();
        return held > accounted ? held - accounted : 0;
    }

    function _gardenBound() internal view override returns (bool) {
        return garden != address(0);
    }

    function _withdraw(Bucket bucket, address destination, uint256 amount) private {
        _requireIMD();
        if (
            amount == 0 || destination == address(0) || destination == address(this) || destination == garden
                || destination == IMD
        ) revert InvalidWithdrawal();
        IERC20 token = IERC20(IMD);
        uint256 held = token.balanceOf(address(this));
        uint256 recipient = token.balanceOf(destination);
        token.safeTransfer(destination, amount);
        if (
            token.balanceOf(address(this)) != held - amount
                || token.balanceOf(destination) != recipient + amount
        ) {
            revert InexactTransfer();
        }
        emit BucketWithdrawn(bucket, msg.sender, destination, amount);
    }
}

src/WishText.sol

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

/// @notice Strict RFC 3629 Unicode scalar validation, without normalization or text alteration.
library WishText {
    uint256 internal constant MAX_BYTES = 1120;
    uint256 internal constant MAX_CODEPOINTS = 280;
    error WishTooLong();
    error InvalidUTF8(uint256 byteOffset);
    error PublicAcknowledgementRequired();

    function validate(string memory text, bool acknowledged) internal pure returns (uint256 count) {
        bytes memory data = bytes(text);
        if (data.length > MAX_BYTES) revert WishTooLong();
        if (data.length != 0 && !acknowledged) revert PublicAcknowledgementRequired();
        uint256 i;
        while (i < data.length) {
            uint8 first = uint8(data[i]);
            uint256 width;
            uint32 scalar;
            if (first <= 0x7f) {
                width = 1;
                scalar = first;
            } else if (first >= 0xc2 && first <= 0xdf) {
                width = 2;
                scalar = first & 0x1f;
            } else if (first >= 0xe0 && first <= 0xef) {
                width = 3;
                scalar = first & 0x0f;
            } else if (first >= 0xf0 && first <= 0xf4) {
                width = 4;
                scalar = first & 0x07;
            } else {
                revert InvalidUTF8(i);
            }
            if (i + width > data.length) revert InvalidUTF8(i);
            for (uint256 j = 1; j < width; ++j) {
                uint8 next = uint8(data[i + j]);
                if (next < 0x80 || next > 0xbf) revert InvalidUTF8(i + j);
                scalar = (scalar << 6) | (next & 0x3f);
            }
            if (
                (width == 2 && scalar < 0x80) || (width == 3 && scalar < 0x800)
                    || (width == 4 && scalar < 0x10000) || (scalar >= 0xd800 && scalar <= 0xdfff)
                    || scalar > 0x10ffff
            ) revert InvalidUTF8(i);
            if (++count > MAX_CODEPOINTS) revert WishTooLong();
            i += width;
        }
    }
}

src/bridge/BridgeMessages.sol

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

/// @notice Application protocol on top of LayerZero V2 / OFT v1. Not an alternative bridge.
library BridgeMessages {
    uint8 internal constant READY = 1;
    uint8 internal constant BURNED = 2;
    uint256 internal constant VERSION = 1;

    function addressWord(address account) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(account)));
    }

    /// @dev LayerZero type-3 executor receive option: worker 1, length 17, type 1, gas uint128.
    function receiveOptions(uint128 gasLimit) internal pure returns (bytes memory) {
        return abi.encodePacked(uint16(3), uint8(1), uint16(17), uint8(1), gasLimit);
    }

    /// @dev Additionally request compose index 0, worker 1, length 19, type 3, index uint16, gas uint128.
    function composeOptions(uint128 receiveGas, uint128 composeGas) internal pure returns (bytes memory) {
        return bytes.concat(
            receiveOptions(receiveGas),
            abi.encodePacked(uint8(1), uint16(19), uint8(3), uint16(0), composeGas)
        );
    }
}

src/bridge/IMDBridgeInterfaces.sol

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

// ABI-compatible subsets of the verified IMD OFT / LayerZero V2 interfaces.
// Provenance and exact upstream interface snapshots: docs/bridge/ and docs/verification.md.
struct SendParam {
    uint32 dstEid;
    bytes32 to;
    uint256 amountLD;
    uint256 minAmountLD;
    bytes extraOptions;
    bytes composeMsg;
    bytes oftCmd;
}

struct MessagingFee {
    uint256 nativeFee;
    uint256 lzTokenFee;
}

struct MessagingReceipt {
    bytes32 guid;
    uint64 nonce;
    MessagingFee fee;
}

struct OFTReceipt {
    uint256 amountSentLD;
    uint256 amountReceivedLD;
}

struct Origin {
    uint32 srcEid;
    bytes32 sender;
    uint64 nonce;
}

struct MessagingParams {
    uint32 dstEid;
    bytes32 receiver;
    bytes message;
    bytes options;
    bool payInLzToken;
}

interface IIMDOFT {
    function token() external view returns (address);
    function approvalRequired() external view returns (bool);
    function endpoint() external view returns (address);
    function peers(uint32 eid) external view returns (bytes32);
    function decimalConversionRate() external view returns (uint256);
    function sharedDecimals() external view returns (uint8);
    function oftVersion() external view returns (bytes4, uint64);
    function quoteSend(SendParam calldata params, bool payInLzToken)
        external
        view
        returns (MessagingFee memory);
    function send(SendParam calldata params, MessagingFee calldata fee, address refundAddress)
        external
        payable
        returns (MessagingReceipt memory, OFTReceipt memory);
}

interface IBridgeEndpoint {
    function eid() external view returns (uint32);
    function quote(MessagingParams calldata params, address sender)
        external
        view
        returns (MessagingFee memory);
    function send(MessagingParams calldata params, address refundAddress)
        external
        payable
        returns (MessagingReceipt memory);
}

interface IBurnableIMD {
    function burn(uint256 amount) external;
}

/// @notice Transfer-restriction views of the verified Base IMD runtime (selectors present in its dispatcher).
/// @dev Its `_transfer` enforces blacklist and, while `limitsInEffect`, `maxWallet` for non-excluded
///      recipients and `tradingActive` unless sender or recipient is fee-excluded; ERC20Burnable `burn`
///      bypasses `_transfer`, so a zero-burn probe alone cannot see them.
interface IBaseIMDRestrictions {
    function isBlacklisted(address account) external view returns (bool);
    function limitsInEffect() external view returns (bool);
    function tradingActive() external view returns (bool);
    function isExcludedFromFees(address account) external view returns (bool);
    function maxWallet() external view returns (uint256);
    function _isExcludedMaxTransactionAmount(address account) external view returns (bool);
}

src/bridge/IMDBurnQueue.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {GardenEconomy} from "../GardenEconomy.sol";
import {
    IIMDOFT,
    IBridgeEndpoint,
    SendParam,
    MessagingFee,
    MessagingReceipt,
    OFTReceipt,
    Origin
} from "./IMDBridgeInterfaces.sol";
import {BridgeMessages} from "./BridgeMessages.sol";
import {BaseBurnReceiver} from "../../base/src/BaseBurnReceiver.sol";

/// @notice Restricted direct IMD OFT sender and authenticated Base burn receipt ledger.
/// @dev No approval, withdrawal, delegate, arbitrary-call or owner confirmation path exists.
///      The Base receiver is never a free owner choice: it is the CREATE2 address that exactly the compiled
///      BaseBurnReceiver creation code, bound to this treasury, gets from the deterministic deployer that
///      exists at the same address on Ethereum and Base. Only that code can ever occupy the frozen address.
abstract contract IMDBurnQueue is GardenEconomy, Ownable2Step, ReentrancyGuard {
    uint256 public constant BRIDGE_UNIT = 1e12; // verified 18 local / 6 shared decimals
    uint32 public constant ETHEREUM_EID = 30101; // LayerZero V2 Ethereum endpoint id (verified eid())
    uint32 public constant BASE_EID = 30184; // LayerZero V2 Base endpoint id (verified eid())
    /// @notice Arachnid deterministic deployment proxy, identical code and address on Ethereum and Base.
    address public constant CREATE2_DEPLOYER = 0x4e59b44847b379578588920cA78FbF26c0B4956C;
    bytes32 public constant CREATE2_DEPLOYER_CODE_HASH =
        0x2fa86add0aed31f33a762c9d88e807c475bd51d0f52bd0955754b2608f7e4989;
    /// @notice Smallest batch a third party can split off; a whole remaining balance may always be sent.
    uint256 public constant MIN_DISPATCH = BURN_ALLOCATION_PER_CANDLE;
    address public endpoint;
    address public baseEndpoint;
    address public baseOFT;
    address public baseReceiver;
    uint128 public acknowledgementGas;
    /// @notice Largest batch any caller can dispatch; frozen with the bridge and checked by the receiver against
    ///         the Base token's transfer limits before it signals readiness.
    uint256 public maxBatch;
    bytes32 public receiverSalt;
    bytes public bridgeOptions;
    bytes32 public verificationEvidence;
    bytes32 public configurationHash;
    bytes32 public bridgeTokenCodeHash;
    bytes32 public endpointCodeHash;
    bool public bridgeFrozen;
    bool public receiverReady;
    bool public purchasesEnabled;
    uint256 public totalBurnAllocated;
    uint256 public pendingBurn;
    uint256 public inTransitBurn;
    uint256 public confirmedBurn;
    uint256 public batchCount;

    struct Batch {
        bytes32 guid;
        uint256 amount;
        bool confirmed;
    }
    mapping(uint256 => Batch) public batches;
    mapping(bytes32 => bool) private _usedGuid;

    error BridgeNotReady();
    error ConfigurationFrozen();
    error InvalidBridgeConfiguration();
    error InvalidBatch();
    error IncorrectNativeFee();
    error InvalidBridgeReceipt();
    error UnauthenticatedMessage();
    error InvalidMessage();
    error AlreadyActive();
    error OwnershipRequired();

    event BridgeFrozen(bytes32 indexed configurationHash, bytes32 indexed evidence, address indexed receiver);
    event ReceiverReady(address indexed receiver);
    event PurchasesActivated();
    event BurnDispatched(uint256 indexed batchId, bytes32 indexed guid, uint256 amount, uint256 retainedDust);
    event BurnConfirmed(uint256 indexed batchId, bytes32 indexed guid, uint256 amount);

    constructor(address owner_) Ownable(owner_) {}

    /// @notice One-time owner configuration AFTER independent verification of BOTH chains and default DVN routes.
    /// @dev The receiver address is derived here from the compiled receiver code, this treasury, the fixed
    ///      endpoint ids and the given Base endpoint/adapter/gas/maximum batch/salt. A receiver built from other
    ///      code, for another queue or with other arguments has a different address and can never authenticate.
    ///      `maxBatch_` bounds every dispatch; the derived receiver refuses readiness while the Base token's
    ///      limits would reject one credit of that size.
    function freezeBridge(
        address endpoint_,
        address baseEndpoint_,
        address baseOFT_,
        uint128 receiveGas_,
        uint128 composeGas_,
        uint128 acknowledgementGas_,
        uint256 maxBatch_,
        bytes32 receiverSalt_,
        bytes32 evidence_
    ) external onlyOwner nonReentrant {
        _requireIMD();
        if (bridgeFrozen) revert ConfigurationFrozen();
        if (
            endpoint_.code.length == 0 || baseEndpoint_ == address(0) || baseOFT_ == address(0)
                || baseOFT_ == IMD || baseOFT_ == baseEndpoint_ || evidence_ == bytes32(0)
                || receiveGas_ < 100_000 || composeGas_ < 100_000 || acknowledgementGas_ < 100_000
                || receiveGas_ > 5_000_000 || composeGas_ > 5_000_000 || acknowledgementGas_ > 5_000_000
                || maxBatch_ < MIN_DISPATCH || maxBatch_ % BRIDGE_UNIT != 0
                || maxBatch_ / BRIDGE_UNIT > type(uint64).max
        ) revert InvalidBridgeConfiguration();
        address receiver_ =
            predictReceiver(baseEndpoint_, baseOFT_, acknowledgementGas_, maxBatch_, receiverSalt_);
        if (receiver_ == baseOFT_ || receiver_ == baseEndpoint_) revert InvalidBridgeConfiguration();
        endpoint = endpoint_;
        baseEndpoint = baseEndpoint_;
        baseOFT = baseOFT_;
        baseReceiver = receiver_;
        acknowledgementGas = acknowledgementGas_;
        maxBatch = maxBatch_;
        receiverSalt = receiverSalt_;
        bridgeOptions = BridgeMessages.composeOptions(receiveGas_, composeGas_);
        verificationEvidence = evidence_;
        bridgeTokenCodeHash = IMD.codehash;
        endpointCodeHash = endpoint_.codehash;
        bridgeFrozen = true;
        _checkBridge();
        bytes32 frozenHash = _configurationHash();
        configurationHash = frozenHash;
        emit BridgeFrozen(frozenHash, evidence_, receiver_);
    }

    function _configurationHash() private view returns (bytes32) {
        return keccak256(
            abi.encode(
                block.chainid,
                address(this),
                endpoint,
                baseEndpoint,
                ETHEREUM_EID,
                BASE_EID,
                baseOFT,
                baseReceiver,
                acknowledgementGas,
                keccak256(abi.encode(maxBatch, receiverSalt, receiverCreationCodeHash())),
                bridgeOptions,
                verificationEvidence
            )
        );
    }

    function activatePurchases() external onlyOwner nonReentrant {
        if (purchasesEnabled) revert AlreadyActive();
        if (!receiverReady || !_gardenBound()) revert BridgeNotReady();
        _checkBridge();
        purchasesEnabled = true;
        emit PurchasesActivated();
    }

    /// @notice keccak256 of the exact BaseBurnReceiver creation code this treasury accepts.
    function receiverCreationCodeHash() public pure returns (bytes32) {
        return keccak256(type(BaseBurnReceiver).creationCode);
    }

    /// @notice CREATE2 init code hash of the receiver bound to THIS treasury with the fixed endpoint ids.
    function receiverInitCodeHash(
        address baseEndpoint_,
        address baseOFT_,
        uint128 acknowledgementGas_,
        uint256 maxBatch_
    ) public view returns (bytes32) {
        return keccak256(
            bytes.concat(
                type(BaseBurnReceiver).creationCode,
                abi.encode(
                    baseEndpoint_,
                    baseOFT_,
                    address(this),
                    ETHEREUM_EID,
                    BASE_EID,
                    acknowledgementGas_,
                    maxBatch_
                )
            )
        );
    }

    /// @notice Address the deterministic deployer gives that receiver on Base for `salt`.
    function predictReceiver(
        address baseEndpoint_,
        address baseOFT_,
        uint128 acknowledgementGas_,
        uint256 maxBatch_,
        bytes32 salt
    ) public view returns (address) {
        bytes32 initCodeHash = receiverInitCodeHash(baseEndpoint_, baseOFT_, acknowledgementGas_, maxBatch_);
        return address(
            uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), CREATE2_DEPLOYER, salt, initCodeHash))))
        );
    }

    /// @notice Amount that `dispatch(maxAmount, ...)` would send now, its retained dust, fee and next batch id.
    function quoteDispatch(uint256 maxAmount)
        external
        view
        returns (uint256 amount, uint256 dust, uint256 nativeFee, uint256 nextBatchId)
    {
        _checkBridge();
        (amount, dust) = _roundedAmount(maxAmount);
        nextBatchId = batchCount + 1;
        MessagingFee memory fee = IIMDOFT(IMD).quoteSend(_sendParam(amount, nextBatchId), false);
        if (fee.lzTokenFee != 0) revert IncorrectNativeFee();
        nativeFee = fee.nativeFee;
    }

    /// @notice Anyone can pay native gas to send pending IMD ONLY to the frozen receiver via IMD.send.
    /// @dev Sends min(maxAmount, pendingBurn, maxBatch) rounded down to a shared unit, so no caller can create
    ///      a batch larger than the frozen bound the receiver checked against the Base token's limits; a larger
    ///      pending balance simply takes several batches. A batch below MIN_DISPATCH is
    ///      allowed only when it is the whole rounded pending balance, so a third party cannot split pending
    ///      funds into micro-batches. `maxBatchId` is an upper bound: an earlier dispatch by someone else
    ///      does not invalidate a prepared one, it only reduces what is left to send.
    ///      A reverted send leaves all tokens pending. Never resend an in-transit batch.
    function dispatch(uint256 maxAmount, uint256 maxBatchId)
        external
        payable
        nonReentrant
        returns (uint256 batchId)
    {
        if (!purchasesEnabled) revert BridgeNotReady();
        _checkBridge();
        (uint256 amount, uint256 dust) = _roundedAmount(maxAmount);
        batchId = batchCount + 1;
        if (batchId > maxBatchId) revert InvalidBatch();
        SendParam memory params = _sendParam(amount, batchId);
        MessagingFee memory fee = IIMDOFT(IMD).quoteSend(params, false);
        if (fee.lzTokenFee != 0 || msg.value != fee.nativeFee) revert IncorrectNativeFee();
        uint256 beforeBalance = IERC20(IMD).balanceOf(address(this));
        pendingBurn -= amount;
        inTransitBurn += amount;
        batchCount = batchId;
        batches[batchId].amount = amount;
        (MessagingReceipt memory receipt, OFTReceipt memory oftReceipt) =
            IIMDOFT(IMD).send{value: msg.value}(params, fee, msg.sender);
        if (
            receipt.guid == bytes32(0) || _usedGuid[receipt.guid] || oftReceipt.amountSentLD != amount
                || oftReceipt.amountReceivedLD != amount || receipt.fee.nativeFee != fee.nativeFee
                || receipt.fee.lzTokenFee != 0
                || IERC20(IMD).balanceOf(address(this)) != beforeBalance - amount
        ) {
            revert InvalidBridgeReceipt();
        }
        _usedGuid[receipt.guid] = true;
        batches[batchId].guid = receipt.guid;
        emit BurnDispatched(batchId, receipt.guid, amount, dust);
    }

    /// @notice LayerZero V2 receiver ABI. Only the frozen endpoint and derived Base receiver may acknowledge.
    function lzReceive(Origin calldata origin, bytes32, bytes calldata message, address, bytes calldata)
        external
        payable
        nonReentrant
    {
        _requireEthereum();
        if (
            !bridgeFrozen || msg.sender != endpoint || endpoint.codehash != endpointCodeHash
                || origin.srcEid != BASE_EID || origin.sender != BridgeMessages.addressWord(baseReceiver)
        ) revert UnauthenticatedMessage();
        if (msg.value != 0 || message.length != 128) revert InvalidMessage();
        (uint8 kind, uint256 batchId, bytes32 guid, uint256 amount) =
            abi.decode(message, (uint8, uint256, bytes32, uint256));
        if (kind == BridgeMessages.READY) {
            // Only the derived receiver code can send this, after checking its token, adapter, endpoint,
            // reciprocal peer, transfer restrictions and burn availability.
            if (batchId != 0 || guid != BridgeMessages.addressWord(baseOFT) || amount != 8453) {
                revert InvalidMessage();
            }
            if (!receiverReady) {
                receiverReady = true;
                emit ReceiverReady(baseReceiver);
            }
        } else if (kind == BridgeMessages.BURNED) {
            Batch storage batch = batches[batchId];
            if (batch.guid == bytes32(0) || batch.guid != guid || batch.amount != amount) {
                revert InvalidBridgeReceipt();
            }
            if (!batch.confirmed) {
                batch.confirmed = true;
                inTransitBurn -= amount;
                confirmedBurn += amount;
                emit BurnConfirmed(batchId, guid, amount);
            }
        } else {
            revert InvalidMessage();
        }
    }

    function allowInitializePath(Origin calldata origin) external view returns (bool) {
        return bridgeFrozen && origin.srcEid == BASE_EID
            && origin.sender == BridgeMessages.addressWord(baseReceiver);
    }

    function nextNonce(uint32, bytes32) external pure returns (uint64) {
        return 0; // unordered, replay protected by batch/GUID
    }

    function totalSupplyBurned() external view returns (uint256) {
        return confirmedBurn;
    }

    function pendingDust() external view returns (uint256) {
        return pendingBurn % BRIDGE_UNIT;
    }

    function renounceOwnership() public view override onlyOwner {
        revert OwnershipRequired();
    }

    function _checkBridge() internal view {
        _requireIMD();
        if (!bridgeFrozen) revert BridgeNotReady();
        IIMDOFT oft = IIMDOFT(IMD);
        (bytes4 interfaceId, uint64 version) = oft.oftVersion();
        if (
            IMD.codehash != bridgeTokenCodeHash || endpoint.codehash != endpointCodeHash
                || oft.endpoint() != endpoint || IBridgeEndpoint(endpoint).eid() != ETHEREUM_EID
                || oft.token() != IMD || oft.approvalRequired()
                || oft.peers(BASE_EID) != BridgeMessages.addressWord(baseOFT)
                || oft.decimalConversionRate() != BRIDGE_UNIT || oft.sharedDecimals() != 6
                || interfaceId != 0x02e49c2c || version != 1
        ) revert InvalidBridgeConfiguration();
    }

    function _roundedAmount(uint256 maxAmount) private view returns (uint256 amount, uint256 dust) {
        uint256 pending = pendingBurn;
        uint256 capped = maxAmount > pending ? pending : maxAmount;
        if (capped > maxBatch) capped = maxBatch;
        amount = capped / BRIDGE_UNIT * BRIDGE_UNIT;
        dust = capped - amount;
        if (amount == 0 || amount / BRIDGE_UNIT > type(uint64).max) revert InvalidBatch();
        if (amount < MIN_DISPATCH && amount != pending / BRIDGE_UNIT * BRIDGE_UNIT) revert InvalidBatch();
    }

    function _sendParam(uint256 amount, uint256 batchId) private view returns (SendParam memory) {
        return SendParam(
            BASE_EID,
            BridgeMessages.addressWord(baseReceiver),
            amount,
            amount,
            bridgeOptions,
            abi.encode(BridgeMessages.VERSION, batchId, amount),
            bytes("")
        );
    }
    function _gardenBound() internal view virtual returns (bool);
}

src/interfaces/IWishGarden.sol

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

/// @dev Used only for the owner's one-time treasury binding after factory deployment.
interface IWishGarden {
    function treasury() external view returns (address);
    function owner() external view returns (address);
    function IMD() external view returns (address);
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    ":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    ":forge-std/=lib/forge-std/src/",
    ":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.