// File: contracts/NISTRelayer.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.6;
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/math/Math.sol";
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@uniswap/lib/contracts/libraries/TransferHelper.sol';
import './interfaces/Staking/INitroStaking.sol';
import './interfaces/Chainlink/IChainLinkFeed.sol';
import './interfaces/Relayer/IKeep3rV1Mini.sol';

contract NISTRelayer is Ownable {
    using SafeMath for uint256;
    //Params for reward bonus and interval
    uint256 public distributeInterval = 2 hours;
    //Requirements for the relayer executing
    uint public minBond = 500 ether;
    uint public minEarned = 0;
    uint public minAge = 0;
    //Amount of users to reward each cycle
    uint256 public stakersPerRun = 10;

    uint internal _gasUsed;

    uint constant public MIN = 11;
    uint constant public MAX = 12;
    uint constant public BASE = 10;
    uint public TARGETBOND = 2500 ether;

    IKeep3rV1Mini public RLR;
    INitroStaking public NIST;
    IChainLinkFeed public FASTGAS;

    constructor(address nisttoken, address rlrtoken, address gasoracle) public {
        RLR     = IKeep3rV1Mini(rlrtoken);
        NIST    = INitroStaking(nisttoken);
        FASTGAS = IChainLinkFeed(gasoracle);
    }

    receive() external payable {}

    function bonds(address keeper) public view returns (uint) {
        return RLR.bonds(keeper, address(RLR)).add(RLR.votes(keeper));
    }

    function calculateReward(uint __gasUsed,address origin,uint _gasPrice) public view returns (uint){
        uint _quote = (__gasUsed).mul(uint(_gasPrice));
        // console.log("Gas used : %s",__gasUsed);
        // console.log("Gas price : %s",_gasPrice);
        uint _min = _quote.mul(MIN).div(BASE);
        uint _boost = _quote.mul(MAX).div(BASE);
        uint _bond = Math.min(bonds(origin), TARGETBOND);
        return Math.max(_min, _boost.mul(_bond).div(TARGETBOND));
    }

    modifier upkeep() {
        _gasUsed = gasleft();
        // console.log(msg.sender);
        require(RLR.isMinKeeper(msg.sender, minBond, minEarned, minAge), "::isKeeper: relayer is not registered");
        _;
        uint gasPrice = Math.min(tx.gasprice, uint(FASTGAS.latestAnswer()));
        uint gasUsed = _gasUsed.sub(gasleft());
        //reward gas spent with 10% bonus as incentive
        uint keeperFee = calculateReward(gasUsed,msg.sender,gasPrice);
        // console.log(keeperFee);
        // console.log(RLR.credits(address(this), RLR.ETH()));
        require(keeperFee <= RLR.credits(address(this), RLR.ETH()),"Not enough ETH to pay back gas");
        //Reward relayer in eth
        RLR.receiptETH(msg.sender, keeperFee);
        uint256 newCreditbal = RLR.credits(address(this), RLR.ETH());
        //If we still have excess after paying the keeperfee,send it back to the nist contract
        // if(newCreditbal > 0)  RLR.receiptETH(address(NIST),newCreditbal);
    }

    // Change requirements and rewards
    function setDistributeInterval(uint256 newInterval) external onlyOwner {
        distributeInterval = newInterval;
    }

    function setMinBond(uint newminbond) external onlyOwner {
        minBond = newminbond;
    }

    function setTargetBond(uint newTarget) external onlyOwner {
        TARGETBOND = newTarget;
    }

    function setMinEarned(uint newMinEarned) external onlyOwner {
        minEarned = newMinEarned;
    }

    function setMinAge(uint newAge) external onlyOwner {
        minAge = newAge;
    }

    function setStakersPerRun(uint256 newCount) external onlyOwner {
        stakersPerRun = newCount;
    }

    function workable() public view returns (bool) {
        (address[] memory addrs,) = getData();
        return
         addrs.length > 0
         &&
         block.timestamp > NIST.previousRewardDistributionTimestamp().add(distributeInterval);
    }

    //Use this function to get data to pass to work
    function getData() public view returns (address[] memory eligible_addresses, uint256 total_reward){
        (eligible_addresses,total_reward) = NIST.getEligibleAddressesForAutomaticPayout(stakersPerRun);
    }
    function work(address[] memory stakers, uint256 tokens_to_liquidate) public upkeep {
        NIST.processAutoRewardPayouts(stakers,tokens_to_liquidate);
    }
}
// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

import "../GSN/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 () internal {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view 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: @openzeppelin/contracts/math/Math.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

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

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

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow, so we distribute
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }
}

// File: @openzeppelin/contracts/math/SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @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) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");

        return c;
    }

    /**
     * @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 sub(a, b, "SafeMath: subtraction overflow");
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        uint256 c = a - b;

        return c;
    }

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

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts 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) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts 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 mod(a, b, "SafeMath: modulo by zero");
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) {
        require(b != 0, errorMessage);
        return a % b;
    }
}

// File: @uniswap/lib/contracts/libraries/TransferHelper.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.0;

// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeApprove: approve failed'
        );
    }

    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::safeTransfer: transfer failed'
        );
    }

    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
        require(
            success && (data.length == 0 || abi.decode(data, (bool))),
            'TransferHelper::transferFrom: transferFrom failed'
        );
    }

    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
    }
}

// File: contracts/interfaces/Staking/INitroStaking.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.6;
//Interface to staking data for relayer job
interface INitroStaking {
  function RelayerJob (  ) external view returns ( address );
  function _stakes ( address ) external view returns ( uint256 stake, uint256 S_init );
  function eth_output_per_second (  ) external view returns ( uint256 );
  function minimumAutoPayoutBalance (  ) external view returns ( uint256 );
  function minimumRewardBalance (  ) external view returns ( uint256 );
  function previousRewardDistributionTimestamp (  ) external view returns ( uint256 );
  function remainingETHToAllocate (  ) external view returns ( uint256 );
  function maxSellRemoval (  ) external view returns ( uint256 );
  function maxBuyBonus (  ) external view returns ( uint256 );
  function stakeHolders (  ) external view returns ( address[] memory);
  function totalStakes (  ) external view returns ( uint256 );
  function totalUnclaimedRewards (  ) external view returns ( uint256 );
  function getEligibleAddressesForAutomaticPayout ( uint256 numToFind ) external view returns ( address[] memory eligible_addresses, uint256 total_reward);
  function getNextEligibleAddressForAutomaticPayout (  ) external view returns ( address );
  function isStakeholder ( address _address ) external view returns ( bool, uint256 );
  function stakeOf ( address _stakeholder ) external view returns ( uint256 );
  function calculateReward ( address _stakeholder ) external view returns ( uint256 );
  function approximateETHPerNISTOutput (  ) external view returns ( uint256 );
  function claimRewards ( address _stakeholder ) external;
  function processAutoRewardPayouts ( address[] calldata stakers, uint256 tokens_to_liquidate) external;
}
// File: contracts/interfaces/Chainlink/IChainLinkFeed.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.6.6;

interface IChainLinkFeed {
    function latestAnswer() external view returns (int256);
}
// File: contracts/interfaces/Relayer/IKeep3rV1Mini.sol



//SPDX-License-Identifier: MIT

pragma solidity ^0.6.6;
interface IKeep3rV1Mini {
    function isKeeper(address) external returns (bool);
    function worked(address keeper) external;
    function totalBonded() external view returns (uint);
    function bonds(address keeper, address credit) external view returns (uint);
    function votes(address keeper) external view returns (uint);
    function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool);
    function addCreditETH(address job) external payable;
    function credits(address job, address credit) external view returns (uint);
    function receipt(address credit, address keeper, uint amount) external;
    function ETH() external view returns (address);
    function receiptETH(address keeper, uint amount) external;
    function addJob(address job) external;
    function mint(uint amount) external;
    function bond(address bonding, uint amount) external;
    function activate(address bonding) external;
}
// File: @openzeppelin/contracts/GSN/Context.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <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 GSN 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 payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}