// File: contracts/entry/Entrypoint.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/*
This Entrypoint contract is what the website uses to interact with the rest of
the system. Users may interact with other contracts directly.
*/

import "../token/ResearchTokenFactory.sol";
import "../token/ResearchTokenInput.sol";
import "../distributor/DistributorV2Factory.sol";

contract Entrypoint {
    DistributorV2Factory immutable distributorFactory;
    ResearchTokenFactory immutable tokenFactory;

    constructor(address researchPortfolioGnosis) {
        // The researchPortfolioGnosis should be one of the following:
        // Goerli: 0x6f07856f4974A32a54A0A0045eDfAEd97Cc78136
        // Mainnet: 0xAAbF8DC8c8208e023c5D8e2d0e3dd30415559E0E
        distributorFactory = new DistributorV2Factory(researchPortfolioGnosis);
        tokenFactory = new ResearchTokenFactory();
    }

    error IncompatibleSizeInputs(uint256 addressSize, uint256 amountSize);

    event CreateResearchTokenAndDistributor(address token, address distributor);
    event CreateDistributorV2(address distributor);

    // This function creates a ResearchToken, then mints it to recipients and
    // distributes it to claimers.
    // Args:
    //  input: A ResearchTokenInput struct.
    //  merkleDistribution: A MerkleDistribution struct.
    //  addresses: a list of addresses to distribute to.
    //  amounts: a list of amounts to distribute; same length as addresses.
    // Returns:
    //  the address of the research token.
    //  the address of the distributor, possibly 0x0 if nothing to distribute.
    function createAndDistributeResearchToken(
        ResearchTokenInput memory input,
        MerkleDistribution memory merkleDistribution,
        address[] memory addresses,
        uint256[] memory amounts
    ) external returns (address, address) {
        if (addresses.length != amounts.length) {
            revert IncompatibleSizeInputs(addresses.length, amounts.length);
        }

        address minter = msg.sender;

        address token = tokenFactory.createResearchToken(minter, input);

        address distributor;
        if (merkleDistribution.amount > 0) {
            // The returnTokenAddress is here for safety purposes. It should be
            // the Research Portfolio gnosis address for the network this is on.
            // If going through the Research Portfolio website, this is what 
            // happens. If manually creating a token with Entrypoint contract,
            // then the funder has the choice of what to use. We recommend using
            // the same gnosis address in order to remain in good standing with
            // the community.
            distributor = distributorFactory.createDistributorV2(
                merkleDistribution.merkleRoot,
                merkleDistribution.manifest,
                merkleDistribution.returnTokenAddress
            );
            ResearchToken(token).mint(distributor, merkleDistribution.amount);
            DistributorV2(distributor).setToken(address(token));
        }

        uint256 addressesLength = addresses.length;
        for (uint i = 0; i < addressesLength; i++) {
            ResearchToken(token).mint(addresses[i], amounts[i]);
        }

        ResearchToken(token).freezeMinting();

        emit CreateResearchTokenAndDistributor(token, distributor);

        return (token, distributor);
    }

    function claimForAccountFromDistributorV2(
        address distributor,
        uint256 index,
        uint256 amount,
        bytes32[] calldata merkleProof
    ) external {
        IDistributorV2 md = IDistributorV2(distributor);
        md.claimForAccount(index, amount, msg.sender, merkleProof);
    }

    function createDistributorV2(
        bytes32 merkleRoot,
        string calldata manifest,
        address tokenAddress,
        address returnTokenAddress
    ) external returns (address) {
        address distributor = distributorFactory.createDistributorV2(
            merkleRoot, manifest, returnTokenAddress);
        DistributorV2(distributor).setToken(tokenAddress);
        emit CreateDistributorV2(distributor);
        return distributor;
    }
}

// File: contracts/token/ResearchTokenFactory.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/*
The ResearchTokenFactory contract creates cloned ResearchToken contracts. It 
uses clone2 and is deterministic conditioned on minting address and research 
identifier.
*/

import "@openzeppelin/contracts/access/Ownable.sol";

import "../libraries/Clones.sol";
import "./MerkleDistribution.sol";
import "./ResearchTokenInput.sol";
import "./ResearchToken.sol";

contract ResearchTokenFactory is Ownable {
    using Clones for address;

    address immutable impl;

    error ResearchIdentifierEmpty();

    constructor() {
        impl = address(new ResearchToken());
    }

    event CreateResearchToken(address token);

    /*
        This function returns the salt used for clone2.
        Args:
            researchIdentifier: the research identifier.
            minter: the minter address.
        Returns:
            the salt.
    */
    function _getSalt(
        string memory researchIdentifier,
        address minter
    ) private pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(
                    type(ResearchToken).creationCode,
                    researchIdentifier,
                    minter
                )
            );
    }

    /*
        This function creates a research token.
        Args:
            minter: The address recipient, likely minter, so referred to as such.
            input: A ResearchTokenInput.sol struct.
        Returns:
            the address of the cloned research token.
    */
    function createResearchToken(
        address minter,
        ResearchTokenInput memory input
    ) external onlyOwner returns (address) {
        if (bytes(input.researchIdentifier).length == 0) {
            revert ResearchIdentifierEmpty();
        }
        bytes32 salt = _getSalt(input.researchIdentifier, minter);
        address payable clone = payable(impl.cloneDeterministic(salt));
        ResearchToken(clone).initialize(input, minter);
        emit CreateResearchToken(clone);
        return clone;
    }

    /*
        This function returns the predicted clone2 address of a research token 
        given the research identifier and minter.
        Args:
            researchIdentifier: the research identifier.
            minter: the minter address.
        Returns:
            the predicted clone2 address.
    */
    function getResearchTokenPredictedAddress(
        string memory researchIdentifier,
        address minter
    ) external view returns (address) {
        bytes32 salt = _getSalt(researchIdentifier, minter);
        return impl.predictDeterministicAddress(salt);
    }
}

// File: contracts/token/ResearchTokenInput.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

struct ResearchTokenInput {
    string name;
    string symbol;
    string researchIdentifier;
    string metadata;
}

// File: contracts/distributor/DistributorV2Factory.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/*
The DistributorV2Factory contract creates cloned DistributorV2 contracts.
*/

import "@openzeppelin/contracts/access/Ownable.sol";

import "../libraries/Clones.sol";
import "./DistributorV2.sol";

contract DistributorV2Factory is Ownable {
    using Clones for address;

    address immutable impl;
    // The researchPortfolioGnosis should be one of the following:
    // Goerli: 0x6f07856f4974A32a54A0A0045eDfAEd97Cc78136
    // Mainnet: 0xAAbF8DC8c8208e023c5D8e2d0e3dd30415559E0E
    address public researchPortfolioGnosis;

    constructor(address researchPortfolioGnosis_) {
        researchPortfolioGnosis = researchPortfolioGnosis_;
        impl = address(new DistributorV2());
    }

    function createDistributorV2(
        bytes32 merkleRoot,
        string calldata manifest,
        address returnTokenAddress
    ) external onlyOwner returns (address) {
        address payable clone = payable(impl.clone());
        DistributorV2(clone).initialize(merkleRoot, manifest, 
            returnTokenAddress, researchPortfolioGnosis);
        return clone;
    }
}

// File: contracts/token/MerkleDistribution.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

struct MerkleDistribution {
    string manifest;
    bytes32 merkleRoot;
    uint256 amount;
    address returnTokenAddress;
}

// File: contracts/libraries/Clones.sol



// SPDX-License-Identifier: MIT
// NOTE: This was from the Immunefi Team.

pragma solidity ^0.8.19;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 *
 * Modified to implement the more-minimal variation described here https://medium.com/coinmonks/the-more-minimal-proxy-5756ae08ee48
 */

library Clones {
    error CreateFailed();
    error Create2Failed();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        assembly {
            let ptr := mload(0x40)
            mstore(
                ptr,
                0x3d602c80600a3d3981f33d3d3d3d363d3d37363d730000000000000000000000
            )
            mstore(add(ptr, 0x15), shl(0x60, implementation))
            mstore(
                add(ptr, 0x29),
                0x5af43d3d93803e602a57fd5bf300000000000000000000000000000000000000
            )
            instance := create(0, ptr, 0x36)
        }
        if (instance == address(0)) {
            revert CreateFailed();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt
    ) internal returns (address instance) {
        assembly {
            let ptr := mload(0x40)
            mstore(
                ptr,
                0x3d602c80600a3d3981f33d3d3d3d363d3d37363d730000000000000000000000
            )
            mstore(add(ptr, 0x15), shl(0x60, implementation))
            mstore(
                add(ptr, 0x29),
                0x5af43d3d93803e602a57fd5bf300000000000000000000000000000000000000
            )
            instance := create2(0, ptr, 0x36, salt)
        }
        if (instance == address(0)) {
            revert Create2Failed();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly {
            let ptr := mload(0x40)
            mstore(
                ptr,
                0x3d602c80600a3d3981f33d3d3d3d363d3d37363d730000000000000000000000
            )
            mstore(add(ptr, 0x15), shl(0x60, implementation))
            mstore(
                add(ptr, 0x29),
                0x5af43d3d93803e602a57fd5bf3ff000000000000000000000000000000000000
            )
            mstore(add(ptr, 0x37), shl(0x60, deployer))
            mstore(add(ptr, 0x4b), salt)
            mstore(add(ptr, 0x6b), keccak256(ptr, 0x36))
            predicted := keccak256(add(ptr, 0x36), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

// File: contracts/token/ResearchToken.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/*
The ResearchToken is a clone contract that is largely an ERC20 and inherits from
ERC20Abstract. The major difference from other ERC20 contracts is that it has an 
important string attribute "researchIdentifier". It also "freeze"s, although 
that is not uncommon.
*/

import "../initializable/Initializable.sol";
import "../abstracts/ERC20Abstract.sol";
import "../interfaces/IERC20Distributor.sol";
import "../token/ResearchTokenInput.sol";

contract ResearchToken is Initializable, ERC20Abstract {
    uint256 public constant erc20_cap = 1000000 * 10 ** 18;
    string public metadata;
    string public researchIdentifier;
    bool public frozen;
    address public minter;

    error AlreadyFrozen();
    error MinterIsZero();
    error SupplyNotEqualToCap();
    error CapExceeded();

    function initialize(
        ResearchTokenInput memory input,
        address minter_
    ) public virtual initializer {
        __ERC20Abstract_unchained(input.name, input.symbol);
        if (minter_ == address(0)) {
            revert MinterIsZero();
        }
        minter = minter_;

        metadata = input.metadata;
        researchIdentifier = input.researchIdentifier;
    }

    function freezeMinting() public {
        // NOTE: This gets called by the Entrypoint right after creation. If
        // that is changed, then this needs another guard.
        if (frozen) {
            revert AlreadyFrozen();
        }
        if (totalSupply() != erc20_cap) {
            revert SupplyNotEqualToCap();
        }
        frozen = true;
    }

    function mint(address account, uint256 amount) public {
        if (frozen) {
            revert AlreadyFrozen();
        }
        if (totalSupply() + amount > erc20_cap) {
            revert CapExceeded();
        }
        _mint(account, amount);
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: 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() {
        _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);
    }
}

// File: contracts/initializable/Initializable.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/*
  This was taken from OpenZeppelin.
*/

/**
 * @title Initializable
 *
 * @dev Helper contract to support initializer functions. To use it, replace
 * the constructor with a function that has the `initializer` modifier.
 * WARNING: Unlike constructors, initializer functions must be manually
 * invoked. This applies both to deploying an Initializable contract, as well
 * as extending an Initializable contract via inheritance.
 * WARNING: When used with inheritance, manual care must be taken to not invoke
 * a parent initializer twice, or ensure that all initializers are idempotent,
 * because this is not dealt with automatically as with constructors.
 */
contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private initialized;
    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private initializing;

    error AlreadyInitialized();

    /**
     * @dev Modifier to use in the initializer function of a contract.
     */
    modifier initializer() {
        if (!(initializing || isConstructor() || !initialized)) {
            revert AlreadyInitialized();
        }

        bool isTopLevelCall = !initializing;
        if (isTopLevelCall) {
            initializing = true;
            initialized = true;
        }

        _;

        if (isTopLevelCall) {
            initializing = false;
        }
    }

    /// @dev Returns true if and only if the function is running in the constructor
    function isConstructor() private view returns (bool) {
        // extcodesize checks the size of the code stored in an address, and
        // address returns the current address. Since the code is still not
        // deployed when running a constructor, any checks on its code size will
        // yield zero, making it an effective way to detect if a contract is
        // under construction or not.
        address self = address(this);
        uint256 cs;
        assembly {
            cs := extcodesize(self)
        }
        return cs == 0;
    }
}

// File: contracts/abstracts/ERC20Abstract.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.19;

/*
This was taken from OpenZeppelin and modified only slightly.
*/

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../initializable/Initializable.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 Contracts guidelines: functions revert
 * instead 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}.
 */
abstract contract ERC20Abstract is IERC20, IERC20Metadata, Initializable {
    mapping(address => uint256) private _erc20_balances;
    mapping(address => mapping(address => uint256)) private _erc20_allowances;
    uint256 private _erc20_totalSupply;
    string private _erc20_name;
    string private _erc20_symbol;

    error AllowanceBelowZero();
    error AllowanceInsufficient();
    error ApproveFromZero();
    error ApproveToZero();
    error MintToZero();
    error TransferFromZero();
    error TransferToZero();
    error TransferExceedsBalance();

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20Abstract_unchained(
        string memory name_,
        string memory symbol_
    ) public initializer {
        _erc20_name = name_;
        _erc20_symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _erc20_name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _erc20_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
     * overridden;
     *
     * 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 override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _erc20_totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(
        address account
    ) public view virtual override returns (uint256) {
        return _erc20_balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address owner = msg.sender;
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(
        address owner,
        address spender
    ) public view virtual override returns (uint256) {
        return _erc20_allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(
        address spender,
        uint256 amount
    ) public virtual override returns (bool) {
        address owner = msg.sender;
        _approve(owner, 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}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = msg.sender;
        _spendAllowance(from, spender, amount);
        _transfer(from, to, 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) {
        address owner = msg.sender;
        _approve(owner, spender, allowance(owner, 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) {
        address owner = msg.sender;
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance >= subtractedValue) {
            revert AllowanceBelowZero();
        }
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This 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:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        if (from == address(0)) {
            revert TransferFromZero();
        }
        if (to == address(0)) {
            revert TransferToZero();
        }

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _erc20_balances[from];
        if (fromBalance < amount) {
            revert TransferExceedsBalance();
        }
        unchecked {
            _erc20_balances[from] = fromBalance - amount;
        }
        _erc20_balances[to] = _erc20_balances[to] + amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, 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:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        if (account == address(0)) {
            revert MintToZero();
        }

        _beforeTokenTransfer(address(0), account, amount);

        _erc20_totalSupply = _erc20_totalSupply + amount;
        _erc20_balances[account] = _erc20_balances[account] + amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, 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 {
        if (owner == address(0)) {
            revert ApproveFromZero();
        }
        if (spender == address(0)) {
            revert ApproveToZero();
        }

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

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < amount) {
                revert AllowanceInsufficient();
            }
            unchecked {
                _approve(owner, spender, currentAllowance - 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 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 {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

// File: contracts/interfaces/IERC20Distributor.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;

/*
    Interface for a Distributor of ERC20 tokens.
*/

// The DistributorTypeMerkleV# constants identify the Distributor type. These
// are used when emitting events.
uint256 constant DistributorTypeMerkleV1 = 1;
uint256 constant DistributorTypeMerkleV2 = 2;

// Allows anyone to claim a token if they haven't already.
interface IERC20Distributor {
    // Returns the address of the token distributed by this contract.
    function token() external view returns (address);

    function manifest() external view returns (string memory);

    // Returns true if the index has been marked claimed.
    function isClaimed(uint256 index) external view returns (bool);

    // Sets the token for the Distributor. Aborts if already done.
    function setToken(address token_) external;

    // This event is triggered whenever a call to #claim succeeds.
    event ERC20ClaimForAccount(uint256 index, uint256 amount, address account);

    // This event is triggered when the (first) call to #distribute succeeds.
    event ERC20Distribution(address token, uint256 distributorType);
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: 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);
}

// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @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 decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: 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) {
        return msg.data;
    }
}

// File: contracts/distributor/DistributorV2.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;

/*
The DistributorV2 is a clone contract version of the Uniswap Distributor. 
It expects a merkleRoot and a manifest, which is a public IPFS CID where to find
the full merkle tree.
*/

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "../initializable/Initializable.sol";
import "../interfaces/IDistributorV2.sol";

contract DistributorV2 is Initializable, IDistributorV2 {
    address public override token;
    bytes32 public override merkleRoot;
    string public manifest;
    // This is a packed array of booleans.
    mapping(uint256 => uint256) private claimedBitMap;
    // The returnTokenAddress is here for safety purposes. Its intended use is 
    // only when something goes wrong with the distributor and we need to redo
    // it. If this has a primary funder (like with the Amaranth Prize), then it
    // is set to that funder. Otherwise, it is set to the gnosis address for the
    // RP org. This is sacrificing some web3 purity for the sake of user
    // experience, where user is both funder and recipient.
    address public returnTokenAddress;

    // The researchPortfolioGnosis should be one of the following:
    // Goerli: 0x6f07856f4974A32a54A0A0045eDfAEd97Cc78136
    // Mainnet: 0xAAbF8DC8c8208e023c5D8e2d0e3dd30415559E0E
    address public researchPortfolioGnosis;

    error InvalidSenderAddress();
    error MerkleRootIsZero();
    error ManifestIsEmpty();
    error NullReturnTokenAddress();
    error TokenIsSet();
    error TokenIsZeroAddress();
    error AlreadyClaimed();
    error InvalidProof();
    error TransferFailed();
    
    function initialize(
        bytes32 merkleRoot_,
        string memory manifest_,
        address returnTokenAddress_,
        address researchPortfolioGnosis_
    ) public virtual initializer {
        if (merkleRoot_ == bytes32(0)) {
            revert MerkleRootIsZero();
        }
        if (bytes(manifest_).length == 0) {
            revert ManifestIsEmpty();
        }        
        __DistributorV2_init(merkleRoot_, manifest_, returnTokenAddress_, 
            researchPortfolioGnosis_);
    }

    function __DistributorV2_init(
        bytes32 merkleRoot_,
        string memory manifest_,
        address returnTokenAddress_,
        address researchPortfolioGnosis_
    ) internal initializer {
        // Do the chain of initializations here.
        __DistributorV2_init_unchained(merkleRoot_, manifest_, 
            returnTokenAddress_, researchPortfolioGnosis_);
    }

    function __DistributorV2_init_unchained(
        bytes32 merkleRoot_,
        string memory manifest_,
        address returnTokenAddress_,
        address researchPortfolioGnosis_
    ) internal initializer {
        merkleRoot = merkleRoot_;
        manifest = manifest_;
        returnTokenAddress = returnTokenAddress_;
        researchPortfolioGnosis = researchPortfolioGnosis_;
    }

    function setToken(address token_) external override {
        if (token != address(0x0)) {
            revert TokenIsSet();
        }
        if (token_ == address(0x0)) {
            revert TokenIsZeroAddress();
        }
        token = token_;
        emit ERC20Distribution(token_, DistributorTypeMerkleV2);
    }

    function isClaimed(uint256 index) public view override returns (bool) {
        uint256 claimedWordIndex = index / 256;
        uint256 claimedBitIndex = index % 256;
        uint256 claimedWord = claimedBitMap[claimedWordIndex];
        uint256 mask = (1 << claimedBitIndex);
        return claimedWord & mask == mask;
    }

    function _setClaimed(uint256 index) private {
        uint256 claimedWordIndex = index / 256;
        uint256 claimedBitIndex = index % 256;
        claimedBitMap[claimedWordIndex] =
            claimedBitMap[claimedWordIndex] |
            (1 << claimedBitIndex);
    }

    function claimForAccount(
        uint256 index,
        uint256 amount,
        address account,
        bytes32[] calldata merkleProof
    ) public override {
        if (isClaimed(index)) {
            revert AlreadyClaimed();
        }

        // Verify the merkle proof.
        bytes32 node = keccak256(
            abi.encodePacked(index, amount, account)
        );
        if (!MerkleProof.verify(merkleProof, merkleRoot, node)) {
            revert InvalidProof();
        }

        // Mark it claimed and send the token.
        _setClaimed(index);
        if (!IERC20(token).transfer(account, amount)) {
            revert TransferFailed();
        }
        emit ERC20ClaimForAccount(index, amount, account);
    }

    /*
    Withdraw can only be called by a Research Portfolio gnosis address, which
    are hardcoded at the top. This is in order to limit the action just to the 
    trusted organization. Note that if the returnTokenAddress is not set, then
    this function doesn't actually do anything. Otherwise, the withdrawn token 
    goes to the returnTokenAddress. 
    
    This is just meant to be used in case of there being a problem with this 
    distributor.
    */
    function withdraw() external {
        if (returnTokenAddress == address(0x0)) {
            revert NullReturnTokenAddress();
        }
        if (msg.sender != researchPortfolioGnosis) {
            revert InvalidSenderAddress();
        }        

        uint256 balance = IERC20(token).balanceOf(address(this));
        if (!IERC20(token).transfer(returnTokenAddress, balance)) {
            revert TransferFailed();
        }
    }

    /*
    withdrawBalance is similar to above. The difference is that the caller can 
    specify an amount to transfer.
    
    This is just meant to be used in case of there being a problem with this 
    distributor and we want to return a small amount. An example is if the email
    embedded wallet is unreachable.
    */
    function withdrawAmount(uint256 amount) external {
        if (returnTokenAddress == address(0x0)) {
            revert NullReturnTokenAddress();
        }
        if (msg.sender != researchPortfolioGnosis) {
            revert InvalidSenderAddress();
        }        
        
        if (!IERC20(token).transfer(returnTokenAddress, amount)) {
            revert TransferFailed();
        }
    }    
}

// File: contracts/interfaces/IDistributorV2.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;

/*
    Interface for the DistributorV2. Adds two functions onto IERC20Distributor.
*/

import "./IERC20Distributor.sol";

interface IDistributorV2 is IERC20Distributor {
    // Returns the merkle root of the merkle tree containing account balances available to claim.
    function merkleRoot() external view returns (bytes32);

    // Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
    function claimForAccount(
        uint256 index,
        uint256 amount,
        address account,
        bytes32[] calldata merkleProof
    ) external;
}

// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Trees proofs.
 *
 * The proofs can be generated using the JavaScript library
 * https://github.com/miguelmota/merkletreejs[merkletreejs].
 * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
 *
 * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        bytes32 computedHash = leaf;

        for (uint256 i = 0; i < proof.length; i++) {
            bytes32 proofElement = proof[i];

            if (computedHash <= proofElement) {
                // Hash(current computed hash + current element of the proof)
                computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
            } else {
                // Hash(current element of the proof + current computed hash)
                computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
            }
        }

        // Check if the computed hash (root) is equal to the provided root
        return computedHash == root;
    }
}