contract DBLendToken is ERC20,Ownable {

    // using Strings for *;
    /// @notice A record of each accounts delegate
    mapping (address => address) public delegates;
    address public miner;
    address public timelock;

    /// @notice A checkpoint for marking number of votes from a given block
    struct Checkpoint {
        uint32 fromBlock;
        uint256 votes;
    }

    /// @notice A record of votes checkpoints for each account, by index
    mapping (address => mapping (uint256 => Checkpoint)) public checkpoints;

    /// @notice The number of checkpoints for each account
    mapping (address => uint256) public numCheckpoints;

    /// @notice The EIP-712 typehash for the contract's domain
    bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");

    /// @notice The EIP-712 typehash for the delegation struct used by the contract
    bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");

    /// @notice A record of states for signing / validating signatures
    mapping (address => uint256) public nonces;

    /// @notice An event thats emitted when an account changes its delegate
    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);

    /// @notice An event thats emitted when a delegate account's vote balance changes
    event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
    
    constructor() ERC20("DBLend Line","DBL"){
        _mint(msg.sender, 2100000*1e8);//Total 2100000 DBL
        // timelock = _timelock;

        //_delegate(address(this), address(this));
        //numCheckpoints[address(this)] = 2100000*1e8;
    }

    function decimals() public pure override returns (uint8) {
        return 8;
    }

    function totalSupply() public view override returns (uint256) {
        return 2100000*1e8 - balanceOf(address(this));
    }

    ///@dev init miner and approve miner transfer dbl
    function initMiner(address _minerAddress) external onlyOwner returns (uint256){
        require(miner == address(0), "DBL: INIT ONLY ONCE");
        require(_minerAddress != address(0), "DBL: NOT VALID MINER");
        return approveMiner(_minerAddress);
    }

    ///@dev update timelock,if timelock has been set, only timelock can be call. Otherwise the owner can call.
    function updateTimelock(address _timelock) external {
        require((timelock == address(0) && msg.sender == owner()) || msg.sender == timelock, "NO PERMISSION");
        require(_timelock != address(0),"INVALID ADDRESS");
        timelock = _timelock;
    }

    ///@dev replace miner through governance voting,if timelock is not set, the owner can operate.
    function _setMiner(address _minerAddress) external {
        require(msg.sender == timelock || (timelock == address(0) && msg.sender == owner()), "DBL: NEED TIMELOCK OR OWNER");
        approveMiner(_minerAddress);
    }

    ///@dev DBLToken contract approve Miner Contract to spend all dbl
    function approveMiner(address _minerAddress) internal returns (uint256){
        //////importance,prevent delegatecall attack
        if(!isContract(_minerAddress)) return 0;
        uint256 balance = balanceOf(address(this));
        _approve(address(this), _minerAddress, 2100000 * 1e8);
        miner = _minerAddress;
        return balance;
    }

    ///@dev Miner mint，actually transfer from address(this) to _account
    function mint(address _account, uint256 _amount) public returns (bool){
        require(msg.sender == miner, "DEL:ONLY MINER");
        return transferFrom(address(this), _account, _amount);
    }

    ///@dev DBL token can be transferred through governance voting
    // function govTransfer(address _receipt, uint256 _amount) public returns (bool){
    //     require(msg.sender == timelock, "DBL:ONLY TIMELOCK");
    //     uint256 balance = balanceOf(address(this));
    //     if(_amount > balance) _amount = balance;
    //     return transferFrom(address(this), _account, _amount);
    // }

    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

    function transfer(address recipient, uint256 amount) public override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        if(recipient == address(this)){
            recipient = address(0);
        }
        _moveDelegates(delegates[_msgSender()], delegates[recipient], amount);
        return true;
    }

    function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = allowance(sender,_msgSender());
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        _approve(sender, _msgSender(), currentAllowance - amount);

        //如果是挖矿铸币，则src为0，不需要记录本地的投票数据
        if(sender == address(this)){
            sender = address(0);
        }       
        _moveDelegates(delegates[sender], delegates[recipient], amount);
        return true;
    }

    /**
     * @notice Delegate votes from `msg.sender` to `delegatee`
     * @param delegatee The address to delegate votes to
     */
    function delegate(address delegatee) public {
        return _delegate(msg.sender, delegatee);
    }

    /**
     * @notice Delegates votes from signatory to `delegatee`
     * @param delegatee The address to delegate votes to
     * @param nonce The contract state required to match the signature
     * @param expiry The time at which to expire the signature
     * @param v The recovery byte of the signature
     * @param r Half of the ECDSA signature pair
     * @param s Half of the ECDSA signature pair
     */
    function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public returns (address){
        bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
        bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
        bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
        address signatory = ecrecover(digest, v, r, s);
        require(signatory != address(0), "DBL::delegateBySig: invalid signature");
        require(nonce == nonces[signatory]++, "DBL::delegateBySig: invalid nonce");
        require(block.timestamp <= expiry, "DBL::delegateBySig: signature expired");
        _delegate(signatory, delegatee);
        return signatory;
    }

    /**
     * @notice Gets the current votes balance for `account`
     * @param account The address to get votes balance
     * @return The number of current votes for `account`
     */
    function getCurrentVotes(address account) external view returns (uint256) {
        uint256 nCheckpoints = numCheckpoints[account];
        return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
    }

    /**
     * @notice Determine the prior number of votes for an account as of a block number
     * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
     * @param account The address of the account to check
     * @param blockNumber The block number to get the vote balance at
     * @return The number of votes the account had as of the given block
     */
    function getPriorVotes(address account, uint256 blockNumber) public view returns (uint256) {
        require(blockNumber < block.number, "DBL::getPriorVotes: not yet determined");

        uint256 nCheckpoints = numCheckpoints[account];
        if (nCheckpoints == 0) {
            return 0;
        }

        // First check most recent balance
        if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
            return checkpoints[account][nCheckpoints - 1].votes;
        }

        // Next check implicit zero balance
        if (checkpoints[account][0].fromBlock > blockNumber) {
            return 0;
        }

        uint256 lower = 0;
        uint256 upper = nCheckpoints - 1;
        while (upper > lower) {
            uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            Checkpoint memory cp = checkpoints[account][center];
            if (cp.fromBlock == blockNumber) {
                return cp.votes;
            } else if (cp.fromBlock < blockNumber) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return checkpoints[account][lower].votes;
    }

    function _delegate(address delegator, address delegatee) internal {
        address currentDelegate = delegates[delegator];
        uint256 delegatorBalance = balanceOf(delegator);
        delegates[delegator] = delegatee;

        emit DelegateChanged(delegator, currentDelegate, delegatee);

        _moveDelegates(currentDelegate, delegatee, delegatorBalance);
    }

    // function _transferTokens(address src, address dst, uint96 amount) internal {
    //     require(src != address(0), "DBL::_transferTokens: cannot transfer from the zero address");
    //     require(dst != address(0), "DBL::_transferTokens: cannot transfer to the zero address");

    //     balances[src] = sub96(balances[src], amount, "DBL::_transferTokens: transfer amount exceeds balance");
    //     balances[dst] = add96(balances[dst], amount, "DBL::_transferTokens: transfer amount overflows");
    //     emit Transfer(src, dst, amount);

    //     _moveDelegates(delegates[src], delegates[dst], amount);
    // }

    //转移投票权，减少原代理地址的票数，增加到新代理地址的票数，票数跟balance相关
    function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
        if (srcRep != dstRep && amount > 0) {
            if (srcRep != address(0)) {                
                uint256 srcRepNum = numCheckpoints[srcRep];
                uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;                
                uint256 srcRepNew = srcRepOld - amount;            
                _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
            }

            if (dstRep != address(0)) {
                uint256 dstRepNum = numCheckpoints[dstRep];
                uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
                uint256 dstRepNew = dstRepOld + amount;
                _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
            }
        }
    }

    function _writeCheckpoint(address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
      uint32 blockNumber = safe32(block.number, "DBL::_writeCheckpoint: block number exceeds 32 bits");

      if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
          checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
      } else {
          checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
          numCheckpoints[delegatee] = nCheckpoints + 1;
      }

      emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
    }

    function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
        require(n < 2**32, errorMessage);
        return uint32(n);
    }

    function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
        require(n < 2**96, errorMessage);
        return uint96(n);
    }

    function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
        uint96 c = a + b;
        require(c >= a, errorMessage);
        return c;
    }

    function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
        require(b <= a, errorMessage);
        return a - b;
    }

    function getChainId() internal view returns (uint256) {
        uint256 chainId;
        assembly { chainId := chainid() }
        return chainId;
    }
}
// ////import './libraries/Strings.sol';
function mint(address _account, uint256 _amount) public returns (bool){
    require(msg.sender == miner, "DEL:ONLY MINER");
    return transferFrom(address(this), _account, _amount);
}

///@dev Miner mint，actually transfer from address(this) to _account