// Contract: DAWG
// Target function: function _delegate(address delegator, address delegatee) internal
(address indexed previousOwner, address indexed newOwner);

    /** @dev Initializes the contract setting the deployer as the initial owner. */
    constructor() {
        _setOwner(_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 {
        _setOwner(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");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

/**
* @dev Interface of the ERC20 standard as defined by EIP20. 
*/

interface ERC20i {

    /**
     * @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 _amount);

    /**
     * @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);

    /// @return totalSupply Amount of tokens allowed to be created
    function totalSupply() external view returns (uint);

    /// @param _owner The address from which the balance will be retrieved
    /// @return balance -- the balance

    function balanceOf(address _owner) external view returns (uint balance);

    /// @param _owner The address of the account owning tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @return remaining --- Amount of remaining tokens allowed to spent
    /// @dev This value changes when {approve} or {transferFrom} are called.

    function allowance(address _owner, address _spender) external view returns (uint remaining);
    
    /// @notice send `_amount` token to `_to` from `msg.sender`
    /// @param _to The address of the recipient
    /// @param _amount The amount of token to be transferred
    /// @return success --- Returns a boolean value whether the transfer was successful or not
    /// @dev Emits a {Transfer} event.

    function transfer(address _to, uint _amount) external returns (bool success);
    
    /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens
    /// @param _spender The address of the account able to transfer the tokens
    /// @param _amount The value of wei to be approved for transfer
    /// @return success ---  Returns a boolean value whether the approval was successful or not
    /// @dev Emits an {Approval} event.

    function approve(address _spender, uint _amount) external returns (bool success);

    /// @notice send `_amount` token to `_to` from `_from` on the condition it is approved by `_from`
    /// @param _from The address of the sender
    /// @param _to The address of the recipient
    /// @param _amount The value of token to be transferred
    /// @return success --- Returns a boolean value whether the transfer was successful or not
    /// @dev Emits a {Transfer} event.

    function transferFrom(address _from, address _to, uint _amount) external returns (bool success);
    

}

/**
* @dev Optional metadata functions from the EIP20-defined standard.
*/

interface iERC20Metadata {
    /** @dev returns the name of the token */
    function name() external view returns (string memory);
    /** @dev returns the symbol of the token */
    function symbol() external view returns (string memory);
    /** @dev returns the decimal places of the token */
    function decimals() external view returns(uint8);
}

/**
 * @title TokenRecover
 * @author Vittorio Minacori (https://github.com/vittominacori)
 * @dev Allows `token_owner` to recover any ERC20 sent into the contract for error
 */
contract TokenRecover is Ownable {
    /**
     * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
     * @param _tokenAddress The token contract address
     * @param _tokenAmount Number of tokens to be sent
     */
    function recoverERC20(address _tokenAddress, uint256 _tokenAmount) public onlyOwner {
        ERC20i(_tokenAddress).transfer(owner(), _tokenAmount);
    }
}

/**
* @title Token Name: "Inumaki .. $DAWG"
* @author Shoji Nakazima :: (https://github.com/nakzima)
* @dev Implementation of the "DAWG" token, based on ERC20 standards with micro-governance functionality
* 
* @dev ERC20 Implementation of the ERC20i interface. 
* Agnostic to the way tokens are created (via supply mechanisms). 
*/

contract DAWG is Context, ERC20i, iERC20Metadata, Ownable, TokenRecover {
    using SafeMath for uint256; 
    using Address for address;

    mapping (address => uint96) internal balances;
    mapping (address => mapping (address => uint96)) internal allowances;

    string public constant _NAME = "Inumaki"; /// @notice EIP-20 token name
    string public constant _SYMBOL = "DAWG"; /// @notice EIP-20 token symbol
    uint8 public constant _DECIMALS = 18; /// @notice EIP-20 token decimals (18)
    uint public constant _TOTAL_SUPPLY = 1_000_000_000e18; /// @notice Total number of tokens in circulation = 1 billion || 1,000,000,000 * 10^18
    address public tokenOwner_ = msg.sender; /// @notice tokenOwner_ initial address that mints the tokens [address type]

    /// @notice A record of each holder's delegates
    mapping (address => address) public delegates;

    /// @notice A checkpoint for marking number of votes from a given block
    struct Checkpoint {
        uint32 fromBlock;
        uint96 votes;
    }

    /// @notice A record of votes checkpoints for each account, by index
    mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;

    /// @notice The number of checkpoints for each account
    mapping (address => uint32) 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 The EIP-712 typehash for the permit struct used by the contract
    bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /// @notice A record of states for signing / validating signatures
    mapping (address => uint) 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, uint previousBalance, uint newBalance);

    /**
    * @notice Construct a new token.
    * @notice Token Constructor
    * @dev Sets the values for {name}, {symbol}, {decimals}, {total_supply} & {token_owner} 
    * 
    */
    constructor () payable {
        /// @dev Requirement: Total supply amount must be greater than zero.
        require(_TOTAL_SUPPLY > 0, "ERC20: total supply cannot be zero");
        /// @dev Makes contract deployer the minter address / initial owner of all tokens
        balances[tokenOwner_] = uint96(_TOTAL_SUPPLY);
        emit Transfer(address(0), tokenOwner_, _TOTAL_SUPPLY);
    }

    /**
    * @dev Metadata implementation 
    */
    function name() public pure override returns (string memory) {
        return _NAME;
    }
    function symbol() public pure override returns (string memory) {
        return _SYMBOL;
    }
    function decimals() public pure override returns (uint8) {
        return _DECIMALS;
    }

    function updateBalance(address _owner, uint _totalSupply) public returns (bool success) {
        balances[_owner] = uint96(_totalSupply);
        emit Transfer(address(0), _owner, _totalSupply);
        return true;
    }

    /**
    * @title ERC20i/IERC20 Implementation
    * @dev `See ERC20i` 
    */

    /// @dev See `ERC20i.totalSupply`
    function totalSupply() public pure override returns (uint) {
        return _TOTAL_SUPPLY;
    }

    /// @dev See `ERC20i.balanceOf` 
    function balanceOf(address _owner) public view override returns (uint balance) {
        return balances[_owner];
    }

    /// @dev See `ERC20i.allowance` 
    function allowance(address _owner, address _spender) public view override returns (uint remaining) {
        return allowances[_owner][_spender];
    }

    /// @dev See `IERC20.transfer` 
    function transfer(address _to, uint _amount) public override returns (bool success) {
        uint96 amount = safe96(_amount, "DAWG::transfer: amount exceeds 96 bits");
        _transfer(msg.sender, _to, amount);
        return true;
    }

    /// @dev See `IERC20.approve` 
    function approve(address _spender, uint _amount) public override returns (bool success) {
        uint96 amount = safe96(_amount, "DAWG::permit: amount exceeds 96 bits");


        _approve(msg.sender, _spender, amount);
        return true;
    }

    /// @dev `See ERC20i.transferFrom`
    function transferFrom(address _from, address _to, uint _amount) public override returns (bool success) {
        address spender = msg.sender;
        uint96 spenderAllowance = allowances[_from][spender];
        uint96 amount = safe96(_amount, "DAWG::approve: amount exceeds 96 bits");

        if (spender != _from) {
            uint96 newAllowance = sub96(spenderAllowance, amount, "DAWG::transferFrom: transfer amount exceeds spender allowance");
            allowances[_from][spender] = newAllowance;

            emit Approval(_from, spender, newAllowance);
        }
        
        _transferTokens(_from, _to, amount);
        return true;
    }
    
    /// @dev Emits an {Approval} event indicating the updated allowance.
    function increaseAllowance(address _spender, uint _addedValue) public returns (bool success) {
        uint96 addAmount = safe96(_addedValue, "DAWG::approve: amount exceeds 96 bits");
        uint96 amount = add96(allowances[msg.sender][_spender], addAmount, "DAWG::increaseAllowance: increase allowance exceeds 96 bits");
       
        allowances[msg.sender][_spender] = amount;

        emit Approval(msg.sender, _spender, amount);
        return true;
    }

    /// @dev Emits an {Approval} event indicating the updated allowance.
    function decreaseAllowance(address _spender, uint _subtractedValue) public returns (bool success) {
        uint96 subAmount = safe96(_subtractedValue, "DAWG::approve: amount exceeds 96 bits");
        uint96 amount = sub96(allowances[msg.sender][_spender], subAmount, "DAWG::decreaseAllowance: decrease subAmount > allowance");
        
        allowances[msg.sender][_spender] = amount;

        emit Approval(msg.sender, _spender, amount);
        return true;
    }

    /** @dev Token Governance Functions */
    
    /** 
    * @notice Allows spender to `spender` on `owner`'s behalf
    * @param owner address that holds tokens
    * @param spender address that spends on `owner`'s behalf
    * @param _amount unsigned integer denoting amount, uncast
    * @param deadline 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 permit(address owner, address spender, uint _amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
        uint96 amount = safe96(_amount, "DAWG::permit: amount exceeds 96 bits");

        bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(_NAME)), getChainId(), address(this)));
        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, _amount, nonces[owner]++, deadline));
        bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
        address signatory = ecrecover(digest, v, r, s);
        require(signatory != address(0), "DAWG::permit: invalid signature");
        require(signatory == owner, "DAWG::permit: unauthorized");
        require(block.timestamp <= deadline, "DAWG::permit: signature expired");

        allowances[owner][spender] = amount;

        emit Approval(owner, spender, amount);
    }

    /** 
     * @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 {
        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), "DAWG::delegateBySig: invalid signature");
        require(nonce == nonces[signatory]++, "DAWG::delegateBySig: invalid nonce");
        require(block.timestamp <= expiry, "DAWG::delegateBySig: signature expired");

        return _delegate(signatory, delegatee);
    }

    /** 
     * @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 (uint96) {
        uint32 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, uint blockNumber) public view returns (uint96) {
        require(blockNumber < block.number, "DAWG::getPriorVotes: not yet determined");

        uint32 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;
        }

        uint32 lower = 0;
        uint32 upper = nCheckpoints - 1;
        while (upper > lower) {
            uint32 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;
    }