// File: @ermine/contracts/ErmineSwap.sol



// SPDX-License-Identifier: MIT
// EVM BLP SWAP & ReturnVM
// https://ermine.pro


pragma solidity ^0.8.23;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@ermine/contracts/Ermine.sol";
import "@ermine/contracts/ErmineVM.sol";
import "@ermine/contracts/ErmineStoreIn.sol";

contract ErmineSwap is Ownable {
    uint256 public totalETH = 0;
    uint256 public totalERM = 0;
    bool start;
    address AddressEVM;
    address AddressERM;
    address payable AddressStore;
    Ermine public coin;
    ErmineVM public nft;
    ErmineStoreIn public store;

    event Received(address, uint);
    event swapETH(address, uint256, uint256);
    event swapERM(address, uint256, uint256);
    event returnvm(address, uint256, uint256);

    receive() external payable {
        emit Received(msg.sender, msg.value);
    }

    struct User {
        uint256 lastTime;
    }

    struct Stat {
        uint256[] _dat;
        uint256[] _price;
    }

    mapping(address => User) private _user;
    mapping(uint256 => Stat) private _stat;

    constructor(address _AddressEVM, address _AddressERM, address payable _AddressStore){
        AddressEVM = _AddressEVM;
        nft = ErmineVM(AddressEVM);
        AddressERM = _AddressERM;
        coin = Ermine(AddressERM);
        AddressStore = _AddressStore;
        store = ErmineStoreIn(AddressStore);
    }

    //For onlyOperator
    modifier onlyErmi() {
    require(msg.sender == AddressStore);
    _;                              
    } 

    function swapETHtoERM() external payable {
    require(start, "Exchange not started! Read Ermine announcements!"); 
    require(block.timestamp >= _user[msg.sender].lastTime + 300, "AntiBot: You can not exchange more than once every 5 minutes!");
    require(msg.value > 0, "Ether value sent is not correct!"); 
    uint256 _perETH = (msg.value / 100);
    uint256 _sumERM = PurchaseAmount(_perETH * 99);
    require(totalERM > _sumERM, "Not enough liquidity in the pool!");
    _user[msg.sender].lastTime = block.timestamp;
    coin.transfer(msg.sender, _sumERM);
    totalERM -= _sumERM;
    totalETH += (_perETH * 99);
    if (store.checkUser(msg.sender)) {
        string memory _toStat = string(abi.encodePacked(Strings.toString(block.timestamp), "500", Strings.toString(msg.value), "&", Strings.toString(_sumERM)));
        store.addStat(msg.sender, _toStat);
    }
    _stat[0]._dat.push(block.timestamp); 
    _stat[0]._price.push(getPrice()); 
    emit swapETH(msg.sender, msg.value, _sumERM);
    }

    function swapERMtoETH(uint256 amount) external {
    require(start, "Exchange not started! Read Ermine announcements!");
    require(block.timestamp >= _user[msg.sender].lastTime + 300, "AntiBot: You can not exchange more than once every 5 minutes!");
    require(totalETH > 0, "Not enough liquidity in the pool!");
    require(coin.balanceOf(msg.sender) >= amount, "There are not enough tokens to exchange on your balance!");
    _user[msg.sender].lastTime = block.timestamp;
    uint256 _per = SaleAmount(amount) / 100;
    coin.transferFrom(msg.sender, address(this), amount);
    require(payable(msg.sender).send(_per * 99));
    totalERM += amount;
    totalETH -= (_per * 100);
    if (store.checkUser(msg.sender)) {
        string memory _toStat = string(abi.encodePacked(Strings.toString(block.timestamp), "501", Strings.toString(_per * 99), "&", Strings.toString(amount)));
        store.addStat(msg.sender, _toStat);
    }
    _stat[0]._dat.push(block.timestamp); 
    _stat[0]._price.push(getPrice()); 
    emit swapERM(msg.sender, amount, _per * 99);
    }

    function setPool(uint256 amount) external payable onlyOwner {
    require((totalERM == 0)||(totalETH == 0), "The pool already exists!");
    require(msg.value > 0, "Ether value sent is not correct!"); 
    coin.transferFrom(msg.sender, address(this), amount);
    totalERM += amount;
    totalETH += msg.value;

    }

    function setAddressStore(address payable _AddressStore) external onlyErmi {
        AddressStore = _AddressStore;
    }

    function setLauch() external onlyErmi {
        start = !start;
    }

    function addLiq(uint256 value) external onlyErmi {
        totalERM += ((value  * 1e18) / getPrice());
        totalETH += value;
    }

    function getPrice() public view returns (uint256) {
    return ((totalETH * 1e18) / totalERM);
    }

    function takeTax(address _to) external payable onlyErmi { 
    require(getTax() > 0, "There are no funds to transfer to the Ermine!");
    require(payable(_to).send(getTax()));
    }

    function PurchaseAmount(uint256 amount) public view returns (uint256) {
        return ((amount * totalERM)/(totalETH + amount));
    }  

    function SaleAmount(uint256 amount) public view returns (uint256) {
        return ((totalETH  * amount)/(totalERM + amount));
    }  

    function ReturnVM(uint[] memory valMiner) external {
        require(start, "Exchange not started! Read Ermine announcements!");
        require(valMiner.length == 12, "Invalid miner ID entered!");
        uint256 totalsum = 0;
        for (uint i = 0; i < 12; i++) {
        if ((valMiner[i]>0)&&(nft.balanceOf(msg.sender, i) >= valMiner[i])) { 
                nft.safeTransferFrom(msg.sender, AddressStore, i, valMiner[i], "");
                totalsum += (store.getPriceVM(i) * valMiner[i]);
            }
        }
        require(totalsum > 0, "You do not have selected miners to change back!");
        uint256 hal = (totalsum / 100) * 15;
        uint256 amount = ((hal * 1e18) / getPrice()); 
        coin.transfer(msg.sender, amount);
        require(payable(msg.sender).send(hal));
        totalETH -= hal;
        totalERM -= amount;
        emit returnvm(msg.sender, hal, amount);
    }

    function getViewMoney(uint[] memory valMiner) public view returns (uint256, uint256) {
        uint256 sumETH = 0;
        uint256 sumERM = 0;
        uint256 bufSum = 0;
        uint256[] memory bufMas = new uint256[](12);
        bufMas = store.getPriceAllVM();
        for (uint i = 0; i < 12; i++) {
            bufSum = ((valMiner[i] * bufMas[i]) / 100) * 15;
            sumETH += bufSum;
            sumERM += bufSum * 1e18 / getPrice();
        }
        return (sumETH, sumERM);
    }

    function getTax() public view returns(uint256) {
        if (address(this).balance > totalETH) {
            return(address(this).balance - totalETH);
        }
        else {
            return(0);  
        }    
    }
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

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: @openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_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) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

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

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// 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 Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

// File: @openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return 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
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

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: @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)

pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../../../utils/Context.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20Burnable is Context, ERC20 {
    /**
     * @dev Destroys `amount` tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 amount) public virtual {
        _burn(_msgSender(), amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, deducting from the caller's
     * allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `amount`.
     */
    function burnFrom(address account, uint256 amount) public virtual {
        _spendAllowance(account, _msgSender(), amount);
        _burn(account, amount);
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/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 Contracts guidelines: functions revert
 * instead 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:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, 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}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, 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}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, 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) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, 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) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This 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:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, 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);

        _afterTokenTransfer(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);

        _afterTokenTransfer(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 Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - 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 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 {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

// File: @openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)

pragma solidity ^0.8.0;

import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";

/**
 * @dev _Available since v3.1._
 */
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }
}

// File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)

pragma solidity ^0.8.0;

import "../IERC1155.sol";

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

// File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol)

pragma solidity ^0.8.0;

import "../ERC1155.sol";

/**
 * @dev Extension of ERC1155 that adds tracking of total supply per id.
 *
 * Useful for scenarios where Fungible and Non-fungible tokens have to be
 * clearly identified. Note: While a totalSupply of 1 might mean the
 * corresponding is an NFT, there is no guarantees that no other token with the
 * same id are not going to be minted.
 */
abstract contract ERC1155Supply is ERC1155 {
    mapping(uint256 => uint256) private _totalSupply;

    /**
     * @dev Total amount of tokens in with a given id.
     */
    function totalSupply(uint256 id) public view virtual returns (uint256) {
        return _totalSupply[id];
    }

    /**
     * @dev Indicates whether any token exist with a given id, or not.
     */
    function exists(uint256 id) public view virtual returns (bool) {
        return ERC1155Supply.totalSupply(id) > 0;
    }

    /**
     * @dev See {ERC1155-_beforeTokenTransfer}.
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual override {
        super._beforeTokenTransfer(operator, from, to, ids, amounts, data);

        if (from == address(0)) {
            for (uint256 i = 0; i < ids.length; ++i) {
                _totalSupply[ids[i]] += amounts[i];
            }
        }

        if (to == address(0)) {
            for (uint256 i = 0; i < ids.length; ++i) {
                uint256 id = ids[i];
                uint256 amount = amounts[i];
                uint256 supply = _totalSupply[id];
                require(supply >= amount, "ERC1155: burn amount exceeds totalSupply");
                unchecked {
                    _totalSupply[id] = supply - amount;
                }
            }
        }
    }
}

// File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/extensions/ERC1155Burnable.sol)

pragma solidity ^0.8.0;

import "../ERC1155.sol";

/**
 * @dev Extension of {ERC1155} that allows token holders to destroy both their
 * own tokens and those that they have been approved to use.
 *
 * _Available since v3.1._
 */
abstract contract ERC1155Burnable is ERC1155 {
    function burn(
        address account,
        uint256 id,
        uint256 value
    ) public virtual {
        require(
            account == _msgSender() || isApprovedForAll(account, _msgSender()),
            "ERC1155: caller is not token owner nor approved"
        );

        _burn(account, id, value);
    }

    function burnBatch(
        address account,
        uint256[] memory ids,
        uint256[] memory values
    ) public virtual {
        require(
            account == _msgSender() || isApprovedForAll(account, _msgSender()),
            "ERC1155: caller is not token owner nor approved"
        );

        _burnBatch(account, ids, values);
    }
}

// File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

// File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

// File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/ERC1155.sol)

pragma solidity ^0.8.0;

import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 *
 * _Available since v3.1._
 */
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
    using Address for address;

    // Mapping from token ID to account balances
    mapping(uint256 => mapping(address => uint256)) private _balances;

    // Mapping from account to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
    string private _uri;

    /**
     * @dev See {_setURI}.
     */
    constructor(string memory uri_) {
        _setURI(uri_);
    }

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

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256) public view virtual override returns (string memory) {
        return _uri;
    }

    /**
     * @dev See {IERC1155-balanceOf}.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
        require(account != address(0), "ERC1155: address zero is not a valid owner");
        return _balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
        public
        view
        virtual
        override
        returns (uint256[] memory)
    {
        require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts[i], ids[i]);
        }

        return batchBalances;
    }

    /**
     * @dev See {IERC1155-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC1155-isApprovedForAll}.
     */
    function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[account][operator];
    }

    /**
     * @dev See {IERC1155-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not token owner nor approved"
        );
        _safeTransferFrom(from, to, id, amount, data);
    }

    /**
     * @dev See {IERC1155-safeBatchTransferFrom}.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not token owner nor approved"
        );
        _safeBatchTransferFrom(from, to, ids, amounts, data);
    }

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }
        _balances[id][to] += amount;

        emit TransferSingle(operator, from, to, id, amount);

        _afterTokenTransfer(operator, from, to, ids, amounts, data);

        _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
            _balances[id][to] += amount;
        }

        emit TransferBatch(operator, from, to, ids, amounts);

        _afterTokenTransfer(operator, from, to, ids, amounts, data);

        _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the amounts in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        _uri = newuri;
    }

    /**
     * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        _balances[id][to] += amount;
        emit TransferSingle(operator, address(0), to, id, amount);

        _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

        _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; i++) {
            _balances[ids[i]][to] += amounts[i];
        }

        emit TransferBatch(operator, address(0), to, ids, amounts);

        _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

        _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
    }

    /**
     * @dev Destroys `amount` tokens of token type `id` from `from`
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `amount` tokens of token type `id`.
     */
    function _burn(
        address from,
        uint256 id,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC1155: burn from the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }

        emit TransferSingle(operator, from, address(0), id, amount);

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     */
    function _burnBatch(
        address from,
        uint256[] memory ids,
        uint256[] memory amounts
    ) internal virtual {
        require(from != address(0), "ERC1155: burn from the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

        for (uint256 i = 0; i < ids.length; i++) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
        }

        emit TransferBatch(operator, from, address(0), ids, amounts);

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC1155: setting approval status for self");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `ids` and `amounts` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `id` and `amount` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {}

    function _doSafeTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) private {
        if (to.isContract()) {
            try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
                if (response != IERC1155Receiver.onERC1155Received.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non ERC1155Receiver implementer");
            }
        }
    }

    function _doSafeBatchTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) private {
        if (to.isContract()) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
                bytes4 response
            ) {
                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non ERC1155Receiver implementer");
            }
        }
    }

    function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
        uint256[] memory array = new uint256[](1);
        array[0] = element;

        return array;
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @ermine/contracts/ErmineVM.sol



// SPDX-License-Identifier: MIT
// Ermine Virtual Miners (EVM) :: https://ermine.pro 

//  ███████╗██████╗$███╗$$$███╗██╗███╗$$$██╗███████╗██╗$$$██╗███╗$$$███╗
//  ██╔════╝██╔══██╗████╗$████║██║████╗$$██║██╔════╝██║$$$██║████╗$████║
//  █████╗$$██████╔╝██╔████╔██║██║██╔██╗$██║█████╗$$██║$$$██║██╔████╔██║
//  ██╔══╝$$██╔══██╗██║╚██╔╝██║██║██║╚██╗██║██╔══╝$$╚██╗$██╔╝██║╚██╔╝██║
//  ███████╗██║$$██║██║$╚═╝$██║██║██║$╚████║███████╗$╚████╔╝$██║$╚═╝$██║
//  ╚══════╝╚═╝$$╚═╝╚═╝$$$$$╚═╝╚═╝╚═╝$$╚═══╝╚══════╝$$╚═══╝$$╚═╝$$$$$╚═╝

pragma solidity ^0.8.17;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

contract ErmineVM is ERC1155Supply, Ownable  {
    uint[] public maxAmountEVM = new uint256[](12);
    uint[] public burnedEVM = new uint256[](12);
    uint256 public timeAddLE;
    address public addressErmineStore;
    bool VMpart1 = false;
    bool VMpart2 = false;
    string public name;
    string public symbol;  

event Burn(address indexed from, uint evm_id, uint256 amount);

struct Admin {
    bool sys;
}

mapping(address => Admin) public checkAdmin;

constructor(string memory _uri, string memory _name, string memory _symbol) ERC1155(_uri) {
    name = _name;
    symbol = _symbol;
    checkAdmin[msg.sender].sys = true;
    //Mint to the developers' wallet to distribute them to community members for fulfilling certain conditions (competitions)
    //100 miners with 1 IPS each
    _mint(msg.sender, 0, 100, "");
    //Setting the maximum number of EVMs for each category
    maxAmountEVM[0] = 1000000;
    maxAmountEVM[1] = 500000;
    maxAmountEVM[2] = 300000;
    maxAmountEVM[3] = 100000;
    maxAmountEVM[4] = 50000;
    maxAmountEVM[5] = 20000;
    maxAmountEVM[6] = 10000;
    maxAmountEVM[7] = 5000;
    maxAmountEVM[8] = 50000;
    maxAmountEVM[9] = 20000;
    maxAmountEVM[10] = 3000;
    maxAmountEVM[11] = 1000;
}

modifier onlyAdmin() {
    require(checkAdmin[msg.sender].sys);
    _;                              
} 

//EVM mint for Ermine store part 1
function mintEVMforStore() external onlyOwner {
require(addressErmineStore != address(0), "Ermine store address not specified! Set the store address and try again!");
require(!VMpart1, "Virtual miners have already been sent to the Ermine store. Can't be repeated!");
    VMpart1 = !VMpart1;
    _mint(addressErmineStore, 0, (maxAmountEVM[0] - 100), "");
    for (uint i = 1; i < 8; i++) {
    _mint(addressErmineStore, i, maxAmountEVM[i], "");
    //Setting the time to transfer VM LE to the Ermine store. VM LE release will be available in 181 days.
    timeAddLE = block.timestamp + 15638400;
    }
}

//EVM mint for Ermine store part 2. Available one time. The call is available to everyone.
function mintEVMLEforStore() external {
require(block.timestamp >= timeAddLE, "It is not yet possible to ship the EVM LE to the Ermine store. Less than 181 days have passed since the first shipment!");
require(VMpart1, "Release the EVM in the first batch first!");
require(!VMpart2, "Virtual miners have already been sent to the Ermine store. Can't be repeated!");
    VMpart2 = !VMpart2;
    for (uint i = 8; i < 12; i++) {
    _mint(addressErmineStore, i, maxAmountEVM[i], "");
    }
}

//Burning is available to everyone
function burnMyEVM(uint evm_id, uint256 amount) external { 
    require(balanceOf(msg.sender, evm_id) >= amount, "You don't have enough EVM to burn them!");
    _burn(msg.sender, evm_id, amount);
    burnedEVM[evm_id] += amount;
    emit Burn(msg.sender, evm_id, amount);
}

//Set Ermine store address (you can only set the store address once)
function setErmineStore(address _ErmineStore) external onlyOwner {
    require(addressErmineStore == address(0), "The address of the Ermine store is already set!");
    addressErmineStore = _ErmineStore;
    checkAdmin[addressErmineStore].sys = true;
}

//Set URI
function setURI(string memory newuri) public onlyAdmin {
    _setURI(newuri);
}

//Remove Admin Rights
function RemoveAdmin() public onlyAdmin {
    require(checkAdmin[msg.sender].sys, "You cannot relinquish admin rights as you are not an admin!");
    checkAdmin[msg.sender].sys = !checkAdmin[msg.sender].sys;
}

//View URI
function uri(uint256 _id) public view override returns (string memory) {
    require(exists(_id), "URI: nonexistent EVM token");
    return string(abi.encodePacked(super.uri(_id), Strings.toString(_id)));
}

}
// File: @ermine/contracts/ErmineStoreIn.sol



// SPDX-License-Identifier: MIT
// ERMINE STORE, EVM, Affiliate program
// https://ermine.pro

pragma solidity ^0.8.23;

import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@ermine/contracts/Ermine.sol";
import "@ermine/contracts/ErmineVM.sol";
import "@ermine/contracts/ErmineSwap.sol";

contract ErmineStoreIn is ERC1155Receiver, Ownable {
    uint256 public forDEX;
    uint256 public airdrop = 3*1e24;
    uint[] public percent = new uint[](3);
    address walletDev;
    address payable BLP;
    address AddressEVM;
    address AddressERM;
    address payable Treasury;
    Ermine public coin;
    ErmineVM public nft;
    ErmineSwap public swap;

    event Received(address, uint);
    event BuyMiners(address, uint);
    event newUser(uint, address);

    receive() external payable {
        emit Received(msg.sender, msg.value);
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        require(msg.sender == AddressEVM, "You cannot send other NFTs to Ermine Store!");
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        require(msg.sender == AddressEVM, "You cannot send other NFTs to Ermine Store!");
        return this.onERC1155BatchReceived.selector;
    }

    struct Miners {
        uint ips;
        uint price;
    } 

    struct Users {
        uint256 ids;
        uint status;
        uint256 totalETH;
        uint256 ethBal;
        uint256 ermBal;
        string[] _stat;
        address[] refer;
    }
    
    struct Discount {
        uint numberBuy;
        uint size;
    }

    struct Base { 
        address[] all_user; 
    }

    mapping(address => Users) private _users;
    mapping(uint => Miners) public _miners;
    mapping(address => address) private _refer;
    mapping(uint256 => Base) private _base;
    mapping(address => Discount) private _sale;
    mapping(address => bool) private _statista;
    mapping(address => bool) private _ysc;

    constructor(address _wDev, address _AddressEVM, address _AddressERM, uint[] memory _ips, uint[] memory _price) {
        forDEX = 0;
        walletDev = _wDev;
        _ysc[walletDev] = true;
        AddressEVM = _AddressEVM;
        nft = ErmineVM(AddressEVM);
        AddressERM = _AddressERM;
        coin = Ermine(AddressERM);
        percent[0] = 8;
        percent[1] = 3;
        percent[2] = 2;
        for (uint i = 0; i < 12; i++) {
            _miners[i].ips = _ips[i];
            _miners[i].price = _price[i];
        }
    }
    
    modifier onlyOfficial() {
        require((_users[msg.sender].status == 3)||((_users[msg.sender].refer.length > 39)&&(_users[msg.sender].ermBal > 7999e18)&&(_users[msg.sender].totalETH > 100e18)),"You do not have access rights!");
    _;                              
    } 

    modifier onlySale() {
        require(_sale[msg.sender].numberBuy > 0, "There is no discount on the purchase of miners!");
    _;                              
    } 

    modifier onlyDev() {
        require(msg.sender == walletDev, "You do not have access rights!");
    _;                              
    } 

    modifier onlyStat() {
        require(_statista[msg.sender], "You do not have access rights!");
    _;                              
    } 

    modifier onlyOperator() {
        require(_ysc[msg.sender], "You do not have access rights!");
    _;                              
    }

//New user registration
function regUser(address _toReg, uint _ips) internal {
    Base storage base = _base[0];
    base.all_user.push(_toReg);
    Users storage user = _users[_toReg];
    user.ids = base.all_user.length;
    user.status = 0;
    user.ethBal = 0;
    user.ermBal = 0;
    uint256 forReward = 100e18 * _ips; 
    if ((airdrop >= forReward)&&(forReward > 0)) {
        coin.transfer(_toReg, forReward);
        user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "300", Strings.toString(forReward))));
        airdrop -= forReward;
     }
     else {
        user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "301", Strings.toString(user.ermBal))));
     } 
    emit newUser(block.timestamp, msg.sender);
}

function buyMiners(uint[] calldata valMiner, address whoRef) external payable {
    require(valMiner.length == 12, "Invalid miner ID entered!");
    uint256 totalsum = 0;
    uint totalips = 0;
    for (uint i = 0; i < 12; i++) {
        if (nft.balanceOf(address(this), i) >= valMiner[i]) { 
        totalsum += (_miners[i].price * valMiner[i]);
        totalips += (_miners[i].ips * valMiner[i]);
        }
    }
    require(totalsum <= msg.value, "Ether value sent is not correct!");
    uint256 onePer = (totalsum / 100);
    if (Treasury != address(0)) {
	    require(payable(Treasury).send(50 * onePer));}
    else {
	    forDEX += (50 * onePer);
    }
    require(payable(BLP).send((30 * onePer)));
    swap.addLiq((30 * onePer));
    address[] memory REL = new address[](3); 
    if (!checkUser(msg.sender)) {
    regUser(msg.sender, totalips);
    }
    for (uint i = 0; i < 12; i++) {
    if (valMiner[i] > 0) {
    nft.safeTransferFrom(address(this), msg.sender, i, valMiner[i], "");
    }
    }
    _users[msg.sender]._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "400", Strings.toString(totalsum))));
    Users storage user;
    user = _users[whoRef];
    //Direct sale
    if (_refer[msg.sender]==address(0)) {
        if ((!checkUser(whoRef))||(whoRef == msg.sender)) {
            _refer[msg.sender] = walletDev;
            user = _users[walletDev];
            user.refer.push(msg.sender); 
            whoRef = walletDev;
        }
        else {
            _refer[msg.sender] = whoRef;
            user.refer.push(msg.sender);
        }
    }
//A-program
    uint maxper = 20;
    if ((whoRef != msg.sender)&&(whoRef != walletDev)) {
    _users[whoRef].totalETH += totalsum;    
	REL[0] = _refer[msg.sender];
	REL[1] = _refer[REL[0]];
	REL[2] = _refer[REL[1]];
    for (uint i = 0; i < 3; i++) {
        uint x = 0;
	if (REL[i] != address(0)) {
        user = _users[REL[i]];
        if (user.refer.length > 1) {x += 1;} //silver status
        if ((user.refer.length > 19)&&((user.ermBal > 1999e18)||(user.status > 0))) {x += 1;}//gold and official status
        uint realper = (percent[i] + x);
        maxper -= realper;
        uint256 rewSum = (onePer * realper);
        user.ethBal += rewSum;
        user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), Strings.toString(110 + i), Strings.toString(rewSum),"&", Strings.toString(user.ids))));
        if ((user.ids > 1)&&(coin.balanceOf(address(this)) >= 30*1e18)) {
            uint256 sumerm = (realper*3e18);
            user.ermBal += sumerm;
            user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), Strings.toString(310 + i), Strings.toString(sumerm),"&", Strings.toString(user.ids))));
        }
            }
        }
    }
    else {
        _users[walletDev].totalETH += totalsum; 
    }
    //tax for Ermine
    user = _users[walletDev];
    user.ethBal += (onePer * maxper);
    user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "3103", Strings.toString(onePer * maxper))));
    emit BuyMiners(msg.sender, totalsum);
}

function buyForOfficial(uint[] calldata valMiner, address _to) external payable onlyOfficial {
    require((_refer[_to] == msg.sender), "You can sell miners at a discount only for those whom you originally invited yourself!"); 
    processBuy(msg.sender, valMiner, 20);
    _users[_to]._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "401", "0")));
    _users[msg.sender]._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "404", Strings.toString(msg.value))));
}

function buyForGift(uint[] calldata valMiner, address _to) external payable {
    require(checkUser(msg.sender), "Purchase with a discount or as a gift is available only for registered addresses!"); 
    if (!checkUser(_to)) {
        regUser(_to, 0);
        _refer[_to] = msg.sender;
        _users[msg.sender].refer.push(_to);
    }
    processBuy(_to, valMiner, 0);
    _users[_to]._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "402", Strings.toString(msg.value))));
}

function saleDiscount(uint[] calldata valMiner) external payable onlySale {
    Discount storage saleUser = _sale[msg.sender];
    saleUser.numberBuy -= 1;
    processBuy(msg.sender, valMiner, saleUser.size);
    _users[msg.sender]._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "403", Strings.toString(msg.value))));
}

function fixStat() external {
    Users storage user;
    user = _users[msg.sender];
    require(user._stat.length > 0, "This address is not registered in the referral program!");
    require(user.refer.length > 19, "Not enough referrals, invite more!");
    require(user.status < 3, "You already have the highest member status!");
    if ((user.refer.length < 40)&&((user.ermBal >= 1999e18)&&(user.status < 2))) {
        user.status = 2;
        user.ermBal -= 1999e18;
        user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "200", "1999000000000000000000")));
        }
    if ((user.refer.length > 39)&&(user.ermBal >= 7999e18)&&(user.totalETH > 100e18)) {
        user.status = 3;
        user.ermBal -= 7999e18;
        user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "201", "7999000000000000000000")));
        }
}

function depositERM(uint256 _amount, address _to) external {
    Users storage user = _users[_to];
    require(checkUser(_to), "This address is not registered!");
    require(coin.balanceOf(address(msg.sender)) >= _amount, "Your wallet does not have enough Ermine tokens to replenish your account balance!");
    coin.transferFrom(msg.sender, address(this), _amount); 
    user.ermBal += _amount;  
    if (_to==msg.sender) {
        user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "302", Strings.toString(_amount))));  
    }
    else {
        user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "303", Strings.toString(_amount))));    
    }
}

//withdraw ERM token
function withdrawERM() external {
    Users storage user = _users[msg.sender]; 
    require(user.ermBal > 0, "There are no ERM tokens on your account for withdrawal!");
    coin.transfer(msg.sender, user.ermBal);
    user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "202", Strings.toString(user.ermBal))));
    user.ermBal = 0;
}

//withdraw user profit 
function myProfit() external {
    Users storage user = _users[msg.sender];
    //uint256 balance = user.ethBal;
    require(user.ethBal > 0, "Your account has no funds to withdraw!");
    require(user.ethBal < address(this).balance, "It is currently not possible to withdraw funds. There is no liquidity. Please try again later.");
    require(payable(msg.sender).send(user.ethBal));
    user._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "000", Strings.toString(user.ethBal))));
    user.ethBal = 0;
}

function processBuy(address _to, uint[] calldata valMiner, uint _sizeD) internal {
    require(valMiner.length == 12, "Invalid miner ID entered!");
    uint256 totalsum = 0;
    for (uint i = 0; i < 12; i++) {
        if (nft.balanceOf(address(this), i) >= valMiner[i]) { 
        totalsum += (_miners[i].price * valMiner[i]);
        }
    }
    uint256 onePer = (totalsum / 100);
    if (Treasury != address(0)) {
	    require(payable(Treasury).send(50 * onePer));}
    else {
	    forDEX += (50 * onePer);
    }
    require(onePer * (100 - _sizeD) <= msg.value, "Ether value sent is not correct!");
    require(payable(BLP).send((30 * onePer)));
    if (((_sizeD) > 0)&&((_sizeD) < 20)) {
        _users[_refer[_to]].ethBal += (onePer * (20 - _sizeD));
        _users[_refer[_to]]._stat.push(string(abi.encodePacked(Strings.toString(block.timestamp), "405", Strings.toString((onePer * (20 - _sizeD))))));
    }
    emit BuyMiners(msg.sender, totalsum);
    swap.addLiq((30 * onePer));
    for (uint i = 0; i < 12; i++) {
    if (valMiner[i] > 0) {
    nft.safeTransferFrom(address(this), _to, i, valMiner[i], "");
    }
    }
    _users[_refer[_to]].totalETH += totalsum;
}

function addStat(address _user, string memory _wordStat) external onlyStat {
    Users storage user = _users[_user];
    user._stat.push(_wordStat);
}

//New User Registration
function regNewUser() external {
    require(!checkUser(msg.sender), "The user is already registered!");
    regUser(msg.sender, 0);
    if (_refer[msg.sender] == address(0)) {
        _refer[msg.sender] = walletDev;
        _users[walletDev].refer.push(msg.sender);
        }
}

//Withdrawing ETH to the Treasury
function toTreasury() external payable onlyOperator {
    require(Treasury != address(0), "The treasury has not yet been set!");
    require(forDEX > 0, "There are no funds to transfer to the treasury!");
    require(payable(Treasury).send(forDEX));
    forDEX = 0;
}

//Withdrawing profit Ermine
function toErmine(address _to) external payable onlyDev {
    swap.takeTax(_to);
}

//Section Set
//Set BLP
function setBLP(address payable newBLP) external onlyOwner {
    BLP = newBLP;
    swap = ErmineSwap(BLP);
    if (!checkUser(walletDev)) {
    regUser(walletDev, 0);
    _users[walletDev].status = 3;
    }
}

//Launch swap and ReturnVM
function setLauch() external onlyDev {
    swap.setLauch();
}

//Set Treasury
function setTreasury(address payable newTreasury) external onlyDev {
    Treasury = newTreasury;
}

//Set Ermine's new income address
function setNewWalletDev(address _newWal) external onlyDev {
    walletDev = _newWal;
    if (!checkUser(walletDev)) {
    regUser(walletDev, 0);
    _users[walletDev].status = 3;
    }
}

//Set the address for recording statistics on/off
function setStatWallet(address _newWal) external onlyDev {
    _statista[_newWal] = !_statista[_newWal];
}

//Set the address for ysc/operator on/off
function setOperatorYSC(address _Wal) external onlyOperator {
    _ysc[_Wal] = !_ysc[_Wal];
}

//Set new store
function setStore(address payable _newStore) external onlyDev {
    swap.setAddressStore(_newStore);
}

//Set discount wallet
function setDiscountWallet(address _to, uint _val, uint _size) external onlyOfficial {
    require(((_val > 0)&&(_val < 4)&&(_size > 0)&&(_size < 20)), "Incorrect parameters set!");
    require(((_refer[_to]==msg.sender)||(msg.sender==walletDev)), "You can add addresses only for clients you invited!");
    _sale[_to].numberBuy = _val;
    _sale[_to].size = _size;
    if ((msg.sender==walletDev)&&(!checkUser(_to))) {
        _refer[_to] = walletDev;
        regUser(_to, 0);
        _users[walletDev].refer.push(_to);
    } 
    }

//View section
function getIPS(uint _ips) public view returns (uint) {
    return (_miners[_ips].ips);
}

function getPriceVM(uint idVM) public view returns (uint256) {
    return (_miners[idVM].price);
}

function getPriceAllVM() public view returns (uint256[] memory) {
    uint256[] memory bufMas = new uint256[](12);
    for (uint i = 0; i < 12; i++) {
            bufMas[i] = _miners[i].price;
        }
    return (bufMas);
}

//User card
function checkUser(address _wallet) public view returns (bool) {
    if (_users[_wallet]._stat.length < 1) {
        return false;
    }
    else { 
        return true;
    }
    }

//User card
function getUser(address _wallet) public view returns (Users memory) {
        Users storage user = _users[_wallet];
        return user;
    }

//Check sale
function getDiscount(address _wallet) public view returns (Discount memory) {
        Discount storage sale = _sale[_wallet];
        return sale;
    }

//All users
function getAllUsers() public view returns (Base memory) {
        Base storage base = _base[0];
        return base;
    }   

//View ref.
function getRef(address _who) public view returns (address[] memory) {
        return _users[_who].refer; 
    }

//Check operator
function checkOperator(address _whoWal) public view returns (bool) {
        bool _verifyYCS = _ysc[_whoWal];
        return _verifyYCS;
    }  

}
// File: @ermine/contracts/Ermine.sol



// SPDX-License-Identifier: MIT
// Ermine utility token (ERM) :: https://ermine.pro 


//  ███████╗██████╗$███╗$$$███╗██╗███╗$$$██╗███████╗
//  ██╔════╝██╔══██╗████╗$████║██║████╗$$██║██╔════╝
//  █████╗$$██████╔╝██╔████╔██║██║██╔██╗$██║█████╗$$
//  ██╔══╝$$██╔══██╗██║╚██╔╝██║██║██║╚██╗██║██╔══╝$$
//  ███████╗██║$$██║██║$╚═╝$██║██║██║$╚████║███████╗
//  ╚══════╝╚═╝$$╚═╝╚═╝$$$$$╚═╝╚═╝╚═╝$$╚═══╝╚══════╝


pragma solidity ^0.8.17;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";

contract Ermine is ERC20, Ownable {
    uint256 public maxAmountERM = 800 * 1e24;
    uint256 public burnedERM = 0;

    event Burn(address indexed from, uint256 amount);
    
    constructor () ERC20 ("Ermine", "ERM") {
        _mint(msg.sender, maxAmountERM);
    }

//Burning is available to everyone
    function burn(uint256 amount) external {
        require(balanceOf(msg.sender) >= amount, "There are not enough tokens on your balance!");
        require((totalSupply() - amount) >= (400 * 1e24), "No more burning! At least 400M ERM must remain!");
        _burn(msg.sender, amount);
        burnedERM += amount;
        emit Burn(msg.sender, amount);
    }    
}