contract Miner is Context, IERC20, Ownable {
  using SafeMath for uint256;

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

  string private _symbol;
  string private _name;

  uint256 private _totalSupply;
  uint8 private _decimals;
  uint8 public investorIndex;
  uint256 public finalTotalSupply;
  uint256 public investorsCap;
  uint256 public investorsClaimed;
  
  struct VestibleToken {
    string vestingOwnerName;
    uint256 vestingStartTime;
    uint256 vestingTimeUnit;
    uint256 numVestingPeriods;
    uint256 supplyLeftToVest;
    uint256 supplyVested;
  }
  
  // 0th represent the team's vesting schedule
  // 1st represent the operations teams' vesting schedule
  mapping (uint8 => VestibleToken) public vestibleTokens;

  constructor() public {
    _name = "Cloud Miner";
    _symbol = "MINE";
    _decimals = 18;

    // 1b total tokens.
    // This is the final total supply across all chains after all vesting. 
    // Initial supply will start from the Ethereum blockchain and pegged out into other chains.
    // Other chains will start from an initial supply of 0 and only pegged in from the Ethereum blockchain supply.
    // All vestings are intended to be done on ETH as well and bridged and transfered to other chains if needed.
    finalTotalSupply = 1e9 * 1e18; 
    _totalSupply = finalTotalSupply; 

    uint256 startTime = now;

    // Construct vestible tokens for the team and operations
    vestibleTokens[0] = VestibleToken("team", startTime, 180 days, 10, finalTotalSupply.mul(10).div(100), 0);
    vestibleTokens[1] = VestibleToken("operations", startTime, 30 days, 12, finalTotalSupply.mul(6).div(100), 0);

    _totalSupply = _totalSupply.sub(vestibleTokens[0].supplyLeftToVest);
    _totalSupply = _totalSupply.sub(vestibleTokens[1].supplyLeftToVest);

    investorIndex = 2;

    investorsCap = finalTotalSupply.mul(20).div(100);
    _totalSupply = _totalSupply.sub(investorsCap);

    _balances[msg.sender] = _totalSupply;

    emit Transfer(address(0), msg.sender, _totalSupply);
  }

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

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

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

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

  /**
   * @dev See {ERC20-totalSupply}.
   */
  function totalSupply() external view returns (uint256) {
    return _totalSupply;
  }

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

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

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

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

  /**
   * @dev See {ERC20-transferFrom}.
   *
   * Emits an {Approval} event indicating the updated allowance. This is not
   * required by the EIP. See the note at the beginning of {ERC20};
   *
   * 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) external returns (bool) {
    _transfer(sender, recipient, amount);
    _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: 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 {ERC20-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 {ERC20-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, "ERC20: decreased allowance below zero"));
    return true;
  }

// Fixed supply after creation and vesting
//   /**
//    * @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), "ERC20: transfer from the zero address");
    require(recipient != address(0), "ERC20: transfer to the zero address");

    _balances[sender] = _balances[sender].sub(amount, "ERC20: 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.
   */
  function _mint(address account, uint256 amount) internal {
    require(account != address(0), "ERC20: mint to the zero address");

    _totalSupply = _totalSupply.add(amount);
    _balances[account] = _balances[account].add(amount);
    emit Transfer(address(0), account, amount);
  }

  /**
   * @dev Destroys `amount` tokens from `account`, reducing the
   * total supply.
   *
   * Emits a {Transfer} event with `to` set to the zero address.
   *
   * Requirements
   *
   * - `account` cannot be the zero address.
   * - `account` must have at least `amount` tokens.
   */
  function _burn(address account, uint256 amount) internal {
    require(account != address(0), "ERC20: burn from the zero address");

    _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
    _totalSupply = _totalSupply.sub(amount);
    emit Transfer(account, 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), "ERC20: approve from the zero address");
    require(spender != address(0), "ERC20: approve to the zero address");

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

  /**
   * @dev Destroys `amount` tokens from `account`.`amount` is then deducted
   * from the caller's allowance.
   *
   * See {_burn} and {_approve}.
   */
  function _burnFrom(address account, uint256 amount) internal {
    _burn(account, amount);
    _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
  }

  // Burning tokens
  function burn(uint256 _value) public {
      _burn(msg.sender, _value);
  }

  event InvestorAdded(
    uint8 index,
    string vestingOwnerName,
    uint256 vestingStartTime,
    uint256 vestingTimeUnit,
    uint256 numVestingPeriods,
    uint256 supplyLeftToVest,
    uint256 supplyVested,
    uint256 tokensPerVesting);

  function computeTokensPerVesting(VestibleToken memory token) internal pure returns (uint256) {
    return token.supplyLeftToVest.add(token.supplyVested).div(token.numVestingPeriods);
  }

  function addInvestor(string memory _investorName,  uint256 _vestingTimeUnit, uint8 _numVestingPeriods, uint256 _tokensToVest) public onlyOwner {
    require(investorsClaimed.add(_tokensToVest ) <= investorsCap);
    require(investorIndex < 255, "InvestorIndex overflow");
    require(_numVestingPeriods > 0, "numVestingPeriods should be positive");

    uint256 startTime = now;
    investorsClaimed = investorsClaimed.add(_tokensToVest);
    
    vestibleTokens[investorIndex] = VestibleToken(_investorName, startTime, _vestingTimeUnit, _numVestingPeriods, _tokensToVest, 0);

    emit InvestorAdded(
        investorIndex,
        vestibleTokens[investorIndex].vestingOwnerName,
        vestibleTokens[investorIndex].vestingStartTime,
        vestibleTokens[investorIndex].vestingTimeUnit,
        vestibleTokens[investorIndex].numVestingPeriods,
        vestibleTokens[investorIndex].supplyLeftToVest,
        vestibleTokens[investorIndex].supplyVested,
        computeTokensPerVesting(vestibleTokens[investorIndex]));

    investorIndex++;
  }

  event TokenVested(
      uint8 index,
      uint256 numVestingPeriodsPassed,
      uint256 tokensJustVested,
      uint256 supplyVested,
      uint256 supplyLeftToVest);
  
  function releaseIthInvestorTokens(uint8 index) public onlyOwner {
    uint256 tokensPerVesting = computeTokensPerVesting(vestibleTokens[index]);
    require(vestibleTokens[index].supplyLeftToVest >= tokensPerVesting, "Not enough to vest");

    uint256 numVestingPeriodsPassed = now.sub(vestibleTokens[index].vestingStartTime).div(vestibleTokens[index].vestingTimeUnit);
    uint256 unlockedTokens = numVestingPeriodsPassed.mul(tokensPerVesting);
    require(unlockedTokens > vestibleTokens[index].supplyVested, "Not enough unlocked");
    require(vestibleTokens[index].supplyVested.div(tokensPerVesting) < vestibleTokens[index].numVestingPeriods, "Cannot vest more than numVestingPeriods");
    vestibleTokens[index].supplyVested = vestibleTokens[index].supplyVested.add(tokensPerVesting);
    vestibleTokens[index].supplyLeftToVest = vestibleTokens[index].supplyLeftToVest.sub(tokensPerVesting);
    _mint(msg.sender, tokensPerVesting);
    
    emit TokenVested(
        index, numVestingPeriodsPassed, tokensPerVesting,
        vestibleTokens[index].supplyVested, vestibleTokens[index].supplyLeftToVest);
  }

  // Section to support cross chain peg in and peg out by owner
  event PegOutEvent(uint256 value, string destinationChain);

  function pegOut(uint256 value, string memory destinationChain) public onlyOwner{
      require(value < _balances[msg.sender], "Cannot peg out more than owner amount");
      _burn(msg.sender, value);
      emit PegOutEvent(value, destinationChain);
  }

  // Peg-in records the amount of tokens, the peg-out chain and the peg-out transaction's ID to guarantee a 1-1 match
  // between the peg-out transaction of one chain and peg-in transaction of another chain.
  event PegInEvent(uint256 value, string originChain, string originationTransaction);

  function pegIn(uint256 value, string memory originChain, string memory originationTransaction) public onlyOwner{
      _mint(msg.sender, value);
      emit PegInEvent(value, originChain, originationTransaction);
  }
}
function _burn(address account, uint256 amount) internal {
  require(account != address(0), "ERC20: burn from the zero address");

  _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
  _totalSupply = _totalSupply.sub(amount);
  emit Transfer(account, address(0), amount);
}

/**
 * @dev Destroys `amount` tokens from `account`, reducing the
 * total supply.
 *
 * Emits a {Transfer} event with `to` set to the zero address.
 *
 * Requirements
 *
 * - `account` cannot be the zero address.
 * - `account` must have at least `amount` tokens.
 */