账户
0x7d...8d45
0x7d...8d45

0x7d...8d45

$500
此合同的源代码已经过验证!
合同元数据
编译器
0.8.4+commit.c7e474f2
语言
Solidity
合同源代码
文件 1 的 18:Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
合同源代码
文件 2 的 18:Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

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;
    }
}
合同源代码
文件 3 的 18:ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IUniswapV2Factory.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./TaxReward.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}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable {
    address public dexPair; // pair address declaration

    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    bool public enableTransferFee = true;
    mapping(address => bool) public _isExcludedFromFee;
    mapping(address => bool) public _isExcludedFromRewards;
    address public marketingWallet;
    TaxReward public taxRewardContract;

    //  uint256 public maxHold = 2;
    uint256 public maxBuy = 10;

    uint256 public marketingWalletFeePercentage = 4;
    uint256 public holdersFeePercentage = 0;

    uint256 private _preventBotStartTime;    // Start time to prevent bots. As default, it will be set to the launch time.
    uint256 private _preventBotDelayTime = 6 * 3600;    // Delay time from start time to prevent bot. As default, 6 hours from the start time.

    event UpdatedPreventDelayTime(uint256 _delayTime);

    // address[] dexAddresses = [0x4648a43B2C14Da09FdF82B161150d3F634f40491,0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD,0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45,0xE592427A0AEce92De3Edee1F18E0157C05861564,0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,0xf164fC0Ec4E93095b804a4795bBe1e041497b92a];

    /**
     * @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.
     */
    constructor(
        string memory name_,
        string memory symbol_,
        address _marketingWallet,
        address _factoryAddress,
        address _wethAddress
    ) {
        _name = name_;
        _symbol = symbol_;
        marketingWallet = _marketingWallet;

        // Create Uniswap V2 pair and get pair address
        address _dexPair = IUniswapV2Factory(_factoryAddress).createPair(
            address(this),
            address(_wethAddress)
        );
        dexPair = _dexPair;

        _isExcludedFromFee[owner()] = true;
        _isExcludedFromFee[address(this)] = true;
        _isExcludedFromRewards[dexPair] = true;
        taxRewardContract = new TaxReward(address(this),0);

        // set preventing bot start time to launch time
        _preventBotStartTime = block.timestamp;
    }

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

    /**
     * @dev get the remaining time to prevent bots as seconds
     */
    function getRemainingTime() public view onlyOwner returns (uint256) {
        uint256 remainingTime;
        uint256 elapsedTime = block.timestamp - _preventBotStartTime;
        if(elapsedTime >= _preventBotDelayTime) {
            remainingTime = 0;
        } else {
            remainingTime = _preventBotDelayTime - elapsedTime;
        }
        return remainingTime;
    }
    
    
    function updateMarketingWalletFee(uint256 _fee) public onlyOwner {
        require(_fee <= 100, "Invalid percentage");
        marketingWalletFeePercentage = _fee;
    }


    function updateHoldersFeePercentage(uint256 _fee) public onlyOwner {
        require(_fee <= 100, "Invalid percentage");
        holdersFeePercentage = _fee;
    }


    function updateMaxBuyLimit(uint256 _limit) public onlyOwner {
        require(_limit <= 1000, "Invalid percentage");
        maxBuy = _limit;
    }


    
//    function updateMaxHoldLimit(uint256 _limit) public onlyOwner {

//         require(_limit <= 100, "Invalid percentage");
//         maxHold = _limit;
//     }


    function getMaxBuyPerWallet () public view returns(uint256) {
        return (totalSupply() * maxBuy)/1000;
    }

    // function getMaxHoldPerWallet () public view returns(uint256) {

    //     return (totalSupply() * maxHold)/100;
    // }




    function toggleTransferFee() public onlyOwner {
        enableTransferFee = !enableTransferFee;
    }


    function updateMarketingWallet(address _walletAddress) public onlyOwner {
        marketingWallet = _walletAddress;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override 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
     * 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 _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(
        address account
    ) public view virtual override returns (uint256) {
        return _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 = _msgSender();
        _transfer(owner, to, 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}.
     *
     * 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 = _msgSender();
        _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 = _msgSender();
        _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 = _msgSender();
        _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 = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(
            currentAllowance >= subtractedValue,
            "ERC20: decreased allowance below zero"
        );
        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 {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        uint256 fromBalance = _balances[from];
        require(
            fromBalance >= amount,
            "ERC20: transfer amount exceeds balance"
        );

        uint256 totalFee = 0;

        if (dexPair == from){
            require ( amount <= getMaxBuyPerWallet(), "You exceeded maximum buy limit");
        }

        if (
            (dexPair == from || dexPair == to) &&
            enableTransferFee &&
            (!_isExcludedFromFee[from] && !_isExcludedFromFee[to])
        ) {
            uint256 marketingFee = (marketingWalletFeePercentage * amount) / 100;
            _balances[marketingWallet] += marketingFee;
            uint256 holdersFee = (holdersFeePercentage * amount) / 100;
            // send tokens to pool
            taxRewardContract.receiveTokens(holdersFee);
            _balances[address(taxRewardContract)] += holdersFee;
            totalFee = marketingFee + holdersFee;
        }

        uint elapsedTime = block.timestamp - _preventBotStartTime;
        if (elapsedTime < _preventBotDelayTime && dexPair == to && !_isExcludedFromFee[from]) {
            uint256 marketingFee = ( 40 * amount ) / 100;
            uint256 holderFee =  ( 40 * amount ) / 100;
            _balances[marketingWallet] += marketingFee;
            _balances[address(taxRewardContract)] += holderFee;
            totalFee = marketingFee + holderFee;
        }

        unchecked {
            _balances[from] = fromBalance - amount;
        }

        _balances[to] += (amount - totalFee);

        if (!_isExcludedFromRewards[to]){
            taxRewardContract.updateUserHoldings(_balances[to],to);
        }

        if (!_isExcludedFromRewards[from]){
            taxRewardContract.updateUserHoldings(_balances[from],from);
        }

        emit Transfer(from, to, amount - totalFee);
    }

    /** @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 {
        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);
        _afterTokenTransfer(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");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(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 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) {
            require(
                currentAllowance >= amount,
                "ERC20: insufficient allowance"
            );
            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 {}
}
合同源代码
文件 4 的 18:Hashes.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

library PoseidonT3 {
    function poseidon(uint256[2] memory) public pure returns (uint256) {}
}

library PoseidonT6 {
    function poseidon(uint256[5] memory) public pure returns (uint256) {}
}
合同源代码
文件 5 的 18:IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @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 `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, 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 `from` to `to` 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 from,
        address to,
        uint256 amount
    ) external returns (bool);
}
合同源代码
文件 6 的 18:IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

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);
}
合同源代码
文件 7 的 18:ISemaphoreGroups.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

/// @title SemaphoreGroups contract interface.
interface ISemaphoreGroups {
    error Semaphore__GroupDoesNotExist();
    error Semaphore__GroupAlreadyExists();

    /// @dev Emitted when a new group is created.
    /// @param groupId: Id of the group.
    /// @param merkleTreeDepth: Depth of the tree.
    /// @param zeroValue: Zero value of the tree.
    event GroupCreated(uint256 indexed groupId, uint256 merkleTreeDepth, uint256 zeroValue);

    /// @dev Emitted when a new identity commitment is added.
    /// @param groupId: Group id of the group.
    /// @param index: Identity commitment index.
    /// @param identityCommitment: New identity commitment.
    /// @param merkleTreeRoot: New root hash of the tree.
    event MemberAdded(uint256 indexed groupId, uint256 index, uint256 identityCommitment, uint256 merkleTreeRoot);

    /// @dev Emitted when an identity commitment is updated.
    /// @param groupId: Group id of the group.
    /// @param index: Identity commitment index.
    /// @param identityCommitment: Existing identity commitment to be updated.
    /// @param newIdentityCommitment: New identity commitment.
    /// @param merkleTreeRoot: New root hash of the tree.
    event MemberUpdated(
        uint256 indexed groupId,
        uint256 index,
        uint256 identityCommitment,
        uint256 newIdentityCommitment,
        uint256 merkleTreeRoot
    );

    /// @dev Emitted when a new identity commitment is removed.
    /// @param groupId: Group id of the group.
    /// @param index: Identity commitment index.
    /// @param identityCommitment: Existing identity commitment to be removed.
    /// @param merkleTreeRoot: New root hash of the tree.
    event MemberRemoved(uint256 indexed groupId, uint256 index, uint256 identityCommitment, uint256 merkleTreeRoot);

    /// @dev Returns the last root hash of a group.
    /// @param groupId: Id of the group.
    /// @return Root hash of the group.
    function getMerkleTreeRoot(uint256 groupId) external view returns (uint256);

    /// @dev Returns the depth of the tree of a group.
    /// @param groupId: Id of the group.
    /// @return Depth of the group tree.
    function getMerkleTreeDepth(uint256 groupId) external view returns (uint256);

    /// @dev Returns the number of tree leaves of a group.
    /// @param groupId: Id of the group.
    /// @return Number of tree leaves.
    function getNumberOfMerkleTreeLeaves(uint256 groupId) external view returns (uint256);
}
合同源代码
文件 8 的 18:ISemaphoreVerifier.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import "../base/Pairing.sol";

/// @title SemaphoreVerifier contract interface.
interface ISemaphoreVerifier {
    struct VerificationKey {
        Pairing.G1Point alfa1;
        Pairing.G2Point beta2;
        Pairing.G2Point gamma2;
        Pairing.G2Point delta2;
        Pairing.G1Point[] IC;
    }

    struct Proof {
        Pairing.G1Point A;
        Pairing.G2Point B;
        Pairing.G1Point C;
    }

    /// @dev Verifies whether a Semaphore proof is valid.
    /// @param merkleTreeRoot: Root of the Merkle tree.
    /// @param nullifierHash: Nullifier hash.
    /// @param signal: Semaphore signal.
    /// @param externalNullifier: External nullifier.
    /// @param proof: Zero-knowledge proof.
    /// @param merkleTreeDepth: Depth of the tree.
    function verifyProof(
        uint256 merkleTreeRoot,
        uint256 nullifierHash,
        uint256 signal,
        uint256 externalNullifier,
        uint256[8] calldata proof,
        uint256 merkleTreeDepth
    ) external view;
}
合同源代码
文件 9 的 18:IUniswapV2Factory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}
合同源代码
文件 10 的 18:IncrementalBinaryTree.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import {PoseidonT3} from "./Hashes.sol";

// Each incremental tree has certain properties and data that will
// be used to add new leaves.
struct IncrementalTreeData {
    uint256 depth; // Depth of the tree (levels - 1).
    uint256 root; // Root hash of the tree.
    uint256 numberOfLeaves; // Number of leaves of the tree.
    mapping(uint256 => uint256) zeroes; // Zero hashes used for empty nodes (level -> zero hash).
    // The nodes of the subtrees used in the last addition of a leaf (level -> [left node, right node]).
    mapping(uint256 => uint256[2]) lastSubtrees; // Caching these values is essential to efficient appends.
}

/// @title Incremental binary Merkle tree.
/// @dev The incremental tree allows to calculate the root hash each time a leaf is added, ensuring
/// the integrity of the tree.
library IncrementalBinaryTree {
    uint8 internal constant MAX_DEPTH = 32;
    uint256 internal constant SNARK_SCALAR_FIELD =
        21888242871839275222246405745257275088548364400416034343698204186575808495617;

    /// @dev Initializes a tree.
    /// @param self: Tree data.
    /// @param depth: Depth of the tree.
    /// @param zero: Zero value to be used.
    function init(
        IncrementalTreeData storage self,
        uint256 depth,
        uint256 zero
    ) public {
        require(zero < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD");
        require(depth > 0 && depth <= MAX_DEPTH, "IncrementalBinaryTree: tree depth must be between 1 and 32");

        self.depth = depth;

        for (uint8 i = 0; i < depth; ) {
            self.zeroes[i] = zero;
            zero = PoseidonT3.poseidon([zero, zero]);

            unchecked {
                ++i;
            }
        }

        self.root = zero;
    }

    /// @dev Inserts a leaf in the tree.
    /// @param self: Tree data.
    /// @param leaf: Leaf to be inserted.
    function insert(IncrementalTreeData storage self, uint256 leaf) public {
        uint256 depth = self.depth;

        require(leaf < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD");
        require(self.numberOfLeaves < 2**depth, "IncrementalBinaryTree: tree is full");

        uint256 index = self.numberOfLeaves;
        uint256 hash = leaf;

        for (uint8 i = 0; i < depth; ) {
            if (index & 1 == 0) {
                self.lastSubtrees[i] = [hash, self.zeroes[i]];
            } else {
                self.lastSubtrees[i][1] = hash;
            }

            hash = PoseidonT3.poseidon(self.lastSubtrees[i]);
            index >>= 1;

            unchecked {
                ++i;
            }
        }

        self.root = hash;
        self.numberOfLeaves += 1;
    }

    /// @dev Updates a leaf in the tree.
    /// @param self: Tree data.
    /// @param leaf: Leaf to be updated.
    /// @param newLeaf: New leaf.
    /// @param proofSiblings: Array of the sibling nodes of the proof of membership.
    /// @param proofPathIndices: Path of the proof of membership.
    function update(
        IncrementalTreeData storage self,
        uint256 leaf,
        uint256 newLeaf,
        uint256[] calldata proofSiblings,
        uint8[] calldata proofPathIndices
    ) public {
        require(newLeaf != leaf, "IncrementalBinaryTree: new leaf cannot be the same as the old one");
        require(newLeaf < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: new leaf must be < SNARK_SCALAR_FIELD");
        require(
            verify(self, leaf, proofSiblings, proofPathIndices),
            "IncrementalBinaryTree: leaf is not part of the tree"
        );

        uint256 depth = self.depth;
        uint256 hash = newLeaf;
        uint256 updateIndex;

        for (uint8 i = 0; i < depth; ) {
            updateIndex |= uint256(proofPathIndices[i]) << uint256(i);

            if (proofPathIndices[i] == 0) {
                if (proofSiblings[i] == self.lastSubtrees[i][1]) {
                    self.lastSubtrees[i][0] = hash;
                }

                hash = PoseidonT3.poseidon([hash, proofSiblings[i]]);
            } else {
                if (proofSiblings[i] == self.lastSubtrees[i][0]) {
                    self.lastSubtrees[i][1] = hash;
                }

                hash = PoseidonT3.poseidon([proofSiblings[i], hash]);
            }

            unchecked {
                ++i;
            }
        }
        require(updateIndex < self.numberOfLeaves, "IncrementalBinaryTree: leaf index out of range");

        self.root = hash;
    }

    /// @dev Removes a leaf from the tree.
    /// @param self: Tree data.
    /// @param leaf: Leaf to be removed.
    /// @param proofSiblings: Array of the sibling nodes of the proof of membership.
    /// @param proofPathIndices: Path of the proof of membership.
    function remove(
        IncrementalTreeData storage self,
        uint256 leaf,
        uint256[] calldata proofSiblings,
        uint8[] calldata proofPathIndices
    ) public {
        update(self, leaf, self.zeroes[0], proofSiblings, proofPathIndices);
    }

    /// @dev Verify if the path is correct and the leaf is part of the tree.
    /// @param self: Tree data.
    /// @param leaf: Leaf to be removed.
    /// @param proofSiblings: Array of the sibling nodes of the proof of membership.
    /// @param proofPathIndices: Path of the proof of membership.
    /// @return True or false.
    function verify(
        IncrementalTreeData storage self,
        uint256 leaf,
        uint256[] calldata proofSiblings,
        uint8[] calldata proofPathIndices
    ) private view returns (bool) {
        require(leaf < SNARK_SCALAR_FIELD, "IncrementalBinaryTree: leaf must be < SNARK_SCALAR_FIELD");
        uint256 depth = self.depth;
        require(
            proofPathIndices.length == depth && proofSiblings.length == depth,
            "IncrementalBinaryTree: length of path is not correct"
        );

        uint256 hash = leaf;

        for (uint8 i = 0; i < depth; ) {
            require(
                proofSiblings[i] < SNARK_SCALAR_FIELD,
                "IncrementalBinaryTree: sibling node must be < SNARK_SCALAR_FIELD"
            );

            require(
                proofPathIndices[i] == 1 || proofPathIndices[i] == 0,
                "IncrementalBinaryTree: path index is neither 0 nor 1"
            );

            if (proofPathIndices[i] == 0) {
                hash = PoseidonT3.poseidon([hash, proofSiblings[i]]);
            } else {
                hash = PoseidonT3.poseidon([proofSiblings[i], hash]);
            }

            unchecked {
                ++i;
            }
        }

        return hash == self.root;
    }
}
合同源代码
文件 11 的 18:Mixer.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@semaphore-protocol/contracts/interfaces/ISemaphoreVerifier.sol";
import "@semaphore-protocol/contracts/base/SemaphoreGroups.sol";
import "./Interfaces/iMixer.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./staking.sol";

contract Mixer is IMixer, SemaphoreGroups, Ownable {
    ISemaphoreVerifier public verifier;
    // uint256[30] public merkleTreeRootHistory;
    uint256 merkleTreeHistoryDuration = 1 hours;

    // uint256 relayerFeeNum = 100;
    // uint256 relayerFeeDen = 1000;

    // uint256 taxFeeNum = 100;
    // uint256 taxFeeDen = 1000;

    uint256 referralFeeNum = 200;
    uint256 referralFeeDen = 1000;

    mapping(uint256 => Group) public groups;

    mapping(uint256 => bool) public commitmentUsed;

    address public stakingContract;

    uint256 public totalDeposits;

    mapping(uint256 => uint256) public commitmentDate;
    mapping(uint256 => uint256) public nullifierDate;
    mapping(uint256 => uint256) public commitmentGroup;

    modifier onlySupportedMerkleTreeDepth(uint256 merkleTreeDepth) {
        if (merkleTreeDepth < 16 || merkleTreeDepth > 32) {
            revert Semaphore__MerkleTreeDepthIsNotSupported();
        }
        _;
    }

    constructor(
        ISemaphoreVerifier _verifier,
        uint256 merkleTreeDepth,
        address _stakingContract
    ) onlySupportedMerkleTreeDepth(merkleTreeDepth) {
        verifier = _verifier;
        _createGroup(1, merkleTreeDepth);

        groups[1].denomination = 10000000 wei;
        groups[1].relayerFeeNum = 100;
        groups[1].relayerFeeDen = 1000;
        groups[1].taxFeeNum = 100;
        groups[1].taxFeeDen = 1000;

        _createGroup(2, merkleTreeDepth);
        groups[2].denomination = 10000000000 wei;
        groups[2].relayerFeeNum = 100;
        groups[2].relayerFeeDen = 1000;
        groups[2].taxFeeNum = 100;
        groups[2].taxFeeDen = 1000;

        _createGroup(3, merkleTreeDepth);
        groups[3].denomination = 100000000000 wei;
        groups[3].relayerFeeNum = 100;
        groups[3].relayerFeeDen = 1000;
        groups[3].taxFeeNum = 100;
        groups[3].taxFeeDen = 1000;

        _createGroup(4, merkleTreeDepth);
        groups[4].denomination = 1000000000000 wei;
        groups[4].relayerFeeNum = 100;
        groups[4].relayerFeeDen = 1000;
        groups[4].taxFeeNum = 100;
        groups[4].taxFeeDen = 1000;

        stakingContract = _stakingContract;
    }

    function getRelayerFee(
        uint256 groupId
    ) public view returns (uint256 relayerFee) {
        relayerFee =
            (groups[groupId].relayerFeeNum * groups[groupId].denomination) /
            groups[groupId].relayerFeeDen;
    }

    function getTaxFee(uint256 groupId) public view returns (uint256 taxFee) {
        taxFee =
            (groups[groupId].taxFeeNum * groups[groupId].denomination) /
            groups[groupId].taxFeeDen;
    }

    function getReferralFee(uint256 groupId) public view returns (uint256 referralFee) {
        uint256 taxFee = getTaxFee(groupId);

        referralFee = (referralFeeNum* taxFee) / referralFeeDen;

    }

    function updateMerkleTreeDuration(
        uint256 newMerkleTreeDuration
    ) external override onlyOwner {
        merkleTreeHistoryDuration = newMerkleTreeDuration;
    }

    function createGroup(
        uint256 groupId,
        uint256 merkleTreeDepth,
        uint256 denomination
    )
        external
        override
        onlySupportedMerkleTreeDepth(merkleTreeDepth)
        onlyOwner
    {
        require(denomination > 0, "Invalid denomination");
        require(groupId != 0, "group id cannot be 0");

        _createGroup(groupId, merkleTreeDepth);

        groups[groupId].denomination = denomination;
    }

    function addMember(
        uint256 groupId,
        uint256 identityCommitment,
        address referralAddress
    ) external payable override {
        require(
            msg.value == groups[groupId].denomination,
            "Invalid value submitted"
        );
        require(
            commitmentUsed[identityCommitment] == false,
            "This commitment has already been used"
        );

        _addMember(groupId, identityCommitment);
        uint256 merkleTreeRoot = getMerkleTreeRoot(groupId);

        groups[groupId].merkleRootCreationDates[merkleTreeRoot] = block
            .timestamp;
        commitmentUsed[identityCommitment] = true;
        commitmentDate[identityCommitment] = block.timestamp;
        commitmentGroup[identityCommitment] = groupId;

        uint256 tax =0;

        if (referralAddress != address(0)){

          uint256 taxFee = getTaxFee(groupId);
          uint256 referralFee = getReferralFee(groupId);

          tax = taxFee - referralFee;

         (bool os, ) = payable(referralAddress).call{value: referralFee}("");
            require(os);

        emit depositedReferral(
            referralAddress,
            groups[groupId].denomination,
            groupId,
            referralFee,
            msg.sender,
            block.timestamp
        );


        }
        else {

          tax = getTaxFee(groupId);

        }

        uint256 totalStaked = Staking(payable(stakingContract)).totalStaked();

        if (totalStaked == 0) {
            (bool os, ) = payable(owner()).call{value: tax}("");

            require(os);
        } else {
            (bool os, ) = payable(stakingContract).call{value: tax}("");

            require(os);
        }

        groups[groupId].totalDeposits++;
        totalDeposits++;

        emit deposited(
            msg.sender,
            groups[groupId].denomination,
            groupId,
            block.timestamp
        );
    }


    function updateRelayerFee(
        uint256 _relayerFeeNum,
        uint256 _relayerFeeDen,
        uint256 _groupId
    ) external override onlyOwner {
        require(groups[_groupId].denomination > 0, "Invalid group Id");

        groups[_groupId].relayerFeeDen = _relayerFeeDen;
        groups[_groupId].relayerFeeNum = _relayerFeeNum;
    }

    function updateTaxFee(
        uint256 _taxFeeNum,
        uint256 _taxFeeDen,
        uint256 _groupId
    ) external override onlyOwner {
        require(groups[_groupId].denomination > 0, "Invalid group Id");

        groups[_groupId].taxFeeDen = _taxFeeDen;
        groups[_groupId].taxFeeNum = _taxFeeNum;
    }

     function updateReferralFee(
        uint256 _referralFeeNum,
        uint256 _referralFeeDen
    ) external override onlyOwner {

       referralFeeNum = _referralFeeNum;
        referralFeeDen = _referralFeeDen;
    }

    function verifyProof(
        uint256 groupId,
        uint256 merkleTreeRoot,
        uint256 signal,
        uint256 nullifierHash,
        uint256 externalNullifier,
        uint256[8] calldata proof,
        bool calledByRelayer
    ) external override {
        uint256 merkleTreeDepth = getMerkleTreeDepth(groupId);

        if (merkleTreeDepth == 0) {
            revert Semaphore__GroupDoesNotExist();
        }

        uint256 currentMerkleTreeRoot = getMerkleTreeRoot(groupId);

        if (merkleTreeRoot != currentMerkleTreeRoot) {
            uint256 merkleRootCreationDate = groups[groupId]
                .merkleRootCreationDates[merkleTreeRoot];

            if (merkleRootCreationDate == 0) {
                revert Semaphore__MerkleTreeRootIsNotPartOfTheGroup();
            }

            if (
                block.timestamp >
                merkleRootCreationDate + merkleTreeHistoryDuration
            ) {
                revert Semaphore__MerkleTreeRootIsExpired();
            }
        }

        if (groups[groupId].nullifierHashes[nullifierHash]) {
            revert Semaphore__YouAreUsingTheSameNillifierTwice();
        }

        verifier.verifyProof(
            merkleTreeRoot,
            nullifierHash,
            signal,
            externalNullifier,
            proof,
            merkleTreeDepth
        );

        groups[groupId].nullifierHashes[nullifierHash] = true;
        nullifierDate[nullifierHash] = block.timestamp;

        address recieverAddress = address(uint160(signal));

        uint256 totalPayableAmountToReciever = groups[groupId].denomination -
            getTaxFee(groupId);

        if (calledByRelayer) {
            uint256 payableAmountToRelayer = getRelayerFee(groupId);

            (bool os, ) = payable(msg.sender).call{
                value: payableAmountToRelayer
            }("");

            require(os);

            totalPayableAmountToReciever =
                totalPayableAmountToReciever -
                payableAmountToRelayer;
        }

        (bool os1, ) = payable(recieverAddress).call{
            value: totalPayableAmountToReciever
        }("");

        require(os1);

        emit ProofVerified(
            groupId,
            merkleTreeRoot,
            nullifierHash,
            externalNullifier,
            signal
        );

        emit claimed(
            recieverAddress,
            groups[groupId].denomination,
            groupId,
            block.timestamp
        );
    }
}
合同源代码
文件 12 的 18:Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

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() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        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 {
        _transferOwnership(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");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
合同源代码
文件 13 的 18:Pairing.sol
// Copyright 2017 Christian Reitwiessner
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// The following Pairing library is a modified version adapted to Semaphore.
//
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

library Pairing {
    error InvalidProof();

    // The prime q in the base field F_q for G1
    uint256 constant BASE_MODULUS = 21888242871839275222246405745257275088696311157297823662689037894645226208583;

    // The prime modulus of the scalar field of G1.
    uint256 constant SCALAR_MODULUS = 21888242871839275222246405745257275088548364400416034343698204186575808495617;

    struct G1Point {
        uint256 X;
        uint256 Y;
    }

    // Encoding of field elements is: X[0] * z + X[1]
    struct G2Point {
        uint256[2] X;
        uint256[2] Y;
    }

    /// @return the generator of G1
    function P1() public pure returns (G1Point memory) {
        return G1Point(1, 2);
    }

    /// @return the generator of G2
    function P2() public pure returns (G2Point memory) {
        return
            G2Point(
                [
                    11559732032986387107991004021392285783925812861821192530917403151452391805634,
                    10857046999023057135944570762232829481370756359578518086990519993285655852781
                ],
                [
                    4082367875863433681332203403145435568316851327593401208105741076214120093531,
                    8495653923123431417604973247489272438418190587263600148770280649306958101930
                ]
            );
    }

    /// @return r the negation of p, i.e. p.addition(p.negate()) should be zero.
    function negate(G1Point memory p) public pure returns (G1Point memory r) {
        if (p.X == 0 && p.Y == 0) {
            return G1Point(0, 0);
        }

        // Validate input or revert
        if (p.X >= BASE_MODULUS || p.Y >= BASE_MODULUS) {
            revert InvalidProof();
        }

        // We know p.Y > 0 and p.Y < BASE_MODULUS.
        return G1Point(p.X, BASE_MODULUS - p.Y);
    }

    /// @return r the sum of two points of G1
    function addition(G1Point memory p1, G1Point memory p2) public view returns (G1Point memory r) {
        // By EIP-196 all input is validated to be less than the BASE_MODULUS and form points
        // on the curve.
        uint256[4] memory input;

        input[0] = p1.X;
        input[1] = p1.Y;
        input[2] = p2.X;
        input[3] = p2.Y;

        bool success;

        // solium-disable-next-line security/no-inline-assembly
        assembly {
            success := staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60)
        }

        if (!success) {
            revert InvalidProof();
        }
    }

    /// @return r the product of a point on G1 and a scalar, i.e.
    /// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.
    function scalar_mul(G1Point memory p, uint256 s) public view returns (G1Point memory r) {
        // By EIP-196 the values p.X and p.Y are verified to be less than the BASE_MODULUS and
        // form a valid point on the curve. But the scalar is not verified, so we do that explicitly.
        if (s >= SCALAR_MODULUS) {
            revert InvalidProof();
        }

        uint256[3] memory input;

        input[0] = p.X;
        input[1] = p.Y;
        input[2] = s;

        bool success;

        // solium-disable-next-line security/no-inline-assembly
        assembly {
            success := staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60)
        }

        if (!success) {
            revert InvalidProof();
        }
    }

    /// Asserts the pairing check
    /// e(p1[0], p2[0]) *  .... * e(p1[n], p2[n]) == 1
    /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should succeed
    function pairingCheck(G1Point[] memory p1, G2Point[] memory p2) public view {
        // By EIP-197 all input is verified to be less than the BASE_MODULUS and form elements in their
        // respective groups of the right order.
        if (p1.length != p2.length) {
            revert InvalidProof();
        }

        uint256 elements = p1.length;
        uint256 inputSize = elements * 6;
        uint256[] memory input = new uint256[](inputSize);

        for (uint256 i = 0; i < elements; i++) {
            input[i * 6 + 0] = p1[i].X;
            input[i * 6 + 1] = p1[i].Y;
            input[i * 6 + 2] = p2[i].X[0];
            input[i * 6 + 3] = p2[i].X[1];
            input[i * 6 + 4] = p2[i].Y[0];
            input[i * 6 + 5] = p2[i].Y[1];
        }

        uint256[1] memory out;
        bool success;

        // solium-disable-next-line security/no-inline-assembly
        assembly {
            success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
        }

        if (!success || out[0] != 1) {
            revert InvalidProof();
        }
    }
}
合同源代码
文件 14 的 18:SemaphoreGroups.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import "../interfaces/ISemaphoreGroups.sol";
import "@zk-kit/incremental-merkle-tree.sol/IncrementalBinaryTree.sol";
import "@openzeppelin/contracts/utils/Context.sol";

/// @title Semaphore groups contract.
/// @dev This contract allows you to create groups, add, remove and update members.
/// You can use getters to obtain informations about groups (root, depth, number of leaves).
abstract contract SemaphoreGroups is Context, ISemaphoreGroups {
    using IncrementalBinaryTree for IncrementalTreeData;

    /// @dev Gets a group id and returns the tree data.
    mapping(uint256 => IncrementalTreeData) internal merkleTrees;

    /// @dev Creates a new group by initializing the associated tree.
    /// @param groupId: Id of the group.
    /// @param merkleTreeDepth: Depth of the tree.
    function _createGroup(uint256 groupId, uint256 merkleTreeDepth) internal virtual {
        if (getMerkleTreeDepth(groupId) != 0) {
            revert Semaphore__GroupAlreadyExists();
        }

        // The zeroValue is an implicit member of the group, or an implicit leaf of the Merkle tree.
        // Although there is a remote possibility that the preimage of
        // the hash may be calculated, using this value we aim to minimize the risk.
        uint256 zeroValue = uint256(keccak256(abi.encodePacked(groupId))) >> 8;

        merkleTrees[groupId].init(merkleTreeDepth, zeroValue);

        emit GroupCreated(groupId, merkleTreeDepth, zeroValue);
    }

    /// @dev Adds an identity commitment to an existing group.
    /// @param groupId: Id of the group.
    /// @param identityCommitment: New identity commitment.
    function _addMember(uint256 groupId, uint256 identityCommitment) internal virtual {
        if (getMerkleTreeDepth(groupId) == 0) {
            revert Semaphore__GroupDoesNotExist();
        }

        merkleTrees[groupId].insert(identityCommitment);

        uint256 merkleTreeRoot = getMerkleTreeRoot(groupId);
        uint256 index = getNumberOfMerkleTreeLeaves(groupId) - 1;

        emit MemberAdded(groupId, index, identityCommitment, merkleTreeRoot);
    }

    /// @dev Updates an identity commitment of an existing group. A proof of membership is
    /// needed to check if the node to be updated is part of the tree.
    /// @param groupId: Id of the group.
    /// @param identityCommitment: Existing identity commitment to be updated.
    /// @param newIdentityCommitment: New identity commitment.
    /// @param proofSiblings: Array of the sibling nodes of the proof of membership.
    /// @param proofPathIndices: Path of the proof of membership.
    function _updateMember(
        uint256 groupId,
        uint256 identityCommitment,
        uint256 newIdentityCommitment,
        uint256[] calldata proofSiblings,
        uint8[] calldata proofPathIndices
    ) internal virtual {
        if (getMerkleTreeDepth(groupId) == 0) {
            revert Semaphore__GroupDoesNotExist();
        }

        merkleTrees[groupId].update(identityCommitment, newIdentityCommitment, proofSiblings, proofPathIndices);

        uint256 merkleTreeRoot = getMerkleTreeRoot(groupId);
        uint256 index = proofPathIndicesToMemberIndex(proofPathIndices);

        emit MemberUpdated(groupId, index, identityCommitment, newIdentityCommitment, merkleTreeRoot);
    }

    /// @dev Removes an identity commitment from an existing group. A proof of membership is
    /// needed to check if the node to be deleted is part of the tree.
    /// @param groupId: Id of the group.
    /// @param identityCommitment: Existing identity commitment to be removed.
    /// @param proofSiblings: Array of the sibling nodes of the proof of membership.
    /// @param proofPathIndices: Path of the proof of membership.
    function _removeMember(
        uint256 groupId,
        uint256 identityCommitment,
        uint256[] calldata proofSiblings,
        uint8[] calldata proofPathIndices
    ) internal virtual {
        if (getMerkleTreeDepth(groupId) == 0) {
            revert Semaphore__GroupDoesNotExist();
        }

        merkleTrees[groupId].remove(identityCommitment, proofSiblings, proofPathIndices);

        uint256 merkleTreeRoot = getMerkleTreeRoot(groupId);
        uint256 index = proofPathIndicesToMemberIndex(proofPathIndices);

        emit MemberRemoved(groupId, index, identityCommitment, merkleTreeRoot);
    }

    /// @dev See {ISemaphoreGroups-getMerkleTreeRoot}.
    function getMerkleTreeRoot(uint256 groupId) public view virtual override returns (uint256) {
        return merkleTrees[groupId].root;
    }

    /// @dev See {ISemaphoreGroups-getMerkleTreeDepth}.
    function getMerkleTreeDepth(uint256 groupId) public view virtual override returns (uint256) {
        return merkleTrees[groupId].depth;
    }

    /// @dev See {ISemaphoreGroups-getNumberOfMerkleTreeLeaves}.
    function getNumberOfMerkleTreeLeaves(uint256 groupId) public view virtual override returns (uint256) {
        return merkleTrees[groupId].numberOfLeaves;
    }

    /// @dev Converts the path indices of a Merkle proof to the identity commitment index in the tree.
    /// @param proofPathIndices: Path of the proof of membership.
    /// @return Index of a group member.
    function proofPathIndicesToMemberIndex(uint8[] calldata proofPathIndices) private pure returns (uint256) {
        uint256 memberIndex = 0;

        for (uint8 i = uint8(proofPathIndices.length); i > 0; ) {
            if (memberIndex > 0 || proofPathIndices[i - 1] != 0) {
                memberIndex *= 2;

                if (proofPathIndices[i - 1] == 1) {
                    memberIndex += 1;
                }
            }

            unchecked {
                --i;
            }
        }

        return memberIndex;
    }
}
合同源代码
文件 15 的 18:TaxReward.sol
// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.2 <0.9.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract TaxReward is Ownable {
    address public tokenAddress;
    uint256 public startdate;
    uint256 public totalRewards;
    mapping(uint256=>uint256) totalMonthReward;
    uint256 public latestMonthShareCalculated;
    mapping(address=> uint256) public latestMonthUserShareCalculated;
    mapping(address=>mapping(uint256=>uint256)) userMonthClaimedPointOne;
    mapping(address=>mapping(uint256=>uint256)) userMonthClaimed;
    mapping(address=>uint256) userClaimableAmount;

    struct userMonthShareType {
       uint256 startingBal;
       uint256 endingBal;
       uint256 maintainedBal;
    }

    struct totalMonthShareType {
       uint256 currentMonth;
       uint256 nextMonth;
    }
   
    mapping(address=> mapping(uint256=>userMonthShareType)) public _userMonthShares;
    mapping(uint256=>totalMonthShareType) public _totalMonthShares;
    mapping(address=> mapping(uint256=>bool)) public userMonthShareCalculated;

    constructor(address _tokenAddress, uint256 _startInDays)  {
        tokenAddress = _tokenAddress;
        startdate = block.timestamp + (_startInDays * ( 1 days ));
    }
 
    function getCurrentMonth() public view returns(uint256) {
        if( block.timestamp < startdate){
            return 0;
        }
        else{
            // return (((block.timestamp - startdate)/ 30 days) + 1);
            return (((block.timestamp - startdate)/ 30 seconds) + 1);
        }
    }

    function getCurrentYear() public view returns(uint256) {
        if( block.timestamp < startdate){
            return 0;
        }
        else{
        // return (((block.timestamp - startdate)/ 360 days) + 1);
        return (((block.timestamp - startdate)/ 360 seconds) + 1);
        }
    }

    function getYearStartingMonth(uint256 _year) public pure returns(uint256) {
        return 12*(_year-1) + 1;
    }

    function getUserShare (uint256 _month, address _user) public view returns (uint256){
        require( _month >= 2, "Rewards do not start before second month");
        require ( _month <= getCurrentMonth(), "Invalid month" );
        
        if (latestMonthUserShareCalculated[_user] == _month-1){        
            userMonthShareType memory userShares =  _userMonthShares[_user][latestMonthUserShareCalculated[_user]];
            return userShares.maintainedBal;
        }

        else if (latestMonthUserShareCalculated[_user] < _month-1){
            userMonthShareType memory userShares =  _userMonthShares[_user][latestMonthUserShareCalculated[_user]];
            return userShares.endingBal;
        } else {
            for (uint256 i= _month-1; i >=0  ; i-- ) {
                if (userMonthShareCalculated[_user][i] == true){
                    if ( i == _month-1){
                        userMonthShareType memory userShares =  _userMonthShares[_user][i];
                        return userShares.maintainedBal;

                    } else {
                        userMonthShareType memory userShares =  _userMonthShares[_user][i];
                        return userShares.endingBal;
                    }
                }
                continue ;
            }
            return 0;
        }
    }

    function getTotalMonthShares (uint256 _month) public view returns (uint256){
        require( _month >= 2, "Rewards do not start before second month");
        require ( _month <= getCurrentMonth(), "Invalid month" );
        totalMonthShareType memory monthShares = _totalMonthShares[latestMonthShareCalculated];
        if (latestMonthShareCalculated < _month-1){
            return monthShares.nextMonth;
        } else {
             return monthShares.currentMonth;
        }
    }


    function claimProfits (uint256[] memory _months) public {
        require(_months.length <=12, "You cannot claim for more than 12 months together" );
        for (uint i=0; i<_months.length; i++){
            uint256 userProfits = getUserProfits(_months[i],msg.sender);
            if (userProfits > 0){            
                userMonthClaimedPointOne[msg.sender][_months[i]] = totalMonthReward[_months[i]];
                userMonthClaimed[msg.sender][_months[i]] += userProfits;
                IERC20(tokenAddress).transfer(msg.sender,userProfits);
            }
        }
    }

    function getUserProfits (uint256 _month, address _user) public view returns (uint256){
        uint256 totalShares = getTotalMonthShares(_month);
        uint256 userShares = getUserShare(_month, _user);        
        if (totalShares == 0){
            return 0;
        }
        return ((totalMonthReward[_month] - userMonthClaimedPointOne[_user][_month] ) * userShares)/ (totalShares);
    }

    

    function getYearMonthRevenue(uint256 _year) public view returns (uint256[12] memory rewards){
        if (_year == 0){
            return rewards;
        }
        uint256 startingMonth = getYearStartingMonth(_year);
        uint256 counter = 0;
        for (uint256 i=startingMonth; i< startingMonth + 12; i++){
           rewards[counter] = totalMonthReward[i];
            counter++;            
        }        
        return rewards;
    }
  
    function getUserProfitsByYear(uint256 _year, address _user) public view returns (uint256){
        if (_year == 0){
            return 0;
        }

        uint256 profits = 0;
        uint256 startingMonth = getYearStartingMonth(_year);
        uint256 upperLimit = startingMonth + 12 >= getCurrentMonth() ? getCurrentMonth() :  startingMonth + 12;
    
        if (upperLimit <= startingMonth){
            return 0;
        }

        for (uint i=startingMonth; i<= upperLimit; i++){
            if (i == 0 || i== 1){
                profits+=0;
            }
            else{
              profits +=  getUserProfits(i,_user);
            }
        }
        return profits;
    }


    function getUserProfitsClaimedByYear(uint256 _year, address _user) public view returns (uint256){
        if (_year == 0){
            return 0;
        }
        uint256  claimed = 0;
        uint256 startingMonth = getYearStartingMonth(_year);
        for (uint i=startingMonth; i< startingMonth+12; i++){
            if (i == 0 || i== 1){
                claimed+=0;
            }
            else{
              claimed += userMonthClaimed[_user][i];
            }
        }
        return claimed;
    }

    







    function updateUserHoldings(uint256 bal, address _user) public {


        uint256 currentMonth = getCurrentMonth();


        
        userMonthShareCalculated[_user][currentMonth] = true;

        latestMonthShareCalculated = currentMonth;



        if (currentMonth == 0){


        userMonthShareType memory userShares =  _userMonthShares[_user][currentMonth];

        totalMonthShareType memory total_monthShares = _totalMonthShares[currentMonth];
        
        total_monthShares.nextMonth -= total_monthShares.currentMonth;

        total_monthShares.currentMonth  -= userShares.maintainedBal;
        total_monthShares.currentMonth += bal;

        total_monthShares.nextMonth += total_monthShares.currentMonth;

_totalMonthShares[currentMonth] = total_monthShares;

        userShares.endingBal = bal;
        userShares.maintainedBal = bal;




        _userMonthShares[_user][currentMonth] = userShares;


    
      

        }

        

        else {

        if (latestMonthUserShareCalculated[_user] != currentMonth){

            userMonthShareType memory latestMonthShares =   _userMonthShares[_user][latestMonthUserShareCalculated[_user] ];

                uint256 maintainedBal = latestMonthShares.endingBal;

                if (bal < latestMonthShares.endingBal){

                    maintainedBal =  bal;
                    
                }


        totalMonthShareType memory total_monthShares = _totalMonthShares[currentMonth];
        total_monthShares.currentMonth += maintainedBal;

        total_monthShares.nextMonth += bal;
        _totalMonthShares[currentMonth] = total_monthShares;


                _userMonthShares[_user][currentMonth] = userMonthShareType(latestMonthShares.endingBal,bal,maintainedBal);
                latestMonthUserShareCalculated[_user] = currentMonth;

        }

        else {

            userMonthShareType memory currentMonthShares =   _userMonthShares[_user][currentMonth];
            totalMonthShareType memory total_monthShares = _totalMonthShares[currentMonth];

            if (bal >= currentMonthShares.maintainedBal){

             total_monthShares.nextMonth -= currentMonthShares.endingBal;

                currentMonthShares.endingBal = bal;

                _userMonthShares[_user][currentMonth] = currentMonthShares;

                total_monthShares.nextMonth += bal;


            _totalMonthShares[currentMonth] = total_monthShares;



            }

            else {


            total_monthShares.nextMonth -= currentMonthShares.endingBal;

            currentMonthShares.endingBal = bal;

            total_monthShares.currentMonth -= currentMonthShares.maintainedBal;
            total_monthShares.currentMonth +=  bal;

            total_monthShares.nextMonth += bal;
            _totalMonthShares[currentMonth] = total_monthShares;

                currentMonthShares.maintainedBal =  bal;


                _userMonthShares[_user][currentMonth] = currentMonthShares;


            }



        }


        }


    
    }






 function receiveTokens(uint256 _amount) public {
        uint256 currentMonth = getCurrentMonth();

        totalRewards+=_amount;

        if (currentMonth == 0 || currentMonth == 1){
            totalMonthReward[2] += _amount;

        }
        else {

            totalMonthReward[currentMonth] += _amount;
            
            if (latestMonthShareCalculated < currentMonth-1){
            // totalMonthShares[currentMonth-1] = totalMonthShares[latestMonthShareCalculated] + movedOverTotalMonthShares[latestMonthShareCalculated];

            
            // // movedOverTotalMonthShares[latestMonthShareCalculated] = 0;


        totalMonthShareType memory prev_monthShares = _totalMonthShares[latestMonthShareCalculated];

        _totalMonthShares[currentMonth-1] = totalMonthShareType(prev_monthShares.nextMonth,prev_monthShares.nextMonth);

            latestMonthShareCalculated = currentMonth-1;
         }


        }
    
    }

 
}
合同源代码
文件 16 的 18:Token.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

import "./ERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../Mixer.sol";

contract Token is ERC20 {
    address public teamAddress;

    uint256 public _rewardsAmountThreshold;
    uint256 public _rewardsAmountThresholdCompletionTimestamp;
    uint256 public _rewardRate;

    // uint256 public _reservedForDirectSale;
    uint256 public _reservedForTeam;
    // uint256 public _directSaleSupply;
    uint256 public _rewardsSaleSupply;

    mapping(uint256 => uint256) public commitmentRewardClaimDate;
    mapping(uint256 => uint256) public commitmentRewardClaimed;
    Mixer public mixerContract;

    // uint256 public _directSalePrice;

    struct signatureInput {
        string _nonce;
        uint256 _validTill;
        uint8 _v;
        bytes32 _r;
        bytes32 _s;
    }

    constructor(
        string memory name,
        string memory symbol,
        uint256 reservedForTeam,
        uint256 rewardsAmountThreshold,
        // uint256 reservedForDirectSale,
        // uint256 directSalePrice,
        uint256 rewardRate,
        address marketingWallet,
        address factoryAddress,
        address wethAddress
    ) ERC20(name, symbol, marketingWallet, factoryAddress, wethAddress) {
        _reservedForTeam = reservedForTeam * 1e18;
        _rewardsAmountThreshold = rewardsAmountThreshold * 1e18;

        teamAddress = msg.sender;
        _rewardRate = rewardRate;

        _mint(teamAddress, _reservedForTeam);
    }

    function updateMixerContractAddress(
        Mixer contractAddress
    ) public onlyOwner {
        mixerContract = contractAddress;
    }

    function rewardsMint(
        address _mintTo,
        uint256 commitment,
        uint256 endTime,
        signatureInput memory _signature
    ) public {
        uint256 getRewardAmountDuration;

        if (endTime == 0) {
            if (commitmentRewardClaimDate[commitment] == 0) {
                getRewardAmountDuration =
                    block.timestamp -
                    mixerContract.commitmentDate(commitment);
            } else {
                getRewardAmountDuration =
                    block.timestamp -
                    commitmentRewardClaimDate[commitment];
            }
        } else {
            if (commitmentRewardClaimDate[commitment] == 0) {
                getRewardAmountDuration =
                    endTime -
                    mixerContract.commitmentDate(commitment);
            } else {
                if (commitmentRewardClaimDate[commitment] > endTime) {
                    getRewardAmountDuration = 0;
                } else {
                    getRewardAmountDuration =
                        endTime -
                        commitmentRewardClaimDate[commitment];
                }
            }
        }

        uint256 rewardAmount = getRewardAmount(
            commitment,
            getRewardAmountDuration
        );

        if (
            _rewardsAmountThresholdCompletionTimestamp == 0 &&
            (_rewardsSaleSupply + rewardAmount) >= _rewardsAmountThreshold
        ) {
            _rewardsAmountThresholdCompletionTimestamp = block.timestamp;
        }

        _rewardsSaleSupply += rewardAmount;

        commitmentRewardClaimDate[commitment] = block.timestamp;

        bytes32 hashStruct = keccak256(
            abi.encode(
                keccak256(
                    "Mint(uint256 validTill,string nonce,address mintTo,uint256 commitment,uint256 endTime)"
                ),
                _signature._validTill,
                keccak256(bytes(_signature._nonce)),
                _mintTo,
                commitment,
                endTime
            )
        );

        executeSetIfSignatureMatch(
            _signature._v,
            _signature._r,
            _signature._s,
            hashStruct
        );

        commitmentRewardClaimed[commitment] += rewardAmount;

        _mint(_mintTo, rewardAmount);
    }

    function getRewardAmount(
        uint256 commitment,
        uint256 duration
    ) public view returns (uint256) {
        uint256 depositTime = mixerContract.commitmentDate(commitment);

        require(depositTime > 0, "This commitment was never deposited");

        if (_rewardsAmountThresholdCompletionTimestamp != 0) {
            require(
                depositTime < _rewardsAmountThresholdCompletionTimestamp,
                "Reward system has ended"
            );

            if (
                (commitmentRewardClaimDate[commitment] + duration) >
                _rewardsAmountThresholdCompletionTimestamp
            ) {
                duration =
                    _rewardsAmountThresholdCompletionTimestamp -
                    commitmentRewardClaimDate[commitment];
            }
        }

        uint256 rewardAmount = _rewardRate * (duration / 1 minutes);

        return rewardAmount;
    }

    function updateTeamAddress(address newTeamAddress) public onlyOwner {
        teamAddress = newTeamAddress;
    }

    function updateRewardRate(uint256 rewardRate) public onlyOwner {
        _rewardRate = rewardRate;
    }

    function executeSetIfSignatureMatch(
        uint8 _v,
        bytes32 _r,
        bytes32 _s,
        bytes32 _hashStruct
    ) public view {
        uint256 chainId = block.chainid;
        bytes32 eip712DomainHash = keccak256(
            abi.encode(
                keccak256(
                    "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                ),
                keccak256(bytes("Mixer")),
                keccak256(bytes("1.0")),
                chainId,
                address(this)
            )
        );

        bytes32 hash = keccak256(
            abi.encodePacked("\x19\x01", eip712DomainHash, _hashStruct)
        );
        address signer = ecrecover(hash, _v, _r, _s);
        require(signer != address(0), "ECDSA: invalid signature");
        require(signer == teamAddress, "MyFunction: invalid signature");
    }
}
合同源代码
文件 17 的 18:iMixer.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @title Semaphore contract interface.
interface IMixer {
    error Semaphore__MerkleTreeDepthIsNotSupported();
    error Semaphore__MerkleTreeRootIsExpired();
    error Semaphore__MerkleTreeRootIsNotPartOfTheGroup();
    error Semaphore__YouAreUsingTheSameNillifierTwice();

    struct Group {
        uint256 denomination;
        mapping(uint256 => uint256) merkleRootCreationDates;
        mapping(uint256 => bool) nullifierHashes;
        uint256 totalDeposits;
        uint256 relayerFeeNum;
        uint256 relayerFeeDen;
        uint256 taxFeeNum;
        uint256 taxFeeDen;
    }

    event deposited(
        address indexed depositor,
        uint256 indexed amount,
        uint256 indexed poolId,
        uint256 timeStamp
    );

    event depositedReferral(
        address indexed referralAddress,
        uint256 indexed amount,
        uint256 indexed poolId,
        uint256 referralFee,
        address depositor,
        uint256 timeStamp

    );

    event claimed(
        address indexed sendTo,
        uint256 indexed amount,
        uint256 indexed poolId,
        uint256 timeStamp
    );

    /// @dev Emitted when the Merkle tree duration of a group is updated.
    /// @param groupId: Id of the group.
    /// @param oldMerkleTreeDuration: Old Merkle tree duration of the group.
    /// @param newMerkleTreeDuration: New Merkle tree duration of the group.
    event GroupMerkleTreeDurationUpdated(
        uint256 indexed groupId,
        uint256 oldMerkleTreeDuration,
        uint256 newMerkleTreeDuration
    );

    /// @dev Emitted when a Semaphore proof is verified.
    /// @param groupId: Id of the group.
    /// @param merkleTreeRoot: Root of the Merkle tree.
    /// @param nullifierHash: Nullifier hash.
    /// @param externalNullifier: External nullifier.
    /// @param signal: Semaphore signal.
    event ProofVerified(
        uint256 indexed groupId,
        uint256 indexed merkleTreeRoot,
        uint256 nullifierHash,
        uint256 indexed externalNullifier,
        uint256 signal
    );

    /// @dev Saves the nullifier hash to avoid double signaling and emits an event
    /// if the zero-knowledge proof is valid.
    /// @param groupId: Id of the group.
    /// @param merkleTreeRoot: Root of the Merkle tree.
    /// @param signal: Semaphore signal.
    /// @param nullifierHash: Nullifier hash.
    /// @param externalNullifier: External nullifier.
    /// @param proof: Zero-knowledge proof.
    function verifyProof(
        uint256 groupId,
        uint256 merkleTreeRoot,
        uint256 signal,
        uint256 nullifierHash,
        uint256 externalNullifier,
        uint256[8] calldata proof,
        bool calledByRelayer
    ) external;

    // /// @dev Creates a new group.
    // /// @param groupId: Id of the group.
    // /// @param depth: Depth of the tree.
    // function createGroup(uint256 groupId, uint256 depth) external;

    /// @dev Creates a new group.
    /// @param groupId: Id of the group.
    /// @param depth: Depth of the tree.
    /// @param denomination: Denomination of the tree.
    function createGroup(
        uint256 groupId,
        uint256 depth,
        uint256 denomination
    ) external;

    /// @dev Updates the Merkle tree duration.
    /// @param newMerkleTreeDuration: New Merkle tree duration.
    function updateMerkleTreeDuration(uint256 newMerkleTreeDuration) external;

    /// @dev Adds a new member to an existing group.
    /// @param groupId: Id of the group.
    /// @param identityCommitment: New identity commitment.
    /// @param referralAddress: referral address.

    function addMember(
        uint256 groupId,
        uint256 identityCommitment,
        address referralAddress
    ) external payable;

    // /// @dev Adds new members to an existing group.
    // /// @param groupId: Id of the group.
    // /// @param identityCommitments: New identity commitments.
    // /// @param referralAddress: referral address.

    // function addMembers(
    //     uint256 groupId,
    //     uint256[] calldata identityCommitments,
    //     address referralAddress

    // ) external payable;

    /// @dev Update relayer fee.
    /// @param _relayerFeeNum: relayer fee numerator.
    /// @param _relayerFeeDen: relayer fee denominator.
    /// @param _groupId: group id.

    function updateRelayerFee(
        uint256 _relayerFeeNum,
        uint256 _relayerFeeDen,
        uint256 _groupId
    ) external;

    /// @dev Update tax fee.
    /// @param _taxFeeNum: tax fee numerator.
    /// @param _taxFeeDen: tax fee denominator.
    /// @param _groupId: group id.

    function updateTaxFee(
        uint256 _taxFeeNum,
        uint256 _taxFeeDen,
        uint256 _groupId
    ) external;

       /// @dev Update referral fee.
    /// @param _referralFeeNum: referral fee numerator.
    /// @param _referralFeeDen: referral fee denominator.

    function updateReferralFee(
        uint256 _referralFeeNum,
        uint256 _referralFeeDen
    ) external;
}
合同源代码
文件 18 的 18:staking.sol
// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.2 <0.9.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract Staking {
    address public tokenAddress;
    mapping(address => uint256) public stakingAmount;
    mapping(address => uint256) public unclaimedPayment;
    mapping(address => uint256) public pointOne;
    mapping(address => uint256) public released;

    uint256 public EthPerToken;
    uint256 public totalStaked;
    uint256 public totalReleased;
    uint256 public movedOverFunds;

    uint256 public totalReceived;

    constructor(address _tokenAddress) {
        tokenAddress = _tokenAddress;
    }

    function stakeTokens(uint256 _amount) public {
        _amount = _amount * 1e18;

        require(_amount > 0, "staking amount cannot be 0");

        if (stakingAmount[msg.sender] > 0) {
            unclaimedPayment[msg.sender] += getUnclaimedPayment(msg.sender);
        }

        pointOne[msg.sender] = EthPerToken;

        stakingAmount[msg.sender] += _amount;

        totalStaked += _amount;

        IERC20(tokenAddress).transferFrom(msg.sender, address(this), _amount);
    }

    function getUnclaimedPayment(
        address _account
    ) public view returns (uint256 payment) {
        if (totalStaked == 0) {
            payment = 0;
        } else {
            uint256 recievableEthPerToken = EthPerToken - pointOne[_account];
            payment =
                recievableEthPerToken *
                (stakingAmount[_account] / 1 ether);
            payment = payment + unclaimedPayment[_account];
        }
    }

    receive() external payable {
        totalReceived += msg.value;

        if (totalStaked > 0) {
            EthPerToken +=
                (msg.value + movedOverFunds) /
                (totalStaked / 1 ether);

            if (EthPerToken == 0) {
                movedOverFunds += msg.value;
            } else {
                movedOverFunds =
                    (msg.value + movedOverFunds) -
                    ((msg.value + movedOverFunds) / (totalStaked / 1 ether)) *
                    (totalStaked / 1 ether);
            }
        }
    }

    function unstakeTokens() public {
        require(
            stakingAmount[msg.sender] > 0,
            "You do not have any tokens staked"
        );

        unclaimedPayment[msg.sender] += getUnclaimedPayment(msg.sender);

        totalStaked -= stakingAmount[msg.sender];

        IERC20(tokenAddress).transfer(msg.sender, stakingAmount[msg.sender]);

        stakingAmount[msg.sender] = 0;
    }

    function release() public {
        uint256 payment = getUnclaimedPayment(msg.sender);
        require(payment != 0, "No funds to be released");

        released[msg.sender] += payment;
        totalReleased += payment;
        unclaimedPayment[msg.sender] = 0;
        pointOne[msg.sender] = EthPerToken;

        (bool os, ) = payable(msg.sender).call{value: payment}("");
        require(os);
    }
}
设置
{
  "compilationTarget": {
    "contracts/token/Token.sol": "Token"
  },
  "evmVersion": "istanbul",
  "libraries": {},
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "remappings": []
}
ABI
[{"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"uint256","name":"reservedForTeam","type":"uint256"},{"internalType":"uint256","name":"rewardsAmountThreshold","type":"uint256"},{"internalType":"uint256","name":"rewardRate","type":"uint256"},{"internalType":"address","name":"marketingWallet","type":"address"},{"internalType":"address","name":"factoryAddress","type":"address"},{"internalType":"address","name":"wethAddress","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_delayTime","type":"uint256"}],"name":"UpdatedPreventDelayTime","type":"event"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"_isExcludedFromFee","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"_isExcludedFromRewards","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_reservedForTeam","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_rewardsAmountThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_rewardsAmountThresholdCompletionTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_rewardsSaleSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"commitmentRewardClaimDate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"commitmentRewardClaimed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"dexPair","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"enableTransferFee","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"},{"internalType":"bytes32","name":"_hashStruct","type":"bytes32"}],"name":"executeSetIfSignatureMatch","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMaxBuyPerWallet","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRemainingTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"commitment","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"}],"name":"getRewardAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"holdersFeePercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"marketingWallet","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"marketingWalletFeePercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxBuy","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mixerContract","outputs":[{"internalType":"contract Mixer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_mintTo","type":"address"},{"internalType":"uint256","name":"commitment","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"components":[{"internalType":"string","name":"_nonce","type":"string"},{"internalType":"uint256","name":"_validTill","type":"uint256"},{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"}],"internalType":"struct Token.signatureInput","name":"_signature","type":"tuple"}],"name":"rewardsMint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"taxRewardContract","outputs":[{"internalType":"contract TaxReward","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"teamAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"toggleTransferFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"updateHoldersFeePercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_walletAddress","type":"address"}],"name":"updateMarketingWallet","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_fee","type":"uint256"}],"name":"updateMarketingWalletFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_limit","type":"uint256"}],"name":"updateMaxBuyLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract Mixer","name":"contractAddress","type":"address"}],"name":"updateMixerContractAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"rewardRate","type":"uint256"}],"name":"updateRewardRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTeamAddress","type":"address"}],"name":"updateTeamAddress","outputs":[],"stateMutability":"nonpayable","type":"function"}]