{"sources":{"LoopringV3.sol":{"content":"// SPDX-License-Identifier: Apache-2.0\r\n// Copyright 2017 Loopring Technology Limited.\r\npragma solidity ^0.7.0;\r\n\r\n\r\n/// @title Ownable\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\n/// @dev The Ownable contract has an owner address, and provides basic\r\n///      authorization control functions, this simplifies the implementation of\r\n///      \"user permissions\".\r\ncontract Ownable\r\n{\r\n    address public owner;\r\n\r\n    event OwnershipTransferred(\r\n        address indexed previousOwner,\r\n        address indexed newOwner\r\n    );\r\n\r\n    /// @dev The Ownable constructor sets the original `owner` of the contract\r\n    ///      to the sender.\r\n    constructor()\r\n    {\r\n        owner = msg.sender;\r\n    }\r\n\r\n    /// @dev Throws if called by any account other than the owner.\r\n    modifier onlyOwner()\r\n    {\r\n        require(msg.sender == owner, \"UNAUTHORIZED\");\r\n        _;\r\n    }\r\n\r\n    /// @dev Allows the current owner to transfer control of the contract to a\r\n    ///      new owner.\r\n    /// @param newOwner The address to transfer ownership to.\r\n    function transferOwnership(\r\n        address newOwner\r\n        )\r\n        public\r\n        virtual\r\n        onlyOwner\r\n    {\r\n        require(newOwner != address(0), \"ZERO_ADDRESS\");\r\n        emit OwnershipTransferred(owner, newOwner);\r\n        owner = newOwner;\r\n    }\r\n\r\n    function renounceOwnership()\r\n        public\r\n        onlyOwner\r\n    {\r\n        emit OwnershipTransferred(owner, address(0));\r\n        owner = address(0);\r\n    }\r\n}\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n\r\n\r\n/// @title Claimable\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\n/// @dev Extension for the Ownable contract, where the ownership needs\r\n///      to be claimed. This allows the new owner to accept the transfer.\r\ncontract Claimable is Ownable\r\n{\r\n    address public pendingOwner;\r\n\r\n    /// @dev Modifier throws if called by any account other than the pendingOwner.\r\n    modifier onlyPendingOwner() {\r\n        require(msg.sender == pendingOwner, \"UNAUTHORIZED\");\r\n        _;\r\n    }\r\n\r\n    /// @dev Allows the current owner to set the pendingOwner address.\r\n    /// @param newOwner The address to transfer ownership to.\r\n    function transferOwnership(\r\n        address newOwner\r\n        )\r\n        public\r\n        override\r\n        onlyOwner\r\n    {\r\n        require(newOwner != address(0) && newOwner != owner, \"INVALID_ADDRESS\");\r\n        pendingOwner = newOwner;\r\n    }\r\n\r\n    /// @dev Allows the pendingOwner address to finalize the transfer.\r\n    function claimOwnership()\r\n        public\r\n        onlyPendingOwner\r\n    {\r\n        emit OwnershipTransferred(owner, pendingOwner);\r\n        owner = pendingOwner;\r\n        pendingOwner = address(0);\r\n    }\r\n}\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n/// @title Utility Functions for uint\r\n/// @author Daniel Wang - <daniel@loopring.org>\r\nlibrary MathUint\r\n{\r\n    using MathUint for uint;\r\n\r\n    function mul(\r\n        uint a,\r\n        uint b\r\n        )\r\n        internal\r\n        pure\r\n        returns (uint c)\r\n    {\r\n        c = a * b;\r\n        require(a == 0 || c / a == b, \"MUL_OVERFLOW\");\r\n    }\r\n\r\n    function sub(\r\n        uint a,\r\n        uint b\r\n        )\r\n        internal\r\n        pure\r\n        returns (uint)\r\n    {\r\n        require(b <= a, \"SUB_UNDERFLOW\");\r\n        return a - b;\r\n    }\r\n\r\n    function add(\r\n        uint a,\r\n        uint b\r\n        )\r\n        internal\r\n        pure\r\n        returns (uint c)\r\n    {\r\n        c = a + b;\r\n        require(c >= a, \"ADD_OVERFLOW\");\r\n    }\r\n\r\n    function add64(\r\n        uint64 a,\r\n        uint64 b\r\n        )\r\n        internal\r\n        pure\r\n        returns (uint64 c)\r\n    {\r\n        c = a + b;\r\n        require(c >= a, \"ADD_OVERFLOW\");\r\n    }\r\n}\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n/// @title Utility Functions for addresses\r\n/// @author Daniel Wang - <daniel@loopring.org>\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\nlibrary AddressUtil\r\n{\r\n    using AddressUtil for *;\r\n\r\n    function isContract(\r\n        address addr\r\n        )\r\n        internal\r\n        view\r\n        returns (bool)\r\n    {\r\n        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\r\n        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\r\n        // for accounts without code, i.e. `keccak256('')`\r\n        bytes32 codehash;\r\n        // solhint-disable-next-line no-inline-assembly\r\n        assembly { codehash := extcodehash(addr) }\r\n        return (codehash != 0x0 &&\r\n                codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);\r\n    }\r\n\r\n    function toPayable(\r\n        address addr\r\n        )\r\n        internal\r\n        pure\r\n        returns (address payable)\r\n    {\r\n        return payable(addr);\r\n    }\r\n\r\n    // Works like address.send but with a customizable gas limit\r\n    // Make sure your code is safe for reentrancy when using this function!\r\n    function sendETH(\r\n        address to,\r\n        uint    amount,\r\n        uint    gasLimit\r\n        )\r\n        internal\r\n        returns (bool success)\r\n    {\r\n        if (amount == 0) {\r\n            return true;\r\n        }\r\n        address payable recipient = to.toPayable();\r\n        /* solium-disable-next-line */\r\n        (success, ) = recipient.call{value: amount, gas: gasLimit}(\"\");\r\n    }\r\n\r\n    // Works like address.transfer but with a customizable gas limit\r\n    // Make sure your code is safe for reentrancy when using this function!\r\n    function sendETHAndVerify(\r\n        address to,\r\n        uint    amount,\r\n        uint    gasLimit\r\n        )\r\n        internal\r\n        returns (bool success)\r\n    {\r\n        success = to.sendETH(amount, gasLimit);\r\n        require(success, \"TRANSFER_FAILURE\");\r\n    }\r\n\r\n    // Works like call but is slightly more efficient when data\r\n    // needs to be copied from memory to do the call.\r\n    function fastCall(\r\n        address to,\r\n        uint    gasLimit,\r\n        uint    value,\r\n        bytes   memory data\r\n        )\r\n        internal\r\n        returns (bool success, bytes memory returnData)\r\n    {\r\n        if (to != address(0)) {\r\n            assembly {\r\n                // Do the call\r\n                success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)\r\n                // Copy the return data\r\n                let size := returndatasize()\r\n                returnData := mload(0x40)\r\n                mstore(returnData, size)\r\n                returndatacopy(add(returnData, 32), 0, size)\r\n                // Update free memory pointer\r\n                mstore(0x40, add(returnData, add(32, size)))\r\n            }\r\n        }\r\n    }\r\n\r\n    // Like fastCall, but throws when the call is unsuccessful.\r\n    function fastCallAndVerify(\r\n        address to,\r\n        uint    gasLimit,\r\n        uint    value,\r\n        bytes   memory data\r\n        )\r\n        internal\r\n        returns (bytes memory returnData)\r\n    {\r\n        bool success;\r\n        (success, returnData) = fastCall(to, gasLimit, value, data);\r\n        if (!success) {\r\n            assembly {\r\n                revert(add(returnData, 32), mload(returnData))\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n/// @title ERC20 safe transfer\r\n/// @dev see https://github.com/sec-bit/badERC20Fix\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\nlibrary ERC20SafeTransfer\r\n{\r\n    function safeTransferAndVerify(\r\n        address token,\r\n        address to,\r\n        uint    value\r\n        )\r\n        internal\r\n    {\r\n        safeTransferWithGasLimitAndVerify(\r\n            token,\r\n            to,\r\n            value,\r\n            gasleft()\r\n        );\r\n    }\r\n\r\n    function safeTransfer(\r\n        address token,\r\n        address to,\r\n        uint    value\r\n        )\r\n        internal\r\n        returns (bool)\r\n    {\r\n        return safeTransferWithGasLimit(\r\n            token,\r\n            to,\r\n            value,\r\n            gasleft()\r\n        );\r\n    }\r\n\r\n    function safeTransferWithGasLimitAndVerify(\r\n        address token,\r\n        address to,\r\n        uint    value,\r\n        uint    gasLimit\r\n        )\r\n        internal\r\n    {\r\n        require(\r\n            safeTransferWithGasLimit(token, to, value, gasLimit),\r\n            \"TRANSFER_FAILURE\"\r\n        );\r\n    }\r\n\r\n    function safeTransferWithGasLimit(\r\n        address token,\r\n        address to,\r\n        uint    value,\r\n        uint    gasLimit\r\n        )\r\n        internal\r\n        returns (bool)\r\n    {\r\n        // A transfer is successful when 'call' is successful and depending on the token:\r\n        // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)\r\n        // - A single boolean is returned: this boolean needs to be true (non-zero)\r\n\r\n        // bytes4(keccak256(\"transfer(address,uint256)\")) = 0xa9059cbb\r\n        bytes memory callData = abi.encodeWithSelector(\r\n            bytes4(0xa9059cbb),\r\n            to,\r\n            value\r\n        );\r\n        (bool success, ) = token.call{gas: gasLimit}(callData);\r\n        return checkReturnValue(success);\r\n    }\r\n\r\n    function safeTransferFromAndVerify(\r\n        address token,\r\n        address from,\r\n        address to,\r\n        uint    value\r\n        )\r\n        internal\r\n    {\r\n        safeTransferFromWithGasLimitAndVerify(\r\n            token,\r\n            from,\r\n            to,\r\n            value,\r\n            gasleft()\r\n        );\r\n    }\r\n\r\n    function safeTransferFrom(\r\n        address token,\r\n        address from,\r\n        address to,\r\n        uint    value\r\n        )\r\n        internal\r\n        returns (bool)\r\n    {\r\n        return safeTransferFromWithGasLimit(\r\n            token,\r\n            from,\r\n            to,\r\n            value,\r\n            gasleft()\r\n        );\r\n    }\r\n\r\n    function safeTransferFromWithGasLimitAndVerify(\r\n        address token,\r\n        address from,\r\n        address to,\r\n        uint    value,\r\n        uint    gasLimit\r\n        )\r\n        internal\r\n    {\r\n        bool result = safeTransferFromWithGasLimit(\r\n            token,\r\n            from,\r\n            to,\r\n            value,\r\n            gasLimit\r\n        );\r\n        require(result, \"TRANSFER_FAILURE\");\r\n    }\r\n\r\n    function safeTransferFromWithGasLimit(\r\n        address token,\r\n        address from,\r\n        address to,\r\n        uint    value,\r\n        uint    gasLimit\r\n        )\r\n        internal\r\n        returns (bool)\r\n    {\r\n        // A transferFrom is successful when 'call' is successful and depending on the token:\r\n        // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)\r\n        // - A single boolean is returned: this boolean needs to be true (non-zero)\r\n\r\n        // bytes4(keccak256(\"transferFrom(address,address,uint256)\")) = 0x23b872dd\r\n        bytes memory callData = abi.encodeWithSelector(\r\n            bytes4(0x23b872dd),\r\n            from,\r\n            to,\r\n            value\r\n        );\r\n        (bool success, ) = token.call{gas: gasLimit}(callData);\r\n        return checkReturnValue(success);\r\n    }\r\n\r\n    function checkReturnValue(\r\n        bool success\r\n        )\r\n        internal\r\n        pure\r\n        returns (bool)\r\n    {\r\n        // A transfer/transferFrom is successful when 'call' is successful and depending on the token:\r\n        // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)\r\n        // - A single boolean is returned: this boolean needs to be true (non-zero)\r\n        if (success) {\r\n            assembly {\r\n                switch returndatasize()\r\n                // Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded\r\n                case 0 {\r\n                    success := 1\r\n                }\r\n                // Standard ERC20: a single boolean value is returned which needs to be true\r\n                case 32 {\r\n                    returndatacopy(0, 0, 32)\r\n                    success := mload(0)\r\n                }\r\n                // None of the above: not successful\r\n                default {\r\n                    success := 0\r\n                }\r\n            }\r\n        }\r\n        return success;\r\n    }\r\n}\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n/// @title ReentrancyGuard\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\n/// @dev Exposes a modifier that guards a function against reentrancy\r\n///      Changing the value of the same storage value multiple times in a transaction\r\n///      is cheap (starting from Istanbul) so there is no need to minimize\r\n///      the number of times the value is changed\r\ncontract ReentrancyGuard\r\n{\r\n    //The default value must be 0 in order to work behind a proxy.\r\n    uint private _guardValue;\r\n\r\n    // Use this modifier on a function to prevent reentrancy\r\n    modifier nonReentrant()\r\n    {\r\n        // Check if the guard value has its original value\r\n        require(_guardValue == 0, \"REENTRANCY\");\r\n\r\n        // Set the value to something else\r\n        _guardValue = 1;\r\n\r\n        // Function body\r\n        _;\r\n\r\n        // Set the value back\r\n        _guardValue = 0;\r\n    }\r\n}\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\npragma experimental ABIEncoderV2;\r\n\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\ninterface IAgent{}\r\n\r\ninterface IAgentRegistry\r\n{\r\n    /// @dev Returns whether an agent address is an agent of an account owner\r\n    /// @param owner The account owner.\r\n    /// @param agent The agent address\r\n    /// @return True if the agent address is an agent for the account owner, else false\r\n    function isAgent(\r\n        address owner,\r\n        address agent\r\n        )\r\n        external\r\n        view\r\n        returns (bool);\r\n\r\n    /// @dev Returns whether an agent address is an agent of all account owners\r\n    /// @param owners The account owners.\r\n    /// @param agent The agent address\r\n    /// @return True if the agent address is an agent for the account owner, else false\r\n    function isAgent(\r\n        address[] calldata owners,\r\n        address            agent\r\n        )\r\n        external\r\n        view\r\n        returns (bool);\r\n}\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n\r\n\r\n\r\n/// @title IBlockVerifier\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\nabstract contract IBlockVerifier is Claimable\r\n{\r\n    // -- Events --\r\n\r\n    event CircuitRegistered(\r\n        uint8  indexed blockType,\r\n        uint16         blockSize,\r\n        uint8          blockVersion\r\n    );\r\n\r\n    event CircuitDisabled(\r\n        uint8  indexed blockType,\r\n        uint16         blockSize,\r\n        uint8          blockVersion\r\n    );\r\n\r\n    // -- Public functions --\r\n\r\n    /// @dev Sets the verifying key for the specified circuit.\r\n    ///      Every block permutation needs its own circuit and thus its own set of\r\n    ///      verification keys. Only a limited number of block sizes per block\r\n    ///      type are supported.\r\n    /// @param blockType The type of the block\r\n    /// @param blockSize The number of requests handled in the block\r\n    /// @param blockVersion The block version (i.e. which circuit version needs to be used)\r\n    /// @param vk The verification key\r\n    function registerCircuit(\r\n        uint8    blockType,\r\n        uint16   blockSize,\r\n        uint8    blockVersion,\r\n        uint[18] calldata vk\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Disables the use of the specified circuit.\r\n    ///      This will stop NEW blocks from using the given circuit, blocks that were already committed\r\n    ///      can still be verified.\r\n    /// @param blockType The type of the block\r\n    /// @param blockSize The number of requests handled in the block\r\n    /// @param blockVersion The block version (i.e. which circuit version needs to be used)\r\n    function disableCircuit(\r\n        uint8  blockType,\r\n        uint16 blockSize,\r\n        uint8  blockVersion\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Verifies blocks with the given public data and proofs.\r\n    ///      Verifying a block makes sure all requests handled in the block\r\n    ///      are correctly handled by the operator.\r\n    /// @param blockType The type of block\r\n    /// @param blockSize The number of requests handled in the block\r\n    /// @param blockVersion The block version (i.e. which circuit version needs to be used)\r\n    /// @param publicInputs The hash of all the public data of the blocks\r\n    /// @param proofs The ZK proofs proving that the blocks are correct\r\n    /// @return True if the block is valid, false otherwise\r\n    function verifyProofs(\r\n        uint8  blockType,\r\n        uint16 blockSize,\r\n        uint8  blockVersion,\r\n        uint[] calldata publicInputs,\r\n        uint[] calldata proofs\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n\r\n    /// @dev Checks if a circuit with the specified parameters is registered.\r\n    /// @param blockType The type of the block\r\n    /// @param blockSize The number of requests handled in the block\r\n    /// @param blockVersion The block version (i.e. which circuit version needs to be used)\r\n    /// @return True if the circuit is registered, false otherwise\r\n    function isCircuitRegistered(\r\n        uint8  blockType,\r\n        uint16 blockSize,\r\n        uint8  blockVersion\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n\r\n    /// @dev Checks if a circuit can still be used to commit new blocks.\r\n    /// @param blockType The type of the block\r\n    /// @param blockSize The number of requests handled in the block\r\n    /// @param blockVersion The block version (i.e. which circuit version needs to be used)\r\n    /// @return True if the circuit is enabled, false otherwise\r\n    function isCircuitEnabled(\r\n        uint8  blockType,\r\n        uint16 blockSize,\r\n        uint8  blockVersion\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n}\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n/// @title IDepositContract.\r\n/// @dev   Contract storing and transferring funds for an exchange.\r\n///\r\n///        ERC1155 tokens can be supported by registering pseudo token addresses calculated\r\n///        as `address(keccak256(real_token_address, token_params))`. Then the custom\r\n///        deposit contract can look up the real token address and paramsters with the\r\n///        pseudo token address before doing the transfers.\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\ninterface IDepositContract\r\n{\r\n    /// @dev Returns if a token is suppoprted by this contract.\r\n    function isTokenSupported(address token)\r\n        external\r\n        view\r\n        returns (bool);\r\n\r\n    /// @dev Transfers tokens from a user to the exchange. This function will\r\n    ///      be called when a user deposits funds to the exchange.\r\n    ///      In a simple implementation the funds are simply stored inside the\r\n    ///      deposit contract directly. More advanced implementations may store the funds\r\n    ///      in some DeFi application to earn interest, so this function could directly\r\n    ///      call the necessary functions to store the funds there.\r\n    ///\r\n    ///      This function needs to throw when an error occurred!\r\n    ///\r\n    ///      This function can only be called by the exchange.\r\n    ///\r\n    /// @param from The address of the account that sends the tokens.\r\n    /// @param token The address of the token to transfer (`0x0` for ETH).\r\n    /// @param amount The amount of tokens to transfer.\r\n    /// @param extraData Opaque data that can be used by the contract to handle the deposit\r\n    /// @return amountReceived The amount to deposit to the user's account in the Merkle tree\r\n    function deposit(\r\n        address from,\r\n        address token,\r\n        uint96  amount,\r\n        bytes   calldata extraData\r\n        )\r\n        external\r\n        payable\r\n        returns (uint96 amountReceived);\r\n\r\n    /// @dev Transfers tokens from the exchange to a user. This function will\r\n    ///      be called when a withdrawal is done for a user on the exchange.\r\n    ///      In the simplest implementation the funds are simply stored inside the\r\n    ///      deposit contract directly so this simply transfers the requested tokens back\r\n    ///      to the user. More advanced implementations may store the funds\r\n    ///      in some DeFi application to earn interest so the function would\r\n    ///      need to get those tokens back from the DeFi application first before they\r\n    ///      can be transferred to the user.\r\n    ///\r\n    ///      This function needs to throw when an error occurred!\r\n    ///\r\n    ///      This function can only be called by the exchange.\r\n    ///\r\n    /// @param from The address from which 'amount' tokens are transferred.\r\n    /// @param to The address to which 'amount' tokens are transferred.\r\n    /// @param token The address of the token to transfer (`0x0` for ETH).\r\n    /// @param amount The amount of tokens transferred.\r\n    /// @param extraData Opaque data that can be used by the contract to handle the withdrawal\r\n    function withdraw(\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint    amount,\r\n        bytes   calldata extraData\r\n        )\r\n        external\r\n        payable;\r\n\r\n    /// @dev Transfers tokens (ETH not supported) for a user using the allowance set\r\n    ///      for the exchange. This way the approval can be used for all functionality (and\r\n    ///      extended functionality) of the exchange.\r\n    ///      Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw`\r\n    ///      should be used for that as they will contain specialised logic for those operations.\r\n    ///      This function can be called by the exchange to transfer onchain funds of users\r\n    ///      necessary for Agent functionality.\r\n    ///\r\n    ///      This function needs to throw when an error occurred!\r\n    ///\r\n    ///      This function can only be called by the exchange.\r\n    ///\r\n    /// @param from The address of the account that sends the tokens.\r\n    /// @param to The address to which 'amount' tokens are transferred.\r\n    /// @param token The address of the token to transfer (ETH is and cannot be suppported).\r\n    /// @param amount The amount of tokens transferred.\r\n    function transfer(\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint    amount\r\n        )\r\n        external\r\n        payable;\r\n\r\n    /// @dev Checks if the given address is used for depositing ETH or not.\r\n    ///      Is used while depositing to send the correct ETH amount to the deposit contract.\r\n    ///\r\n    ///      Note that 0x0 is always registered for deposting ETH when the exchange is created!\r\n    ///      This function allows additional addresses to be used for depositing ETH, the deposit\r\n    ///      contract can implement different behaviour based on the address value.\r\n    ///\r\n    /// @param addr The address to check\r\n    /// @return True if the address is used for depositing ETH, else false.\r\n    function isETH(address addr)\r\n        external\r\n        view\r\n        returns (bool);\r\n}\r\n\r\n\r\n\r\n/// @title ExchangeData\r\n/// @dev All methods in this lib are internal, therefore, there is no need\r\n///      to deploy this library independently.\r\n/// @author Daniel Wang  - <daniel@loopring.org>\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\nlibrary ExchangeData\r\n{\r\n    // -- Enums --\r\n    enum TransactionType\r\n    {\r\n        NOOP,\r\n        DEPOSIT,\r\n        WITHDRAWAL,\r\n        TRANSFER,\r\n        SPOT_TRADE,\r\n        ACCOUNT_UPDATE,\r\n        AMM_UPDATE\r\n    }\r\n\r\n    // -- Structs --\r\n    struct Token\r\n    {\r\n        address token;\r\n    }\r\n\r\n    struct ProtocolFeeData\r\n    {\r\n        uint32 syncedAt; // only valid before 2105 (85 years to go)\r\n        uint8  takerFeeBips;\r\n        uint8  makerFeeBips;\r\n        uint8  previousTakerFeeBips;\r\n        uint8  previousMakerFeeBips;\r\n    }\r\n\r\n    // General auxiliary data for each conditional transaction\r\n    struct AuxiliaryData\r\n    {\r\n        uint  txIndex;\r\n        bytes data;\r\n    }\r\n\r\n    // This is the (virtual) block the owner  needs to submit onchain to maintain the\r\n    // per-exchange (virtual) blockchain.\r\n    struct Block\r\n    {\r\n        uint8      blockType;\r\n        uint16     blockSize;\r\n        uint8      blockVersion;\r\n        bytes      data;\r\n        uint256[8] proof;\r\n\r\n        // Whether we should store the @BlockInfo for this block on-chain.\r\n        bool storeBlockInfoOnchain;\r\n\r\n        // Block specific data that is only used to help process the block on-chain.\r\n        // It is not used as input for the circuits and it is not necessary for data-availability.\r\n        AuxiliaryData[] auxiliaryData;\r\n\r\n        // Arbitrary data, mainly for off-chain data-availability, i.e.,\r\n        // the multihash of the IPFS file that contains the block data.\r\n        bytes offchainData;\r\n    }\r\n\r\n    struct BlockInfo\r\n    {\r\n        // The time the block was submitted on-chain.\r\n        uint32  timestamp;\r\n        // The public data hash of the block (the 28 most significant bytes).\r\n        bytes28 blockDataHash;\r\n    }\r\n\r\n    // Represents an onchain deposit request.\r\n    struct Deposit\r\n    {\r\n        uint96 amount;\r\n        uint64 timestamp;\r\n    }\r\n\r\n    // A forced withdrawal request.\r\n    // If the actual owner of the account initiated the request (we don't know who the owner is\r\n    // at the time the request is being made) the full balance will be withdrawn.\r\n    struct ForcedWithdrawal\r\n    {\r\n        address owner;\r\n        uint64  timestamp;\r\n    }\r\n\r\n    struct Constants\r\n    {\r\n        uint SNARK_SCALAR_FIELD;\r\n        uint MAX_OPEN_FORCED_REQUESTS;\r\n        uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE;\r\n        uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS;\r\n        uint MAX_NUM_ACCOUNTS;\r\n        uint MAX_NUM_TOKENS;\r\n        uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED;\r\n        uint MIN_TIME_IN_SHUTDOWN;\r\n        uint TX_DATA_AVAILABILITY_SIZE;\r\n        uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND;\r\n    }\r\n\r\n    function SNARK_SCALAR_FIELD() internal pure returns (uint) {\r\n        // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.\r\n        return 21888242871839275222246405745257275088548364400416034343698204186575808495617;\r\n    }\r\n    function MAX_OPEN_FORCED_REQUESTS() internal pure returns (uint16) { return 4096; }\r\n    function MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE() internal pure returns (uint32) { return 15 days; }\r\n    function TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS() internal pure returns (uint32) { return 7 days; }\r\n    function MAX_NUM_ACCOUNTS() internal pure returns (uint) { return 2 ** 32; }\r\n    function MAX_NUM_TOKENS() internal pure returns (uint) { return 2 ** 16; }\r\n    function MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED() internal pure returns (uint32) { return 7 days; }\r\n    function MIN_TIME_IN_SHUTDOWN() internal pure returns (uint32) { return 30 days; }\r\n    // The amount of bytes each rollup transaction uses in the block data for data-availability.\r\n    // This is the maximum amount of bytes of all different transaction types.\r\n    function TX_DATA_AVAILABILITY_SIZE() internal pure returns (uint32) { return 68; }\r\n    function MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND() internal pure returns (uint32) { return 15 days; }\r\n    function ACCOUNTID_PROTOCOLFEE() internal pure returns (uint32) { return 0; }\r\n\r\n    function TX_DATA_AVAILABILITY_SIZE_PART_1() internal pure returns (uint32) { return 29; }\r\n    function TX_DATA_AVAILABILITY_SIZE_PART_2() internal pure returns (uint32) { return 39; }\r\n\r\n    struct AccountLeaf\r\n    {\r\n        uint32   accountID;\r\n        address  owner;\r\n        uint     pubKeyX;\r\n        uint     pubKeyY;\r\n        uint32   nonce;\r\n        uint     feeBipsAMM;\r\n    }\r\n\r\n    struct BalanceLeaf\r\n    {\r\n        uint16   tokenID;\r\n        uint96   balance;\r\n        uint96   weightAMM;\r\n        uint     storageRoot;\r\n    }\r\n\r\n    struct MerkleProof\r\n    {\r\n        ExchangeData.AccountLeaf accountLeaf;\r\n        ExchangeData.BalanceLeaf balanceLeaf;\r\n        uint[48]                 accountMerkleProof;\r\n        uint[24]                 balanceMerkleProof;\r\n    }\r\n\r\n    struct BlockContext\r\n    {\r\n        bytes32 DOMAIN_SEPARATOR;\r\n        uint32  timestamp;\r\n    }\r\n\r\n    // Represents the entire exchange state except the owner of the exchange.\r\n    struct State\r\n    {\r\n        uint32  maxAgeDepositUntilWithdrawable;\r\n        bytes32 DOMAIN_SEPARATOR;\r\n\r\n        ILoopringV3      loopring;\r\n        IBlockVerifier   blockVerifier;\r\n        IAgentRegistry   agentRegistry;\r\n        IDepositContract depositContract;\r\n\r\n\r\n        // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree\r\n        // stores balances for users using an account model.\r\n        bytes32 merkleRoot;\r\n\r\n        // List of all blocks\r\n        mapping(uint => BlockInfo) blocks;\r\n        uint  numBlocks;\r\n\r\n        // List of all tokens\r\n        Token[] tokens;\r\n\r\n        // A map from a token to its tokenID + 1\r\n        mapping (address => uint16) tokenToTokenId;\r\n\r\n        // A map from an accountID to a tokenID to if the balance is withdrawn\r\n        mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode;\r\n\r\n        // A map from an account to a token to the amount withdrawable for that account.\r\n        // This is only used when the automatic distribution of the withdrawal failed.\r\n        mapping (address => mapping (uint16 => uint)) amountWithdrawable;\r\n\r\n        // A map from an account to a token to the forced withdrawal (always full balance)\r\n        mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;\r\n\r\n        // A map from an address to a token to a deposit\r\n        mapping (address => mapping (uint16 => Deposit)) pendingDeposits;\r\n\r\n        // A map from an account owner to an approved transaction hash to if the transaction is approved or not\r\n        mapping (address => mapping (bytes32 => bool)) approvedTx;\r\n\r\n        // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address\r\n        mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient;\r\n\r\n\r\n        // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner\r\n        uint32 numPendingForcedTransactions;\r\n\r\n        // Cached data for the protocol fee\r\n        ProtocolFeeData protocolFeeData;\r\n\r\n        // Time when the exchange was shutdown\r\n        uint shutdownModeStartTime;\r\n\r\n        // Time when the exchange has entered withdrawal mode\r\n        uint withdrawalModeStartTime;\r\n\r\n        // Last time the protocol fee was withdrawn for a specific token\r\n        mapping (address => uint) protocolFeeLastWithdrawnTime;\r\n    }\r\n}\r\n\r\n\r\n\r\n/// @title IExchangeV3\r\n/// @dev Note that Claimable and RentrancyGuard are inherited here to\r\n///      ensure all data members are declared on IExchangeV3 to make it\r\n///      easy to support upgradability through proxies.\r\n///\r\n///      Subclasses of this contract must NOT define constructor to\r\n///      initialize data.\r\n///\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\n/// @author Daniel Wang  - <daniel@loopring.org>\r\nabstract contract IExchangeV3 is Claimable\r\n{\r\n    // -- Events --\r\n\r\n    event ExchangeCloned(\r\n        address exchangeAddress,\r\n        address owner,\r\n        bytes32 genesisMerkleRoot\r\n    );\r\n\r\n    event TokenRegistered(\r\n        address token,\r\n        uint16  tokenId\r\n    );\r\n\r\n    event Shutdown(\r\n        uint timestamp\r\n    );\r\n\r\n    event WithdrawalModeActivated(\r\n        uint timestamp\r\n    );\r\n\r\n    event BlockSubmitted(\r\n        uint    indexed blockIdx,\r\n        bytes32         merkleRoot,\r\n        bytes32         publicDataHash\r\n    );\r\n\r\n    event DepositRequested(\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint16  tokenId,\r\n        uint96  amount\r\n    );\r\n\r\n    event ForcedWithdrawalRequested(\r\n        address owner,\r\n        address token,\r\n        uint32  accountID\r\n    );\r\n\r\n    event WithdrawalCompleted(\r\n        uint8   category,\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint    amount\r\n    );\r\n\r\n    event WithdrawalFailed(\r\n        uint8   category,\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint    amount\r\n    );\r\n\r\n    event ProtocolFeesUpdated(\r\n        uint8 takerFeeBips,\r\n        uint8 makerFeeBips,\r\n        uint8 previousTakerFeeBips,\r\n        uint8 previousMakerFeeBips\r\n    );\r\n\r\n    event TransactionApproved(\r\n        address owner,\r\n        bytes32 transactionHash\r\n    );\r\n\r\n    // events from libraries\r\n    /*event DepositProcessed(\r\n        address to,\r\n        uint32  toAccountId,\r\n        uint16  token,\r\n        uint    amount\r\n    );*/\r\n\r\n    /*event ForcedWithdrawalProcessed(\r\n        uint32 fromAccountID,\r\n        uint16 tokenID,\r\n        uint   amount\r\n    );*/\r\n\r\n    /*event ConditionalTransferProcessed(\r\n        address from,\r\n        address to,\r\n        uint16  token,\r\n        uint    amount\r\n    );*/\r\n\r\n    /*event AccountUpdated(\r\n        uint32 owner,\r\n        uint   publicKey\r\n    );*/\r\n\r\n\r\n    // -- Initialization --\r\n    /// @dev Initializes this exchange. This method can only be called once.\r\n    /// @param  loopring The LoopringV3 contract address.\r\n    /// @param  owner The owner of this exchange.\r\n    /// @param  genesisMerkleRoot The initial Merkle tree state.\r\n    function initialize(\r\n        address loopring,\r\n        address owner,\r\n        bytes32 genesisMerkleRoot\r\n        )\r\n        virtual\r\n        external;\r\n\r\n    /// @dev Initialized the agent registry contract used by the exchange.\r\n    ///      Can only be called by the exchange owner once.\r\n    /// @param agentRegistry The agent registry contract to be used\r\n    function setAgentRegistry(address agentRegistry)\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Gets the agent registry contract used by the exchange.\r\n    /// @return the agent registry contract\r\n    function getAgentRegistry()\r\n        external\r\n        virtual\r\n        view\r\n        returns (IAgentRegistry);\r\n\r\n    ///      Can only be called by the exchange owner once.\r\n    /// @param depositContract The deposit contract to be used\r\n    function setDepositContract(address depositContract)\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Gets the deposit contract used by the exchange.\r\n    /// @return the deposit contract\r\n    function getDepositContract()\r\n        external\r\n        virtual\r\n        view\r\n        returns (IDepositContract);\r\n\r\n    // @dev Exchange owner withdraws fees from the exchange.\r\n    // @param token Fee token address\r\n    // @param feeRecipient Fee recipient address\r\n    function withdrawExchangeFees(\r\n        address token,\r\n        address feeRecipient\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    // -- Constants --\r\n    /// @dev Returns a list of constants used by the exchange.\r\n    /// @return constants The list of constants.\r\n    function getConstants()\r\n        external\r\n        virtual\r\n        pure\r\n        returns(ExchangeData.Constants memory);\r\n\r\n    // -- Mode --\r\n    /// @dev Returns hether the exchange is in withdrawal mode.\r\n    /// @return Returns true if the exchange is in withdrawal mode, else false.\r\n    function isInWithdrawalMode()\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n\r\n    /// @dev Returns whether the exchange is shutdown.\r\n    /// @return Returns true if the exchange is shutdown, else false.\r\n    function isShutdown()\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n\r\n    // -- Tokens --\r\n    /// @dev Registers an ERC20 token for a token id. Note that different exchanges may have\r\n    ///      different ids for the same ERC20 token.\r\n    ///\r\n    ///      Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH),\r\n    ///      and 3 is reserved for Loopring Token (LRC).\r\n    ///\r\n    ///      This function is only callable by the exchange owner.\r\n    ///\r\n    /// @param  tokenAddress The token's address\r\n    /// @return tokenID The token's ID in this exchanges.\r\n    function registerToken(\r\n        address tokenAddress\r\n        )\r\n        external\r\n        virtual\r\n        returns (uint16 tokenID);\r\n\r\n    /// @dev Returns the id of a registered token.\r\n    /// @param  tokenAddress The token's address\r\n    /// @return tokenID The token's ID in this exchanges.\r\n    function getTokenID(\r\n        address tokenAddress\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint16 tokenID);\r\n\r\n    /// @dev Returns the address of a registered token.\r\n    /// @param  tokenID The token's ID in this exchanges.\r\n    /// @return tokenAddress The token's address\r\n    function getTokenAddress(\r\n        uint16 tokenID\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (address tokenAddress);\r\n\r\n    // -- Stakes --\r\n    /// @dev Gets the amount of LRC the owner has staked onchain for this exchange.\r\n    ///      The stake will be burned if the exchange does not fulfill its duty by\r\n    ///      processing user requests in time. Please note that order matching may potentially\r\n    ///      performed by another party and is not part of the exchange's duty.\r\n    ///\r\n    /// @return The amount of LRC staked\r\n    function getExchangeStake()\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint);\r\n\r\n    /// @dev Withdraws the amount staked for this exchange.\r\n    ///      This can only be done if the exchange has been correctly shutdown:\r\n    ///      - The exchange owner has shutdown the exchange\r\n    ///      - All deposit requests are processed\r\n    ///      - All funds are returned to the users (merkle root is reset to initial state)\r\n    ///\r\n    ///      Can only be called by the exchange owner.\r\n    ///\r\n    /// @return amountLRC The amount of LRC withdrawn\r\n    function withdrawExchangeStake(\r\n        address recipient\r\n        )\r\n        external\r\n        virtual\r\n        returns (uint amountLRC);\r\n\r\n    /// @dev Can by called by anyone to burn the stake of the exchange when certain\r\n    ///      conditions are fulfilled.\r\n    ///\r\n    ///      Currently this will only burn the stake of the exchange if\r\n    ///      the exchange is in withdrawal mode.\r\n    function burnExchangeStake()\r\n        external\r\n        virtual;\r\n\r\n    // -- Blocks --\r\n\r\n    /// @dev Gets the current Merkle root of this exchange's virtual blockchain.\r\n    /// @return The current Merkle root.\r\n    function getMerkleRoot()\r\n        external\r\n        virtual\r\n        view\r\n        returns (bytes32);\r\n\r\n    /// @dev Gets the height of this exchange's virtual blockchain. The block height for a\r\n    ///      new exchange is 1.\r\n    /// @return The virtual blockchain height which is the index of the last block.\r\n    function getBlockHeight()\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint);\r\n\r\n    /// @dev Gets some minimal info of a previously submitted block that's kept onchain.\r\n    ///      A DEX can use this function to implement a payment receipt verification\r\n    ///      contract with a challange-response scheme.\r\n    /// @param blockIdx The block index.\r\n    function getBlockInfo(uint blockIdx)\r\n        external\r\n        virtual\r\n        view\r\n        returns (ExchangeData.BlockInfo memory);\r\n\r\n    /// @dev Sumbits new blocks to the rollup blockchain.\r\n    ///\r\n    ///      This function can only be called by the exchange operator.\r\n    ///\r\n    /// @param blocks The blocks being submitted\r\n    ///      - blockType: The type of the new block\r\n    ///      - blockSize: The number of onchain or offchain requests/settlements\r\n    ///        that have been processed in this block\r\n    ///      - blockVersion: The circuit version to use for verifying the block\r\n    ///      - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain\r\n    ///      - data: The data for this block\r\n    ///      - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e.,\r\n    ///        the multihash of the IPFS file that contains the block data.\r\n    function submitBlocks(ExchangeData.Block[] calldata blocks)\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Gets the number of available forced request slots.\r\n    /// @return The number of available slots.\r\n    function getNumAvailableForcedSlots()\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint);\r\n\r\n    // -- Deposits --\r\n\r\n    /// @dev Deposits Ether or ERC20 tokens to the specified account.\r\n    ///\r\n    ///      This function is only callable by an agent of 'from'.\r\n    ///\r\n    ///      A fee to the owner is paid in ETH to process the deposit.\r\n    ///      The operator is not forced to do the deposit and the user can send\r\n    ///      any fee amount.\r\n    ///\r\n    /// @param from The address that deposits the funds to the exchange\r\n    /// @param to The account owner's address receiving the funds\r\n    /// @param tokenAddress The address of the token, use `0x0` for Ether.\r\n    /// @param amount The amount of tokens to deposit\r\n    /// @param auxiliaryData Optional extra data used by the deposit contract\r\n    function deposit(\r\n        address from,\r\n        address to,\r\n        address tokenAddress,\r\n        uint96  amount,\r\n        bytes   calldata auxiliaryData\r\n        )\r\n        external\r\n        virtual\r\n        payable;\r\n\r\n    /// @dev Gets the amount of tokens that may be added to the owner's account.\r\n    /// @param owner The destination address for the amount deposited.\r\n    /// @param tokenAddress The address of the token, use `0x0` for Ether.\r\n    /// @return The amount of tokens pending.\r\n    function getPendingDepositAmount(\r\n        address owner,\r\n        address tokenAddress\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint96);\r\n\r\n    // -- Withdrawals --\r\n    /// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens.\r\n    ///      This request always withdraws the full balance.\r\n    ///\r\n    ///      This function is only callable by an agent of the account.\r\n    ///\r\n    ///      The total fee in ETH that the user needs to pay is 'withdrawalFee'.\r\n    ///      If the user sends too much ETH the surplus is sent back immediately.\r\n    ///\r\n    ///      Note that after such an operation, it will take the owner some\r\n    ///      time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request\r\n    ///      and create the deposit to the offchain account.\r\n    ///\r\n    /// @param owner The expected owner of the account\r\n    /// @param tokenAddress The address of the token, use `0x0` for Ether.\r\n    /// @param accountID The address the account in the Merkle tree.\r\n    function forceWithdraw(\r\n        address owner,\r\n        address tokenAddress,\r\n        uint32  accountID\r\n        )\r\n        external\r\n        virtual\r\n        payable;\r\n\r\n    /// @dev Checks if a forced withdrawal is pending for an account balance.\r\n    /// @param  accountID The accountID of the account to check.\r\n    /// @param  token The token address\r\n    /// @return True if a request is pending, false otherwise\r\n    function isForcedWithdrawalPending(\r\n        uint32  accountID,\r\n        address token\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n\r\n    /// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the\r\n    ///      protocol fees account. The complete balance is always withdrawn.\r\n    ///\r\n    ///      Anyone can request a withdrawal of the protocol fees.\r\n    ///\r\n    ///      Note that after such an operation, it will take the owner some\r\n    ///      time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request\r\n    ///      and create the deposit to the offchain account.\r\n    ///\r\n    /// @param tokenAddress The address of the token, use `0x0` for Ether.\r\n    function withdrawProtocolFees(\r\n        address tokenAddress\r\n        )\r\n        external\r\n        virtual\r\n        payable;\r\n\r\n    /// @dev Gets the time the protocol fee for a token was last withdrawn.\r\n    /// @param tokenAddress The address of the token, use `0x0` for Ether.\r\n    /// @return The time the protocol fee was last withdrawn.\r\n    function getProtocolFeeLastWithdrawnTime(\r\n        address tokenAddress\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint);\r\n\r\n    /// @dev Allows anyone to withdraw funds for a specified user using the balances stored\r\n    ///      in the Merkle tree. The funds will be sent to the owner of the acount.\r\n    ///\r\n    ///      Can only be used in withdrawal mode (i.e. when the owner has stopped\r\n    ///      committing blocks and is not able to commit any more blocks).\r\n    ///\r\n    ///      This will NOT modify the onchain merkle root! The merkle root stored\r\n    ///      onchain will remain the same after the withdrawal. We store if the user\r\n    ///      has withdrawn the balance in State.withdrawnInWithdrawMode.\r\n    ///\r\n    /// @param  merkleProof The Merkle inclusion proof\r\n    function withdrawFromMerkleTree(\r\n        ExchangeData.MerkleProof calldata merkleProof\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`.\r\n    /// @param  accountID The accountID of the balance to check.\r\n    /// @param  token The token address\r\n    /// @return True if it was already withdrawn, false otherwise\r\n    function isWithdrawnInWithdrawalMode(\r\n        uint32  accountID,\r\n        address token\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n\r\n    /// @dev Allows withdrawing funds deposited to the contract in a deposit request when\r\n    ///      it was never processed by the owner within the maximum time allowed.\r\n    ///\r\n    ///      Can be called by anyone. The deposited tokens will be sent back to\r\n    ///      the owner of the account they were deposited in.\r\n    ///\r\n    /// @param  owner The address of the account the withdrawal was done for.\r\n    /// @param  token The token address\r\n    function withdrawFromDepositRequest(\r\n        address owner,\r\n        address token\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Allows withdrawing funds after a withdrawal request (either onchain\r\n    ///      or offchain) was submitted in a block by the operator.\r\n    ///\r\n    ///      Can be called by anyone. The withdrawn tokens will be sent to\r\n    ///      the owner of the account they were withdrawn out.\r\n    ///\r\n    ///      Normally it is should not be needed for users to call this manually.\r\n    ///      Funds from withdrawal requests will be sent to the account owner\r\n    ///      immediately by the owner when the block is submitted.\r\n    ///      The user will however need to call this manually if the transfer failed.\r\n    ///\r\n    ///      Tokens and owners must have the same size.\r\n    ///\r\n    /// @param  owners The addresses of the account the withdrawal was done for.\r\n    /// @param  tokens The token addresses\r\n    function withdrawFromApprovedWithdrawals(\r\n        address[] calldata owners,\r\n        address[] calldata tokens\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`.\r\n    /// @param  owner The address of the account the withdrawal was done for.\r\n    /// @param  token The token address\r\n    /// @return The amount withdrawable\r\n    function getAmountWithdrawable(\r\n        address owner,\r\n        address token\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint);\r\n\r\n    /// @dev Notifies the exchange that the owner did not process a forced request.\r\n    ///      If this is indeed the case, the exchange will enter withdrawal mode.\r\n    ///\r\n    ///      Can be called by anyone.\r\n    ///\r\n    /// @param  accountID The accountID the forced request was made for\r\n    /// @param  token The token address of the the forced request\r\n    function notifyForcedRequestTooOld(\r\n        uint32  accountID,\r\n        address token\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Allows a withdrawal to be done to an adddresss that is different\r\n    ///      than initialy specified in the withdrawal request. This can be used to\r\n    ///      implement functionality like fast withdrawals.\r\n    ///\r\n    ///      This function can only be called by an agent.\r\n    ///\r\n    /// @param from The address of the account that does the withdrawal.\r\n    /// @param to The address to which 'amount' tokens were going to be withdrawn.\r\n    /// @param token The address of the token that is withdrawn ('0x0' for ETH).\r\n    /// @param amount The amount of tokens that are going to be withdrawn.\r\n    /// @param storageID The storageID of the withdrawal request.\r\n    /// @param newRecipient The new recipient address of the withdrawal.\r\n    function setWithdrawalRecipient(\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint96  amount,\r\n        uint32  storageID,\r\n        address newRecipient\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Gets the withdrawal recipient.\r\n    ///\r\n    /// @param from The address of the account that does the withdrawal.\r\n    /// @param to The address to which 'amount' tokens were going to be withdrawn.\r\n    /// @param token The address of the token that is withdrawn ('0x0' for ETH).\r\n    /// @param amount The amount of tokens that are going to be withdrawn.\r\n    /// @param storageID The storageID of the withdrawal request.\r\n    function getWithdrawalRecipient(\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint96  amount,\r\n        uint32  storageID\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (address);\r\n\r\n    /// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance\r\n    ///      the user has set for the exchange. This way the user only needs to approve a single exchange contract\r\n    ///      for all exchange/agent features, which allows for a more seamless user experience.\r\n    ///\r\n    ///      This function can only be called by an agent.\r\n    ///\r\n    /// @param from The address of the account that sends the tokens.\r\n    /// @param to The address to which 'amount' tokens are transferred.\r\n    /// @param token The address of the token to transfer (ETH is and cannot be suppported).\r\n    /// @param amount The amount of tokens transferred.\r\n    function onchainTransferFrom(\r\n        address from,\r\n        address to,\r\n        address token,\r\n        uint    amount\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Allows an agent to approve a rollup tx.\r\n    ///\r\n    ///      This function can only be called by an agent.\r\n    ///\r\n    /// @param owner The owner of the account\r\n    /// @param txHash The hash of the transaction\r\n    function approveTransaction(\r\n        address owner,\r\n        bytes32 txHash\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Allows an agent to approve multiple rollup txs.\r\n    ///\r\n    ///      This function can only be called by an agent.\r\n    ///\r\n    /// @param owners The account owners\r\n    /// @param txHashes The hashes of the transactions\r\n    function approveTransactions(\r\n        address[] calldata owners,\r\n        bytes32[] calldata txHashes\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Checks if a rollup tx is approved using the tx's hash.\r\n    ///\r\n    /// @param owner The owner of the account that needs to authorize the tx\r\n    /// @param txHash The hash of the transaction\r\n    /// @return True if the tx is approved, else false\r\n    function isTransactionApproved(\r\n        address owner,\r\n        bytes32 txHash\r\n        )\r\n        external\r\n        virtual\r\n        view\r\n        returns (bool);\r\n\r\n    // -- Admins --\r\n    /// @dev Sets the max time deposits have to wait before becoming withdrawable.\r\n    /// @param newValue The new value.\r\n    /// @return  The old value.\r\n    function setMaxAgeDepositUntilWithdrawable(\r\n        uint32 newValue\r\n        )\r\n        external\r\n        virtual\r\n        returns (uint32);\r\n\r\n    /// @dev Returns the max time deposits have to wait before becoming withdrawable.\r\n    /// @return The value.\r\n    function getMaxAgeDepositUntilWithdrawable()\r\n        external\r\n        virtual\r\n        view\r\n        returns (uint32);\r\n\r\n    /// @dev Shuts down the exchange.\r\n    ///      Once the exchange is shutdown all onchain requests are permanently disabled.\r\n    ///      When all requirements are fulfilled the exchange owner can withdraw\r\n    ///      the exchange stake with withdrawStake.\r\n    ///\r\n    ///      Note that the exchange can still enter the withdrawal mode after this function\r\n    ///      has been invoked successfully. To prevent entering the withdrawal mode before the\r\n    ///      the echange stake can be withdrawn, all withdrawal requests still need to be handled\r\n    ///      for at least MIN_TIME_IN_SHUTDOWN seconds.\r\n    ///\r\n    ///      Can only be called by the exchange owner.\r\n    ///\r\n    /// @return success True if the exchange is shutdown, else False\r\n    function shutdown()\r\n        external\r\n        virtual\r\n        returns (bool success);\r\n\r\n    /// @dev Gets the protocol fees for this exchange.\r\n    /// @return syncedAt The timestamp the protocol fees were last updated\r\n    /// @return takerFeeBips The protocol taker fee\r\n    /// @return makerFeeBips The protocol maker fee\r\n    /// @return previousTakerFeeBips The previous protocol taker fee\r\n    /// @return previousMakerFeeBips The previous protocol maker fee\r\n    function getProtocolFeeValues()\r\n        external\r\n        virtual\r\n        view\r\n        returns (\r\n            uint32 syncedAt,\r\n            uint8 takerFeeBips,\r\n            uint8 makerFeeBips,\r\n            uint8 previousTakerFeeBips,\r\n            uint8 previousMakerFeeBips\r\n        );\r\n\r\n    /// @dev Gets the domain separator used in this exchange.\r\n    function getDomainSeparator()\r\n        external\r\n        virtual\r\n        view\r\n        returns (bytes32);\r\n}\r\n\r\n\r\n// Copyright 2017 Loopring Technology Limited.\r\n\r\n\r\n\r\n\r\n\r\n/// @title ILoopringV3\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\n/// @author Daniel Wang  - <daniel@loopring.org>\r\nabstract contract ILoopringV3 is Claimable\r\n{\r\n    // == Events ==\r\n    event ExchangeStakeDeposited(address exchangeAddr, uint amount);\r\n    event ExchangeStakeWithdrawn(address exchangeAddr, uint amount);\r\n    event ExchangeStakeBurned(address exchangeAddr, uint amount);\r\n    event SettingsUpdated(uint time);\r\n\r\n    // == Public Variables ==\r\n    mapping (address => uint) internal exchangeStake;\r\n\r\n    address public lrcAddress;\r\n    uint    public totalStake;\r\n    address public blockVerifierAddress;\r\n    uint    public forcedWithdrawalFee;\r\n    uint    public tokenRegistrationFeeLRCBase;\r\n    uint    public tokenRegistrationFeeLRCDelta;\r\n    uint8   public protocolTakerFeeBips;\r\n    uint8   public protocolMakerFeeBips;\r\n\r\n    address payable public protocolFeeVault;\r\n\r\n    // == Public Functions ==\r\n    /// @dev Updates the global exchange settings.\r\n    ///      This function can only be called by the owner of this contract.\r\n    ///\r\n    ///      Warning: these new values will be used by existing and\r\n    ///      new Loopring exchanges.\r\n    function updateSettings(\r\n        address payable _protocolFeeVault,   // address(0) not allowed\r\n        address _blockVerifierAddress,       // address(0) not allowed\r\n        uint    _forcedWithdrawalFee\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Updates the global protocol fee settings.\r\n    ///      This function can only be called by the owner of this contract.\r\n    ///\r\n    ///      Warning: these new values will be used by existing and\r\n    ///      new Loopring exchanges.\r\n    function updateProtocolFeeSettings(\r\n        uint8 _protocolTakerFeeBips,\r\n        uint8 _protocolMakerFeeBips\r\n        )\r\n        external\r\n        virtual;\r\n\r\n    /// @dev Gets the amount of staked LRC for an exchange.\r\n    /// @param exchangeAddr The address of the exchange\r\n    /// @return stakedLRC The amount of LRC\r\n    function getExchangeStake(\r\n        address exchangeAddr\r\n        )\r\n        public\r\n        virtual\r\n        view\r\n        returns (uint stakedLRC);\r\n\r\n    /// @dev Burns a certain amount of staked LRC for a specific exchange.\r\n    ///      This function is meant to be called only from exchange contracts.\r\n    /// @return burnedLRC The amount of LRC burned. If the amount is greater than\r\n    ///         the staked amount, all staked LRC will be burned.\r\n    function burnExchangeStake(\r\n        uint amount\r\n        )\r\n        external\r\n        virtual\r\n        returns (uint burnedLRC);\r\n\r\n    /// @dev Stakes more LRC for an exchange.\r\n    /// @param  exchangeAddr The address of the exchange\r\n    /// @param  amountLRC The amount of LRC to stake\r\n    /// @return stakedLRC The total amount of LRC staked for the exchange\r\n    function depositExchangeStake(\r\n        address exchangeAddr,\r\n        uint    amountLRC\r\n        )\r\n        external\r\n        virtual\r\n        returns (uint stakedLRC);\r\n\r\n    /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address.\r\n    ///      This function is meant to be called only from within exchange contracts.\r\n    /// @param  recipient The address to receive LRC\r\n    /// @param  requestedAmount The amount of LRC to withdraw\r\n    /// @return amountLRC The amount of LRC withdrawn\r\n    function withdrawExchangeStake(\r\n        address recipient,\r\n        uint    requestedAmount\r\n        )\r\n        external\r\n        virtual\r\n        returns (uint amountLRC);\r\n\r\n    /// @dev Gets the protocol fee values for an exchange.\r\n    /// @return takerFeeBips The protocol taker fee\r\n    /// @return makerFeeBips The protocol maker fee\r\n    function getProtocolFeeValues(\r\n        )\r\n        public\r\n        virtual\r\n        view\r\n        returns (\r\n            uint8 takerFeeBips,\r\n            uint8 makerFeeBips\r\n        );\r\n}\r\n\r\n\r\n\r\n/// @title LoopringV3\r\n/// @dev This contract does NOT support proxy.\r\n/// @author Brecht Devos - <brecht@loopring.org>\r\n/// @author Daniel Wang  - <daniel@loopring.org>\r\ncontract LoopringV3 is ILoopringV3, ReentrancyGuard\r\n{\r\n    using AddressUtil       for address payable;\r\n    using MathUint          for uint;\r\n    using ERC20SafeTransfer for address;\r\n\r\n    // -- Constructor --\r\n    constructor(\r\n        address _lrcAddress,\r\n        address payable _protocolFeeVault,\r\n        address _blockVerifierAddress\r\n        )\r\n        Claimable()\r\n    {\r\n        require(address(0) != _lrcAddress, \"ZERO_ADDRESS\");\r\n\r\n        lrcAddress = _lrcAddress;\r\n\r\n        updateSettingsInternal(_protocolFeeVault, _blockVerifierAddress, 0);\r\n    }\r\n\r\n    // == Public Functions ==\r\n    function updateSettings(\r\n        address payable _protocolFeeVault,\r\n        address _blockVerifierAddress,\r\n        uint    _forcedWithdrawalFee\r\n        )\r\n        external\r\n        override\r\n        nonReentrant\r\n        onlyOwner\r\n    {\r\n        updateSettingsInternal(\r\n            _protocolFeeVault,\r\n            _blockVerifierAddress,\r\n            _forcedWithdrawalFee\r\n        );\r\n    }\r\n\r\n    function updateProtocolFeeSettings(\r\n        uint8 _protocolTakerFeeBips,\r\n        uint8 _protocolMakerFeeBips\r\n        )\r\n        external\r\n        override\r\n        nonReentrant\r\n        onlyOwner\r\n    {\r\n        protocolTakerFeeBips = _protocolTakerFeeBips;\r\n        protocolMakerFeeBips = _protocolMakerFeeBips;\r\n\r\n        emit SettingsUpdated(block.timestamp);\r\n    }\r\n\r\n    function getExchangeStake(\r\n        address exchangeAddr\r\n        )\r\n        public\r\n        override\r\n        view\r\n        returns (uint)\r\n    {\r\n        return exchangeStake[exchangeAddr];\r\n    }\r\n\r\n    function burnExchangeStake(\r\n        uint amount\r\n        )\r\n        external\r\n        override\r\n        nonReentrant\r\n        returns (uint burnedLRC)\r\n    {\r\n        burnedLRC = exchangeStake[msg.sender];\r\n\r\n        if (amount < burnedLRC) {\r\n            burnedLRC = amount;\r\n        }\r\n        if (burnedLRC > 0) {\r\n            lrcAddress.safeTransferAndVerify(protocolFeeVault, burnedLRC);\r\n            exchangeStake[msg.sender] = exchangeStake[msg.sender].sub(burnedLRC);\r\n            totalStake = totalStake.sub(burnedLRC);\r\n        }\r\n        emit ExchangeStakeBurned(msg.sender, burnedLRC);\r\n    }\r\n\r\n    function depositExchangeStake(\r\n        address exchangeAddr,\r\n        uint    amountLRC\r\n        )\r\n        external\r\n        override\r\n        nonReentrant\r\n        returns (uint stakedLRC)\r\n    {\r\n        require(amountLRC > 0, \"ZERO_VALUE\");\r\n\r\n        lrcAddress.safeTransferFromAndVerify(msg.sender, address(this), amountLRC);\r\n\r\n        stakedLRC = exchangeStake[exchangeAddr].add(amountLRC);\r\n        exchangeStake[exchangeAddr] = stakedLRC;\r\n        totalStake = totalStake.add(amountLRC);\r\n\r\n        emit ExchangeStakeDeposited(exchangeAddr, amountLRC);\r\n    }\r\n\r\n    function withdrawExchangeStake(\r\n        address recipient,\r\n        uint    requestedAmount\r\n        )\r\n        external\r\n        override\r\n        nonReentrant\r\n        returns (uint amountLRC)\r\n    {\r\n        uint stake = exchangeStake[msg.sender];\r\n        amountLRC = (stake > requestedAmount) ? requestedAmount : stake;\r\n\r\n        if (amountLRC > 0) {\r\n            lrcAddress.safeTransferAndVerify(recipient, amountLRC);\r\n            exchangeStake[msg.sender] = exchangeStake[msg.sender].sub(amountLRC);\r\n            totalStake = totalStake.sub(amountLRC);\r\n        }\r\n\r\n        emit ExchangeStakeWithdrawn(msg.sender, amountLRC);\r\n    }\r\n\r\n    function getProtocolFeeValues()\r\n        public\r\n        override\r\n        view\r\n        returns (\r\n            uint8 takerFeeBips,\r\n            uint8 makerFeeBips\r\n        )\r\n    {\r\n        return (protocolTakerFeeBips, protocolMakerFeeBips);\r\n    }\r\n\r\n    // == Internal Functions ==\r\n    function updateSettingsInternal(\r\n        address payable  _protocolFeeVault,\r\n        address _blockVerifierAddress,\r\n        uint    _forcedWithdrawalFee\r\n        )\r\n        private\r\n    {\r\n        require(address(0) != _protocolFeeVault, \"ZERO_ADDRESS\");\r\n        require(address(0) != _blockVerifierAddress, \"ZERO_ADDRESS\");\r\n\r\n        protocolFeeVault = _protocolFeeVault;\r\n        blockVerifierAddress = _blockVerifierAddress;\r\n        forcedWithdrawalFee = _forcedWithdrawalFee;\r\n\r\n        emit SettingsUpdated(block.timestamp);\r\n    }\r\n}"}},"matchId":"6770648","creationMatch":"match","runtimeMatch":"match","verifiedAt":"2025-07-04T22:46:56Z","match":"match","chainId":"1","address":"0xe56D6ccab6551932C0356E4e8d5dAF0630920C71"}