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



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

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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: @openzeppelin/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.20;

/**
 * @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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

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

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

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

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

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

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

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

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

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

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

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

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

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @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: contracts/StakingContract.sol



//SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

//import "hardhat/console.sol";
import "./interfaces/INFTContract.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract StakingContract is Ownable {

    event Staked(uint256[] ids, address owner);
    event Unstaked(uint256[] ids, address owner);
    event Halved(uint256 newRewardsPerBlock, address operator);
    event Claimed(address owner, uint256 amount);

    uint256 constant startingRewardPerBlock = 50 * 10 ** 18;
    uint256 constant halvingInterval = 2100000;
    uint256 constant thresholdHR = 21000;

    INFTContract immutable nftProvider;
    IERC20 immutable token;
    address operator;

    mapping(uint256 => uint256) totalRewardPerHRatBlock;

    mapping(uint256 => address) public owners;
    mapping(uint256 => uint256) startBlock;
    mapping(uint256 => uint256) hrs;

    mapping(address => uint256) public userHR;
    mapping(address => uint256) public claimed;
    mapping(address => uint256) rewardAcc;
    mapping(address => uint256) lastUpdateBlock;

    uint256 public currentActiveHR;
    uint256 public currentRewardsPerBlock;
    uint256 public nextHalvingTS;

    mapping(address => int256) public nftAmounts;

    int256 public nftStaked;
    uint256 public uniqStakers;
    uint256 public totalClaimed;

    uint256 lastChangedRewardBlock;
    uint256 totalMintedintedBeforeHalving;

    uint256 currentRewardsPerBHR;
    uint256 lastProcessedBlock;
    uint256 tokenBalance;

    constructor(
        address _initialOwner,
        address _nftProvider,
        address _token
    ) Ownable(_initialOwner) {
        token = IERC20(_token);
        nftProvider = INFTContract(_nftProvider);
        tokenBalance = token.balanceOf(address(this));
    }

    function getEarnedByVMM(uint256 id) public view returns (uint256) {
        return hrs[id] * (_currentTotalPerHR() - totalRewardPerHRatBlock[startBlock[id]]);
    }

    function getAvailableForClaim(address user) public view returns (uint256) {
        return getTotalReward(user) - getClaimed(user);
    }

    function getClaimed(address user) public view returns (uint256) {
        return claimed[user];
    }

    function getTotalReward(address user) public view returns (uint256) {
        return rewardAcc[user] + userHR[user] * (_currentTotalPerHR() - totalRewardPerHRatBlock[lastUpdateBlock[user]]);
    }

    function getAverageRewardPerBlock(address user) public view returns (uint256){
        uint256 bn = block.number;
        uint256 delta = bn - lastProcessedBlock;
        uint256 balance = token.balanceOf(address(this));
        uint256 feeIncome = balance - tokenBalance;
        return (userHR[user] * currentRewardsPerBHR) + (userHR[user] * feeIncome) / (delta * currentActiveHR);
    }

    function getMinted() public view returns (uint256){
        return totalMintedintedBeforeHalving + (block.number - lastChangedRewardBlock) * currentRewardsPerBlock;
    }

    function getRemainingBlockReward() public view returns (uint256){
        return 2 * startingRewardPerBlock * halvingInterval - getMinted();
    }

    function claim() public {
        address user = msg.sender;
        _updateRewards();
        _updateUser(user, 0);
        uint256 amount = rewardAcc[user] - claimed[user];
        claimed[user] += amount;
        totalClaimed += amount;
        tokenBalance -= amount;
        token.transfer(user, amount);
        emit Claimed(user, amount);
    }

    function stake(uint256[] memory ids) public {
        address receiver = nftProvider.ownerOf(ids[0]);
        require(
            receiver == msg.sender || operator == msg.sender,
            "E01: Only owner or operator allowed to stake"
        );
        uint8 len = uint8(ids.length);
        uint256 totalHR;
        uint256 bn = block.number;

        _updateRewards();
        _updateUser(receiver, int8(len));

        for (uint8 i = 0; i < len; ++i) {
            uint256 id = ids[i];
            address nftOwner = nftProvider.ownerOf(id);
            require(
                nftOwner == receiver,
                "E02: All VMMs staked within one request should have same owner"
            );
            require(startBlock[id] == 0, "E03: VMM already staked");
            owners[id] = nftOwner;
            uint256 hr = nftProvider.nftHashrate(id);
            totalHR += hr;
            hrs[id] = hr;
            startBlock[id] = bn;
        }

        userHR[receiver] += totalHR;
        uint256 newHR = currentActiveHR + totalHR;
        if ((currentRewardsPerBlock == 0) && (newHR >= thresholdHR)) {
            currentRewardsPerBlock = startingRewardPerBlock;
            nextHalvingTS = bn + halvingInterval;
            lastChangedRewardBlock = bn;
        }
        currentActiveHR = newHR;
        currentRewardsPerBHR = currentRewardsPerBlock / newHR;

        emit Staked(ids, receiver);
    }

    function unstake(uint256[] memory ids) public {
        address staker = owners[ids[0]];
        require(
            staker == msg.sender || operator == msg.sender,
            "E04: Only owner or operator allowed to unstake"
        );
        uint8 len = uint8(ids.length);
        uint256 totalHR;

        _updateRewards();
        _updateUser(staker, - int8(len));

        for (uint8 i = 0; i < len; ++i) {
            uint256 id = ids[i];
            require(startBlock[id] != 0, "E05: VMM is not staked");
            require(owners[id] == staker, "E06: All VMMs unstaked within one request should have same owner");
            totalHR += hrs[id];
            startBlock[id] = 0;
            hrs[id] = 0;
            owners[id] = address(0);
        }

        userHR[staker] -= totalHR;
        uint256 updatedActiveHR = currentActiveHR - totalHR;
        require(updatedActiveHR > 0, "E07: Last VMM could not be unstaked");
        currentActiveHR = updatedActiveHR;
        currentRewardsPerBHR = currentRewardsPerBlock / updatedActiveHR;

        emit Unstaked(ids, staker);
    }

    function restakeOnSell(uint256 id, address newOwner) public {
        require(startBlock[id] != 0, "E08: VMM is not staked");
        require(
            operator == msg.sender,
            "E09: Only operator allowed to restake"
        );

        _updateRewards();
        address nftOwner = owners[id];
        uint256 bn = block.number;
        uint256 hr = hrs[id];

        _updateUser(newOwner, 1);
        _updateUser(nftOwner, - 1);

        startBlock[id] = bn;

        userHR[nftOwner] -= hr;
        userHR[newOwner] += hr;

        owners[id] = newOwner;

        uint256[] memory t = new uint256[](1);
        t[0] = id;
        emit Unstaked(t, nftOwner);
        emit Staked(t, newOwner);
    }

    function halve() public {
        if ((block.number > nextHalvingTS) && (currentRewardsPerBlock != 0)) {
            _updateRewards();
            totalMintedintedBeforeHalving += (block.number - lastChangedRewardBlock) * currentRewardsPerBlock;
            lastChangedRewardBlock = block.number;
            nextHalvingTS = block.number + halvingInterval;
            currentRewardsPerBlock = currentRewardsPerBlock / 2;
            currentRewardsPerBHR = currentRewardsPerBlock / currentActiveHR;
            emit Halved(currentRewardsPerBlock, msg.sender);
        }
    }

    function setOperator(address _operator) public {
        _checkOwner();
        operator = _operator;
    }

    function _currentTotalPerHR() private view returns (uint256) {
        return
            totalRewardPerHRatBlock[lastProcessedBlock] +
            ((block.number - lastProcessedBlock) * currentRewardsPerBHR) +
            ((token.balanceOf(address(this)) - tokenBalance) / currentActiveHR);
    }

    function _updateRewards() private {
        unchecked {
            uint256 bn = block.number;
            uint256 delta = bn - lastProcessedBlock;
            uint256 balance = token.balanceOf(address(this));
            uint256 feeIncome = balance - tokenBalance;
            uint256 _currentActiveHR = currentActiveHR;
            uint256 feePerHR;
        // solhint-disable-next-line no-inline-assembly
            assembly {
            // black Solidity magic :)
                feePerHR := div(feeIncome, _currentActiveHR)
            }
            uint256 totalReward = totalRewardPerHRatBlock[lastProcessedBlock] +
                delta *
                currentRewardsPerBHR +
                        feePerHR;
            totalRewardPerHRatBlock[bn] = totalReward;
            lastProcessedBlock = bn;
            tokenBalance = balance;
        }
    }

    function _updateUser(address user, int8 amount) private {

        uint256 bn = block.number;
        rewardAcc[user] +=
            userHR[user] *
            (totalRewardPerHRatBlock[bn] -
                totalRewardPerHRatBlock[lastUpdateBlock[user]]);
        lastUpdateBlock[user] = bn;
        if (amount != 0) {
            nftStaked += amount;
            int256 oldAmount = nftAmounts[user];
            int256 newAmount = oldAmount + amount;
            if (oldAmount == 0) {
                ++uniqStakers;
            } else if (newAmount == 0) {
                --uniqStakers;
            }
            nftAmounts[user] = newAmount;
        }
    }
}

// File: contracts/interfaces/INFTContract.sol



//SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

interface INFTContract is IERC721 {
    function nftHashrate(uint256 _tokenId) external view returns (uint16);
}