ETH Price: $2,681.51 (+5.49%)

Transaction Decoder

Block:
16820558 at Mar-13-2023 05:29:59 PM +UTC
Transaction Fee:
0.004310169454519005 ETH $11.56
Gas Used:
141,495 Gas / 30.461637899 Gwei

Emitted Events:

214 StarNFTV4.Approval( owner=0xa6feeedd8f67d058f4ec73c2acb4549a9b89f1bc, approved=0x00000000...000000000, tokenId=2688 )
215 StarNFTV4.Transfer( from=0xa6feeedd8f67d058f4ec73c2acb4549a9b89f1bc, to=[Sender] 0x68f697130e9626d1ccbaabde9a19a2789492071b, tokenId=2688 )
216 GnosisSafeProxy.0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d( 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d, 0x00000000000000000000000020f780a973856b93f63670377900c1d2a50a77c4, 000000000000000000000000000000000000000000000000000028048c5ec000 )
217 ElementEx.0x9c248aa1a265aa616f707b979d57f4529bb63a4fc34dc7fc61fdddc18410f74e( 0x9c248aa1a265aa616f707b979d57f4529bb63a4fc34dc7fc61fdddc18410f74e, 8a46392446a904d6fd8a54f164e52399ec33680e234e9f7b53ff96b83a91c8ab, 000000000000000000000000a6feeedd8f67d058f4ec73c2acb4549a9b89f1bc, 00000000000000000000000068f697130e9626d1ccbaabde9a19a2789492071b, 0000000000000000000000000000000000000000000000000000000000000033, 000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, 000000000000000000000000000000000000000000000000001f438daa060000, 0000000000000000000000000000000000000000000000000000000000000120, 0000000000000000000000004f912cc688142386fc208462976ff7ee8169dffd, 0000000000000000000000000000000000000000000000000000000000000a80, 0000000000000000000000000000000000000000000000000000000000000001, 00000000000000000000000000ca62445b06a9adc1879a44485b4efdcb7b75f3, 000000000000000000000000000000000000000000000000000028048c5ec000 )

Account State Difference:

  Address   Before After State Difference Code
0x00cA6244...dcB7b75F3 45.23503689648634555 Eth45.23508089648634555 Eth0.000044
0x20F780A9...2a50a77c4
(Element: ElementEx)
0x4F912cC6...E8169DffD
(Manta-builder)
54.222412021011610418 Eth54.222426170511610418 Eth0.0000141495
0x68F69713...89492071b
0.021198177429197692 Eth
Nonce: 18
0.008088007974678687 Eth
Nonce: 19
0.013110169454519005
0xA6FEEeDD...a9B89f1Bc 0.000000014595278 Eth0.008756014595278 Eth0.008756

Execution Trace

ETH 0.0088 ReservoirV6_0_0.execute( executionInfos= )
  • ETH 0.0088 ElementModule.acceptETHListingERC721( order=[{name:maker, type:address, order:1, indexed:false, value:0xA6FEEeDD8f67D058F4EC73c2acB4549a9B89f1Bc, valueString:0xA6FEEeDD8f67D058F4EC73c2acB4549a9B89f1Bc}, {name:taker, type:address, order:2, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:expiry, type:uint256, order:3, indexed:false, value:7209799543768454456, valueString:7209799543768454456}, {name:nonce, type:uint256, order:4, indexed:false, value:51, valueString:51}, {name:erc20Token, type:address, order:5, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:erc20TokenAmount, type:uint256, order:6, indexed:false, value:8756000000000000, valueString:8756000000000000}, {name:fees, type:tuple[], order:7, indexed:false}, {name:nft, type:address, order:8, indexed:false, value:0x4F912cC688142386fc208462976Ff7EE8169DffD, valueString:0x4F912cC688142386fc208462976Ff7EE8169DffD}, {name:nftId, type:uint256, order:9, indexed:false, value:2688, valueString:2688}], signature=[{name:signatureType, type:uint8, order:1, indexed:false, value:0, valueString:0}, {name:v, type:uint8, order:2, indexed:false, value:27, valueString:27}, {name:r, type:bytes32, order:3, indexed:false, value:0D54B9874D518E4F94346DB05985DB6329CF6B8519551408B775A4A502BBA61D, valueString:0D54B9874D518E4F94346DB05985DB6329CF6B8519551408B775A4A502BBA61D}, {name:s, type:bytes32, order:4, indexed:false, value:3237FDE392AADBEC54AD39B8D9F8488A5881411365FE18E5EF8672E948BE8138, valueString:3237FDE392AADBEC54AD39B8D9F8488A5881411365FE18E5EF8672E948BE8138}], params=[{name:fillTo, type:address, order:1, indexed:false, value:0x68F697130E9626d1cCBAaBde9a19a2789492071b, valueString:0x68F697130E9626d1cCBAaBde9a19a2789492071b}, {name:refundTo, type:address, order:2, indexed:false, value:0x68F697130E9626d1cCBAaBde9a19a2789492071b, valueString:0x68F697130E9626d1cCBAaBde9a19a2789492071b}, {name:revertIfIncomplete, type:bool, order:3, indexed:false, value:true, valueString:True}, {name:amount, type:uint256, order:4, indexed:false, value:8800000000000000, valueString:8800000000000000}], fees= )
    • ETH 0.0088 ElementEx.b18d619f( )
      • ETH 0.0088 ERC721OrdersFeature.buyERC721Ex( sellOrder=[{name:maker, type:address, order:1, indexed:false, value:0xA6FEEeDD8f67D058F4EC73c2acB4549a9B89f1Bc, valueString:0xA6FEEeDD8f67D058F4EC73c2acB4549a9B89f1Bc}, {name:taker, type:address, order:2, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:expiry, type:uint256, order:3, indexed:false, value:7209799543768454456, valueString:7209799543768454456}, {name:nonce, type:uint256, order:4, indexed:false, value:51, valueString:51}, {name:erc20Token, type:address, order:5, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:erc20TokenAmount, type:uint256, order:6, indexed:false, value:8756000000000000, valueString:8756000000000000}, {name:fees, type:tuple[], order:7, indexed:false}, {name:nft, type:address, order:8, indexed:false, value:0x4F912cC688142386fc208462976Ff7EE8169DffD, valueString:0x4F912cC688142386fc208462976Ff7EE8169DffD}, {name:nftId, type:uint256, order:9, indexed:false, value:2688, valueString:2688}], signature=[{name:signatureType, type:uint8, order:1, indexed:false, value:0, valueString:0}, {name:v, type:uint8, order:2, indexed:false, value:27, valueString:27}, {name:r, type:bytes32, order:3, indexed:false, value:0D54B9874D518E4F94346DB05985DB6329CF6B8519551408B775A4A502BBA61D, valueString:0D54B9874D518E4F94346DB05985DB6329CF6B8519551408B775A4A502BBA61D}, {name:s, type:bytes32, order:4, indexed:false, value:3237FDE392AADBEC54AD39B8D9F8488A5881411365FE18E5EF8672E948BE8138, valueString:3237FDE392AADBEC54AD39B8D9F8488A5881411365FE18E5EF8672E948BE8138}], taker=0x68F697130E9626d1cCBAaBde9a19a2789492071b, takerData=0x )
        • Null: 0x000...001.8a463924( )
        • StarNFTV4.transferFrom( from=0xA6FEEeDD8f67D058F4EC73c2acB4549a9B89f1Bc, to=0x68F697130E9626d1cCBAaBde9a19a2789492071b, tokenId=2688 )
        • ETH 0.008756 0xa6feeedd8f67d058f4ec73c2acb4549a9b89f1bc.CALL( )
        • ETH 0.000044 GnosisSafeProxy.CALL( )
          • ETH 0.000044 GnosisSafe.DELEGATECALL( )
            File 1 of 7: ReservoirV6_0_0
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
            import {Address} from "@openzeppelin/contracts/utils/Address.sol";
            contract ReservoirV6_0_0 is ReentrancyGuard {
                using Address for address;
                // --- Structs ---
                struct ExecutionInfo {
                    address module;
                    bytes data;
                    uint256 value;
                }
                struct AmountCheckInfo {
                    address target;
                    bytes data;
                    uint256 threshold;
                }
                // --- Errors ---
                error UnsuccessfulExecution();
                error UnsuccessfulPayment();
                // --- Modifiers ---
                modifier refundETH() {
                    _;
                    uint256 leftover = address(this).balance;
                    if (leftover > 0) {
                        (bool success, ) = payable(msg.sender).call{value: leftover}("");
                        if (!success) {
                            revert UnsuccessfulPayment();
                        }
                    }
                }
                // --- Fallback ---
                receive() external payable {}
                // --- Public ---
                // Trigger a set of executions atomically
                function execute(ExecutionInfo[] calldata executionInfos)
                    external
                    payable
                    nonReentrant
                    refundETH
                {
                    uint256 length = executionInfos.length;
                    for (uint256 i = 0; i < length; ) {
                        _executeInternal(executionInfos[i]);
                        unchecked {
                            ++i;
                        }
                    }
                }
                // Trigger a set of executions with amount checking. As opposed to the regular
                // `execute` method, `executeWithAmountCheck` supports stopping the executions
                // once the provided amount check reaches a certain value. This is useful when
                // trying to fill orders with slippage (eg. provide multiple orders and try to
                // fill until a certain balance is reached). In order to be flexible, checking
                // the amount is done generically by calling the `target` contract with `data`.
                // For example, this could be used to check the ERC721 total owned balance (by
                // using `balanceOf(owner)`), the ERC1155 total owned balance per token id (by
                // using `balanceOf(owner, tokenId)`), but also for checking the ERC1155 total
                // owned balance per multiple token ids (by using a custom contract that wraps
                // `balanceOfBatch(owners, tokenIds)`).
                function executeWithAmountCheck(
                    ExecutionInfo[] calldata executionInfos,
                    AmountCheckInfo calldata amountCheckInfo
                ) external payable nonReentrant refundETH {
                    // Cache some data for efficiency
                    address target = amountCheckInfo.target;
                    bytes calldata data = amountCheckInfo.data;
                    uint256 threshold = amountCheckInfo.threshold;
                    uint256 length = executionInfos.length;
                    for (uint256 i = 0; i < length; ) {
                        // Check the amount and break if it exceeds the threshold
                        uint256 amount = _getAmount(target, data);
                        if (amount >= threshold) {
                            break;
                        }
                        _executeInternal(executionInfos[i]);
                        unchecked {
                            ++i;
                        }
                    }
                }
                // --- Internal ---
                function _executeInternal(ExecutionInfo calldata executionInfo) internal {
                    address module = executionInfo.module;
                    // Ensure the target is a contract
                    if (!module.isContract()) {
                        revert UnsuccessfulExecution();
                    }
                    (bool success, ) = module.call{value: executionInfo.value}(
                        executionInfo.data
                    );
                    if (!success) {
                        revert UnsuccessfulExecution();
                    }
                }
                function _getAmount(address target, bytes calldata data)
                    internal
                    view
                    returns (uint256 amount)
                {
                    // Ensure the target is a contract
                    if (!target.isContract()) {
                        revert UnsuccessfulExecution();
                    }
                    (bool success, bytes memory result) = target.staticcall(data);
                    if (!success) {
                        revert UnsuccessfulExecution();
                    }
                    amount = abi.decode(result, (uint256));
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Contract module that helps prevent reentrant calls to a function.
             *
             * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
             * available, which can be applied to functions to make sure there are no nested
             * (reentrant) calls to them.
             *
             * Note that because there is a single `nonReentrant` guard, functions marked as
             * `nonReentrant` may not call one another. This can be worked around by making
             * those functions `private`, and then adding `external` `nonReentrant` entry
             * points to them.
             *
             * TIP: If you would like to learn more about reentrancy and alternative ways
             * to protect against it, check out our blog post
             * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
             */
            abstract contract ReentrancyGuard {
                // Booleans are more expensive than uint256 or any type that takes up a full
                // word because each write operation emits an extra SLOAD to first read the
                // slot's contents, replace the bits taken up by the boolean, and then write
                // back. This is the compiler's defense against contract upgrades and
                // pointer aliasing, and it cannot be disabled.
                // The values being non-zero value makes deployment a bit more expensive,
                // but in exchange the refund on every call to nonReentrant will be lower in
                // amount. Since refunds are capped to a percentage of the total
                // transaction's gas, it is best to keep them low in cases like this one, to
                // increase the likelihood of the full refund coming into effect.
                uint256 private constant _NOT_ENTERED = 1;
                uint256 private constant _ENTERED = 2;
                uint256 private _status;
                constructor() {
                    _status = _NOT_ENTERED;
                }
                /**
                 * @dev Prevents a contract from calling itself, directly or indirectly.
                 * Calling a `nonReentrant` function from another `nonReentrant`
                 * function is not supported. It is possible to prevent this from happening
                 * by making the `nonReentrant` function external, and making it call a
                 * `private` function that does the actual work.
                 */
                modifier nonReentrant() {
                    // On the first call to nonReentrant, _notEntered will be true
                    require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                    // Any calls to nonReentrant after this point will fail
                    _status = _ENTERED;
                    _;
                    // By storing the original value once again, a refund is triggered (see
                    // https://eips.ethereum.org/EIPS/eip-2200)
                    _status = _NOT_ENTERED;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize, which returns 0 for contracts in
                    // construction, since the code is only stored at the end of the
                    // constructor execution.
                    uint256 size;
                    assembly {
                        size := extcodesize(account)
                    }
                    return size > 0;
                }
                /**
                 * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    (bool success, ) = recipient.call{value: amount}("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
                /**
                 * @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, it is bubbled up by this
                 * function (like regular Solidity function calls).
                 *
                 * 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.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCall(target, data, "Address: low-level call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                 * `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, errorMessage);
                }
                /**
                 * @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`.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(address(this).balance >= value, "Address: insufficient balance for call");
                    require(isContract(target), "Address: call to non-contract");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    return functionStaticCall(target, data, "Address: low-level static call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    require(isContract(target), "Address: static call to non-contract");
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(isContract(target), "Address: delegate call to non-contract");
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        // 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
                            assembly {
                                let returndata_size := mload(returndata)
                                revert(add(32, returndata), returndata_size)
                            }
                        } else {
                            revert(errorMessage);
                        }
                    }
                }
            }
            

            File 2 of 7: StarNFTV4
            /*
                Copyright 2022 Project Galaxy.
                Licensed under the Apache License, Version 2.0 (the "License");
                you may not use this file except in compliance with the License.
                You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
                Unless required by applicable law or agreed to in writing, software
                distributed under the License is distributed on an "AS IS" BASIS,
                WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                See the License for the specific language governing permissions and
                limitations under the License.
                SPDX-License-Identifier: Apache License, Version 2.0
            */
            pragma solidity 0.7.6;
            import "IERC721.sol";
            import "IERC721Receiver.sol";
            import "IERC721Metadata.sol";
            import "Address.sol";
            import "Strings.sol";
            import "Ownable.sol";
            import "ERC165.sol";
            import "IStarNFT.sol";
            /**
             * @dev Fork https://github.com/generalgalactic/ERC721S and implement IStarNFT interface
             */
            contract StarNFTV4 is Ownable, ERC165, IERC721, IERC721Metadata, IStarNFT {
                using Address for address;
                using Strings for uint256;
                /* ============ State Variables ============ */
                struct Star {
                    uint160 owner;
                    uint96 cid; // Max value is 7.9E28, enough to store campaign id
                }
                // Token name
                string private _name;
                // Token symbol
                string private _symbol;
                // Total number of tokens burned
                uint256 private _burnCount;
                // Array of all tokens storing the owner's address and the campaign id
                Star[] private _tokens;
                // Mapping owner address to token count
                mapping(address => uint256) private _balances;
                // Mapping from token ID to approved address
                mapping(uint256 => address) private _tokenApprovals;
                // Mapping from owner to operator approvals
                mapping(address => mapping(address => bool)) private _operatorApprovals;
                // Mint and burn star.
                mapping(address => bool) private _minters;
                // Default allow transfer
                bool private _transferable = true;
                // Base token URI
                string private _baseURI;
                /* ============ Events ============ */
                // Add new minter
                event EventMinterAdded(address indexed newMinter);
                // Remove old minter
                event EventMinterRemoved(address indexed oldMinter);
                /* ============ Modifiers ============ */
                /**
                 * Only minter.
                 */
                modifier onlyMinter() {
                    require(_minters[msg.sender], "StarNFT: must be minter");
                    _;
                }
                /**
                 * Only allow transfer.
                 */
                modifier onlyTransferable() {
                    require(_transferable, "StarNFT: must transferable");
                    _;
                }
                /**
                 * @dev Initializes the contract
                 */
                constructor() {
                    // Initialize zero index value
                    Star memory _star = Star(0, 0);
                    _tokens.push(_star);
                }
                /**
                 * @dev See {IERC165-supportsInterface}.
                 */
                function supportsInterface(bytes4 interfaceId)
                public
                view
                override(ERC165, IERC165)
                returns (bool)
                {
                    return
                    interfaceId == type(IERC721).interfaceId ||
                    interfaceId == type(IERC721Metadata).interfaceId ||
                    interfaceId == type(IStarNFT).interfaceId ||
                    super.supportsInterface(interfaceId);
                }
                /**
                 * @dev Is this address a minters.
                 */
                function minters(address account) public view returns (bool) {
                    return _minters[account];
                }
                /**
                 * @dev Is this contract allow nft transfer.
                 */
                function transferable() public view returns (bool) {
                    return _transferable;
                }
                /**
                 * @dev Returns the base URI for nft.
                 */
                function baseURI() public view returns (string memory) {
                    return _baseURI;
                }
                /**
                 * @dev Get Star NFT CID.
                 */
                function cid(uint256 tokenId) public view returns (uint256) {
                    require(_exists(tokenId), "StarNFT: StarNFT does not exist");
                    return _tokens[tokenId].cid;
                }
                /**
                 * @dev Get Star NFT owner
                 */
                function getNumMinted() public view override returns (uint256) {
                    return _tokens.length-1;
                }
                /**
                 * @dev See {IERC721Enumerable-totalSupply}.
                 */
                function totalSupply() public view returns (uint256) {
                    return getNumMinted() - _burnCount;
                }
                /**
                 * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
                 * This is implementation is O(n) and should not be
                 * called by other contracts.
                 */
                function tokenOfOwnerByIndex(address owner, uint256 index)
                public
                view
                returns (uint256)
                {
                    uint256 currentIndex = 0;
                    for (uint256 i = 1; i < _tokens.length; i++) {
                        if (isOwnerOf(owner, i)) {
                            if (currentIndex == index) {
                                return i;
                            }
                            currentIndex += 1;
                        }
                    }
                    revert("ERC721Enumerable: owner index out of bounds");
                }
                /**
                 * @dev See {IERC721-balanceOf}.
                 */
                function balanceOf(address owner)
                public
                view
                override
                returns (uint256)
                {
                    require(
                        owner != address(0),
                        "ERC721: balance query for the zero address"
                    );
                    return _balances[owner];
                }
                /**
                 * @dev See {IERC721-ownerOf}.
                 */
                function ownerOf(uint256 tokenId)
                public
                view
                override
                returns (address)
                {
                    require(
                        _exists(tokenId),
                        "ERC721: owner query for nonexistent token"
                    );
                    return address(_tokens[tokenId].owner);
                }
                /**
                 * @dev See {IStarNFT-isOwnerOf}.
                 */
                function isOwnerOf(address account, uint256 id)
                public
                view
                override
                returns (bool)
                {
                    address owner = ownerOf(id);
                    return owner == account;
                }
                /**
                 * @dev See {IERC721Metadata-name}.
                 */
                function name() public view virtual override returns (string memory) {
                    return _name;
                }
                /**
                 * @dev See {IERC721Metadata-symbol}.
                 */
                function symbol() public view virtual override returns (string memory) {
                    return _symbol;
                }
                /**
                 * @dev See {IERC721Metadata-tokenURI}.
                 */
                function tokenURI(uint256 tokenId)
                public
                view
                override
                returns (string memory)
                {
                    require(
                        _exists(tokenId),
                        "ERC721Metadata: URI query for nonexistent token"
                    );
                    return
                    bytes(_baseURI).length > 0
                    ? string(abi.encodePacked(_baseURI, tokenId.toString(), ".json"))
                    : "";
                }
                /**
                 * @dev See {IERC721-approve}.
                 */
                function approve(address to, uint256 tokenId) public override {
                    address owner = ownerOf(tokenId);
                    require(to != owner, "ERC721: approval to current owner");
                    require(
                        _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
                        "ERC721: approve caller is not owner nor approved for all"
                    );
                    _approve(to, tokenId);
                }
                /**
                 * @dev See {IERC721-getApproved}.
                 */
                function getApproved(uint256 tokenId)
                public
                view
                override
                returns (address)
                {
                    require(
                        _exists(tokenId),
                        "ERC721: approved query for nonexistent token"
                    );
                    return _tokenApprovals[tokenId];
                }
                /**
                 * @dev See {IERC721-setApprovalForAll}.
                 */
                function setApprovalForAll(address operator, bool approved)
                public
                override
                {
                    require(operator != _msgSender(), "ERC721: approve to caller");
                    _operatorApprovals[_msgSender()][operator] = approved;
                    emit ApprovalForAll(_msgSender(), operator, approved);
                }
                /**
                 * @dev See {IERC721-isApprovedForAll}.
                 */
                function isApprovedForAll(address owner, address operator)
                public
                view
                override
                returns (bool)
                {
                    return _operatorApprovals[owner][operator];
                }
                /**
                 * @dev See {IERC721-transferFrom}.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) public onlyTransferable override {
                    //solhint-disable-next-line max-line-length
                    require(
                        _isApprovedOrOwner(_msgSender(), tokenId),
                        "ERC721: transfer caller is not owner nor approved"
                    );
                    _transfer(from, to, tokenId);
                }
                /**
                 * @dev See {IERC721-safeTransferFrom}.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId
                ) public onlyTransferable override {
                    safeTransferFrom(from, to, tokenId, "");
                }
                /**
                 * @dev See {IERC721-safeTransferFrom}.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                ) public onlyTransferable override {
                    require(
                        _isApprovedOrOwner(_msgSender(), tokenId),
                        "ERC721: transfer caller is not owner nor approved"
                    );
                    _safeTransfer(from, to, tokenId, _data);
                }
                /**
                 * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
                 * are aware of the ERC721 protocol to prevent tokens from being forever locked.
                 *
                 * `_data` is additional data, it has no specified format and it is sent in call to `to`.
                 *
                 * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
                 * implement alternative mechanisms to perform token transfer, such as signature-based.
                 *
                 * Requirements:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must exist and be owned by `from`.
                 * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                 *
                 * Emits a {Transfer} event.
                 */
                function _safeTransfer(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                ) internal {
                    _transfer(from, to, tokenId);
                    require(
                        _checkOnERC721Received(from, to, tokenId, _data),
                        "ERC721: transfer to non ERC721Receiver implementer"
                    );
                }
                /**
                 * @dev Returns whether `tokenId` exists.
                 *
                 * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
                 *
                 * Tokens start existing when they are minted (`_mint`),
                 * and stop existing when they are burned (`_burn`).
                 */
                function _exists(uint256 tokenId) internal view returns (bool) {
                    return tokenId > 0 && tokenId <= getNumMinted() && _tokens[tokenId].owner != 0x0;
                }
                /**
                 * @dev Returns whether `spender` is allowed to manage `tokenId`.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function _isApprovedOrOwner(address spender, uint256 tokenId)
                internal
                view
                returns (bool)
                {
                    address owner = ownerOf(tokenId);
                    return (spender == owner ||
                    getApproved(tokenId) == spender ||
                    isApprovedForAll(owner, spender));
                }
                /* ============ External Functions ============ */
                function mint(address account, uint256 cid)
                external
                override
                onlyMinter
                returns (uint256)
                {
                    require(account != address(0), "StarNFT: mint to the zero address");
                    uint256 tokenId = _tokens.length;
                    Star memory star = Star(uint160(account), uint96(cid));
                    _balances[account] += 1;
                    _tokens.push(star);
                    require(
                        _checkOnERC721Received(address(0), account, tokenId, ""),
                        "StarNFT: transfer to non ERC721Receiver implementer"
                    );
                    emit Transfer(address(0), account, tokenId);
                    return tokenId;
                }
                function mintBatch(
                    address account,
                    uint256 amount,
                    uint256[] calldata cidArr
                ) external override onlyMinter returns (uint256[] memory) {
                    require(account != address(0), "StarNFT: mint to the zero address");
                    uint256[] memory ids = new uint256[](amount);
                    _balances[account] += amount;
                    for (uint256 i = 0; i < ids.length; i++) {
                        uint256 tokenId = _tokens.length;
                        Star memory star = Star(uint160(account), uint96(cidArr[i]));
                        ids[i] = tokenId;
                        _tokens.push(star);
                        require(
                            _checkOnERC721Received(address(0), account, tokenId, ""),
                            "StarNFT: transfer to non ERC721Receiver implementer"
                        );
                        emit Transfer(address(0), account, tokenId);
                    }
                    return ids;
                }
                function burn(address account, uint256 id) external override onlyMinter {
                    require(
                        _isApprovedOrOwner(_msgSender(), id),
                        "StarNFT: caller is not approved or owner"
                    );
                    require(isOwnerOf(account, id), "StarNFT: not owner");
                    // Clear approvals
                    _approve(address(0), id);
                    _burnCount++;
                    _balances[account] -= 1;
                    _tokens[id].owner = 0;
                    _tokens[id].cid = 0;
                    emit Transfer(account, address(0), id);
                }
                function burnBatch(address account, uint256[] calldata ids)
                external
                override
                onlyMinter
                {
                    _burnCount += ids.length;
                    _balances[account] -= ids.length;
                    for (uint256 i = 0; i < ids.length; i++) {
                        uint256 tokenId = ids[i];
                        require(
                            _isApprovedOrOwner(_msgSender(), tokenId),
                            "StarNFT: caller is not approved or owner"
                        );
                        require(isOwnerOf(account, tokenId), "StarNFT: not owner");
                        // Clear approvals
                        _approve(address(0), tokenId);
                        _tokens[tokenId].owner = 0;
                        _tokens[tokenId].cid = 0;
                        emit Transfer(account, address(0), tokenId);
                    }
                }
                /**
                 * @dev Transfers `tokenId` from `from` to `to`.
                 *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - `tokenId` token must be owned by `from`.
                 *
                 * Emits a {Transfer} event.
                 */
                function _transfer(
                    address from,
                    address to,
                    uint256 tokenId
                ) internal virtual {
                    require(
                        isOwnerOf(from, tokenId),
                        "ERC721: transfer of token that is not own"
                    );
                    require(to != address(0), "ERC721: transfer to the zero address");
                    // Clear approvals from the previous owner
                    _approve(address(0), tokenId);
                    _balances[from] -= 1;
                    _balances[to] += 1;
                    _tokens[tokenId].owner = uint160(to);
                    emit Transfer(from, to, tokenId);
                }
                /**
                 * @dev Approve `to` to operate on `tokenId`
                 *
                 * Emits a {Approval} event.
                 */
                function _approve(address to, uint256 tokenId) internal virtual {
                    _tokenApprovals[tokenId] = to;
                    emit Approval(ownerOf(tokenId), to, tokenId);
                }
                /**
                 * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
                 * The call is not executed if the target address is not a contract.
                 *
                 * @param from address representing the previous owner of the given token ID
                 * @param to target address that will receive the tokens
                 * @param tokenId uint256 ID of the token to be transferred
                 * @param _data bytes optional data to send along with the call
                 * @return bool whether the call correctly returned the expected magic value
                 */
                function _checkOnERC721Received(
                    address from,
                    address to,
                    uint256 tokenId,
                    bytes memory _data
                ) private returns (bool) {
                    if (to.isContract()) {
                        try
                        IERC721Receiver(to).onERC721Received(
                            _msgSender(),
                            from,
                            tokenId,
                            _data
                        )
                        returns (bytes4 retval) {
                            return retval == IERC721Receiver.onERC721Received.selector;
                        } catch (bytes memory reason) {
                            if (reason.length == 0) {
                                revert(
                                "ERC721: transfer to non ERC721Receiver implementer"
                                );
                            } else {
                                assembly {
                                    revert(add(32, reason), mload(reason))
                                }
                            }
                        }
                    }
                    return true;
                }
                /* ============ Util Functions ============ */
                /**
                 * @dev Sets a new baseURI for all token types.
                 */
                function setURI(string calldata newURI) external onlyOwner {
                    _baseURI = newURI;
                }
                /**
                 * @dev Sets a new transferable for all token types.
                 */
                function setTransferable(bool transferable) external onlyOwner {
                    _transferable = transferable;
                }
                /**
                 * @dev Sets a new name for all token types.
                 */
                function setName(string calldata newName) external onlyOwner {
                    _name = newName;
                }
                /**
                 * @dev Sets a new symbol for all token types.
                 */
                function setSymbol(string calldata newSymbol) external onlyOwner {
                    _symbol = newSymbol;
                }
                /**
                 * @dev Add a new minter.
                 */
                function addMinter(address minter) external onlyOwner {
                    require(minter != address(0), "minter must not be null address");
                    require(!_minters[minter], "minter already added");
                    _minters[minter] = true;
                    emit EventMinterAdded(minter);
                }
                /**
                 * @dev Remove a old minter.
                 */
                function removeMinter(address minter) external onlyOwner {
                    require(_minters[minter], "minter does not exist");
                    delete _minters[minter];
                    emit EventMinterRemoved(minter);
                }
            }// SPDX-License-Identifier: MIT
            pragma solidity >=0.6.2 <0.8.0;
            import "IERC165.sol";
            /**
             * @dev Required interface of an ERC721 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`, checking first that contract recipients
                 * are aware of the ERC721 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 be 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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
                 *
                 * 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 Returns the account approved for `tokenId` token.
                 *
                 * Requirements:
                 *
                 * - `tokenId` must exist.
                 */
                function getApproved(uint256 tokenId) external view returns (address operator);
                /**
                 * @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 caller.
                 *
                 * Emits an {ApprovalForAll} event.
                 */
                function setApprovalForAll(address operator, bool _approved) external;
                /**
                 * @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);
                /**
                  * @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;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.0 <0.8.0;
            /**
             * @dev Interface of the ERC165 standard, as defined in the
             * https://eips.ethereum.org/EIPS/eip-165[EIP].
             *
             * 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[EIP 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);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.0 <0.8.0;
            /**
             * @title ERC721 token receiver interface
             * @dev Interface for any contract that wants to support safeTransfers
             * from ERC721 asset contracts.
             */
            interface IERC721Receiver {
                /**
                 * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
                 * by `operator` from `from`, this function is called.
                 *
                 * It must return its Solidity selector to confirm the token transfer.
                 * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
                 *
                 * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
                 */
                function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.2 <0.8.0;
            import "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);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.2 <0.8.0;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize, which returns 0 for contracts in
                    // construction, since the code is only stored at the end of the
                    // constructor execution.
                    uint256 size;
                    // solhint-disable-next-line no-inline-assembly
                    assembly { size := extcodesize(account) }
                    return size > 0;
                }
                /**
                 * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                    (bool success, ) = recipient.call{ value: amount }("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
                /**
                 * @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, it is bubbled up by this
                 * function (like regular Solidity function calls).
                 *
                 * 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.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                  return functionCall(target, data, "Address: low-level call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                 * `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, errorMessage);
                }
                /**
                 * @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`.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                    require(address(this).balance >= value, "Address: insufficient balance for call");
                    require(isContract(target), "Address: call to non-contract");
                    // solhint-disable-next-line avoid-low-level-calls
                    (bool success, bytes memory returndata) = target.call{ value: value }(data);
                    return _verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    return functionStaticCall(target, data, "Address: low-level static call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                    require(isContract(target), "Address: static call to non-contract");
                    // solhint-disable-next-line avoid-low-level-calls
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return _verifyCallResult(success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                    require(isContract(target), "Address: delegate call to non-contract");
                    // solhint-disable-next-line avoid-low-level-calls
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return _verifyCallResult(success, returndata, errorMessage);
                }
                function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        // 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
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                let returndata_size := mload(returndata)
                                revert(add(32, returndata), returndata_size)
                            }
                        } else {
                            revert(errorMessage);
                        }
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.0 <0.8.0;
            /**
             * @dev String operations.
             */
            library Strings {
                /**
                 * @dev Converts a `uint256` to its ASCII `string` representation.
                 */
                function toString(uint256 value) internal pure returns (string memory) {
                    // Inspired by OraclizeAPI's implementation - MIT licence
                    // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                    if (value == 0) {
                        return "0";
                    }
                    uint256 temp = value;
                    uint256 digits;
                    while (temp != 0) {
                        digits++;
                        temp /= 10;
                    }
                    bytes memory buffer = new bytes(digits);
                    uint256 index = digits - 1;
                    temp = value;
                    while (temp != 0) {
                        buffer[index--] = bytes1(uint8(48 + temp % 10));
                        temp /= 10;
                    }
                    return string(buffer);
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.0 <0.8.0;
            import "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.
             *
             * By default, the owner account will be the one that deploys the contract. 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;
                event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                /**
                 * @dev Initializes the contract setting the deployer as the initial owner.
                 */
                constructor () internal {
                    address msgSender = _msgSender();
                    _owner = msgSender;
                    emit OwnershipTransferred(address(0), msgSender);
                }
                /**
                 * @dev Returns the address of the current owner.
                 */
                function owner() public view virtual returns (address) {
                    return _owner;
                }
                /**
                 * @dev Throws if called by any account other than the owner.
                 */
                modifier onlyOwner() {
                    require(owner() == _msgSender(), "Ownable: caller is not the owner");
                    _;
                }
                /**
                 * @dev Leaves the contract without owner. It will not be possible to call
                 * `onlyOwner` functions anymore. Can only be called by the current owner.
                 *
                 * NOTE: Renouncing ownership will leave the contract without an owner,
                 * thereby removing any functionality that is only available to the owner.
                 */
                function renounceOwnership() public virtual onlyOwner {
                    emit OwnershipTransferred(_owner, address(0));
                    _owner = 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 {
                    require(newOwner != address(0), "Ownable: new owner is the zero address");
                    emit OwnershipTransferred(_owner, newOwner);
                    _owner = newOwner;
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.0 <0.8.0;
            /*
             * @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 GSN 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 payable) {
                    return msg.sender;
                }
                function _msgData() internal view virtual returns (bytes memory) {
                    this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                    return msg.data;
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.6.0 <0.8.0;
            import "IERC165.sol";
            /**
             * @dev Implementation of the {IERC165} interface.
             *
             * Contracts may inherit from this and call {_registerInterface} to declare
             * their support of an interface.
             */
            abstract contract ERC165 is IERC165 {
                /*
                 * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
                 */
                bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
                /**
                 * @dev Mapping of interface ids to whether or not it's supported.
                 */
                mapping(bytes4 => bool) private _supportedInterfaces;
                constructor () internal {
                    // Derived contracts need only register support for their own interfaces,
                    // we register support for ERC165 itself here
                    _registerInterface(_INTERFACE_ID_ERC165);
                }
                /**
                 * @dev See {IERC165-supportsInterface}.
                 *
                 * Time complexity O(1), guaranteed to always use less than 30 000 gas.
                 */
                function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                    return _supportedInterfaces[interfaceId];
                }
                /**
                 * @dev Registers the contract as an implementer of the interface defined by
                 * `interfaceId`. Support of the actual ERC165 interface is automatic and
                 * registering its interface id is not required.
                 *
                 * See {IERC165-supportsInterface}.
                 *
                 * Requirements:
                 *
                 * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
                 */
                function _registerInterface(bytes4 interfaceId) internal virtual {
                    require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
                    _supportedInterfaces[interfaceId] = true;
                }
            }
            /*
                Copyright 2021 Project Galaxy.
                Licensed under the Apache License, Version 2.0 (the "License");
                you may not use this file except in compliance with the License.
                You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
                Unless required by applicable law or agreed to in writing, software
                distributed under the License is distributed on an "AS IS" BASIS,
                WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                See the License for the specific language governing permissions and
                limitations under the License.
                SPDX-License-Identifier: Apache License, Version 2.0
            */
            pragma solidity 0.7.6;
            /**
             * @title IStarNFT
             * @author Galaxy Protocol
             *
             * Interface for operating with StarNFTs.
             */
            interface IStarNFT {
                /* ============ Events =============== */
                /* ============ Functions ============ */
                function isOwnerOf(address, uint256) external view returns (bool);
                function getNumMinted() external view returns (uint256);
                // mint
                function mint(address account, uint256 powah) external returns (uint256);
                function mintBatch(address account, uint256 amount, uint256[] calldata powahArr) external returns (uint256[] memory);
                function burn(address account, uint256 id) external;
                function burnBatch(address account, uint256[] calldata ids) external;
            }
            

            File 3 of 7: GnosisSafeProxy
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            
            /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
            /// @author Richard Meissner - <[email protected]>
            interface IProxy {
                function masterCopy() external view returns (address);
            }
            
            /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
            /// @author Stefan George - <[email protected]>
            /// @author Richard Meissner - <[email protected]>
            contract GnosisSafeProxy {
                // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
                // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
                address internal singleton;
            
                /// @dev Constructor function sets address of singleton contract.
                /// @param _singleton Singleton address.
                constructor(address _singleton) {
                    require(_singleton != address(0), "Invalid singleton address provided");
                    singleton = _singleton;
                }
            
                /// @dev Fallback function forwards all transactions and returns all received return data.
                fallback() external payable {
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
                        // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
                        if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                            mstore(0, _singleton)
                            return(0, 0x20)
                        }
                        calldatacopy(0, 0, calldatasize())
                        let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
                        returndatacopy(0, 0, returndatasize())
                        if eq(success, 0) {
                            revert(0, returndatasize())
                        }
                        return(0, returndatasize())
                    }
                }
            }
            
            /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
            /// @author Stefan George - <[email protected]>
            contract GnosisSafeProxyFactory {
                event ProxyCreation(GnosisSafeProxy proxy, address singleton);
            
                /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                /// @param singleton Address of singleton contract.
                /// @param data Payload for message call sent to new proxy contract.
                function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
                    proxy = new GnosisSafeProxy(singleton);
                    if (data.length > 0)
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                                revert(0, 0)
                            }
                        }
                    emit ProxyCreation(proxy, singleton);
                }
            
                /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
                function proxyRuntimeCode() public pure returns (bytes memory) {
                    return type(GnosisSafeProxy).runtimeCode;
                }
            
                /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
                function proxyCreationCode() public pure returns (bytes memory) {
                    return type(GnosisSafeProxy).creationCode;
                }
            
                /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
                ///      This method is only meant as an utility to be called from other methods
                /// @param _singleton Address of singleton contract.
                /// @param initializer Payload for message call sent to new proxy contract.
                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                function deployProxyWithNonce(
                    address _singleton,
                    bytes memory initializer,
                    uint256 saltNonce
                ) internal returns (GnosisSafeProxy proxy) {
                    // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
                    bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
                    bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
                    }
                    require(address(proxy) != address(0), "Create2 call failed");
                }
            
                /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                /// @param _singleton Address of singleton contract.
                /// @param initializer Payload for message call sent to new proxy contract.
                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                function createProxyWithNonce(
                    address _singleton,
                    bytes memory initializer,
                    uint256 saltNonce
                ) public returns (GnosisSafeProxy proxy) {
                    proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                    if (initializer.length > 0)
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                                revert(0, 0)
                            }
                        }
                    emit ProxyCreation(proxy, _singleton);
                }
            
                /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
                /// @param _singleton Address of singleton contract.
                /// @param initializer Payload for message call sent to new proxy contract.
                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
                function createProxyWithCallback(
                    address _singleton,
                    bytes memory initializer,
                    uint256 saltNonce,
                    IProxyCreationCallback callback
                ) public returns (GnosisSafeProxy proxy) {
                    uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
                    proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
                    if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
                }
            
                /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
                ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
                ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
                /// @param _singleton Address of singleton contract.
                /// @param initializer Payload for message call sent to new proxy contract.
                /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                function calculateCreateProxyWithNonceAddress(
                    address _singleton,
                    bytes calldata initializer,
                    uint256 saltNonce
                ) external returns (GnosisSafeProxy proxy) {
                    proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                    revert(string(abi.encodePacked(proxy)));
                }
            }
            
            interface IProxyCreationCallback {
                function proxyCreated(
                    GnosisSafeProxy proxy,
                    address _singleton,
                    bytes calldata initializer,
                    uint256 saltNonce
                ) external;
            }

            File 4 of 7: ElementEx
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "./migrations/LibBootstrap.sol";
            import "./features/BootstrapFeature.sol";
            import "./storage/LibProxyStorage.sol";
            /// @dev An extensible proxy contract that serves as a universal entry point for
            ///      interacting with the 0x protocol.
            contract ElementEx {
                /// @dev Construct this contract and register the `BootstrapFeature` feature.
                ///      After constructing this contract, `bootstrap()` should be called
                ///      by `bootstrap()` to seed the initial feature set.
                /// @param bootstrapper Who can call `bootstrap()`.
                constructor(address bootstrapper) {
                    // Temporarily create and register the bootstrap feature.
                    // It will deregister itself after `bootstrap()` has been called.
                    BootstrapFeature bootstrap = new BootstrapFeature(bootstrapper);
                    LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] =
                        address(bootstrap);
                }
                // solhint-disable state-visibility
                /// @dev Forwards calls to the appropriate implementation contract.
                fallback() external payable {
                    bytes memory b = msg.data;
                    bytes4 selector;
                    assembly {
                        selector := mload(add(b, 32))
                        // Solidity does not require us to clean the trailing bytes.
                        // We do it anyway
                        selector := and(selector, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
                    }
                    address impl = LibProxyStorage.getStorage().impls[selector];
                    if (impl == address(0)) {
                        revert("METHOD_NOT_IMPLEMENTED");
                    }
                    (bool success, bytes memory resultData) = impl.delegatecall(msg.data);
                    if (!success) {
                        _revertWithData(resultData);
                    }
                    _returnWithData(resultData);
                }
                /// @dev Fallback for just receiving ether.
                receive() external payable {}
                // solhint-enable state-visibility
                /// @dev Get the implementation contract of a registered function.
                /// @param selector The function selector.
                /// @return impl The implementation contract address.
                function getFunctionImplementation(bytes4 selector) public view returns (address impl) {
                    return LibProxyStorage.getStorage().impls[selector];
                }
                /// @dev Revert with arbitrary bytes.
                /// @param data Revert data.
                function _revertWithData(bytes memory data) private pure {
                    assembly { revert(add(data, 32), mload(data)) }
                }
                /// @dev Return with arbitrary bytes.
                /// @param data Return data.
                function _returnWithData(bytes memory data) private pure {
                    assembly { return(add(data, 32), mload(data)) }
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            library LibBootstrap {
                /// @dev Magic bytes returned by the bootstrapper to indicate success.
                ///      This is `keccack('BOOTSTRAP_SUCCESS')`.
                bytes4 internal constant BOOTSTRAP_SUCCESS = 0xd150751b;
                /// @dev Perform a delegatecall and ensure it returns the magic bytes.
                /// @param target The call target.
                /// @param data The call data.
                function delegatecallBootstrapFunction(address target, bytes memory data) internal {
                    (bool success, bytes memory resultData) = target.delegatecall(data);
                    if (!success ||
                        resultData.length != 32 ||
                        abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS)
                    {
                        revert("BOOTSTRAP_CALL_FAILED");
                    }
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "../migrations/LibBootstrap.sol";
            import "../storage/LibProxyStorage.sol";
            import "./interfaces/IBootstrapFeature.sol";
            /// @dev Detachable `bootstrap()` feature.
            contract BootstrapFeature is IBootstrapFeature {
                // solhint-disable state-visibility,indent
                /// @dev The ZeroEx contract.
                ///      This has to be immutable to persist across delegatecalls.
                address immutable private _deployer;
                /// @dev The implementation address of this contract.
                ///      This has to be immutable to persist across delegatecalls.
                address immutable private _implementation;
                /// @dev The deployer.
                ///      This has to be immutable to persist across delegatecalls.
                address immutable private _bootstrapCaller;
                // solhint-enable state-visibility,indent
                /// @dev Construct this contract and set the bootstrap migration contract.
                ///      After constructing this contract, `bootstrap()` should be called
                ///      to seed the initial feature set.
                /// @param bootstrapCaller The allowed caller of `bootstrap()`.
                constructor(address bootstrapCaller) {
                    _deployer = msg.sender;
                    _implementation = address(this);
                    _bootstrapCaller = bootstrapCaller;
                }
                /// @dev Bootstrap the initial feature set of this contract by delegatecalling
                ///      into `target`. Before exiting the `bootstrap()` function will
                ///      deregister itself from the proxy to prevent being called again.
                /// @param target The bootstrapper contract address.
                /// @param callData The call data to execute on `target`.
                function bootstrap(address target, bytes calldata callData) external override {
                    // Only the bootstrap caller can call this function.
                    if (msg.sender != _bootstrapCaller) {
                        revert("INVALID_BOOTSTRAP_CALLER");
                    }
                    // Deregister.
                    LibProxyStorage.getStorage().impls[this.bootstrap.selector] = address(0);
                    // Self-destruct.
                    BootstrapFeature(_implementation).die();
                    // Call the bootstrapper.
                    LibBootstrap.delegatecallBootstrapFunction(target, callData);
                }
                /// @dev Self-destructs this contract.
                ///      Can only be called by the deployer.
                function die() external {
                    require(address(this) == _implementation);
                    if (msg.sender != _deployer) {
                        revert("INVALID_DIE_CALLER");
                    }
                    selfdestruct(payable(msg.sender));
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "./LibStorage.sol";
            /// @dev Storage helpers for the proxy contract.
            library LibProxyStorage {
                /// @dev Storage bucket for proxy contract.
                struct Storage {
                    // Mapping of function selector -> function implementation
                    mapping(bytes4 => address) impls;
                }
                /// @dev Get the storage bucket for this contract.
                function getStorage() internal pure returns (Storage storage stor) {
                    uint256 storageSlot = LibStorage.STORAGE_ID_PROXY;
                    // Dip into assembly to change the slot pointed to by the local
                    // variable `stor`.
                    // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
                    assembly { stor.slot := storageSlot }
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            /// @dev Detachable `bootstrap()` feature.
            interface IBootstrapFeature {
                /// @dev Bootstrap the initial feature set of this contract by delegatecalling
                ///      into `target`. Before exiting the `bootstrap()` function will
                ///      deregister itself from the proxy to prevent being called again.
                /// @param target The bootstrapper contract address.
                /// @param callData The call data to execute on `target`.
                function bootstrap(address target, bytes calldata callData) external;
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            /// @dev Common storage helpers
            library LibStorage {
                /// @dev What to bit-shift a storage ID by to get its slot.
                ///      This gives us a maximum of 2**128 inline fields in each bucket.
                uint256 constant STORAGE_ID_PROXY = 1 << 128;
                uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128;
                uint256 constant STORAGE_ID_OWNABLE = 3 << 128;
                uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128;
                uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128;
                uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128;
            }
            

            File 5 of 7: ElementModule
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Contract module that helps prevent reentrant calls to a function.
             *
             * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
             * available, which can be applied to functions to make sure there are no nested
             * (reentrant) calls to them.
             *
             * Note that because there is a single `nonReentrant` guard, functions marked as
             * `nonReentrant` may not call one another. This can be worked around by making
             * those functions `private`, and then adding `external` `nonReentrant` entry
             * points to them.
             *
             * TIP: If you would like to learn more about reentrancy and alternative ways
             * to protect against it, check out our blog post
             * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
             */
            abstract contract ReentrancyGuard {
                // Booleans are more expensive than uint256 or any type that takes up a full
                // word because each write operation emits an extra SLOAD to first read the
                // slot's contents, replace the bits taken up by the boolean, and then write
                // back. This is the compiler's defense against contract upgrades and
                // pointer aliasing, and it cannot be disabled.
                // The values being non-zero value makes deployment a bit more expensive,
                // but in exchange the refund on every call to nonReentrant will be lower in
                // amount. Since refunds are capped to a percentage of the total
                // transaction's gas, it is best to keep them low in cases like this one, to
                // increase the likelihood of the full refund coming into effect.
                uint256 private constant _NOT_ENTERED = 1;
                uint256 private constant _ENTERED = 2;
                uint256 private _status;
                constructor() {
                    _status = _NOT_ENTERED;
                }
                /**
                 * @dev Prevents a contract from calling itself, directly or indirectly.
                 * Calling a `nonReentrant` function from another `nonReentrant`
                 * function is not supported. It is possible to prevent this from happening
                 * by making the `nonReentrant` function external, and making it call a
                 * `private` function that does the actual work.
                 */
                modifier nonReentrant() {
                    _nonReentrantBefore();
                    _;
                    _nonReentrantAfter();
                }
                function _nonReentrantBefore() private {
                    // On the first call to nonReentrant, _status will be _NOT_ENTERED
                    require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                    // Any calls to nonReentrant after this point will fail
                    _status = _ENTERED;
                }
                function _nonReentrantAfter() private {
                    // By storing the original value once again, a refund is triggered (see
                    // https://eips.ethereum.org/EIPS/eip-2200)
                    _status = _NOT_ENTERED;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
            pragma solidity ^0.8.0;
            import "../../utils/introspection/IERC165.sol";
            /**
             * @dev Required interface of an ERC1155 compliant contract, as defined in the
             * https://eips.ethereum.org/EIPS/eip-1155[EIP].
             *
             * _Available since v3.1._
             */
            interface IERC1155 is IERC165 {
                /**
                 * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
                 */
                event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
                /**
                 * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
                 * transfers.
                 */
                event TransferBatch(
                    address indexed operator,
                    address indexed from,
                    address indexed to,
                    uint256[] ids,
                    uint256[] values
                );
                /**
                 * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
                 * `approved`.
                 */
                event ApprovalForAll(address indexed account, address indexed operator, bool approved);
                /**
                 * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
                 *
                 * If an {URI} event was emitted for `id`, the standard
                 * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
                 * returned by {IERC1155MetadataURI-uri}.
                 */
                event URI(string value, uint256 indexed id);
                /**
                 * @dev Returns the amount of tokens of token type `id` owned by `account`.
                 *
                 * Requirements:
                 *
                 * - `account` cannot be the zero address.
                 */
                function balanceOf(address account, uint256 id) external view returns (uint256);
                /**
                 * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
                 *
                 * Requirements:
                 *
                 * - `accounts` and `ids` must have the same length.
                 */
                function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
                    external
                    view
                    returns (uint256[] memory);
                /**
                 * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
                 *
                 * Emits an {ApprovalForAll} event.
                 *
                 * Requirements:
                 *
                 * - `operator` cannot be the caller.
                 */
                function setApprovalForAll(address operator, bool approved) external;
                /**
                 * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
                 *
                 * See {setApprovalForAll}.
                 */
                function isApprovedForAll(address account, address operator) external view returns (bool);
                /**
                 * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
                 *
                 * Emits a {TransferSingle} event.
                 *
                 * Requirements:
                 *
                 * - `to` cannot be the zero address.
                 * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
                 * - `from` must have a balance of tokens of type `id` of at least `amount`.
                 * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
                 * acceptance magic value.
                 */
                function safeTransferFrom(
                    address from,
                    address to,
                    uint256 id,
                    uint256 amount,
                    bytes calldata data
                ) external;
                /**
                 * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
                 *
                 * Emits a {TransferBatch} event.
                 *
                 * Requirements:
                 *
                 * - `ids` and `amounts` must have the same length.
                 * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
                 * acceptance magic value.
                 */
                function safeBatchTransferFrom(
                    address from,
                    address to,
                    uint256[] calldata ids,
                    uint256[] calldata amounts,
                    bytes calldata data
                ) external;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
             * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
             *
             * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
             * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
             * need to send a transaction, and thus is not required to hold Ether at all.
             */
            interface IERC20Permit {
                /**
                 * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                 * given ``owner``'s signed approval.
                 *
                 * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                 * ordering also apply here.
                 *
                 * Emits an {Approval} event.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 * - `deadline` must be a timestamp in the future.
                 * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                 * over the EIP712-formatted function arguments.
                 * - the signature must use ``owner``'s current nonce (see {nonces}).
                 *
                 * For more information on the signature format, see the
                 * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                 * section].
                 */
                function permit(
                    address owner,
                    address spender,
                    uint256 value,
                    uint256 deadline,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) external;
                /**
                 * @dev Returns the current nonce for `owner`. This value must be
                 * included whenever a signature is generated for {permit}.
                 *
                 * Every successful call to {permit} increases ``owner``'s nonce by one. This
                 * prevents a signature from being used multiple times.
                 */
                function nonces(address owner) external view returns (uint256);
                /**
                 * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                 */
                // solhint-disable-next-line func-name-mixedcase
                function DOMAIN_SEPARATOR() external view returns (bytes32);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            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 amount of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
                /**
                 * @dev Returns the amount of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
                /**
                 * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
                /**
                 * @dev Moves `amount` tokens from `from` to `to` using the
                 * allowance mechanism. `amount` 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 amount
                ) external returns (bool);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
            pragma solidity ^0.8.0;
            import "../IERC20.sol";
            import "../extensions/draft-IERC20Permit.sol";
            import "../../../utils/Address.sol";
            /**
             * @title SafeERC20
             * @dev Wrappers around ERC20 operations that throw on failure (when the token
             * contract returns false). Tokens that return no value (and instead revert or
             * throw on failure) are also supported, non-reverting calls are assumed to be
             * successful.
             * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
             * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
             */
            library SafeERC20 {
                using Address for address;
                function safeTransfer(
                    IERC20 token,
                    address to,
                    uint256 value
                ) internal {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                }
                function safeTransferFrom(
                    IERC20 token,
                    address from,
                    address to,
                    uint256 value
                ) internal {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                }
                /**
                 * @dev Deprecated. This function has issues similar to the ones found in
                 * {IERC20-approve}, and its usage is discouraged.
                 *
                 * Whenever possible, use {safeIncreaseAllowance} and
                 * {safeDecreaseAllowance} instead.
                 */
                function safeApprove(
                    IERC20 token,
                    address spender,
                    uint256 value
                ) internal {
                    // safeApprove should only be called when setting an initial allowance,
                    // or when resetting it to zero. To increase and decrease it, use
                    // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                    require(
                        (value == 0) || (token.allowance(address(this), spender) == 0),
                        "SafeERC20: approve from non-zero to non-zero allowance"
                    );
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                }
                function safeIncreaseAllowance(
                    IERC20 token,
                    address spender,
                    uint256 value
                ) internal {
                    uint256 newAllowance = token.allowance(address(this), spender) + value;
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                }
                function safeDecreaseAllowance(
                    IERC20 token,
                    address spender,
                    uint256 value
                ) internal {
                    unchecked {
                        uint256 oldAllowance = token.allowance(address(this), spender);
                        require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                        uint256 newAllowance = oldAllowance - value;
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                    }
                }
                function safePermit(
                    IERC20Permit token,
                    address owner,
                    address spender,
                    uint256 value,
                    uint256 deadline,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) internal {
                    uint256 nonceBefore = token.nonces(owner);
                    token.permit(owner, spender, value, deadline, v, r, s);
                    uint256 nonceAfter = token.nonces(owner);
                    require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                }
                /**
                 * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                 * on the return value: the return value is optional (but if data is returned, it must not be false).
                 * @param token The token targeted by the call.
                 * @param data The call data (encoded using abi.encode or one of its variants).
                 */
                function _callOptionalReturn(IERC20 token, bytes memory data) private {
                    // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                    // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                    // the target address contains contract code and also asserts for success in the low-level call.
                    bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                    if (returndata.length > 0) {
                        // Return data is optional
                        require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
            pragma solidity ^0.8.0;
            import "../../utils/introspection/IERC165.sol";
            /**
             * @dev Required interface of an ERC721 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 ERC721 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 ERC721
                 * 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 caller.
                 *
                 * 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);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
            pragma solidity ^0.8.1;
            /**
             * @dev Collection of functions related to the address type
             */
            library Address {
                /**
                 * @dev Returns true if `account` is a contract.
                 *
                 * [IMPORTANT]
                 * ====
                 * It is unsafe to assume that an address for which this function returns
                 * false is an externally-owned account (EOA) and not a contract.
                 *
                 * Among others, `isContract` will return false for the following
                 * types of addresses:
                 *
                 *  - an externally-owned account
                 *  - a contract in construction
                 *  - an address where a contract will be created
                 *  - an address where a contract lived, but was destroyed
                 * ====
                 *
                 * [IMPORTANT]
                 * ====
                 * You shouldn't rely on `isContract` to protect against flash loan attacks!
                 *
                 * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                 * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                 * constructor.
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize/address.code.length, which returns 0
                    // for contracts in construction, since the code is only stored at the end
                    // of the constructor execution.
                    return account.code.length > 0;
                }
                /**
                 * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                 */
                function sendValue(address payable recipient, uint256 amount) internal {
                    require(address(this).balance >= amount, "Address: insufficient balance");
                    (bool success, ) = recipient.call{value: amount}("");
                    require(success, "Address: unable to send value, recipient may have reverted");
                }
                /**
                 * @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, it is bubbled up by this
                 * function (like regular Solidity function calls).
                 *
                 * 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.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                 * `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, 0, errorMessage);
                }
                /**
                 * @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`.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value
                ) internal returns (bytes memory) {
                    return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                 * with `errorMessage` as a fallback revert reason when `target` reverts.
                 *
                 * _Available since v3.1._
                 */
                function functionCallWithValue(
                    address target,
                    bytes memory data,
                    uint256 value,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    require(address(this).balance >= value, "Address: insufficient balance for call");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                    return functionStaticCall(target, data, "Address: low-level static call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a static call.
                 *
                 * _Available since v3.3._
                 */
                function functionStaticCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                    return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                }
                /**
                 * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                 * but performing a delegate call.
                 *
                 * _Available since v3.4._
                 */
                function functionDelegateCall(
                    address target,
                    bytes memory data,
                    string memory errorMessage
                ) internal returns (bytes memory) {
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                 * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                 *
                 * _Available since v4.8._
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    if (success) {
                        if (returndata.length == 0) {
                            // only check isContract if the call was successful and the return data is empty
                            // otherwise we already know that it was a contract
                            require(isContract(target), "Address: call to non-contract");
                        }
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason or using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC165 standard, as defined in the
             * https://eips.ethereum.org/EIPS/eip-165[EIP].
             *
             * 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[EIP 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);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            interface IElement {
                struct Signature {
                    uint8 signatureType;
                    uint8 v;
                    bytes32 r;
                    bytes32 s;
                }
                struct Property {
                    address propertyValidator;
                    bytes propertyData;
                }
                struct Fee {
                    address recipient;
                    uint256 amount;
                    bytes feeData;
                }
                struct NFTSellOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address nft;
                    uint256 nftId;
                }
                struct NFTBuyOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address nft;
                    uint256 nftId;
                    Property[] nftProperties;
                }
                struct ERC1155SellOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address erc1155Token;
                    uint256 erc1155TokenId;
                    // End of fields shared with NFTOrder
                    uint128 erc1155TokenAmount;
                }
                struct ERC1155BuyOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address erc1155Token;
                    uint256 erc1155TokenId;
                    Property[] erc1155TokenProperties;
                    // End of fields shared with NFTOrder
                    uint128 erc1155TokenAmount;
                }
                struct BatchSignedOrder {
                    address maker;
                    uint256 listingTime;
                    uint256 expirationTime;
                    uint256 startNonce;
                    address erc20Token;
                    address platformFeeRecipient;
                    uint8 v;
                    bytes32 r;
                    bytes32 s;
                    bytes collectionsBytes;
                }
                /// @param data1 [56 bits(startNonce) + 8 bits(v) + 32 bits(listingTime) + 160 bits(maker)]
                /// @param data2 [64 bits(taker part1) + 32 bits(expiryTime) + 160 bits(erc20Token)]
                /// @param data3 [96 bits(taker part2) + 160 bits(platformFeeRecipient)]
                struct Parameter {
                    uint256 data1;
                    uint256 data2;
                    uint256 data3;
                    bytes32 r;
                    bytes32 s;
                }
                /// @param data1 [56 bits(startNonce) + 8 bits(v) + 32 bits(listingTime) + 160 bits(maker)]
                /// @param data2 [64 bits(taker part1) + 32 bits(expiryTime) + 160 bits(erc20Token)]
                /// @param data3 [96 bits(taker part2) + 160 bits(platformFeeRecipient)]
                struct Parameters {
                    uint256 data1;
                    uint256 data2;
                    uint256 data3;
                    bytes32 r;
                    bytes32 s;
                    bytes collections;
                }
                function buyERC721Ex(
                    NFTSellOrder calldata sellOrder,
                    Signature calldata signature,
                    address taker,
                    bytes calldata takerData
                ) external payable;
                function batchBuyERC721sEx(
                    NFTSellOrder[] calldata sellOrders,
                    Signature[] calldata signatures,
                    address[] calldata takers,
                    bytes[] calldata takerDatas,
                    bool revertIfIncomplete
                ) external payable returns (bool[] memory successes);
                function buyERC1155Ex(
                    ERC1155SellOrder calldata sellOrder,
                    Signature calldata signature,
                    address taker,
                    uint128 erc1155BuyAmount,
                    bytes calldata takerData
                ) external payable;
                function batchBuyERC1155sEx(
                    ERC1155SellOrder[] calldata sellOrders,
                    Signature[] calldata signatures,
                    address[] calldata takers,
                    uint128[] calldata erc1155TokenAmounts,
                    bytes[] calldata takerDatas,
                    bool revertIfIncomplete
                ) external payable returns (bool[] memory successes);
                function sellERC721(
                    NFTBuyOrder calldata buyOrder,
                    Signature calldata signature,
                    uint256 erc721TokenId,
                    bool unwrapNativeToken,
                    bytes calldata takerData
                ) external;
                function sellERC1155(
                    ERC1155BuyOrder calldata buyOrder,
                    Signature calldata signature,
                    uint256 erc1155TokenId,
                    uint128 erc1155SellAmount,
                    bool unwrapNativeToken,
                    bytes calldata takerData
                ) external;
                function fillBatchSignedERC721Order(
                    Parameter calldata parameter,
                    bytes calldata collections
                ) external payable;
                /// @param additional1 [96 bits(withdrawETHAmount) + 160 bits(erc20Token)]
                /// @param additional2 [8 bits(revertIfIncomplete) + 88 bits(unused) + 160 bits(royaltyFeeRecipient)]
                function fillBatchSignedERC721Orders(
                    Parameters[] calldata parameters,
                    uint256 additional1,
                    uint256 additional2
                ) external payable;
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            // Adapted from:
            // https://github.com/boringcrypto/BoringSolidity/blob/e74c5b22a61bfbadd645e51a64aa1d33734d577a/contracts/BoringOwnable.sol
            contract TwoStepOwnable {
                // --- Fields ---
                address public owner;
                address public pendingOwner;
                // --- Events ---
                event OwnershipTransferred(
                    address indexed previousOwner,
                    address indexed newOwner
                );
                // --- Errors ---
                error InvalidParams();
                error Unauthorized();
                // --- Modifiers ---
                modifier onlyOwner() {
                    if (msg.sender != owner) {
                        revert Unauthorized();
                    }
                    _;
                }
                // --- Constructor ---
                constructor(address initialOwner) {
                    owner = initialOwner;
                    emit OwnershipTransferred(address(0), initialOwner);
                }
                // --- Methods ---
                function transferOwnership(address newOwner) public onlyOwner {
                    pendingOwner = newOwner;
                }
                function claimOwnership() public {
                    address _pendingOwner = pendingOwner;
                    if (msg.sender != _pendingOwner) {
                        revert Unauthorized();
                    }
                    owner = _pendingOwner;
                    pendingOwner = address(0);
                    emit OwnershipTransferred(owner, _pendingOwner);
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
            import {TwoStepOwnable} from "../../misc/TwoStepOwnable.sol";
            // Notes:
            // - includes common helpers useful for all modules
            abstract contract BaseModule is TwoStepOwnable, ReentrancyGuard {
                using SafeERC20 for IERC20;
                // --- Events ---
                event CallExecuted(address target, bytes data, uint256 value);
                // --- Errors ---
                error UnsuccessfulCall();
                error UnsuccessfulPayment();
                error WrongParams();
                // --- Constructor ---
                constructor(address owner) TwoStepOwnable(owner) {}
                // --- Owner ---
                // To be able to recover anything that gets stucked by mistake in the module,
                // we allow the owner to perform any arbitrary call. Since the goal is to be
                // stateless, this should only happen in case of mistakes. In addition, this
                // method is also useful for withdrawing any earned trading rewards.
                function makeCalls(
                    address[] calldata targets,
                    bytes[] calldata data,
                    uint256[] calldata values
                ) external payable onlyOwner nonReentrant {
                    uint256 length = targets.length;
                    for (uint256 i = 0; i < length; ) {
                        _makeCall(targets[i], data[i], values[i]);
                        emit CallExecuted(targets[i], data[i], values[i]);
                        unchecked {
                            ++i;
                        }
                    }
                }
                // --- Helpers ---
                function _sendETH(address to, uint256 amount) internal {
                    if (amount > 0) {
                        (bool success, ) = payable(to).call{value: amount}("");
                        if (!success) {
                            revert UnsuccessfulPayment();
                        }
                    }
                }
                function _sendERC20(
                    address to,
                    uint256 amount,
                    IERC20 token
                ) internal {
                    if (amount > 0) {
                        token.safeTransfer(to, amount);
                    }
                }
                function _makeCall(
                    address target,
                    bytes memory data,
                    uint256 value
                ) internal {
                    (bool success, ) = payable(target).call{value: value}(data);
                    if (!success) {
                        revert UnsuccessfulCall();
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
            import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
            import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
            import {BaseModule} from "../BaseModule.sol";
            // Notes:
            // - includes common helpers useful for all marketplace/exchange modules
            abstract contract BaseExchangeModule is BaseModule {
                using SafeERC20 for IERC20;
                // --- Structs ---
                // Every fill execution has the following parameters:
                // - `fillTo`: the recipient of the received items
                // - `refundTo`: the recipient of any refunds
                // - `revertIfIncomplete`: whether to revert or skip unsuccessful fills
                // The below `ETHListingParams` and `ERC20ListingParams` rely on the
                // off-chain execution encoder to ensure that the orders filled with
                // the passed in listing parameters exactly match (eg. order amounts
                // and payment tokens match).
                struct ETHListingParams {
                    address fillTo;
                    address refundTo;
                    bool revertIfIncomplete;
                    // The total amount of ETH to be provided when filling
                    uint256 amount;
                }
                struct ERC20ListingParams {
                    address fillTo;
                    address refundTo;
                    bool revertIfIncomplete;
                    // The ERC20 payment token for the listings
                    IERC20 token;
                    // The total amount of `token` to be provided when filling
                    uint256 amount;
                }
                struct OfferParams {
                    address fillTo;
                    address refundTo;
                    bool revertIfIncomplete;
                }
                struct Fee {
                    address recipient;
                    uint256 amount;
                }
                // --- Fields ---
                address public immutable router;
                // --- Errors ---
                error UnsuccessfulFill();
                // --- Constructor ---
                constructor(address routerAddress) {
                    router = routerAddress;
                }
                // --- Modifiers ---
                modifier refundETHLeftover(address refundTo) {
                    _;
                    uint256 leftover = address(this).balance;
                    if (leftover > 0) {
                        _sendETH(refundTo, leftover);
                    }
                }
                modifier refundERC20Leftover(address refundTo, IERC20 token) {
                    _;
                    uint256 leftover = token.balanceOf(address(this));
                    if (leftover > 0) {
                        token.safeTransfer(refundTo, leftover);
                    }
                }
                modifier chargeETHFees(Fee[] calldata fees, uint256 amount) {
                    if (fees.length == 0) {
                        _;
                    } else {
                        uint256 balanceBefore = address(this).balance;
                        _;
                        uint256 length = fees.length;
                        if (length > 0) {
                            uint256 balanceAfter = address(this).balance;
                            uint256 actualPaid = balanceBefore - balanceAfter;
                            uint256 actualFee;
                            for (uint256 i = 0; i < length; ) {
                                // Adjust the fee to what was actually paid
                                actualFee = (fees[i].amount * actualPaid) / amount;
                                if (actualFee > 0) {
                                    _sendETH(fees[i].recipient, actualFee);
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                }
                modifier chargeERC20Fees(
                    Fee[] calldata fees,
                    IERC20 token,
                    uint256 amount
                ) {
                    if (fees.length == 0) {
                        _;
                    } else {
                        uint256 balanceBefore = token.balanceOf(address(this));
                        _;
                        uint256 length = fees.length;
                        if (length > 0) {
                            uint256 balanceAfter = token.balanceOf(address(this));
                            uint256 actualPaid = balanceBefore - balanceAfter;
                            uint256 actualFee;
                            for (uint256 i = 0; i < length; ) {
                                // Adjust the fee to what was actually paid
                                actualFee = (fees[i].amount * actualPaid) / amount;
                                if (actualFee > 0) {
                                    token.safeTransfer(fees[i].recipient, actualFee);
                                }
                                unchecked {
                                    ++i;
                                }
                            }
                        }
                    }
                }
                // --- Helpers ---
                function _sendAllETH(address to) internal {
                    _sendETH(to, address(this).balance);
                }
                function _sendAllERC20(address to, IERC20 token) internal {
                    uint256 balance = token.balanceOf(address(this));
                    if (balance > 0) {
                        token.safeTransfer(to, balance);
                    }
                }
                function _sendAllERC721(
                    address to,
                    IERC721 token,
                    uint256 tokenId
                ) internal {
                    if (token.ownerOf(tokenId) == address(this)) {
                        token.safeTransferFrom(address(this), to, tokenId);
                    }
                }
                function _sendAllERC1155(
                    address to,
                    IERC1155 token,
                    uint256 tokenId
                ) internal {
                    uint256 balance = token.balanceOf(address(this), tokenId);
                    if (balance > 0) {
                        token.safeTransferFrom(address(this), to, tokenId, balance, "");
                    }
                }
                function _approveERC20IfNeeded(
                    IERC20 token,
                    address spender,
                    uint256 amount
                ) internal {
                    uint256 allowance = token.allowance(address(this), spender);
                    if (allowance < amount) {
                        token.approve(spender, amount - allowance);
                    }
                }
                function _approveERC721IfNeeded(IERC721 token, address operator) internal {
                    bool isApproved = token.isApprovedForAll(address(this), operator);
                    if (!isApproved) {
                        token.setApprovalForAll(operator, true);
                    }
                }
                function _approveERC1155IfNeeded(IERC1155 token, address operator)
                    internal
                {
                    bool isApproved = token.isApprovedForAll(address(this), operator);
                    if (!isApproved) {
                        token.setApprovalForAll(operator, true);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.9;
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
            import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
            import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
            import {BaseExchangeModule} from "./BaseExchangeModule.sol";
            import {BaseModule} from "../BaseModule.sol";
            import {IElement} from "../../../interfaces/IElement.sol";
            // Notes:
            // - supports filling listings (both ERC721/ERC1155)
            // - supports filling offers (both ERC721/ERC1155)
            contract ElementModule is BaseExchangeModule {
                using SafeERC20 for IERC20;
                // --- Fields ---
                IElement public constant EXCHANGE =
                    IElement(0x20F780A973856B93f63670377900C1d2a50a77c4);
                // --- Constructor ---
                constructor(address owner, address router)
                    BaseModule(owner)
                    BaseExchangeModule(router)
                {}
                // --- Fallback ---
                receive() external payable {}
                // --- [ERC721] Single ETH listing ---
                function acceptETHListingERC721(
                    IElement.NFTSellOrder calldata order,
                    IElement.Signature calldata signature,
                    ETHListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundETHLeftover(params.refundTo)
                    chargeETHFees(fees, params.amount)
                {
                    // Execute fill
                    _buyERC721Ex(
                        order,
                        signature,
                        params.fillTo,
                        params.revertIfIncomplete,
                        params.amount
                    );
                }
                // --- [ERC721] Single ERC20 listing ---
                function acceptERC20ListingERC721(
                    IElement.NFTSellOrder calldata order,
                    IElement.Signature calldata signature,
                    ERC20ListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundERC20Leftover(params.refundTo, params.token)
                    chargeERC20Fees(fees, params.token, params.amount)
                {
                    // Approve the exchange if needed
                    _approveERC20IfNeeded(params.token, address(EXCHANGE), params.amount);
                    // Execute fill
                    _buyERC721Ex(
                        order,
                        signature,
                        params.fillTo,
                        params.revertIfIncomplete,
                        0
                    );
                }
                // --- [ERC721] Multiple ETH listings ---
                function acceptETHListingsERC721(
                    IElement.NFTSellOrder[] calldata orders,
                    IElement.Signature[] calldata signatures,
                    ETHListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundETHLeftover(params.refundTo)
                    chargeETHFees(fees, params.amount)
                {
                    // Execute fill
                    _buyERC721sEx(
                        orders,
                        signatures,
                        params.fillTo,
                        params.revertIfIncomplete,
                        params.amount
                    );
                }
                // --- [ERC721] Multiple ERC20 listings ---
                function acceptERC20ListingsERC721(
                    IElement.NFTSellOrder[] calldata orders,
                    IElement.Signature[] calldata signatures,
                    ERC20ListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundERC20Leftover(params.refundTo, params.token)
                    chargeERC20Fees(fees, params.token, params.amount)
                {
                    // Approve the exchange if needed
                    _approveERC20IfNeeded(params.token, address(EXCHANGE), params.amount);
                    // Execute fill
                    _buyERC721sEx(
                        orders,
                        signatures,
                        params.fillTo,
                        params.revertIfIncomplete,
                        0
                    );
                }
                // --- [ERC721] Single ETH listing V2 ---
                function acceptETHListingERC721V2(
                    IElement.BatchSignedOrder calldata order,
                    ETHListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundETHLeftover(params.refundTo)
                    chargeETHFees(fees, params.amount)
                {
                    // Execute fill
                    _fillBatchSignedOrder(
                        order,
                        params.fillTo,
                        params.revertIfIncomplete,
                        params.amount
                    );
                }
                // --- [ERC721] Single ERC20 listing V2 ---
                function acceptERC20ListingERC721V2(
                    IElement.BatchSignedOrder calldata order,
                    ERC20ListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundERC20Leftover(params.refundTo, params.token)
                    chargeERC20Fees(fees, params.token, params.amount)
                {
                    // Approve the exchange if needed
                    _approveERC20IfNeeded(params.token, address(EXCHANGE), params.amount);
                    // Execute fill
                    _fillBatchSignedOrder(
                        order,
                        params.fillTo,
                        params.revertIfIncomplete,
                        0
                    );
                }
                // --- [ERC721] Multiple ETH listings V2 ---
                function acceptETHListingsERC721V2(
                    IElement.BatchSignedOrder[] calldata orders,
                    ETHListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundETHLeftover(params.refundTo)
                    chargeETHFees(fees, params.amount)
                {
                    // Execute fill
                    _fillBatchSignedOrders(
                        orders,
                        params.fillTo,
                        params.revertIfIncomplete,
                        params.amount
                    );
                }
                // --- [ERC721] Multiple ERC20 listings V2 ---
                function acceptERC20ListingsERC721V2(
                    IElement.BatchSignedOrder[] calldata orders,
                    ERC20ListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundERC20Leftover(params.refundTo, params.token)
                    chargeERC20Fees(fees, params.token, params.amount)
                {
                    // Approve the exchange if needed
                    _approveERC20IfNeeded(params.token, address(EXCHANGE), params.amount);
                    // Execute fill
                    _fillBatchSignedOrders(
                        orders,
                        params.fillTo,
                        params.revertIfIncomplete,
                        0
                    );
                }
                // --- [ERC1155] Single ETH listing ---
                function acceptETHListingERC1155(
                    IElement.ERC1155SellOrder calldata order,
                    IElement.Signature calldata signature,
                    uint128 amount,
                    ETHListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundETHLeftover(params.refundTo)
                    chargeETHFees(fees, params.amount)
                {
                    // Execute fill
                    _buyERC1155Ex(
                        order,
                        signature,
                        amount,
                        params.fillTo,
                        params.revertIfIncomplete,
                        params.amount
                    );
                }
                // --- [ERC1155] Single ERC20 listing ---
                function acceptERC20ListingERC1155(
                    IElement.ERC1155SellOrder calldata order,
                    IElement.Signature calldata signature,
                    uint128 amount,
                    ERC20ListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundERC20Leftover(params.refundTo, params.token)
                    chargeERC20Fees(fees, params.token, params.amount)
                {
                    // Approve the exchange if needed
                    _approveERC20IfNeeded(params.token, address(EXCHANGE), params.amount);
                    // Execute fill
                    _buyERC1155Ex(
                        order,
                        signature,
                        amount,
                        params.fillTo,
                        params.revertIfIncomplete,
                        0
                    );
                }
                // --- [ERC1155] Multiple ETH listings ---
                function acceptETHListingsERC1155(
                    IElement.ERC1155SellOrder[] calldata orders,
                    IElement.Signature[] calldata signatures,
                    uint128[] calldata amounts,
                    ETHListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundETHLeftover(params.refundTo)
                    chargeETHFees(fees, params.amount)
                {
                    // Execute fill
                    _buyERC1155sEx(
                        orders,
                        signatures,
                        amounts,
                        params.fillTo,
                        params.revertIfIncomplete,
                        params.amount
                    );
                }
                // --- [ERC1155] Multiple ERC20 listings ---
                function acceptERC20ListingsERC1155(
                    IElement.ERC1155SellOrder[] calldata orders,
                    IElement.Signature[] calldata signatures,
                    uint128[] calldata amounts,
                    ERC20ListingParams calldata params,
                    Fee[] calldata fees
                )
                    external
                    payable
                    nonReentrant
                    refundERC20Leftover(params.refundTo, params.token)
                    chargeERC20Fees(fees, params.token, params.amount)
                {
                    // Approve the exchange if needed
                    _approveERC20IfNeeded(params.token, address(EXCHANGE), params.amount);
                    // Execute fill
                    _buyERC1155sEx(
                        orders,
                        signatures,
                        amounts,
                        params.fillTo,
                        params.revertIfIncomplete,
                        0
                    );
                }
                // --- [ERC721] Single offer ---
                function acceptERC721Offer(
                    IElement.NFTBuyOrder calldata order,
                    IElement.Signature calldata signature,
                    OfferParams calldata params,
                    uint256 tokenId,
                    Fee[] calldata fees
                ) external nonReentrant {
                    // Approve the exchange if needed
                    _approveERC721IfNeeded(IERC721(order.nft), address(EXCHANGE));
                    // Execute fill
                    try EXCHANGE.sellERC721(order, signature, tokenId, false, "") {
                        // Pay fees
                        uint256 feesLength = fees.length;
                        for (uint256 i; i < feesLength; ) {
                            Fee memory fee = fees[i];
                            _sendERC20(fee.recipient, fee.amount, order.erc20Token);
                            unchecked {
                                ++i;
                            }
                        }
                        // Forward any left payment to the specified receiver
                        _sendAllERC20(params.fillTo, order.erc20Token);
                    } catch {
                        // Revert if specified
                        if (params.revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                    // Refund any ERC721 leftover
                    _sendAllERC721(params.refundTo, IERC721(order.nft), tokenId);
                }
                // --- [ERC1155] Single offer ---
                function acceptERC1155Offer(
                    IElement.ERC1155BuyOrder calldata order,
                    IElement.Signature calldata signature,
                    uint128 amount,
                    OfferParams calldata params,
                    uint256 tokenId,
                    Fee[] calldata fees
                ) external nonReentrant {
                    // Approve the exchange if needed
                    _approveERC1155IfNeeded(IERC1155(order.erc1155Token), address(EXCHANGE));
                    // Execute fill
                    try EXCHANGE.sellERC1155(order, signature, tokenId, amount, false, "") {
                        // Pay fees
                        uint256 feesLength = fees.length;
                        for (uint256 i; i < feesLength; ) {
                            Fee memory fee = fees[i];
                            _sendERC20(fee.recipient, fee.amount, order.erc20Token);
                            unchecked {
                                ++i;
                            }
                        }
                        // Forward any left payment to the specified receiver
                        _sendAllERC20(params.fillTo, order.erc20Token);
                    } catch {
                        // Revert if specified
                        if (params.revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                    // Refund any ERC1155 leftover
                    _sendAllERC1155(params.refundTo, IERC1155(order.erc1155Token), tokenId);
                }
                // --- ERC721 / ERC1155 hooks ---
                // Single token offer acceptance can be done approval-less by using the
                // standard `safeTransferFrom` method together with specifying data for
                // further contract calls. An example:
                // `safeTransferFrom(
                //      0xWALLET,
                //      0xMODULE,
                //      TOKEN_ID,
                //      0xABI_ENCODED_ROUTER_EXECUTION_CALLDATA_FOR_OFFER_ACCEPTANCE
                // )`
                function onERC721Received(
                    address, // operator,
                    address, // from
                    uint256, // tokenId,
                    bytes calldata data
                ) external returns (bytes4) {
                    if (data.length > 0) {
                        _makeCall(router, data, 0);
                    }
                    return this.onERC721Received.selector;
                }
                function onERC1155Received(
                    address, // operator
                    address, // from
                    uint256, // tokenId
                    uint256, // amount
                    bytes calldata data
                ) external returns (bytes4) {
                    if (data.length > 0) {
                        _makeCall(router, data, 0);
                    }
                    return this.onERC1155Received.selector;
                }
                // --- Internal ---
                function _buyERC721Ex(
                    IElement.NFTSellOrder calldata order,
                    IElement.Signature calldata signature,
                    address receiver,
                    bool revertIfIncomplete,
                    uint256 value
                ) internal {
                    // Execute fill
                    try EXCHANGE.buyERC721Ex{value: value}(order, signature, receiver, "") {
                    } catch {
                        // Revert if specified
                        if (revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                }
                function _buyERC721sEx(
                    IElement.NFTSellOrder[] calldata orders,
                    IElement.Signature[] calldata signatures,
                    address receiver,
                    bool revertIfIncomplete,
                    uint256 value
                ) internal {
                    uint256 length = orders.length;
                    address[] memory takers = new address[](length);
                    for (uint256 i; i < length; ) {
                        takers[i] = receiver;
                        unchecked { ++i; }
                    }
                    // Execute fill
                    try EXCHANGE.batchBuyERC721sEx{value: value}(
                        orders,
                        signatures,
                        takers,
                        new bytes[](length),
                        revertIfIncomplete
                    ) {} catch {
                        // Revert if specified
                        if (revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                }
                function _fillBatchSignedOrder(
                    IElement.BatchSignedOrder calldata order,
                    address receiver,
                    bool revertIfIncomplete,
                    uint256 value
                ) internal {
                    IElement.Parameter memory parameter;
                    parameter.r = order.r;
                    parameter.s = order.s;
                    // data1 [56 bits(startNonce) + 8 bits(v) + 32 bits(listingTime) + 160 bits(maker)]
                    parameter.data1 =
                        (order.startNonce << 200) | (uint256(order.v) << 192) |
                        (order.listingTime << 160) | uint256(uint160(order.maker));
                    // data2 [64 bits(taker part1) + 32 bits(expiryTime) + 160 bits(erc20Token)]
                    uint256 taker = uint256(uint160(receiver));
                    parameter.data2 =
                        ((taker >> 96) << 192) | (order.expirationTime << 160) | uint256(uint160(order.erc20Token));
                    // data3 [96 bits(taker part2) + 160 bits(platformFeeRecipient)]
                    parameter.data3 =
                        (taker << 160) | uint256(uint160(order.platformFeeRecipient));
                    // Execute fill
                    try EXCHANGE.fillBatchSignedERC721Order{value: value}(parameter, order.collectionsBytes) {
                    } catch {
                        // Revert if specified
                        if (revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                }
                function _fillBatchSignedOrders(
                    IElement.BatchSignedOrder[] calldata orders,
                    address receiver,
                    bool revertIfIncomplete,
                    uint256 value
                ) internal {
                    uint256 length = orders.length;
                    uint256 taker = uint256(uint160(receiver));
                    IElement.Parameters[] memory parameters = new IElement.Parameters[](length);
                    for (uint256 i; i < length; ) {
                        IElement.BatchSignedOrder calldata order = orders[i];
                        IElement.Parameters memory parameter;
                        parameter.r = order.r;
                        parameter.s = order.s;
                        parameter.collections = order.collectionsBytes;
                        // data1 [56 bits(startNonce) + 8 bits(v) + 32 bits(listingTime) + 160 bits(maker)]
                        parameter.data1 =
                            (order.startNonce << 200) | (uint256(order.v) << 192) |
                            (order.listingTime << 160) | uint256(uint160(order.maker));
                        // data2 [64 bits(taker part1) + 32 bits(expiryTime) + 160 bits(erc20Token)]
                        parameter.data2 =
                            ((taker >> 96) << 192) | (order.expirationTime << 160) | uint256(uint160(order.erc20Token));
                        // data3 [96 bits(taker part2) + 160 bits(platformFeeRecipient)]
                        parameter.data3 =
                            (taker << 160) | uint256(uint160(order.platformFeeRecipient));
                        parameters[i] = parameter;
                        unchecked { ++i; }
                    }
                    // Execute fill
                    uint256 additional2 = revertIfIncomplete ? (1 << 248) : 0;
                    try EXCHANGE.fillBatchSignedERC721Orders{value: value}(parameters, 0, additional2) {
                    } catch {
                        // Revert if specified
                        if (revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                }
                function _buyERC1155Ex(
                    IElement.ERC1155SellOrder calldata order,
                    IElement.Signature calldata signature,
                    uint128 amount,
                    address receiver,
                    bool revertIfIncomplete,
                    uint256 value
                ) internal {
                    try EXCHANGE.buyERC1155Ex{value: value}(order, signature, receiver, amount, "") {
                    } catch {
                        // Revert if specified
                        if (revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                }
                function _buyERC1155sEx(
                    IElement.ERC1155SellOrder[] calldata orders,
                    IElement.Signature[] calldata signatures,
                    uint128[] calldata amounts,
                    address receiver,
                    bool revertIfIncomplete,
                    uint256 value
                ) internal {
                    uint256 length = orders.length;
                    address[] memory takers = new address[](length);
                    for (uint256 i; i < length; ) {
                        takers[i] = receiver;
                        unchecked { ++i; }
                    }
                    // Execute fill
                    try EXCHANGE.batchBuyERC1155sEx{value: value}(
                        orders,
                        signatures,
                        takers,
                        amounts,
                        new bytes[](length),
                        revertIfIncomplete
                    ) {} catch {
                        // Revert if specified
                        if (revertIfIncomplete) {
                            revert UnsuccessfulFill();
                        }
                    }
                }
            }
            

            File 6 of 7: ERC721OrdersFeature
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2021 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "../../fixins/FixinERC721Spender.sol";
            import "../../storage/LibCommonNftOrdersStorage.sol";
            import "../../storage/LibERC721OrdersStorage.sol";
            import "../interfaces/IERC721OrdersFeature.sol";
            import "./NFTOrders.sol";
            /// @dev Feature for interacting with ERC721 orders.
            contract ERC721OrdersFeature is IERC721OrdersFeature, FixinERC721Spender, NFTOrders {
                using LibNFTOrder for LibNFTOrder.NFTBuyOrder;
                /// @dev The magic return value indicating the success of a `onERC721Received`.
                bytes4 private constant ERC721_RECEIVED_MAGIC_BYTES = this.onERC721Received.selector;
                uint256 private constant ORDER_NONCE_MASK = (1 << 184) - 1;
                constructor(IEtherToken weth) NFTOrders(weth) {
                }
                /// @dev Sells an ERC721 asset to fill the given order.
                /// @param buyOrder The ERC721 buy order.
                /// @param signature The order signature from the maker.
                /// @param erc721TokenId The ID of the ERC721 asset being
                ///        sold. If the given order specifies properties,
                ///        the asset must satisfy those properties. Otherwise,
                ///        it must equal the tokenId in the order.
                /// @param unwrapNativeToken If this parameter is true and the
                ///        ERC20 token of the order is e.g. WETH, unwraps the
                ///        token before transferring it to the taker.
                function sellERC721(
                    LibNFTOrder.NFTBuyOrder memory buyOrder,
                    LibSignature.Signature memory signature,
                    uint256 erc721TokenId,
                    bool unwrapNativeToken,
                    bytes memory takerData
                ) public override {
                    _sellERC721(buyOrder, signature, erc721TokenId, unwrapNativeToken, msg.sender, msg.sender, takerData);
                }
                /// @dev Buys an ERC721 asset by filling the given order.
                /// @param sellOrder The ERC721 sell order.
                /// @param signature The order signature.
                function buyERC721(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature) public override payable {
                    uint256 ethBalanceBefore;
                    assembly { ethBalanceBefore := sub(selfbalance(), callvalue()) }
                    _buyERC721(sellOrder, signature);
                    if (address(this).balance != ethBalanceBefore) {
                        // Refund
                        _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
                    }
                }
                function buyERC721Ex(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    LibSignature.Signature memory signature,
                    address taker,
                    bytes memory takerData
                ) public override payable {
                    uint256 ethBalanceBefore;
                    assembly { ethBalanceBefore := sub(selfbalance(), callvalue()) }
                    _buyERC721Ex(sellOrder, signature, taker, msg.value, takerData);
                    if (address(this).balance != ethBalanceBefore) {
                        // Refund
                        _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
                    }
                }
                /// @dev Cancel a single ERC721 order by its nonce. The caller
                ///      should be the maker of the order. Silently succeeds if
                ///      an order with the same nonce has already been filled or
                ///      cancelled.
                /// @param orderNonce The order nonce.
                function cancelERC721Order(uint256 orderNonce) public override {
                    // Mark order as cancelled
                    _setOrderStatusBit(msg.sender, orderNonce);
                    emit ERC721OrderCancelled(msg.sender, orderNonce);
                }
                /// @dev Cancel multiple ERC721 orders by their nonces. The caller
                ///      should be the maker of the orders. Silently succeeds if
                ///      an order with the same nonce has already been filled or
                ///      cancelled.
                /// @param orderNonces The order nonces.
                function batchCancelERC721Orders(uint256[] calldata orderNonces) external override {
                    for (uint256 i = 0; i < orderNonces.length; i++) {
                        cancelERC721Order(orderNonces[i]);
                    }
                }
                /// @dev Buys multiple ERC721 assets by filling the
                ///      given orders.
                /// @param sellOrders The ERC721 sell orders.
                /// @param signatures The order signatures.
                /// @param revertIfIncomplete If true, reverts if this
                ///        function fails to fill any individual order.
                /// @return successes An array of booleans corresponding to whether
                ///         each order in `orders` was successfully filled.
                function batchBuyERC721s(
                    LibNFTOrder.NFTSellOrder[] memory sellOrders,
                    LibSignature.Signature[] memory signatures,
                    bool revertIfIncomplete
                ) public override payable returns (bool[] memory successes) {
                    // Array length must match.
                    uint256 length = sellOrders.length;
                    require(length == signatures.length, "ARRAY_LENGTH_MISMATCH");
                    successes = new bool[](length);
                    uint256 ethBalanceBefore = address(this).balance - msg.value;
                    if (revertIfIncomplete) {
                        for (uint256 i = 0; i < length; i++) {
                            // Will revert if _buyERC721 reverts.
                            _buyERC721(sellOrders[i], signatures[i]);
                            successes[i] = true;
                        }
                    } else {
                        for (uint256 i = 0; i < length; i++) {
                            // Delegatecall `buyERC721FromProxy` to swallow reverts while
                            // preserving execution context.
                            (successes[i], ) = _implementation.delegatecall(
                                abi.encodeWithSelector(this.buyERC721FromProxy.selector, sellOrders[i], signatures[i])
                            );
                        }
                    }
                    // Refund
                   _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
                }
                function batchBuyERC721sEx(
                    LibNFTOrder.NFTSellOrder[] memory sellOrders,
                    LibSignature.Signature[] memory signatures,
                    address[] calldata takers,
                    bytes[] memory takerDatas,
                    bool revertIfIncomplete
                ) public override payable returns (bool[] memory successes) {
                    // All array length must match.
                    uint256 length = sellOrders.length;
                    require(length == signatures.length && length == takers.length && length == takerDatas.length, "ARRAY_LENGTH_MISMATCH");
                    successes = new bool[](length);
                    uint256 ethBalanceBefore = address(this).balance - msg.value;
                    if (revertIfIncomplete) {
                        for (uint256 i = 0; i < length; i++) {
                            // Will revert if _buyERC721Ex reverts.
                            _buyERC721Ex(sellOrders[i], signatures[i], takers[i], address(this).balance - ethBalanceBefore, takerDatas[i]);
                            successes[i] = true;
                        }
                    } else {
                        for (uint256 i = 0; i < length; i++) {
                            // Delegatecall `buyERC721ExFromProxy` to swallow reverts while
                            // preserving execution context.
                            (successes[i], ) = _implementation.delegatecall(
                                abi.encodeWithSelector(this.buyERC721ExFromProxy.selector, sellOrders[i], signatures[i], takers[i],
                                    address(this).balance - ethBalanceBefore, takerDatas[i])
                            );
                        }
                    }
                    // Refund
                   _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
                }
                // @Note `buyERC721FromProxy` is a external function, must call from an external Exchange Proxy,
                //        but should not be registered in the Exchange Proxy.
                function buyERC721FromProxy(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature) external payable {
                    require(_implementation != address(this), "MUST_CALL_FROM_PROXY");
                    _buyERC721(sellOrder, signature);
                }
                // @Note `buyERC721ExFromProxy` is a external function, must call from an external Exchange Proxy,
                //        but should not be registered in the Exchange Proxy.
                function buyERC721ExFromProxy(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, address taker, uint256 ethAvailable, bytes memory takerData) external payable {
                    require(_implementation != address(this), "MUST_CALL_FROM_PROXY");
                    _buyERC721Ex(sellOrder, signature, taker, ethAvailable, takerData);
                }
                /// @dev Matches a pair of complementary orders that have
                ///      a non-negative spread. Each order is filled at
                ///      their respective price, and the matcher receives
                ///      a profit denominated in the ERC20 token.
                /// @param sellOrder Order selling an ERC721 asset.
                /// @param buyOrder Order buying an ERC721 asset.
                /// @param sellOrderSignature Signature for the sell order.
                /// @param buyOrderSignature Signature for the buy order.
                /// @return profit The amount of profit earned by the caller
                ///         of this function (denominated in the ERC20 token
                ///         of the matched orders).
                function matchERC721Orders(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    LibNFTOrder.NFTBuyOrder memory buyOrder,
                    LibSignature.Signature memory sellOrderSignature,
                    LibSignature.Signature memory buyOrderSignature
                ) public override returns (uint256 profit) {
                    // The ERC721 tokens must match
                    require(sellOrder.nft == buyOrder.nft, "ERC721_TOKEN_MISMATCH_ERROR");
                    LibNFTOrder.OrderInfo memory sellOrderInfo = _getOrderInfo(sellOrder);
                    LibNFTOrder.OrderInfo memory buyOrderInfo = _getOrderInfo(buyOrder);
                    _validateSellOrder(sellOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker);
                    _validateBuyOrder(buyOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.nftId, "");
                    // English Auction
                    if (sellOrder.expiry >> 252 == 2) {
                        _resetEnglishAuctionTokenAmountAndFees(sellOrder, buyOrder.erc20TokenAmount, 1, 1);
                    }
                    // Mark both orders as filled.
                    _updateOrderState(sellOrder, sellOrderInfo.orderHash, 1);
                    _updateOrderState(buyOrder.asNFTSellOrder(), buyOrderInfo.orderHash, 1);
                    // The difference in ERC20 token amounts is the spread.
                    uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount;
                    // Transfer the ERC721 asset from seller to buyer.
                    _transferERC721AssetFrom(sellOrder.nft, sellOrder.maker, buyOrder.maker, sellOrder.nftId);
                    // Handle the ERC20 side of the order:
                    if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH) {
                        // The sell order specifies ETH, while the buy order specifies WETH.
                        // The orders are still compatible with one another, but we'll have
                        // to unwrap the WETH on behalf of the buyer.
                        // Step 1: Transfer WETH from the buyer to the EP.
                        //         Note that we transfer `buyOrder.erc20TokenAmount`, which
                        //         is the amount the buyer signaled they are willing to pay
                        //         for the ERC721 asset, which may be more than the seller's
                        //         ask.
                        _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount);
                        // Step 2: Unwrap the WETH into ETH. We unwrap the entire
                        //         `buyOrder.erc20TokenAmount`.
                        //         The ETH will be used for three purposes:
                        //         - To pay the seller
                        //         - To pay fees for the sell order
                        //         - Any remaining ETH will be sent to
                        //           `msg.sender` as profit.
                        WETH.withdraw(buyOrder.erc20TokenAmount);
                        // Step 3: Pay the seller (in ETH).
                        _transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount);
                        // Step 4: Pay fees for the buy order. Note that these are paid
                        //         in _WETH_ by the _buyer_. By signing the buy order, the
                        //         buyer signals that they are willing to spend a total
                        //         of `erc20TokenAmount` _plus_ fees, all denominated in
                        //         the `erc20Token`, which in this case is WETH.
                        _payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, 1, 1, false);
                        // Step 5: Pay fees for the sell order. The `erc20Token` of the
                        //         sell order is ETH, so the fees are paid out in ETH.
                        //         There should be `spread` wei of ETH remaining in the
                        //         EP at this point, which we will use ETH to pay the
                        //         sell order fees.
                        uint256 sellOrderFees = _payFees(sellOrder, address(this), 1, 1, true);
                        // Step 6: The spread less the sell order fees is the amount of ETH
                        //         remaining in the EP that can be sent to `msg.sender` as
                        //         the profit from matching these two orders.
                        profit = spread - sellOrderFees;
                        if (profit > 0) {
                            _transferEth(payable(msg.sender), profit);
                        }
                    } else {
                        // ERC20 tokens must match
                        require(sellOrder.erc20Token == buyOrder.erc20Token, "ERC20_TOKEN_MISMATCH_ERROR");
                        // Step 1: Transfer the ERC20 token from the buyer to the seller.
                        //         Note that we transfer `sellOrder.erc20TokenAmount`, which
                        //         is at most `buyOrder.erc20TokenAmount`.
                        _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount);
                        // Step 2: Pay fees for the buy order. Note that these are paid
                        //         by the buyer. By signing the buy order, the buyer signals
                        //         that they are willing to spend a total of
                        //         `buyOrder.erc20TokenAmount` _plus_ `buyOrder.fees`.
                        _payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, 1, 1, false);
                        // Step 3: Pay fees for the sell order. These are paid by the buyer
                        //         as well. After paying these fees, we may have taken more
                        //         from the buyer than they agreed to in the buy order. If
                        //         so, we revert in the following step.
                        uint256 sellOrderFees = _payFees(sellOrder, buyOrder.maker, 1, 1, false);
                        // Step 4: We calculate the profit as:
                        //         profit = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount - sellOrderFees
                        //                = spread - sellOrderFees
                        //         I.e. the buyer would've been willing to pay up to `profit`
                        //         more to buy the asset, so instead that amount is sent to
                        //         `msg.sender` as the profit from matching these two orders.
                        profit = spread - sellOrderFees;
                        if (profit > 0) {
                            _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, msg.sender, profit);
                        }
                    }
                    _emitEventSellOrderFilled(
                        sellOrder,
                        buyOrder.maker,
                        sellOrderInfo.orderHash
                    );
                    _emitEventBuyOrderFilled(
                        buyOrder,
                        sellOrder.maker,
                        sellOrder.nftId,
                        buyOrderInfo.orderHash
                    );
                }
                /// @dev Matches pairs of complementary orders that have
                ///      non-negative spreads. Each order is filled at
                ///      their respective price, and the matcher receives
                ///      a profit denominated in the ERC20 token.
                /// @param sellOrders Orders selling ERC721 assets.
                /// @param buyOrders Orders buying ERC721 assets.
                /// @param sellOrderSignatures Signatures for the sell orders.
                /// @param buyOrderSignatures Signatures for the buy orders.
                /// @return profits The amount of profit earned by the caller
                ///         of this function for each pair of matched orders
                ///         (denominated in the ERC20 token of the order pair).
                /// @return successes An array of booleans corresponding to
                ///         whether each pair of orders was successfully matched.
                function batchMatchERC721Orders(
                    LibNFTOrder.NFTSellOrder[] memory sellOrders,
                    LibNFTOrder.NFTBuyOrder[] memory buyOrders,
                    LibSignature.Signature[] memory sellOrderSignatures,
                    LibSignature.Signature[] memory buyOrderSignatures
                ) public override returns (uint256[] memory profits, bool[] memory successes) {
                    // All array length must match.
                    uint256 length = sellOrders.length;
                    require(length == buyOrders.length && length == sellOrderSignatures.length && length == buyOrderSignatures.length, "ARRAY_LENGTH_MISMATCH");
                    profits = new uint256[](length);
                    successes = new bool[](length);
                    for (uint256 i = 0; i < length; i++) {
                        bytes memory returnData;
                        // Delegatecall `matchERC721Orders` to catch reverts while
                        // preserving execution context.
                        (successes[i], returnData) = _implementation.delegatecall(
                            abi.encodeWithSelector(this.matchERC721Orders.selector, sellOrders[i], buyOrders[i],
                                sellOrderSignatures[i], buyOrderSignatures[i])
                        );
                        if (successes[i]) {
                            // If the matching succeeded, record the profit.
                            (uint256 profit) = abi.decode(returnData, (uint256));
                            profits[i] = profit;
                        }
                    }
                }
                /// @dev Callback for the ERC721 `safeTransferFrom` function.
                ///      This callback can be used to sell an ERC721 asset if
                ///      a valid ERC721 order, signature and `unwrapNativeToken`
                ///      are encoded in `data`. This allows takers to sell their
                ///      ERC721 asset without first calling `setApprovalForAll`.
                /// @param operator The address which called `safeTransferFrom`.
                /// @param tokenId The ID of the asset being transferred.
                /// @param data Additional data with no specified format. If a
                ///        valid ERC721 order, signature and `unwrapNativeToken`
                ///        are encoded in `data`, this function will try to fill
                ///        the order using the received asset.
                /// @return success The selector of this function (0x150b7a02),
                ///         indicating that the callback succeeded.
                function onERC721Received(address operator, address /* from */, uint256 tokenId, bytes calldata data) external override returns (bytes4 success) {
                    // Decode the order, signature, and `unwrapNativeToken` from
                    // `data`. If `data` does not encode such parameters, this
                    // will throw.
                    (LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken)
                        = abi.decode(data, (LibNFTOrder.NFTBuyOrder, LibSignature.Signature, bool));
                    // `onERC721Received` is called by the ERC721 token contract.
                    // Check that it matches the ERC721 token in the order.
                    require(msg.sender == buyOrder.nft, "ERC721_TOKEN_MISMATCH_ERROR");
                    // operator taker
                    // address(this) owner (we hold the NFT currently)
                    _sellERC721(buyOrder, signature, tokenId, unwrapNativeToken, operator, address(this), new bytes(0));
                    return ERC721_RECEIVED_MAGIC_BYTES;
                }
                /// @dev Approves an ERC721 sell order on-chain. After pre-signing
                ///      the order, the `PRESIGNED` signature type will become
                ///      valid for that order and signer.
                /// @param order An ERC721 sell order.
                function preSignERC721SellOrder(LibNFTOrder.NFTSellOrder memory order) public override {
                    require(order.maker == msg.sender, "ONLY_MAKER");
                    uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker];
                    bytes32 orderHash = getERC721SellOrderHash(order);
                    LibERC721OrdersStorage.getStorage().preSigned[orderHash] = (hashNonce + 1);
                    emit ERC721SellOrderPreSigned(order.maker, order.taker, order.expiry, order.nonce,
                        order.erc20Token, order.erc20TokenAmount, order.fees, order.nft, order.nftId);
                }
                /// @dev Approves an ERC721 buy order on-chain. After pre-signing
                ///      the order, the `PRESIGNED` signature type will become
                ///      valid for that order and signer.
                /// @param order An ERC721 buy order.
                function preSignERC721BuyOrder(LibNFTOrder.NFTBuyOrder memory order) public override {
                    require(order.maker == msg.sender, "ONLY_MAKER");
                    uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker];
                    bytes32 orderHash = getERC721BuyOrderHash(order);
                    LibERC721OrdersStorage.getStorage().preSigned[orderHash] = (hashNonce + 1);
                    emit ERC721BuyOrderPreSigned(order.maker, order.taker, order.expiry, order.nonce,
                        order.erc20Token, order.erc20TokenAmount, order.fees, order.nft, order.nftId, order.nftProperties);
                }
                // Core settlement logic for selling an ERC721 asset.
                // Used by `sellERC721` and `onERC721Received`.
                function _sellERC721(
                    LibNFTOrder.NFTBuyOrder memory buyOrder,
                    LibSignature.Signature memory signature,
                    uint256 erc721TokenId,
                    bool unwrapNativeToken,
                    address taker,
                    address currentNftOwner,
                    bytes memory takerData
                ) private {
                    (, bytes32 orderHash) = _sellNFT(
                        buyOrder,
                        signature,
                        SellParams(1, erc721TokenId, unwrapNativeToken, taker, currentNftOwner, takerData)
                    );
                    _emitEventBuyOrderFilled(
                        buyOrder,
                        taker,
                        erc721TokenId,
                        orderHash
                    );
                }
                // Core settlement logic for buying an ERC721 asset.
                // Used by `buyERC721` and `batchBuyERC721s`.
                function _buyERC721(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature) internal {
                    (, bytes32 orderHash) = _buyNFT(sellOrder, signature, 1);
                    _emitEventSellOrderFilled(
                        sellOrder,
                        msg.sender,
                        orderHash
                    );
                }
                function _buyERC721Ex(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    LibSignature.Signature memory signature,
                    address taker,
                    uint256 ethAvailable,
                    bytes memory takerData
                ) internal {
                    if (taker == address (0)) {
                        taker = msg.sender;
                    } else {
                        require(taker != address(this), "_buy721Ex/TAKER_CANNOT_SELF");
                    }
                    (, bytes32 orderHash) = _buyNFTEx(sellOrder, signature, BuyParams(1, ethAvailable, taker, takerData));
                    _emitEventSellOrderFilled(
                        sellOrder,
                        taker,
                        orderHash
                    );
                }
                function _emitEventSellOrderFilled(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    address taker,
                    bytes32 orderHash
                ) internal {
                    Fee[] memory fees = new Fee[](sellOrder.fees.length);
                    for (uint256 i; i < sellOrder.fees.length; ) {
                        fees[i].recipient = sellOrder.fees[i].recipient;
                        fees[i].amount = sellOrder.fees[i].amount;
                        unchecked {
                            sellOrder.erc20TokenAmount += fees[i].amount;
                            ++i;
                        }
                    }
                    emit ERC721SellOrderFilled(
                        orderHash,
                        sellOrder.maker,
                        taker,
                        sellOrder.nonce,
                        sellOrder.erc20Token,
                        sellOrder.erc20TokenAmount,
                        fees,
                        sellOrder.nft,
                        sellOrder.nftId
                    );
                }
                function _emitEventBuyOrderFilled(
                    LibNFTOrder.NFTBuyOrder memory buyOrder,
                    address taker,
                    uint256 nftId,
                    bytes32 orderHash
                ) internal {
                    Fee[] memory fees = new Fee[](buyOrder.fees.length);
                    for (uint256 i; i < buyOrder.fees.length; ) {
                        fees[i].recipient = buyOrder.fees[i].recipient;
                        fees[i].amount = buyOrder.fees[i].amount;
                        unchecked {
                            buyOrder.erc20TokenAmount += fees[i].amount;
                            ++i;
                        }
                    }
                    emit ERC721BuyOrderFilled(
                        orderHash,
                        buyOrder.maker,
                        taker,
                        buyOrder.nonce,
                        buyOrder.erc20Token,
                        buyOrder.erc20TokenAmount,
                        fees,
                        buyOrder.nft,
                        nftId
                    );
                }
                /// @dev Checks whether the given signature is valid for the
                ///      the given ERC721 sell order. Reverts if not.
                /// @param order The ERC721 sell order.
                /// @param signature The signature to validate.
                function validateERC721SellOrderSignature(LibNFTOrder.NFTSellOrder memory order, LibSignature.Signature memory signature) public override view {
                    _validateOrderSignature(getERC721SellOrderHash(order), signature, order.maker);
                }
                /// @dev Checks whether the given signature is valid for the
                ///      the given ERC721 buy order. Reverts if not.
                /// @param order The ERC721 buy order.
                /// @param signature The signature to validate.
                function validateERC721BuyOrderSignature(LibNFTOrder.NFTBuyOrder memory order, LibSignature.Signature memory signature) public override view {
                    _validateOrderSignature(getERC721BuyOrderHash(order), signature, order.maker);
                }
                /// @dev Validates that the given signature is valid for the
                ///      given maker and order hash. Reverts if the signature
                ///      is not valid.
                /// @param orderHash The hash of the order that was signed.
                /// @param signature The signature to check.
                /// @param maker The maker of the order.
                function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal override view {
                    if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) {
                        require(LibERC721OrdersStorage.getStorage().preSigned[orderHash]
                            == LibCommonNftOrdersStorage.getStorage().hashNonces[maker] + 1, "PRESIGNED_INVALID_SIGNER");
                    } else {
                        require(maker != address(0) && maker == ecrecover(orderHash, signature.v, signature.r, signature.s), "INVALID_SIGNER_ERROR");
                    }
                }
                /// @dev Transfers an NFT asset.
                /// @param token The address of the NFT contract.
                /// @param from The address currently holding the asset.
                /// @param to The address to transfer the asset to.
                /// @param tokenId The ID of the asset to transfer.
                function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 /* amount */) internal override {
                    _transferERC721AssetFrom(token, from, to, tokenId);
                }
                /// @dev Updates storage to indicate that the given order
                ///      has been filled by the given amount.
                /// @param order The order that has been filled.
                function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 /* orderHash */, uint128 /* fillAmount */) internal override {
                    _setOrderStatusBit(order.maker, order.nonce);
                }
                function _setOrderStatusBit(address maker, uint256 nonce) private {
                    // The bitvector is indexed by the lower 8 bits of the nonce.
                    uint256 flag = 1 << (nonce & 255);
                    // Update order status bit vector to indicate that the given order
                    // has been cancelled/filled by setting the designated bit to 1.
                    LibERC721OrdersStorage.getStorage().orderStatusByMaker[maker][uint248((nonce >> 8) & ORDER_NONCE_MASK)] |= flag;
                }
                /// @dev Get the current status of an ERC721 sell order.
                /// @param order The ERC721 sell order.
                /// @return status The status of the order.
                function getERC721SellOrderStatus(LibNFTOrder.NFTSellOrder memory order) public override view returns (LibNFTOrder.OrderStatus) {
                    // Check for listingTime.
                    // Gas Optimize, listingTime only used in rare cases.
                    if (order.expiry & 0xffffffff00000000 > 0) {
                        if ((order.expiry >> 32) & 0xffffffff > block.timestamp) {
                            return LibNFTOrder.OrderStatus.INVALID;
                        }
                    }
                    // Check for expiryTime.
                    if (order.expiry & 0xffffffff <= block.timestamp) {
                        return LibNFTOrder.OrderStatus.EXPIRED;
                    }
                    // Check `orderStatusByMaker` state variable to see if the order
                    // has been cancelled or previously filled.
                    LibERC721OrdersStorage.Storage storage stor = LibERC721OrdersStorage.getStorage();
                    // `orderStatusByMaker` is indexed by maker and nonce.
                    uint256 orderStatusBitVector = stor.orderStatusByMaker[order.maker][uint248((order.nonce >> 8) & ORDER_NONCE_MASK)];
                    // The bitvector is indexed by the lower 8 bits of the nonce.
                    uint256 flag = 1 << (order.nonce & 255);
                    // If the designated bit is set, the order has been cancelled or
                    // previously filled, so it is now unfillable.
                    if (orderStatusBitVector & flag != 0) {
                        return LibNFTOrder.OrderStatus.UNFILLABLE;
                    }
                    // Otherwise, the order is fillable.
                    return LibNFTOrder.OrderStatus.FILLABLE;
                }
                /// @dev Get the current status of an ERC721 buy order.
                /// @param order The ERC721 buy order.
                /// @return status The status of the order.
                function getERC721BuyOrderStatus(LibNFTOrder.NFTBuyOrder memory order) public override view returns (LibNFTOrder.OrderStatus) {
                    // Only buy orders with `nftId` == 0 can be property orders.
                    if (order.nftId != 0 && order.nftProperties.length > 0) {
                        return LibNFTOrder.OrderStatus.INVALID;
                    }
                    // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be
                    // transferred from the buyer by a contract.
                    if (address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) {
                        return LibNFTOrder.OrderStatus.INVALID;
                    }
                    return getERC721SellOrderStatus(order.asNFTSellOrder());
                }
                /// @dev Get the order info for an NFT sell order.
                /// @param nftSellOrder The NFT sell order.
                /// @return orderInfo Info about the order.
                function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal override view returns (LibNFTOrder.OrderInfo memory) {
                    LibNFTOrder.OrderInfo memory orderInfo;
                    orderInfo.orderHash = getERC721SellOrderHash(nftSellOrder);
                    orderInfo.status = getERC721SellOrderStatus(nftSellOrder);
                    orderInfo.orderAmount = 1;
                    orderInfo.remainingAmount = orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE ? 1 : 0;
                    return orderInfo;
                }
                /// @dev Get the order info for an NFT buy order.
                /// @param nftBuyOrder The NFT buy order.
                /// @return orderInfo Info about the order.
                function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal override view returns (LibNFTOrder.OrderInfo memory) {
                    LibNFTOrder.OrderInfo memory orderInfo;
                    orderInfo.orderHash = getERC721BuyOrderHash(nftBuyOrder);
                    orderInfo.status = getERC721BuyOrderStatus(nftBuyOrder);
                    orderInfo.orderAmount = 1;
                    orderInfo.remainingAmount = orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE ? 1 : 0;
                    return orderInfo;
                }
                /// @dev Get the EIP-712 hash of an ERC721 sell order.
                /// @param order The ERC721 sell order.
                /// @return orderHash The order hash.
                function getERC721SellOrderHash(LibNFTOrder.NFTSellOrder memory order) public override view returns (bytes32) {
                    return _getEIP712Hash(LibNFTOrder.getNFTSellOrderStructHash(
                            order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]));
                }
                /// @dev Get the EIP-712 hash of an ERC721 buy order.
                /// @param order The ERC721 buy order.
                /// @return orderHash The order hash.
                function getERC721BuyOrderHash(LibNFTOrder.NFTBuyOrder memory order) public override view returns (bytes32) {
                    return _getEIP712Hash(LibNFTOrder.getNFTBuyOrderStructHash(
                            order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]));
                }
                /// @dev Get the order status bit vector for the given
                ///      maker address and nonce range.
                /// @param maker The maker of the order.
                /// @param nonceRange Order status bit vectors are indexed
                ///        by maker address and the upper 248 bits of the
                ///        order nonce. We define `nonceRange` to be these
                ///        248 bits.
                /// @return bitVector The order status bit vector for the
                ///         given maker and nonce range.
                function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) external override view returns (uint256) {
                    uint248 range = uint248(nonceRange & ORDER_NONCE_MASK);
                    return LibERC721OrdersStorage.getStorage().orderStatusByMaker[maker][range];
                }
                function getHashNonce(address maker) external override view returns (uint256) {
                    return LibCommonNftOrdersStorage.getStorage().hashNonces[maker];
                }
                /// Increment a particular maker's nonce, thereby invalidating all orders that were not signed
                /// with the original nonce.
                function incrementHashNonce() external override {
                    uint256 newHashNonce = ++LibCommonNftOrdersStorage.getStorage().hashNonces[msg.sender];
                    emit HashNonceIncremented(msg.sender, newHashNonce);
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            /// @dev Helpers for moving ERC721 assets around.
            abstract contract FixinERC721Spender {
                // Mask of the lower 20 bytes of a bytes32.
                uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
                /// @dev Transfer an ERC721 asset from `owner` to `to`.
                /// @param token The address of the ERC721 token contract.
                /// @param owner The owner of the asset.
                /// @param to The recipient of the asset.
                /// @param tokenId The token ID of the asset to transfer.
                function _transferERC721AssetFrom(address token, address owner, address to, uint256 tokenId) internal {
                    uint256 success;
                    assembly {
                        let ptr := mload(0x40) // free memory pointer
                        // selector for transferFrom(address,address,uint256)
                        mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                        mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK))
                        mstore(add(ptr, 0x24), and(to, ADDRESS_MASK))
                        mstore(add(ptr, 0x44), tokenId)
                        success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, 0, 0)
                    }
                    require(success != 0, "_transferERC721/TRANSFER_FAILED");
                }
                /// @dev Safe transfer an ERC721 asset from `owner` to `to`.
                /// @param token The address of the ERC721 token contract.
                /// @param owner The owner of the asset.
                /// @param to The recipient of the asset.
                /// @param tokenId The token ID of the asset to transfer.
                function _safeTransferERC721AssetFrom(address token, address owner, address to, uint256 tokenId) internal {
                    uint256 success;
                    assembly {
                        let ptr := mload(0x40) // free memory pointer
                        // selector for safeTransferFrom(address,address,uint256)
                        mstore(ptr, 0x42842e0e00000000000000000000000000000000000000000000000000000000)
                        mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK))
                        mstore(add(ptr, 0x24), and(to, ADDRESS_MASK))
                        mstore(add(ptr, 0x44), tokenId)
                        success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, 0, 0)
                    }
                    require(success != 0, "_safeTransferERC721/TRANSFER_FAILED");
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Copyright 2022 Element.Market
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "./LibStorage.sol";
            library LibCommonNftOrdersStorage {
                /// @dev Storage bucket for this feature.
                struct Storage {
                    /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */
                    // The current nonce for the maker represents the only valid nonce that can be signed by the maker
                    // If a signature was signed with a nonce that's different from the one stored in nonces, it
                    // will fail validation.
                    mapping(address => uint256) hashNonces;
                }
                /// @dev Get the storage bucket for this contract.
                function getStorage() internal pure returns (Storage storage stor) {
                    uint256 storageSlot = LibStorage.STORAGE_ID_COMMON_NFT_ORDERS;
                    // Dip into assembly to change the slot pointed to by the local
                    // variable `stor`.
                    // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
                    assembly { stor.slot := storageSlot }
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "./LibStorage.sol";
            /// @dev Storage helpers for `ERC721OrdersFeature`.
            library LibERC721OrdersStorage {
                /// @dev Storage bucket for this feature.
                struct Storage {
                    // maker => nonce range => order status bit vector
                    mapping(address => mapping(uint248 => uint256)) orderStatusByMaker;
                    // order hash => hashNonce
                    mapping(bytes32 => uint256) preSigned;
                }
                /// @dev Get the storage bucket for this contract.
                function getStorage() internal pure returns (Storage storage stor) {
                    uint256 storageSlot = LibStorage.STORAGE_ID_ERC721_ORDERS;
                    // Dip into assembly to change the slot pointed to by the local
                    // variable `stor`.
                    // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
                    assembly { stor.slot := storageSlot }
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2021 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import "../libs/LibNFTOrder.sol";
            import "../libs/LibSignature.sol";
            import "./INFTOrdersFeature.sol";
            /// @dev Feature for interacting with ERC721 orders.
            interface IERC721OrdersFeature is INFTOrdersFeature {
                /// @dev Emitted whenever an `ERC721SellOrder` is filled.
                /// @param orderHash The `ERC721SellOrder` hash.
                /// @param maker The maker of the order.
                /// @param taker The taker of the order.
                /// @param erc20Token The address of the ERC20 token.
                /// @param erc20TokenAmount The amount of ERC20 token to sell.
                /// @param erc721Token The address of the ERC721 token.
                /// @param erc721TokenId The ID of the ERC721 asset.
                event ERC721SellOrderFilled(
                    bytes32 orderHash,
                    address maker,
                    address taker,
                    uint256 nonce,
                    IERC20 erc20Token,
                    uint256 erc20TokenAmount,
                    Fee[] fees,
                    address erc721Token,
                    uint256 erc721TokenId
                );
                /// @dev Emitted whenever an `ERC721BuyOrder` is filled.
                /// @param orderHash The `ERC721BuyOrder` hash.
                /// @param maker The maker of the order.
                /// @param taker The taker of the order.
                /// @param erc20Token The address of the ERC20 token.
                /// @param erc20TokenAmount The amount of ERC20 token to buy.
                /// @param erc721Token The address of the ERC721 token.
                /// @param erc721TokenId The ID of the ERC721 asset.
                event ERC721BuyOrderFilled(
                    bytes32 orderHash,
                    address maker,
                    address taker,
                    uint256 nonce,
                    IERC20 erc20Token,
                    uint256 erc20TokenAmount,
                    Fee[] fees,
                    address erc721Token,
                    uint256 erc721TokenId
                );
                /// @dev Emitted when an `ERC721SellOrder` is pre-signed.
                ///      Contains all the fields of the order.
                event ERC721SellOrderPreSigned(
                    address maker,
                    address taker,
                    uint256 expiry,
                    uint256 nonce,
                    IERC20 erc20Token,
                    uint256 erc20TokenAmount,
                    LibNFTOrder.Fee[] fees,
                    address erc721Token,
                    uint256 erc721TokenId
                );
                /// @dev Emitted when an `ERC721BuyOrder` is pre-signed.
                ///      Contains all the fields of the order.
                event ERC721BuyOrderPreSigned(
                    address maker,
                    address taker,
                    uint256 expiry,
                    uint256 nonce,
                    IERC20 erc20Token,
                    uint256 erc20TokenAmount,
                    LibNFTOrder.Fee[] fees,
                    address erc721Token,
                    uint256 erc721TokenId,
                    LibNFTOrder.Property[] nftProperties
                );
                /// @dev Emitted whenever an `ERC721Order` is cancelled.
                /// @param maker The maker of the order.
                /// @param nonce The nonce of the order that was cancelled.
                event ERC721OrderCancelled(address maker, uint256 nonce);
                /// @dev Emitted HashNonceIncremented.
                event HashNonceIncremented(address maker, uint256 newHashNonce);
                /// @dev Sells an ERC721 asset to fill the given order.
                /// @param buyOrder The ERC721 buy order.
                /// @param signature The order signature from the maker.
                /// @param erc721TokenId The ID of the ERC721 asset being
                ///        sold. If the given order specifies properties,
                ///        the asset must satisfy those properties. Otherwise,
                ///        it must equal the tokenId in the order.
                /// @param unwrapNativeToken If this parameter is true and the
                ///        ERC20 token of the order is e.g. WETH, unwraps the
                ///        token before transferring it to the taker.
                function sellERC721(LibNFTOrder.NFTBuyOrder calldata buyOrder, LibSignature.Signature calldata signature, uint256 erc721TokenId, bool unwrapNativeToken, bytes calldata takerData) external;
                /// @dev Buys an ERC721 asset by filling the given order.
                /// @param sellOrder The ERC721 sell order.
                /// @param signature The order signature.
                function buyERC721(LibNFTOrder.NFTSellOrder calldata sellOrder, LibSignature.Signature calldata signature) external payable;
                /// @dev Buys an ERC721 asset by filling the given order.
                /// @param sellOrder The ERC721 sell order.
                /// @param signature The order signature.
                /// @param taker The address to receive ERC721. If this parameter
                ///         is zero, transfer ERC721 to `msg.sender`.
                function buyERC721Ex(LibNFTOrder.NFTSellOrder calldata sellOrder, LibSignature.Signature calldata signature, address taker, bytes calldata takerData) external payable;
                /// @dev Cancel a single ERC721 order by its nonce. The caller
                ///      should be the maker of the order. Silently succeeds if
                ///      an order with the same nonce has already been filled or
                ///      cancelled.
                /// @param orderNonce The order nonce.
                function cancelERC721Order(uint256 orderNonce) external;
                /// @dev Cancel multiple ERC721 orders by their nonces. The caller
                ///      should be the maker of the orders. Silently succeeds if
                ///      an order with the same nonce has already been filled or
                ///      cancelled.
                /// @param orderNonces The order nonces.
                function batchCancelERC721Orders(uint256[] calldata orderNonces) external;
                /// @dev Buys multiple ERC721 assets by filling the
                ///      given orders.
                /// @param sellOrders The ERC721 sell orders.
                /// @param signatures The order signatures.
                /// @param revertIfIncomplete If true, reverts if this
                ///        function fails to fill any individual order.
                /// @return successes An array of booleans corresponding to whether
                ///         each order in `orders` was successfully filled.
                function batchBuyERC721s(
                    LibNFTOrder.NFTSellOrder[] calldata sellOrders,
                    LibSignature.Signature[] calldata signatures,
                    bool revertIfIncomplete
                ) external payable returns (bool[] memory successes);
                /// @dev Buys multiple ERC721 assets by filling the
                ///      given orders.
                /// @param sellOrders The ERC721 sell orders.
                /// @param signatures The order signatures.
                /// @param takers The address to receive ERC721.
                /// @param takerDatas The data (if any) to pass to the taker
                ///        callback for each order. Refer to the `takerData`
                ///        parameter to for `buyERC721`.
                /// @param revertIfIncomplete If true, reverts if this
                ///        function fails to fill any individual order.
                /// @return successes An array of booleans corresponding to whether
                ///         each order in `orders` was successfully filled.
                function batchBuyERC721sEx(
                    LibNFTOrder.NFTSellOrder[] calldata sellOrders,
                    LibSignature.Signature[] calldata signatures,
                    address[] calldata takers,
                    bytes[] calldata takerDatas,
                    bool revertIfIncomplete
                ) external payable returns (bool[] memory successes);
                /// @dev Matches a pair of complementary orders that have
                ///      a non-negative spread. Each order is filled at
                ///      their respective price, and the matcher receives
                ///      a profit denominated in the ERC20 token.
                /// @param sellOrder Order selling an ERC721 asset.
                /// @param buyOrder Order buying an ERC721 asset.
                /// @param sellOrderSignature Signature for the sell order.
                /// @param buyOrderSignature Signature for the buy order.
                /// @return profit The amount of profit earned by the caller
                ///         of this function (denominated in the ERC20 token
                ///         of the matched orders).
                function matchERC721Orders(
                    LibNFTOrder.NFTSellOrder calldata sellOrder,
                    LibNFTOrder.NFTBuyOrder calldata buyOrder,
                    LibSignature.Signature calldata sellOrderSignature,
                    LibSignature.Signature calldata buyOrderSignature
                ) external returns (uint256 profit);
                /// @dev Matches pairs of complementary orders that have
                ///      non-negative spreads. Each order is filled at
                ///      their respective price, and the matcher receives
                ///      a profit denominated in the ERC20 token.
                /// @param sellOrders Orders selling ERC721 assets.
                /// @param buyOrders Orders buying ERC721 assets.
                /// @param sellOrderSignatures Signatures for the sell orders.
                /// @param buyOrderSignatures Signatures for the buy orders.
                /// @return profits The amount of profit earned by the caller
                ///         of this function for each pair of matched orders
                ///         (denominated in the ERC20 token of the order pair).
                /// @return successes An array of booleans corresponding to
                ///         whether each pair of orders was successfully matched.
                function batchMatchERC721Orders(
                    LibNFTOrder.NFTSellOrder[] calldata sellOrders,
                    LibNFTOrder.NFTBuyOrder[] calldata buyOrders,
                    LibSignature.Signature[] calldata sellOrderSignatures,
                    LibSignature.Signature[] calldata buyOrderSignatures
                ) external returns (uint256[] memory profits, bool[] memory successes);
                /// @dev Callback for the ERC721 `safeTransferFrom` function.
                ///      This callback can be used to sell an ERC721 asset if
                ///      a valid ERC721 order, signature and `unwrapNativeToken`
                ///      are encoded in `data`. This allows takers to sell their
                ///      ERC721 asset without first calling `setApprovalForAll`.
                /// @param operator The address which called `safeTransferFrom`.
                /// @param from The address which previously owned the token.
                /// @param tokenId The ID of the asset being transferred.
                /// @param data Additional data with no specified format. If a
                ///        valid ERC721 order, signature and `unwrapNativeToken`
                ///        are encoded in `data`, this function will try to fill
                ///        the order using the received asset.
                /// @return success The selector of this function (0x150b7a02),
                ///         indicating that the callback succeeded.
                function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4 success);
                /// @dev Approves an ERC721 sell order on-chain. After pre-signing
                ///      the order, the `PRESIGNED` signature type will become
                ///      valid for that order and signer.
                /// @param order An ERC721 sell order.
                function preSignERC721SellOrder(LibNFTOrder.NFTSellOrder calldata order) external;
                /// @dev Approves an ERC721 buy order on-chain. After pre-signing
                ///      the order, the `PRESIGNED` signature type will become
                ///      valid for that order and signer.
                /// @param order An ERC721 buy order.
                function preSignERC721BuyOrder(LibNFTOrder.NFTBuyOrder calldata order) external;
                /// @dev Checks whether the given signature is valid for the
                ///      the given ERC721 sell order. Reverts if not.
                /// @param order The ERC721 sell order.
                /// @param signature The signature to validate.
                function validateERC721SellOrderSignature(LibNFTOrder.NFTSellOrder calldata order, LibSignature.Signature calldata signature) external view;
                /// @dev Checks whether the given signature is valid for the
                ///      the given ERC721 buy order. Reverts if not.
                /// @param order The ERC721 buy order.
                /// @param signature The signature to validate.
                function validateERC721BuyOrderSignature(LibNFTOrder.NFTBuyOrder calldata order, LibSignature.Signature calldata signature) external view;
                /// @dev Get the current status of an ERC721 sell order.
                /// @param order The ERC721 sell order.
                /// @return status The status of the order.
                function getERC721SellOrderStatus(LibNFTOrder.NFTSellOrder calldata order) external view returns (LibNFTOrder.OrderStatus);
                /// @dev Get the current status of an ERC721 buy order.
                /// @param order The ERC721 buy order.
                /// @return status The status of the order.
                function getERC721BuyOrderStatus(LibNFTOrder.NFTBuyOrder calldata order) external view returns (LibNFTOrder.OrderStatus);
                /// @dev Get the EIP-712 hash of an ERC721 sell order.
                /// @param order The ERC721 sell order.
                /// @return orderHash The order hash.
                function getERC721SellOrderHash(LibNFTOrder.NFTSellOrder calldata order) external view returns (bytes32);
                /// @dev Get the EIP-712 hash of an ERC721 buy order.
                /// @param order The ERC721 buy order.
                /// @return orderHash The order hash.
                function getERC721BuyOrderHash(LibNFTOrder.NFTBuyOrder calldata order) external view returns (bytes32);
                /// @dev Get the order status bit vector for the given
                ///      maker address and nonce range.
                /// @param maker The maker of the order.
                /// @param nonceRange Order status bit vectors are indexed
                ///        by maker address and the upper 248 bits of the
                ///        order nonce. We define `nonceRange` to be these
                ///        248 bits.
                /// @return bitVector The order status bit vector for the
                ///         given maker and nonce range.
                function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) external view returns (uint256);
                function getHashNonce(address maker) external view returns (uint256);
                /// Increment a particular maker's nonce, thereby invalidating all orders that were not signed
                /// with the original nonce.
                function incrementHashNonce() external;
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2021 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import "../../fixins/FixinEIP712.sol";
            import "../../fixins/FixinTokenSpender.sol";
            import "../../vendor/IEtherToken.sol";
            import "../../vendor/IFeeRecipient.sol";
            import "../libs/LibSignature.sol";
            import "../libs/LibNFTOrder.sol";
            /// @dev Abstract base contract inherited by ERC721OrdersFeature and NFTOrders
            abstract contract NFTOrders is FixinEIP712, FixinTokenSpender {
                using LibNFTOrder for LibNFTOrder.NFTBuyOrder;
                /// @dev Native token pseudo-address.
                address constant internal NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
                /// @dev The WETH token contract.
                IEtherToken internal immutable WETH;
                /// @dev The implementation address of this feature.
                address internal immutable _implementation;
                /// @dev The magic return value indicating the success of a `receiveZeroExFeeCallback`.
                bytes4 private constant FEE_CALLBACK_MAGIC_BYTES = IFeeRecipient.receiveZeroExFeeCallback.selector;
                constructor(IEtherToken weth) {
                    require(address(weth) != address(0), "WETH_ADDRESS_ERROR");
                    WETH = weth;
                    // Remember this feature's original address.
                    _implementation = address(this);
                }
                event TakerDataEmitted(
                    bytes32 orderHash,
                    bytes takerData
                );
                struct SellParams {
                    uint128 sellAmount;
                    uint256 tokenId;
                    bool unwrapNativeToken;
                    address taker;
                    address currentNftOwner;
                    bytes takerData;
                }
                struct BuyParams {
                    uint128 buyAmount;
                    uint256 ethAvailable;
                    address taker;
                    bytes takerData;
                }
                // Core settlement logic for selling an NFT asset.
                function _sellNFT(
                    LibNFTOrder.NFTBuyOrder memory buyOrder,
                    LibSignature.Signature memory signature,
                    SellParams memory params
                ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) {
                    LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(buyOrder);
                    orderHash = orderInfo.orderHash;
                    // Check that the order can be filled.
                    _validateBuyOrder(buyOrder, signature, orderInfo, params.taker, params.tokenId, params.takerData);
                    // Check amount.
                    if (params.sellAmount > orderInfo.remainingAmount) {
                        revert("_sellNFT/EXCEEDS_REMAINING_AMOUNT");
                    }
                    // Update the order state.
                    _updateOrderState(buyOrder.asNFTSellOrder(), orderInfo.orderHash, params.sellAmount);
                    // Calculate erc20 pay amount.
                    erc20FillAmount = (params.sellAmount == orderInfo.orderAmount) ?
                        buyOrder.erc20TokenAmount : buyOrder.erc20TokenAmount * params.sellAmount / orderInfo.orderAmount;
                    if (params.unwrapNativeToken) {
                        // The ERC20 token must be WETH for it to be unwrapped.
                        require(buyOrder.erc20Token == WETH, "_sellNFT/ERC20_TOKEN_MISMATCH_ERROR");
                        // Transfer the WETH from the maker to the Exchange Proxy
                        // so we can unwrap it before sending it to the seller.
                        // TODO: Probably safe to just use WETH.transferFrom for some
                        //       small gas savings
                        _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), erc20FillAmount);
                        // Unwrap WETH into ETH.
                        WETH.withdraw(erc20FillAmount);
                        // Send ETH to the seller.
                        _transferEth(payable(params.taker), erc20FillAmount);
                    } else {
                        // Transfer the ERC20 token from the buyer to the seller.
                        _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, params.taker, erc20FillAmount);
                    }
                    // Transfer the NFT asset to the buyer.
                    // If this function is called from the
                    // `onNFTReceived` callback the Exchange Proxy
                    // holds the asset. Otherwise, transfer it from
                    // the seller.
                    _transferNFTAssetFrom(buyOrder.nft, params.currentNftOwner, buyOrder.maker, params.tokenId, params.sellAmount);
                    // The buyer pays the order fees.
                    _payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, params.sellAmount, orderInfo.orderAmount, false);
                    // Emit TakerData Event.
                    if (params.takerData.length > 0x20) {
                        _emitEventTakerData(orderHash, params.takerData);
                    }
                }
                // Core settlement logic for buying an NFT asset.
                function _buyNFT(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    LibSignature.Signature memory signature,
                    uint128 buyAmount
                ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) {
                    LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder);
                    orderHash = orderInfo.orderHash;
                    // Check that the order can be filled.
                    _validateSellOrder(sellOrder, signature, orderInfo, msg.sender);
                    // Check amount.
                    if (buyAmount > orderInfo.remainingAmount) {
                        revert("_buyNFT/EXCEEDS_REMAINING_AMOUNT");
                    }
                    // Update the order state.
                    _updateOrderState(sellOrder, orderInfo.orderHash, buyAmount);
                    // Calculate erc20 pay amount.
                    erc20FillAmount = (buyAmount == orderInfo.orderAmount) ?
                        sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * buyAmount, orderInfo.orderAmount);
                    // Transfer the NFT asset to the buyer (`msg.sender`).
                    _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, msg.sender, sellOrder.nftId, buyAmount);
                    if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) {
                        // Transfer ETH to the seller.
                        _transferEth(payable(sellOrder.maker), erc20FillAmount);
                        // Fees are paid from the EP's current balance of ETH.
                        _payFees(sellOrder, address(this), buyAmount, orderInfo.orderAmount, true);
                    } else {
                        // Transfer ERC20 token from the buyer to the seller.
                        _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount);
                        // The buyer pays fees.
                        _payFees(sellOrder, msg.sender, buyAmount, orderInfo.orderAmount, false);
                    }
                }
                function _buyNFTEx(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    LibSignature.Signature memory signature,
                    BuyParams memory params
                ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) {
                    LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder);
                    orderHash = orderInfo.orderHash;
                    // Check that the order can be filled.
                    _validateSellOrder(sellOrder, signature, orderInfo, params.taker);
                    // Check amount.
                    if (params.buyAmount > orderInfo.remainingAmount) {
                        revert("_buyNFTEx/EXCEEDS_REMAINING_AMOUNT");
                    }
                    // Update the order state.
                    _updateOrderState(sellOrder, orderInfo.orderHash, params.buyAmount);
                    // Dutch Auction
                    if (sellOrder.expiry >> 252 == 1) {
                        uint256 count = (sellOrder.expiry >> 64) & 0xffffffff;
                        if (count > 0) {
                            _resetDutchAuctionTokenAmountAndFees(sellOrder, count);
                        }
                    }
                    // Calculate erc20 pay amount.
                    erc20FillAmount = (params.buyAmount == orderInfo.orderAmount) ?
                        sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * params.buyAmount, orderInfo.orderAmount);
                    // Transfer the NFT asset to the buyer.
                    _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, params.taker, sellOrder.nftId, params.buyAmount);
                    uint256 ethAvailable = params.ethAvailable;
                    if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) {
                        uint256 totalPaid = erc20FillAmount + _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount);
                        if (ethAvailable < totalPaid) {
                            // Transfer WETH from the buyer to this contract.
                            uint256 withDrawAmount = totalPaid - ethAvailable;
                            _transferERC20TokensFrom(WETH, msg.sender, address(this), withDrawAmount);
                            // Unwrap WETH into ETH.
                            WETH.withdraw(withDrawAmount);
                        }
                        // Transfer ETH to the seller.
                        _transferEth(payable(sellOrder.maker), erc20FillAmount);
                        // Fees are paid from the EP's current balance of ETH.
                        _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true);
                    } else if (sellOrder.erc20Token == WETH) {
                        uint256 totalFeesPaid = _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount);
                        if (ethAvailable > totalFeesPaid) {
                            uint256 depositAmount = ethAvailable - totalFeesPaid;
                            if (depositAmount < erc20FillAmount) {
                                // Transfer WETH from the buyer to this contract.
                                _transferERC20TokensFrom(WETH, msg.sender, address(this), (erc20FillAmount - depositAmount));
                            } else {
                                depositAmount = erc20FillAmount;
                            }
                            // Wrap ETH.
                            WETH.deposit{value: depositAmount}();
                            // Transfer WETH to the seller.
                            _transferERC20Tokens(WETH, sellOrder.maker, erc20FillAmount);
                            // Fees are paid from the EP's current balance of ETH.
                            _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true);
                        } else {
                            // Transfer WETH from the buyer to the seller.
                            _transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount);
                            if (ethAvailable > 0) {
                                if (ethAvailable < totalFeesPaid) {
                                    // Transfer WETH from the buyer to this contract.
                                    uint256 value = totalFeesPaid - ethAvailable;
                                    _transferERC20TokensFrom(WETH, msg.sender, address(this), value);
                                    // Unwrap WETH into ETH.
                                    WETH.withdraw(value);
                                }
                                // Fees are paid from the EP's current balance of ETH.
                                _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true);
                            } else {
                                // The buyer pays fees using WETH.
                                _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false);
                            }
                        }
                    } else {
                        // Transfer ERC20 token from the buyer to the seller.
                        _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount);
                        // The buyer pays fees.
                        _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false);
                    }
                    // Emit TakerData Event.
                    if (params.takerData.length > 0x20) {
                        _emitEventTakerData(orderHash, params.takerData);
                    }
                }
                function _emitEventTakerData(bytes32 orderHash, bytes memory takerData) internal {
                    uint256 startPoint;
                    uint256 endPoint;
                    assembly {
                        let data0 := mload(add(takerData, 0x20))
                        // data0 == [4 bytes(magic bytes) + 24 bytes(unused) + 2 bytes(endPoint) + 2 bytes(startPoint)]
                        if eq(shr(224, data0), 0xfeefeefe) {
                            startPoint := and(data0, 0xffff)
                            endPoint := and(shr(16, data0), 0xffff)
                        }
                    }
                    if (startPoint >= endPoint || (endPoint + 0x20) > takerData.length) {
                        return;
                    }
                    bytes memory data;
                    bytes32 dataBefore;
                    assembly {
                        data := add(add(takerData, 0x20), startPoint)
                        dataBefore := mload(data)
                        mstore(data, sub(endPoint, startPoint))
                    }
                    emit TakerDataEmitted(orderHash, data);
                    assembly {
                        mstore(data, dataBefore)
                    }
                }
                function _validateSellOrder(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    LibSignature.Signature memory signature,
                    LibNFTOrder.OrderInfo memory orderInfo,
                    address taker
                ) internal view {
                    // Taker must match the order taker, if one is specified.
                    require(sellOrder.taker == address(0) || sellOrder.taker == taker, "_validateOrder/ONLY_TAKER");
                    // Check that the order is valid and has not expired, been cancelled,
                    // or been filled.
                    require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL");
                    // Check the signature.
                    _validateOrderSignature(orderInfo.orderHash, signature, sellOrder.maker);
                }
                function _validateBuyOrder(
                    LibNFTOrder.NFTBuyOrder memory buyOrder,
                    LibSignature.Signature memory signature,
                    LibNFTOrder.OrderInfo memory orderInfo,
                    address taker,
                    uint256 tokenId,
                    bytes memory takerData
                ) internal view {
                    // The ERC20 token cannot be ETH.
                    require(address(buyOrder.erc20Token) != NATIVE_TOKEN_ADDRESS, "_validateBuyOrder/TOKEN_MISMATCH");
                    // Taker must match the order taker, if one is specified.
                    require(buyOrder.taker == address(0) || buyOrder.taker == taker, "_validateBuyOrder/ONLY_TAKER");
                    // Check that the order is valid and has not expired, been cancelled,
                    // or been filled.
                    require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL");
                    // Check that the asset with the given token ID satisfies the properties
                    // specified by the order.
                    _validateOrderProperties(buyOrder, tokenId, takerData);
                    // Check the signature.
                    _validateOrderSignature(orderInfo.orderHash, signature, buyOrder.maker);
                }
                function _resetDutchAuctionTokenAmountAndFees(LibNFTOrder.NFTSellOrder memory order, uint256 count) internal view {
                    require(count <= 100000000, "COUNT_OUT_OF_SIDE");
                    uint256 listingTime = (order.expiry >> 32) & 0xffffffff;
                    uint256 denominator = ((order.expiry & 0xffffffff) - listingTime) * 100000000;
                    uint256 multiplier = (block.timestamp - listingTime) * count;
                    // Reset erc20TokenAmount
                    uint256 amount = order.erc20TokenAmount;
                    order.erc20TokenAmount = amount - amount * multiplier / denominator;
                    // Reset fees
                    for (uint256 i = 0; i < order.fees.length; i++) {
                        amount = order.fees[i].amount;
                        order.fees[i].amount = amount - amount * multiplier / denominator;
                    }
                }
                function _resetEnglishAuctionTokenAmountAndFees(
                    LibNFTOrder.NFTSellOrder memory sellOrder,
                    uint256 buyERC20Amount,
                    uint256 fillAmount,
                    uint256 orderAmount
                ) internal pure {
                    uint256 sellOrderFees = _calcTotalFeesPaid(sellOrder.fees, fillAmount, orderAmount);
                    uint256 sellTotalAmount = sellOrderFees + sellOrder.erc20TokenAmount;
                    if (buyERC20Amount != sellTotalAmount) {
                        uint256 spread = buyERC20Amount - sellTotalAmount;
                        uint256 sum;
                        // Reset fees
                        if (sellTotalAmount > 0) {
                            for (uint256 i = 0; i < sellOrder.fees.length; i++) {
                                uint256 diff = spread * sellOrder.fees[i].amount / sellTotalAmount;
                                sellOrder.fees[i].amount += diff;
                                sum += diff;
                            }
                        }
                        // Reset erc20TokenAmount
                        sellOrder.erc20TokenAmount += spread - sum;
                    }
                }
                function _ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                    // ceil(a / b) = floor((a + b - 1) / b)
                    return (a + b - 1) / b;
                }
                function _calcTotalFeesPaid(LibNFTOrder.Fee[] memory fees, uint256 fillAmount, uint256 orderAmount) private pure returns (uint256 totalFeesPaid) {
                    if (fillAmount == orderAmount) {
                        for (uint256 i = 0; i < fees.length; i++) {
                            totalFeesPaid += fees[i].amount;
                        }
                    } else {
                        for (uint256 i = 0; i < fees.length; i++) {
                            totalFeesPaid += fees[i].amount * fillAmount / orderAmount;
                        }
                    }
                    return totalFeesPaid;
                }
                function _payFees(
                    LibNFTOrder.NFTSellOrder memory order,
                    address payer,
                    uint128 fillAmount,
                    uint128 orderAmount,
                    bool useNativeToken
                ) internal returns (uint256 totalFeesPaid) {
                    for (uint256 i = 0; i < order.fees.length; i++) {
                        LibNFTOrder.Fee memory fee = order.fees[i];
                        uint256 feeFillAmount = (fillAmount == orderAmount) ? fee.amount : fee.amount * fillAmount / orderAmount;
                        if (useNativeToken) {
                            // Transfer ETH to the fee recipient.
                            _transferEth(payable(fee.recipient), feeFillAmount);
                        } else {
                            if (feeFillAmount > 0) {
                                // Transfer ERC20 token from payer to recipient.
                                _transferERC20TokensFrom(order.erc20Token, payer, fee.recipient, feeFillAmount);
                            }
                        }
                        // Note that the fee callback is _not_ called if zero
                        // `feeData` is provided. If `feeData` is provided, we assume
                        // the fee recipient is a contract that implements the
                        // `IFeeRecipient` interface.
                        if (fee.feeData.length > 0) {
                            // Invoke the callback
                            bytes4 callbackResult = IFeeRecipient(fee.recipient).receiveZeroExFeeCallback(
                                useNativeToken ? NATIVE_TOKEN_ADDRESS : address(order.erc20Token),
                                feeFillAmount,
                                fee.feeData
                            );
                            // Check for the magic success bytes
                            require(callbackResult == FEE_CALLBACK_MAGIC_BYTES, "_payFees/CALLBACK_FAILED");
                        }
                        // Sum the fees paid
                        totalFeesPaid += feeFillAmount;
                    }
                    return totalFeesPaid;
                }
                function _validateOrderProperties(LibNFTOrder.NFTBuyOrder memory order, uint256 tokenId, bytes memory takerData) internal view {
                    // If no properties are specified, check that the given
                    // `tokenId` matches the one specified in the order.
                    if (order.nftProperties.length == 0) {
                        require(tokenId == order.nftId, "_validateProperties/TOKEN_ID_ERR");
                    } else {
                        // Validate each property
                        for (uint256 i = 0; i < order.nftProperties.length; i++) {
                            LibNFTOrder.Property memory property = order.nftProperties[i];
                            // `address(0)` is interpreted as a no-op. Any token ID
                            // will satisfy a property with `propertyValidator == address(0)`.
                            if (address(property.propertyValidator) != address(0)) {
                                // Call the property validator and throw a descriptive error
                                // if the call reverts.
                                try property.propertyValidator.validateProperty(order.nft, tokenId, property.propertyData, takerData) {
                                } catch (bytes memory /* reason */) {
                                    revert("PROPERTY_VALIDATION_FAILED");
                                }
                            }
                        }
                    }
                }
                /// @dev Validates that the given signature is valid for the
                ///      given maker and order hash. Reverts if the signature
                ///      is not valid.
                /// @param orderHash The hash of the order that was signed.
                /// @param signature The signature to check.
                /// @param maker The maker of the order.
                function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal virtual view;
                /// @dev Transfers an NFT asset.
                /// @param token The address of the NFT contract.
                /// @param from The address currently holding the asset.
                /// @param to The address to transfer the asset to.
                /// @param tokenId The ID of the asset to transfer.
                /// @param amount The amount of the asset to transfer. Always
                ///        1 for ERC721 assets.
                function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 amount) internal virtual;
                /// @dev Updates storage to indicate that the given order
                ///      has been filled by the given amount.
                /// @param order The order that has been filled.
                /// @param orderHash The hash of `order`.
                /// @param fillAmount The amount (denominated in the NFT asset)
                ///        that the order has been filled by.
                function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 orderHash, uint128 fillAmount) internal virtual;
                /// @dev Get the order info for an NFT sell order.
                /// @param nftSellOrder The NFT sell order.
                /// @return orderInfo Info about the order.
                function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory);
                /// @dev Get the order info for an NFT buy order.
                /// @param nftBuyOrder The NFT buy order.
                /// @return orderInfo Info about the order.
                function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory);
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            /// @dev Common storage helpers
            library LibStorage {
                /// @dev What to bit-shift a storage ID by to get its slot.
                ///      This gives us a maximum of 2**128 inline fields in each bucket.
                uint256 constant STORAGE_ID_PROXY = 1 << 128;
                uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128;
                uint256 constant STORAGE_ID_OWNABLE = 3 << 128;
                uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128;
                uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128;
                uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128;
                uint256 constant STORAGE_ID_REENTRANCY_GUARD = 7 << 128;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            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 amount of tokens in existence.
                 */
                function totalSupply() external view returns (uint256);
                /**
                 * @dev Returns the amount of tokens owned by `account`.
                 */
                function balanceOf(address account) external view returns (uint256);
                /**
                 * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
                /**
                 * @dev Moves `amount` tokens from `from` to `to` using the
                 * allowance mechanism. `amount` 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 amount
                ) external returns (bool);
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2021 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import "../../vendor/IPropertyValidator.sol";
            /// @dev A library for common NFT order operations.
            library LibNFTOrder {
                enum OrderStatus {
                    INVALID,
                    FILLABLE,
                    UNFILLABLE,
                    EXPIRED
                }
                struct Property {
                    IPropertyValidator propertyValidator;
                    bytes propertyData;
                }
                struct Fee {
                    address recipient;
                    uint256 amount;
                    bytes feeData;
                }
                struct NFTSellOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address nft;
                    uint256 nftId;
                }
                // All fields except `nftProperties` align
                // with those of NFTSellOrder
                struct NFTBuyOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address nft;
                    uint256 nftId;
                    Property[] nftProperties;
                }
                // All fields except `erc1155TokenAmount` align
                // with those of NFTSellOrder
                struct ERC1155SellOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address erc1155Token;
                    uint256 erc1155TokenId;
                    // End of fields shared with NFTOrder
                    uint128 erc1155TokenAmount;
                }
                // All fields except `erc1155TokenAmount` align
                // with those of NFTBuyOrder
                struct ERC1155BuyOrder {
                    address maker;
                    address taker;
                    uint256 expiry;
                    uint256 nonce;
                    IERC20 erc20Token;
                    uint256 erc20TokenAmount;
                    Fee[] fees;
                    address erc1155Token;
                    uint256 erc1155TokenId;
                    Property[] erc1155TokenProperties;
                    // End of fields shared with NFTOrder
                    uint128 erc1155TokenAmount;
                }
                struct OrderInfo {
                    bytes32 orderHash;
                    OrderStatus status;
                    // `orderAmount` is 1 for all ERC721Orders, and
                    // `erc1155TokenAmount` for ERC1155Orders.
                    uint128 orderAmount;
                    // The remaining amount of the ERC721/ERC1155 asset
                    // that can be filled for the order.
                    uint128 remainingAmount;
                }
                // The type hash for sell orders, which is:
                // keccak256(abi.encodePacked(
                //    "NFTSellOrder(",
                //        "address maker,",
                //        "address taker,",
                //        "uint256 expiry,",
                //        "uint256 nonce,",
                //        "address erc20Token,",
                //        "uint256 erc20TokenAmount,",
                //        "Fee[] fees,",
                //        "address nft,",
                //        "uint256 nftId,",
                //        "uint256 hashNonce",
                //    ")",
                //    "Fee(",
                //        "address recipient,",
                //        "uint256 amount,",
                //        "bytes feeData",
                //    ")"
                // ))
                uint256 private constant _NFT_SELL_ORDER_TYPE_HASH = 0xed676c7f3e8232a311454799b1cf26e75b4abc90c9bf06c9f7e8e79fcc7fe14d;
                // The type hash for buy orders, which is:
                // keccak256(abi.encodePacked(
                //    "NFTBuyOrder(",
                //        "address maker,",
                //        "address taker,",
                //        "uint256 expiry,",
                //        "uint256 nonce,",
                //        "address erc20Token,",
                //        "uint256 erc20TokenAmount,",
                //        "Fee[] fees,",
                //        "address nft,",
                //        "uint256 nftId,",
                //        "Property[] nftProperties,",
                //        "uint256 hashNonce",
                //    ")",
                //    "Fee(",
                //        "address recipient,",
                //        "uint256 amount,",
                //        "bytes feeData",
                //    ")",
                //    "Property(",
                //        "address propertyValidator,",
                //        "bytes propertyData",
                //    ")"
                // ))
                uint256 private constant _NFT_BUY_ORDER_TYPE_HASH = 0xa525d336300f566329800fcbe82fd263226dc27d6c109f060d9a4a364281521c;
                // The type hash for ERC1155 sell orders, which is:
                // keccak256(abi.encodePacked(
                //    "ERC1155SellOrder(",
                //        "address maker,",
                //        "address taker,",
                //        "uint256 expiry,",
                //        "uint256 nonce,",
                //        "address erc20Token,",
                //        "uint256 erc20TokenAmount,",
                //        "Fee[] fees,",
                //        "address erc1155Token,",
                //        "uint256 erc1155TokenId,",
                //        "uint128 erc1155TokenAmount,",
                //        "uint256 hashNonce",
                //    ")",
                //    "Fee(",
                //        "address recipient,",
                //        "uint256 amount,",
                //        "bytes feeData",
                //    ")"
                // ))
                uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda;
                // The type hash for ERC1155 buy orders, which is:
                // keccak256(abi.encodePacked(
                //    "ERC1155BuyOrder(",
                //        "address maker,",
                //        "address taker,",
                //        "uint256 expiry,",
                //        "uint256 nonce,",
                //        "address erc20Token,",
                //        "uint256 erc20TokenAmount,",
                //        "Fee[] fees,",
                //        "address erc1155Token,",
                //        "uint256 erc1155TokenId,",
                //        "Property[] erc1155TokenProperties,",
                //        "uint128 erc1155TokenAmount,",
                //        "uint256 hashNonce",
                //    ")",
                //    "Fee(",
                //        "address recipient,",
                //        "uint256 amount,",
                //        "bytes feeData",
                //    ")",
                //    "Property(",
                //        "address propertyValidator,",
                //        "bytes propertyData",
                //    ")"
                // ))
                uint256 private constant _ERC_1155_BUY_ORDER_TYPE_HASH = 0x1a6eaae1fbed341e0974212ec17f035a9d419cadc3bf5154841cbf7fd605ba48;
                // keccak256(abi.encodePacked(
                //    "Fee(",
                //        "address recipient,",
                //        "uint256 amount,",
                //        "bytes feeData",
                //    ")"
                // ))
                uint256 private constant _FEE_TYPE_HASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115;
                // keccak256(abi.encodePacked(
                //    "Property(",
                //        "address propertyValidator,",
                //        "bytes propertyData",
                //    ")"
                // ))
                uint256 private constant _PROPERTY_TYPE_HASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8;
                // keccak256("");
                bytes32 private constant _EMPTY_ARRAY_KECCAK256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                // keccak256(abi.encodePacked(keccak256(abi.encode(
                //    _PROPERTY_TYPE_HASH,
                //    address(0),
                //    keccak256("")
                // ))));
                bytes32 private constant _NULL_PROPERTY_STRUCT_HASH = 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d;
                uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
                function asNFTSellOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (NFTSellOrder memory order) {
                    assembly { order := nftBuyOrder }
                }
                function asNFTSellOrder(ERC1155SellOrder memory erc1155SellOrder) internal pure returns (NFTSellOrder memory order) {
                    assembly { order := erc1155SellOrder }
                }
                function asNFTBuyOrder(ERC1155BuyOrder memory erc1155BuyOrder) internal pure returns (NFTBuyOrder memory order) {
                    assembly { order := erc1155BuyOrder }
                }
                function asERC1155SellOrder(NFTSellOrder memory nftSellOrder) internal pure returns (ERC1155SellOrder memory order) {
                    assembly { order := nftSellOrder }
                }
                function asERC1155BuyOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (ERC1155BuyOrder memory order) {
                    assembly { order := nftBuyOrder }
                }
                // @dev Get the struct hash of an sell order.
                /// @param order The sell order.
                /// @return structHash The struct hash of the order.
                function getNFTSellOrderStructHash(NFTSellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
                    bytes32 feesHash = _feesHash(order.fees);
                    // Hash in place, equivalent to:
                    // return keccak256(abi.encode(
                    //     _NFT_SELL_ORDER_TYPE_HASH,
                    //     order.maker,
                    //     order.taker,
                    //     order.expiry,
                    //     order.nonce,
                    //     order.erc20Token,
                    //     order.erc20TokenAmount,
                    //     feesHash,
                    //     order.nft,
                    //     order.nftId,
                    //     hashNonce
                    // ));
                    assembly {
                        if lt(order, 32) { invalid() } // Don't underflow memory.
                        let typeHashPos := sub(order, 32) // order - 32
                        let feesHashPos := add(order, 192) // order + (32 * 6)
                        let hashNoncePos := add(order, 288) // order + (32 * 9)
                        let typeHashMemBefore := mload(typeHashPos)
                        let feeHashMemBefore := mload(feesHashPos)
                        let hashNonceMemBefore := mload(hashNoncePos)
                        mstore(typeHashPos, _NFT_SELL_ORDER_TYPE_HASH)
                        mstore(feesHashPos, feesHash)
                        mstore(hashNoncePos, hashNonce)
                        structHash := keccak256(typeHashPos, 352 /* 32 * 11 */ )
                        mstore(typeHashPos, typeHashMemBefore)
                        mstore(feesHashPos, feeHashMemBefore)
                        mstore(hashNoncePos, hashNonceMemBefore)
                    }
                    return structHash;
                }
                /// @dev Get the struct hash of an buy order.
                /// @param order The buy order.
                /// @return structHash The struct hash of the order.
                function getNFTBuyOrderStructHash(NFTBuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
                    bytes32 propertiesHash = _propertiesHash(order.nftProperties);
                    bytes32 feesHash = _feesHash(order.fees);
                    // Hash in place, equivalent to:
                    // return keccak256(abi.encode(
                    //     _NFT_BUY_ORDER_TYPE_HASH,
                    //     order.maker,
                    //     order.taker,
                    //     order.expiry,
                    //     order.nonce,
                    //     order.erc20Token,
                    //     order.erc20TokenAmount,
                    //     feesHash,
                    //     order.nft,
                    //     order.nftId,
                    //     propertiesHash,
                    //     hashNonce
                    // ));
                    assembly {
                        if lt(order, 32) { invalid() } // Don't underflow memory.
                        let typeHashPos := sub(order, 32) // order - 32
                        let feesHashPos := add(order, 192) // order + (32 * 6)
                        let propertiesHashPos := add(order, 288) // order + (32 * 9)
                        let hashNoncePos := add(order, 320) // order + (32 * 10)
                        let typeHashMemBefore := mload(typeHashPos)
                        let feeHashMemBefore := mload(feesHashPos)
                        let propertiesHashMemBefore := mload(propertiesHashPos)
                        let hashNonceMemBefore := mload(hashNoncePos)
                        mstore(typeHashPos, _NFT_BUY_ORDER_TYPE_HASH)
                        mstore(feesHashPos, feesHash)
                        mstore(propertiesHashPos, propertiesHash)
                        mstore(hashNoncePos, hashNonce)
                        structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ )
                        mstore(typeHashPos, typeHashMemBefore)
                        mstore(feesHashPos, feeHashMemBefore)
                        mstore(propertiesHashPos, propertiesHashMemBefore)
                        mstore(hashNoncePos, hashNonceMemBefore)
                    }
                    return structHash;
                }
                /// @dev Get the struct hash of an ERC1155 sell order.
                /// @param order The ERC1155 sell order.
                /// @return structHash The struct hash of the order.
                function getERC1155SellOrderStructHash(ERC1155SellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
                    bytes32 feesHash = _feesHash(order.fees);
                    // Hash in place, equivalent to:
                    // return keccak256(abi.encode(
                    //     _ERC_1155_SELL_ORDER_TYPE_HASH,
                    //     order.maker,
                    //     order.taker,
                    //     order.expiry,
                    //     order.nonce,
                    //     order.erc20Token,
                    //     order.erc20TokenAmount,
                    //     feesHash,
                    //     order.erc1155Token,
                    //     order.erc1155TokenId,
                    //     order.erc1155TokenAmount,
                    //     hashNonce
                    // ));
                    assembly {
                        if lt(order, 32) { invalid() } // Don't underflow memory.
                        let typeHashPos := sub(order, 32) // order - 32
                        let feesHashPos := add(order, 192) // order + (32 * 6)
                        let hashNoncePos := add(order, 320) // order + (32 * 10)
                        let typeHashMemBefore := mload(typeHashPos)
                        let feesHashMemBefore := mload(feesHashPos)
                        let hashNonceMemBefore := mload(hashNoncePos)
                        mstore(typeHashPos, _ERC_1155_SELL_ORDER_TYPE_HASH)
                        mstore(feesHashPos, feesHash)
                        mstore(hashNoncePos, hashNonce)
                        structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ )
                        mstore(typeHashPos, typeHashMemBefore)
                        mstore(feesHashPos, feesHashMemBefore)
                        mstore(hashNoncePos, hashNonceMemBefore)
                    }
                    return structHash;
                }
                /// @dev Get the struct hash of an ERC1155 buy order.
                /// @param order The ERC1155 buy order.
                /// @return structHash The struct hash of the order.
                function getERC1155BuyOrderStructHash(ERC1155BuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
                    bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties);
                    bytes32 feesHash = _feesHash(order.fees);
                    // Hash in place, equivalent to:
                    // return keccak256(abi.encode(
                    //     _ERC_1155_BUY_ORDER_TYPE_HASH,
                    //     order.maker,
                    //     order.taker,
                    //     order.expiry,
                    //     order.nonce,
                    //     order.erc20Token,
                    //     order.erc20TokenAmount,
                    //     feesHash,
                    //     order.erc1155Token,
                    //     order.erc1155TokenId,
                    //     propertiesHash,
                    //     order.erc1155TokenAmount,
                    //     hashNonce
                    // ));
                    assembly {
                        if lt(order, 32) { invalid() } // Don't underflow memory.
                        let typeHashPos := sub(order, 32) // order - 32
                        let feesHashPos := add(order, 192) // order + (32 * 6)
                        let propertiesHashPos := add(order, 288) // order + (32 * 9)
                        let hashNoncePos := add(order, 352) // order + (32 * 11)
                        let typeHashMemBefore := mload(typeHashPos)
                        let feesHashMemBefore := mload(feesHashPos)
                        let propertiesHashMemBefore := mload(propertiesHashPos)
                        let hashNonceMemBefore := mload(hashNoncePos)
                        mstore(typeHashPos, _ERC_1155_BUY_ORDER_TYPE_HASH)
                        mstore(feesHashPos, feesHash)
                        mstore(propertiesHashPos, propertiesHash)
                        mstore(hashNoncePos, hashNonce)
                        structHash := keccak256(typeHashPos, 416 /* 32 * 13 */ )
                        mstore(typeHashPos, typeHashMemBefore)
                        mstore(feesHashPos, feesHashMemBefore)
                        mstore(propertiesHashPos, propertiesHashMemBefore)
                        mstore(hashNoncePos, hashNonceMemBefore)
                    }
                    return structHash;
                }
                // Hashes the `properties` array as part of computing the
                // EIP-712 hash of an `ERC721Order` or `ERC1155Order`.
                function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) {
                    uint256 numProperties = properties.length;
                    // We give `properties.length == 0` and `properties.length == 1`
                    // special treatment because we expect these to be the most common.
                    if (numProperties == 0) {
                        propertiesHash = _EMPTY_ARRAY_KECCAK256;
                    } else if (numProperties == 1) {
                        Property memory property = properties[0];
                        if (address(property.propertyValidator) == address(0) && property.propertyData.length == 0) {
                            propertiesHash = _NULL_PROPERTY_STRUCT_HASH;
                        } else {
                            // propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode(
                            //     _PROPERTY_TYPE_HASH,
                            //     properties[0].propertyValidator,
                            //     keccak256(properties[0].propertyData)
                            // ))));
                            bytes32 dataHash = keccak256(property.propertyData);
                            assembly {
                                // Load free memory pointer
                                let mem := mload(64)
                                mstore(mem, _PROPERTY_TYPE_HASH)
                                // property.propertyValidator
                                mstore(add(mem, 32), and(ADDRESS_MASK, mload(property)))
                                // keccak256(property.propertyData)
                                mstore(add(mem, 64), dataHash)
                                mstore(mem, keccak256(mem, 96))
                                propertiesHash := keccak256(mem, 32)
                            }
                        }
                    } else {
                        bytes32[] memory propertyStructHashArray = new bytes32[](numProperties);
                        for (uint256 i = 0; i < numProperties; i++) {
                            propertyStructHashArray[i] = keccak256(abi.encode(
                                    _PROPERTY_TYPE_HASH, properties[i].propertyValidator, keccak256(properties[i].propertyData)));
                        }
                        assembly {
                            propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32))
                        }
                    }
                }
                // Hashes the `fees` array as part of computing the
                // EIP-712 hash of an `ERC721Order` or `ERC1155Order`.
                function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) {
                    uint256 numFees = fees.length;
                    // We give `fees.length == 0` and `fees.length == 1`
                    // special treatment because we expect these to be the most common.
                    if (numFees == 0) {
                        feesHash = _EMPTY_ARRAY_KECCAK256;
                    } else if (numFees == 1) {
                        // feesHash = keccak256(abi.encodePacked(keccak256(abi.encode(
                        //     _FEE_TYPE_HASH,
                        //     fees[0].recipient,
                        //     fees[0].amount,
                        //     keccak256(fees[0].feeData)
                        // ))));
                        Fee memory fee = fees[0];
                        bytes32 dataHash = keccak256(fee.feeData);
                        assembly {
                            // Load free memory pointer
                            let mem := mload(64)
                            mstore(mem, _FEE_TYPE_HASH)
                            // fee.recipient
                            mstore(add(mem, 32), and(ADDRESS_MASK, mload(fee)))
                            // fee.amount
                            mstore(add(mem, 64), mload(add(fee, 32)))
                            // keccak256(fee.feeData)
                            mstore(add(mem, 96), dataHash)
                            mstore(mem, keccak256(mem, 128))
                            feesHash := keccak256(mem, 32)
                        }
                    } else {
                        bytes32[] memory feeStructHashArray = new bytes32[](numFees);
                        for (uint256 i = 0; i < numFees; i++) {
                            feeStructHashArray[i] = keccak256(abi.encode(_FEE_TYPE_HASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData)));
                        }
                        assembly {
                            feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32))
                        }
                    }
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            /// @dev A library for validating signatures.
            library LibSignature {
                /// @dev Allowed signature types.
                enum SignatureType {
                    EIP712,
                    PRESIGNED
                }
                /// @dev Encoded EC signature.
                struct Signature {
                    // How to validate the signature.
                    SignatureType signatureType;
                    // EC Signature data.
                    uint8 v;
                    // EC Signature data.
                    bytes32 r;
                    // EC Signature data.
                    bytes32 s;
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              CopyrightCopyright 2022 Element.Market Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            /// @dev Feature for interacting with ERC721 orders.
            interface INFTOrdersFeature {
                struct Fee {
                    address recipient;
                    uint256 amount;
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2021 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            interface IPropertyValidator {
                /// @dev Checks that the given ERC721/ERC1155 asset satisfies the properties encoded in `propertyData`.
                ///      Should revert if the asset does not satisfy the specified properties.
                /// @param tokenAddress The ERC721/ERC1155 token contract address.
                /// @param tokenId The ERC721/ERC1155 tokenId of the asset to check.
                /// @param propertyData Encoded properties or auxiliary data needed to perform the check.
                function validateProperty(address tokenAddress, uint256 tokenId, bytes calldata propertyData, bytes calldata takerData) external view;
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            /// @dev EIP712 helpers for features.
            abstract contract FixinEIP712 {
                bytes32 private constant DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
                bytes32 private constant NAME = keccak256("ElementEx");
                bytes32 private constant VERSION = keccak256("1.0.0");
                function _getEIP712Hash(bytes32 structHash) internal view returns (bytes32) {
                    return keccak256(abi.encodePacked(hex"1901", keccak256(abi.encode(DOMAIN, NAME, VERSION, block.chainid, address(this))), structHash));
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2020 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import "@openzeppelin/contracts/utils/math/Math.sol";
            /// @dev Helpers for moving tokens around.
            abstract contract FixinTokenSpender {
                // Mask of the lower 20 bytes of a bytes32.
                uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
                /// @dev Transfers ERC20 tokens from `owner` to `to`.
                /// @param token The token to spend.
                /// @param owner The owner of the tokens.
                /// @param to The recipient of the tokens.
                /// @param amount The amount of `token` to transfer.
                function _transferERC20TokensFrom(IERC20 token, address owner, address to, uint256 amount) internal {
                    uint256 success;
                    assembly {
                        let ptr := mload(0x40) // free memory pointer
                        // selector for transferFrom(address,address,uint256)
                        mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                        mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK))
                        mstore(add(ptr, 0x24), and(to, ADDRESS_MASK))
                        mstore(add(ptr, 0x44), amount)
                        success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, ptr, 32)
                        let rdsize := returndatasize()
                        // Check for ERC20 success. ERC20 tokens should return a boolean,
                        // but some don't. We accept 0-length return data as success, or at
                        // least 32 bytes that starts with a 32-byte boolean true.
                        success := and(
                            success,                             // call itself succeeded
                            or(
                                iszero(rdsize),                  // no return data, or
                                and(
                                    iszero(lt(rdsize, 32)),      // at least 32 bytes
                                    eq(mload(ptr), 1)            // starts with uint256(1)
                                )
                            )
                        )
                    }
                    require(success != 0, "_transferERC20/TRANSFER_FAILED");
                }
                /// @dev Transfers ERC20 tokens from ourselves to `to`.
                /// @param token The token to spend.
                /// @param to The recipient of the tokens.
                /// @param amount The amount of `token` to transfer.
                function _transferERC20Tokens(IERC20 token, address to, uint256 amount) internal {
                    uint256 success;
                    assembly {
                        let ptr := mload(0x40) // free memory pointer
                        // selector for transfer(address,uint256)
                        mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                        mstore(add(ptr, 0x04), and(to, ADDRESS_MASK))
                        mstore(add(ptr, 0x24), amount)
                        success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x44, ptr, 32)
                        let rdsize := returndatasize()
                        // Check for ERC20 success. ERC20 tokens should return a boolean,
                        // but some don't. We accept 0-length return data as success, or at
                        // least 32 bytes that starts with a 32-byte boolean true.
                        success := and(
                            success,                             // call itself succeeded
                            or(
                                iszero(rdsize),                  // no return data, or
                                and(
                                    iszero(lt(rdsize, 32)),      // at least 32 bytes
                                    eq(mload(ptr), 1)            // starts with uint256(1)
                                )
                            )
                        )
                    }
                    require(success != 0, "_transferERC20/TRANSFER_FAILED");
                }
                /// @dev Transfers some amount of ETH to the given recipient and
                ///      reverts if the transfer fails.
                /// @param recipient The recipient of the ETH.
                /// @param amount The amount of ETH to transfer.
                function _transferEth(address payable recipient, uint256 amount) internal {
                    if (amount > 0) {
                        (bool success,) = recipient.call{value: amount}("");
                        require(success, "_transferEth/TRANSFER_FAILED");
                    }
                }
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Copyright 2022 Element.Market
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            interface IEtherToken is IERC20 {
                /// @dev Wrap ether.
                function deposit() external payable;
                /// @dev Unwrap ether.
                function withdraw(uint256 amount) external;
            }
            // SPDX-License-Identifier: Apache-2.0
            /*
              Modifications Copyright 2022 Element.Market
              Copyright 2021 ZeroEx Intl.
              Licensed under the Apache License, Version 2.0 (the "License");
              you may not use this file except in compliance with the License.
              You may obtain a copy of the License at
                http://www.apache.org/licenses/LICENSE-2.0
              Unless required by applicable law or agreed to in writing, software
              distributed under the License is distributed on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
              See the License for the specific language governing permissions and
              limitations under the License.
            */
            pragma solidity ^0.8.13;
            interface IFeeRecipient {
                /// @dev A callback function invoked in the ERC721Feature for each ERC721
                ///      order fee that get paid. Integrators can make use of this callback
                ///      to implement arbitrary fee-handling logic, e.g. splitting the fee
                ///      between multiple parties.
                /// @param tokenAddress The address of the token in which the received fee is
                ///        denominated. `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` indicates
                ///        that the fee was paid in the native token (e.g. ETH).
                /// @param amount The amount of the given token received.
                /// @param feeData Arbitrary data encoded in the `Fee` used by this callback.
                /// @return success The selector of this function (0x0190805e),
                ///         indicating that the callback succeeded.
                function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Standard math utilities missing in the Solidity language.
             */
            library Math {
                enum Rounding {
                    Down, // Toward negative infinity
                    Up, // Toward infinity
                    Zero // Toward zero
                }
                /**
                 * @dev Returns the largest of two numbers.
                 */
                function max(uint256 a, uint256 b) internal pure returns (uint256) {
                    return a >= b ? a : b;
                }
                /**
                 * @dev Returns the smallest of two numbers.
                 */
                function min(uint256 a, uint256 b) internal pure returns (uint256) {
                    return a < b ? a : b;
                }
                /**
                 * @dev Returns the average of two numbers. The result is rounded towards
                 * zero.
                 */
                function average(uint256 a, uint256 b) internal pure returns (uint256) {
                    // (a + b) / 2 can overflow.
                    return (a & b) + (a ^ b) / 2;
                }
                /**
                 * @dev Returns the ceiling of the division of two numbers.
                 *
                 * This differs from standard division with `/` in that it rounds up instead
                 * of rounding down.
                 */
                function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                    // (a + b - 1) / b can overflow on addition, so we distribute.
                    return a == 0 ? 0 : (a - 1) / b + 1;
                }
                /**
                 * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                 * with further edits by Uniswap Labs also under MIT license.
                 */
                function mulDiv(
                    uint256 x,
                    uint256 y,
                    uint256 denominator
                ) internal pure returns (uint256 result) {
                    unchecked {
                        // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                        // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                        // variables such that product = prod1 * 2^256 + prod0.
                        uint256 prod0; // Least significant 256 bits of the product
                        uint256 prod1; // Most significant 256 bits of the product
                        assembly {
                            let mm := mulmod(x, y, not(0))
                            prod0 := mul(x, y)
                            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                        }
                        // Handle non-overflow cases, 256 by 256 division.
                        if (prod1 == 0) {
                            return prod0 / denominator;
                        }
                        // Make sure the result is less than 2^256. Also prevents denominator == 0.
                        require(denominator > prod1);
                        ///////////////////////////////////////////////
                        // 512 by 256 division.
                        ///////////////////////////////////////////////
                        // Make division exact by subtracting the remainder from [prod1 prod0].
                        uint256 remainder;
                        assembly {
                            // Compute remainder using mulmod.
                            remainder := mulmod(x, y, denominator)
                            // Subtract 256 bit number from 512 bit number.
                            prod1 := sub(prod1, gt(remainder, prod0))
                            prod0 := sub(prod0, remainder)
                        }
                        // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                        // See https://cs.stackexchange.com/q/138556/92363.
                        // Does not overflow because the denominator cannot be zero at this stage in the function.
                        uint256 twos = denominator & (~denominator + 1);
                        assembly {
                            // Divide denominator by twos.
                            denominator := div(denominator, twos)
                            // Divide [prod1 prod0] by twos.
                            prod0 := div(prod0, twos)
                            // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                            twos := add(div(sub(0, twos), twos), 1)
                        }
                        // Shift in bits from prod1 into prod0.
                        prod0 |= prod1 * twos;
                        // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                        // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                        // four bits. That is, denominator * inv = 1 mod 2^4.
                        uint256 inverse = (3 * denominator) ^ 2;
                        // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                        // in modular arithmetic, doubling the correct bits in each step.
                        inverse *= 2 - denominator * inverse; // inverse mod 2^8
                        inverse *= 2 - denominator * inverse; // inverse mod 2^16
                        inverse *= 2 - denominator * inverse; // inverse mod 2^32
                        inverse *= 2 - denominator * inverse; // inverse mod 2^64
                        inverse *= 2 - denominator * inverse; // inverse mod 2^128
                        inverse *= 2 - denominator * inverse; // inverse mod 2^256
                        // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                        // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                        // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                        // is no longer required.
                        result = prod0 * inverse;
                        return result;
                    }
                }
                /**
                 * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                 */
                function mulDiv(
                    uint256 x,
                    uint256 y,
                    uint256 denominator,
                    Rounding rounding
                ) internal pure returns (uint256) {
                    uint256 result = mulDiv(x, y, denominator);
                    if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                        result += 1;
                    }
                    return result;
                }
                /**
                 * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
                 *
                 * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                 */
                function sqrt(uint256 a) internal pure returns (uint256) {
                    if (a == 0) {
                        return 0;
                    }
                    // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                    // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                    // `msb(a) <= a < 2*msb(a)`.
                    // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
                    // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
                    // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
                    // good first aproximation of `sqrt(a)` with at least 1 correct bit.
                    uint256 result = 1;
                    uint256 x = a;
                    if (x >> 128 > 0) {
                        x >>= 128;
                        result <<= 64;
                    }
                    if (x >> 64 > 0) {
                        x >>= 64;
                        result <<= 32;
                    }
                    if (x >> 32 > 0) {
                        x >>= 32;
                        result <<= 16;
                    }
                    if (x >> 16 > 0) {
                        x >>= 16;
                        result <<= 8;
                    }
                    if (x >> 8 > 0) {
                        x >>= 8;
                        result <<= 4;
                    }
                    if (x >> 4 > 0) {
                        x >>= 4;
                        result <<= 2;
                    }
                    if (x >> 2 > 0) {
                        result <<= 1;
                    }
                    // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                    // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                    // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                    // into the expected uint128 result.
                    unchecked {
                        result = (result + a / result) >> 1;
                        result = (result + a / result) >> 1;
                        result = (result + a / result) >> 1;
                        result = (result + a / result) >> 1;
                        result = (result + a / result) >> 1;
                        result = (result + a / result) >> 1;
                        result = (result + a / result) >> 1;
                        return min(result, a / result);
                    }
                }
                /**
                 * @notice Calculates sqrt(a), following the selected rounding direction.
                 */
                function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                    uint256 result = sqrt(a);
                    if (rounding == Rounding.Up && result * result < a) {
                        result += 1;
                    }
                    return result;
                }
            }
            

            File 7 of 7: GnosisSafe
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            import "./base/ModuleManager.sol";
            import "./base/OwnerManager.sol";
            import "./base/FallbackManager.sol";
            import "./base/GuardManager.sol";
            import "./common/EtherPaymentFallback.sol";
            import "./common/Singleton.sol";
            import "./common/SignatureDecoder.sol";
            import "./common/SecuredTokenTransfer.sol";
            import "./common/StorageAccessible.sol";
            import "./interfaces/ISignatureValidator.sol";
            import "./external/GnosisSafeMath.sol";
            /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
            /// @author Stefan George - <[email protected]>
            /// @author Richard Meissner - <[email protected]>
            contract GnosisSafe is
                EtherPaymentFallback,
                Singleton,
                ModuleManager,
                OwnerManager,
                SignatureDecoder,
                SecuredTokenTransfer,
                ISignatureValidatorConstants,
                FallbackManager,
                StorageAccessible,
                GuardManager
            {
                using GnosisSafeMath for uint256;
                string public constant VERSION = "1.3.0";
                // keccak256(
                //     "EIP712Domain(uint256 chainId,address verifyingContract)"
                // );
                bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
                // keccak256(
                //     "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
                // );
                bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
                event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
                event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
                event SignMsg(bytes32 indexed msgHash);
                event ExecutionFailure(bytes32 txHash, uint256 payment);
                event ExecutionSuccess(bytes32 txHash, uint256 payment);
                uint256 public nonce;
                bytes32 private _deprecatedDomainSeparator;
                // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners
                mapping(bytes32 => uint256) public signedMessages;
                // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners
                mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
                // This constructor ensures that this contract can only be used as a master copy for Proxy contracts
                constructor() {
                    // By setting the threshold it is not possible to call setup anymore,
                    // so we create a Safe with 0 owners and threshold 1.
                    // This is an unusable Safe, perfect for the singleton
                    threshold = 1;
                }
                /// @dev Setup function sets initial storage of contract.
                /// @param _owners List of Safe owners.
                /// @param _threshold Number of required confirmations for a Safe transaction.
                /// @param to Contract address for optional delegate call.
                /// @param data Data payload for optional delegate call.
                /// @param fallbackHandler Handler for fallback calls to this contract
                /// @param paymentToken Token that should be used for the payment (0 is ETH)
                /// @param payment Value that should be paid
                /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
                function setup(
                    address[] calldata _owners,
                    uint256 _threshold,
                    address to,
                    bytes calldata data,
                    address fallbackHandler,
                    address paymentToken,
                    uint256 payment,
                    address payable paymentReceiver
                ) external {
                    // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
                    setupOwners(_owners, _threshold);
                    if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
                    // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
                    setupModules(to, data);
                    if (payment > 0) {
                        // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
                        // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
                        handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
                    }
                    emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
                }
                /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
                ///      Note: The fees are always transferred, even if the user transaction fails.
                /// @param to Destination address of Safe transaction.
                /// @param value Ether value of Safe transaction.
                /// @param data Data payload of Safe transaction.
                /// @param operation Operation type of Safe transaction.
                /// @param safeTxGas Gas that should be used for the Safe transaction.
                /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                /// @param gasPrice Gas price that should be used for the payment calculation.
                /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
                function execTransaction(
                    address to,
                    uint256 value,
                    bytes calldata data,
                    Enum.Operation operation,
                    uint256 safeTxGas,
                    uint256 baseGas,
                    uint256 gasPrice,
                    address gasToken,
                    address payable refundReceiver,
                    bytes memory signatures
                ) public payable virtual returns (bool success) {
                    bytes32 txHash;
                    // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                    {
                        bytes memory txHashData =
                            encodeTransactionData(
                                // Transaction info
                                to,
                                value,
                                data,
                                operation,
                                safeTxGas,
                                // Payment info
                                baseGas,
                                gasPrice,
                                gasToken,
                                refundReceiver,
                                // Signature info
                                nonce
                            );
                        // Increase nonce and execute transaction.
                        nonce++;
                        txHash = keccak256(txHashData);
                        checkSignatures(txHash, txHashData, signatures);
                    }
                    address guard = getGuard();
                    {
                        if (guard != address(0)) {
                            Guard(guard).checkTransaction(
                                // Transaction info
                                to,
                                value,
                                data,
                                operation,
                                safeTxGas,
                                // Payment info
                                baseGas,
                                gasPrice,
                                gasToken,
                                refundReceiver,
                                // Signature info
                                signatures,
                                msg.sender
                            );
                        }
                    }
                    // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
                    // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
                    require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
                    // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                    {
                        uint256 gasUsed = gasleft();
                        // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
                        // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
                        success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
                        gasUsed = gasUsed.sub(gasleft());
                        // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
                        // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
                        require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
                        // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
                        uint256 payment = 0;
                        if (gasPrice > 0) {
                            payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
                        }
                        if (success) emit ExecutionSuccess(txHash, payment);
                        else emit ExecutionFailure(txHash, payment);
                    }
                    {
                        if (guard != address(0)) {
                            Guard(guard).checkAfterExecution(txHash, success);
                        }
                    }
                }
                function handlePayment(
                    uint256 gasUsed,
                    uint256 baseGas,
                    uint256 gasPrice,
                    address gasToken,
                    address payable refundReceiver
                ) private returns (uint256 payment) {
                    // solhint-disable-next-line avoid-tx-origin
                    address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
                    if (gasToken == address(0)) {
                        // For ETH we will only adjust the gas price to not be higher than the actual used gas price
                        payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
                        require(receiver.send(payment), "GS011");
                    } else {
                        payment = gasUsed.add(baseGas).mul(gasPrice);
                        require(transferToken(gasToken, receiver, payment), "GS012");
                    }
                }
                /**
                 * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                 * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                 * @param data That should be signed (this is passed to an external validator contract)
                 * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                 */
                function checkSignatures(
                    bytes32 dataHash,
                    bytes memory data,
                    bytes memory signatures
                ) public view {
                    // Load threshold to avoid multiple storage loads
                    uint256 _threshold = threshold;
                    // Check that a threshold is set
                    require(_threshold > 0, "GS001");
                    checkNSignatures(dataHash, data, signatures, _threshold);
                }
                /**
                 * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                 * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                 * @param data That should be signed (this is passed to an external validator contract)
                 * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                 * @param requiredSignatures Amount of required valid signatures.
                 */
                function checkNSignatures(
                    bytes32 dataHash,
                    bytes memory data,
                    bytes memory signatures,
                    uint256 requiredSignatures
                ) public view {
                    // Check that the provided signature data is not too short
                    require(signatures.length >= requiredSignatures.mul(65), "GS020");
                    // There cannot be an owner with address 0.
                    address lastOwner = address(0);
                    address currentOwner;
                    uint8 v;
                    bytes32 r;
                    bytes32 s;
                    uint256 i;
                    for (i = 0; i < requiredSignatures; i++) {
                        (v, r, s) = signatureSplit(signatures, i);
                        if (v == 0) {
                            // If v is 0 then it is a contract signature
                            // When handling contract signatures the address of the contract is encoded into r
                            currentOwner = address(uint160(uint256(r)));
                            // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
                            // This check is not completely accurate, since it is possible that more signatures than the threshold are send.
                            // Here we only check that the pointer is not pointing inside the part that is being processed
                            require(uint256(s) >= requiredSignatures.mul(65), "GS021");
                            // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
                            require(uint256(s).add(32) <= signatures.length, "GS022");
                            // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
                            uint256 contractSignatureLen;
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                contractSignatureLen := mload(add(add(signatures, s), 0x20))
                            }
                            require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
                            // Check signature
                            bytes memory contractSignature;
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
                                contractSignature := add(add(signatures, s), 0x20)
                            }
                            require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
                        } else if (v == 1) {
                            // If v is 1 then it is an approved hash
                            // When handling approved hashes the address of the approver is encoded into r
                            currentOwner = address(uint160(uint256(r)));
                            // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
                            require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
                        } else if (v > 30) {
                            // If v > 30 then default va (27,28) has been adjusted for eth_sign flow
                            // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
                            currentOwner = ecrecover(keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
            32", dataHash)), v - 4, r, s);
                        } else {
                            // Default is the ecrecover flow with the provided data hash
                            // Use ecrecover with the messageHash for EOA signatures
                            currentOwner = ecrecover(dataHash, v, r, s);
                        }
                        require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
                        lastOwner = currentOwner;
                    }
                }
                /// @dev Allows to estimate a Safe transaction.
                ///      This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
                ///      Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
                /// @param to Destination address of Safe transaction.
                /// @param value Ether value of Safe transaction.
                /// @param data Data payload of Safe transaction.
                /// @param operation Operation type of Safe transaction.
                /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
                /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
                function requiredTxGas(
                    address to,
                    uint256 value,
                    bytes calldata data,
                    Enum.Operation operation
                ) external returns (uint256) {
                    uint256 startGas = gasleft();
                    // We don't provide an error message here, as we use it to return the estimate
                    require(execute(to, value, data, operation, gasleft()));
                    uint256 requiredGas = startGas - gasleft();
                    // Convert response to string and return via error message
                    revert(string(abi.encodePacked(requiredGas)));
                }
                /**
                 * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
                 * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
                 */
                function approveHash(bytes32 hashToApprove) external {
                    require(owners[msg.sender] != address(0), "GS030");
                    approvedHashes[msg.sender][hashToApprove] = 1;
                    emit ApproveHash(hashToApprove, msg.sender);
                }
                /// @dev Returns the chain id used by this contract.
                function getChainId() public view returns (uint256) {
                    uint256 id;
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        id := chainid()
                    }
                    return id;
                }
                function domainSeparator() public view returns (bytes32) {
                    return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
                }
                /// @dev Returns the bytes that are hashed to be signed by owners.
                /// @param to Destination address.
                /// @param value Ether value.
                /// @param data Data payload.
                /// @param operation Operation type.
                /// @param safeTxGas Gas that should be used for the safe transaction.
                /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                /// @param gasPrice Maximum gas price that should be used for this transaction.
                /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                /// @param _nonce Transaction nonce.
                /// @return Transaction hash bytes.
                function encodeTransactionData(
                    address to,
                    uint256 value,
                    bytes calldata data,
                    Enum.Operation operation,
                    uint256 safeTxGas,
                    uint256 baseGas,
                    uint256 gasPrice,
                    address gasToken,
                    address refundReceiver,
                    uint256 _nonce
                ) public view returns (bytes memory) {
                    bytes32 safeTxHash =
                        keccak256(
                            abi.encode(
                                SAFE_TX_TYPEHASH,
                                to,
                                value,
                                keccak256(data),
                                operation,
                                safeTxGas,
                                baseGas,
                                gasPrice,
                                gasToken,
                                refundReceiver,
                                _nonce
                            )
                        );
                    return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
                }
                /// @dev Returns hash to be signed by owners.
                /// @param to Destination address.
                /// @param value Ether value.
                /// @param data Data payload.
                /// @param operation Operation type.
                /// @param safeTxGas Fas that should be used for the safe transaction.
                /// @param baseGas Gas costs for data used to trigger the safe transaction.
                /// @param gasPrice Maximum gas price that should be used for this transaction.
                /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                /// @param _nonce Transaction nonce.
                /// @return Transaction hash.
                function getTransactionHash(
                    address to,
                    uint256 value,
                    bytes calldata data,
                    Enum.Operation operation,
                    uint256 safeTxGas,
                    uint256 baseGas,
                    uint256 gasPrice,
                    address gasToken,
                    address refundReceiver,
                    uint256 _nonce
                ) public view returns (bytes32) {
                    return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            import "../common/Enum.sol";
            /// @title Executor - A contract that can execute transactions
            /// @author Richard Meissner - <[email protected]>
            contract Executor {
                function execute(
                    address to,
                    uint256 value,
                    bytes memory data,
                    Enum.Operation operation,
                    uint256 txGas
                ) internal returns (bool success) {
                    if (operation == Enum.Operation.DelegateCall) {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
                        }
                    } else {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
                        }
                    }
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            import "../common/SelfAuthorized.sol";
            /// @title Fallback Manager - A contract that manages fallback calls made to this contract
            /// @author Richard Meissner - <[email protected]>
            contract FallbackManager is SelfAuthorized {
                event ChangedFallbackHandler(address handler);
                // keccak256("fallback_manager.handler.address")
                bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
                function internalSetFallbackHandler(address handler) internal {
                    bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        sstore(slot, handler)
                    }
                }
                /// @dev Allows to add a contract to handle fallback calls.
                ///      Only fallback calls without value and with data will be forwarded.
                ///      This can only be done via a Safe transaction.
                /// @param handler contract to handle fallbacks calls.
                function setFallbackHandler(address handler) public authorized {
                    internalSetFallbackHandler(handler);
                    emit ChangedFallbackHandler(handler);
                }
                // solhint-disable-next-line payable-fallback,no-complex-fallback
                fallback() external {
                    bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        let handler := sload(slot)
                        if iszero(handler) {
                            return(0, 0)
                        }
                        calldatacopy(0, 0, calldatasize())
                        // The msg.sender address is shifted to the left by 12 bytes to remove the padding
                        // Then the address without padding is stored right after the calldata
                        mstore(calldatasize(), shl(96, caller()))
                        // Add 20 bytes for the address appended add the end
                        let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
                        returndatacopy(0, 0, returndatasize())
                        if iszero(success) {
                            revert(0, returndatasize())
                        }
                        return(0, returndatasize())
                    }
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            import "../common/Enum.sol";
            import "../common/SelfAuthorized.sol";
            interface Guard {
                function checkTransaction(
                    address to,
                    uint256 value,
                    bytes memory data,
                    Enum.Operation operation,
                    uint256 safeTxGas,
                    uint256 baseGas,
                    uint256 gasPrice,
                    address gasToken,
                    address payable refundReceiver,
                    bytes memory signatures,
                    address msgSender
                ) external;
                function checkAfterExecution(bytes32 txHash, bool success) external;
            }
            /// @title Fallback Manager - A contract that manages fallback calls made to this contract
            /// @author Richard Meissner - <[email protected]>
            contract GuardManager is SelfAuthorized {
                event ChangedGuard(address guard);
                // keccak256("guard_manager.guard.address")
                bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
                /// @dev Set a guard that checks transactions before execution
                /// @param guard The address of the guard to be used or the 0 address to disable the guard
                function setGuard(address guard) external authorized {
                    bytes32 slot = GUARD_STORAGE_SLOT;
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        sstore(slot, guard)
                    }
                    emit ChangedGuard(guard);
                }
                function getGuard() internal view returns (address guard) {
                    bytes32 slot = GUARD_STORAGE_SLOT;
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        guard := sload(slot)
                    }
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            import "../common/Enum.sol";
            import "../common/SelfAuthorized.sol";
            import "./Executor.sol";
            /// @title Module Manager - A contract that manages modules that can execute transactions via this contract
            /// @author Stefan George - <[email protected]>
            /// @author Richard Meissner - <[email protected]>
            contract ModuleManager is SelfAuthorized, Executor {
                event EnabledModule(address module);
                event DisabledModule(address module);
                event ExecutionFromModuleSuccess(address indexed module);
                event ExecutionFromModuleFailure(address indexed module);
                address internal constant SENTINEL_MODULES = address(0x1);
                mapping(address => address) internal modules;
                function setupModules(address to, bytes memory data) internal {
                    require(modules[SENTINEL_MODULES] == address(0), "GS100");
                    modules[SENTINEL_MODULES] = SENTINEL_MODULES;
                    if (to != address(0))
                        // Setup has to complete successfully or transaction fails.
                        require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
                }
                /// @dev Allows to add a module to the whitelist.
                ///      This can only be done via a Safe transaction.
                /// @notice Enables the module `module` for the Safe.
                /// @param module Module to be whitelisted.
                function enableModule(address module) public authorized {
                    // Module address cannot be null or sentinel.
                    require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                    // Module cannot be added twice.
                    require(modules[module] == address(0), "GS102");
                    modules[module] = modules[SENTINEL_MODULES];
                    modules[SENTINEL_MODULES] = module;
                    emit EnabledModule(module);
                }
                /// @dev Allows to remove a module from the whitelist.
                ///      This can only be done via a Safe transaction.
                /// @notice Disables the module `module` for the Safe.
                /// @param prevModule Module that pointed to the module to be removed in the linked list
                /// @param module Module to be removed.
                function disableModule(address prevModule, address module) public authorized {
                    // Validate module address and check that it corresponds to module index.
                    require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                    require(modules[prevModule] == module, "GS103");
                    modules[prevModule] = modules[module];
                    modules[module] = address(0);
                    emit DisabledModule(module);
                }
                /// @dev Allows a Module to execute a Safe transaction without any further confirmations.
                /// @param to Destination address of module transaction.
                /// @param value Ether value of module transaction.
                /// @param data Data payload of module transaction.
                /// @param operation Operation type of module transaction.
                function execTransactionFromModule(
                    address to,
                    uint256 value,
                    bytes memory data,
                    Enum.Operation operation
                ) public virtual returns (bool success) {
                    // Only whitelisted modules are allowed.
                    require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
                    // Execute transaction without further confirmations.
                    success = execute(to, value, data, operation, gasleft());
                    if (success) emit ExecutionFromModuleSuccess(msg.sender);
                    else emit ExecutionFromModuleFailure(msg.sender);
                }
                /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
                /// @param to Destination address of module transaction.
                /// @param value Ether value of module transaction.
                /// @param data Data payload of module transaction.
                /// @param operation Operation type of module transaction.
                function execTransactionFromModuleReturnData(
                    address to,
                    uint256 value,
                    bytes memory data,
                    Enum.Operation operation
                ) public returns (bool success, bytes memory returnData) {
                    success = execTransactionFromModule(to, value, data, operation);
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        // Load free memory location
                        let ptr := mload(0x40)
                        // We allocate memory for the return data by setting the free memory location to
                        // current free memory location + data size + 32 bytes for data size value
                        mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
                        // Store the size
                        mstore(ptr, returndatasize())
                        // Store the data
                        returndatacopy(add(ptr, 0x20), 0, returndatasize())
                        // Point the return data to the correct memory location
                        returnData := ptr
                    }
                }
                /// @dev Returns if an module is enabled
                /// @return True if the module is enabled
                function isModuleEnabled(address module) public view returns (bool) {
                    return SENTINEL_MODULES != module && modules[module] != address(0);
                }
                /// @dev Returns array of modules.
                /// @param start Start of the page.
                /// @param pageSize Maximum number of modules that should be returned.
                /// @return array Array of modules.
                /// @return next Start of the next page.
                function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
                    // Init array with max page size
                    array = new address[](pageSize);
                    // Populate return array
                    uint256 moduleCount = 0;
                    address currentModule = modules[start];
                    while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
                        array[moduleCount] = currentModule;
                        currentModule = modules[currentModule];
                        moduleCount++;
                    }
                    next = currentModule;
                    // Set correct size of returned array
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        mstore(array, moduleCount)
                    }
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            import "../common/SelfAuthorized.sol";
            /// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
            /// @author Stefan George - <[email protected]>
            /// @author Richard Meissner - <[email protected]>
            contract OwnerManager is SelfAuthorized {
                event AddedOwner(address owner);
                event RemovedOwner(address owner);
                event ChangedThreshold(uint256 threshold);
                address internal constant SENTINEL_OWNERS = address(0x1);
                mapping(address => address) internal owners;
                uint256 internal ownerCount;
                uint256 internal threshold;
                /// @dev Setup function sets initial storage of contract.
                /// @param _owners List of Safe owners.
                /// @param _threshold Number of required confirmations for a Safe transaction.
                function setupOwners(address[] memory _owners, uint256 _threshold) internal {
                    // Threshold can only be 0 at initialization.
                    // Check ensures that setup function can only be called once.
                    require(threshold == 0, "GS200");
                    // Validate that threshold is smaller than number of added owners.
                    require(_threshold <= _owners.length, "GS201");
                    // There has to be at least one Safe owner.
                    require(_threshold >= 1, "GS202");
                    // Initializing Safe owners.
                    address currentOwner = SENTINEL_OWNERS;
                    for (uint256 i = 0; i < _owners.length; i++) {
                        // Owner address cannot be null.
                        address owner = _owners[i];
                        require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
                        // No duplicate owners allowed.
                        require(owners[owner] == address(0), "GS204");
                        owners[currentOwner] = owner;
                        currentOwner = owner;
                    }
                    owners[currentOwner] = SENTINEL_OWNERS;
                    ownerCount = _owners.length;
                    threshold = _threshold;
                }
                /// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
                ///      This can only be done via a Safe transaction.
                /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
                /// @param owner New owner address.
                /// @param _threshold New threshold.
                function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
                    // Owner address cannot be null, the sentinel or the Safe itself.
                    require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
                    // No duplicate owners allowed.
                    require(owners[owner] == address(0), "GS204");
                    owners[owner] = owners[SENTINEL_OWNERS];
                    owners[SENTINEL_OWNERS] = owner;
                    ownerCount++;
                    emit AddedOwner(owner);
                    // Change threshold if threshold was changed.
                    if (threshold != _threshold) changeThreshold(_threshold);
                }
                /// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
                ///      This can only be done via a Safe transaction.
                /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
                /// @param prevOwner Owner that pointed to the owner to be removed in the linked list
                /// @param owner Owner address to be removed.
                /// @param _threshold New threshold.
                function removeOwner(
                    address prevOwner,
                    address owner,
                    uint256 _threshold
                ) public authorized {
                    // Only allow to remove an owner, if threshold can still be reached.
                    require(ownerCount - 1 >= _threshold, "GS201");
                    // Validate owner address and check that it corresponds to owner index.
                    require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
                    require(owners[prevOwner] == owner, "GS205");
                    owners[prevOwner] = owners[owner];
                    owners[owner] = address(0);
                    ownerCount--;
                    emit RemovedOwner(owner);
                    // Change threshold if threshold was changed.
                    if (threshold != _threshold) changeThreshold(_threshold);
                }
                /// @dev Allows to swap/replace an owner from the Safe with another address.
                ///      This can only be done via a Safe transaction.
                /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
                /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
                /// @param oldOwner Owner address to be replaced.
                /// @param newOwner New owner address.
                function swapOwner(
                    address prevOwner,
                    address oldOwner,
                    address newOwner
                ) public authorized {
                    // Owner address cannot be null, the sentinel or the Safe itself.
                    require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
                    // No duplicate owners allowed.
                    require(owners[newOwner] == address(0), "GS204");
                    // Validate oldOwner address and check that it corresponds to owner index.
                    require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
                    require(owners[prevOwner] == oldOwner, "GS205");
                    owners[newOwner] = owners[oldOwner];
                    owners[prevOwner] = newOwner;
                    owners[oldOwner] = address(0);
                    emit RemovedOwner(oldOwner);
                    emit AddedOwner(newOwner);
                }
                /// @dev Allows to update the number of required confirmations by Safe owners.
                ///      This can only be done via a Safe transaction.
                /// @notice Changes the threshold of the Safe to `_threshold`.
                /// @param _threshold New threshold.
                function changeThreshold(uint256 _threshold) public authorized {
                    // Validate that threshold is smaller than number of owners.
                    require(_threshold <= ownerCount, "GS201");
                    // There has to be at least one Safe owner.
                    require(_threshold >= 1, "GS202");
                    threshold = _threshold;
                    emit ChangedThreshold(threshold);
                }
                function getThreshold() public view returns (uint256) {
                    return threshold;
                }
                function isOwner(address owner) public view returns (bool) {
                    return owner != SENTINEL_OWNERS && owners[owner] != address(0);
                }
                /// @dev Returns array of owners.
                /// @return Array of Safe owners.
                function getOwners() public view returns (address[] memory) {
                    address[] memory array = new address[](ownerCount);
                    // populate return array
                    uint256 index = 0;
                    address currentOwner = owners[SENTINEL_OWNERS];
                    while (currentOwner != SENTINEL_OWNERS) {
                        array[index] = currentOwner;
                        currentOwner = owners[currentOwner];
                        index++;
                    }
                    return array;
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /// @title Enum - Collection of enums
            /// @author Richard Meissner - <[email protected]>
            contract Enum {
                enum Operation {Call, DelegateCall}
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
            /// @author Richard Meissner - <[email protected]>
            contract EtherPaymentFallback {
                event SafeReceived(address indexed sender, uint256 value);
                /// @dev Fallback function accepts Ether transactions.
                receive() external payable {
                    emit SafeReceived(msg.sender, msg.value);
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /// @title SecuredTokenTransfer - Secure token transfer
            /// @author Richard Meissner - <[email protected]>
            contract SecuredTokenTransfer {
                /// @dev Transfers a token and returns if it was a success
                /// @param token Token that should be transferred
                /// @param receiver Receiver to whom the token should be transferred
                /// @param amount The amount of tokens that should be transferred
                function transferToken(
                    address token,
                    address receiver,
                    uint256 amount
                ) internal returns (bool transferred) {
                    // 0xa9059cbb - keccack("transfer(address,uint256)")
                    bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        // We write the return value to scratch space.
                        // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
                        let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
                        switch returndatasize()
                            case 0 {
                                transferred := success
                            }
                            case 0x20 {
                                transferred := iszero(or(iszero(success), iszero(mload(0))))
                            }
                            default {
                                transferred := 0
                            }
                    }
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /// @title SelfAuthorized - authorizes current contract to perform actions
            /// @author Richard Meissner - <[email protected]>
            contract SelfAuthorized {
                function requireSelfCall() private view {
                    require(msg.sender == address(this), "GS031");
                }
                modifier authorized() {
                    // This is a function call as it minimized the bytecode size
                    requireSelfCall();
                    _;
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /// @title SignatureDecoder - Decodes signatures that a encoded as bytes
            /// @author Richard Meissner - <[email protected]>
            contract SignatureDecoder {
                /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
                /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures
                /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
                /// @param signatures concatenated rsv signatures
                function signatureSplit(bytes memory signatures, uint256 pos)
                    internal
                    pure
                    returns (
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    )
                {
                    // The signature format is a compact form of:
                    //   {bytes32 r}{bytes32 s}{uint8 v}
                    // Compact means, uint8 is not padded to 32 bytes.
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        let signaturePos := mul(0x41, pos)
                        r := mload(add(signatures, add(signaturePos, 0x20)))
                        s := mload(add(signatures, add(signaturePos, 0x40)))
                        // Here we are loading the last 32 bytes, including 31 bytes
                        // of 's'. There is no 'mload8' to do this.
                        //
                        // 'byte' is not working due to the Solidity parser, so lets
                        // use the second best option, 'and'
                        v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
                    }
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /// @title Singleton - Base for singleton contracts (should always be first super contract)
            ///         This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
            /// @author Richard Meissner - <[email protected]>
            contract Singleton {
                // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
                // It should also always be ensured that the address is stored alone (uses a full word)
                address private singleton;
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
            /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
            contract StorageAccessible {
                /**
                 * @dev Reads `length` bytes of storage in the currents contract
                 * @param offset - the offset in the current contract's storage in words to start reading from
                 * @param length - the number of words (32 bytes) of data to read
                 * @return the bytes that were read.
                 */
                function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
                    bytes memory result = new bytes(length * 32);
                    for (uint256 index = 0; index < length; index++) {
                        // solhint-disable-next-line no-inline-assembly
                        assembly {
                            let word := sload(add(offset, index))
                            mstore(add(add(result, 0x20), mul(index, 0x20)), word)
                        }
                    }
                    return result;
                }
                /**
                 * @dev Performs a delegetecall on a targetContract in the context of self.
                 * Internally reverts execution to avoid side effects (making it static).
                 *
                 * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
                 * Specifically, the `returndata` after a call to this method will be:
                 * `success:bool || response.length:uint256 || response:bytes`.
                 *
                 * @param targetContract Address of the contract containing the code to execute.
                 * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
                 */
                function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
                        mstore(0x00, success)
                        mstore(0x20, returndatasize())
                        returndatacopy(0x40, 0, returndatasize())
                        revert(0, add(returndatasize(), 0x40))
                    }
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            /**
             * @title GnosisSafeMath
             * @dev Math operations with safety checks that revert on error
             * Renamed from SafeMath to GnosisSafeMath to avoid conflicts
             * TODO: remove once open zeppelin update to solc 0.5.0
             */
            library GnosisSafeMath {
                /**
                 * @dev Multiplies two numbers, reverts on overflow.
                 */
                function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                    // benefit is lost if 'b' is also tested.
                    // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                    if (a == 0) {
                        return 0;
                    }
                    uint256 c = a * b;
                    require(c / a == b);
                    return c;
                }
                /**
                 * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                 */
                function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                    require(b <= a);
                    uint256 c = a - b;
                    return c;
                }
                /**
                 * @dev Adds two numbers, reverts on overflow.
                 */
                function add(uint256 a, uint256 b) internal pure returns (uint256) {
                    uint256 c = a + b;
                    require(c >= a);
                    return c;
                }
                /**
                 * @dev Returns the largest of two numbers.
                 */
                function max(uint256 a, uint256 b) internal pure returns (uint256) {
                    return a >= b ? a : b;
                }
            }
            // SPDX-License-Identifier: LGPL-3.0-only
            pragma solidity >=0.7.0 <0.9.0;
            contract ISignatureValidatorConstants {
                // bytes4(keccak256("isValidSignature(bytes,bytes)")
                bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
            }
            abstract contract ISignatureValidator is ISignatureValidatorConstants {
                /**
                 * @dev Should return whether the signature provided is valid for the provided data
                 * @param _data Arbitrary length data signed on the behalf of address(this)
                 * @param _signature Signature byte array associated with _data
                 *
                 * MUST return the bytes4 magic value 0x20c13b0b when function passes.
                 * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
                 * MUST allow external calls
                 */
                function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
            }