// File: Address.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.2;

/**
 * @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) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            codehash := extcodehash(account)
        }
        return (codehash != accountHash && codehash != 0x0);
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (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');
        return _functionCallWithValue(target, data, value, errorMessage);
    }

    function _functionCallWithValue(
        address target,
        bytes memory data,
        uint256 weiValue,
        string memory errorMessage
    ) private returns (bytes memory) {
        require(isContract(target), 'Address: call to non-contract');

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{value: weiValue}(data);
        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

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: AggregatorV3Interface.sol



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

interface AggregatorV3Interface {

  function decimals() external view returns (uint8);
  function description() external view returns (string memory);
  function version() external view returns (uint256);

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

}

// File: BtclSeedRound.sol



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

import "./Context.sol";
import "./ERC677Receiver.sol";
import "./ERC677.sol";
import "./SafeERC677.sol";
import "./IERC677.sol";
import "./ReentrancyGuard.sol";
import "./Address.sol";
import "./IWETH.sol";
import "./SafeMathChainlink.sol";
import "./AggregatorV3Interface.sol";

contract BtclSeedRound is Context, ReentrancyGuard {
    using SafeMathChainlink for uint256;
    using SafeERC677 for IERC677;

    event TokensPurchased(address purchaser, uint256 btclAmount, uint256 usdAmount);
    event DepositedTokens(address from, uint256 value, bytes data);

    IERC677 public btclToken;
    address payable public wallet;
    address payable public bonus;
    address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
    address  DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    
    struct UserInfo {
        uint256 totalLockedBTCL;      // Total BTCL Tokens left to be released
        uint256 totalClaimedBTCL;     // Total BTCL Tokens Claimed 
        uint256 totalUSDContributed;  // Total USD Contribution in decimals
        uint256 totalContributions;   // Total Unique Contributions
        uint256 lastRewardBlock;      // Last Block when Tokens were Claimed
    }
    
    struct UserContribution {
        address token;                // Individual Token Address
        uint256 time;                 // Individual Contribution Timestamp
        uint256 tokenInUSD;           // Individual Token USD Value
        uint256 tokenAmount;          // Individual Token Contribution
        uint256 btclToDistribute;     // Individual BTCL Tokens to be distributed
    }

    uint256 public kycUsdLimit = 1500000;       // Max Contribution $15K with 2 extra decimals for precision
    uint256 public kycLimitUplifted = 5000000;  // Max Contribution $50K with 2 extra decimals for precision
    uint256 public startBlock = 13656111;       // https://etherscan.io/block/countdown/13656111 (~21 Nov 2021 UTC = 04:00AM)
    uint256 public endBlock = 13915000;         // https://etherscan.io/block/countdown/13915000 (~1 Jan 2022 UTC = 00:00AM)
    uint256 public cliffEndingBlock = 14777777; // https://etherscan.io/block/countdown/14777777 (~15 May 2022 UTC = 00:00AM)
    uint256 public blocksPerMonth = 200000;
    uint256 public btclDistributed;
    uint256 public totalRaised;
    uint256 public totalBtclClaimed;
    uint256 public uniqueContributors;
    uint256 public uniqueContributions;
    uint256[12] public vestingSchedules;
    uint256[12] public vestingPercentages = [24,5,5,5,5,5,5,5,5,12,12,12];
    
    mapping(uint256 => address) public uniqueAddress;
    mapping(address => bool) private isUnique;
    mapping(address => bool) private kyc;
    mapping(address => bool) private kycUplifted;
    mapping(address => UserInfo) public userInfo;
    mapping(address => mapping(uint256 => UserContribution)) public userContribution;
    mapping(address => mapping(uint256 => uint256)) public totalBTCL;
    mapping(address => address) public tokensAndFeeds;

    /**
     * @dev Team Multisig Wallet Modifier
     */
    modifier onlyTeam() {
        require(wallet == _msgSender(), "Only the team wallet can run this function");
        _;
    }
    
    /*
     * Bitcoin Lottery - Seed Round
     * @param _assets the list of accepted tokens
     * @param _priceOracles the list of price feeds
     */
    constructor(IERC677[] memory _assets, address[] memory _priceOracles) public {
        wallet = _msgSender();
        
        for(uint256 i = 0; i < _priceOracles.length; i++) {
            tokensAndFeeds[address(_assets[i])] = _priceOracles[i];
        }
        
        for(uint256 i = 0; i < vestingPercentages.length; i++) {
            vestingSchedules[i] = cliffEndingBlock.add(blocksPerMonth.mul(i));
        }
    }

    /*
     * Aggregate the value for whitelisted tokens.
     * @param _asset the token to be contributed.
     * @param _amount the amount of the token contribution.
     * @return totalUSD and toContribute and toDistribute 
     */
    function getTokenExchangeRate(address _asset, uint256 _amount) public view returns (uint256 totalUSD, uint256 toContribute, uint256 toDistribute) {
        if(_asset == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { _asset = WETH; } // eth price feed fix
        else { require(tokensAndFeeds[_asset] != address(0), "Asset must be whitelisted"); } // other whitelisted asset price feeds
        
        (, int256 price_token, , , ) = AggregatorV3Interface(tokensAndFeeds[_asset]).latestRoundData();
        (, int256 price_dai, , , ) = AggregatorV3Interface(tokensAndFeeds[DAI]).latestRoundData();

        toContribute = _amount;
        
        if(_asset == USDT || _asset == USDC) {
            totalUSD = _amount.div(10000); // with 2 extra decimals
            toDistribute = totalUSD.mul(666666666666666666); // 0,66 BTCL for 1 cent
        } else if (_asset == DAI) {
            totalUSD = _amount.div(10000000000000000); // with 2 extra decimals
            toDistribute = totalUSD.mul(666666666666666666); // 0,66 BTCL for 1 cent
        } else {
            uint256 tokenDecimals = uint256(10 ** uint256(IERC677(_asset).decimals()));
            uint256 tokenValueInUSD = uint256(price_token).div(uint256(price_dai));
            uint256 tokenOneDollarWorth = tokenDecimals.div(tokenValueInUSD);
            totalUSD = _amount.mul(100).div(tokenOneDollarWorth); // with 2 extra decimals
            toDistribute = totalUSD.mul(666666666666666666); // 0.66 BTCL for 1 cent
        }
    }
    
    /**
     * @dev Contribute with ETH directly
     */
    receive() external payable {
        buyTokensWithETH(_msgSender());
    }

    /*
     * Contribute with ETH directly.
     * @param _beneficiary the contributors address.
     * @return success Contribution succeeded or failed.
     */
    function buyTokensWithETH(address _beneficiary) public payable nonReentrant returns (bool success) {
        require(kyc[_msgSender()] == true && _msgSender() == _beneficiary, "Only Whitelisted addresses are allowed to participate in the Seed Round.");
        
        (uint256 totalUSD, uint256 toContribute, uint256 toDistribute) = getTokenExchangeRate(WETH, msg.value);

        _createPayment(_msgSender(), 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, totalUSD, toContribute, toDistribute);
        
        return true;
    }
    
    /*
     * Contribute with any of the Whitelisted Tokens (WBTC/WETH/LINK/UNI/DAI/USDC/USDT).
     * @param _asset the token used to make the contribution.
     * @param _value the value to be contributed.
     * @return success Contribution succeeded or failed.
     */
    function buyTokens(address _asset, uint256 _value) public nonReentrant returns (bool success) {
        require(kyc[_msgSender()] == true, "Only Whitelisted addresses are allowed to participate in the Seed Round.");

        (uint256 totalUSD, uint256 toContribute, uint256 toDistribute) = getTokenExchangeRate(_asset, _value);
        
        _createPayment(_msgSender(), _asset, totalUSD, toContribute, toDistribute);
    
        return true;
    }
    
    /*
     * Helper function to create the contribution and set BTCL Token Vesting & Distribution Emissions.
     * @param beneficiary The address of the Contributor.
     * @param asset The token used to Contribute.
     * @param value The total amount in USD Contributed.
     */
    function _createPayment(address _beneficiary, address _asset, uint256 _value, uint256 toContribute, uint256 toDistribute) private {
        checkKycDepositLimit(_beneficiary, _value);

        makeContribution(_beneficiary, _asset, toContribute);

        splitTokensInStages(toDistribute);
        
        hydrateContribution(_beneficiary, _asset, toContribute, toDistribute, _value); 
        
        checkUnique();
        
        // EMIT & RETURN TRUE IF CONTRIBUTION SUCCEEDED
        emit TokensPurchased(_beneficiary, toDistribute, _value);
    }

    /**
     * KYC helper function that checks USD Contribution limits.
     * @param _beneficiary the address of the contributor.
     * @param _value the amount contributed.
     */
    function checkKycDepositLimit(address _beneficiary, uint256 _value) private view {
        require(block.number >= startBlock && block.number <= endBlock && btclDistributed < 250000000 * 1e18, "Seed Round finished successfully. Congrats to everyone!");
        require(_value >= 10000, "Contribution amount must be atleast 100$");
        
        UserInfo storage user = userInfo[_beneficiary];
        
        // check if KYC Limit is 15K or 50K and if it was already reached.
        uint256 newUSDValue = user.totalUSDContributed.add(_value);
        
        if(kycUplifted[_beneficiary] == true) {
            require(newUSDValue <= kycLimitUplifted, "Address can't contribute more than 50K USD.");
        } else {
            require(newUSDValue <= kycUsdLimit, "Address can't contribute more than 15K USD.");    
        }

    }
        
    /**
     * KYC helper function to make either ETH or Tokens Contribution
     * @param _beneficiary the address of the contributor.
     * @param _asset the amount contributed.
     * @param toContribute the amount contributed.
     */
    function makeContribution(address _beneficiary, address _asset, uint256 toContribute) private {
        if(_asset == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
            wallet.transfer(msg.value);
        } else {
            makeTokenContribution(_beneficiary, _asset, toContribute);
        }
    }
    
    /**
     * Helper function that checks token allowance and makes the contribution.
     * @param _beneficiary the address of the contributor.
     * @param _asset the asset used to contribute.
     * @param _toContribute the amount contributed.
     */
    function makeTokenContribution(address _beneficiary, address _asset, uint256 _toContribute) private {
        uint256 allowance = IERC677(_asset).allowance(_beneficiary, address(this));
        require(allowance >= _toContribute, "Check the token allowance");
        IERC677(_asset).safeTransferFrom(_beneficiary, wallet, _toContribute);
    }
    
    /**
     * Helper function that split BTCL Tokens into multiple release stages.
     * @param _toDistribute total BTCL Tokens that will be distributed.
     */
    function splitTokensInStages(uint256 _toDistribute) private {
        uint256 accumulatedTokens;
        for(uint256 i = 0; i < vestingPercentages.length; i++) {
            uint256 storedBTCL = totalBTCL[_msgSender()][i];
            uint256 tempBTCL = _toDistribute.mul(vestingPercentages[i]).div(100);
            accumulatedTokens = accumulatedTokens.add(_toDistribute.mul(vestingPercentages[i]).div(100));
            // run in all stages except the last stage
            if(i != vestingPercentages.length - 1) {
                totalBTCL[_msgSender()][i] = tempBTCL.add(storedBTCL);
            } else {
                // check if there are any dustTokens stuck and add them to final vesting stage.
                uint256 dustTokens = _toDistribute.sub(accumulatedTokens);
                totalBTCL[_msgSender()][i] = tempBTCL.add(storedBTCL).add(dustTokens);
            }
        }
    }
    
    /**
     * Helper function that updates individual and global variables.
     * @param _beneficiary the address of the contributor.
     * @param _asset the asset used to contribute.
     * @param _toContribute the amount contributed.
     * @param _toDistribute total BTCL Tokens that will be distributed.
     * @param _value The total amount in USD Contributed.
     */
    function hydrateContribution(address _beneficiary, address _asset, uint256 _toContribute, uint256 _toDistribute, uint256 _value) private {
        UserInfo storage user = userInfo[_beneficiary];
        UserContribution storage contribution = userContribution[_beneficiary][user.totalContributions];
        
        // HYDRATE USER CONTRIBUTION
        user.totalContributions = user.totalContributions.add(1);
        user.totalLockedBTCL = user.totalLockedBTCL.add(_toDistribute);
        user.totalUSDContributed = user.totalUSDContributed.add(_value);
        
        // TOTAL BTCL TO DISTRIBUTE & TOTAL RAISED IN USD
        btclDistributed = btclDistributed.add(_toDistribute);
        totalRaised = totalRaised.add(_value);
        uniqueContributions = uniqueContributions.add(1);
        
        // HYDRATE INDIVIDUAL CONTRIBUTION
        contribution.token = _asset;
        contribution.time = now;
        contribution.tokenInUSD = _value;
        contribution.tokenAmount = _toContribute;
        contribution.btclToDistribute = _toDistribute;
    }
    
    /*
     * Helper function to help keep track of all contributors onchain
     */
    function checkUnique() private {
        if(isUnique[_msgSender()] == false) { 
            isUnique[_msgSender()] = true;
            uniqueAddress[uniqueContributors] = _msgSender();
            uniqueContributors = uniqueContributors.add(1);
        }
    }
    
    /**
     * Claim unlockable BTCL Tokens based on current vesting stage.
     * @return total BTCL tokens claimed.
     */
    function claimVestedTokens() public nonReentrant returns (uint256 total) {
        uint256 totalBtclLeftToWithdraw;
        
        if(block.number > cliffEndingBlock) {
            
            UserInfo storage user = userInfo[_msgSender()];
        
            for(uint256 i = 0; i < vestingSchedules.length; i++) {
                if (block.number >= vestingSchedules[i]) {
                    uint256 tempBTCL = totalBTCL[_msgSender()][i];
                    totalBtclLeftToWithdraw = totalBtclLeftToWithdraw.add(tempBTCL);
                    user.totalClaimedBTCL = user.totalClaimedBTCL.add(tempBTCL);
                    totalBTCL[_msgSender()][i] = 0;
                    user.lastRewardBlock = block.number;
                    totalBtclClaimed = totalBtclClaimed.add(tempBTCL);
                }
            }
            
            btclToken.safeTransfer(_msgSender(), totalBtclLeftToWithdraw);
        
            return (totalBtclLeftToWithdraw);
        } else {
            revert("The Vesting Cliff Period has not yet passed.");
        }

    }
    
    /**
     * Get tokens unlocked percentage on current stage.
     * @param _contributorAddress the contributor address.
     * @return stage and percent and total Percent of tokens that can be claimed.
     */
    function getTokensUnlockedPercentage(address _contributorAddress) public view returns (uint256 stage, uint256 percentage, uint256 total) {
        uint256 totalLeftToWithdraw;
        uint256 allowedPercent;
        uint256 currentStage;
        
        for(uint8 i = 0; i < vestingSchedules.length; i++) {
            if (block.number >= vestingSchedules[i]) {
                allowedPercent = allowedPercent.add(vestingPercentages[i]);
                currentStage = i;
            }
        }
        
        for(uint256 v = 0; v <= currentStage; v++) {
            if (block.number >= vestingSchedules[currentStage]) {
                uint256 tempBTCL = totalBTCL[_contributorAddress][v];
                totalLeftToWithdraw = totalLeftToWithdraw.add(tempBTCL);
            }
        }
        
        return (currentStage, allowedPercent, totalLeftToWithdraw);
    }

    /**
     * @dev KYC helper function used to display current KYC Status.
     * @param _contributorAddress The Contributor Address Whitelisting Address.
     * @return whitelisted and KYC uplift Status.
     */
    function checkKYC(address _contributorAddress) public view returns (bool whitelisted, bool uplifted) {
        return (kyc[_contributorAddress], kycUplifted[_contributorAddress]);
    }

    /**
     * @dev KYC helper function used by the team to whitelist multiple addresses at once.
     * @param _addresses whitelisted address list.
     * @param _whitelisted whitelisted address can contribute up to $15K.
     * @param _kycUplift whitelisted address owner has provided sources of funds and was uplifted to contribute up to $50K.
     */
    function multiKycWhitelisting(address[] memory _addresses, bool[] memory _whitelisted, bool[] memory _kycUplift) public onlyTeam returns (bool success) {
        for(uint256 i = 0; i < _addresses.length; i++) {
            kyc[_addresses[i]] = _whitelisted[i];
            kycUplifted[_addresses[i]] = _kycUplift[i];
        }
        return true;
    }
    
    /**
     * @dev ChainLink helper function used to update old Chainlink Price Feed Aggregators or add new ones.
     * @param _asset The token associated to the Chainlink Price Feed.
     * @param _newAggregatorAddress The Aggregator Contract Address.
     */
    function updateAggregatorAddress(address _asset, address _newAggregatorAddress) public onlyTeam {
        tokensAndFeeds[_asset] = _newAggregatorAddress;
    }
    
    /**
     * @dev Team helper function used to update old multisig wallet address.
     * @param _newWallet The new team multi signature wallet.
     */
    function updateTeamWalletAddress(address payable _newWallet) public onlyTeam {
        wallet = _newWallet;
    }
    
    /**
     * @dev Team helper function used to update old bonus reserve address.
     * @param _newWallet The new bonus reserve smart contract.
     */
    function updateBonusReserveAddress(address payable _newWallet) public onlyTeam {
        bonus = _newWallet;
    }
    
    /**
     * @dev Team helper function used to upgrade the BTCL Governance Token.
     * Future Upgrades: Gassless DAO Voting, Approval Signatures with no GAS Costs, Merkle Proofs.
     * @param _btclToken The new upgraded BTCL Governance Token.
    */
    function updateBtclTokenAddress(address payable _btclToken) public onlyTeam {
        btclToken = IERC677(_btclToken);
    }
    
    /**
     * @dev Team helper function used to redistribute undistributed BTCL Tokens back into the Community Bonus Reserve.
     */
    function redistributeTokens() public onlyTeam {
        require(block.number >= endBlock, "The Seed Round Contribution period has not yet finished");
        uint256 undistributedBtclTokens = uint256(250000000 * 1e18).sub(btclDistributed);
        btclToken.safeTransfer(bonus, undistributedBtclTokens);
    }

    /**
     * @dev ERC677 TokenFallback Function.
     * @param _wallet The team address can send BTCL tokens to the Seed Round Contract.
     * @param _value The amount of tokens sent by the team to the BTCL Seed Round Contract.
     * @param _data The transaction metadata.
     */
    function onTokenTransfer(address _wallet, uint256 _value, bytes memory _data) public {
        require(_msgSender() == address(btclToken), "Contract only accepts BTCL Tokens");
        require(wallet == _wallet,"Only team wallet is allowed");
        emit DepositedTokens(_wallet, _value, _data);
    }
    
}

// File: Context.sol



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

pragma solidity >=0.4.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.
 */
contract Context {
    // Empty internal constructor, to prevent people from mistakenly deploying
    // an instance of this contract, which should be used via inheritance.
    constructor() internal {}

    function _msgSender() internal view returns (address payable) {
        return msg.sender;
    }

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

// File: ERC677.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

import './Ownable.sol';
import './Context.sol';
import './IERC677.sol';
import './SafeMath.sol';
import './Address.sol';
import './ERC677Receiver.sol';

/**
 * @dev Implementation of the {IERC677} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC677PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-ERC677-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC677 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC677-approve}.
 */
contract ERC677 is Context, IERC677, Ownable {
    using SafeMath for uint256;
    using Address for address;

    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;
    
    address private _owner;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name, string memory symbol, uint256 initialSupply, uint8 decimals) public {
        _name = name;
        _symbol = symbol;
        _decimals = decimals;
        _totalSupply = initialSupply * (10 ** uint256(_decimals));
        _balances[_msgSender()] = _balances[_msgSender()].add(_totalSupply);
        _owner = _msgSender();
        emit Transfer(address(0), _msgSender(), _totalSupply);
    }

    /**
     * @dev Returns the ERC677 token owner.
     */
    function getOwner() external override view returns (address) {
        return _owner;
    }

    /**
     * @dev Returns the token name.
     */
    function name() public override view returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the token decimals.
     */
    function decimals() public override view returns (uint8) {
        return _decimals;
    }

    /**
     * @dev Returns the token symbol.
     */
    function symbol() public override view returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {ERC677-totalSupply}.
     */
    function totalSupply() public override view returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {ERC677-balanceOf}.
     */
    function balanceOf(address account) public override view returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {ERC677-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {ERC677-allowance}.
     */
    function allowance(address owner, address spender) public override view returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {ERC677-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {ERC677-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC677};
     *
     * Requirements:
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for `sender`'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(
            sender,
            _msgSender(),
            _allowances[sender][_msgSender()].sub(amount, 'ERC677: transfer amount exceeds allowance')
        );
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {ERC677-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {ERC677-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
        _approve(
            _msgSender(),
            spender,
            _allowances[_msgSender()][spender].sub(subtractedValue, 'ERC677: decreased allowance below zero')
        );
        return true;
    }

    /**
     * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
     * the total supply.
     *
     * Requirements
     *
     * - `msg.sender` must be the token owner
     */
    // function mint(uint256 amount) public onlyOwner returns (bool) {
    //     _mint(_msgSender(), amount);
    //     return true;
    // }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal {
        require(sender != address(0), 'ERC677: transfer from the zero address');
        require(recipient != address(0), 'ERC677: transfer to the zero address');

        _balances[sender] = _balances[sender].sub(amount, 'ERC677: transfer amount exceeds balance');
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements
     *
     * - `to` cannot be the zero address.
     */
 
    /**
     * @dev Destroys `amount` tokens from `msg.sender`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements
     *
     * - `account` must have at least `amount` tokens.
     */
    function burn(uint256 amount) public override {
        _balances[msg.sender] = _balances[msg.sender].sub(amount, 'ERC677: burn amount exceeds balance');
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(msg.sender, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
     *
     * This is internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal {
        require(owner != address(0), 'ERC677: approve from the zero address');
        require(spender != address(0), 'ERC677: approve to the zero address');

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
    * @dev Transfer tokens to a contract address with additional data.
    * @param _to The address to transfer to.
    * @param _value The amount to be transferred.
    * @param _data The extra data to be passed to the receiving contract, mostly used "0x", empty byte.
    */
    function transferAndCall(address _to, uint _value, bytes memory _data) public override returns (bool success) {
        require(_msgSender() != address(0), "ERC20: approve from the zero address");
        require(_to != address(0), "ERC20: approve to the zero address");

        transfer(_to, _value);
        if (isContract(_to)) {
            contractFallback(_to, _value, _data);
        }
        return true;
    }
    
    function contractFallback(address _to, uint _value, bytes memory _data) private {
        ERC677Receiver receiver = ERC677Receiver(_to);
        receiver.onTokenTransfer(msg.sender, _value, _data);
    }

    function isContract(address _addr) private view returns (bool hasCode) {
        uint length;
        // solhint-disable-next-line no-inline-assembly
        assembly { length := extcodesize(_addr) }
        return length > 0;
    }
}

// File: ERC677Receiver.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;

abstract contract ERC677Receiver {
    function onTokenTransfer(address _sender, uint _value, bytes memory _data) virtual public;
}

// interface ERC677Receiver {
//     function onTokenTransfer(
//         address _sender,
//         uint256 _value,
//         bytes calldata _data
//     ) external;
// }

// File: IERC677.sol



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

pragma solidity >=0.4.0;

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

    /**
     * @dev Returns the token decimals.
     */
    function decimals() external view returns (uint8);

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

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

    /**
     * @dev Returns the ERC677 token owner.
     */
    function getOwner() external view returns (address);

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

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

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

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

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

 
    /**
     * @dev Destroys `amount` tokens from `msg.sender`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements
     *
     * - `account` must have at least `amount` tokens.
     */
    function burn(uint amount) external;
    
    /**
    * @dev transfer token to a contract address with additional data if the recipient is a contact.
    * @param to The address to transfer to.
    * @param value The amount to be transferred.
    * @param data The extra data to be passed to the receiving contract.
    */
    function transferAndCall(address to, uint value, bytes memory data) external returns (bool success);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

// File: IWETH.sol



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

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}

// File: Ownable.sol



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

pragma solidity >=0.4.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.
 */
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 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 onlyOwner {
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     */
    function _transferOwnership(address newOwner) internal {
        require(newOwner != address(0), 'Ownable: new owner is the zero address');
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

// File: ReentrancyGuard.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() public {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

// File: SafeERC677.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

import './IERC677.sol';
import './SafeMath.sol';
import './Address.sol';

/**
 * @title SafeERC677
 * @dev Wrappers around BEP20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC677 for IERC677;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC677 {
    using SafeMath for uint256;
    using Address for address;

    function safeTransfer(
        IERC677 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC677 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC677-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC677 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        // solhint-disable-next-line max-line-length
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            'SafeERC677: approve from non-zero to non-zero allowance'
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC677 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender).add(value);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC677 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender).sub(
            value,
            'SafeERC677: decreased allowance below zero'
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC677 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, 'SafeERC677: low-level call failed');
        if (returndata.length > 0) {
            // Return data is optional
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), 'SafeERC677: ERC677 operation did not succeed');
        }
    }
}

// File: SafeMath.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.4.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;
    }

    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = x < y ? x : y;
    }

    // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
    function sqrt(uint256 y) internal pure returns (uint256 z) {
        if (y > 3) {
            z = y;
            uint256 x = y / 2 + 1;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
    }
}

// File: SafeMathChainlink.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 SafeMathChainlink {
  /**
    * @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) {
    require(b <= a, "SafeMath: subtraction overflow");
    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-solidity/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) {
    // Solidity only automatically asserts when dividing by 0
    require(b > 0, "SafeMath: division by zero");
    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) {
    require(b != 0, "SafeMath: modulo by zero");
    return a % b;
  }
}