// File: Address.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return
            functionCallWithValue(
                target,
                data,
                value,
                "Address: low-level call with value failed"
            );
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(
            address(this).balance >= value,
            "Address: insufficient balance for call"
        );
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(
            data
        );
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data)
        internal
        view
        returns (bytes memory)
    {
        return
            functionStaticCall(
                target,
                data,
                "Address: low-level static call failed"
            );
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data)
        internal
        returns (bytes memory)
    {
        return
            functionDelegateCall(
                target,
                data,
                "Address: low-level delegate call failed"
            );
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: Context.sol



// SPDX-License-Identifier: MIT

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: ERC165S.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC165S.sol";

/**
 * @dev Implementation of the {IERC165S} interface.
 *
 * Contracts that want to implement IERC165S 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 ERC165S is IERC165S {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId)
        public
        view
        virtual
        override
        returns (bool)
    {
        return interfaceId == type(IERC165S).interfaceId;
    }
}

// File: ERC721S.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC721S.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./Address.sol";
import "./Context.sol";
import "./Strings.sol";
import "./ERC165S.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721S] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721S is Context, ERC165S, IERC721S, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    // CUSTOM: Visible for child contract so it's possible to emulate methods of ERC721S's enumerable extension
    mapping(uint256 => address) internal _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

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

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev See {IERC721S-balanceOf}.
     */
    function balanceOf(address owner)
        public
        view
        virtual
        override
        returns (uint256)
    {
        require(
            owner != address(0),
            "ERC721S: balance query for the zero address"
        );
        return _balances[owner];
    }

    /**
     * @dev See {IERC721S-ownerOf}.
     */
    function ownerOf(uint256 tokenId)
        public
        view
        virtual
        override
        returns (address)
    {
        address owner = _owners[tokenId];
        require(
            owner != address(0),
            "ERC721S: owner query for nonexistent token"
        );
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId)
        public
        view
        virtual
        override
        returns (string memory)
    {
        require(
            _exists(tokenId),
            "ERC721Metadata: URI query for nonexistent token"
        );

        string memory baseURI = _baseURI();
        return
            bytes(baseURI).length > 0
                ? string(abi.encodePacked(baseURI, tokenId.toString()))
                : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721S-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721S.ownerOf(tokenId);
        require(to != owner, "ERC721S: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721S: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721S-getApproved}.
     */
    function getApproved(uint256 tokenId)
        public
        view
        virtual
        override
        returns (address)
    {
        require(
            _exists(tokenId),
            "ERC721: approved query for nonexistent token"
        );

        return _tokenApprovals[tokenId];
    }

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

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

    /**
     * @dev See {IERC721S-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(
            _isApprovedOrOwner(_msgSender(), tokenId),
            "ERC721S: transfer caller is not owner nor approved"
        );

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721S-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721S-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(
            _isApprovedOrOwner(_msgSender(), tokenId),
            "ERC721S: transfer caller is not owner nor approved"
        );
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721S protocol to prevent tokens from being forever locked.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(
            _checkOnERC721Received(from, to, tokenId, _data),
            "ERC721S: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId)
        internal
        view
        virtual
        returns (bool)
    {
        require(
            _exists(tokenId),
            "ERC721S: operator query for nonexistent token"
        );
        address owner = ERC721S.ownerOf(tokenId);
        return (spender == owner ||
            getApproved(tokenId) == spender ||
            isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721S-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721S: mint to the zero address");
        require(!_exists(tokenId), "ERC721S: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721S.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(
            ERC721S.ownerOf(tokenId) == from,
            "ERC721S: transfer from incorrect owner"
        );
        require(to != address(0), "ERC721S: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721S.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits a {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721S: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try
                IERC721Receiver(to).onERC721Received(
                    _msgSender(),
                    from,
                    tokenId,
                    _data
                )
            returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert(
                        "ERC721S: transfer to non ERC721Receiver implementer"
                    );
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` 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 tokenId
    ) 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.
     * - `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 tokenId
    ) internal virtual {}
}

// File: ERC721SBurnable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ERC721S.sol";
import "./Ownable.sol";

/**
 * @title ERC721S Burnable Token
 * @dev ERC721S Token that can be irreversibly burned (destroyed).
 */
abstract contract ERC721SBurnable is Ownable, ERC721S {
    /**
     * @dev Burns `tokenId`. See {ERC721-_burn}.
     *
     * Requirements:
     *
     * - The caller must own `tokenId` or be an approved operator.
     */
    function burn(uint256 tokenId) public virtual {
        //solhint-disable-next-line max-line-length
        require(
            _msgSender() == owner() ||
                _isApprovedOrOwner(_msgSender(), tokenId),
            "ERC721SBurnable: caller is not owner nor approved"
        );
        _burn(tokenId);
    }
}

// File: GoldStaking.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC721S.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
import "./Address.sol";
import "./IERC721Receiver.sol";

interface IRandomNumGenerator {
    function getRandomNumber(
        uint256 _seed,
        uint256 _limit,
        uint256 _random
    ) external view returns (uint16);
}

interface IStakingDevice {
    function getMultifier(uint16 tokenId) external view returns (uint8);
}

interface IAFF {
    function mint(address to, uint256 amount) external;
}

contract GoldStaking is Ownable, IERC721Receiver {
    using Address for address;

    struct NftInfo {
        uint256 lastClaimTime;
        uint256 penddingAmount;
        uint256 value;
    }

    struct TokenReward {
        uint16 id;
        uint256 reward;
        uint8 nftType;
        uint256 tax;
    }

    struct UserRewards {
        uint256 totalReward;
        TokenReward[] tokenRewards;
    }

    address private admin;

    uint256 public stakeStopTime;

    address public angryfrogAddress;
    address public deviceAddress;
    address public affAddress;
    address public randomGen;

    uint256 public stakedFrog;
    uint256 public stakedDevice;
    uint256 public totalClaimedToken;
    uint256 public totalStealedToken;

    uint256 public dailyRewardAmount = 3 * 10**18;
    uint8 private taxFeeOfCitizen = 30;
    uint8 private taxFeeOfGangster = 10;
    uint16[] private multifierValue = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];

    mapping(uint16 => NftInfo) public nftInfos;
    mapping(uint16 => uint8) public nftTypes; // 0: Citizen, 1: Gangster, 2: Business
    mapping(address => uint16[]) public stakers;
    mapping(address => uint16[]) public devices;

    address[] public businessHolders;
    address[] public gangsterHolders;
    uint256 public businessReward;
    uint256 public gangsterReward;

    bool public lastClaimStealed;

    event StakeDeivce(address indexed user, uint16[] tokenIds);
    event Stake(address indexed user, uint16[] tokenIds);
    event Claim(
        address indexed user,
        uint16[] tokenIds,
        uint256 amount,
        bool unstake
    );
    event WithdrawDevice(address indexed user, uint16[] tokenId);
    event Steal(address from, address to, uint256 amount, bool unstake);

    string public constant CONTRACT_NAME = "Gold Contract";
    bytes32 public constant DOMAIN_TYPEHASH =
        keccak256(
            "EIP712Domain(string name,uint256 chainId,address verifyingContract)"
        );

    bytes32 public constant STAKE_TYPEHASH =
        keccak256("Stake(address user,uint16[] tokenIds,uint8[] types)");

    constructor(address _admin) {
        admin = _admin;
    }

    function setContractAddress(
        address _randomGen,
        address _angryfrogAddress,
        address _deviceAddress,
        address _affAddress
    ) public onlyOwner {
        require(
            _randomGen != address(0) &&
                _angryfrogAddress != address(0) &&
                _deviceAddress != address(0) &&
                _affAddress != address(0),
            "Zero address."
        );
        randomGen = _randomGen;
        angryfrogAddress = _angryfrogAddress;
        deviceAddress = _deviceAddress;
        affAddress = _affAddress;
    }

    function setDailyTokenReward(
        uint256 _dailyRewardAmount,
        uint8 _taxFeeOfGangster,
        uint8 _taxFeeOfCitizen
    ) public onlyOwner {
        dailyRewardAmount = _dailyRewardAmount;
        taxFeeOfGangster = _taxFeeOfGangster;
        taxFeeOfCitizen = _taxFeeOfCitizen;
    }

    function getStakedFrogCounts()
        public
        view
        returns (
            uint256,
            uint256,
            uint256,
            uint256
        )
    {
        return (
            stakedFrog,
            businessHolders.length,
            gangsterHolders.length,
            stakedFrog - businessHolders.length - gangsterHolders.length
        );
    }

    function setStakeStop(bool _stop) public onlyOwner {
        if (_stop) {
            stakeStopTime = block.timestamp;
        } else {
            stakeStopTime = 0;
        }
    }

    function setMultifiers(uint16[] memory _mutifiers) public onlyOwner {
        for (uint8 i; i < 10; i++) {
            multifierValue[i] = _mutifiers[i];
        }
    }

    function getMultifierByDeviceId(uint16 deviceId)
        public
        view
        returns (uint16)
    {
        uint8 number = IStakingDevice(deviceAddress).getMultifier(deviceId);
        return multifierValue[number];
    }

    function getDailyRewardByTokenId(uint16 tokenId)
        public
        view
        returns (uint256)
    {
        if (nftTypes[tokenId] == 2) {
            return (dailyRewardAmount * 3) / 1440;
        } else if (nftTypes[tokenId] == 1) {
            return (dailyRewardAmount * 2) / 1440;
        } else {
            return dailyRewardAmount / 1440;
        }
    }

    function getRewardByTokenId(uint16 tokenId, address user)
        public
        view
        returns (uint256)
    {
        NftInfo memory nftInfo = nftInfos[tokenId];

        if (nftInfo.lastClaimTime == 0) {
            return 0;
        } else {
            uint16[] memory deviceIds = devices[user];
            uint16 _totalMultifier = 100;
            for (uint8 i; i < deviceIds.length; i++) {
                _totalMultifier =
                    _totalMultifier +
                    getMultifierByDeviceId(deviceIds[i]);
            }

            uint256 currentTime = stakeStopTime == 0
                ? block.timestamp
                : stakeStopTime;

            return
                nftInfo.penddingAmount +
                ((getDailyRewardByTokenId(tokenId) * _totalMultifier) / 100) *
                ((currentTime - nftInfo.lastClaimTime) / 1 minutes);
        }
    }

    function getDevices(address user) public view returns (uint16[] memory) {
        uint16[] memory deviceIds = devices[user];
        return deviceIds;
    }

    function getReward(address user) public view returns (UserRewards memory) {
        uint16[] memory tokenIds = stakers[user];

        uint256 _totalReward;

        TokenReward[] memory _tokenRewards = new TokenReward[](tokenIds.length);

        for (uint8 i; i < tokenIds.length; i++) {
            uint256 _available = getRewardByTokenId(tokenIds[i], user);
            uint256 _tax;

            if (nftTypes[tokenIds[i]] == 2) {
                _tax = businessReward - nftInfos[tokenIds[i]].value;
            } else if (nftTypes[tokenIds[i]] == 1) {
                _tax = gangsterReward - nftInfos[tokenIds[i]].value;
            }

            _totalReward = _totalReward + _available + _tax;

            _tokenRewards[i] = TokenReward({
                id: tokenIds[i],
                nftType: nftTypes[tokenIds[i]],
                reward: _available,
                tax: _tax
            });
        }

        UserRewards memory _userRewards = UserRewards({
            totalReward: _totalReward,
            tokenRewards: _tokenRewards
        });

        return _userRewards;
    }

    function stake(
        uint16[] memory tokenIds,
        uint8[] memory types,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public {
        require(stakeStopTime == 0, "Stake: Not started yet");
        require(tx.origin == msg.sender, "Only EOA");

        bytes32 domainSeparator = keccak256(
            abi.encode(
                DOMAIN_TYPEHASH,
                keccak256(bytes(CONTRACT_NAME)),
                getChainId(),
                address(this)
            )
        );
        bytes32 structHash = keccak256(
            abi.encode(
                STAKE_TYPEHASH,
                msg.sender,
                keccak256(abi.encodePacked(tokenIds)),
                keccak256(abi.encodePacked(types))
            )
        );
        bytes32 digest = keccak256(
            abi.encodePacked("\x19\x01", domainSeparator, structHash)
        );
        address signatory = ecrecover(digest, v, r, s);
        require(signatory == admin, "Invalid signatory");

        uint16[] storage staker = stakers[msg.sender];

        for (uint8 i; i < tokenIds.length; i++) {
            if (msg.sender != angryfrogAddress) {
                require(
                    IERC721S(angryfrogAddress).ownerOf(tokenIds[i]) ==
                        msg.sender,
                    "This NFT does not belong to address"
                );
                IERC721S(angryfrogAddress).transferFrom(
                    msg.sender,
                    address(this),
                    tokenIds[i]
                );
            }

            staker.push(tokenIds[i]);
            nftInfos[tokenIds[i]].lastClaimTime = block.timestamp;

            if (types[i] == 2) {
                nftTypes[tokenIds[i]] = 2;
                businessHolders.push(msg.sender);
                nftInfos[tokenIds[i]].value = businessReward;
            } else if (types[i] == 1) {
                nftTypes[tokenIds[i]] = 1;
                gangsterHolders.push(msg.sender);
                nftInfos[tokenIds[i]].value = gangsterReward;
            }
        }

        stakedFrog = stakedFrog + tokenIds.length;

        emit Stake(msg.sender, tokenIds);
    }

    function stakeDevice(address account, uint16[] memory deviceIds) public {
        require(stakeStopTime == 0, "Stake: Not starte yet");
        require(
            account == msg.sender || msg.sender == deviceAddress,
            "You do not have a permission to do that"
        );
        _tempClaimReward(account);

        uint16[] storage staker = stakers[account];
        uint16[] storage device = devices[account];
        require(
            staker.length >= device.length + deviceIds.length,
            "Stake: Device stake is limited."
        );

        for (uint8 i; i < deviceIds.length; i++) {
            if (msg.sender != deviceAddress) {
                require(
                    IERC721S(deviceAddress).ownerOf(deviceIds[i]) == msg.sender,
                    "This NFT does not belong to address"
                );
                IERC721S(deviceAddress).transferFrom(
                    msg.sender,
                    address(this),
                    deviceIds[i]
                );
            }
            device.push(deviceIds[i]);
        }

        stakedDevice = stakedDevice + deviceIds.length;
        emit StakeDeivce(account, deviceIds);
    }

    function _tempClaimReward(address account) internal {
        uint16[] memory tokenIds = stakers[account];
        for (uint8 i; i < tokenIds.length; i++) {
            uint256 available = getRewardByTokenId(tokenIds[i], account);
            if (available > 0) {
                nftInfos[tokenIds[i]].penddingAmount =
                    nftInfos[tokenIds[i]].penddingAmount +
                    available;
                nftInfos[tokenIds[i]].lastClaimTime = block.timestamp;
            }
        }
    }

    function _setNftInfo(uint16 tokenId) internal {
        nftInfos[tokenId].lastClaimTime = block.timestamp;
        nftInfos[tokenId].penddingAmount = 0;
    }

    function _resetNftInfo(uint16 tokenId) internal {
        nftInfos[tokenId].lastClaimTime = 0;
        nftInfos[tokenId].penddingAmount = 0;
    }

    function _existTokenId(address account, uint16 tokenId)
        internal
        view
        returns (bool, uint8)
    {
        uint16[] memory tokenIds = stakers[account];
        for (uint8 i; i < tokenIds.length; i++) {
            if (tokenIds[i] == tokenId) {
                return (true, i);
            }
        }
        return (false, 0);
    }

    function _existDeviceId(address account, uint16 tokenId)
        internal
        view
        returns (bool, uint8)
    {
        uint16[] memory tokenIds = devices[account];
        for (uint8 i; i < tokenIds.length; i++) {
            if (tokenIds[i] == tokenId) {
                return (true, i);
            }
        }
        return (false, 0);
    }

    function claimReward(
        uint16[] memory tokenIds,
        bool safe,
        bool unstake
    ) external {
        require(tx.origin == msg.sender, "Only EOA");

        for (uint8 i; i < tokenIds.length; i++) {
            (bool exist, ) = _existTokenId(msg.sender, tokenIds[i]);
            require(exist, "Not Your Own");
        }

        uint16[] storage staker = stakers[msg.sender];

        uint256 totalReward;
        uint256 totalBusinessReward;
        uint256 totalGangsterReward;
        uint256 totalCitizenReward;

        for (uint8 i; i < tokenIds.length; i++) {
            if (nftTypes[tokenIds[i]] == 2) {
                uint256 reward = _claimFromBusiness(tokenIds[i]);
                totalBusinessReward = totalBusinessReward + reward;

                if (unstake) {
                    uint256 indexOfHolder = 0;
                    for (uint256 j; j < businessHolders.length; j++) {
                        if (businessHolders[j] == msg.sender) {
                            indexOfHolder = j;
                            break;
                        }
                    }
                    businessHolders[indexOfHolder] = businessHolders[
                        businessHolders.length - 1
                    ];
                    businessHolders.pop();
                }
            } else if (nftTypes[tokenIds[i]] == 1) {
                uint256 reward = _claimFromGangster(tokenIds[i], safe);
                totalGangsterReward = totalGangsterReward + reward;

                if (unstake) {
                    uint256 indexOfHolder = 0;
                    for (uint256 j; j < gangsterHolders.length; j++) {
                        if (gangsterHolders[j] == msg.sender) {
                            indexOfHolder = j;
                            break;
                        }
                    }
                    gangsterHolders[indexOfHolder] = gangsterHolders[
                        gangsterHolders.length - 1
                    ];
                    gangsterHolders.pop();
                }
            } else {
                uint256 reward = _claimFromCitizen(tokenIds[i], safe);
                totalCitizenReward = totalCitizenReward + reward;
            }

            if (unstake) {
                _resetNftInfo(tokenIds[i]);
                (, uint8 index) = _existTokenId(msg.sender, tokenIds[i]);
                staker[index] = staker[staker.length - 1];
                staker.pop();

                IERC721S(angryfrogAddress).transferFrom(
                    address(this),
                    _msgSender(),
                    tokenIds[i]
                );
            } else {
                _setNftInfo(tokenIds[i]);
            }
        }

        totalReward =
            totalBusinessReward +
            totalGangsterReward +
            totalCitizenReward;
        totalClaimedToken = totalClaimedToken + totalReward;

        if (unstake) {
            stakedFrog = stakedFrog - tokenIds.length;
        }

        if (safe) {
            IAFF(affAddress).mint(msg.sender, totalReward);
            emit Claim(_msgSender(), tokenIds, totalReward, unstake);
        } else {
            address recipient = _selectRecipientFromGangster(totalReward);

            if (recipient != msg.sender) {
                totalStealedToken =
                    totalStealedToken +
                    totalGangsterReward +
                    totalCitizenReward;

                IAFF(affAddress).mint(
                    recipient,
                    totalGangsterReward + totalCitizenReward
                );
                lastClaimStealed = true;
                emit Steal(
                    msg.sender,
                    recipient,
                    totalGangsterReward + totalCitizenReward,
                    unstake
                );

                IAFF(affAddress).mint(recipient, totalBusinessReward);
                emit Claim(
                    _msgSender(),
                    tokenIds,
                    totalBusinessReward,
                    unstake
                );
            } else {
                lastClaimStealed = false;
                IAFF(affAddress).mint(recipient, totalReward);
                emit Claim(_msgSender(), tokenIds, totalReward, unstake);
            }
        }
    }

    function _claimFromCitizen(uint16 tokenId, bool safe)
        internal
        returns (uint256)
    {
        uint256 available = getRewardByTokenId(tokenId, msg.sender);
        if (safe) {
            uint256 _tax = (available * taxFeeOfCitizen) / 100;
            _payTaxForCitizen(_tax);
            return available - _tax;
        } else {
            return available;
        }
    }

    function _claimFromGangster(uint16 tokenId, bool safe)
        internal
        returns (uint256)
    {
        uint256 available = getRewardByTokenId(tokenId, msg.sender);
        uint256 taxReward = gangsterReward - nftInfos[tokenId].value;
        nftInfos[tokenId].value = gangsterReward;

        if (safe) {
            uint256 _tax = ((available + taxReward) * taxFeeOfGangster) / 100;
            _payTaxForGangster(_tax);
            return (available + taxReward) - _tax;
        } else {
            return (available + taxReward);
        }
    }

    function _claimFromBusiness(uint16 tokenId) internal returns (uint256) {
        uint256 available = getRewardByTokenId(tokenId, msg.sender);
        uint256 taxReward = businessReward - nftInfos[tokenId].value;
        nftInfos[tokenId].value = businessReward;

        return (available + taxReward);
    }

    function withdrawDevice(uint16[] memory deviceIds) external {
        require(tx.origin == msg.sender, "Only EOA");

        for (uint8 i; i < deviceIds.length; i++) {
            (bool exist, ) = _existDeviceId(msg.sender, deviceIds[i]);
            require(exist, "Not Your Own");
        }
        _tempClaimReward(msg.sender);

        uint16[] storage device = devices[msg.sender];

        for (uint8 i; i < deviceIds.length; i++) {
            (, uint8 index) = _existDeviceId(msg.sender, deviceIds[i]);
            device[index] = device[device.length - 1];
            device.pop();

            IERC721S(deviceAddress).transferFrom(
                address(this),
                _msgSender(),
                deviceIds[i]
            );
        }

        stakedDevice = stakedDevice - deviceIds.length;
        emit WithdrawDevice(_msgSender(), deviceIds);
    }

    function _payTaxForCitizen(uint256 _amount) internal {
        uint256 _amountForGangster = _amount / 3;
        uint256 _amountForBusiness = _amount - _amountForGangster;

        if (businessHolders.length != 0) {
            businessReward += _amountForBusiness / businessHolders.length;
        }
        if (gangsterHolders.length != 0) {
            gangsterReward += _amountForGangster / gangsterHolders.length;
        }
    }

    function _payTaxForGangster(uint256 _amount) internal {
        if (businessHolders.length != 0) {
            businessReward += _amount / businessHolders.length;
        }
    }

    function _selectRecipient(uint256 seed) private view returns (address) {
        if (
            IRandomNumGenerator(randomGen).getRandomNumber(
                businessHolders.length + seed,
                100,
                block.timestamp
            ) >= 10
        ) {
            return msg.sender;
        }

        address thief = randomBusinessOwner(businessHolders.length + seed);
        if (thief == address(0x0)) {
            return msg.sender;
        }
        return thief;
    }

    function _selectRecipientFromGangster(uint256 seed)
        private
        view
        returns (address)
    {
        if (
            IRandomNumGenerator(randomGen).getRandomNumber(
                gangsterHolders.length + seed,
                100,
                block.timestamp
            ) >= 10
        ) {
            return msg.sender;
        }

        address thief = randomGangsterOwner(gangsterHolders.length + seed);
        if (thief == address(0x0)) {
            return msg.sender;
        }
        return thief;
    }

    function randomBusinessOwner(uint256 seed) public view returns (address) {
        if (businessHolders.length == 0) return address(0x0);

        uint256 holderIndex = IRandomNumGenerator(randomGen).getRandomNumber(
            businessHolders.length + seed,
            businessHolders.length,
            block.timestamp
        );

        return businessHolders[holderIndex];
    }

    function randomGangsterOwner(uint256 seed) public view returns (address) {
        if (gangsterHolders.length == 0) return address(0x0);

        uint256 holderIndex = IRandomNumGenerator(randomGen).getRandomNumber(
            gangsterHolders.length + seed,
            gangsterHolders.length,
            block.timestamp
        );

        return gangsterHolders[holderIndex];
    }

    function onERC721Received(
        address,
        address from,
        uint256,
        bytes calldata
    ) external pure override returns (bytes4) {
        require(from == address(0x0), "Cannot send tokens to Barn directly");
        return IERC721Receiver.onERC721Received.selector;
    }

    function getChainId() internal view returns (uint256) {
        uint256 chainId;
        assembly {
            chainId := chainid()
        }
        return chainId;
    }
}

// File: IERC165S.sol



// SPDX-License-Identifier: MIT

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 IERC165S {
    /**
     * @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: IERC721Metadata.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC721S.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721S {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// File: IERC721Receiver.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @title ERC721S token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721S asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721S} `tokenId` token is transferred to this contract via {IERC721S-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721S.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: IERC721S.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC165S.sol";

/**
 * @dev Required interface of an ERC721S compliant contract.
 */
interface IERC721S is IERC165S {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(
        address indexed from,
        address indexed to,
        uint256 indexed tokenId
    );

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(
        address indexed owner,
        address indexed approved,
        uint256 indexed tokenId
    );

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(
        address indexed owner,
        address indexed operator,
        bool approved
    );

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721S protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId)
        external
        view
        returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator)
        external
        view
        returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

// File: Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./Context.sol";

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

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

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

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

// File: SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b)
        internal
        pure
        returns (bool, uint256)
    {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b)
        internal
        pure
        returns (bool, uint256)
    {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b)
        internal
        pure
        returns (bool, uint256)
    {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b)
        internal
        pure
        returns (bool, uint256)
    {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b)
        internal
        pure
        returns (bool, uint256)
    {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

// File: StakingDevice.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ERC721SBurnable.sol";
import "./SafeMath.sol";
import "./IERC721S.sol";

interface IRandomNumGenerator {
    function getRandomNumber(
        uint256 _seed,
        uint256 _limit,
        uint256 _random
    ) external view returns (uint16);
}

interface IAFF {
    function burn(address from, uint256 amount) external;
}

interface IGoldStaking {
    function stakeDevice(address owner, uint16[] memory tokenIds) external;

    function randomBusinessOwner(uint256 seed) external view returns (address);
}

/**
 * @title StakingDevice Contract
 * @dev Extends ERC721S Non-Fungible Token Standard basic implementation
 */
contract StakingDevice is ERC721SBurnable {
    using SafeMath for uint256;

    string public baseTokenURI;
    uint16 private mintedCount;
    uint16 public MAX_SUPPLY;

    uint256 public mintPrice;
    uint16 public maxByMint;

    address public stakingAddress;
    address public tokenAddress;
    IRandomNumGenerator randomGen;

    mapping(uint16 => uint8) private multifiers;

    event Steel(address from, address to, uint16 tokenId);

    constructor() ERC721S("Staking Device", "GPU") {
        MAX_SUPPLY = 10000;
        mintPrice = 450 ether;
        maxByMint = 20;
    }

    function setMintPrice(uint256 newMintPrice) external onlyOwner {
        mintPrice = newMintPrice;
    }

    function setMaxByMint(uint16 newMaxByMint) external onlyOwner {
        maxByMint = newMaxByMint;
    }

    function setMaxSupply(uint16 _max_supply) external onlyOwner {
        MAX_SUPPLY = _max_supply;
    }

    function setContractAddress(
        address _stakingAddress,
        address _tokenAddress,
        IRandomNumGenerator _randomGen
    ) external onlyOwner {
        stakingAddress = _stakingAddress;
        tokenAddress = _tokenAddress;
        randomGen = _randomGen;
    }

    function setBaseURI(string memory baseURI) external onlyOwner {
        baseTokenURI = baseURI;
    }

    function _baseURI() internal view virtual override returns (string memory) {
        return baseTokenURI;
    }

    function getMultifier(uint16 tokenId) public view returns (uint8) {
        return multifiers[tokenId];
    }

    function getMultifiers(uint16[] memory tokenIds)
        public
        view
        returns (uint8[] memory)
    {
        uint8[] memory _multifiers = new uint8[](tokenIds.length);
        for (uint8 i; i < tokenIds.length; i++) {
            _multifiers[i] = multifiers[tokenIds[i]];
        }
        return _multifiers;
    }

    function exists(uint256 _tokenId) public view returns (bool) {
        return _exists(_tokenId);
    }

    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        // Hardcode the Manager's approval so that users don't have to waste gas approving
        if (_msgSender() != stakingAddress)
            require(
                _isApprovedOrOwner(_msgSender(), tokenId),
                "ERC721S: transfer caller is not owner nor approved"
            );
        _transfer(from, to, tokenId);
    }

    function totalSupply() public view virtual returns (uint256) {
        return mintedCount;
    }

    function getTokensOfOwner(address owner)
        public
        view
        returns (uint256[] memory)
    {
        uint256 tokenCount = balanceOf(owner);
        uint256 supply = totalSupply();

        if (tokenCount == 0) {
            return new uint256[](0);
        } else {
            uint256[] memory result = new uint256[](tokenCount);
            uint256 resultIndex = 0;
            uint256 tokenId;

            for (tokenId = 0; tokenId < supply; tokenId++) {
                if (_owners[tokenId] == owner) {
                    result[resultIndex] = tokenId;
                    resultIndex++;
                    if (resultIndex >= tokenCount) {
                        break;
                    }
                }
            }
            return result;
        }
    }

    function _getRandom(uint256 _tokenId) public view returns (uint8) {
        uint256 random = randomGen.getRandomNumber(
            _tokenId,
            100,
            totalSupply()
        );

        if (random >= 99) {
            return 9;
        } else if (random >= 97) {
            return 8;
        } else if (random >= 93) {
            return 7;
        } else if (random >= 87) {
            return 6;
        } else if (random >= 80) {
            return 5;
        } else if (random >= 71) {
            return 4;
        } else if (random >= 61) {
            return 3;
        } else if (random >= 50) {
            return 2;
        } else if (random >= 37) {
            return 1;
        } else {
            return 0;
        }
    }

    function mintByUser(
        uint8 _numberOfTokens,
        uint256 _amount,
        bool _stake
    ) external {
        require(tx.origin == msg.sender, "Only EOA");
        require(
            totalSupply() + _numberOfTokens <= MAX_SUPPLY,
            "Max Limit To Presale"
        );
        require(_numberOfTokens <= maxByMint, "Exceeds Amount");

        require(mintPrice.mul(_numberOfTokens) <= _amount, "Low Price To Mint");

        IAFF(tokenAddress).burn(msg.sender, _amount);

        uint16[] memory tokenIds = _stake
            ? new uint16[](_numberOfTokens)
            : new uint16[](0);

        for (uint8 i = 0; i < _numberOfTokens; i += 1) {
            address recipient = _selectRecipient(i);
            uint16 tokenId = uint16(totalSupply() + i);

            uint8 randomNumber = _getRandom(tokenId);
            multifiers[tokenId] = randomNumber;

            if (recipient != msg.sender) {
                emit Steel(msg.sender, recipient, tokenId);
            }

            if (_stake && recipient == msg.sender) {
                tokenIds[i] = tokenId;
                _safeMint(stakingAddress, tokenId);
            } else {
                _safeMint(msg.sender, tokenId);
            }
        }
        mintedCount = mintedCount + _numberOfTokens;

        if (_stake && tokenIds.length > 0) {
            IGoldStaking(stakingAddress).stakeDevice(msg.sender, tokenIds);
        }
    }

    function _selectRecipient(uint256 seed) private view returns (address) {
        if (
            randomGen.getRandomNumber(
                totalSupply() + seed,
                100,
                totalSupply()
            ) >= 10
        ) {
            return msg.sender;
        }

        address thief = IGoldStaking(stakingAddress).randomBusinessOwner(
            totalSupply() + seed
        );
        if (thief == address(0x0)) {
            return msg.sender;
        }
        return thief;
    }
}

// File: Strings.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

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