Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x4B148B27cF7fc42f14e75f142148Af3a45B5b06f
Balance 0 ETH
Nonce 1
Code Size 5448 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

5448 bytes
0x6080806040526004361015610012575f80fd5b5f3560e01c90816301ffc9a714610f7257508063205bcec814610f10578063248a9ca314610ede57806329dcb0cf14610e9b5780632b6b063314610e5e5780632dd2615314610d305780632f2ff15d14610cf357806336568abe14610caf5780633e413bee14610c6b5780633fc3066614610bf25780634c4a386f14610bd05780634f0a1fe2146109b95780637bf421651461097c57806391d14854146109345780639b043c4a146107e4578063a217fddf146107ca578063b29a814014610748578063b5545a3c1461063c578063c5c4744c1461061f578063d547741f146105db578063dba3e4ec1461042e578063f0d81e4a146103cd578063f3fef3a31461030f578063fa09e630146101a2578063fa5b731b146101685763fac28eab1461013a575f80fd5b34610164576020366003190112610164576004355f526006602052602060405f2054604051908152f35b5f80fd5b34610164575f3660031901126101645760206040517f00000000000000000000000000000000000000000000000000000000000f42408152f35b34610164576020366003190112610164576101bb610fc5565b6101c36111cd565b6040516370a0823160e01b8152306004820152907f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486020836024816001600160a01b0385165afa928315610304575f936102d0575b506102216111cd565b6001600160401b037f0000000000000000000000000000000000000000000000000000000068f4fcf01642106102c15760ff600254166102b2576001600160a01b0382169283156102a35761029a817f7084f5476618d8e60b11ef0d7d3f06914655adb8793e28ff7f018d4c76d505d5946020946113c7565b604051908152a2005b639fabe1c160e01b5f5260045ffd5b632ccec72d60e11b5f5260045ffd5b631bf5519360e01b5f5260045ffd5b9092506020813d6020116102fc575b816102ec6020938361106e565b8101031261016457519183610218565b3d91506102df565b6040513d5f823e3d90fd5b3461016457604036600319011261016457610328610fc5565b6024356103336111cd565b6001600160401b037f0000000000000000000000000000000000000000000000000000000068f4fcf01642106102c15760ff600254166102b2576001600160a01b0382169182156102a3578161029a7f7084f5476618d8e60b11ef0d7d3f06914655adb8793e28ff7f018d4c76d505d5936020937f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486113c7565b34610164575f366003190112610164576004546103e9816110d6565b905f5b81811061040d576040516020808252819061040990820186610ff1565b0390f35b806001915f52600660205260405f205461042782866110c2565b52016103ec565b346101645760203660031901126101645760043563ffffffff81168091036101645761045861135c565b60ff600254166102b2576001600160401b037f0000000000000000000000000000000000000000000000000000000068f4fcf0164210156105cc5780156105bd576104c55f917f00000000000000000000000000000000000000000000000000000000000f424090611108565b6104f18130337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4861137c565b3382526005602052604082208280526020526040822061051282825461111b565b905581805260066020526040822061052b82825461111b565b90556105398160075461111b565b6007557f461a3a6b0a2768233582f91cbb99a5d4a7470b5aca53eddc0dfd1c81d7b640e56105b46001600160401b03421661059360405161057981611053565b338152866020820152856040820152826060820152611128565b604080519485526001600160401b0390911660208501523393918291820190565b0390a360018055005b630417669560e11b5f5260045ffd5b63387b2e5560e11b5f5260045ffd5b346101645760403660031901126101645761061d6004356105fa610fdb565b90610618610613825f525f602052600160405f20015490565b61121c565b6112dc565b005b34610164575f366003190112610164576020600754604051908152f35b34610164575f3660031901126101645761065461135c565b60ff600254161561073957335f52600360205260ff60405f20541661072a576004545f905f905b8082106106fd578280156105bd57335f52600360205260405f20600160ff198254161790556106cb81337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486113c7565b6040519081527fd7dee2702d63ad89917b6a4da9981c90c4d24f8c2bdfd64c604ecae57d8d065160203392a260018055005b9091610722600191335f52600560205260405f20855f5260205260405f20549061111b565b92019061067b565b63542f378d60e11b5f5260045ffd5b636f9f51c760e01b5f5260045ffd5b3461016457604036600319011261016457610761610fc5565b6024359061076d6111cd565b6001600160a01b031680156102a35781156107bb5761078d8233836113c7565b6040519182527f879f92dded0f26b83c3e00b12e0395dc72cfc3077343d1854ed6988edd1f909660203393a3005b6365e52d5160e11b5f5260045ffd5b34610164575f3660031901126101645760206040515f8152f35b346101645760403660031901126101645760043560243563ffffffff81168082036101645761081161135c565b60ff600254166102b2576001600160401b037f0000000000000000000000000000000000000000000000000000000068f4fcf0164210156105cc5780156105bd578215610925576004548310156109255761086b836110a6565b5091600183019182549163ffffffff8360201c16948286106109165767ffffffff000000009261089b9154611108565b940360201b169067ffffffff0000000019161790556108dc8130337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4861137c565b335f52600560205260405f20825f5260205260405f206108fd82825461111b565b9055815f52600660205260405f2061052b82825461111b565b631354bc7b60e11b5f5260045ffd5b63fb782ddb60e01b5f5260045ffd5b346101645760403660031901126101645761094d610fdb565b6004355f525f60205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b34610164575f36600319011261016457602060405160ff7f0000000000000000000000000000000000000000000000000000000000000006168152f35b3461016457602036600319011261016457600854600435818111610bc9575b6109e18161108f565b906109ef604051928361106e565b8082526109fb8161108f565b602083019390601f1901368537610a11826110d6565b93610a1b836110d6565b90610a258461108f565b92610a33604051948561106e565b848452610a3f8561108f565b602085019590601f19013687376008545f198301928084115f5b848110610b15575050505050506040519586956080870190608088525180915260a0870192905f5b818110610af35750505091610aa28260209488610ab09503868a0152610ff1565b908682036040880152610ff1565b91848303606086015251918281520191905f5b818110610ad1575050500390f35b82516001600160401b0316845285945060209384019390920191600101610ac3565b82516001600160a01b0316855289985060209485019490920191600101610a81565b819b969798999a9b610bb5578083035f190190868211610bb55784821015610ba1576001600160401b0360038e60019460085f5260205f209060021b0190610b6685878060a01b03845416926110c2565b5284810154610b75858d6110c2565b526002810154610b85858f6110c2565b52015416610b93828d6110c2565b52019a99989796959a610a59565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b50806109d8565b34610164575f36600319011261016457602060ff600254166040519015158152f35b3461016457602036600319011261016457610c0b610fc5565b600454610c17816110d6565b916001600160a01b03165f5b828110610c40576040516020808252819061040990820187610ff1565b600190825f52600560205260405f20815f5260205260405f2054610c6482876110c2565b5201610c23565b34610164575f366003190112610164576040517f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486001600160a01b03168152602090f35b3461016457604036600319011261016457610cc8610fdb565b336001600160a01b03821603610ce45761061d906004356112dc565b63334bd91960e11b5f5260045ffd5b346101645760403660031901126101645761061d600435610d12610fdb565b90610d2b610613825f525f602052600160405f20015490565b611254565b34610164575f36600319011261016457600454610d4c8161108f565b90610d5a604051928361106e565b808252601f19610d698261108f565b015f5b818110610e355750505f5b818110610de257826040518091602082016020835281518091526020604084019201905f5b818110610daa575050500390f35b919350916020606060019263ffffffff6040885180518452828682015116868501520151166040820152019401910191849392610d9c565b80610dee6001926110a6565b5063ffffffff8360405192610e0284611024565b805484520154818116602084015260201c166040820152610e2382866110c2565b52610e2e81856110c2565b5001610d77565b602090604051610e4481611024565b5f81525f838201525f604082015282828701015201610d6c565b34610164576020366003190112610164576001600160a01b03610e7f610fc5565b165f526003602052602060ff60405f2054166040519015158152f35b34610164575f3660031901126101645760206040516001600160401b037f0000000000000000000000000000000000000000000000000000000068f4fcf0168152f35b34610164576020366003190112610164576020610f086004355f525f602052600160405f20015490565b604051908152f35b34610164576020366003190112610164576004358015158091036101645760207fc62bad48baf48cd6ecbbd0a7536378816f16faa18d9690765e826bae497ab9cb91610f5a6111cd565b60ff196002541660ff821617600255604051908152a1005b34610164576020366003190112610164576004359063ffffffff60e01b821680920361016457602091637965db0b60e01b8114908115610fb4575b5015158152f35b6301ffc9a760e01b14905083610fad565b600435906001600160a01b038216820361016457565b602435906001600160a01b038216820361016457565b90602080835192838152019201905f5b81811061100e5750505090565b8251845260209384019390920191600101611001565b606081019081106001600160401b0382111761103f57604052565b634e487b7160e01b5f52604160045260245ffd5b608081019081106001600160401b0382111761103f57604052565b90601f801991011681019081106001600160401b0382111761103f57604052565b6001600160401b03811161103f5760051b60200190565b600454811015610ba15760045f5260205f209060011b01905f90565b8051821015610ba15760209160051b010190565b906110e08261108f565b6110ed604051918261106e565b82815280926110fe601f199161108f565b0190602036910137565b81810292918115918404141715610bb557565b91908201809211610bb557565b6008546801000000000000000081101561103f5760018101600855600854811015610ba15760085f5260021b7ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee301606060036001600160401b039260018060a01b038551166bffffffffffffffffffffffff60a01b825416178155602085015160018201556040850151600282015501920151166001600160401b0319825416179055565b335f9081527fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5602052604090205460ff161561120557565b63e2517d3f60e01b5f52336004525f60245260445ffd5b5f8181526020818152604080832033845290915290205460ff161561123e5750565b63e2517d3f60e01b5f523360045260245260445ffd5b5f818152602081815260408083206001600160a01b038616845290915290205460ff166112d6575f818152602081815260408083206001600160a01b0395909516808452949091528120805460ff19166001179055339291907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b50505f90565b5f818152602081815260408083206001600160a01b038616845290915290205460ff16156112d6575f818152602081815260408083206001600160a01b0395909516808452949091528120805460ff19169055339291907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b60026001541461136d576002600155565b633ee5aeb560e01b5f5260045ffd5b6040516323b872dd60e01b60208201526001600160a01b0392831660248201529290911660448301526064808301939093529181526113c5916113c060848361106e565b611402565b565b60405163a9059cbb60e01b60208201526001600160a01b0390921660248301526044808301939093529181526113c5916113c060648361106e565b81516001600160a01b03909116915f91829160200182855af13d156114a8573d6001600160401b03811161103f5761145c916040519161144c6020601f19601f840116018461106e565b82523d5f602084013e5b836114b4565b8051908115159182611484575b50506114725750565b635274afe760e01b5f5260045260245ffd5b81925090602091810103126101645760200151801590811503610164575f80611469565b61145c90606090611456565b906114d857508051156114c957805190602001fd5b630a12f52160e11b5f5260045ffd5b81511580611509575b6114e9575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156114e156fea2646970667358221220eca6192e6b9d133c6fd31de1dae4a5f4a762cf922d46041c14f770e4882cdddf64736f6c634300081b0033

Verified Source Code Full Match

Compiler: v0.8.27+commit.40a35a09 EVM: shanghai Optimization: Yes (200 runs)
AccessControl.sol 209 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}
IAccessControl.sol 98 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}
IERC20.sol 79 lines
// 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);
}
IERC20Metadata.sol 26 lines
// 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);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
SafeERC20.sol 118 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}
Address.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @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://consensys.net/diligence/blog/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.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // 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 FailedInnerCall();
        }
    }
}
Context.sol 28 lines
// 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;
    }
}
ReentrancyGuard.sol 84 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
ERC165.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
BFHCrowdfunding.sol 353 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.27;

import {AccessControl}   from "@openzeppelin/contracts/access/AccessControl.sol";
import {Context}         from "@openzeppelin/contracts/utils/Context.sol";
import {IERC20}          from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata}  from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20}       from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/**
 * USDC-based crowdfunding contract
 *
 * - menuId = 0 is the free tier (donate in whole USDC units; unlimited “stock”)
 * - menuId >= 1 are fixed-price menus with limited stock
 * - Refund mode is reversible via toggleRefund(bool)
 * - Separate donation entrypoints: donateFixed(menuId, units) / donateFree(usdcWholeUnits)
 * - No `require`; all validation via named custom errors and `if (...) revert`
 * - No custom modifiers; use onlyRole(DEFAULT_ADMIN_ROLE). Sender via _msgSender()
 * - Event `Donated` contains no “count”; only amount is emitted
 * - getMenus() returns the full menu array in one call
 * - donationsOf()/totalsByMenu() return per-menu arrays only (no overall total)
 * - recentDonations(n) returns newest-first
 */
contract BFHCrowdfunding is Context, AccessControl, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // ---------- Custom Errors ----------
    // generic / params
    error AddressZero();
    error ArrayLengthMismatch();
    error NoFixedMenuDefined();
    error UnitsZero();

    // time / state
    error DeadlinePassed();    // trying to donate after (>=) deadline, or providing non-future deadline in ctor
    error BeforeDeadline();    // trying to withdraw before deadline
    error RefundsEnabled();    // attempting donate/withdraw while refund mode ON
    error RefundsDisabled();   // attempting claimRefund while refund mode OFF
    error AlreadyRefunded();   // address already claimed its one-shot refund

    // menu
    error InvalidMenuId();     // invalid menuId (e.g., donateFixed with menuId=0, or out-of-bounds)
    error MenuSoldOut();       // fixed menu stock insufficient

    // token recovery
    error AmountZero();        // attempting to recover zero amount

    // ---------- Token / base ----------
    IERC20  public immutable usdc;
    uint8   public immutable usdcDecimals;
    uint256 public immutable ONE_USDC;
    uint64  public immutable deadline;

    // ---------- Refund state ----------
    bool public refundEnabled;                   // reversible toggle
    mapping(address => bool) public hasRefunded; // one-shot full refund per address

    // ---------- Menu ----------
    struct Menu {
        // For menuId=0 (free tier), price is always 0 and stock fields are unused.
        uint256 price;        // price in token smallest unit (USDC decimals)
        uint32  initialStock; // informational for fixed menus
        uint32  remaining;    // remaining stock for fixed menus
    }
    // index 0 is the free tier
    Menu[] private _menus;

    // ---------- Accounting ----------
    // cumulative donated amount per (user, menu)
    mapping(address => mapping(uint256 => uint256)) private _donatedPerMenu;
    // total raised per menu
    mapping(uint256 => uint256) public totalRaisedPerMenu;
    // grand total (kept for convenience; not exposed as a view that returns it)
    uint256 public totalRaised;

    // ---------- Donation log (no “count”) ----------
    struct DonationRecord {
        address donor;
        uint256 menuId;
        uint256 amount;    // in smallest unit
        uint64  timestamp; // block.timestamp
    }
    DonationRecord[] private _donationLog;

    // ---------- Events ----------
    event Donated(address indexed donor, uint256 indexed menuId, uint256 amount, uint64 timestamp);
    event RefundToggled(bool enabled);
    event Refunded(address indexed donor, uint256 amount);
    event Withdrawn(address indexed to, uint256 amount);
    event TokenRecovered(address indexed token, address indexed to, uint256 amount);

    // ---------- Constructor ----------
    /// @param usdcAddress USDC token address
    /// @param deadline_   UNIX timestamp (seconds). Donations are blocked at/after this time
    /// @param fixedPricesWholeUSD USD whole-number prices for menuId=1..N (e.g., [30,100,100,200,...])
    /// @param fixedStocks         Stock counts for menuId=1..N        (e.g., [4999,4999,4999,100,...])
    /// @dev menuId=0 is implicitly created as the free tier.
    constructor(
        address usdcAddress,
        uint64  deadline_,
        uint256[] memory fixedPricesWholeUSD,
        uint32[]  memory fixedStocks
    ) {
        if (usdcAddress == address(0)) revert AddressZero();
        if (deadline_ <= uint64(block.timestamp)) revert DeadlinePassed();
        if (fixedPricesWholeUSD.length != fixedStocks.length) revert ArrayLengthMismatch();
        if (fixedPricesWholeUSD.length == 0) revert NoFixedMenuDefined();

        _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());

        usdc = IERC20(usdcAddress);
        usdcDecimals = IERC20Metadata(usdcAddress).decimals();
        ONE_USDC = 10 ** usdcDecimals;
        deadline = deadline_;

        // menuId = 0: free tier
        _menus.push(Menu({price: 0, initialStock: 0, remaining: 0}));

        // menuId = 1..N: fixed menus
        for (uint256 i = 0; i < fixedPricesWholeUSD.length; i++) {
            uint256 price = fixedPricesWholeUSD[i] * ONE_USDC;
            uint32  stock = fixedStocks[i];
            _menus.push(Menu({price: price, initialStock: stock, remaining: stock}));
        }
    }

    // ---------- Donate (fixed) ----------
    /// @notice Donate to a fixed-price menu in units (>=1)
    /// @dev Reverts if refund mode is ON, if deadline passed, menuId invalid, or stock insufficient
    /// @param menuId menu index, must be 1..N (0 is the free tier and invalid here)
    /// @param units  number of units to purchase/donate (>=1)
    function donateFixed(uint256 menuId, uint32 units)
        external
        nonReentrant
    {
        if (refundEnabled) revert RefundsEnabled();
        if (block.timestamp >= uint256(deadline)) revert DeadlinePassed();
        if (units == 0) revert UnitsZero();
        if (menuId == 0) revert InvalidMenuId();
        if (menuId >= _menus.length) revert InvalidMenuId();

        address sender = _msgSender();
        Menu storage m = _menus[menuId];
        if (m.remaining < units) revert MenuSoldOut();

        uint256 amount = m.price * uint256(units);
        unchecked { m.remaining -= units; }

        usdc.safeTransferFrom(sender, address(this), amount);

        _donatedPerMenu[sender][menuId] += amount;
        totalRaisedPerMenu[menuId] += amount;
        totalRaised += amount;

        _donationLog.push(DonationRecord({
            donor: sender,
            menuId: menuId,
            amount: amount,
            timestamp: uint64(block.timestamp)
        }));

        emit Donated(sender, menuId, amount, uint64(block.timestamp));
    }

    // ---------- Donate (free) ----------
    /// @notice Donate to the free tier (menuId=0) using whole USDC units (no decimals)
    /// @dev 1 unit = exactly 1 USDC = 10^decimals smallest units
    /// @param usdcWholeUnits Number of whole USDC to donate (e.g., 21 => 21 USDC)
    function donateFree(uint32 usdcWholeUnits)
        external
        nonReentrant
    {
        if (refundEnabled) revert RefundsEnabled();
        if (block.timestamp >= uint256(deadline)) revert DeadlinePassed();
        if (usdcWholeUnits == 0) revert UnitsZero();

        address sender = _msgSender();
        uint256 amount = uint256(usdcWholeUnits) * ONE_USDC;

        usdc.safeTransferFrom(sender, address(this), amount);

        _donatedPerMenu[sender][0] += amount;
        totalRaisedPerMenu[0] += amount;
        totalRaised += amount;

        _donationLog.push(DonationRecord({
            donor: sender,
            menuId: 0,
            amount: amount,
            timestamp: uint64(block.timestamp)
        }));

        emit Donated(sender, 0, amount, uint64(block.timestamp));
    }

    // ---------- Refunds (reversible toggle; one-shot per address) ----------
    /// @notice Toggle refund mode ON/OFF. Reversible
    /// @param enabled True to enable refund mode, false to disable
    function toggleRefund(bool enabled)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        refundEnabled = enabled;
        emit RefundToggled(enabled);
    }

    /// @notice Claim a full refund (sum of all past donations across all menus)
    /// @dev One-shot per address; reverts if already refunded or refund mode is OFF
    function claimRefund()
        external
        nonReentrant
    {
        if (!refundEnabled) revert RefundsDisabled();
        address sender = _msgSender();
        if (hasRefunded[sender]) revert AlreadyRefunded();

        uint256 n = _menus.length;
        uint256 amt;
        for (uint256 i = 0; i < n; i++) {
            amt += _donatedPerMenu[sender][i];
        }
        if (amt == 0) revert UnitsZero(); // nothing to refund

        hasRefunded[sender] = true;
        usdc.safeTransfer(sender, amt);
        emit Refunded(sender, amt);
    }

    // ---------- Withdrawals (after deadline; not allowed during refunds) ----------
    /// @notice Withdraw USDC to `to` after the deadline, only when refund mode is OFF
    /// @param to The address to receive the withdrawn USDC
    /// @param amount The amount of USDC to withdraw (in smallest unit)
    function withdraw(address to, uint256 amount)
        public
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        if (block.timestamp < uint256(deadline)) revert BeforeDeadline();
        if (refundEnabled) revert RefundsEnabled();
        if (to == address(0)) revert AddressZero();

        usdc.safeTransfer(to, amount);
        emit Withdrawn(to, amount);
    }

    /// @notice Withdraw all USDC balance to `to` (same conditions as `withdraw`)
    /// @param to The address to receive all withdrawn USDC
    function withdrawAll(address to)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        uint256 bal = usdc.balanceOf(address(this));
        withdraw(to, bal);
    }

    // ---------- Views ----------
    /// @notice Return all menus (index 0 is the free tier)
    /// @return menus Array of all menu items including free tier at index 0
    function getMenus() external view returns (Menu[] memory menus) {
        uint256 n = _menus.length;
        menus = new Menu[](n);
        for (uint256 i = 0; i < n; i++) {
            menus[i] = _menus[i];
        }
    }

    /// @notice Return per-menu cumulative donations for `account` (no grand total)
    /// @param account The address to query donation amounts for
    /// @return amountPerMenu Array of donation amounts per menu in smallest unit
    function donationsOf(address account)
        external
        view
        returns (uint256[] memory amountPerMenu)
    {
        uint256 n = _menus.length;
        amountPerMenu = new uint256[](n);
        for (uint256 i = 0; i < n; i++) {
            amountPerMenu[i] = _donatedPerMenu[account][i];
        }
    }

    /// @notice Return per-menu total raised (no grand total)
    /// @return totals Array of total amounts raised per menu in smallest unit
    function totalsByMenu()
        external
        view
        returns (uint256[] memory totals)
    {
        uint256 n = _menus.length;
        totals = new uint256[](n);
        for (uint256 i = 0; i < n; i++) {
            totals[i] = totalRaisedPerMenu[i];
        }
    }

    /// @notice Return most recent `n` donations, newest first
    /// @param n Maximum number of recent donations to return
    /// @return donors Array of donor addresses
    /// @return menuIds Array of menu IDs for each donation
    /// @return amounts Array of donation amounts in smallest unit
    /// @return timestamps Array of block timestamps for each donation
    function recentDonations(uint256 n)
        external
        view
        returns (
            address[] memory donors,
            uint256[] memory menuIds,
            uint256[] memory amounts,
            uint64[]  memory timestamps
        )
    {
        uint256 len = _donationLog.length;
        if (n > len) n = len;

        donors = new address[](n);
        menuIds = new uint256[](n);
        amounts = new uint256[](n);
        timestamps = new uint64[](n);

        for (uint256 i = 0; i < n; i++) {
            DonationRecord storage r = _donationLog[len - 1 - i];
            donors[i]     = r.donor;
            menuIds[i]    = r.menuId;
            amounts[i]    = r.amount;
            timestamps[i] = r.timestamp;
        }
    }

    /// @notice Recover tokens that were accidentally sent to this contract
    /// @param token The address of the ERC20 token to recover
    /// @param amount The amount of tokens to recover
    function recoverToken(address token, uint256 amount)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        if (token == address(0)) revert AddressZero();
        if (amount == 0) revert AmountZero();

        address sender = _msgSender();
        IERC20(token).safeTransfer(sender, amount);
        emit TokenRecovered(token, sender, amount);
    }

    // ---------- OZ ----------
    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(AccessControl)
        returns (bool)
    {
        return super.supportsInterface(interfaceId);
    }
}

Read Contract

DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
ONE_USDC 0xfa5b731b → uint256
deadline 0x29dcb0cf → uint64
donationsOf 0x3fc30666 → uint256[]
getMenus 0x2dd26153 → tuple[]
getRoleAdmin 0x248a9ca3 → bytes32
hasRefunded 0x2b6b0633 → bool
hasRole 0x91d14854 → bool
recentDonations 0x4f0a1fe2 → address[], uint256[], uint256[], uint64[]
refundEnabled 0x4c4a386f → bool
supportsInterface 0x01ffc9a7 → bool
totalRaised 0xc5c4744c → uint256
totalRaisedPerMenu 0xfac28eab → uint256
totalsByMenu 0xf0d81e4a → uint256[]
usdc 0x3e413bee → address
usdcDecimals 0x7bf42165 → uint8

Write Contract 10 functions

These functions modify contract state and require a wallet transaction to execute.

claimRefund 0xb5545a3c
No parameters
donateFixed 0x9b043c4a
uint256 menuId
uint32 units
donateFree 0xdba3e4ec
uint32 usdcWholeUnits
grantRole 0x2f2ff15d
bytes32 role
address account
recoverToken 0xb29a8140
address token
uint256 amount
renounceRole 0x36568abe
bytes32 role
address callerConfirmation
revokeRole 0xd547741f
bytes32 role
address account
toggleRefund 0x205bcec8
bool enabled
withdraw 0xf3fef3a3
address to
uint256 amount
withdrawAll 0xfa09e630
address to

Recent Transactions

No transactions found for this address