// File: address.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: arrays.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
   /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * `array` is expected to be sorted in ascending order, and to contain no
     * repeated elements.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        if (array.length == 0) {
            return 0;
        }

        uint256 low = 0;
        uint256 high = array.length;

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds down (it does integer division with truncation).
            if (array[mid] > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && array[low - 1] == element) {
            return low - 1;
        } else {
            return low;
        }
    }
}

// File: context.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: counters.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

// File: erc1363.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./erc20snapshot.sol";
import "./address.sol";
import "./ierc165.sol";
import "./erc165.sol";
import "./ierc1363.sol";
import "./ierc1363receiver.sol";
import "./ierc1363spender.sol";

/**
 * @title ERC1363
 * @author Vittorio Minacori (https://github.com/vittominacori) (with trivial mods by loma oopaloopa)
 * @dev Implementation of an ERC1363 interface
 */
abstract contract ERC1363 is ERC20Snapshot, IERC1363, ERC165 {
    using Address for address;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC1363).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Transfer tokens to a specified address and then execute a callback on recipient.
     * @param recipient The address to transfer to.
     * @param amount The amount to be transferred.
     * @return A boolean that indicates if the operation was successful.
     */
    function transferAndCall(address recipient, uint256 amount) public virtual override returns (bool) {
        return transferAndCall(recipient, amount, "");
    }

    /**
     * @dev Transfer tokens to a specified address and then execute a callback on recipient.
     * @param recipient The address to transfer to
     * @param amount The amount to be transferred
     * @param data Additional data with no specified format
     * @return A boolean that indicates if the operation was successful.
     */
    function transferAndCall(
        address recipient,
        uint256 amount,
        bytes memory data
    ) public virtual override returns (bool) {
        transfer(recipient, amount);
        require(_checkAndCallTransfer(_msgSender(), recipient, amount, data), "ERC1363: _checkAndCallTransfer reverts");
        return true;
    }

    /**
     * @dev Transfer tokens from one address to another and then execute a callback on recipient.
     * @param sender The address which you want to send tokens from
     * @param recipient The address which you want to transfer to
     * @param amount The amount of tokens to be transferred
     * @return A boolean that indicates if the operation was successful.
     */
    function transferFromAndCall(
        address sender,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        return transferFromAndCall(sender, recipient, amount, "");
    }

    /**
     * @dev Transfer tokens from one address to another and then execute a callback on recipient.
     * @param sender The address which you want to send tokens from
     * @param recipient The address which you want to transfer to
     * @param amount The amount of tokens to be transferred
     * @param data Additional data with no specified format
     * @return A boolean that indicates if the operation was successful.
     */
    function transferFromAndCall(
        address sender,
        address recipient,
        uint256 amount,
        bytes memory data
    ) public virtual override returns (bool) {
        transferFrom(sender, recipient, amount);
        require(_checkAndCallTransfer(sender, recipient, amount, data), "ERC1363: _checkAndCallTransfer reverts");
        return true;
    }

    /**
     * @dev Approve spender to transfer tokens and then execute a callback on recipient.
     * @param spender The address allowed to transfer to
     * @param amount The amount allowed to be transferred
     * @return A boolean that indicates if the operation was successful.
     */
    function approveAndCall(address spender, uint256 amount) public virtual override returns (bool) {
        return approveAndCall(spender, amount, "");
    }

    /**
     * @dev Approve spender to transfer tokens and then execute a callback on recipient.
     * @param spender The address allowed to transfer to.
     * @param amount The amount allowed to be transferred.
     * @param data Additional data with no specified format.
     * @return A boolean that indicates if the operation was successful.
     */
    function approveAndCall(
        address spender,
        uint256 amount,
        bytes memory data
    ) public virtual override returns (bool) {
        approve(spender, amount);
        require(_checkAndCallApprove(spender, amount, data), "ERC1363: _checkAndCallApprove reverts");
        return true;
    }

    /**
     * @dev Internal function to invoke `onTransferReceived` on a target address
     *  The call is not executed if the target address is not a contract
     * @param sender address Representing the previous owner of the given token value
     * @param recipient address Target address that will receive the tokens
     * @param amount uint256 The amount mount of tokens to be transferred
     * @param data bytes Optional data to send along with the call
     * @return whether the call correctly returned the expected magic value
     */
    function _checkAndCallTransfer(
        address sender,
        address recipient,
        uint256 amount,
        bytes memory data
    ) internal virtual returns (bool) {
        if (!recipient.isContract()) {
            return false;
        }
        bytes4 retval = IERC1363Receiver(recipient).onTransferReceived(_msgSender(), sender, amount, data);
        return (retval == IERC1363Receiver(recipient).onTransferReceived.selector);
    }

    /**
     * @dev Internal function to invoke `onApprovalReceived` on a target address
     *  The call is not executed if the target address is not a contract
     * @param spender address The address which will spend the funds
     * @param amount uint256 The amount of tokens to be spent
     * @param data bytes Optional data to send along with the call
     * @return whether the call correctly returned the expected magic value
     */
    function _checkAndCallApprove(
        address spender,
        uint256 amount,
        bytes memory data
    ) internal virtual returns (bool) {
        if (!spender.isContract()) {
            return false;
        }
        bytes4 retval = IERC1363Spender(spender).onApprovalReceived(_msgSender(), amount, data);
        return (retval == IERC1363Spender(spender).onApprovalReceived.selector);
    }
}

// File: erc165.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./ierc165.sol";

/**
 * @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 ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: erc20.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./ierc20.sol";
import "./ierc20metadata.sol";
import "./context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - amount);
        }

        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}

// File: erc20snapshot.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./erc20.sol";
import "./arrays.sol";
import "./counters.sol";

/**
 * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
 * total supply at the time are recorded for later access.
 *
 * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
 * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
 * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
 * used to create an efficient ERC20 forking mechanism.
 *
 * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
 * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
 * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
 * and the account address.
 *
 * NOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having it
 * return `block.number` will trigger the creation of snapshot at the begining of each new block. When overridding this
 * function, be careful about the monotonicity of its result. Non-monotonic snapshot ids will break the contract.
 *
 * Implementing snapshots for every block using this method will incur significant gas costs. For a gas-efficient
 * alternative consider {ERC20Votes}.
 *
 * ==== Gas Costs
 *
 * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
 * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
 * smaller since identical balances in subsequent snapshots are stored as a single entry.
 *
 * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
 * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
 * transfers will have normal cost until the next snapshot, and so on.
 */

abstract contract ERC20Snapshot is ERC20 {
    // Inspired by Jordi Baylina's MiniMeToken to record historical balances:
    // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol

    using Arrays for uint256[];
    using Counters for Counters.Counter;

    // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
    // Snapshot struct, but that would impede usage of functions that work on an array.
    struct Snapshots {
        uint256[] ids;
        uint256[] values;
    }

    mapping (address => Snapshots) private _accountBalanceSnapshots;
    Snapshots private _totalSupplySnapshots;

    // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
    Counters.Counter private _currentSnapshotId;

    /**
     * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
     */
    event Snapshot(uint256 id);

    /**
     * @dev Creates a new snapshot and returns its snapshot id.
     *
     * Emits a {Snapshot} event that contains the same id.
     *
     * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
     * set of accounts, for example using {AccessControl}, or it may be open to the public.
     *
     * [WARNING]
     * ====
     * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
     * you must consider that it can potentially be used by attackers in two ways.
     *
     * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
     * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
     * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
     * section above.
     *
     * We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
     * ====
     */
    function _snapshot() internal virtual returns (uint256) {
        _currentSnapshotId.increment();

        uint256 currentId = _getCurrentSnapshotId();
        emit Snapshot(currentId);
        return currentId;
    }

    /**
     * @dev Get the current snapshotId
     */
    function _getCurrentSnapshotId() internal view virtual returns (uint256) {
        return _currentSnapshotId.current();
    }

    /**
     * @dev Retrieves the balance of `account` at the time `snapshotId` was created.
     */
    function balanceOfAt(address account, uint256 snapshotId) public view virtual returns (uint256) {
        (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);

        return snapshotted ? value : balanceOf(account);
    }

    /**
     * @dev Retrieves the total supply at the time `snapshotId` was created.
     */
    function totalSupplyAt(uint256 snapshotId) public view virtual returns(uint256) {
        (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);

        return snapshotted ? value : totalSupply();
    }

    // Update balance and/or total supply snapshots before the values are modified. This is implemented
    // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations.
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
      super._beforeTokenTransfer(from, to, amount);

      if (from == address(0)) {
        // mint
        _updateAccountSnapshot(to);
        _updateTotalSupplySnapshot();
      } else if (to == address(0)) {
        // burn
        _updateAccountSnapshot(from);
        _updateTotalSupplySnapshot();
      } else {
        // transfer
        _updateAccountSnapshot(from);
        _updateAccountSnapshot(to);
      }
    }

    function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
        private view returns (bool, uint256)
    {
        require(snapshotId > 0, "ERC20Snapshot: id is 0");
        require(snapshotId <= _getCurrentSnapshotId(), "ERC20Snapshot: nonexistent id");

        // When a valid snapshot is queried, there are three possibilities:
        //  a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
        //  created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
        //  to this id is the current one.
        //  b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
        //  requested id, and its value is the one to return.
        //  c) More snapshots were created after the requested one, and the queried value was later modified. There will be
        //  no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
        //  larger than the requested one.
        //
        // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
        // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
        // exactly this.

        uint256 index = snapshots.ids.findUpperBound(snapshotId);

        if (index == snapshots.ids.length) {
            return (false, 0);
        } else {
            return (true, snapshots.values[index]);
        }
    }

    function _updateAccountSnapshot(address account) private {
        _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
    }

    function _updateTotalSupplySnapshot() private {
        _updateSnapshot(_totalSupplySnapshots, totalSupply());
    }

    function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
        uint256 currentId = _getCurrentSnapshotId();
        if (_lastSnapshotId(snapshots.ids) < currentId) {
            snapshots.ids.push(currentId);
            snapshots.values.push(currentValue);
        }
    }

    function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
        if (ids.length == 0) {
            return 0;
        } else {
            return ids[ids.length - 1];
        }
    }
}

// File: ierc1363.sol



// SPDX-License-Identifier: CC0-1.0

pragma solidity 0.8.6;

interface IERC1363 {  /* is ERC20, ERC165 */
  /*
   * Note: the ERC-165 identifier for this interface is 0xb0202a11.
   * 0xb0202a11 ===
   *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
   *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
   *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
   *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
   *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
   *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
   */

  /**
   * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
   * @param to address The address which you want to transfer to
   * @param value uint256 The amount of tokens to be transferred
   * @return true unless throwing
   */
  function transferAndCall(address to, uint256 value) external returns (bool);

  /**
   * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver
   * @param to address The address which you want to transfer to
   * @param value uint256 The amount of tokens to be transferred
   * @param data bytes Additional data with no specified format, sent in call to `to`
   * @return true unless throwing
   */
  function transferAndCall(address to, uint256 value, bytes memory data) external returns (bool);

  /**
   * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
   * @param from address The address which you want to send tokens from
   * @param to address The address which you want to transfer to
   * @param value uint256 The amount of tokens to be transferred
   * @return true unless throwing
   */
  function transferFromAndCall(address from, address to, uint256 value) external returns (bool);


  /**
   * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver
   * @param from address The address which you want to send tokens from
   * @param to address The address which you want to transfer to
   * @param value uint256 The amount of tokens to be transferred
   * @param data bytes Additional data with no specified format, sent in call to `to`
   * @return true unless throwing
   */
  function transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool);

  /**
   * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
   * and then call `onApprovalReceived` on spender.
   * @param spender address The address which will spend the funds
   * @param value uint256 The amount of tokens to be spent
   */
  function approveAndCall(address spender, uint256 value) external returns (bool);

  /**
   * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
   * and then call `onApprovalReceived` on spender.
   * @param spender address The address which will spend the funds
   * @param value uint256 The amount of tokens to be spent
   * @param data bytes Additional data with no specified format, sent in call to `spender`
   */
  function approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool);
}
// File: ierc1363receiver.sol



// SPDX-License-Identifier: CC0-1.0

pragma solidity 0.8.6;

/**
 * @title IERC1363Receiver interface
 * @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall`
 *  from ERC1363 token contracts.
 */
interface IERC1363Receiver {
  /*
   * Note: the ERC-165 identifier for this interface is 0x88a7ca5c.
   * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))
   */

  /**
   * @notice Handle the receipt of ERC1363 tokens
   * @dev Any ERC1363 smart contract calls this function on the recipient
   * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the
   * transfer. Return of other than the magic value MUST result in the
   * transaction being reverted.
   * Note: the token contract address is always the message sender.
   * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function
   * @param from address The address which are token transferred from
   * @param value uint256 The amount of tokens transferred
   * @param data bytes Additional data with no specified format
   * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))`
   *  unless throwing
   */
  function onTransferReceived(address operator, address from, uint256 value, bytes memory data) external returns (bytes4);
}
// File: ierc1363spender.sol



// SPDX-License-Identifier: CC0-1.0

pragma solidity 0.8.6;

/**
 * @title IERC1363Spender interface
 * @dev Interface for any contract that wants to support `approveAndCall`
 *  from ERC1363 token contracts.
 */
interface IERC1363Spender {
  /*
   * Note: the ERC-165 identifier for this interface is 0x7b04a2d0.
   * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))
   */

  /**
   * @notice Handle the approval of ERC1363 tokens
   * @dev Any ERC1363 smart contract calls this function on the recipient
   * after an `approve`. This function MAY throw to revert and reject the
   * approval. Return of other than the magic value MUST result in the
   * transaction being reverted.
   * Note: the token contract address is always the message sender.
   * @param owner address The address which called `approveAndCall` function
   * @param value uint256 The amount of tokens to be spent
   * @param data bytes Additional data with no specified format
   * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))`
   *  unless throwing
   */
  function onApprovalReceived(address owner, uint256 value, bytes memory data) external returns (bytes4);
}
// File: ierc165.sol



// SPDX-License-Identifier: CC0-1.0

pragma solidity 0.8.6;

interface IERC165 {
    /// @notice Query if a contract implements an interface
    /// @param interfaceID The interface identifier, as specified in ERC-165
    /// @dev Interface identification is specified in ERC-165. This function
    ///  uses less than 30,000 gas.
    /// @return `true` if the contract implements `interfaceID` and
    ///  `interfaceID` is not 0xffffffff, `false` otherwise
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// File: ierc20.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: ierc20metadata.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./ierc20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: imigratablevendorregistry.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

/// A collection of all methods on a previous VendorRegistry called by the new version of WrappedAsset during migration.
/// The migration process does not use any VendorRegistry methods on the previous version that are not in this interface.
interface IMigratableVendorRegistry
    {
    /// Look up the MRX addrees for a given (ethereum or BSC) vendor address.
    /// @param  vendorAddress The vendor address address for which to look up the MRX address.
    /// @return The MRX address, or address(0) if the vendor address is not registered.
    function findMrxFromVendor(address vendorAddress) external view returns (address);
    }

// File: imigratablewrappedasset.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

/// A collection of all methods on a previous WrappedAsset called by the new version of WrappedAsset during migration.
/// The migration process does not use any WrappedAsset methods on the previous version that are not in this interface.
interface IMigratableWrappedAsset
    {
    /// Only called by the next version of WrappedAsset during migration, this method deducts a maximum amount or its total value (whichever is less) from the given account.
    /// @param   account   The account from which to remove the wrapped MRX.
    /// @param   maxAmount The maximum amount to deduct in satoshi.
    /// @return The amount of MRX actually removed.
    function migrationBurn(address account, uint256 maxAmount) external returns (uint256);
    }

// File: iownable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

interface IOwnable
    {
    function getOwner() external view returns (address);
    modifier isOwner() virtual;
    }

// File: managable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./ownable.sol";

/**
 * @title Managable
 * @dev Set & change managers permission
 */
contract Managable is Ownable {
    mapping(address => bool) private managers;

    // event for EVM logging
    event ManagersChanged(address indexed manager, bool allowed);

    // modifier to check if caller is manager
    modifier isManager() {
        // If the first argument of 'require' evaluates to 'false', execution terminates and all
        // changes to the state and to Ether balances are reverted.
        // This used to consume all gas in old EVM versions, but not anymore.
        // It is often a good idea to use 'require' to check if functions are called correctly.
        // As a second argument, you can also provide an explanation about what went wrong.
        require(
            managers[msg.sender] == true || this.getOwner() == msg.sender,
            "Caller is not manager"
        );
        _;
    }

    /**
     * @dev Change manager
     * @param manager address of manager
     */
    function setManager(address manager, bool allowed) public isOwner {
        managers[manager] = allowed;
        emit ManagersChanged(manager, allowed);
    }

    function addressIsAManager(address addr) public view returns (bool) {
        return managers[addr] == true || this.getOwner() == addr;
    }
}

// File: math.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @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, so we distribute.
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 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 / b + (a % b == 0 ? 0 : 1);
    }
}

// File: ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./iownable.sol";

/**
 * @title Owner
 * @dev Set & change owner
 */
contract Ownable is IOwnable {
    address private owner;

    // event for EVM logging
    event OwnerSet(address indexed oldOwner, address indexed newOwner);

    // modifier to check if caller is owner
    modifier isOwner() override {
        // If the first argument of 'require' evaluates to 'false', execution terminates and all
        // changes to the state and to Ether balances are reverted.
        // This used to consume all gas in old EVM versions, but not anymore.
        // It is often a good idea to use 'require' to check if functions are called correctly.
        // As a second argument, you can also provide an explanation about what went wrong.
        require(msg.sender == owner, "Caller is not owner");
        _;
    }

    /**
     * @dev Set contract deployer as owner
     */
    constructor() {
        owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
        emit OwnerSet(address(0), owner);
    }

    /**
     * @dev Change owner
     * @param newOwner address of new owner
     */
    function changeOwner(address newOwner) public isOwner {
        emit OwnerSet(owner, newOwner);
        owner = newOwner;
    }

    /**
     * @dev Return owner address
     * @return address of owner
     */
    function getOwner() override public view returns (address) {
        return owner;
    }
}

// File: pausable.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./context.sol";

/**
 * @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 Pausable is Context {
    /**
     * @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.
     */
    constructor () {
        _paused = false;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        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());
    }
}

// File: test_receiver.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./ierc1363receiver.sol";

contract Test_Receiver is IERC1363Receiver
    {
    address public           lastOperatorSeen              = address(0);
    address public           lastFromSeen                  = address(0);
    uint256 public           lastValueSeen                 = 0;
    bytes   public           lastDataSeen                  = bytes.concat();
    bytes4  private constant INTERFACE_ID_ERC1363_RECEIVER = 0x88a7ca5c;

    function onTransferReceived(address operator, address from, uint256 value, bytes memory data) external override returns (bytes4)
        {
        lastOperatorSeen = operator;
        lastFromSeen = from;
        lastValueSeen = value;
        lastDataSeen = data;
        return INTERFACE_ID_ERC1363_RECEIVER;
        }
    }

// File: test_spender.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./ierc1363spender.sol";

contract Test_Spender is IERC1363Spender
    {
    address public           lastOwnerSeen                = address(0);
    uint256 public           lastValueSeen                = 0;
    bytes   public           lastDataSeen                 = bytes.concat();
    bytes4  private constant INTERFACE_ID_ERC1363_SPENDER = 0x7b04a2d0;

    function onApprovalReceived(address owner, uint256 value, bytes memory data) external override returns (bytes4)
        {
        lastOwnerSeen = owner;
        lastValueSeen = value;
        lastDataSeen = data;
        return INTERFACE_ID_ERC1363_SPENDER;
        }
    }

// File: vendorregistry.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./pausable.sol";
import "./managable.sol";
import "./wrappedasset.sol";
import "./imigratablevendorregistry.sol";



/// Maintains a registry of Ethereum/BSC adrresses of vendors allowed to wrap MRX, & their associated MRX withdrawal addresses.
/// @title  VendorRegistry
/// @dev    Uses solidity mappings to maintain a bi-directional 1-to-1 mapping between ethereum or BSC addresses and MRX addresses.
/// @author loma oopaloopa
contract VendorRegistry is Pausable, Managable, IMigratableVendorRegistry
    {
    address                     private wrappedAssetAddr;
    WrappedAsset                private wrappedAsset;
    mapping(address => address) private vendor2mrx;
    mapping(address => address) private mrx2vendor;

    /// Emitted when a registration is created or updated.
    /// @param mrxAddress    The registration's MRX address.
    /// @param vendorAddress The registration's (ethereum or BSC) vendor address.
    event Registered(address mrxAddress, address vendorAddress);

    /// Emitted when a registration's MRX address is cahnged by setVendorRegistration().
    /// @param mrxAddress    The registration's old MRX address from before the change.
    /// @param vendorAddress The registration's (ethereum or BSC) vendor address.
    event Unregistered(address mrxAddress, address vendorAddress);

    /// Deploy a VendorRegistry and WrappedAssest pair, the parameters are apssed unchanged to the WrappedAsstes's constructor.
    constructor(string memory tokenName, string memory tokenSymbol, uint256 tokenCap, uint256 tokenSnapshotIntervalHours)
        {
        wrappedAsset = new WrappedAsset(tokenName, tokenSymbol, tokenCap, tokenSnapshotIntervalHours);
        wrappedAssetAddr = address(wrappedAsset);
        wrappedAsset.setVendorRegistry(address(this));
        wrappedAsset.changeOwner(getOwner());
        }

    /// An owner only method to change the WrappedAsset this VendorRegistry is associated with, use WrappedAsset.setVendorRegistry() to make the required reciprical change on WrappedAsset.
    /// @param WrappedAssetAddress The address of the new WrappedAsset contract to pair with.
    function setWrappedAsset(address WrappedAssetAddress) public isOwner
        {
        wrappedAssetAddr = WrappedAssetAddress;
        wrappedAsset = WrappedAsset(WrappedAssetAddress);
        }

    /// Look up the (ethereum or BSC) vendor address associated with a given MRX address.
    /// @param  mrxAddress The MRX address for which to look up the vendor address.
    /// @return The vendor address, or address(0) if the MRX address is not registered.
    function findVendorFromMrx(address mrxAddress) public view returns (address)
        {
        return mrx2vendor[mrxAddress];
        }

    /// Look up the MRX addrees for a given (ethereum or BSC) vendor address.
    /// @param  vendorAddress The vendor address address for which to look up the MRX address.
    /// @return The MRX address, or address(0) if the vendor address is not registered.
    function findMrxFromVendor(address vendorAddress) public override view returns (address)
        {
        return vendor2mrx[vendorAddress];
        }

    /// Check whether or not a given MRX address is registered.
    /// @param  mrxAddress The MRX address for which to find the registration status.
    /// @return True if the MRX address is registered and false if it's not.
    function isRegistered(address mrxAddress) public view returns (bool)
        {
        return mrx2vendor[mrxAddress] != address(0);
        }

    /// Get the address of the associated WrappedAsset contract.
    /// @return The address of the associated WrappedAsset contract.
    function getWrappedAsset() public view returns (address)
        {
        return wrappedAssetAddr;
        }

    /// A pausable method to register the caller's (ethereum or BSC) address as a vendor, with the given MRX address. This is the method members of the public use to register.
    /// @param mrxAddress The MRX address to register.
    /// @param signature  A manager of this contract's signature on a premission to register message.
    function registerAsVendor(address mrxAddress, bytes memory signature) public whenNotPaused
        {
        require(mrxAddress != address(0), "VendorRegistry: Registration failed, the MRX address can not be zero.");
        require(mrx2vendor[mrxAddress] == address(0) && vendor2mrx[msg.sender] == address(0), "VendorRegistry: Registration failed, 1 or more addresses have already been registered.");
        bytes memory message = abi.encodePacked(msg.sender, address(this), mrxAddress);
        require(addressIsAManager(recoverSigner(message, signature)), "VendorRegistry: Registration failed, invalid signature.");
        mrx2vendor[mrxAddress] = msg.sender;
        vendor2mrx[msg.sender] = mrxAddress;
        emit Registered(mrxAddress, msg.sender);
        }

    /// A management only method to create a vendor registration, or to update the MRX address for an existing vendor registration.
    /// @param mrxAddress    The new MRX address for the vendor.
    /// @param vendorAddress The vendor's (ethereum or BSC) address.
    function setVendorRegistration(address mrxAddress, address vendorAddress) public isManager
        {
        require(mrxAddress != address(0) && vendorAddress != address(0), "VendorRegistry: Registration failed, the zero address can not be registered.");
        bool registrationHappened = false;
        address existingMrxAddress = vendor2mrx[vendorAddress];
        if (existingMrxAddress != mrxAddress)
            {
            if (existingMrxAddress != address(0))
                {
                emit Unregistered(existingMrxAddress, mrx2vendor[existingMrxAddress]);
                mrx2vendor[existingMrxAddress] = address(0);
                }
            registrationHappened = true;
            vendor2mrx[vendorAddress] = mrxAddress;
            }
        address existingVendorAddress = mrx2vendor[mrxAddress];
        if (existingVendorAddress != vendorAddress)
            {
            require(existingVendorAddress == address(0), "VendorRegistry: Registration failed, the MRX address has already been registered by a different vendor.");
            registrationHappened = true;
            mrx2vendor[mrxAddress] = vendorAddress;
            }
        if (registrationHappened) emit Registered(mrxAddress, vendorAddress);
        }

    /// Only ever called by WrappedAsset.migrateFromPreviousVersion(), this method checks if the vendor address is already registerd, and if not registers it with the given MRX address.
    /// @param mrxAddress    The new MRX address for the vendor (to be used only if the vendor address is not already registered).
    /// @param vendorAddress The vendor's (ethereum or BSC) address.
    function migrateVendorRegistration(address mrxAddress, address vendorAddress) external
        {
        require(msg.sender == wrappedAssetAddr, "VendorRegistry: Access not permitted.");
        require(mrxAddress != address(0) && vendorAddress != address(0), "VendorRegistry: Registration failed, the zero address can not be registered.");
        if (vendor2mrx[vendorAddress] == address(0))
            {
            require(mrx2vendor[mrxAddress] == address(0), "VendorRegistry: Registration failed, the MRX address has already been registered.");
            vendor2mrx[vendorAddress] = mrxAddress;
            mrx2vendor[mrxAddress] = vendorAddress;
            emit Registered(mrxAddress, vendorAddress);
            }
        }

    /// A management only method to pause the public's ability to register, however the (management only) setVendorRegistration() function will continue to work.
    function pause() public isManager
        {
        _pause();
        }

    /// A management only method to restart the public's ability to register.
    function unpause() public isManager
        {
        _unpause();
        }

    function recoverSigner(bytes memory message, bytes memory signature) internal pure returns (address)
        {
        require(signature.length == 65, "VendorRegistry: Action failed due to an invalid signature.");
        uint8 v;
        bytes32 r;
        bytes32 s;
        assembly
            {
            r := mload(add(signature, 32))
            s := mload(add(signature, 64))
            v := byte(0, mload(add(signature, 96)))
            }
        return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))), v, r, s);
        }
    }

// File: wrappedasset.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.6;

import "./erc1363.sol";
import "./pausable.sol";
import "./managable.sol";
import "./vendorregistry.sol";
import "./imigratablewrappedasset.sol";
import "./imigratablevendorregistry.sol";



/// An ERC1363 (also ERC20) for wrapping MRX on the ethereum or BSC chain.
/// @title  WrappedAsset
/// @author loma oopaloopa
contract WrappedAsset is ERC1363, Pausable, Managable, IMigratableWrappedAsset
    {
    address                  public  prevVendorRegistry      = address(0);
    address                  public  prevWrappedAsset        = address(0);
    address                  public  nextWrappedAsset        = address(0);

    uint256 immutable        private maxSupply;
    uint256                  private snapshotIntervalSeconds;
    uint256                  private snapshotId              = 0;
    uint256                  private snapshotBlockTimestamp  = 0;
    mapping(bytes32 => bool) private usedNonces;
    address                  private registryAddr            = address(0);
    VendorRegistry           private registry;

    /// Emitted whenever a new snapshot is stored.
    /// @param blockTimestamp The timestamp of the first block after the snapshot.
    /// @param blockNumber    The block number of the first block after the snapshot.
    /// @param snapshotId     The new current snapshot ID after the snapshot.
    event SnapshotInfo(uint256 indexed blockTimestamp, uint256 indexed blockNumber, uint256 indexed snapshotId);

    /// Deploy a new WrappedAsset contract, never called directly -- only from VendorRegistry's constructor.
    /// @param tokenName                  The name for the token (returned by name()).
    /// @param tokenSymbol                The symbol for the token (returned by symbol()).
    /// @param tokenCap                   The cap or maximum amount of tokens allowed in satoshi.
    /// @param tokenSnapshotIntervalHours The initial time in hours between automatic snapshots.
    constructor(string memory tokenName, string memory tokenSymbol, uint256 tokenCap, uint256 tokenSnapshotIntervalHours) ERC20(tokenName, tokenSymbol) Ownable() Pausable()
        {
        require(tokenCap > 0, "WrappedAsset: The maxSupply is 0, it must be > 0.");
        require(tokenSnapshotIntervalHours > 0, "WrappedAsset: The time between snapshots can't be 0, it must be at least 1 hour.");
        maxSupply = tokenCap;
        snapshotIntervalSeconds = 60*60*tokenSnapshotIntervalHours;
        }

    /// An owner only method to change the VendorRegistry this WrappedAsset is associated with, use VendorRegistry.setWrappedAsset() to make the required reciprical change on VendorRegistry.
    /// @param vendorRegistryAddress The address of the new VendorRegistry contract to pair with.
    function setVendorRegistry(address vendorRegistryAddress) public isOwner
        {
        registryAddr = vendorRegistryAddress;
        registry = VendorRegistry(vendorRegistryAddress);
        }

    /// Get the address of this WrappedAsset's VendorRegistry.
    /// @return The VendorRegistry contract's address.
    function getVendorRegistry() public view returns (address)
        {
        return registryAddr;
        }

    /// An owner only method to set the origin VendorRegistry & WrappedAsset from which the public method migrateFromPreviousVersion() will transfer registrations and funds to this WrappedAsset and it's VendorRegistry.
    /// Call setNextVersion() on the previous WrappedAsset first.
    /// @param vendorRegistry The address of the origin VendorRegistry from which registrations will be transfered to this WrappedAsset's VendorRegistry by migrateFromPreviousVersion().
    /// @param wrappedAsset   The address of the origin WrappedAsset from which funds will be transfered to this WrappedAsset by migrateFromPreviousVersion().
    function setPrevVersion(address vendorRegistry, address wrappedAsset) public isOwner
        {
        require(vendorRegistry != address(0), "WrappedAsset: The address of the previous VendorRegistry can't be 0.");
        require(wrappedAsset != address(0), "WrappedAsset: The address of the previous WrappedAsset can't be 0.");
        require(prevVendorRegistry == address(0), "WrappedAsset: The previous version has already been set.");
        prevVendorRegistry = vendorRegistry;
        prevWrappedAsset = wrappedAsset;
        }

    /// An owner only method to set the address of the next version of WrappedAsset which is allowed to migrate funds and registrations out of this WrappedAsset and it's VendorRegistry.
    /// After calling this call setPrevVersion() on the next WrappedAsset to enable migration.
    /// @param wrappedAsset The address of the WrappedAsset to which funds may be migrated (I.E. the WrappedAsset allowed to call migrationBurn()).
    function setNextVersion(address wrappedAsset) public isOwner
        {
        require(wrappedAsset != address(0), "WrappedAsset: The address of the next WrappedAsset can't be 0.");
        require(nextWrappedAsset == address(0), "WrappedAsset: The next version has already been set.");
        nextWrappedAsset = wrappedAsset;
        }

    /// @inheritdoc ERC20
    function name() public view virtual override returns (string memory)
        {
        return super.name();
        }

    /// @inheritdoc ERC20
    function symbol() public view virtual override returns (string memory)
        {
        return super.symbol();
        }

    /// @inheritdoc ERC20
    function decimals() public pure virtual override returns (uint8)
        {
        return 8;
        }

    /// Get the maximum amount of tokens allowed in satoshi.
    /// @return The maximum amount of tokens allowed in satoshi.
    function cap() public view returns (uint256)
        {
        return maxSupply;
        }

    /// Get the maximum amount of tokens in satoshi that can currently be minted without exceeding the maximum supply.
    /// @return The number of satoshi available before reaching the maximum supply.
    function unusedSupply() public view virtual returns (uint256)
        {
        return maxSupply - totalSupply();
        }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual override returns (uint256)
        {
        return super.totalSupply();
        }

    /// Get the amount of wrapped MRX in the caller's account in satoshi.
    /// @return The caller's balance in satoshi.
    function balance() public view virtual returns (uint256)
        {
        return super.balanceOf(_msgSender());
        }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual override returns (uint256)
        {
        return super.balanceOf(account);
        }

    /// @inheritdoc IERC20
    function transfer(address recipient, uint256 amount) public virtual override returns (bool)
        {
        return super.transfer(recipient, amount);
        }

    /// Move the caller's funds and, if necessary, their registration from the previous WrappedAsset & VendorRegistry (as set with setPrevVersion()) to this WrappedAsset and ir's VendorRegistry.
    /// This is the method members of the public use to move to an upgraded WrappedAsset & VendorRegistry.
    function migrateFromPreviousVersion() public
        {
        require(prevVendorRegistry != address(0), "WrappedAsset: Migration failed because the previous version has not been set.");
        IMigratableVendorRegistry prevVr = IMigratableVendorRegistry(prevVendorRegistry);
        address mrxAddress = prevVr.findMrxFromVendor(_msgSender());
        require(mrxAddress != address(0), "WrappedAsset: Migration failed because the caller is not registered with the previous version.");
        if (registry.findMrxFromVendor(_msgSender()) == address(0)) registry.migrateVendorRegistration(mrxAddress, _msgSender());
        IMigratableWrappedAsset prevWa = IMigratableWrappedAsset(prevWrappedAsset);
        uint256 amount = prevWa.migrationBurn(_msgSender(), unusedSupply());
        _mint(_msgSender(), amount);
        }

    /// A pausable method by which a member of the public can add an amount of wrapped MRX to their account 1 time only, and only with permission in the form of a nonce and a signature.
    /// @param amount    The amount of wrapped MRX to add to the caller's account in satoshi.
    /// @param nonce     A 1 time use only large number forever uniquely identifying this permission to mint.
    /// @param signature A manager of this contract's signature on a premission to mint message.
    function vendorMint(uint256 amount, bytes32 nonce, bytes memory signature) public whenNotPaused
        {
        require(totalSupply() + amount <= maxSupply, "WrappedAsset: Mint failed, it would exceed the cap.");
        require(registry.findMrxFromVendor(msg.sender) != address(0), "WrappedAsset: Mint failed, the caller's address has not been registered as a vendor.");
        require(!usedNonces[nonce], "WrappedAsset: Mint failed, this mint has been used before.");
        usedNonces[nonce] = true;
        bytes memory message = abi.encodePacked(msg.sender, amount, address(this), nonce);
        require(addressIsAManager(recoverSigner(message, signature)), "WrappedAsset: Mint failed, invalid signature.");
        _mint(_msgSender(), amount);
        }

    /// Check whether or not the vendor mint identifed by the nonce has happened.
    /// @return True if the mint has happened, and false otherwise.
    function mintRedeemed(bytes32 nonce) public view returns (bool)
        {
        return usedNonces[nonce];
        }

    /// A manager only method to mint wrapped MRX into the manager's account without needing any permission.
    /// @param amount The amount of wrapped MRX to add to the manager's account in satoshi.
    function mint(uint256 amount) public isManager virtual
        {
        require(totalSupply() + amount <= maxSupply, "WrappedAsset: Mint failed, it would exceed the cap.");
        _mint(_msgSender(), amount);
        }

    /// Deduct the given amount from the caller's account.
    /// @param amount The amount to be deducted from the caller's account in satoshi.
    function burn(uint256 amount) public virtual
        {
        require(registry.findMrxFromVendor(_msgSender()) != address(0), "WrappedAsset: Burn failed, the caller's address has not been registered as a vendor.");
        _burn(_msgSender(), amount);
        }

    /// @inheritdoc IMigratableWrappedAsset
    function migrationBurn(address account, uint256 maxAmount) external override returns (uint256)
        {
        require(address(0) != nextWrappedAsset, "WrappedAsset: Migration failed because the next version has not been set.");
        require(_msgSender() == nextWrappedAsset, "WrappedAsset: Access not permitted.");
        require(registry.findMrxFromVendor(account) != address(0), "WrappedAsset: Migration failed, the caller's address has not been registered as a vendor.");
        uint256 amount = balanceOf(account);
        if (amount > maxAmount) amount = maxAmount;
        _burn(account, amount);
        return amount;
        }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual override returns (uint256)
        {
        return super.allowance(owner, spender);
        }

    /// @inheritdoc IERC20
    function approve(address spender, uint256 amount) public virtual override returns (bool)
        {
        return super.approve(spender, amount);
        }

    /// @inheritdoc IERC20
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
        {
        return super.transferFrom(sender, recipient, amount);
        }

    /// @inheritdoc ERC20
    function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool)
        {
        return super.increaseAllowance(spender, addedValue);
        }

    /// @inheritdoc ERC20
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool)
        {
        return super.decreaseAllowance(spender, subtractedValue);
        }

    /// Pause the process of vendor minting with vendorMint().
    function pause() public isManager virtual
        {
        _pause();
        }

    /// Restart the process of vendor minting with vendorMint().
    function unpause() public isManager virtual
        {
        _unpause();
        }
    /// Check whether or not the process of vendor minting with vendorMint() is currently paused.
    /// @return True if the process of vendor minting with vendorMint() is currently paused, otherwise false.
    function paused() public view virtual override returns (bool)
        {
        return super.paused();
        }

    /// Get the balance of account at the time snapshotId was created.
    /// @param  account The account for which to get the balance at the time snapshotId was created.
    /// @param  snapId  The id of the snapshot.
    /// @return The amount of wrapped MRX in the account in satoshi. 
    function balanceOfAt(address account, uint256 snapId) public view virtual override returns (uint256)
        {
        return super.balanceOfAt(account, snapId);
        }

    /// Get the total supply at the time snapshotId was created.
    /// @param  snapId The snapshot id.
    /// @return The total supply at the time snapshotId was created in satoshi.
    function totalSupplyAt(uint256 snapId) public view virtual override returns(uint256)
        {
        return super.totalSupplyAt(snapId);
        }

    /// Get the current snapshot id.
    /// @return The current snapshot id.
    function getCurrentSnapshotId() public view virtual returns (uint256)
        {
        return _getCurrentSnapshotId();
        }

    /// Take a snapshot.
    /// @return The new current snapshot id after the snapshot.
    function takeSnapshot() public isManager virtual returns (uint256)
        {
        nextSnapshotId(block.timestamp);
        return _getCurrentSnapshotId();
        }

    /// Set the interval in hours between automatic snapshots.
    /// @param snapshotIntervalHours The new interval in hours between automatic snapshots.
    function setSnapshotIntervalHours(uint256 snapshotIntervalHours) public isManager virtual
        {
        require(snapshotIntervalHours > 0, "WrappedAsset: The time between snapshots can't be 0, it must be at least 1 hour.");
        snapshotIntervalSeconds = 60*60*snapshotIntervalHours;
        }

    /// Get the current interval in hours between automatic snapshots.
    /// @return The current interval in hours between automatic snapshots.
    function getSnapshotIntervalHours() public view virtual returns (uint256)
        {
        return snapshotIntervalSeconds/(60*60);
        }

    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override
        {
        uint256 timestamp = block.timestamp;
        if (timestamp > snapshotBlockTimestamp + snapshotIntervalSeconds) nextSnapshotId(timestamp);
        super._beforeTokenTransfer(from, to, amount);
        }

    function nextSnapshotId(uint256 blockTimestamp) private
        {
        snapshotId++;
        snapshotBlockTimestamp = blockTimestamp;
        emit SnapshotInfo(blockTimestamp, block.number, snapshotId);
        }

    function _getCurrentSnapshotId() internal view virtual override returns (uint256)
        {
        return snapshotId;
        }

    function recoverSigner(bytes memory message, bytes memory signature) internal pure returns (address)
        {
        require(signature.length == 65, "WrappedAsset: Action failed, invalid signature.");
        uint8 v;
        bytes32 r;
        bytes32 s;
        assembly
            {
            r := mload(add(signature, 32))
            s := mload(add(signature, 64))
            v := byte(0, mload(add(signature, 96)))
            }
        return ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", keccak256(message))), v, r, s);
        }
    }