S Price: $0.509691 (+0.48%)

Contract

0x2e062C260F9e011E6D483d662d255cB3D013c791

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
BookViewer

Compiler Version
v0.8.25+commit.b61c2a91

Optimization Enabled:
Yes with 1000 runs

Other Settings:
cancun EvmVersion
File 1 of 33 : BookViewer.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.20;

import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; // To generate artifacts
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {IBookManager} from "core/interfaces/IBookManager.sol";
import {SignificantBit} from "core/libraries/SignificantBit.sol";
import {Math} from "core/libraries/Math.sol";
import {Lockers} from "core/libraries/Lockers.sol";
import {BookId} from "core/libraries/BookId.sol";
import {Tick, TickLibrary} from "core/libraries/Tick.sol";
import {FeePolicy, FeePolicyLibrary} from "core/libraries/FeePolicy.sol";

import {IBookViewer} from "./interfaces/IBookViewer.sol";
import {IController} from "./interfaces/IController.sol";

contract BookViewer is IBookViewer, UUPSUpgradeable, Ownable2Step, Initializable {
    using SafeCast for *;
    using TickLibrary for *;
    using Math for uint256;
    using SignificantBit for uint256;
    using FeePolicyLibrary for FeePolicy;

    IBookManager public immutable bookManager;

    constructor(IBookManager bookManager_) Ownable(msg.sender) {
        bookManager = bookManager_;
    }

    function __BookViewer_init(address owner) external initializer {
        _transferOwnership(owner);
    }

    function _authorizeUpgrade(address) internal override onlyOwner {}

    function getLiquidity(BookId id, Tick tick, uint256 n) external view returns (Liquidity[] memory liquidity) {
        liquidity = new Liquidity[](n);
        if (bookManager.getDepth(id, tick) == 0) tick = bookManager.maxLessThan(id, tick);
        uint256 i;
        while (i < n) {
            if (Tick.unwrap(tick) == type(int24).min) break;
            liquidity[i] = Liquidity({tick: tick, depth: bookManager.getDepth(id, tick)});
            tick = bookManager.maxLessThan(id, tick);
            unchecked {
                ++i;
            }
        }
        assembly {
            mstore(liquidity, i)
        }
    }

    function getExpectedInput(IController.TakeOrderParams memory params)
        external
        view
        returns (uint256 takenQuoteAmount, uint256 spentBaseAmount)
    {
        IBookManager.BookKey memory key = bookManager.getBookKey(params.id);

        if (bookManager.isEmpty(params.id)) return (0, 0);

        Tick tick = bookManager.getHighest(params.id);

        while (Tick.unwrap(tick) > type(int24).min) {
            unchecked {
                if (params.limitPrice > tick.toPrice()) break;
                uint256 maxAmount;
                if (key.takerPolicy.usesQuote()) {
                    maxAmount = key.takerPolicy.calculateOriginalAmount(params.quoteAmount - takenQuoteAmount, true);
                } else {
                    maxAmount = params.quoteAmount - takenQuoteAmount;
                }
                maxAmount = maxAmount.divide(key.unitSize, true);

                if (maxAmount == 0) break;
                uint256 currentDepth = bookManager.getDepth(params.id, tick);
                uint256 quoteAmount = (currentDepth > maxAmount ? maxAmount : currentDepth) * key.unitSize;
                uint256 baseAmount = tick.quoteToBase(quoteAmount, true);
                if (key.takerPolicy.usesQuote()) {
                    quoteAmount = uint256(int256(quoteAmount) - key.takerPolicy.calculateFee(quoteAmount, false));
                } else {
                    baseAmount = uint256(baseAmount.toInt256() + key.takerPolicy.calculateFee(baseAmount, false));
                }
                if (quoteAmount == 0) break;

                takenQuoteAmount += quoteAmount;
                spentBaseAmount += baseAmount;
                if (params.quoteAmount <= takenQuoteAmount) break;
                tick = bookManager.maxLessThan(params.id, tick);
            }
        }
    }

    function getExpectedOutput(IController.SpendOrderParams memory params)
        external
        view
        returns (uint256 takenQuoteAmount, uint256 spentBaseAmount)
    {
        IBookManager.BookKey memory key = bookManager.getBookKey(params.id);

        if (bookManager.isEmpty(params.id)) return (0, 0);

        Tick tick = bookManager.getHighest(params.id);

        unchecked {
            while (spentBaseAmount <= params.baseAmount && Tick.unwrap(tick) > type(int24).min) {
                if (params.limitPrice > tick.toPrice()) break;
                uint256 maxAmount;
                if (key.takerPolicy.usesQuote()) {
                    maxAmount = params.baseAmount - spentBaseAmount;
                } else {
                    maxAmount = key.takerPolicy.calculateOriginalAmount(params.baseAmount - spentBaseAmount, false);
                }
                maxAmount = tick.baseToQuote(maxAmount, false) / key.unitSize;

                if (maxAmount == 0) break;
                uint256 currentDepth = bookManager.getDepth(params.id, tick);
                uint256 quoteAmount = (currentDepth > maxAmount ? maxAmount : currentDepth) * key.unitSize;
                uint256 baseAmount = tick.quoteToBase(quoteAmount, true);
                if (key.takerPolicy.usesQuote()) {
                    quoteAmount = uint256(int256(quoteAmount) - key.takerPolicy.calculateFee(quoteAmount, false));
                } else {
                    baseAmount = uint256(baseAmount.toInt256() + key.takerPolicy.calculateFee(baseAmount, false));
                }
                if (baseAmount == 0) break;

                takenQuoteAmount += quoteAmount;
                spentBaseAmount += baseAmount;
                tick = bookManager.maxLessThan(params.id, tick);
            }
        }
    }
}

File 2 of 33 : 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);
    }
}

File 3 of 33 : Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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.
     */
    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);
    }
}

File 4 of 33 : draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

File 5 of 33 : IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

File 6 of 33 : IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

File 7 of 33 : ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)

pragma solidity ^0.8.20;

import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";

/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy {
    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
     * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    constructor(address implementation, bytes memory _data) payable {
        ERC1967Utils.upgradeToAndCall(implementation, _data);
    }

    /**
     * @dev Returns the current implementation address.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
     */
    function _implementation() internal view virtual override returns (address) {
        return ERC1967Utils.getImplementation();
    }
}

File 8 of 33 : ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

File 9 of 33 : Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)

pragma solidity ^0.8.20;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
     * function and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }
}

File 10 of 33 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

File 11 of 33 : UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

File 12 of 33 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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);
}

File 13 of 33 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 14 of 33 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

File 15 of 33 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

File 16 of 33 : 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;
    }
}

File 17 of 33 : Errors.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();
}

File 18 of 33 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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);
}

File 19 of 33 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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) {
        /// @solidity memory-safe-assembly
        assembly {
            u := iszero(iszero(b))
        }
    }
}

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

pragma solidity ^0.8.24;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

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

    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlotType.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlotType) {
        return AddressSlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlotType.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlotType) {
        return BooleanSlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32SlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32SlotType.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32SlotType) {
        return Bytes32SlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256SlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256SlotType.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256SlotType) {
        return Uint256SlotType.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256SlotType is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256SlotType.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256SlotType) {
        return Int256SlotType.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlotType slot) internal view returns (address value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlotType slot, address value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlotType slot) internal view returns (bool value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlotType slot, bool value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32SlotType slot) internal view returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32SlotType slot, bytes32 value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256SlotType slot) internal view returns (uint256 value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256SlotType slot, uint256 value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256SlotType slot) internal view returns (int256 value) {
        /// @solidity memory-safe-assembly
        assembly {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256SlotType slot, int256 value) internal {
        /// @solidity memory-safe-assembly
        assembly {
            tstore(slot, value)
        }
    }
}

File 21 of 33 : IBookManager.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

import {BookId} from "../libraries/BookId.sol";
import {Currency} from "../libraries/Currency.sol";
import {OrderId} from "../libraries/OrderId.sol";
import {Tick} from "../libraries/Tick.sol";
import {FeePolicy} from "../libraries/FeePolicy.sol";
import {IERC721Permit} from "./IERC721Permit.sol";
import {IHooks} from "./IHooks.sol";

/**
 * @title IBookManager
 * @notice The interface for the BookManager contract
 */
interface IBookManager is IERC721Metadata, IERC721Permit {
    error InvalidUnitSize();
    error InvalidFeePolicy();
    error InvalidProvider(address provider);
    error LockedBy(address locker, address hook);
    error CurrencyNotSettled();

    /**
     * @notice Event emitted when a new book is opened
     * @param id The book id
     * @param base The base currency
     * @param quote The quote currency
     * @param unitSize The unit size of the book
     * @param makerPolicy The maker fee policy
     * @param takerPolicy The taker fee policy
     * @param hooks The hooks contract
     */
    event Open(
        BookId indexed id,
        Currency indexed base,
        Currency indexed quote,
        uint64 unitSize,
        FeePolicy makerPolicy,
        FeePolicy takerPolicy,
        IHooks hooks
    );

    /**
     * @notice Event emitted when a new order is made
     * @param bookId The book id
     * @param user The user address
     * @param tick The order tick
     * @param orderIndex The order index
     * @param unit The order unit
     * @param provider The provider address
     */
    event Make(
        BookId indexed bookId, address indexed user, Tick tick, uint256 orderIndex, uint64 unit, address provider
    );

    /**
     * @notice Event emitted when an order is taken
     * @param bookId The book id
     * @param user The user address
     * @param tick The order tick
     * @param unit The order unit
     */
    event Take(BookId indexed bookId, address indexed user, Tick tick, uint64 unit);

    /**
     * @notice Event emitted when an order is canceled
     * @param orderId The order id
     * @param unit The canceled unit
     */
    event Cancel(OrderId indexed orderId, uint64 unit);

    /**
     * @notice Event emitted when an order is claimed
     * @param orderId The order id
     * @param unit The claimed unit
     */
    event Claim(OrderId indexed orderId, uint64 unit);

    /**
     * @notice Event emitted when a provider is whitelisted
     * @param provider The provider address
     */
    event Whitelist(address indexed provider);

    /**
     * @notice Event emitted when a provider is delisted
     * @param provider The provider address
     */
    event Delist(address indexed provider);

    /**
     * @notice Event emitted when a provider collects fees
     * @param provider The provider address
     * @param recipient The recipient address
     * @param currency The currency
     * @param amount The collected amount
     */
    event Collect(address indexed provider, address indexed recipient, Currency indexed currency, uint256 amount);

    /**
     * @notice Event emitted when new default provider is set
     * @param newDefaultProvider The new default provider address
     */
    event SetDefaultProvider(address indexed newDefaultProvider);

    /**
     * @notice This structure represents a unique identifier for a book in the BookManager.
     * @param base The base currency of the book
     * @param unitSize The unit size of the book
     * @param quote The quote currency of the book
     * @param makerPolicy The maker fee policy of the book
     * @param hooks The hooks contract of the book
     * @param takerPolicy The taker fee policy of the book
     */
    struct BookKey {
        Currency base;
        uint64 unitSize;
        Currency quote;
        FeePolicy makerPolicy;
        IHooks hooks;
        FeePolicy takerPolicy;
    }

    /**
     * @notice Returns the base URI
     * @return The base URI
     */
    function baseURI() external view returns (string memory);

    /**
     * @notice Returns the contract URI
     * @return The contract URI
     */
    function contractURI() external view returns (string memory);

    /**
     * @notice Returns the default provider
     * @return The default provider
     */
    function defaultProvider() external view returns (address);

    /**
     * @notice Returns the total reserves of a given currency
     * @param currency The currency in question
     * @return The total reserves amount
     */
    function reservesOf(Currency currency) external view returns (uint256);

    /**
     * @notice Checks if a provider is whitelisted
     * @param provider The address of the provider
     * @return True if the provider is whitelisted, false otherwise
     */
    function isWhitelisted(address provider) external view returns (bool);

    /**
     * @notice Verifies if an owner has authorized a spender for a token
     * @param owner The address of the token owner
     * @param spender The address of the spender
     * @param tokenId The token ID
     */
    function checkAuthorized(address owner, address spender, uint256 tokenId) external view;

    /**
     * @notice Calculates the amount owed to a provider in a given currency
     * @param provider The provider's address
     * @param currency The currency in question
     * @return The owed amount
     */
    function tokenOwed(address provider, Currency currency) external view returns (uint256);

    /**
     * @notice Calculates the currency balance changes for a given locker
     * @param locker The address of the locker
     * @param currency The currency in question
     * @return The net change in currency balance
     */
    function getCurrencyDelta(address locker, Currency currency) external view returns (int256);

    /**
     * @notice Retrieves the book key for a given book ID
     * @param id The book ID
     * @return The book key
     */
    function getBookKey(BookId id) external view returns (BookKey memory);

    /**
     * @notice This structure represents a current status for an order in the BookManager.
     * @param provider The provider of the order
     * @param open The open unit of the order
     * @param claimable The claimable unit of the order
     */
    struct OrderInfo {
        address provider;
        uint64 open;
        uint64 claimable;
    }

    /**
     * @notice Provides information about an order
     * @param id The order ID
     * @return Order information including provider, open status, and claimable unit
     */
    function getOrder(OrderId id) external view returns (OrderInfo memory);

    /**
     * @notice Retrieves the locker and caller addresses for a given lock
     * @param i The index of the lock
     * @return locker The locker's address
     * @return lockCaller The caller's address
     */
    function getLock(uint256 i) external view returns (address locker, address lockCaller);

    /**
     * @notice Provides the lock data
     * @return The lock data including necessary numeric values
     */
    function getLockData() external view returns (uint128, uint128);

    /**
     * @notice Returns the depth of a given book ID and tick
     * @param id The book ID
     * @param tick The tick
     * @return The depth of the tick
     */
    function getDepth(BookId id, Tick tick) external view returns (uint64);

    /**
     * @notice Retrieves the highest tick for a given book ID
     * @param id The book ID
     * @return tick The highest tick
     */
    function getHighest(BookId id) external view returns (Tick tick);

    /**
     * @notice Finds the maximum tick less than a specified tick in a book
     * @dev Returns `Tick.wrap(type(int24).min)` if the specified tick is the lowest
     * @param id The book ID
     * @param tick The specified tick
     * @return The next lower tick
     */
    function maxLessThan(BookId id, Tick tick) external view returns (Tick);

    /**
     * @notice Checks if a book is opened
     * @param id The book ID
     * @return True if the book is opened, false otherwise
     */
    function isOpened(BookId id) external view returns (bool);

    /**
     * @notice Checks if a book is empty
     * @param id The book ID
     * @return True if the book is empty, false otherwise
     */
    function isEmpty(BookId id) external view returns (bool);

    /**
     * @notice Encodes a BookKey into a BookId
     * @param key The BookKey to encode
     * @return The encoded BookId
     */
    function encodeBookKey(BookKey calldata key) external pure returns (BookId);

    /**
     * @notice Loads a value from a specific storage slot
     * @param slot The storage slot
     * @return The value in the slot
     */
    function load(bytes32 slot) external view returns (bytes32);

    /**
     * @notice Loads a sequence of values starting from a specific slot
     * @param startSlot The starting slot
     * @param nSlot The number of slots to load
     * @return The sequence of values
     */
    function load(bytes32 startSlot, uint256 nSlot) external view returns (bytes memory);

    /**
     * @notice Opens a new book
     * @param key The book key
     * @param hookData The hook data
     */
    function open(BookKey calldata key, bytes calldata hookData) external;

    /**
     * @notice Locks a book manager function
     * @param locker The locker address
     * @param data The lock data
     * @return The lock return data
     */
    function lock(address locker, bytes calldata data) external returns (bytes memory);

    /**
     * @notice This structure represents the parameters for making an order.
     * @param key The book key for the order
     * @param tick The tick for the order
     * @param unit The unit for the order. Times key.unitSize to get actual bid amount.
     * @param provider The provider for the order. The limit order service provider address to collect fees.
     */
    struct MakeParams {
        BookKey key;
        Tick tick;
        uint64 unit;
        address provider;
    }

    /**
     * @notice Make a limit order
     * @param params The order parameters
     * @param hookData The hook data
     * @return id The order id. Returns 0 if the order is not settled
     * @return quoteAmount The amount of quote currency to be paid
     */
    function make(MakeParams calldata params, bytes calldata hookData)
        external
        returns (OrderId id, uint256 quoteAmount);

    /**
     * @notice This structure represents the parameters for taking orders in the specified tick.
     * @param key The book key for the order
     * @param tick The tick for the order
     * @param maxUnit The max unit to take
     */
    struct TakeParams {
        BookKey key;
        Tick tick;
        uint64 maxUnit;
    }

    /**
     * @notice Take a limit order at specific tick
     * @param params The order parameters
     * @param hookData The hook data
     * @return quoteAmount The amount of quote currency to be received
     * @return baseAmount The amount of base currency to be paid
     */
    function take(TakeParams calldata params, bytes calldata hookData)
        external
        returns (uint256 quoteAmount, uint256 baseAmount);

    /**
     * @notice This structure represents the parameters for canceling an order.
     * @param id The order id for the order
     * @param toUnit The remaining open unit for the order after cancellation. Must not exceed the current open unit.
     */
    struct CancelParams {
        OrderId id;
        uint64 toUnit;
    }

    /**
     * @notice Cancel a limit order
     * @param params The order parameters
     * @param hookData The hook data
     * @return canceledAmount The amount of quote currency canceled
     */
    function cancel(CancelParams calldata params, bytes calldata hookData) external returns (uint256 canceledAmount);

    /**
     * @notice Claims an order
     * @param id The order ID
     * @param hookData The hook data
     * @return claimedAmount The amount claimed
     */
    function claim(OrderId id, bytes calldata hookData) external returns (uint256 claimedAmount);

    /**
     * @notice Collects fees from a provider
     * @param recipient The recipient address
     * @param currency The currency
     * @return The collected amount
     */
    function collect(address recipient, Currency currency) external returns (uint256);

    /**
     * @notice Withdraws a currency
     * @param currency The currency
     * @param to The recipient address
     * @param amount The amount
     */
    function withdraw(Currency currency, address to, uint256 amount) external;

    /**
     * @notice Settles a currency
     * @param currency The currency
     * @return The settled amount
     */
    function settle(Currency currency) external payable returns (uint256);

    /**
     * @notice Whitelists a provider
     * @param provider The provider address
     */
    function whitelist(address provider) external;

    /**
     * @notice Delists a provider
     * @param provider The provider address
     */
    function delist(address provider) external;

    /**
     * @notice Sets the default provider
     * @param newDefaultProvider The new default provider address
     */
    function setDefaultProvider(address newDefaultProvider) external;
}

File 22 of 33 : IERC721Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";

/**
 * @title IERC721Permit
 * @notice An interface for the ERC721 permit extension
 */
interface IERC721Permit is IERC721 {
    error InvalidSignature();
    error PermitExpired();

    /**
     * @notice The EIP-712 typehash for the permit struct used by the contract
     */
    function PERMIT_TYPEHASH() external pure returns (bytes32);

    /**
     * @notice The EIP-712 domain separator for this contract
     */
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /**
     * @notice Approve the spender to transfer the given tokenId
     * @param spender The address to approve
     * @param tokenId The tokenId to approve
     * @param deadline The deadline for the signature
     * @param v The recovery id of the signature
     * @param r The r value of the signature
     * @param s The s value of the signature
     */
    function permit(address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;

    /**
     * @notice Get the current nonce for a token
     * @param tokenId The tokenId to get the nonce for
     * @return The current nonce
     */
    function nonces(uint256 tokenId) external view returns (uint256);
}

File 23 of 33 : IHooks.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IBookManager} from "./IBookManager.sol";
import {OrderId} from "../libraries/OrderId.sol";

/**
 * @title IHooks
 * @notice Interface for the hooks contract
 */
interface IHooks {
    /**
     * @notice Hook called before opening a new book
     * @param sender The sender of the open transaction
     * @param key The key of the book being opened
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function beforeOpen(address sender, IBookManager.BookKey calldata key, bytes calldata hookData)
        external
        returns (bytes4);

    /**
     * @notice Hook called after opening a new book
     * @param sender The sender of the open transaction
     * @param key The key of the book being opened
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function afterOpen(address sender, IBookManager.BookKey calldata key, bytes calldata hookData)
        external
        returns (bytes4);

    /**
     * @notice Hook called before making a new order
     * @param sender The sender of the make transaction
     * @param params The parameters of the make transaction
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function beforeMake(address sender, IBookManager.MakeParams calldata params, bytes calldata hookData)
        external
        returns (bytes4);

    /**
     * @notice Hook called after making a new order
     * @param sender The sender of the make transaction
     * @param params The parameters of the make transaction
     * @param orderId The id of the order that was made
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function afterMake(
        address sender,
        IBookManager.MakeParams calldata params,
        OrderId orderId,
        bytes calldata hookData
    ) external returns (bytes4);

    /**
     * @notice Hook called before taking an order
     * @param sender The sender of the take transaction
     * @param params The parameters of the take transaction
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function beforeTake(address sender, IBookManager.TakeParams calldata params, bytes calldata hookData)
        external
        returns (bytes4);

    /**
     * @notice Hook called after taking an order
     * @param sender The sender of the take transaction
     * @param params The parameters of the take transaction
     * @param takenUnit The unit that was taken
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function afterTake(
        address sender,
        IBookManager.TakeParams calldata params,
        uint64 takenUnit,
        bytes calldata hookData
    ) external returns (bytes4);

    /**
     * @notice Hook called before canceling an order
     * @param sender The sender of the cancel transaction
     * @param params The parameters of the cancel transaction
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function beforeCancel(address sender, IBookManager.CancelParams calldata params, bytes calldata hookData)
        external
        returns (bytes4);

    /**
     * @notice Hook called after canceling an order
     * @param sender The sender of the cancel transaction
     * @param params The parameters of the cancel transaction
     * @param canceledUnit The unit that was canceled
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function afterCancel(
        address sender,
        IBookManager.CancelParams calldata params,
        uint64 canceledUnit,
        bytes calldata hookData
    ) external returns (bytes4);

    /**
     * @notice Hook called before claiming an order
     * @param sender The sender of the claim transaction
     * @param orderId The id of the order being claimed
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function beforeClaim(address sender, OrderId orderId, bytes calldata hookData) external returns (bytes4);

    /**
     * @notice Hook called after claiming an order
     * @param sender The sender of the claim transaction
     * @param orderId The id of the order being claimed
     * @param claimedUnit The unit that was claimed
     * @param hookData The data passed to the hook
     * @return Returns the function selector if the hook is successful
     */
    function afterClaim(address sender, OrderId orderId, uint64 claimedUnit, bytes calldata hookData)
        external
        returns (bytes4);
}

File 24 of 33 : BookId.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.20;

import {IBookManager} from "../interfaces/IBookManager.sol";

type BookId is uint192;

library BookIdLibrary {
    function toId(IBookManager.BookKey memory bookKey) internal pure returns (BookId id) {
        bytes32 hash = keccak256(abi.encode(bookKey));
        assembly {
            id := and(hash, 0xffffffffffffffffffffffffffffffffffffffffffffffff)
        }
    }
}

File 25 of 33 : Currency.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.20;

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

type Currency is address;

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    using CurrencyLibrary for Currency;

    /// @notice Thrown when a native transfer fails
    error NativeTransferFailed();

    /// @notice Thrown when an ERC20 transfer fails
    error ERC20TransferFailed();

    Currency public constant NATIVE = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // implementation from
        // https://github.com/transmissions11/solmate/blob/e8f96f25d48fe702117ce76c79228ca4f20206cb/src/utils/SafeTransferLib.sol

        bool success;
        if (currency.isNative()) {
            assembly {
                // Transfer the ETH and store if it succeeded or not.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }

            if (!success) revert NativeTransferFailed();
        } else {
            assembly {
                // Get a pointer to some free memory.
                let freeMemoryPointer := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, freeMemoryPointer, 68, 0, 32)
                    )
            }

            if (!success) revert ERC20TransferFailed();
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isNative()) return address(this).balance;
        else return IERC20(Currency.unwrap(currency)).balanceOf(address(this));
    }

    function equals(Currency currency, Currency other) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(other);
    }

    function isNative(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(NATIVE);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

File 26 of 33 : FeePolicy.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.20;

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

type FeePolicy is uint24;

library FeePolicyLibrary {
    uint256 internal constant RATE_PRECISION = 10 ** 6;
    int256 internal constant MAX_FEE_RATE = 500000;
    int256 internal constant MIN_FEE_RATE = -500000;

    uint256 internal constant RATE_MASK = 0x7fffff; // 23 bits

    error InvalidFeePolicy();

    function encode(bool usesQuote_, int24 rate_) internal pure returns (FeePolicy feePolicy) {
        if (rate_ > MAX_FEE_RATE || rate_ < MIN_FEE_RATE) {
            revert InvalidFeePolicy();
        }

        uint256 mask = usesQuote_ ? 1 << 23 : 0;
        assembly {
            feePolicy := or(mask, add(and(rate_, 0xffffff), MAX_FEE_RATE))
        }
    }

    function isValid(FeePolicy self) internal pure returns (bool) {
        int24 r = rate(self);

        return !(r > MAX_FEE_RATE || r < MIN_FEE_RATE);
    }

    function usesQuote(FeePolicy self) internal pure returns (bool f) {
        assembly {
            f := shr(23, self)
        }
    }

    function rate(FeePolicy self) internal pure returns (int24 r) {
        assembly {
            r := sub(and(self, RATE_MASK), MAX_FEE_RATE)
        }
    }

    function calculateFee(FeePolicy self, uint256 amount, bool reverseRounding) internal pure returns (int256 fee) {
        int24 r = rate(self);

        bool positive = r > 0;
        uint256 absRate;
        unchecked {
            absRate = uint256(uint24(positive ? r : -r));
        }
        // @dev absFee must be less than type(int256).max
        uint256 absFee = Math.divide(amount * absRate, RATE_PRECISION, reverseRounding ? !positive : positive);
        fee = positive ? int256(absFee) : -int256(absFee);
    }

    function calculateOriginalAmount(FeePolicy self, uint256 amount, bool reverseFee)
        internal
        pure
        returns (uint256 originalAmount)
    {
        int24 r = rate(self);

        uint256 divider;
        assembly {
            if reverseFee { r := sub(0, r) }
            divider := add(RATE_PRECISION, r)
        }
        originalAmount = Math.divide(amount * RATE_PRECISION, divider, reverseFee);
    }
}

File 27 of 33 : Lockers.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.23;

import {IHooks} from "../interfaces/IHooks.sol";

/// @author Sonic Market
/// @author Modified from Uniswap V4 (https://github.com/Uniswap/v4-core/tree/98680ebc1a654120e995d53a5b10ec6fe153066f)
/// @notice Contains data about pool lockers.

/// @dev This library manages a custom storage implementation for a queue
///      that tracks current lockers. The "sentinel" storage slot for this data structure,
///      always passed in as IPoolManager.LockData storage self, stores not just the current
///      length of the queue but also the global count of non-zero deltas across all lockers.
///      The values of the data structure start at OFFSET, and each value is a locker address.
library Lockers {
    /// struct LockData {
    ///     /// @notice The current number of active lockers
    ///     uint128 length;
    ///     /// @notice The total number of nonzero deltas over all active + completed lockers
    ///     uint128 nonzeroDeltaCount;
    /// }
    // uint256(keccak256("LockData")) + 1
    uint256 internal constant LOCK_DATA_SLOT = 0x760a9a962ae3d184e99c0483cf5684fb3170f47116ca4f445c50209da4f4f907;

    // uint256(keccak256("Lockers")) + 1
    uint256 internal constant LOCKERS_SLOT = 0x722b431450ce53c44434ec138439e45a0639fe031b803ee019b776fae5cfa2b1;

    // The number of slots per item in the lockers array
    uint256 internal constant LOCKER_STRUCT_SIZE = 2;

    // uint256(keccak256("HookAddress")) + 1
    uint256 internal constant HOOK_ADDRESS_SLOT = 0xfcac7593714b88fec0c578a53e9f3f6e4b47eb26c9dcaa7eff23a3ac156be422;

    uint256 internal constant NONZERO_DELTA_COUNT_OFFSET = 2 ** 128;

    uint256 internal constant LENGTH_MASK = (1 << 128) - 1;

    /// @dev Pushes a locker onto the end of the queue, and updates the sentinel storage slot.
    function push(address locker, address lockCaller) internal {
        assembly {
            let data := tload(LOCK_DATA_SLOT)
            let l := and(data, LENGTH_MASK)

            // LOCKERS_SLOT + l * LOCKER_STRUCT_SIZE
            let indexToWrite := add(LOCKERS_SLOT, mul(l, LOCKER_STRUCT_SIZE))

            // in the next storage slot, write the locker and lockCaller
            tstore(indexToWrite, locker)
            tstore(add(indexToWrite, 1), lockCaller)

            // increase the length
            tstore(LOCK_DATA_SLOT, add(data, 1))
        }
    }

    function lockData() internal view returns (uint128 l, uint128 nonzeroDeltaCount) {
        assembly {
            let data := tload(LOCK_DATA_SLOT)
            l := and(data, LENGTH_MASK)
            nonzeroDeltaCount := shr(128, data)
        }
    }

    function length() internal view returns (uint128 l) {
        assembly {
            l := and(tload(LOCK_DATA_SLOT), LENGTH_MASK)
        }
    }

    /// @dev Pops a locker off the end of the queue. Note that no storage gets cleared.
    function pop() internal {
        assembly {
            let data := tload(LOCK_DATA_SLOT)
            let l := and(data, LENGTH_MASK)
            if iszero(l) {
                mstore(0x00, 0xf1c77ed0) // LockersPopFailed()
                revert(0x1c, 0x04)
            }

            // LOCKERS_SLOT + (l - 1) * LOCKER_STRUCT_SIZE
            let indexToWrite := add(LOCKERS_SLOT, mul(sub(l, 1), LOCKER_STRUCT_SIZE))

            // in the next storage slot, delete the locker and lockCaller
            tstore(indexToWrite, 0)
            tstore(add(indexToWrite, 1), 0)

            // decrease the length
            tstore(LOCK_DATA_SLOT, sub(data, 1))
        }
    }

    function getLocker(uint256 i) internal view returns (address locker) {
        assembly {
            // LOCKERS_SLOT + (i * LOCKER_STRUCT_SIZE)
            locker := tload(add(LOCKERS_SLOT, mul(i, LOCKER_STRUCT_SIZE)))
        }
    }

    function getLockCaller(uint256 i) internal view returns (address locker) {
        assembly {
            // LOCKERS_SLOT + (i * LOCKER_STRUCT_SIZE + 1)
            locker := tload(add(LOCKERS_SLOT, add(mul(i, LOCKER_STRUCT_SIZE), 1)))
        }
    }

    function getCurrentLocker() internal view returns (address) {
        unchecked {
            uint256 l = length();
            return l > 0 ? getLocker(l - 1) : address(0);
        }
    }

    function getCurrentLockCaller() internal view returns (address) {
        unchecked {
            uint256 l = length();
            return l > 0 ? getLockCaller(l - 1) : address(0);
        }
    }

    function incrementNonzeroDeltaCount() internal {
        assembly {
            tstore(LOCK_DATA_SLOT, add(tload(LOCK_DATA_SLOT), NONZERO_DELTA_COUNT_OFFSET))
        }
    }

    function decrementNonzeroDeltaCount() internal {
        assembly {
            tstore(LOCK_DATA_SLOT, sub(tload(LOCK_DATA_SLOT), NONZERO_DELTA_COUNT_OFFSET))
        }
    }

    function getCurrentHook() internal view returns (IHooks currentHook) {
        return IHooks(getHook(length()));
    }

    function getHook(uint256 i) internal view returns (address hook) {
        assembly {
            hook := tload(add(HOOK_ADDRESS_SLOT, i))
        }
    }

    function setCurrentHook(IHooks currentHook) internal returns (bool set) {
        // Set the hook address for the current locker if the address is 0.
        // If the address is nonzero, a hook has already been set for this lock, and is not allowed to be updated or cleared at the end of the call.
        if (address(getCurrentHook()) == address(0)) {
            uint256 l = length();
            assembly {
                tstore(add(HOOK_ADDRESS_SLOT, l), currentHook)
            }
            return true;
        }
    }

    function clearCurrentHook() internal {
        uint256 l = length();
        assembly {
            tstore(add(HOOK_ADDRESS_SLOT, l), 0)
        }
    }
}

File 28 of 33 : Math.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.0;

library Math {
    function divide(uint256 a, uint256 b, bool roundingUp) internal pure returns (uint256 ret) {
        // In the OrderBook contract code, b is never zero.
        assembly {
            ret := add(div(a, b), and(gt(mod(a, b), 0), roundingUp))
        }
    }

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                    sar(96, mul(add(24828157081833163892658089445524,
                        sar(96, mul(add(3273285459638523848632254066296,
                            x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Base conversion: mul `2**96 / (5**18 * 2**192)`.
            r := sdiv(p, 302231454903657293676544000000000000000000)
        }
    }
}

File 29 of 33 : OrderId.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.0;

import {Tick} from "./Tick.sol";
import {BookId} from "./BookId.sol";

type OrderId is uint256;

library OrderIdLibrary {
    /**
     * @dev Encode the order id.
     * @param bookId The book id.
     * @param tick The tick.
     * @param index The index.
     * @return id The order id.
     */
    function encode(BookId bookId, Tick tick, uint40 index) internal pure returns (OrderId id) {
        // @dev If we just use tick at the assembly code, the code will convert tick into bytes32.
        //      e.g. When index == -2, the shifted value( shl(40, tick) ) will be
        //      0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0000000000 instead of 0xfffffffe0000000000
        //      Therefore, we have to safely cast tick into uint256 first.
        uint256 _tick = uint256(uint24(Tick.unwrap(tick)));
        assembly {
            id := add(index, add(shl(40, _tick), shl(64, bookId)))
        }
    }

    function decode(OrderId id) internal pure returns (BookId bookId, Tick tick, uint40 index) {
        assembly {
            bookId := shr(64, id)
            tick := and(shr(40, id), 0xffffff)
            index := and(id, 0xffffffffff)
        }
    }

    function getBookId(OrderId id) internal pure returns (BookId bookId) {
        assembly {
            bookId := shr(64, id)
        }
    }

    function getTick(OrderId id) internal pure returns (Tick tick) {
        assembly {
            tick := and(shr(40, id), 0xffffff)
        }
    }

    function getIndex(OrderId id) internal pure returns (uint40 index) {
        assembly {
            index := and(id, 0xffffffffff)
        }
    }
}

File 30 of 33 : SignificantBit.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.0;

library SignificantBit {
    // http://supertech.csail.mit.edu/papers/debruijn.pdf
    uint256 internal constant DEBRUIJN_SEQ = 0x818283848586878898A8B8C8D8E8F929395969799A9B9D9E9FAAEB6BEDEEFF;
    bytes internal constant DEBRUIJN_INDEX =
        hex"0001020903110a19042112290b311a3905412245134d2a550c5d32651b6d3a7506264262237d468514804e8d2b95569d0d495ea533a966b11c886eb93bc176c9071727374353637324837e9b47af86c7155181ad4fd18ed32c9096db57d59ee30e2e4a6a5f92a6be3498aae067ddb2eb1d5989b56fd7baf33ca0c2ee77e5caf7ff0810182028303840444c545c646c7425617c847f8c949c48a4a8b087b8c0c816365272829aaec650acd0d28fdad4e22d6991bd97dfdcea58b4d6f29fede4f6fe0f1f2f3f4b5b6b607b8b93a3a7b7bf357199c5abcfd9e168bcdee9b3f1ecf5fd1e3e5a7a8aa2b670c4ced8bbe8f0f4fc3d79a1c3cde7effb78cce6facbf9f8";

    /**
     * @notice Finds the index of the least significant bit.
     * @param x The value to compute the least significant bit for. Must be a non-zero value.
     * @return ret The index of the least significant bit.
     */
    function leastSignificantBit(uint256 x) internal pure returns (uint8) {
        require(x > 0);
        uint256 index;
        assembly {
            index := shr(248, mul(and(x, add(not(x), 1)), DEBRUIJN_SEQ))
        }
        return uint8(DEBRUIJN_INDEX[index]); // can optimize with CODECOPY opcode
    }

    function mostSignificantBit(uint256 x) internal pure returns (uint8 msb) {
        require(x > 0);
        assembly {
            let f := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            x := shr(f, x)
            f := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            x := shr(f, x)
            f := shl(5, gt(x, 0xFFFFFFFF))
            msb := or(msb, f)
            x := shr(f, x)
            f := shl(4, gt(x, 0xFFFF))
            msb := or(msb, f)
            x := shr(f, x)
            f := shl(3, gt(x, 0xFF))
            msb := or(msb, f)
            x := shr(f, x)
            f := shl(2, gt(x, 0xF))
            msb := or(msb, f)
            x := shr(f, x)
            f := shl(1, gt(x, 0x3))
            msb := or(msb, f)
            x := shr(f, x)
            f := gt(x, 0x1)
            msb := or(msb, f)
        }
    }
}

File 31 of 33 : Tick.sol
// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.20;

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

type Tick is int24;

library TickLibrary {
    using Math for *;
    using TickLibrary for Tick;

    error InvalidTick();
    error InvalidPrice();
    error TickOverflow();

    int24 internal constant MAX_TICK = 2 ** 19 - 1;
    int24 internal constant MIN_TICK = -MAX_TICK;

    uint256 internal constant MIN_PRICE = 1350587;
    uint256 internal constant MAX_PRICE = 4647684107270898330752324302845848816923571339324334;

    uint256 private constant _R0 = 0xfff97272373d413259a46990;
    uint256 private constant _R1 = 0xfff2e50f5f656932ef12357c;
    uint256 private constant _R2 = 0xffe5caca7e10e4e61c3624ea;
    uint256 private constant _R3 = 0xffcb9843d60f6159c9db5883;
    uint256 private constant _R4 = 0xff973b41fa98c081472e6896;
    uint256 private constant _R5 = 0xff2ea16466c96a3843ec78b3;
    uint256 private constant _R6 = 0xfe5dee046a99a2a811c461f1;
    uint256 private constant _R7 = 0xfcbe86c7900a88aedcffc83b;
    uint256 private constant _R8 = 0xf987a7253ac413176f2b074c;
    uint256 private constant _R9 = 0xf3392b0822b70005940c7a39;
    uint256 private constant _R10 = 0xe7159475a2c29b7443b29c7f;
    uint256 private constant _R11 = 0xd097f3bdfd2022b8845ad8f7;
    uint256 private constant _R12 = 0xa9f746462d870fdf8a65dc1f;
    uint256 private constant _R13 = 0x70d869a156d2a1b890bb3df6;
    uint256 private constant _R14 = 0x31be135f97d08fd981231505;
    uint256 private constant _R15 = 0x9aa508b5b7a84e1c677de54;
    uint256 private constant _R16 = 0x5d6af8dedb81196699c329;
    uint256 private constant _R17 = 0x2216e584f5fa1ea92604;
    uint256 private constant _R18 = 0x48a170391f7dc42;
    uint256 private constant _R19 = 0x149b34;

    function validateTick(Tick tick) internal pure {
        if (Tick.unwrap(tick) > MAX_TICK || Tick.unwrap(tick) < MIN_TICK) revert InvalidTick();
    }

    modifier validatePrice(uint256 price) {
        if (price > MAX_PRICE || price < MIN_PRICE) revert InvalidPrice();
        _;
    }

    function fromPrice(uint256 price) internal pure validatePrice(price) returns (Tick) {
        unchecked {
            int24 tick = int24((int256(price).lnWad() * 42951820407860) / 2 ** 128);
            if (toPrice(Tick.wrap(tick)) > price) return Tick.wrap(tick - 1);
            return Tick.wrap(tick);
        }
    }

    function toPrice(Tick tick) internal pure returns (uint256 price) {
        validateTick(tick);
        int24 tickValue = Tick.unwrap(tick);
        uint256 absTick = uint24(tickValue < 0 ? -tickValue : tickValue);

        unchecked {
            if (absTick & 0x1 != 0) price = _R0;
            else price = 1 << 96;
            if (absTick & 0x2 != 0) price = (price * _R1) >> 96;
            if (absTick & 0x4 != 0) price = (price * _R2) >> 96;
            if (absTick & 0x8 != 0) price = (price * _R3) >> 96;
            if (absTick & 0x10 != 0) price = (price * _R4) >> 96;
            if (absTick & 0x20 != 0) price = (price * _R5) >> 96;
            if (absTick & 0x40 != 0) price = (price * _R6) >> 96;
            if (absTick & 0x80 != 0) price = (price * _R7) >> 96;
            if (absTick & 0x100 != 0) price = (price * _R8) >> 96;
            if (absTick & 0x200 != 0) price = (price * _R9) >> 96;
            if (absTick & 0x400 != 0) price = (price * _R10) >> 96;
            if (absTick & 0x800 != 0) price = (price * _R11) >> 96;
            if (absTick & 0x1000 != 0) price = (price * _R12) >> 96;
            if (absTick & 0x2000 != 0) price = (price * _R13) >> 96;
            if (absTick & 0x4000 != 0) price = (price * _R14) >> 96;
            if (absTick & 0x8000 != 0) price = (price * _R15) >> 96;
            if (absTick & 0x10000 != 0) price = (price * _R16) >> 96;
            if (absTick & 0x20000 != 0) price = (price * _R17) >> 96;
            if (absTick & 0x40000 != 0) price = (price * _R18) >> 96;
        }
        if (tickValue > 0) price = 0x1000000000000000000000000000000000000000000000000 / price;
    }

    function gt(Tick a, Tick b) internal pure returns (bool) {
        return Tick.unwrap(a) > Tick.unwrap(b);
    }

    function baseToQuote(Tick tick, uint256 base, bool roundingUp) internal pure returns (uint256) {
        return Math.divide((base * tick.toPrice()), 1 << 96, roundingUp);
    }

    function quoteToBase(Tick tick, uint256 quote, bool roundingUp) internal pure returns (uint256) {
        // @dev quote = unit(uint64) * unitSize(uint64) < 2^96
        //      We don't need to check overflow here
        return Math.divide(quote << 96, tick.toPrice(), roundingUp);
    }
}

File 32 of 33 : IBookViewer.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {BookId} from "core/libraries/BookId.sol";
import {IBookManager} from "core/interfaces/IBookManager.sol";
import {Tick} from "core/libraries/Tick.sol";

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

/**
 * @title IBookViewer
 * @notice Interface for the book viewer contract
 */
interface IBookViewer {
    struct Liquidity {
        Tick tick;
        uint64 depth;
    }

    /**
     * @notice Returns the book manager
     * @return The instance of the book manager
     */
    function bookManager() external view returns (IBookManager);

    /**
     * @notice Returns the liquidity for a specific book
     * @param id The id of the book
     * @param from The starting tick
     * @param n The number of ticks to return
     * @return liquidity An array of liquidity data
     */
    function getLiquidity(BookId id, Tick from, uint256 n) external view returns (Liquidity[] memory liquidity);

    /**
     * @notice Returns the expected input for a take order
     * @param params The parameters of the take order
     * @return takenQuoteAmount The expected taken quote amount
     * @return spentBaseAmount The expected spend base amount
     */
    function getExpectedInput(IController.TakeOrderParams memory params)
        external
        view
        returns (uint256 takenQuoteAmount, uint256 spentBaseAmount);

    /**
     * @notice Returns the expected output for a spend order
     * @param params The parameters of the spend order
     * @return takenQuoteAmount The expected taken quote amount
     * @return spentBaseAmount The expected spend base amount
     */
    function getExpectedOutput(IController.SpendOrderParams memory params)
        external
        view
        returns (uint256 takenQuoteAmount, uint256 spentBaseAmount);
}

File 33 of 33 : IController.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {OrderId} from "core/libraries/OrderId.sol";
import {BookId} from "core/libraries/BookId.sol";
import {Tick} from "core/libraries/Tick.sol";
import {IBookManager} from "core/interfaces/IBookManager.sol";

/**
 * @title IController
 * @notice Interface for the controller contract
 */
interface IController {
    // Error messages
    error InvalidAccess();
    error InvalidLength();
    error Deadline();
    error ControllerSlippage();
    error InvalidAction();

    /**
     * @notice Enum for the different actions that can be performed
     */
    enum Action {
        OPEN,
        MAKE,
        LIMIT,
        TAKE,
        SPEND,
        CLAIM,
        CANCEL
    }

    /**
     * @notice Struct for the parameters of the ERC20 permit
     */
    struct ERC20PermitParams {
        address token;
        uint256 permitAmount;
        PermitSignature signature;
    }

    /**
     * @notice Struct for the parameters of the ERC721 permit
     */
    struct ERC721PermitParams {
        uint256 tokenId;
        PermitSignature signature;
    }

    /**
     * @notice Struct for the signature of the permit
     */
    struct PermitSignature {
        uint256 deadline;
        uint8 v;
        bytes32 r;
        bytes32 s;
    }

    /**
     * @notice Struct for the parameters of the open book action
     */
    struct OpenBookParams {
        IBookManager.BookKey key;
        bytes hookData;
    }

    /**
     * @notice Struct for the parameters of the make order action
     */
    struct MakeOrderParams {
        BookId id;
        Tick tick;
        uint256 quoteAmount;
        bytes hookData;
    }

    /**
     * @notice Struct for the parameters of the limit order action
     */
    struct LimitOrderParams {
        BookId takeBookId;
        BookId makeBookId;
        uint256 limitPrice;
        Tick tick;
        uint256 quoteAmount;
        bytes takeHookData;
        bytes makeHookData;
    }

    /**
     * @notice Struct for the parameters of the take order action
     */
    struct TakeOrderParams {
        BookId id;
        uint256 limitPrice;
        uint256 quoteAmount;
        uint256 maxBaseAmount;
        bytes hookData;
    }

    /**
     * @notice Struct for the parameters of the spend order action
     */
    struct SpendOrderParams {
        BookId id;
        uint256 limitPrice;
        uint256 baseAmount;
        uint256 minQuoteAmount;
        bytes hookData;
    }

    /**
     * @notice Struct for the parameters of the claim order action
     */
    struct ClaimOrderParams {
        OrderId id;
        bytes hookData;
    }

    /**
     * @notice Struct for the parameters of the cancel order action
     */
    struct CancelOrderParams {
        OrderId id;
        uint256 leftQuoteAmount;
        bytes hookData;
    }

    /**
     * @notice Returns the book manager
     * @return The instance of the book manager
     */
    function bookManager() external view returns (IBookManager);

    /**
     * @notice Opens a book
     * @param openBookParamsList The parameters of the open book action
     * @param deadline The deadline for the action
     */
    function open(OpenBookParams[] calldata openBookParamsList, uint64 deadline) external;

    /**
     * @notice Returns the depth of a book
     * @param id The id of the book
     * @param tick The tick of the book
     * @return The depth of the book in quote amount
     */
    function getDepth(BookId id, Tick tick) external view returns (uint256);

    /**
     * @notice Returns the highest price of a book
     * @param id The id of the book
     * @return The highest price of the book with 2**96 precision
     */
    function getHighestPrice(BookId id) external view returns (uint256);

    /**
     * @notice Returns the details of an order
     * @param orderId The id of the order
     * @return provider The provider of the order
     * @return price The price of the order with 2**96 precision
     * @return openAmount The open quote amount of the order
     * @return claimableAmount The claimable base amount of the order
     */
    function getOrder(OrderId orderId)
        external
        view
        returns (address provider, uint256 price, uint256 openAmount, uint256 claimableAmount);

    /**
     * @notice Converts a price to a tick
     * @param price The price to convert
     * @return The tick
     */
    function fromPrice(uint256 price) external pure returns (Tick);

    /**
     * @notice Converts a tick to a price
     * @param tick The tick to convert
     * @return The price with 2**96 precision
     */
    function toPrice(Tick tick) external pure returns (uint256);

    /**
     * @notice Executes a list of actions
     * @dev IMPORTANT: The caller must provide `tokensToSettle` to receive appropriate tokens after execution.
     * @param actionList The list of actions to execute
     * @param paramsDataList The parameters of the actions
     * @param tokensToSettle The tokens to settle
     * @param erc20PermitParamsList The parameters of the ERC20 permits
     * @param erc721PermitParamsList The parameters of the ERC721 permits
     * @param deadline The deadline for the actions
     * @return ids The ids of the orders
     */
    function execute(
        Action[] calldata actionList,
        bytes[] calldata paramsDataList,
        address[] calldata tokensToSettle,
        ERC20PermitParams[] calldata erc20PermitParamsList,
        ERC721PermitParams[] calldata erc721PermitParamsList,
        uint64 deadline
    ) external payable returns (OrderId[] memory ids);

    /**
     * @notice Makes a list of orders
     * @dev IMPORTANT: The caller must provide `tokensToSettle` to receive appropriate tokens after execution.
     * @param orderParamsList The list of actions to make
     * @param tokensToSettle The tokens to settle
     * @param permitParamsList The parameters of the permits
     * @param deadline The deadline for the actions
     * @return ids The ids of the orders
     */
    function make(
        MakeOrderParams[] calldata orderParamsList,
        address[] calldata tokensToSettle,
        ERC20PermitParams[] calldata permitParamsList,
        uint64 deadline
    ) external payable returns (OrderId[] memory ids);

    /**
     * @notice Takes a list of orders
     * @dev IMPORTANT: The caller must provide `tokensToSettle` to receive appropriate tokens after execution.
     * @param orderParamsList The list of actions to take
     * @param tokensToSettle The tokens to settle
     * @param permitParamsList The parameters of the permits
     * @param deadline The deadline for the actions
     */
    function take(
        TakeOrderParams[] calldata orderParamsList,
        address[] calldata tokensToSettle,
        ERC20PermitParams[] calldata permitParamsList,
        uint64 deadline
    ) external payable;

    /**
     * @notice Spends to take a list of orders
     * @dev IMPORTANT: The caller must provide `tokensToSettle` to receive appropriate tokens after execution.
     * @param orderParamsList The list of actions to spend
     * @param tokensToSettle The tokens to settle
     * @param permitParamsList The parameters of the permits
     * @param deadline The deadline for the actions
     */
    function spend(
        SpendOrderParams[] calldata orderParamsList,
        address[] calldata tokensToSettle,
        ERC20PermitParams[] calldata permitParamsList,
        uint64 deadline
    ) external payable;

    /**
     * @notice Claims a list of orders
     * @dev IMPORTANT: The caller must provide `tokensToSettle` to receive appropriate tokens after execution.
     * @param orderParamsList The list of actions to claim
     * @param tokensToSettle The tokens to settle
     * @param permitParamsList The parameters of the permits
     * @param deadline The deadline for the actions
     */
    function claim(
        ClaimOrderParams[] calldata orderParamsList,
        address[] calldata tokensToSettle,
        ERC721PermitParams[] calldata permitParamsList,
        uint64 deadline
    ) external;

    /**
     * @notice Cancels a list of orders
     * @dev IMPORTANT: The caller must provide `tokensToSettle` to receive appropriate tokens after execution.
     * @param orderParamsList The list of actions to cancel
     * @param tokensToSettle The tokens to settle
     * @param permitParamsList The parameters of the permits
     * @param deadline The deadline for the actions
     */
    function cancel(
        CancelOrderParams[] calldata orderParamsList,
        address[] calldata tokensToSettle,
        ERC721PermitParams[] calldata permitParamsList,
        uint64 deadline
    ) external;
}

Settings
{
  "evmVersion": "cancun",
  "optimizer": {
    "enabled": true,
    "runs": 1000
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"contract IBookManager","name":"bookManager_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidTick","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintToInt","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"__BookViewer_init","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"bookManager","outputs":[{"internalType":"contract IBookManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"BookId","name":"id","type":"uint192"},{"internalType":"uint256","name":"limitPrice","type":"uint256"},{"internalType":"uint256","name":"quoteAmount","type":"uint256"},{"internalType":"uint256","name":"maxBaseAmount","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"internalType":"struct IController.TakeOrderParams","name":"params","type":"tuple"}],"name":"getExpectedInput","outputs":[{"internalType":"uint256","name":"takenQuoteAmount","type":"uint256"},{"internalType":"uint256","name":"spentBaseAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"BookId","name":"id","type":"uint192"},{"internalType":"uint256","name":"limitPrice","type":"uint256"},{"internalType":"uint256","name":"baseAmount","type":"uint256"},{"internalType":"uint256","name":"minQuoteAmount","type":"uint256"},{"internalType":"bytes","name":"hookData","type":"bytes"}],"internalType":"struct IController.SpendOrderParams","name":"params","type":"tuple"}],"name":"getExpectedOutput","outputs":[{"internalType":"uint256","name":"takenQuoteAmount","type":"uint256"},{"internalType":"uint256","name":"spentBaseAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"BookId","name":"id","type":"uint192"},{"internalType":"Tick","name":"tick","type":"int24"},{"internalType":"uint256","name":"n","type":"uint256"}],"name":"getLiquidity","outputs":[{"components":[{"internalType":"Tick","name":"tick","type":"int24"},{"internalType":"uint64","name":"depth","type":"uint64"}],"internalType":"struct IBookViewer.Liquidity[]","name":"liquidity","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"}]

60c060405230608052348015610013575f80fd5b506040516121db3803806121db833981016040819052610032916100dd565b338061005757604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b61006081610072565b506001600160a01b031660a05261010a565b600180546001600160a01b031916905561008b8161008e565b50565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f602082840312156100ed575f80fd5b81516001600160a01b0381168114610103575f80fd5b9392505050565b60805160a05161204061019b5f395f818161013b015281816102f3015281816103880152818161042c0152818161058c015281816106d90152818161078301528181610818015281816108bc015281816109fc01528181610b5d01528181610dec01528181610e9501528181610f66015261102101525f81816115ee0152818161161701526117c001526120405ff3fe6080604052600436106100ce575f3560e01c8063694d8a291161007c5780638da5cb5b116100575780638da5cb5b1461021f578063ad3cb1cc1461023b578063e30c397814610290578063f2fde38b146102ad575f80fd5b8063694d8a29146101cb578063715018a6146101f757806379ba50971461020b575f80fd5b80634f1ef286116100ac5780634f1ef2861461017557806350a216c61461018a57806352d1902d146101a9575f80fd5b80630202121a146100d2578063130391b61461010b5780633f322bc91461012a575b5f80fd5b3480156100dd575f80fd5b506100f16100ec366004611c66565b6102cc565b604080519283526020830191909152015b60405180910390f35b348015610116575f80fd5b506100f1610125366004611c66565b61075c565b348015610135575f80fd5b5061015d7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610102565b610188610183366004611cb4565b610bd9565b005b348015610195575f80fd5b506101886101a4366004611d01565b610bf8565b3480156101b4575f80fd5b506101bd610d33565b604051908152602001610102565b3480156101d6575f80fd5b506101ea6101e5366004611d2a565b610d61565b6040516101029190611d66565b348015610202575f80fd5b506101886110a5565b348015610216575f80fd5b506101886110b8565b34801561022a575f80fd5b505f546001600160a01b031661015d565b348015610246575f80fd5b506102836040518060400160405280600581526020017f352e302e3000000000000000000000000000000000000000000000000000000081525081565b6040516101029190611dc1565b34801561029b575f80fd5b506001546001600160a01b031661015d565b3480156102b8575f80fd5b506101886102c7366004611d01565b611101565b8051604051639b22917d60e01b81526001600160c01b0390911660048201525f90819081907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690639b22917d9060240160c060405180830381865afa158015610340573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103649190611e1f565b845160405163fcc8fc9b60e01b81526001600160c01b0390911660048201529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063fcc8fc9b90602401602060405180830381865afa1580156103d5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103f99190611ec2565b1561040957505f93849350915050565b835160405163cdc92f2d60e01b81526001600160c01b0390911660048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063cdc92f2d90602401602060405180830381865afa158015610479573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061049d9190611ee1565b90505b846040015183111580156104bb5750627fffff19600282900b135b15610755576104cc8160020b61117e565b856020015111610755575f6104ea8360a0015162ffffff1660171c90565b156104fd57838660400151039050610524565b610521848760400151035f8560a0015162ffffff166114469092919063ffffffff16565b90505b602083015167ffffffffffffffff16610542600284900b835f611493565b8161054f5761054f611efc565b049050805f0361055f5750610755565b8551604051630835177160e31b81526001600160c01b039091166004820152600283900b60248201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906341a8bb8890604401602060405180830381865afa1580156105d9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105fd9190611f10565b67ffffffffffffffff1690505f846020015167ffffffffffffffff168383116106265782610628565b835b0290505f61063c600286900b8360016114df565b90506106518660a0015162ffffff1660171c90565b156106745760a086015161066b9062ffffff16835f611501565b82039150610696565b60a08601516106899062ffffff16825f611501565b61069282611581565b0190505b805f036106a65750505050610755565b885160405163285e76b760e21b81526001600160c01b039091166004820152600286900b602482015297820197968101967f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a179dadc90604401602060405180830381865afa158015610726573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061074a9190611ee1565b9450505050506104a0565b5050915091565b8051604051639b22917d60e01b81526001600160c01b0390911660048201525f90819081907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690639b22917d9060240160c060405180830381865afa1580156107d0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107f49190611e1f565b845160405163fcc8fc9b60e01b81526001600160c01b0390911660048201529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063fcc8fc9b90602401602060405180830381865afa158015610865573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108899190611ec2565b1561089957505f93849350915050565b835160405163cdc92f2d60e01b81526001600160c01b0390911660048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063cdc92f2d90602401602060405180830381865afa158015610909573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061092d9190611ee1565b90505b627fffff19600282900b13156107555761094c8160020b61117e565b856020015111610755575f61096a8360a0015162ffffff1660171c90565b1561099b576109948587604001510360018560a0015162ffffff166114469092919063ffffffff16565b90506109a5565b8486604001510390505b602083015167ffffffffffffffff168082049082061515600116019050805f036109cf5750610755565b8551604051630835177160e31b81526001600160c01b039091166004820152600283900b60248201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906341a8bb8890604401602060405180830381865afa158015610a49573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a6d9190611f10565b67ffffffffffffffff1690505f846020015167ffffffffffffffff16838311610a965782610a98565b835b0290505f610aac600286900b8360016114df565b9050610ac18660a0015162ffffff1660171c90565b15610ae45760a0860151610adb9062ffffff16835f611501565b82039150610b06565b60a0860151610af99062ffffff16825f611501565b610b0282611581565b0190505b815f03610b165750505050610755565b604089015197820197968101968810610b325750505050610755565b885160405163285e76b760e21b81526001600160c01b039091166004820152600286900b60248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a179dadc90604401602060405180830381865afa158015610baa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bce9190611ee1565b945050505050610930565b610be16115e3565b610bea8261169a565b610bf482826116a2565b5050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000810460ff16159067ffffffffffffffff165f81158015610c425750825b90505f8267ffffffffffffffff166001148015610c5e5750303b155b905081158015610c6c575080155b15610ca3576040517ff92ee8a900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610cd757845468ff00000000000000001916680100000000000000001785555b610ce08661178f565b8315610d2b57845468ff000000000000000019168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b505050505050565b5f610d3c6117b5565b507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc90565b60608167ffffffffffffffff811115610d7c57610d7c611b1d565b604051908082528060200260200182016040528015610dc057816020015b604080518082019091525f8082526020820152815260200190600190039081610d9a5790505b50604051630835177160e31b81526001600160c01b0386166004820152600285900b60248201529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906341a8bb8890604401602060405180830381865afa158015610e39573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e5d9190611f10565b67ffffffffffffffff165f03610f095760405163285e76b760e21b81526001600160c01b0385166004820152600284900b60248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a179dadc90604401602060405180830381865afa158015610ee2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f069190611ee1565b92505b5f5b8281101561109c5762800000600285900b011561109c57604080518082018252600286900b8082529151630835177160e31b81526001600160c01b038816600482015260248101929092529060208201906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906341a8bb8890604401602060405180830381865afa158015610fab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fcf9190611f10565b67ffffffffffffffff16815250828281518110610fee57610fee611f29565b602090810291909101015260405163285e76b760e21b81526001600160c01b0386166004820152600285900b60248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a179dadc90604401602060405180830381865afa15801561106e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110929190611ee1565b9350600101610f0b565b81529392505050565b6110ad6117fe565b6110b65f61178f565b565b60015433906001600160a01b031681146110f55760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b6110fe8161178f565b50565b6111096117fe565b600180546001600160a01b03831673ffffffffffffffffffffffffffffffffffffffff1990911681179091556111465f546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b5f6111888261182a565b815f600282900b811361119b57816111a4565b6111a482611f51565b62ffffff81169150600116156111c8576bfff97272373d413259a4699092506111d9565b6c0100000000000000000000000092505b60028116156111f85760606bfff2e50f5f656932ef12357c8402901c92505b60048116156112175760606bffe5caca7e10e4e61c3624ea8402901c92505b60088116156112365760606bffcb9843d60f6159c9db58838402901c92505b60108116156112555760606bff973b41fa98c081472e68968402901c92505b60208116156112745760606bff2ea16466c96a3843ec78b38402901c92505b60408116156112935760606bfe5dee046a99a2a811c461f18402901c92505b60808116156112b25760606bfcbe86c7900a88aedcffc83b8402901c92505b6101008116156112d25760606bf987a7253ac413176f2b074c8402901c92505b6102008116156112f25760606bf3392b0822b70005940c7a398402901c92505b6104008116156113125760606be7159475a2c29b7443b29c7f8402901c92505b6108008116156113325760606bd097f3bdfd2022b8845ad8f78402901c92505b6110008116156113525760606ba9f746462d870fdf8a65dc1f8402901c92505b6120008116156113725760606b70d869a156d2a1b890bb3df68402901c92505b6140008116156113925760606b31be135f97d08fd9812315058402901c92505b6180008116156113b25760606b09aa508b5b7a84e1c677de548402901c92505b620100008116156113d25760606a5d6af8dedb81196699c3298402901c92505b620200008116156113f1576060692216e584f5fa1ea926048402901c92505b6204000081161561140e57606067048a170391f7dc428402901c92505b5f8260020b131561143f5761143c837801000000000000000000000000000000000000000000000000611f71565b92505b5050919050565b5f6207a11f19627fffff85160181831561146057815f0391505b81620f4240019050611489620f42408661147a9190611f90565b82810615158616908390040190565b9695505050505050565b5f6114d56114a38560020b61117e565b6114ad9085611f90565b6bffffffffffffffffffffffff8116151584166c010000000000000000000000009091040190565b90505b9392505050565b5f6114d5606084901b6114f48660020b61117e565b8082061515851691040190565b5f6207a11f19627fffff851601600281900b8212828161152357825f03611525565b825b62ffffff1690505f61155e61153a8389611f90565b620f424088611550578581830615151691040190565b808206151586151691040190565b9050826115735761156e81611fa7565b611575565b805b98975050505050505050565b5f7f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8211156115df576040517f24775e06000000000000000000000000000000000000000000000000000000008152600481018390526024016110ec565b5090565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148061167c57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166116707f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b031614155b156110b65760405163703e46dd60e11b815260040160405180910390fd5b6110fe6117fe565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156116fc575060408051601f3d908101601f191682019092526116f991810190611fdd565b60015b61172457604051634c9c8ce360e01b81526001600160a01b03831660048201526024016110ec565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8114611780576040517faa1d49a4000000000000000000000000000000000000000000000000000000008152600481018290526024016110ec565b61178a8383611886565b505050565b6001805473ffffffffffffffffffffffffffffffffffffffff191690556110fe816118db565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146110b65760405163703e46dd60e11b815260040160405180910390fd5b5f546001600160a01b031633146110b65760405163118cdaa760e01b81523360048201526024016110ec565b6207ffff600282900b138061184f57506118466207ffff611f51565b60020b8160020b125b156110fe576040517fce8ef7fc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61188f82611937565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156118d35761178a82826119ba565b610bf4611a2e565b5f80546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b806001600160a01b03163b5f0361196c57604051634c9c8ce360e01b81526001600160a01b03821660048201526024016110ec565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60605f80846001600160a01b0316846040516119d69190611ff4565b5f60405180830381855af49150503d805f8114611a0e576040519150601f19603f3d011682016040523d82523d5f602084013e611a13565b606091505b5091509150611a23858383611a66565b925050505b92915050565b34156110b6576040517fb398979f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606082611a7b57611a7682611adb565b6114d8565b8151158015611a9257506001600160a01b0384163b155b15611ad4576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016110ec565b50806114d8565b805115611aeb5780518082602001fd5b6040517fd6bda27500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b634e487b7160e01b5f52604160045260245ffd5b80356001600160c01b0381168114611b47575f80fd5b919050565b5f82601f830112611b5b575f80fd5b813567ffffffffffffffff80821115611b7657611b76611b1d565b604051601f8301601f19908116603f01168101908282118183101715611b9e57611b9e611b1d565b81604052838152866020858801011115611bb6575f80fd5b836020870160208301375f602085830101528094505050505092915050565b5f60a08284031215611be5575f80fd5b60405160a0810167ffffffffffffffff8282108183111715611c0957611c09611b1d565b81604052829350611c1985611b31565b83526020850135602084015260408501356040840152606085013560608401526080850135915080821115611c4c575f80fd5b50611c5985828601611b4c565b6080830152505092915050565b5f60208284031215611c76575f80fd5b813567ffffffffffffffff811115611c8c575f80fd5b611c9884828501611bd5565b949350505050565b6001600160a01b03811681146110fe575f80fd5b5f8060408385031215611cc5575f80fd5b8235611cd081611ca0565b9150602083013567ffffffffffffffff811115611ceb575f80fd5b611cf785828601611b4c565b9150509250929050565b5f60208284031215611d11575f80fd5b81356114d881611ca0565b8060020b81146110fe575f80fd5b5f805f60608486031215611d3c575f80fd5b611d4584611b31565b92506020840135611d5581611d1c565b929592945050506040919091013590565b602080825282518282018190525f919060409081850190868401855b82811015611db4578151805160020b855286015167ffffffffffffffff16868501529284019290850190600101611d82565b5091979650505050505050565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b805167ffffffffffffffff81168114611b47575f80fd5b805162ffffff81168114611b47575f80fd5b5f60c08284031215611e2f575f80fd5b60405160c0810181811067ffffffffffffffff82111715611e5257611e52611b1d565b6040528251611e6081611ca0565b8152611e6e60208401611df6565b60208201526040830151611e8181611ca0565b6040820152611e9260608401611e0d565b60608201526080830151611ea581611ca0565b6080820152611eb660a08401611e0d565b60a08201529392505050565b5f60208284031215611ed2575f80fd5b815180151581146114d8575f80fd5b5f60208284031215611ef1575f80fd5b81516114d881611d1c565b634e487b7160e01b5f52601260045260245ffd5b5f60208284031215611f20575f80fd5b6114d882611df6565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b5f8160020b627fffff198103611f6957611f69611f3d565b5f0392915050565b5f82611f8b57634e487b7160e01b5f52601260045260245ffd5b500490565b8082028115828204841417611a2857611a28611f3d565b5f7f80000000000000000000000000000000000000000000000000000000000000008203611fd757611fd7611f3d565b505f0390565b5f60208284031215611fed575f80fd5b5051919050565b5f82518060208501845e5f92019182525091905056fea26469706673582212202a6365f3211b0e4e759787a34d064cbd17ec349cb8593d91b5d1342db9f406d864736f6c63430008190033000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c636

Deployed Bytecode

0x6080604052600436106100ce575f3560e01c8063694d8a291161007c5780638da5cb5b116100575780638da5cb5b1461021f578063ad3cb1cc1461023b578063e30c397814610290578063f2fde38b146102ad575f80fd5b8063694d8a29146101cb578063715018a6146101f757806379ba50971461020b575f80fd5b80634f1ef286116100ac5780634f1ef2861461017557806350a216c61461018a57806352d1902d146101a9575f80fd5b80630202121a146100d2578063130391b61461010b5780633f322bc91461012a575b5f80fd5b3480156100dd575f80fd5b506100f16100ec366004611c66565b6102cc565b604080519283526020830191909152015b60405180910390f35b348015610116575f80fd5b506100f1610125366004611c66565b61075c565b348015610135575f80fd5b5061015d7f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c63681565b6040516001600160a01b039091168152602001610102565b610188610183366004611cb4565b610bd9565b005b348015610195575f80fd5b506101886101a4366004611d01565b610bf8565b3480156101b4575f80fd5b506101bd610d33565b604051908152602001610102565b3480156101d6575f80fd5b506101ea6101e5366004611d2a565b610d61565b6040516101029190611d66565b348015610202575f80fd5b506101886110a5565b348015610216575f80fd5b506101886110b8565b34801561022a575f80fd5b505f546001600160a01b031661015d565b348015610246575f80fd5b506102836040518060400160405280600581526020017f352e302e3000000000000000000000000000000000000000000000000000000081525081565b6040516101029190611dc1565b34801561029b575f80fd5b506001546001600160a01b031661015d565b3480156102b8575f80fd5b506101886102c7366004611d01565b611101565b8051604051639b22917d60e01b81526001600160c01b0390911660048201525f90819081907f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b031690639b22917d9060240160c060405180830381865afa158015610340573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103649190611e1f565b845160405163fcc8fc9b60e01b81526001600160c01b0390911660048201529091507f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063fcc8fc9b90602401602060405180830381865afa1580156103d5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103f99190611ec2565b1561040957505f93849350915050565b835160405163cdc92f2d60e01b81526001600160c01b0390911660048201525f907f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063cdc92f2d90602401602060405180830381865afa158015610479573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061049d9190611ee1565b90505b846040015183111580156104bb5750627fffff19600282900b135b15610755576104cc8160020b61117e565b856020015111610755575f6104ea8360a0015162ffffff1660171c90565b156104fd57838660400151039050610524565b610521848760400151035f8560a0015162ffffff166114469092919063ffffffff16565b90505b602083015167ffffffffffffffff16610542600284900b835f611493565b8161054f5761054f611efc565b049050805f0361055f5750610755565b8551604051630835177160e31b81526001600160c01b039091166004820152600283900b60248201525f907f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b0316906341a8bb8890604401602060405180830381865afa1580156105d9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105fd9190611f10565b67ffffffffffffffff1690505f846020015167ffffffffffffffff168383116106265782610628565b835b0290505f61063c600286900b8360016114df565b90506106518660a0015162ffffff1660171c90565b156106745760a086015161066b9062ffffff16835f611501565b82039150610696565b60a08601516106899062ffffff16825f611501565b61069282611581565b0190505b805f036106a65750505050610755565b885160405163285e76b760e21b81526001600160c01b039091166004820152600286900b602482015297820197968101967f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063a179dadc90604401602060405180830381865afa158015610726573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061074a9190611ee1565b9450505050506104a0565b5050915091565b8051604051639b22917d60e01b81526001600160c01b0390911660048201525f90819081907f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b031690639b22917d9060240160c060405180830381865afa1580156107d0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107f49190611e1f565b845160405163fcc8fc9b60e01b81526001600160c01b0390911660048201529091507f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063fcc8fc9b90602401602060405180830381865afa158015610865573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108899190611ec2565b1561089957505f93849350915050565b835160405163cdc92f2d60e01b81526001600160c01b0390911660048201525f907f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063cdc92f2d90602401602060405180830381865afa158015610909573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061092d9190611ee1565b90505b627fffff19600282900b13156107555761094c8160020b61117e565b856020015111610755575f61096a8360a0015162ffffff1660171c90565b1561099b576109948587604001510360018560a0015162ffffff166114469092919063ffffffff16565b90506109a5565b8486604001510390505b602083015167ffffffffffffffff168082049082061515600116019050805f036109cf5750610755565b8551604051630835177160e31b81526001600160c01b039091166004820152600283900b60248201525f907f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b0316906341a8bb8890604401602060405180830381865afa158015610a49573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a6d9190611f10565b67ffffffffffffffff1690505f846020015167ffffffffffffffff16838311610a965782610a98565b835b0290505f610aac600286900b8360016114df565b9050610ac18660a0015162ffffff1660171c90565b15610ae45760a0860151610adb9062ffffff16835f611501565b82039150610b06565b60a0860151610af99062ffffff16825f611501565b610b0282611581565b0190505b815f03610b165750505050610755565b604089015197820197968101968810610b325750505050610755565b885160405163285e76b760e21b81526001600160c01b039091166004820152600286900b60248201527f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063a179dadc90604401602060405180830381865afa158015610baa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bce9190611ee1565b945050505050610930565b610be16115e3565b610bea8261169a565b610bf482826116a2565b5050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000810460ff16159067ffffffffffffffff165f81158015610c425750825b90505f8267ffffffffffffffff166001148015610c5e5750303b155b905081158015610c6c575080155b15610ca3576040517ff92ee8a900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b845467ffffffffffffffff191660011785558315610cd757845468ff00000000000000001916680100000000000000001785555b610ce08661178f565b8315610d2b57845468ff000000000000000019168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b505050505050565b5f610d3c6117b5565b507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc90565b60608167ffffffffffffffff811115610d7c57610d7c611b1d565b604051908082528060200260200182016040528015610dc057816020015b604080518082019091525f8082526020820152815260200190600190039081610d9a5790505b50604051630835177160e31b81526001600160c01b0386166004820152600285900b60248201529091507f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b0316906341a8bb8890604401602060405180830381865afa158015610e39573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e5d9190611f10565b67ffffffffffffffff165f03610f095760405163285e76b760e21b81526001600160c01b0385166004820152600284900b60248201527f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063a179dadc90604401602060405180830381865afa158015610ee2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f069190611ee1565b92505b5f5b8281101561109c5762800000600285900b011561109c57604080518082018252600286900b8082529151630835177160e31b81526001600160c01b038816600482015260248101929092529060208201906001600160a01b037f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c63616906341a8bb8890604401602060405180830381865afa158015610fab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fcf9190611f10565b67ffffffffffffffff16815250828281518110610fee57610fee611f29565b602090810291909101015260405163285e76b760e21b81526001600160c01b0386166004820152600285900b60248201527f000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c6366001600160a01b03169063a179dadc90604401602060405180830381865afa15801561106e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110929190611ee1565b9350600101610f0b565b81529392505050565b6110ad6117fe565b6110b65f61178f565b565b60015433906001600160a01b031681146110f55760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b6110fe8161178f565b50565b6111096117fe565b600180546001600160a01b03831673ffffffffffffffffffffffffffffffffffffffff1990911681179091556111465f546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b5f6111888261182a565b815f600282900b811361119b57816111a4565b6111a482611f51565b62ffffff81169150600116156111c8576bfff97272373d413259a4699092506111d9565b6c0100000000000000000000000092505b60028116156111f85760606bfff2e50f5f656932ef12357c8402901c92505b60048116156112175760606bffe5caca7e10e4e61c3624ea8402901c92505b60088116156112365760606bffcb9843d60f6159c9db58838402901c92505b60108116156112555760606bff973b41fa98c081472e68968402901c92505b60208116156112745760606bff2ea16466c96a3843ec78b38402901c92505b60408116156112935760606bfe5dee046a99a2a811c461f18402901c92505b60808116156112b25760606bfcbe86c7900a88aedcffc83b8402901c92505b6101008116156112d25760606bf987a7253ac413176f2b074c8402901c92505b6102008116156112f25760606bf3392b0822b70005940c7a398402901c92505b6104008116156113125760606be7159475a2c29b7443b29c7f8402901c92505b6108008116156113325760606bd097f3bdfd2022b8845ad8f78402901c92505b6110008116156113525760606ba9f746462d870fdf8a65dc1f8402901c92505b6120008116156113725760606b70d869a156d2a1b890bb3df68402901c92505b6140008116156113925760606b31be135f97d08fd9812315058402901c92505b6180008116156113b25760606b09aa508b5b7a84e1c677de548402901c92505b620100008116156113d25760606a5d6af8dedb81196699c3298402901c92505b620200008116156113f1576060692216e584f5fa1ea926048402901c92505b6204000081161561140e57606067048a170391f7dc428402901c92505b5f8260020b131561143f5761143c837801000000000000000000000000000000000000000000000000611f71565b92505b5050919050565b5f6207a11f19627fffff85160181831561146057815f0391505b81620f4240019050611489620f42408661147a9190611f90565b82810615158616908390040190565b9695505050505050565b5f6114d56114a38560020b61117e565b6114ad9085611f90565b6bffffffffffffffffffffffff8116151584166c010000000000000000000000009091040190565b90505b9392505050565b5f6114d5606084901b6114f48660020b61117e565b8082061515851691040190565b5f6207a11f19627fffff851601600281900b8212828161152357825f03611525565b825b62ffffff1690505f61155e61153a8389611f90565b620f424088611550578581830615151691040190565b808206151586151691040190565b9050826115735761156e81611fa7565b611575565b805b98975050505050505050565b5f7f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8211156115df576040517f24775e06000000000000000000000000000000000000000000000000000000008152600481018390526024016110ec565b5090565b306001600160a01b037f0000000000000000000000002e062c260f9e011e6d483d662d255cb3d013c79116148061167c57507f0000000000000000000000002e062c260f9e011e6d483d662d255cb3d013c7916001600160a01b03166116707f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b6001600160a01b031614155b156110b65760405163703e46dd60e11b815260040160405180910390fd5b6110fe6117fe565b816001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa9250505080156116fc575060408051601f3d908101601f191682019092526116f991810190611fdd565b60015b61172457604051634c9c8ce360e01b81526001600160a01b03831660048201526024016110ec565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc8114611780576040517faa1d49a4000000000000000000000000000000000000000000000000000000008152600481018290526024016110ec565b61178a8383611886565b505050565b6001805473ffffffffffffffffffffffffffffffffffffffff191690556110fe816118db565b306001600160a01b037f0000000000000000000000002e062c260f9e011e6d483d662d255cb3d013c79116146110b65760405163703e46dd60e11b815260040160405180910390fd5b5f546001600160a01b031633146110b65760405163118cdaa760e01b81523360048201526024016110ec565b6207ffff600282900b138061184f57506118466207ffff611f51565b60020b8160020b125b156110fe576040517fce8ef7fc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61188f82611937565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a28051156118d35761178a82826119ba565b610bf4611a2e565b5f80546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b806001600160a01b03163b5f0361196c57604051634c9c8ce360e01b81526001600160a01b03821660048201526024016110ec565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60605f80846001600160a01b0316846040516119d69190611ff4565b5f60405180830381855af49150503d805f8114611a0e576040519150601f19603f3d011682016040523d82523d5f602084013e611a13565b606091505b5091509150611a23858383611a66565b925050505b92915050565b34156110b6576040517fb398979f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b606082611a7b57611a7682611adb565b6114d8565b8151158015611a9257506001600160a01b0384163b155b15611ad4576040517f9996b3150000000000000000000000000000000000000000000000000000000081526001600160a01b03851660048201526024016110ec565b50806114d8565b805115611aeb5780518082602001fd5b6040517fd6bda27500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b634e487b7160e01b5f52604160045260245ffd5b80356001600160c01b0381168114611b47575f80fd5b919050565b5f82601f830112611b5b575f80fd5b813567ffffffffffffffff80821115611b7657611b76611b1d565b604051601f8301601f19908116603f01168101908282118183101715611b9e57611b9e611b1d565b81604052838152866020858801011115611bb6575f80fd5b836020870160208301375f602085830101528094505050505092915050565b5f60a08284031215611be5575f80fd5b60405160a0810167ffffffffffffffff8282108183111715611c0957611c09611b1d565b81604052829350611c1985611b31565b83526020850135602084015260408501356040840152606085013560608401526080850135915080821115611c4c575f80fd5b50611c5985828601611b4c565b6080830152505092915050565b5f60208284031215611c76575f80fd5b813567ffffffffffffffff811115611c8c575f80fd5b611c9884828501611bd5565b949350505050565b6001600160a01b03811681146110fe575f80fd5b5f8060408385031215611cc5575f80fd5b8235611cd081611ca0565b9150602083013567ffffffffffffffff811115611ceb575f80fd5b611cf785828601611b4c565b9150509250929050565b5f60208284031215611d11575f80fd5b81356114d881611ca0565b8060020b81146110fe575f80fd5b5f805f60608486031215611d3c575f80fd5b611d4584611b31565b92506020840135611d5581611d1c565b929592945050506040919091013590565b602080825282518282018190525f919060409081850190868401855b82811015611db4578151805160020b855286015167ffffffffffffffff16868501529284019290850190600101611d82565b5091979650505050505050565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b805167ffffffffffffffff81168114611b47575f80fd5b805162ffffff81168114611b47575f80fd5b5f60c08284031215611e2f575f80fd5b60405160c0810181811067ffffffffffffffff82111715611e5257611e52611b1d565b6040528251611e6081611ca0565b8152611e6e60208401611df6565b60208201526040830151611e8181611ca0565b6040820152611e9260608401611e0d565b60608201526080830151611ea581611ca0565b6080820152611eb660a08401611e0d565b60a08201529392505050565b5f60208284031215611ed2575f80fd5b815180151581146114d8575f80fd5b5f60208284031215611ef1575f80fd5b81516114d881611d1c565b634e487b7160e01b5f52601260045260245ffd5b5f60208284031215611f20575f80fd5b6114d882611df6565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b5f8160020b627fffff198103611f6957611f69611f3d565b5f0392915050565b5f82611f8b57634e487b7160e01b5f52601260045260245ffd5b500490565b8082028115828204841417611a2857611a28611f3d565b5f7f80000000000000000000000000000000000000000000000000000000000000008203611fd757611fd7611f3d565b505f0390565b5f60208284031215611fed575f80fd5b5051919050565b5f82518060208501845e5f92019182525091905056fea26469706673582212202a6365f3211b0e4e759787a34d064cbd17ec349cb8593d91b5d1342db9f406d864736f6c63430008190033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c636

-----Decoded View---------------
Arg [0] : bookManager_ (address): 0xD4aD5Ed9E1436904624b6dB8B1BE31f36317C636

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000d4ad5ed9e1436904624b6db8b1be31f36317c636


Block Transaction Gas Used Reward
view all blocks produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.