////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT

pragma solidity ^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 meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}





            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @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 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);
}





            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT

pragma solidity ^0.8.0;

////import "./IERC20.sol";
////import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} 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 {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-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 ERC20 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 {IERC20-approve}.
 */
contract ERC20 is Context, IERC20 {
    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The defaut value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overloaded;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-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 virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-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) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        _approve(sender, _msgSender(), currentAllowance - amount);

        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 {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + 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 {IERC20-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 virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        _approve(_msgSender(), spender, currentAllowance - subtractedValue);

        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 virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        _balances[sender] = senderBalance - amount;
        _balances[recipient] += 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 virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += 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 virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        _balances[account] = accountBalance - amount;
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This 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 virtual {
        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 Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}





            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT

pragma solidity ^0.8.0;

////import "../utils/Context.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * 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 () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual 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;
    }
}





            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;

interface IMinerV1{
    function accountStoked(address addr) external view returns (uint256);
    function totalStoke() external view returns (uint256);
    function userTimes(address) external view returns (uint256);
    function totalMineds( address ) external view returns (uint256);
    // function current() external view returns (uint256);//private,don't call
    function earnedBalance( address ) external view returns (uint256);
    
    
}




            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;

////import '@openzeppelin/contracts/token/ERC20/ERC20.sol';

contract DEBIToken is ERC20 {
    constructor() ERC20("DeerBit Token","DEBI") {
        _mint(msg.sender, 100000000000 * 1e8);
    }

    function decimals() public pure override returns (uint8){
        return 8;
    }
}




            
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;

////import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
////import "@openzeppelin/contracts/access/Ownable.sol";
// ////import './libraries/Strings.sol';

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;
    }
}



////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import './DBLendToken.sol';
////import './DEBIToken.sol';
////import './interfaces/IMinerV1.sol';
// ////import './libraries/Strings.sol';

contract Miner is Ownable{
    // using Strings for *;
    address public immutable DBL; // DBL地址，部署时传入，不可修改
    address public immutable DIBI; // DIBI地址，部署时传入，不可修改
    uint256 public constant FIREST_YEAR_DBL = 1050000 * 1e8 * 1e18; // 首年产出DBL，逐年减半(1e18:为了避免分配到每区块时dibi时出现的小数)
    uint256 public immutable DEPLOY_BLOCK;// = 10957872;// 合约发布时间
    uint public constant blocksPerYear = 2102400;//按照平均15秒/区块，每年区块数

    //指定timelock为admin，timelock执行投票通过的业务，修改Miner相关数据
    address public admin;
    address public pendingAdmin;

    //用户质押DIBI每币能够收获的DBL数目perDibiSharedDbl。该数据从0开始，累加所有区块区间的每DIBI能生产的DBL数量
    //同一区块，质押数第一次产生变化前，要更新当前每币产出perDibiSharedDbl
    //用户收获铸币时，需要提前更新每币产出perDibiSharedDbl，收获完成后，更新用户债务：harvestDebt
    //用户收获数目 = block.number- STAKER.lastHarvestBlock
    uint256 public perDibiSharedDbl = 0;    
    uint256 public latestCalTime = 0; //最近一次计算perDibiSharedDbl区块时间,第一次质押时初始化
    uint256 public latestBlockNum = 0;
    uint256 public totalStaked = 0; // 所有质押的DIBI数量

    //The Pause Guardian can pause certain actions as a safety mechanism.
    bool public rewardGuardianPaused = false;
    bool public stakeGuardianPaused = false;

    struct STAKER{
        uint256 stakeBalance; // 用户当前质押余额
        uint256 lastHarvestBlock; // 最后一次收获时间
        uint256 harvestDebt; // 收获时需要扣减的债务
        uint256 rewardPending; // 等待收获的数量 
    }
    mapping(address=>STAKER) public stakers; // 所有质押者
    
    event Stake(address indexed staker,uint256 amounts, uint256 earned);
    event Harvest(address indexed harver,uint256 earned);
    
    /// @notice Emitted when an action is paused globally
    event ActionPaused(string action, bool pauseState);
    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
    event NewAdmin(address oldAdmin, address newAdmin);


    constructor(address _dbl, address _dibi, uint256 _deploy_block){
        require(_dbl != address(0) && _dibi != address(0),"INVALID ADDRESS");
        DBL = _dbl;
        DIBI = _dibi;
        DEPLOY_BLOCK = _deploy_block;
        admin = msg.sender;
    }

    ///@dev 质押前，计算最新每币产出，并对当前用户进行收获，
    function stake(uint256 _amount) external {
        // Pausing is a very serious situation - we revert to sound the alarms
        require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED");


        require(_amount > 0,"AMOUNT MUST > 0");
        require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI");
        STAKER storage staker = stakers[msg.sender]; 
        //因为质押总数会改变，所以要计算出之前这段时间的每币产出
        _calPerDibiSharedDbl();
        uint256 earned = 0;
        //质押的用户stake需要先收获一次
        if(staker.stakeBalance>0){
            earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18;
            if(earned>0 && earned!=2**256-1){
                staker.rewardPending = staker.rewardPending + earned;
                // DBLendToken(DBL).mint(msg.sender,earned);
            }
            staker.lastHarvestBlock = block.number;
        }
        // require(1==2,"1222222");
        //收获完成后，首先转账dibi，再修改数据状态
        DEBIToken(DIBI).transferFrom(msg.sender,address(this),_amount);
        if(totalStaked==0) latestBlockNum=block.number;
        totalStaked += _amount;

        //更新用户质押状态
        staker.stakeBalance += _amount;
        staker.harvestDebt = perDibiSharedDbl * staker.stakeBalance;
        emit Stake(msg.sender, _amount,earned);
    }

    ///@dev 取出DIBI
    function withdraw(uint256 _amount) public {
        require(stakers[msg.sender].stakeBalance >= _amount,"DBL: INSUFFICIENT DIBI");
        STAKER storage staker = stakers[msg.sender];
        //如果有区块间隔，先计算收获
        if(block.number > staker.lastHarvestBlock){      
            // harvest();
            //更新每质押DIBI产出数
            _calPerDibiSharedDbl();
            uint256 earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18;
            if(earned>0 && earned!=2**256-1){
                staker.rewardPending = staker.rewardPending + earned;
            }
            staker.lastHarvestBlock = block.number;
        }
        //先改变状态，再转账
        staker.stakeBalance -= _amount;
        staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl;
        totalStaked -= _amount;
        DEBIToken(DIBI).transfer(msg.sender, _amount);  
    }

    ///@dev 退出质押。先收获，再退出DIBI
    function unStake() external {
        require(stakers[msg.sender].stakeBalance>0,"DBL: INSUFFICIENT DIBI STAKE");
        harvest();
        withdraw(stakers[msg.sender].stakeBalance);     
    }

    //主动用户收获,铸币，在stake、unstake、harvest时发生
    function harvest() public returns(uint256 earned){
        require(stakers[msg.sender].stakeBalance > 0 || stakers[msg.sender].rewardPending > 0, "DBL: INSUFFICIENT STAKE OR REWARD");
        require(block.number > stakers[msg.sender].lastHarvestBlock,"DBL: REPEAT HARVEST");

        //更新每质押DIBI产出数
        _calPerDibiSharedDbl();
        STAKER storage staker = stakers[msg.sender];
        //收获数量 = 质押代币 * 每币收获 / DIBI精度 - 用户扣减数
        earned = ( staker.stakeBalance * perDibiSharedDbl - staker.harvestDebt ) / 1e18;
        //铸币
        if(staker.rewardPending >0 || earned>0){
            //首先更改状态，避免铸币后状态未修改的攻击
            staker.lastHarvestBlock = block.number;
            staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl;
            earned = staker.rewardPending + earned;
            staker.rewardPending = 0;

            DBLendToken(DBL).mint(msg.sender,earned);
            emit Harvest(msg.sender, earned);
        }        
    }    

    ///@dev 计算当前时间段DIBI每币产出,并把当前时间段的每币产出累加。并更新最近计算时间
    function _calPerDibiSharedDbl() internal{
        uint256 incDblPerDIBI = _calPerDibiIncDbl();
        if(incDblPerDIBI > 0){
            //如果被禁止产出，则关闭产量增加的逻辑。恢复后，所有产量正常恢复
            if(!rewardGuardianPaused){
                perDibiSharedDbl += incDblPerDIBI;
                latestBlockNum = block.number;
            }
            
        }
    }


    ///@dev 时间区段新增的每币产出
    function _calPerDibiIncDbl() internal view returns (uint256 incDblPerDIBI){
        incDblPerDIBI = 0;

        //如果被暂停，则不再增加区块产出
        if(rewardGuardianPaused) return incDblPerDIBI;

        //只要时间变化了，也就是区块增加了，就不能跳过计算；如果质押变化，但区块没有改变，也不需要计算
        //if(block.timestamp > latestCalTime && totalStaked>0){ 
        if(block.number > latestBlockNum && totalStaked>0){          
            uint256 current = currentYearDibi();//当年产量总和
            //新增产量 = 间隔时间段 * (当前年产/365天总秒数）
            uint256 increaseDbl = ( block.number - latestBlockNum ) * current / blocksPerYear ; 
            //每币新增产量 = 新增总量  / 总质押DIBI数
            incDblPerDIBI = increaseDbl / totalStaked;
            
        }

        return incDblPerDIBI;
    }

    ///@dev 计算当前年度的DIBI产出。第一年=FIREST_YEAR_DBL,以后逐年减半
    function currentYearDibi() public view returns (uint256 current){
        current = FIREST_YEAR_DBL;
        // if(block.timestamp > START_TIME){
        if(block.number > DEPLOY_BLOCK){
            uint256 severalYears = (block.number - DEPLOY_BLOCK) / blocksPerYear; // 过几年 = 发布时间长/365
            if (severalYears > 0) {
                current = FIREST_YEAR_DBL / (2 * severalYears); // 当年总产量 = 首年总产量 / (2*几年)
            }
        }
        
    }

    ///@dev 查看指定用户可以收获的数量
    ///@param user 指定用户
    function earnedBalance(address user) external view returns(uint256){
        //首先计算当前未更新perDibiSharedDbl时间段的产出，但不更新状态，因而无需gas
        uint256 _perDibiIncDbl = _calPerDibiIncDbl();
        return stakers[user].rewardPending + ( ( perDibiSharedDbl + _perDibiIncDbl ) * stakers[user].stakeBalance - stakers[user].harvestDebt ) / 1e18;
    }

    ///@dev 查看指定用户质押DIBI数量
    ///@param user 指定用户
    function getAmountStakedByAddr(address user) external view returns(uint256){
        return stakers[user].stakeBalance;
    }


    ///old methods
    function accountStoked(address addr) external view returns (uint256) {
        return stakers[addr].stakeBalance;
    }

    function balanceOf(address _account) external view returns (uint256){
        return DBLendToken(DBL).balanceOf(_account);
    }

    function setRewardPaused(bool state) external onlyOwner returns (bool) {
        if(state){
            _calPerDibiSharedDbl();
        }
        rewardGuardianPaused = state;
        emit ActionPaused("Reward", state);
        return state;
    }

    function setStakePaused(bool state) external onlyOwner returns (bool) {
        stakeGuardianPaused = state;
        emit ActionPaused("Stake", state);
        return state;
    }

    function _setPendingAdmin(address _pendingAdming) external {
        require(msg.sender == admin && _pendingAdming != address(0),"Miner::Only Admin Allown");
        address oldPendingAdmin = pendingAdmin;
        pendingAdmin = _pendingAdming;
        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
    }

    function _acceptAdmin() external {
        require(msg.sender == pendingAdmin, "Miner::Must PendingAdmin");
        address oldAdmin = admin;
        admin = pendingAdmin;
        pendingAdmin=address(0);
        emit NewAdmin(oldAdmin,admin);
    }

}