// Contract: GoaldToken
// Target function: function goaldDeployed(address recipient, address goaldAddress) external returns (uint256)
     * 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 returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view 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);
        _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 {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].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 {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) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        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);

        _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 virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _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 virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        _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 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 Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

    /**
     * @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: GPL-3.0-or-later

pragma solidity 0.6.12;
interface IGoaldDAO {
    /** Returns the number of goalds deployed from this DAO. */
    function getGoaldCount() external view returns (uint256);

    /** Returns the current address that fees will be sent to. */
    function getProxyAddress() external view returns (address);

    /** Called if the DAO manager is no longer a holder after burning the initialization tokens. */
    function initializeDecreasesHolders() external;

    /** Called if the DAO manager is now a holder after claiming the initialization tokens. */
    function issuanceIncreasesHolders() external;
    
    /** Makes this DAO ready for deployments (regardless of whether or not there are authorized ones). */
    function makeReady(uint256 governanceStage, uint256 idOffset) external;

    /** Update the reward balances prior to the transfer completing. */
    function preTransfer(address sender, address recipient) external;

    /** Updates holder counts after doing a transfer. */
    function postTransfer(address sender, uint256 senderBefore, uint256 senderAfter, uint256 recipientBefore, uint256 recipientAfter) external;

    /** Called when the DAO has been initialized. */
    function updateGovernanceStage() external;
}

contract GoaldToken is ERC20 {
    address public _manager = msg.sender;

    /** @dev The DAO versions. DAOs only become invalid if they have a security vulnerability that compromises this contract. */
    address[] private _daoAddresses;
    mapping(address => uint256) private _isValidDAO;
    uint256 private constant UNTRACKED_DAO = 0;
    uint256 private constant VALID_DAO     = 1;
    uint256 private constant INVALID_DAO   = 2;

    /** @dev The number of decimals is small to allow for rewards of tokens with substantially different exchange rates. */
    uint8   private constant DECIMALS = 2;

    /** 
     * @dev The minimum amount of tokens necessary to be eligible for a reward. This is "one token", considering decimal places. We
     * are choosing two decimal places because we are initially targeting WBTC, which has 8. This way we can do a minimum reward ratio
     * of 1 / 1,000,000 of a WBTC, relative to our token. So at $25,000 (2020 value), the minimum reward would be $250 (assuming we
     * have issued all 10,000 tokens).
     */
    uint256 private constant REWARD_THRESHOLD = 10**uint256(DECIMALS);

    /**
     * @dev The maximum supply is 210,000 tokens. 110,000 tokens are burned on initiating the DAO; 10,000 are given to Bittrees for
     * initial management. The remainder are minted on a decreasing schedule based on the total number of deployed Goalds.
     */
    uint256 private constant MAX_SUPPLY = 210000 * REWARD_THRESHOLD;

    /** @dev The base token URI for the Goald metadata. */
    string  private _baseTokenURI;

    /** @dev The total number of deployed Goalds across all DAOs. */
    uint256 private _goaldCount;

    /**
     * @dev The stage of the governance token. Tokens can be issued based on deployments regardless of what stage we are in.
     *      0: Created, with no governance protocol initiated. The initial governance issuance can be claimed.
     *      1: Initial governance issuance has been claimed.
     *      2: The governance protocal has been initiated.
     *      3: All governance tokens have been issued.
     */
    uint256 private constant STAGE_INITIAL               = 0;
    uint256 private constant STAGE_ISSUANCE_CLAIMED      = 1;
    uint256 private constant STAGE_DAO_INITIATED         = 2;
    uint256 private constant STAGE_ALL_GOVERNANCE_ISSUED = 3;
    uint256 private _governanceStage;

    // Reentrancy reversions are the only calls to revert (in this contract) that do not have reasons. We add a third state, 'frozen'
    // to allow for locking non-admin functions. The contract may be permanently frozen if it has been upgraded.
    uint256 private constant RE_NOT_ENTERED = 1;
    uint256 private constant RE_ENTERED     = 2;
    uint256 private constant RE_FROZEN      = 3;
    uint256 private _status;

    // Separate reentrancy status to further guard against arbitrary calls against a DAO contract via `unsafeCallDAO()`.
    uint256 private _daoStatus;

    // Override decimal places to 2. See `GoaldProxy.REWARD_THRESHOLD`.
    constructor() ERC20("Goald", "GOALD") public {
        _setupDecimals(DECIMALS);
        _status    = RE_FROZEN;
        _daoStatus = RE_NOT_ENTERED;
    }

    /// Events ///
    
    event DAOStatusChanged(address daoAddress, uint256 status);

    event DAOUpgraded(address daoAddress);

    event GoaldDeployed(address goaldAddress);

    event ManagerChanged(address newManager);

    /// Admin ///

    /** Freezes the contract. Only admin functions can be called. */
    function freeze() external {
        // Reentrancy guard.
        require(_status == RE_NOT_ENTERED);
        require(msg.sender == _manager, "Not manager");

        _status = RE_FROZEN;
    }

    /** Sets the status of a given DAO. */
    function setDAOStatus(address daoAddress, uint256 index, uint256 status) external {
        // Reentrancy guard.
        require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);
        require(msg.sender == _manager, "Not manager");

        // Validate the index as well.
        require(_daoAddresses[index] == daoAddress, "Non-matching DAO index");

        // Validate the status.
        require(status == VALID_DAO || status == INVALID_DAO, "Invalid status");
        uint256 currentStatus = _isValidDAO[daoAddress];
        require(currentStatus != status && (currentStatus == VALID_DAO || currentStatus == INVALID_DAO), "Invalid current status");

        // Update the status.
        _isValidDAO[daoAddress] = status;

        // Hello world!
        emit DAOStatusChanged(daoAddress, status);
    }

    function setManager(address newManager) external {
        // Reentrancy guard.
        require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);
        require(msg.sender == _manager,      "Not manager");
        require(newManager != address(0),    "Can't be zero address");
        require(newManager != address(this), "Can't be this address");

        // If the issuance has been claimed but the DAO has not been initialized, then the new manager must be able to initialize it.
        require((_governanceStage != STAGE_ISSUANCE_CLAIMED) || (balanceOf(newManager) > 110000 * REWARD_THRESHOLD), "New manager can't init DAO");

        _manager = newManager;

        // Hello world!
        emit ManagerChanged(newManager);
    }

    /** Unfreezes the contract. Non-admin functions can again be called. */
    function unfreeze() external {
        // Reentrancy guard.
        require(_status == RE_FROZEN);
        require(msg.sender == _manager, "Not manager");

        _status = RE_NOT_ENTERED;
    }

    /** Upgrades to the new DAO version. Can only be done when frozen. */
    function upgradeDAO(address daoAddress) external {
        // Reentrancy guard.
        require(_status == RE_FROZEN);
        _status = RE_ENTERED;

        // It must be a contract.
        uint256 codeSize;
        assembly { codeSize := extcodesize(daoAddress) }
        require(codeSize > 0, "Not a contract");

        // Make sure it hasn't been tracked yet.
        require(_isValidDAO[daoAddress] == UNTRACKED_DAO, "DAO already tracked");

        // Upgrade the DAO.
        _daoAddresses.push(daoAddress);
        _isValidDAO[daoAddress] = VALID_DAO;

        // Enable the DAO.
        IGoaldDAO(daoAddress).makeReady(_governanceStage, _goaldCount);

        // Hello world!
        emit DAOUpgraded(daoAddress);

        // By storing the original amount once again, a refund is triggered (see https://eips.ethereum.org/EIPS/eip-2200).
        _status = RE_FROZEN;
    }

    /// Goalds ///

    /** Gets the base url for Goald metadata. */
    function getBaseTokenURI() external view returns (string memory) {
        return _baseTokenURI;
    }

    /** Gets the total number of deployed Goalds. */
    function getGoaldCount() external view returns (uint256) {
        return _goaldCount;
    }

    /** Returns the address of the DAO which deployed the Goald. */
    function getGoaldDAO(uint256 id) external view returns (address) {
        require(id < _goaldCount, "ID too large");

        uint256 addressesCount = _daoAddresses.length;
        uint256 index;
        uint256 goaldCount;
        address goaldAddress;

        for (; index < addressesCount; index ++) {
            goaldAddress = _daoAddresses[index];
            goaldCount += IGoaldDAO(goaldAddress).getGoaldCount();
            if (id <= goaldCount) {
                return goaldAddress;
            }
        }

        revert("Unknown DAO");
    }