Referral

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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);
    }
}
"
    },
    "@openzeppelin/contracts/interfaces/draft-IERC6093.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/ERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.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}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * 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.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's 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 returns (uint8) {
        return 18;
    }

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

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual 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 `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

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

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` 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 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        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 `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` 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.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` 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.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     * ```
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)

pragma solidity ^0.8.20;

import {ERC20} from "../ERC20.sol";
import {Context} from "../../../utils/Context.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20Burnable is Context, ERC20 {
    /**
     * @dev Destroys a `value` amount of tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 value) public virtual {
        _burn(_msgSender(), value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, deducting from
     * the caller's allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `value`.
     */
    function burnFrom(address account, uint256 value) public virtual {
        _spendAllowance(account, _msgSender(), value);
        _burn(account, value);
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
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);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}
"
    },
    "@openzeppelin/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    },
    "contracts/cfa/interface/IReferral.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity 0.8.20;\r
\r
interface IReferral {\r
    struct Referrer {\r
        address referrer;\r
        address[] referrals;\r
        uint256 referralCount;\r
        uint256 buyCount;\r
        uint256 rewarded;\r
        bool wasReferred;\r
    }\r
}\r
"
    },
    "contracts/cfa/Referral.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity 0.8.20;\r
\r
import "@openzeppelin/contracts/access/Ownable.sol";\r
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";\r
import "../token/Bean.sol";\r
import "./interface/IReferral.sol";\r
import "../utils/Registry.sol";\r
\r
/**\r
 * @title Referral Contract\r
 * @notice This contract manages a referral system where users can refer others and earn rewards.\r
 * @dev It allows setting referral relationships, calculating rewards, and managing referral-related data.\r
 */\r
contract Referral is Ownable, IReferral {\r
    /// @notice Registry contract to fetch contract addresses.\r
    Registry public registry;\r
\r
    /// @notice Array of referral brackets based on the amount referred.\r
    uint256[] public amtReferredBracket;\r
    /// @notice 2D array storing interest rates for different supply markers and referral brackets.\r
    uint256[][] public interestSet;\r
    /// @notice Array of supply markers for determining referral rewards.\r
    uint256[] public supplyMarkers;\r
    /// @notice Array of reward rates for referred users.\r
    uint256[] public referredRewardRates;\r
    /// @notice Default referrer address.\r
    address public defaultReferrer;\r
    /// @notice Indicates whether the interest rates have been set.\r
    bool _interestSet;\r
\r
    /// @notice Maps addresses to their referral data.\r
    mapping(address => Referrer) public referrer;\r
\r
    // ===================== CONSTANTS =====================\r
    uint256 public constant DISCOUNT_LIMIT = 10; // Maximum buy count for discount eligibility\r
\r
    // =============================================================\r
    //                          EVENTS\r
    // =============================================================\r
\r
    /// @notice Emitted when a referral is recorded.\r
    event ReferralRecorded(address indexed referred, address indexed referrer);\r
\r
    /// @notice Emitted when a referral is removed.\r
    event ReferralRemoved(address indexed user);\r
\r
    // =============================================================\r
    //                          CONSTRUCTOR\r
    // =============================================================\r
\r
    /**\r
     * @notice Initializes the Referral contract.\r
     */\r
    constructor() Ownable(msg.sender) {\r
        supplyMarkers = new uint256[](11);\r
        referredRewardRates = new uint256[](11);\r
    }\r
\r
    // =============================================================\r
    //                          MODIFIERS\r
    // =============================================================\r
\r
    /// @notice Ensures that only registered contracts can call the function.\r
    modifier onlyRegistered() {\r
        Bean bean = Bean(registry.getContractAddress("Bean"));\r
        require(bean.isRegistered(msg.sender), "Referral: Not authorized");\r
        _;\r
    }\r
\r
    // =============================================================\r
    //                          SETTERS\r
    // =============================================================\r
\r
    /**\r
     * @notice Adds a referrer for a new user.\r
     * @dev Can only be called by registered contracts.\r
     * @param _referred The address of the user being referred.\r
     * @param _referrer The address of the referrer.\r
     */\r
    function addReferrer(\r
        address _referred,\r
        address _referrer\r
    ) external onlyRegistered {\r
        require(_referred != address(0), "Referral: Referred cannot be zero address");\r
        require(_referrer != address(0), "Referral: Referrer cannot be zero address");\r
        require(\r
            referrer[_referred].referrer == address(0),\r
            "Referral: Referrer already set"\r
        );\r
        require(_referrer != _referred, "Referral: Cannot refer yourself");\r
        require(isReferrerValid(_referrer), "Referral: Invalid referrer");\r
        require(\r
            referrer[_referrer].referrer != _referred,\r
            "Referral: Direct circular referral not allowed"\r
        );\r
\r
        referrer[_referrer].referrals.push(_referred);\r
        referrer[_referrer].referralCount++;\r
        referrer[_referred].wasReferred = true;\r
        referrer[_referred].referrer = _referrer;\r
\r
        emit ReferralRecorded(_referred, _referrer);\r
    }\r
\r
    /**\r
     * @notice Sets the interest rates for referral rewards.\r
     * @dev Can only be called by the owner.\r
     * @param _newInterestSet A 2D array of interest rates.\r
     */\r
    function setInterestRate(\r
        uint256[][] memory _newInterestSet\r
    ) external onlyOwner {\r
        require(_newInterestSet.length > 0, "Referral: Empty array");\r
\r
        interestSet = new uint256[][](_newInterestSet.length);\r
        _interestSet = true;\r
        for (uint256 i = 0; i < _newInterestSet.length; i++) {\r
            require(_newInterestSet[i].length > 0, "Referral: Empty sub-array");\r
            interestSet[i] = _newInterestSet[i];\r
        }\r
    }\r
\r
    /**\r
     * @notice Sets the supply markers for referral rewards.\r
     * @dev Can only be called by the owner.\r
     * @param _markers An array of supply markers.\r
     */\r
    function setSupplyMarkers(uint256[] memory _markers) external onlyOwner {\r
        require(_markers.length > 0, "Referral: Empty markers array");\r
\r
        for (uint256 i = 0; i < _markers.length; i++) {\r
            supplyMarkers[i] = _markers[i];\r
        }\r
    }\r
\r
    /**\r
     * @notice Sets the reward rates for referred users.\r
     * @dev Can only be called by the owner.\r
     * @param _rewards An array of reward rates.\r
     */\r
    function setReferredRewards(uint256[] memory _rewards) external onlyOwner {\r
        require(_rewards.length > 0, "Referral: Empty markers array");\r
\r
        for (uint256 i = 0; i < _rewards.length; i++) {\r
            referredRewardRates[i] = _rewards[i];\r
        }\r
    }\r
\r
\r
    /**\r
     * @notice Sets the referral brackets based on the amount referred.\r
     * @dev Can only be called by the owner.\r
     * @param _amtReferredBracket An array of referral brackets.\r
     */\r
    function setAmtReferredBracket(\r
        uint256[] memory _amtReferredBracket\r
    ) external onlyOwner {\r
        require(_amtReferredBracket.length > 0, "Referral: Empty array");\r
\r
        amtReferredBracket = _amtReferredBracket;\r
    }\r
\r
    /**\r
     * @notice Sets the registry contract address.\r
     * @dev Can only be called by the owner.\r
     * @param _registry The address of the Registry contract.\r
     */\r
    function setRegistry(Registry _registry) external onlyOwner {\r
        require(address(_registry) != address(0), "Referral: Registry cannot be zero address");\r
        registry = _registry;\r
    }\r
\r
    /**\r
     * @notice Rewards the referrer for a successful referral.\r
     * @dev Can only be called by registered contracts.\r
     * @param _sender The address of the user who made a purchase.\r
     * @param amount The amount of the purchase.\r
     */\r
    function rewardForReferrer(\r
        address _sender,\r
        uint256 amount\r
    ) external onlyRegistered {\r
        require(_sender != address(0), "Referral: Sender cannot be zero address");\r
        require(amount > 0, "Referral: Amount must be greater than zero");\r
        require(referredRewardRates.length != 0, "referredRewardRates not set");\r
        require(supplyMarkers.length != 0, "supplyMarkers not set");\r
        require(amtReferredBracket.length != 0, "supplyMarkers not set");\r
        require(_interestSet, "interest not set");\r
\r
        referrer[_sender].buyCount++;\r
        address _referrer = referrer[_sender].referrer;\r
        uint256 returnRate = getUserInterest(_referrer);\r
        uint256 reward = (amount * returnRate) / 10000;\r
        if (reward > 0) {\r
            Bean token = Bean(registry.getContractAddress("Bean"));\r
            token.mint(_referrer, reward);\r
        }\r
        referrer[_referrer].rewarded += reward;\r
    }\r
\r
    // =============================================================\r
    //                          GETTERS\r
    // =============================================================\r
\r
    /**\r
     * @notice Checks if an address is a contract.\r
     * @param addr The address to check.\r
     * @return isContractBool True if the address is a contract, otherwise false.\r
     */\r
    function isContract(\r
        address addr\r
    ) internal view returns (bool isContractBool) {\r
        uint size;\r
        assembly {\r
            size := extcodesize(addr)\r
        }\r
        isContractBool = size > 0;\r
    }\r
\r
    /**\r
     * @notice Gets the current supply marker based on the total supply of the Bean token.\r
     * @return The current supply marker.\r
     */\r
    function getMarker() public view returns (uint256) {\r
        uint256 totalSupply = IERC20(registry.getContractAddress("Bean"))\r
            .totalSupply();\r
        uint256 supplyMarker = 0;\r
\r
        if (totalSupply > supplyMarkers[supplyMarkers.length - 1]) {\r
            return supplyMarkers.length - 1;\r
        }\r
\r
        for (uint256 index = 0; index < supplyMarkers.length - 1; index++) {\r
            if (\r
                totalSupply > supplyMarkers[index] &&\r
                totalSupply <= supplyMarkers[index + 1]\r
            ) {\r
                supplyMarker = index;\r
                break;\r
            }\r
        }\r
\r
        return supplyMarker;\r
    }\r
\r
    /**\r
     * @notice Gets the interest marker for a referrer based on their referral count.\r
     * @param _referrer The address of the referrer.\r
     * @return The interest marker for the referrer.\r
     */\r
    function getUsersInterestMarker(\r
        address _referrer\r
    ) public view returns (uint256) {\r
        uint256 referredCount = referrer[_referrer].referralCount;\r
\r
        uint256 bracketIndex = 0;\r
        while (\r
            bracketIndex < amtReferredBracket.length &&\r
            referredCount >= amtReferredBracket[bracketIndex]\r
        ) {\r
            bracketIndex++;\r
        }\r
        require(\r
            bracketIndex < interestSet.length,\r
            "Referral: Invalid bracket index"\r
        );\r
        return bracketIndex;\r
    }\r
\r
    /**\r
     * @notice Checks if a referrer is eligible for rewards.\r
     * @param _referrer The address of the referrer.\r
     * @return True if the referrer is eligible, otherwise false.\r
     */\r
    function eligibleForReward(address _referrer) external view returns (bool) {\r
        if (\r
            referrer[_referrer].buyCount < DISCOUNT_LIMIT &&\r
            referrer[_referrer].referrer != address(0)\r
        ) {\r
            return true;\r
        } else {\r
            return false;\r
        }\r
    }\r
\r
    /**\r
     * @notice Checks if a referrer is valid.\r
     * @param _referrer The address of the referrer.\r
     * @return True if the referrer is valid, otherwise false.\r
     */\r
    function isReferrerValid(address _referrer) public view returns (bool) {\r
        if (\r
            _referrer == 0x000000000000000000000000000000000000dEaD ||\r
            isContract(_referrer)\r
        ) {\r
            return false;\r
        }\r
        return true;\r
    }\r
\r
    /**\r
     * @notice Gets the referral attributes for a specific address.\r
     * @param _address The address to query.\r
     * @return The referral attributes for the address.\r
     */\r
    function getAttributes(\r
        address _address\r
    ) external view returns (Referrer memory) {\r
        Referrer memory _attributes = referrer[_address];\r
        return _attributes;\r
    }\r
\r
    /**\r
     * @notice Gets the interest rate for a referrer.\r
     * @param _referrer The address of the referrer.\r
     * @return The interest rate for the referrer.\r
     */\r
    function getUserInterest(\r
        address _referrer\r
    ) internal view returns (uint256) {\r
        uint256 globalMarker = getMarker();\r
        uint256[] memory interestBracket = interestSet[globalMarker];\r
\r
        uint256 userMarker = getUsersInterestMarker(_referrer);\r
        uint256 userInterest = interestBracket[userMarker];\r
\r
        return userInterest;\r
    }\r
\r
    /**\r
     * @notice Gets the list of referrals for a specific address.\r
     * @param _address The address to query.\r
     * @return An array of referral addresses.\r
     */\r
    function checkReferrals(\r
        address _address\r
    ) external view returns (address[] memory) {\r
        address[] memory _referrals = referrer[_address].referrals;\r
        return _referrals;\r
    }\r
\r
    /**\r
     * @notice Gets referral data for a specific address.\r
     * @param _address The address to query.\r
     * @return The referral count, interest rate, and next referral count.\r
     */\r
    function getReferralData(\r
        address _address\r
    ) external view returns (uint256, uint256, uint256) {\r
        uint256 referredCount = referrer[_address].referralCount;\r
\r
        uint256 bracketIndex = 0;\r
        while (\r
            bracketIndex < amtReferredBracket.length &&\r
            referredCount >= amtReferredBracket[bracketIndex]\r
        ) {\r
            bracketIndex++;\r
        }\r
\r
        uint256 nextReferralCount = bracketIndex < amtReferredBracket.length\r
            ? amtReferredBracket[bracketIndex]\r
            : 0;\r
\r
        return (\r
            referrer[_address].referralCount,\r
            getUserInterest(_address),\r
            nextReferralCount\r
        );\r
    }\r
\r
    /**\r
     * @notice Gets the current referred discount rate.\r
     * @return The current referred discount rate.\r
     */\r
    function getReferredDiscount() external view returns (uint256) {\r
        uint256 _getMarker = getMarker();\r
        uint256 reward = referredRewardRates[_getMarker];\r
        return reward;\r
    }\r
\r
    /**\r
     * @notice Gets the referrer for a specific user.\r
     * @param _user The address of the user.\r
     * @return The address of the referrer.\r
     */\r
    function yourReferrer(address _user) external view returns (address) {\r
        return referrer[_user].referrer;\r
    }\r
\r
    /**\r
     * @notice Gets the number of discounts left for a specific user.\r
     * @param _user The address of the user.\r
     * @return The number of discounts left.\r
     */\r
    function discountLeft(address _user) external view returns (uint256) {\r
        return DISCOUNT_LIMIT - referrer[_user].buyCount;\r
    }\r
\r
    /**\r
     * @notice Gets the total rewards received by a specific user.\r
     * @param _user The address of the user.\r
     * @return The total rewards received.\r
     */\r
    function totalRewardsReceived(\r
        address _user\r
    ) external view returns (uint256) {\r
        return referrer[_user].rewarded;\r
    }\r
\r
    /**\r
     * @notice Calculates the discounted price for a given principal amount.\r
     * @param _principal The principal amount.\r
     * @return The discounted price.\r
     */\r
    function getDiscountedPrice(\r
        uint256 _principal\r
    ) external view returns (uint256) {\r
        uint256 _getMarker = getMarker();\r
        uint256 reward = referredRewardRates[_getMarker];\r
        uint256 _discountedPrice = (_principal * reward) / 10000;\r
        return _discountedPrice;\r
    }\r
}\r
"
    },
    "contracts/token/Bean.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0-or-later\r
pragma solidity 0.8.20;\r
\r
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";\r
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";\r
import "@openzeppelin/contracts/access/Ownable.sol";\r
import "../utils/Registry.sol";\r
import "../utils/MultiSig.sol";\r
\r
/**\r
 * @title Bean Token Contract\r
 */\r
contract Bean is Ownable(msg.sender), ERC20, ERC20Burnable {\r
    /// @notice Tracks total rewards given to each address.\r
    mapping(address => uint256) public totalRewarded;\r
    /// @notice Indicates whether an address is authorized to perform restricted operations.\r
    mapping(address => bool) public isRegistered;\r
\r
    /// @notice Emitted when totalRewarded is increased for a user.\r
    event TotalRewardedAdded(address indexed user, uint256 amount);\r
\r
    /// @notice Emitted when a contract is registered or unregistered.\r
    event RegisteredContractSet(\r
        address indexed contractAddress,\r
        bool indexed isRegistered,\r
        address indexed setter\r
    );\r
\r
    /// @notice Emitted when a transaction is delegated to Multi-Sig\r
    event TransactionDelegated(\r
        uint256 indexed txId,\r
        address indexed caller,\r
        string functionName\r
    );\r
\r
    /// @notice Maximum supply of the Bean tokens.\r
    uint256 public immutable MAX_SUPPLY = 21000000000 ether;\r
\r
    /// @notice Registry contract for getting MultiSig address\r
    Registry public registry;\r
\r
    // =============================================================\r
    //                          CONSTRUCTOR\r
    // =============================================================\r
\r
    constructor(uint256 _initSupply) ERC20("BEAN", "BEAN") {\r
        _mint(msg.sender, _initSupply);\r
    }\r
\r
    // =============================================================\r
    //                          MODIFIERS\r
    // =============================================================\r
\r
    /// @notice Smart modifier that delegates to MultiSig if signer calls, executes directly if MultiSig calls\r
    modifier smartMultiSigOrOwner(bytes memory delegationData, string memory description) {\r
        MultiSig multiSig = getMultiSig();\r
        if (address(multiSig) != address(0)) {\r
            // If MultiSig is calling, allow direct execution\r
            if (msg.sender == address(multiSig)) {\r
                _;\r
                return;\r
            }\r
            // If a signer is calling, delegate to MultiSig\r
            if (multiSig.isSigner(msg.sender) || msg.sender == owner()) {\r
                uint256 txId = multiSig.delegateTransaction(address(this), delegationData, description);\r
                emit TransactionDelegated(txId, msg.sender, "contract_registration");\r
                return;\r
            }\r
            revert("Bean: Unauthorized caller");\r
        } else {\r
            require(msg.sender == owner(), "Bean: Only owner when Multi-Sig not set");\r
            _;\r
        }\r
    }\r
\r
    // =============================================================\r
    //                          MAIN FUNCTIONS\r
    // =============================================================\r
\r
    /**\r
     * @notice Mints new tokens to a specified user.\r
     * @dev Can only be called by registered contracts.\r
     * @param _user The address receiving the newly minted tokens.\r
     * @param _amount The amount of tokens to mint.\r
     */\r
    function mint(address _user, uint256 _amount) public {\r
        require(isRegistered[msg.sender], "Bean: Not authorized");\r
        require(_user != address(0), "Bean: Cannot mint to zero address");\r
        require(_amount > 0, "Bean: Amount must be greater than zero");\r
        require(\r
            totalSupply() + _amount <= MAX_SUPPLY,\r
            "Bean: Max supply reached"\r
        );\r
        _mint(_user, _amount);\r
    }\r
\r
    /**\r
     * @notice Adds reward amount to the total rewarded for a specific address.\r
     * @dev Can only be called by registered contracts.\r
     * @param _amount The reward amount to add.\r
     * @param _address The recipient's address for tracking rewards.\r
     */\r
    function addTotalRewarded(uint256 _amount, address _address) external {\r
        require(isRegistered[msg.sender], "Bean: Not authorized");\r
        require(_address != address(0), "Bean: Cannot add reward to zero address");\r
        require(_amount > 0, "Bean: Amount must be greater than zero");\r
        totalRewarded[_address] += _amount;\r
        emit TotalRewardedAdded(_address, _amount);\r
    }\r
\r
    /**\r
     * The caller withdraws everything to a target wallet.\r
     * @notice Allows the owner to withdraw BEAN tokens accidentally sent to this contract.\r
     * @dev Smart function: delegates to MultiSig if signer calls, executes directly if MultiSig calls.\r
     * @param recipient The address to receive the withdrawn tokens.\r
     */\r
    function withdrawAccidentalBeans(address recipient) external smartMultiSigOrOwner(\r
        abi.encodeWithSignature("withdrawAccidentalBeans(address)", recipient),\r
        string(abi.encodePacked("Withdraw accidental BEAN tokens to: ", _addressToString(recipient)))\r
    ) {\r
        require(recipient != address(0), "Bean: Recipient cannot be zero address");\r
        uint256 balance = balanceOf(address(this));\r
        require(balance > 0, "Bean: No BEAN tokens to withdraw");\r
        _transfer(address(this), recipient, balance);\r
    }\r
\r
    // =============================================================\r
    //                            SETTERS\r
    // =============================================================\r
\r
    /**\r
     * @notice Sets the registry contract address.\r
     * @dev Can only be called by the owner.\r
     * @param _registry The address of the Registry contract.\r
     */\r
    function setRegistry(address _registry) external onlyOwner {\r
        require(_registry != address(0), "Bean: Registry cannot be zero address");\r
        registry = Registry(_registry);\r
    }\r
\r
    /**\r
     * @notice Registers a contract as authorized to perform restricted operations.\r
     * @dev Smart function: delegates to MultiSig if signer calls, executes directly if MultiSig calls.\r
     * @param _contract The contract address to authorize.\r
     */\r
    function setRegisteredContracts(address _contract) external smartMultiSigOrOwner(\r
        abi.encodeWithSignature("setRegisteredContracts(address)", _contract),\r
        string(abi.encodePacked("Register contract: ", _addressToString(_contract)))\r
    ) {\r
        require(_contract != address(0), "Bean: Cannot register zero address");\r
        require(!isRegistered[_contract], "Bean: Contract already registered");\r
        isRegistered[_contract] = true;\r
        emit RegisteredContractSet(\r
            _contract,\r
            isRegistered[_contract],\r
            msg.sender\r
        );\r
    }\r
\r
    /**\r
     * @notice Unregisters a contract from performing restricted operations.\r
     * @dev Smart function: delegates to MultiSig if signer calls, executes directly if MultiSig calls.\r
     * @param _contract The contract address to unauthorize.\r
     */\r
    function unregisterContract(address _contract) external smartMultiSigOrOwner(\r
        abi.encodeWithSignature("unregisterContract(address)", _contract),\r
        string(abi.encodePacked("Unregister contract: ", _addressToString(_contract)))\r
    ) {\r
        require(_contract != address(0), "Bean: Cannot unregister zero address");\r
        require(isRegistered[_contract], "Bean: Contract not registered");\r
        isRegistered[_contract] = false;\r
        emit RegisteredContractSet(\r
            _contract,\r
            isRegistered[_contract],\r
            msg.sender\r
        );\r
    }\r
\r
    // =============================================================\r
    //                            GETTER\r
    // =============================================================\r
\r
    /**\r
     * @notice Gets the MultiSig contract address from Registry\r
     * @return The MultiSig contract instance, or address(0) if not set\r
     */\r
    function getMultiSig() internal view returns (MultiSig) {\r
        if (address(registry) == address(0)) {\r
            return MultiSig(address(0));\r
        }\r
\r
        try registry.getContractAddress("MultiSig") returns (address multiSigAddress) {\r
            return MultiSig(multiSigAddress);\r
        } catch {\r
            return MultiSig(address(0));\r
        }\r
    }\r
\r
    /**\r
     * @notice Checks whether the maximum supply of tokens has been reached.\r
     * @return True if the total supply is equal to or exceeds the maximum supply.\r
     */\r
    function isMaxSupplyReached() external view returns (bool) {\r
        return totalSupply() >= MAX_SUPPLY;\r
    }\r
\r
    /**\r
     * @dev Convert address to string for descriptions\r
     */\r
    function _addressToString(address addr) internal pure returns (string memory) {\r
        bytes32 value = bytes32(uint256(uint160(addr)));\r
        bytes memory alphabet = "0123456789abcdef";\r
        bytes memory str = new bytes(42);\r
        str[0] = '0';\r
        str[1] = 'x';\r
        for (uint256 i = 0; i < 20; i++) {\r
            str[2+i*2] = alphabet[uint8(value[i + 12] >> 4)];\r
            str[3+i*2] = alphabet[uint8(value[i + 12] & 0x0f)];\r
        }\r
        return string(str);\r
    }\r
}\r
"
    },
    "contracts/utils/MultiSig.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0\r
pragma solidity 0.8.20;\r
\r
/**\r
 * @title MultiSig\r
 * @dev Multi-signature contract that automatically allows registered contracts from Registry\r
 * Supports multiple pending transactions from different contracts simultaneously\r
 */\r
contract MultiSig {\r
    \r
    // =============================================================\r
    //                          STRUCTS\r
    // =============================================================\r
    \r
    struct Transaction {\r
        address targetContract;      // Contract to call\r
        bytes data;                 // Function call data\r
        uint256 approvals;          // Current approval count\r
        bool executed;              // Execution status\r
        address proposer;           // Who proposed the transaction\r
        uint256 timestamp;          // When proposed\r
        string description;         // Human readable description\r
    }\r
    \r
    // =============================================================\r
    //                          STATE VARIABLES\r
    // =============================================================\r
    \r
    /// @notice Array of the 5 authorized signers\r
    address[5] public signers;\r
    \r
    /// @notice Maps transaction ID to transaction details\r
    mapping(uint256 => Transaction) public transactions;\r
    \r
    /// @notice Maps transaction ID to signer address to approval status\r
    mapping(uint256 => mapping(address => bool)) public hasApproved;\r
    \r
    /// @notice Next transaction ID to use\r
    uint256 public nextTransactionId;\r
    \r
    /// @notice Minimum approvals required (3 out of 5)\r
    uint256 public constant REQUIRED_APPROVALS = 3;\r
    \r
    /// @notice Reference to the Registry contract\r
    address public registry;\r
    \r
    /// @notice Maps contract addresses that can delegate to this Multi-Sig\r
    mapping(address => bool) public authorizedContracts;\r
    \r
    // =============================================================\r
    //                          EVENTS\r
    // =============================================================\r
    \r
    /**\r
     * @notice Emitted when a transaction is proposed\r
     * @param txId The unique transaction ID\r
     * @param targetContract The contract the transaction will call\r
     * @param proposer The address that proposed the transaction\r
     * @param description Human readable description\r
     */\r
    event TransactionProposed(\r
        uint256 indexed txId,\r
        address indexed targetContract,\r
        address indexed proposer,\r
        string description\r
    );\r
    \r
    /**\r
     * @notice Emitted when a signer approves a transaction\r
     * @param txId The transaction ID\r
     * @param signer The address of the approving signer\r
     * @param approvalCount Current approval count\r
     */\r
    event TransactionApproved(\r
        uint256 indexed txId,\r
        address indexed signer,\r
        uint256 approvalCount\r
    );\r
    \r
    /**\r
     * @notice Emitted when a transaction is executed\r
     * @param txId The transaction ID\r
     * @param executor The address that executed the transaction\r
     * @param targetContract The contract that was called\r
     */\r
    event TransactionExecuted(\r
        uint256 indexed txId,\r
        address indexed executor,\r
        address indexed targetContract\r
    );\r
    \r
    /**\r
     * @notice Emitted when a contract is authorized to use Multi-Sig\r
     * @param contractAddress The address of the authorized contract\r
     * @param authorized Whether the contract is authorized\r
     */\r
    event ContractAuthorized(\r
        address indexed contractAddress,\r
        bool authorized\r
    );\r
    \r
    /**\r
     * @notice Emitted when signers are updated\r
     * @param oldSigners The previous array of signers\r
     * @param newSigners The new array of signers\r
     */\r
    event SignersUpdated(\r
        address[5] oldSigners,\r
        address[5] newSigners\r
    );\r
    \r
    // =============================================================\r
    //                          MODIFIERS\r
    // =============================================================\r
    \r
    /**\r
     * @dev Modifier to check if the caller is one of the authorized signers\r
     */\r
    modifier onlySigner() {\r
        require(isSigner(msg.sender), "MultiSig: Not authorized signer");\r
        _;\r
    }\r
    \r
    /**\r
     * @dev Modifier to check if the caller is an authorized contract\r
     */\r
    modifier onlyAuthorizedContract() {\r
        require(_isAuthorizedContract(msg.sender), "MultiSig: Not authorized contract");\r
        _;\r
    }\r
    \r
    /**\r
     * @dev Modifier to check if transaction exists and hasn't been executed\r
     */\r
    modifier validTransaction(uint256 txId) {\r
        require(txId < nextTransactionId, "MultiSig: Transaction does not exist");\r
        require(!transactions[txId].executed, "MultiSig: Transaction already executed");\r
        _;\r
    }\r
    \r
    // =============================================================\r
    //                          CONSTRUCTOR\r
    // =============================================================\r
    \r
    /**\r
     * @notice Initialize the multi-sig with 5 authorized signers and registry\r
     * @param _signer1 First authorized signer address\r
     * @param _signer2 Second authorized signer address\r
     * @param _signer3 Third authorized signer address\r
     * @param _signer4 Fourth authorized signer address\r
     * @param _signer5 Fifth authorized signer address\r
     * @param _registry Address of the Registry contract\r
     */\r
    constructor(\r
        address _signer1,\r
        address _signer2,\r
        address _signer3,\r
        address _signer4,\r
        address _signer5,\r
        address _registry\r
    ) {\r
        require(_signer1 != address(0), "MultiSig: Invalid signer1");\r
        require(_signer2 != address(0), "MultiSig: Invalid signer2");\r
        require(_signer3 != address(0), "MultiSig: Invalid signer3");\r
        require(_signer4 != address(0), "MultiSig: Invalid signer4");\r
        require(_signer5 != address(0), "MultiSig: Invalid signer5");\r
\r
        require(_signer1 != _signer2 && _signer1 != _signer3 && _signer1 != _signer4 && _signer1 != _signer5 &&\r
                _signer2 != _signer3 && _signer2 != _signer4 && _signer2 != _signer5 &&\r
                _signer3 != _signer4 && _signer3 != _signer5 &&\r
                _signer4 != _signer5,\r
                "MultiSig: Duplicate signers not allowed");\r
\r
        signers[0] = _signer1;\r
        signers[1] = _signer2;\r
        signers[2] = _signer3;\r
        signers[3] = _signer4;\r
        signers[4] = _signer5;\r
        registry = _registry;\r
        nextTransactionId = 1; // Start from 1 to avoid confusion with default values\r
    }\r
    \r
    // =============================================================\r
    //                          ADMIN FUNCTIONS\r
    // =============================================================\r
    \r
    /**\r
     * @notice Authorize a contract to delegate transactions to this Multi-Sig\r
     * @param contractAddress The address of the contract to authorize\r
     * @param authorized Whether to authorize or deauthorize\r
     */\r
    function setAuthorizedContract(address contractAddress, bool authorized) external onlySigner {\r
        require(contractAddress != address(0), "MultiSig: Invalid contract address");\r
        require(contractAddress != address(this), "MultiSig: Cannot authorize self");\r
\r
        // This needs Multi-Sig approval too\r
        bytes memory data = abi.encodeWithSignature("_setAuthorizedContract(address,bool)", contractAddress, authorized);\r
        uint256 txId = _createTransaction(\r
            address(this),\r
            data,\r
            string(abi.encodePacked("Authorize contract: ", _addressToString(contractAddress)))\r
        );\r
        \r
        // Auto-approve from the proposer\r
        hasApproved[txId][msg.sender] = true;\r
        transactions[txId].approvals++;\r
        \r
        emit TransactionProposed(txId, address(this), msg.sender, string(abi.encodePacked("Authorize contract: ", _addressToString(contractAddress))));\r
        emit TransactionApproved(txId, msg.sender, transactions[txId].approvals);\r
    }\r
    \r
    /**\r
     * @dev Internal function to actually set authorized contract (called after Multi-Sig approval)\r
     */\r
    function _setAuthorizedContract(address contractAddress, bool authorized) external {\r
        require(msg.sender == address(this), "MultiSig: Only self can call");\r
        authorizedContracts[contractAddress] = authorized;\r
        emit ContractAuthorized(contractAddress, authorized);\r
    }\r
\r
    /**\r
     * @notice Propose to replace the current signers with new ones (requires Multi-Sig approval)\r
     * @param _newSigner1 New first signer address\r
     * @param _newSigner2 New second signer address\r
     * @param _newSigner3 New third signer address\r
     * @param _newSigner4 New fourth signer address\r
     * @param _newSigner5 New fifth signer address\r
     */\r
    function proposeSignerReplacement(\r
        address _newSigner1,\r
        address _newSigner2,\r
        address _newSigner3,\r
        address _newSigner4,\r
        address _newSigner5\r
    ) external onlySigner {\r
        require(_newSigner1 != address(0), "MultiSig: Invalid signer1");\r
        require(_newSigner2 != address(0), "MultiSig: Invalid signer2");\r
        require(_newSigner3 != address(0), "MultiSig: Invalid signer3");\r
        require(_newSigner4 != address(0), "MultiSig: Invalid signer4");\r
        require(_newSigner5 != address(0), "MultiSig: Invalid signer5");\r
\r
        require(_newSigner1 != _newSigner2 && _newSigner1 != _newSigner3 && _newSigner1 != _newSigner4 && _newSigner1 != _newSigner5 &&\r
                _newSigner2 != _newSigner3 && _newSigner2 != _newSigner4 && _newSigner2 != _newSigner5 &&\r
                _newSigner3 != _newSigner4 && _newSigner3 != _newSigner5 &&\r
                _newSigner4 != _newSigner5,\r
                "MultiSig: Duplicate signers not allowed");\r
\r
        bytes memory data = abi.encodeWithSignature(\r
            "_replaceSigners(address,address,address,address,address)",\r
            _newSigner1,\r
            _newSigner2,\r
            _newSigner3,\r
            _newSigner4,\r
            _newSigner5\r
        );\r
\r
        uint256 txId = _createTransaction(\r
            address(this),\r
            data,\r
            string(abi.encodePacked(\r
                "Replace signers with: ",\r
                _addressToString(_newSigner1), ", ",\r
  

Tags:
ERC20, Multisig, Mintable, Burnable, Voting, Upgradeable, Multi-Signature, Factory|addr:0x41e00ca0da24b57c9be9a82a97ac12cbc361f3a3|verified:true|block:23453398|tx:0xcc262c9708cd693ee0a686c49ecd1a9c3938e1e9b16414bb45b20b201c0270ce|first_check:1758969360

Submitted on: 2025-09-27 12:36:02

Comments

Log in to comment.

No comments yet.