Address io1xs36c05w0qxppqw95yv5ulux97c7p82laelkgt

Contract Overview

Balance:
0 IOTX

IOTX Value:
$ 0

Token:
Txn Hash
Block
From
To
Value [Txn Fee]
Parent Txn Hash Block From To Value
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
IOTXClear

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion, None license

Contract Source Code (Solidity)

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol


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

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol


// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;


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

// File: interfaces/ISystemStaking.sol


/*
 * ==================================================================
 * Copyright (C) 2023 Altstake Technology Pte. Ltd. (RockX)
 * This code is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License.
 * If not, see <http://www.gnu.org/licenses/>
 * ==================================================================
 */

pragma solidity ^0.8.9;


// @notice This is the IoTeX system contract interface. It issues an NFT token for each bucket creation.
// For more information see https://github.com/iotexproject/iip13-contracts/blob/main/src/SystemStaking.sol
interface ISystemStaking is IERC721 {
    function isActiveBucketType(uint256 _amount, uint256 _duration) external view returns (bool);
    function bucketOf(uint _tokenId) external view returns ( uint amount_, uint duration_, uint unlockedAt_, uint unstakedAt_, address delegate_);

    function stake(uint _amount, uint _duration, address _delegate, uint _count) external payable returns (uint firstTokenId_);
    function unlock(uint[] calldata _tokenIds) external;
    function unstake(uint[] calldata _tokenIds) external;
    function withdraw( uint[] calldata _tokenIds, address payable _recipient) external;

    function merge(uint[] calldata tokenIds, uint _newDuration) external payable;

    function changeDelegates(uint[] calldata _tokenIds, address _delegate) external;
}

// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol


// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^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 `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: interfaces/IIOTXStaking.sol


/*
 * ==================================================================
 * Copyright (C) 2023 Altstake Technology Pte. Ltd. (RockX)
 * This code is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License.
 * If not, see <http://www.gnu.org/licenses/>
 * ==================================================================
 */

pragma solidity ^0.8.9;


interface IIOTXStaking is IERC721Receiver {
    function exchangeRatio() external returns (uint ratio);
    function currentReserve() external view returns(uint);
    function redeemAmountBase() external returns(uint);
    function getRedeemedTokenIdSlice(uint i, uint j) external view returns (uint[] memory tokenIds);
    function getStakedTokenCount(uint tokenQueueIndex) external view returns (uint count);
    function setGlobalDelegate(address delegate) external;
    function updateDelegates(uint[] calldata tokenIds, address delegate) external;
    function deposit(uint deadline) external payable returns (uint minted);
    function stake() external;
    function redeem(uint iotxsToRedeem, uint deadline) external returns (uint burned);
    function updateReward() external;
    function withdrawManagerFee(uint amount, address recipient) external;
}
// File: interfaces/IIOTXClear.sol


/*
 * ==================================================================
 * Copyright (C) 2023 Altstake Technology Pte. Ltd. (RockX)
 * This code is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License.
 * If not, see <http://www.gnu.org/licenses/>
 * ==================================================================
 */

pragma solidity ^0.8.9;


interface IIOTXClear is IERC721Receiver {
    function updateDelegates(uint[] calldata tokenIds, address delegate) external;
    function getReward(address acount) external returns (uint);
    function joinDebt(address claimAddr, uint amount) external;
    function unstake(uint[] calldata tokenIds) external;
    function payDebts(uint[] calldata tokenIds) external;
    function claimRewards(uint amount, address recipient) external;
    function claimPrincipals(uint amount, address recipient) external;
    function claim(uint amount, address recipient) external;
}

// File: interfaces/Roles.sol


/*
 * ==================================================================
 * Copyright (C) 2023 Altstake Technology Pte. Ltd. (RockX)
 * This code is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License.
 * If not, see <http://www.gnu.org/licenses/>
 * ==================================================================
 */

pragma solidity ^0.8.9;

// Roles
bytes32 constant ROLE_PAUSER = keccak256("ROLE_PAUSER");
bytes32 constant ROLE_MINTER = keccak256("ROLE_MINTER");
bytes32 constant ROLE_STAKER = keccak256("ROLE_STAKER");
bytes32 constant ROLE_FEE_MANAGER = keccak256("ROLE_FEE_MANAGER");
bytes32 constant ROLE_ORACLE = keccak256("ROLE_ORACLE");
// File: @openzeppelin/contracts/utils/Address.sol


// OpenZeppelin Contracts (last updated v4.9.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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/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);
        }
    }
}

// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol


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

// File: @openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol


// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMathUpgradeable {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// File: @openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol


// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 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. If 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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 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) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

// File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol


// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;



/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = MathUpgradeable.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, MathUpgradeable.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// File: @openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol


// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol


// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/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);
        }
    }
}

// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol


// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;


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

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

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

// File: @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol


// OpenZeppelin Contracts (last updated v4.9.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 ReentrancyGuardUpgradeable is Initializable {
    // 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;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _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;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol


// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;



/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol


// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^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 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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol


// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;






/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol


// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;



/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

// File: contracts/IOTXClear.sol


/*
 * ==================================================================
 * Copyright (C) 2023 Altstake Technology Pte. Ltd. (RockX)
 * This code is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License.
 * If not, see <http://www.gnu.org/licenses/>
 * ==================================================================
 */

pragma solidity ^0.8.9;










contract IOTXClear is IIOTXClear, Initializable, PausableUpgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
    using Address for address payable;

    address public systemStaking;

    uint private constant MULTIPLIER = 1e18;

    /**
     * @dev A struct type for recording users' debt, principal and reward.
     */
    struct UserInfo {
        // The remaining amount of the user's debt. Its value fluctuates due to several factors:
        // 1. It increases when a user request to redeem IOTXs from the 'IOTXStake' contract.
        // 2. It decreases when a debt payment is made.
        uint debt;
        // The claimable amount of the users' principal. Its value fluctuates due to several factors:
        // 1. It increases when a debt payment is made.
        // 2. It decreases when the user claims principal.
        uint principal;
        // The claimable amount of the users' reward. Its value fluctuates due to several factors:
        // 1. It increases When the delegate distributes rewards.
        // 2. It decreases when the user claim a reward.
        uint reward;
        // Users' reward rate depends on the shared 'rewardRate'.
        // It is updated whenever '_updateUserReward' is called.
        uint rewardRate;
    }

    /**
     * @dev A struct type for managing debt items in a FIFO queue.
     */
    struct Debt {
        address account;
        uint amount;
    }

    /**
     * @dev The balance synchronized from this contract fluctuates due to several factors:
     * 1. It increases when the Oracle triggers debt payment.
     * 2. It increases when rewards are distributed by delegates.
     * 3. It decreases when users claim their rewards or principal..
     */
    uint public accountedBalance;

    /**
     * @dev The total debt fluctuates due to several factors:
     * 1. It increases when a new debt item is added.
     * 2. It decreases when a debt payment is made.
     */
    uint public totalDebts;

    /**
     * @dev The accumulated reward rate is influenced by the incremental reward and total debt.
     * It's calculated using the following formula: rewardRate += incrReward * 1e18 / totalDebts
     */
    uint public rewardRate;

    /**
     * @dev The permissible amount of new debt should be in multiples of the base debt amount.
     * This base value is determined at contract initialization.
     * Once set, it remains immutable.
     */
    uint public debtAmountBase;

    /**
     * @dev Simulating a First-In-First-Out (FIFO) queue of debts.
     *
     * A 'joinDebt' request will add a new debt item to the end of the queue.
     * A 'payDebts' request will settle the debt from the front end of the queue.
     *
     * Here are the key features of this FIFO queue:
     * 1. Each debt item is given a unique index.
     * 2. The index for adding a new debt: rearIndex + 1.
     * 3. The index for the next debt payment is: headIndex + 1.
     * 4. The total number of added debts is represented by: rearIndex.
     * 5. The total number of paid debts is represented by: headIndex.
     * 6. The total number of unpaid debts can be calculated as: rearIndex - headIndex.
     */
    mapping(uint=>Debt) private iotxDebts;
    uint private headIndex;
    uint private rearIndex;

    /**
     * @dev The map for user information management:
     * 1. The KEY is the user's account address.
     * 2. The VALUE is of type UserInfo.
     */
    mapping(address => UserInfo) private userInfos;

    event DebtQueued(address account, uint amount, uint debtIndex);
    event DebtPaid(address account, uint amount, uint debtIndex);
    event Claimed(address claimer, address recipient, uint amount);
    event PrincipalClaimed(address claimer, address recipient, uint amount);
    event RewardClaimed(address claimer, address recipient, uint amount);
    event DelegatesUpdated(uint[] tokenIds, address delegate);

    modifier onlyDebtAmount(uint amount) {
        require(amount > 0 && amount % debtAmountBase == 0, "SYS003");  // Invalid debt amount
        _;
    }

    modifier onlyDebtToken(uint[] calldata tokenIds) {
        for (uint i; i < tokenIds.length; i++) {
            (uint tokenAmt, , , ,) = ISystemStaking(systemStaking).bucketOf(tokenIds[i]);
            require(tokenAmt == debtAmountBase, "USR007");  // Invalid token amount for debt payment
        }
        _;
    }


    /**
     * ======================================================================================
     *
     * SYSTEM SETTINGS
     *
     * ======================================================================================
     */

    /**
     * @dev This function is exclusively designed to receive staking rewards generated after the 'joinDebt' function is evoked.
     * Any IOTXs inadvertently sent to this contract will be considered as rewards.
     */
    receive() external payable { }

    /**
     * @dev This function pauses the contract
     */
    function pause() public onlyRole(ROLE_PAUSER) {
        _pause();
    }

    /**
     * @dev This function unpauses the contract
     */
    function unpause() public onlyRole(ROLE_PAUSER) {
        _unpause();
    }

    /**
     * @dev @custom:oz-upgrades-unsafe-allow constructor
     */
    constructor() {
        _disableInitializers();
    }

    /**
     * @dev This function initializes the contract
     */
    function initialize(
        address _systemStaking,
        address _iotxStaking,
        address _oracle,
        address _pauser
    ) public initializer  {
        // Init
        __Pausable_init();
        __AccessControl_init();
        __ReentrancyGuard_init();

        // Roles
        _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _setupRole(ROLE_PAUSER, _pauser);
        _setupRole(ROLE_STAKER, _iotxStaking);
        _setupRole(ROLE_ORACLE, _oracle);

        // Collaborative contracts
        systemStaking = _systemStaking;

        // Debt management parameters
        debtAmountBase = IIOTXStaking(_iotxStaking).redeemAmountBase();
    }


    /**
     * ======================================================================================
     *
     * VIEW FUNCTIONS
     *
     * ======================================================================================
     */

    /**
     * @dev This function is the 'IERC721Receiver' implement for receiving redeemed/unlocked NFT transferred by IOTXStaking contract
     */
    function onERC721Received(
        address, // operator
        address, // from
        uint, // tokenId
        bytes calldata // data
    ) external pure override returns (bytes4) {
            return this.onERC721Received.selector;
    }

    /**
     * @return The balance that has been synchronized and accounted for this contract.
     */
    function getAccountedBalance() external view returns (uint) {
        return accountedBalance;
    }

    /**
     * @return The total amount of outstanding debts.
     */
    function getTotalDebts() external view returns (uint) {
        return totalDebts;
    }

    /**
     * @return The reward rate, which is accumulated and shared among users.
     */
    function getRewardRate() external view returns (uint) {
        return rewardRate;
    }

    /**
     * @dev The permissible amount of new debt should be in multiples of the base debt amount.
     * @return The base amount for joining a new debt item.
     */
    function getDebtAmountBase() external view returns (uint) {
        return debtAmountBase;
    }

    /**
     * @return The user's balance, comprising both rewards and principal, is available for future claims.
     */
    function getBalance(address account) external view returns (uint) {
        return userInfos[account].reward + _calcPendingReward(account) + userInfos[account].principal;
    }

    /**
     * @dev The returned value includes the pending reward that hasn't been accounted yet.
     * @return The user's reward that is available for future claims.
     */
    function getReward(address account) external view returns (uint) {
        return userInfos[account].reward + _calcPendingReward(account);
    }

    /**
     * @dev The amount of the paid debt will be added to the user's principal.
     * @return The user's principal that is available for future claims.
     */
    function getPrincipal(address account) external view returns (uint) {
        return userInfos[account].principal;
    }

    /**
     * @dev The amount of the paid debt will be added to the user's principal.
     * @return The user's remaining debt that needs payment.
     */
    function getDebt(address account) external view returns (uint) {
        return userInfos[account].debt;
    }

    /**
     * @return The total number of debt items, encompassing both paid and outstanding payments.
     */
    function getTotalDebtItemCount() external view returns (uint) {
        return rearIndex;
    }

    /**
     * @return The number of debt items that have been paid.
     */
    function getPaidDebtItemCount() external view returns (uint) {
        return headIndex;
    }

    /**
     * @return The number of debt items awaiting payment.
     */
    function getUnpaidDebtItemCount() external view returns (uint) {
        return rearIndex-headIndex;
    }

    /**
     * @param unpaidDebtIndex The index of the unpaid debt item in the FIFO queue
     * should range between (paidDebtItemCount, totalDebtItemCount].
     * @return The queued unpaid debt item.
     */
    function getUnpaidDebtItem(uint unpaidDebtIndex) external view returns (Debt memory) {
        if (headIndex < unpaidDebtIndex && unpaidDebtIndex <= rearIndex) {
            return iotxDebts[unpaidDebtIndex];
        }
        return Debt({account:0x0000000000000000000000000000000000000000, amount:0});
    }

    /**
     * @return The total queued unpaid debt items.
     */
    function getUnpaidDebtItems() external view returns (Debt[] memory) {
        if (headIndex < rearIndex) {
            uint count = rearIndex - headIndex;
            Debt[] memory items = new Debt[](count);
            uint firstIndex = headIndex+1;
            for (uint i = 0; i < count; i++) {
                items[i] = iotxDebts[firstIndex+i];
            }
            return items;
        }
        return new Debt[](0);
    }

    /**
     * @return The user information of the given account.
     */
    function getUserInfo(address account) external view returns (UserInfo memory) {
        return userInfos[account];
    }

    /**
     * ======================================================================================
     *
     * EXTERNAL FUNCTIONS FOR STAKER
     *
     * ======================================================================================
     */

    /**
     * @dev The contract 'IOTXStaking' calls this function upon the user's redeeming request.
     * This function queues the redeemed amount as debt, which can be paid by withdrawal in FIFO order.
     */
    function joinDebt(address account, uint amount) external whenNotPaused onlyDebtAmount(amount) onlyRole(ROLE_STAKER) {
        // Update current user reward
        _updateUserReward(account);

        // Record new user debt
        _enqueueDebt(account, amount);
    }


    /**
     * ======================================================================================
     *
     * EXTERNAL FUNCTIONS FOR ORACLE
     *
     * ======================================================================================
     */

    /**
     * @dev This function updates the delegates of token IDs.
     */
    function updateDelegates(uint[] calldata tokenIds, address delegate) external whenNotPaused onlyRole(ROLE_ORACLE) {
        ISystemStaking(systemStaking).changeDelegates(tokenIds, delegate);

        emit DelegatesUpdated(tokenIds, delegate);
    }

    /**
     * @dev This function unstakes unlocked tokens, allowing them to be used for future debt payment.
     */
    function unstake(uint[] calldata tokenIds) external whenNotPaused onlyDebtToken(tokenIds) onlyRole(ROLE_ORACLE) {
        if (tokenIds.length > 0) ISystemStaking(systemStaking).unstake(tokenIds);
    }

    /**
     * @dev This function withdraws the specified tokens for debt payment.
     */
    function payDebts(uint[] calldata tokenIds) external whenNotPaused onlyDebtToken(tokenIds) onlyRole(ROLE_ORACLE) {
        uint totalTokenCntToPay = tokenIds.length;
        require(totalTokenCntToPay > 0 && totalDebts >= totalTokenCntToPay*debtAmountBase, "USR008");  // Invalid total principal for debt payment
        uint paidTokenCnt;
        while (paidTokenCnt < totalTokenCntToPay) {
            // Peek next debt
            Debt memory nextDebt = _peekNextDebt();

            // Update current user reward
            _updateUserReward(nextDebt.account);

            // Determine token IDs
            uint remainedTokenCntToPay = totalTokenCntToPay - paidTokenCnt;
            uint maxTokenCntToPay = nextDebt.amount / debtAmountBase;
            uint tokenCntToPay = (maxTokenCntToPay > remainedTokenCntToPay) ? remainedTokenCntToPay: maxTokenCntToPay;
            uint amountToPay = debtAmountBase * tokenCntToPay;

            uint[] memory tokenIdsToPay = new uint[](tokenCntToPay);
            for (uint i = 0; i < tokenCntToPay; i++) {
                tokenIdsToPay[i] = tokenIds[paidTokenCnt+i];
            }

            // Pay the user's debt
            _payNextDebt(amountToPay, tokenIdsToPay);
            paidTokenCnt += tokenCntToPay;
        }
    }


    /**
     * ======================================================================================
     *
     * EXTERNAL FUNCTIONS FOR USERS
     *
     * ======================================================================================
     */

    /**
     * @dev This function allows users to claim their claimable asset to the specified recipient.
     * The assets that the user can claim consist of rewards and principal.
     * The rewards will be subtracted first, followed by the principal.
     */
    function claim(uint amount, address recipient) external nonReentrant whenNotPaused {
        // Update reward
        _updateUserReward(msg.sender);

        // Check user quota
        UserInfo storage info = userInfos[msg.sender];
        require(info.principal + info.reward >= amount, "USR009");  // Insufficient accounted asset

        // Transfer asset
        if (info.reward >= amount) {
            info.reward -= amount;
        } else {
            info.principal -= amount - info.reward;
            info.reward = 0;
        }
        accountedBalance -= amount;
        payable(recipient).sendValue(amount);

        emit Claimed(msg.sender, recipient, amount);
    }

    /**
     * @dev This function allows users to claim their principals to the specified recipient.
     */
    function claimPrincipals(uint amount, address recipient) external nonReentrant whenNotPaused {
        // Check principal
        UserInfo storage info = userInfos[msg.sender];
        require(info.principal >= amount, "USR004");  // Insufficient accounted principal

        // Transfer principal
        info.principal -= amount;
        accountedBalance -= amount;
        payable(recipient).sendValue(amount);

        emit PrincipalClaimed(msg.sender, recipient, amount);
    }

    /**
     * @dev This function allows users to claim their rewards to the specified recipient.
     */
    function claimRewards(uint amount, address recipient) external nonReentrant whenNotPaused {
         // Update reward
        _updateUserReward(msg.sender);

        // Check reward
        UserInfo storage info = userInfos[msg.sender];
        require(info.reward >= amount, "USR005");  // Insufficient accounted reward

        // Transfer reward
        info.reward -= amount;
        accountedBalance -= amount;
        payable(recipient).sendValue(amount);

        emit RewardClaimed(msg.sender, recipient, amount);
    }


    /**
     * ======================================================================================
     *
     * INTERNAL FUNCTIONS
     *
     * ======================================================================================
     */

    /**
     * @dev This function appends a debt item to the FIFO queue.
     */
    function _enqueueDebt(address account, uint amount) internal {
        // Add a debt in FIFO order
        rearIndex += 1;
        iotxDebts[rearIndex] = Debt({account:account, amount:amount});

        // Update debt states
        userInfos[account].debt += amount;
        totalDebts += amount;

        emit DebtQueued(account, amount, rearIndex);
    }

    /**
     * @dev This function retrieves a debt item from the FIFO queue for the next payment,
     * without removing it from the queue.
     */
    function _peekNextDebt() internal view returns (Debt memory firstDebt) {
        firstDebt = iotxDebts[headIndex+1];
    }

    /**
     * @dev This function removes a debt item from the FIFO queue.
     */
    function _dequeueDebt() internal returns (Debt memory debt) {
        require(!_isEmptyQueue(), "SYS004");  // Empty queue
        uint firstDebt = headIndex+1;
        debt = iotxDebts[firstDebt];
        delete iotxDebts[firstDebt];
        headIndex += 1;
    }

    /**
     * @dev This function checks if the FIFO queue is empty.
     */
    function _isEmptyQueue() internal view returns (bool) {
        return rearIndex == headIndex;
    }

    /**
     * @dev This function pays the next debt based on the FIFO queue.
     */
    function _payNextDebt(uint amountToPay, uint[] memory tokenIds) internal {
        // Retrieve next debt
        uint nextDebtIndex = headIndex+1;
        Debt storage nextDebt = iotxDebts[nextDebtIndex];
        address account = nextDebt.account;

        // Withdraw NFT to this contract
        ISystemStaking(systemStaking).withdraw(tokenIds, payable(address(this)));
        accountedBalance += amountToPay;

        // Update debt states
        UserInfo storage userInfo = userInfos[account];
        userInfo.debt -= amountToPay;
        userInfo.principal += amountToPay;

        nextDebt.amount -= amountToPay;
        totalDebts -= amountToPay;

        // Remove debt entry if it has been fully paid
        if (nextDebt.amount == 0) {
            _dequeueDebt();
        }

        emit DebtPaid(account, amountToPay, nextDebtIndex);
    }

    /**
     * @dev This function updates the user's rewards according to their most recent debt
     */
    function _updateUserReward(address account) internal {
        _updateSharedReward();
        UserInfo storage info = userInfos[account];
        info.reward += (rewardRate - info.rewardRate) * info.debt / MULTIPLIER;
        info.rewardRate = rewardRate;
    }

    /**
     * @dev This function synchronizes this contract balance and updates the shared 'rewardRate'.
     */
    function _updateSharedReward() internal {
        if (address(this).balance > accountedBalance && totalDebts > 0) {
            uint incrReward = address(this).balance - accountedBalance;
            rewardRate += incrReward * MULTIPLIER / totalDebts;
            accountedBalance = address(this).balance;
        }
    }

    /**
     * @dev This function calculates the user's pending reward that has not yet been synchronized and accounted for.
     */
    function _calcPendingReward(address account) internal view returns (uint) {
        UserInfo memory info = userInfos[account];
        if (info.debt > 0 && address(this).balance > accountedBalance) {
            uint incrReward = address(this).balance - accountedBalance;
            uint _rewardRate = rewardRate + incrReward * MULTIPLIER / totalDebts;
            return (_rewardRate - info.rewardRate) * info.debt / MULTIPLIER;
        }
        return 0;
    }
}

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"claimer","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Claimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debtIndex","type":"uint256"}],"name":"DebtPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debtIndex","type":"uint256"}],"name":"DebtQueued","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"indexed":false,"internalType":"address","name":"delegate","type":"address"}],"name":"DelegatesUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"claimer","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"PrincipalClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"claimer","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"RewardClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accountedBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claimPrincipals","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claimRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"debtAmountBase","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAccountedBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDebtAmountBase","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPaidDebtItemCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getPrincipal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getReward","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalDebtItemCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalDebts","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"unpaidDebtIndex","type":"uint256"}],"name":"getUnpaidDebtItem","outputs":[{"components":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct IOTXClear.Debt","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUnpaidDebtItemCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUnpaidDebtItems","outputs":[{"components":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct IOTXClear.Debt[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getUserInfo","outputs":[{"components":[{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"principal","type":"uint256"},{"internalType":"uint256","name":"reward","type":"uint256"},{"internalType":"uint256","name":"rewardRate","type":"uint256"}],"internalType":"struct IOTXClear.UserInfo","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_systemStaking","type":"address"},{"internalType":"address","name":"_iotxStaking","type":"address"},{"internalType":"address","name":"_oracle","type":"address"},{"internalType":"address","name":"_pauser","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"joinDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"payDebts","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"systemStaking","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDebts","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"unstake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"address","name":"delegate","type":"address"}],"name":"updateDelegates","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

Contract Creation Code

6080604052600436106102295760003560e01c80637e1a378611610123578063c00007b0116100ab578063e449f3411161006f578063e449f341146106a8578063f3ec464e146106c8578063f8b2cb4f146106de578063f8c8765e146106fe578063ff50bf5e1461071e57600080fd5b8063c00007b014610613578063d2e349ae14610633578063d547741f14610648578063dc8e238b14610668578063ddd5e1b21461068857600080fd5b806391d14854116100f257806391d148541461054d57806397fe64171461056d5780639a78e72e1461058f578063a217fddf146105c6578063a5e35ef6146105db57600080fd5b80637e1a3786146104f85780638456cb591461050d5780638dc43dd3146105225780638ffe1db41461053757600080fd5b806336568abe116101b15780636386c1c7116101755780636386c1c7146104155780636c7b69cb146104685780637180f85b146104885780637abdd2d1146104a85780637b0a47ee146104e257600080fd5b806336568abe1461038657806336d0f761146103a65780633f4ba83a146103d3578063477562a7146103e85780635c975abb146103fd57600080fd5b80632328782f116101f85780632328782f146102e9578063248a9ca31461030b578063257f91331461033b5780632f2ff15d1461035157806333e5761f1461037157600080fd5b806301ffc9a7146102355780630937eb541461026a57806314a1c32d1461028e578063150b7a02146102a457600080fd5b3661023057005b600080fd5b34801561024157600080fd5b506102556102503660046122d3565b61073e565b60405190151581526020015b60405180910390f35b34801561027657600080fd5b5061028060fc5481565b604051908152602001610261565b34801561029a57600080fd5b5061028060fd5481565b3480156102b057600080fd5b506102d06102bf366004612312565b630a85bd0160e11b95945050505050565b6040516001600160e01b03199091168152602001610261565b3480156102f557600080fd5b506103096103043660046123fd565b610775565b005b34801561031757600080fd5b50610280610326366004612454565b60009081526097602052604090206001015490565b34801561034757600080fd5b5061028060ff5481565b34801561035d57600080fd5b5061030961036c36600461246d565b61083c565b34801561037d57600080fd5b5060fc54610280565b34801561039257600080fd5b506103096103a136600461246d565b610866565b3480156103b257600080fd5b506103c66103c1366004612454565b6108e9565b604051610261919061249d565b3480156103df57600080fd5b50610309610964565b3480156103f457600080fd5b5060fd54610280565b34801561040957600080fd5b5060335460ff16610255565b34801561042157600080fd5b506104356104303660046124bd565b610999565b60405161026191908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b34801561047457600080fd5b5061030961048336600461246d565b610a13565b34801561049457600080fd5b506103096104a33660046124da565b610b14565b3480156104b457600080fd5b506102806104c33660046124bd565b6001600160a01b03166000908152610103602052604090206001015490565b3480156104ee57600080fd5b5061028060fe5481565b34801561050457600080fd5b5060fe54610280565b34801561051957600080fd5b50610309610baf565b34801561052e57600080fd5b5060ff54610280565b34801561054357600080fd5b5061010254610280565b34801561055957600080fd5b5061025561056836600461246d565b610be1565b34801561057957600080fd5b50610582610c0c565b6040516102619190612506565b34801561059b57600080fd5b506102806105aa3660046124bd565b6001600160a01b03166000908152610103602052604090205490565b3480156105d257600080fd5b50610280600081565b3480156105e757600080fd5b5060fb546105fb906001600160a01b031681565b6040516001600160a01b039091168152602001610261565b34801561061f57600080fd5b5061028061062e3660046124bd565b610d74565b34801561063f57600080fd5b50610280610da6565b34801561065457600080fd5b5061030961066336600461246d565b610dbf565b34801561067457600080fd5b5061030961068336600461246d565b610de4565b34801561069457600080fd5b506103096106a336600461246d565b610ecd565b3480156106b457600080fd5b506103096106c3366004612566565b61100c565b3480156106d457600080fd5b5061010154610280565b3480156106ea57600080fd5b506102806106f93660046124bd565b61119a565b34801561070a57600080fd5b506103096107193660046125a8565b6111f1565b34801561072a57600080fd5b50610309610739366004612566565b611429565b60006001600160e01b03198216637965db0b60e01b148061076f57506301ffc9a760e01b6001600160e01b03198316145b92915050565b61077d6116d3565b60008051602061295c8339815191526107958161171b565b60fb54604051634c651dbb60e11b81526001600160a01b03909116906398ca3b76906107c99087908790879060040161263a565b600060405180830381600087803b1580156107e357600080fd5b505af11580156107f7573d6000803e3d6000fd5b505050507f055e970cad70d45557223e4ef35ac45bb162f8fc6f8a5986159f49d7d7fc742b84848460405161082e9392919061263a565b60405180910390a150505050565b6000828152609760205260409020600101546108578161171b565b6108618383611725565b505050565b6001600160a01b03811633146108db5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b6108e582826117ab565b5050565b604080518082019091526000808252602082015281610101541080156109125750610102548211155b1561094b575060009081526101006020908152604091829020825180840190935280546001600160a01b03168352600101549082015290565b5050604080518082019091526000808252602082015290565b7f372d55e37651a7c6e1940a3fb8628e4b6122a3c1a8b2b70aee13e0722860456761098e8161171b565b610996611812565b50565b6109c46040518060800160405280600081526020016000815260200160008152602001600081525090565b506001600160a01b031660009081526101036020908152604091829020825160808101845281548152600182015492810192909252600281015492820192909252600390910154606082015290565b610a1b611864565b610a236116d3565b610a2c336118be565b336000908152610103602052604090206002810154831115610a795760405162461bcd60e51b815260206004820152600660248201526555535230303560d01b60448201526064016108d2565b82816002016000828254610a8d919061267c565b925050819055508260fc6000828254610aa6919061267c565b90915550610abf90506001600160a01b03831684611935565b604080513381526001600160a01b03841660208201529081018490527f0aa4d283470c904c551d18bb894d37e17674920f3261a7f854be501e25f421b7906060015b60405180910390a1506108e5600160c955565b610b1c6116d3565b80600081118015610b37575060ff54610b3590826126a9565b155b610b6c5760405162461bcd60e51b815260206004820152600660248201526553595330303360d01b60448201526064016108d2565b7f6a20b7c24b5b16714658404c4ef3b1392074b6a92b5a12ceba6fb9d14a1190cd610b968161171b565b610b9f846118be565b610ba98484611a55565b50505050565b7f372d55e37651a7c6e1940a3fb8628e4b6122a3c1a8b2b70aee13e07228604567610bd98161171b565b610996611b48565b60009182526097602090815260408084206001600160a01b0393909316845291905290205460ff1690565b606061010254610101541015610d315760006101015461010254610c30919061267c565b905060008167ffffffffffffffff811115610c4d57610c4d6126bd565b604051908082528060200260200182016040528015610c9257816020015b6040805180820190915260008082526020820152815260200190600190039081610c6b5790505b5090506000610101546001610ca791906126d3565b905060005b83811015610d28576101006000610cc383856126d3565b81526020808201929092526040908101600020815180830190925280546001600160a01b0316825260010154918101919091528351849083908110610d0a57610d0a6126eb565b60200260200101819052508080610d2090612701565b915050610cac565b50909392505050565b6040805160008082526020820190925290610d6e565b6040805180820190915260008082526020820152815260200190600190039081610d475790505b50905090565b6000610d7f82611b85565b6001600160a01b0383166000908152610103602052604090206002015461076f91906126d3565b60006101015461010254610dba919061267c565b905090565b600082815260976020526040902060010154610dda8161171b565b61086183836117ab565b610dec611864565b610df46116d3565b336000908152610103602052604090206001810154831115610e415760405162461bcd60e51b81526020600482015260066024820152651554d48c0c0d60d21b60448201526064016108d2565b82816001016000828254610e55919061267c565b925050819055508260fc6000828254610e6e919061267c565b90915550610e8790506001600160a01b03831684611935565b604080513381526001600160a01b03841660208201529081018490527f7f8a3859c11803a8872da707dae770c23ab5b3eb3ea899d87a00b1c2bfa7749b90606001610b01565b610ed5611864565b610edd6116d3565b610ee6336118be565b33600090815261010360205260409020600281015460018201548491610f0b916126d3565b1015610f425760405162461bcd60e51b815260206004820152600660248201526555535230303960d01b60448201526064016108d2565b82816002015410610f6c5782816002016000828254610f61919061267c565b90915550610f9b9050565b6002810154610f7b908461267c565b816001016000828254610f8e919061267c565b9091555050600060028201555b8260fc6000828254610fad919061267c565b90915550610fc690506001600160a01b03831684611935565b604080513381526001600160a01b03841660208201529081018490527ff7a40077ff7a04c7e61f6f26fb13774259ddf1b6bce9ecf26a8276cdd399268390606001610b01565b6110146116d3565b818160005b8181101561110f5760fb546000906001600160a01b031663431cd92a858585818110611047576110476126eb565b905060200201356040518263ffffffff1660e01b815260040161106c91815260200190565b60a06040518083038186803b15801561108457600080fd5b505afa158015611098573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110bc919061271c565b50505050905060ff5481146110fc5760405162461bcd60e51b815260206004820152600660248201526555535230303760d01b60448201526064016108d2565b508061110781612701565b915050611019565b5060008051602061295c8339815191526111288161171b565b83156111935760fb5460405163e449f34160e01b81526001600160a01b039091169063e449f341906111609088908890600401612769565b600060405180830381600087803b15801561117a57600080fd5b505af115801561118e573d6000803e3d6000fd5b505050505b5050505050565b6001600160a01b038116600090815261010360205260408120600101546111c083611b85565b6001600160a01b038416600090815261010360205260409020600201546111e791906126d3565b61076f91906126d3565b600054610100900460ff16158080156112115750600054600160ff909116105b8061122b5750303b15801561122b575060005460ff166001145b61128e5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016108d2565b6000805460ff1916600117905580156112b1576000805461ff0019166101001790555b6112b9611c6a565b6112c1611c99565b6112c9611cc0565b6112d4600033611cef565b6112fe7f372d55e37651a7c6e1940a3fb8628e4b6122a3c1a8b2b70aee13e0722860456783611cef565b6113287f6a20b7c24b5b16714658404c4ef3b1392074b6a92b5a12ceba6fb9d14a1190cd85611cef565b61134060008051602061295c83398151915284611cef565b8460fb60006101000a8154816001600160a01b0302191690836001600160a01b03160217905550836001600160a01b03166337f523456040518163ffffffff1660e01b8152600401602060405180830381600087803b1580156113a257600080fd5b505af11580156113b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113da9190612785565b60ff558015611193576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15050505050565b6114316116d3565b818160005b8181101561152c5760fb546000906001600160a01b031663431cd92a858585818110611464576114646126eb565b905060200201356040518263ffffffff1660e01b815260040161148991815260200190565b60a06040518083038186803b1580156114a157600080fd5b505afa1580156114b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114d9919061271c565b50505050905060ff5481146115195760405162461bcd60e51b815260206004820152600660248201526555535230303760d01b60448201526064016108d2565b508061152481612701565b915050611436565b5060008051602061295c8339815191526115458161171b565b838015801590611563575060ff5461155d908261279e565b60fd5410155b6115985760405162461bcd60e51b81526020600482015260066024820152650aaa6a46060760d31b60448201526064016108d2565b60005b818110156116ca5760006115ad611cf9565b90506115bc81600001516118be565b60006115c8838561267c565b9050600060ff5483602001516115de91906127bd565b905060008282116115ef57816115f1565b825b905060008160ff54611603919061279e565b905060008267ffffffffffffffff811115611620576116206126bd565b604051908082528060200260200182016040528015611649578160200160208202803683370190505b50905060005b838110156116a8578d8d611663838b6126d3565b818110611672576116726126eb565b9050602002013582828151811061168b5761168b6126eb565b6020908102919091010152806116a081612701565b91505061164f565b506116b38282611d5a565b6116bd83886126d3565b965050505050505061159b565b50505050505050565b60335460ff16156117195760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b60448201526064016108d2565b565b6109968133611ee8565b61172f8282610be1565b6108e55760008281526097602090815260408083206001600160a01b03851684529091529020805460ff191660011790556117673390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6117b58282610be1565b156108e55760008281526097602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b61181a611f41565b6033805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b600260c95414156118b75760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016108d2565b600260c955565b6118c6611f8a565b6001600160a01b0381166000908152610103602052604090208054600382015460fe54670de0b6b3a764000092916118fd9161267c565b611907919061279e565b61191191906127bd565b81600201600082825461192491906126d3565b909155505060fe5460039091015550565b804710156119855760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e636500000060448201526064016108d2565b6000826001600160a01b03168260405160006040518083038185875af1925050503d80600081146119d2576040519150601f19603f3d011682016040523d82523d6000602084013e6119d7565b606091505b50509050806108615760405162461bcd60e51b815260206004820152603a60248201527f416464726573733a20756e61626c6520746f2073656e642076616c75652c207260448201527f6563697069656e74206d6179206861766520726576657274656400000000000060648201526084016108d2565b600160c955565b60016101026000828254611a6991906126d3565b90915550506040805180820182526001600160a01b0384811680835260208084018681526101025460009081526101008352868120955186546001600160a01b03191695169490941785555160019094019390935581526101039091529081208054839290611ad99084906126d3565b925050819055508060fd6000828254611af291906126d3565b909155505061010254604080516001600160a01b03851681526020810184905280820192909252517fb5de2a99082d929f0850ba77b6c1ff97cd4238074ff4be97da5ae22aa05642289181900360600190a15050565b611b506116d3565b6033805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586118473390565b6001600160a01b038116600090815261010360209081526040808320815160808101835281548082526001830154948201949094526002820154928101929092526003015460608201529015801590611bdf575060fc5447115b15611c6157600060fc5447611bf4919061267c565b9050600060fd54670de0b6b3a764000083611c0f919061279e565b611c1991906127bd565b60fe54611c2691906126d3565b83516060850151919250670de0b6b3a764000091611c44908461267c565b611c4e919061279e565b611c5891906127bd565b95945050505050565b50600092915050565b600054610100900460ff16611c915760405162461bcd60e51b81526004016108d2906127d1565b611719611ff1565b600054610100900460ff166117195760405162461bcd60e51b81526004016108d2906127d1565b600054610100900460ff16611ce75760405162461bcd60e51b81526004016108d2906127d1565b611719612024565b6108e58282611725565b60408051808201909152600080825260208201526101006000610101546001611d2291906126d3565b81526020808201929092526040908101600020815180830190925280546001600160a01b031682526001015491810191909152919050565b6000610101546001611d6c91906126d3565b6000818152610100602052604090819020805460fb54925163b8f4bd7b60e01b815293945090926001600160a01b03918216929091169063b8f4bd7b90611db9908790309060040161281c565b600060405180830381600087803b158015611dd357600080fd5b505af1158015611de7573d6000803e3d6000fd5b505050508460fc6000828254611dfd91906126d3565b90915550506001600160a01b038116600090815261010360205260408120805490918791839190611e2f90849061267c565b9250508190555085816001016000828254611e4a91906126d3565b9250508190555085836001016000828254611e65919061267c565b925050819055508560fd6000828254611e7e919061267c565b90915550506001830154611e9657611e9461204b565b505b604080516001600160a01b0384168152602081018890529081018590527fc167477d6269a6698dabd8aabaff469b2fc5301c9ba41f9d187eeeb30e12488e9060600160405180910390a1505050505050565b611ef28282610be1565b6108e557611eff8161211e565b611f0a836020612130565b604051602001611f1b92919061289c565b60408051601f198184030181529082905262461bcd60e51b82526108d291600401612911565b60335460ff166117195760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b60448201526064016108d2565b60fc5447118015611f9d5750600060fd54115b1561171957600060fc5447611fb2919061267c565b60fd54909150611fca670de0b6b3a76400008361279e565b611fd491906127bd565b60fe6000828254611fe591906126d3565b90915550504760fc5550565b600054610100900460ff166120185760405162461bcd60e51b81526004016108d2906127d1565b6033805460ff19169055565b600054610100900460ff16611a4e5760405162461bcd60e51b81526004016108d2906127d1565b60408051808201909152600080825260208201526101015461010254141561209e5760405162461bcd60e51b815260206004820152600660248201526514d654cc0c0d60d21b60448201526064016108d2565b60006101015460016120b091906126d3565b600081815261010060208181526040808420815180830190925280546001600160a01b03811683526001808301805485870152888852959094526001600160a01b03191690559183905561010180549296509394509291906121139084906126d3565b925050819055505090565b606061076f6001600160a01b03831660145b6060600061213f83600261279e565b61214a9060026126d3565b67ffffffffffffffff811115612162576121626126bd565b6040519080825280601f01601f19166020018201604052801561218c576020820181803683370190505b509050600360fc1b816000815181106121a7576121a76126eb565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106121d6576121d66126eb565b60200101906001600160f81b031916908160001a90535060006121fa84600261279e565b6122059060016126d3565b90505b600181111561227d576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110612239576122396126eb565b1a60f81b82828151811061224f5761224f6126eb565b60200101906001600160f81b031916908160001a90535060049490941c9361227681612944565b9050612208565b5083156122cc5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016108d2565b9392505050565b6000602082840312156122e557600080fd5b81356001600160e01b0319811681146122cc57600080fd5b6001600160a01b038116811461099657600080fd5b60008060008060006080868803121561232a57600080fd5b8535612335816122fd565b94506020860135612345816122fd565b935060408601359250606086013567ffffffffffffffff8082111561236957600080fd5b818801915088601f83011261237d57600080fd5b81358181111561238c57600080fd5b89602082850101111561239e57600080fd5b9699959850939650602001949392505050565b60008083601f8401126123c357600080fd5b50813567ffffffffffffffff8111156123db57600080fd5b6020830191508360208260051b85010111156123f657600080fd5b9250929050565b60008060006040848603121561241257600080fd5b833567ffffffffffffffff81111561242957600080fd5b612435868287016123b1565b9094509250506020840135612449816122fd565b809150509250925092565b60006020828403121561246657600080fd5b5035919050565b6000806040838503121561248057600080fd5b823591506020830135612492816122fd565b809150509250929050565b81516001600160a01b03168152602080830151908201526040810161076f565b6000602082840312156124cf57600080fd5b81356122cc816122fd565b600080604083850312156124ed57600080fd5b82356124f8816122fd565b946020939093013593505050565b602080825282518282018190526000919060409081850190868401855b828110156125595761254984835180516001600160a01b03168252602090810151910152565b9284019290850190600101612523565b5091979650505050505050565b6000806020838503121561257957600080fd5b823567ffffffffffffffff81111561259057600080fd5b61259c858286016123b1565b90969095509350505050565b600080600080608085870312156125be57600080fd5b84356125c9816122fd565b935060208501356125d9816122fd565b925060408501356125e9816122fd565b915060608501356125f9816122fd565b939692955090935050565b81835260006001600160fb1b0383111561261d57600080fd5b8260051b8083602087013760009401602001938452509192915050565b60408152600061264e604083018587612604565b905060018060a01b0383166020830152949350505050565b634e487b7160e01b600052601160045260246000fd5b60008282101561268e5761268e612666565b500390565b634e487b7160e01b600052601260045260246000fd5b6000826126b8576126b8612693565b500690565b634e487b7160e01b600052604160045260246000fd5b600082198211156126e6576126e6612666565b500190565b634e487b7160e01b600052603260045260246000fd5b600060001982141561271557612715612666565b5060010190565b600080600080600060a0868803121561273457600080fd5b85519450602086015193506040860151925060608601519150608086015161275b816122fd565b809150509295509295909350565b60208152600061277d602083018486612604565b949350505050565b60006020828403121561279757600080fd5b5051919050565b60008160001904831182151516156127b8576127b8612666565b500290565b6000826127cc576127cc612693565b500490565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b604080825283519082018190526000906020906060840190828701845b8281101561285557815184529284019290840190600101612839565b5050506001600160a01b039490941692019190915250919050565b60005b8381101561288b578181015183820152602001612873565b83811115610ba95750506000910152565b7f416363657373436f6e74726f6c3a206163636f756e74200000000000000000008152600083516128d4816017850160208801612870565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351612905816028840160208801612870565b01602801949350505050565b6020815260008251806020840152612930816040850160208701612870565b601f01601f19169190910160400192915050565b60008161295357612953612666565b50600019019056fe66098348ac86aa2c1efef4ea51eb3a0dd075bfeef7e5784ec740dc5b4ee760fda26469706673582212201a4b095c21e98c3d6769ac6c646bd8925e0a2df0441e6f24d4e4ee6034b8571364736f6c63430008090033

Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.