ZCHFSavingsManager

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/ZCHFSavingsManager.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {RedemptionLimiter} from "./RedemptionLimiter.sol";

/// @notice Minimal ERC-20 interface used for basic token operations
interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function balanceOf(address who) external view returns (uint256);
}

/// @notice Minimal interface for interacting with the Frankencoin savings module
interface IFrankencoinSavings {
    function save(uint192 amount) external;
    function currentTicks() external view returns (uint64);
    function currentRatePPM() external view returns (uint24);
    function INTEREST_DELAY() external view returns (uint64);
    function withdraw(address target, uint192 amount) external returns (uint256);
}

/// @title ZCHFSavingsManager
/// @notice Manages batch deposits into the Frankencoin Savings Module with delayed interest and fee deduction.
/// @dev Tracks each deposit independently using an identifier, computes accrued interest using the external tick-based system,
/// and deducts a fixed annual fee on interest. Only entities with OPERATOR_ROLE can create/redeem deposits.
/// Funds can only be received by addresses with RECEIVER_ROLE.
/// @author Plusplus AG (dev@plusplus.swiss)
/// @custom:security-contact security@plusplus.swiss
contract ZCHFSavingsManager is AccessControl, ReentrancyGuard, RedemptionLimiter {
    /// @notice Role required to create or redeem deposits
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");

    /// @notice Role required to receive withdrawn or rescued funds
    bytes32 public constant RECEIVER_ROLE = keccak256("RECEIVER_ROLE");

    /// @notice Annual fee in parts per million (ppm). For example, 12,500 ppm = 1.25% yearly.
    /// @dev Uint24 is used by the savings module for all ppm values.
    uint24 public constant FEE_ANNUAL_PPM = 12_500;

    /// @notice Struct representing a single tracked customer deposit
    /// @dev `ticksAtDeposit` includes a delay to skip initial non-interest-bearing period.
    struct Deposit {
        /// @dev Amount originally deposited into the savings module (principal). Uint192 is used by the savings module for all amount variables.
        uint192 initialAmount;
        /// @dev Block timestamp when the deposit was created. Uint40 is used by the savings module for all timestamps.
        uint40 createdAt;
        /// @dev Tick count (ppm-seconds) at which interest accrual starts for this deposit. Uint64 is used by the savings module for all tick variables.
        uint64 ticksAtDeposit;
    }

    /// @notice Mapping of unique deposit identifiers to deposit metadata
    /// @dev The identifier is a hashed customer ID, to retain pseudonimity on-chain.
    ///      No way to enumerate deposits as it is not needed by the contract logic. Use events or identifier lists.
    mapping(bytes32 => Deposit) public deposits;

    IERC20 public immutable ZCHF;
    IFrankencoinSavings public immutable savingsModule;

    /// @notice Emitted when a new deposit is created
    /// @param identifier Hashed customer ID
    /// @param amount The amount deposited in ZCHF
    event DepositCreated(bytes32 indexed identifier, uint192 amount);

    /// @notice Emitted when a deposit is redeemed
    /// @param identifier Hashed customer ID
    /// @param totalAmount Amount withdrawn (principal + net interest)
    event DepositRedeemed(bytes32 indexed identifier, uint192 totalAmount);

    // ===========================
    // Custom Errors
    // ===========================

    /// @notice Thrown when a deposit with the given identifier already exists
    error DepositAlreadyExists(bytes32 identifier);

    /// @notice Thrown when a deposit with the given identifier is not found
    error DepositNotFound(bytes32 identifier);

    /// @notice Thrown when expected positive amount is given as zero
    error ZeroAmount();

    /// @notice Thrown when transferFrom fails
    error TransferFromFailed(address from, address to, uint256 amount);

    /// @notice Thrown when an address lacks the RECEIVER_ROLE
    error InvalidReceiver(address receiver);

    /// @notice Thrown when input arrays do not match in length or other argument errors occur
    error InvalidArgument();

    /// @notice Thrown when withdrawal from the savings module is not the expected amount
    error UnexpectedWithdrawalAmount();

    /// @notice Initializes the manager and grants initial roles
    /// @dev This contract grants itself RECEIVER_ROLE for internal redemptions.
    /// @param admin Address to receive DEFAULT_ADMIN_ROLE
    /// @param zchfToken Address of the deployed ZCHF token contract
    /// @param savingsModule_ Address of the deployed Frankencoin savings module
    constructor(address admin, address zchfToken, address savingsModule_) {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(RECEIVER_ROLE, address(this));
        ZCHF = IERC20(zchfToken);
        savingsModule = IFrankencoinSavings(savingsModule_);

        // Not needed as the savings module is a registered minter with max allowance to move funds
        // ZCHF.approve(address(savingsModule), type(uint256).max);
    }

    /// @notice Sets the daily redemption limit for a user (in ZCHF).
    /// @dev Only callable by DEFAULT_ADMIN_ROLE. See {RedemptionLimiter-_setDailyRedemptionLimit}.
    /// @param user The operator whose limit is being set.
    /// @param dailyLimit The daily quota (in ZCHF) for the rolling window.
    function setDailyLimit(address user, uint192 dailyLimit) external onlyRole(DEFAULT_ADMIN_ROLE) {
        _setDailyRedemptionLimit(user, dailyLimit);
    }

    /// @notice Creates one or more deposits and forwards the total amount to the savings module.
    /// @dev Each deposit is assigned a unique identifier and accrues interest starting after a fixed delay.
    ///      Reverts if any identifier already exists or any amount is zero. Saves once for all.
    /// @param identifiers Unique identifiers for each deposit. Is a hash of the customer ID (must not be reused).
    /// @param amounts Corresponding deposit amounts (must match identifiers length, non-zero)
    /// @param source The address providing the ZCHF. If `address(this)`, will skip pulling funds.
    function createDeposits(bytes32[] calldata identifiers, uint192[] calldata amounts, address source)
        external
        onlyRole(OPERATOR_ROLE)
        nonReentrant
    {
        uint256 len = identifiers.length;
        if (len != amounts.length) revert InvalidArgument();

        uint256 totalAmount;

        // Pre-validate and sum amounts
        for (uint256 i = 0; i < len; ++i) {
            uint192 amt = amounts[i];

            if (amt == 0) revert ZeroAmount();

            totalAmount += amt;
        }

        // Pull funds from source, if applicable
        if (source != address(this)) {
            bool success = ZCHF.transferFrom(source, address(this), totalAmount);
            if (!success) revert TransferFromFailed(source, address(this), totalAmount);
        }

        // In theory, totalAmount can overflow when cast down. This must be an Input error.
        if (totalAmount > type(uint192).max) revert InvalidArgument();

        // Forward to savings module in a single save() call
        savingsModule.save(uint192(totalAmount));

        // Interest starts accruing only after a fixed delay (defined in savings module).
        // Precompute common tick baseline and post-delay snapshot
        uint64 baseTicks = savingsModule.currentTicks();
        uint24 rate = savingsModule.currentRatePPM();
        uint64 delay = savingsModule.INTEREST_DELAY();
        uint64 tickDelay = uint64(uint256(rate) * delay);
        uint64 ticksAtDeposit = baseTicks + tickDelay;
        uint40 ts = uint40(block.timestamp);

        // Record each individual deposit
        for (uint256 i = 0; i < len; ++i) {
            bytes32 id = identifiers[i];
            uint192 amt = amounts[i];

            if (deposits[id].createdAt != 0) revert DepositAlreadyExists(id);
            deposits[id] = Deposit({initialAmount: amt, createdAt: ts, ticksAtDeposit: ticksAtDeposit});

            emit DepositCreated(id, amt);
        }
    }

    /// @notice Redeems a batch of deposits and forwards the total redeemed funds (principal + net interest) to a receiver.
    /// @dev Each deposit is deleted after redemption. The total amount is withdrawn in a single call to the savings module.
    ///      Operators must respect their daily redemption limit.
    /// @param identifiers Unique identifiers (hashed customer IDs) of the deposits to redeem
    /// @param receiver Address that will receive the ZCHF; must have RECEIVER_ROLE
    function redeemDeposits(bytes32[] calldata identifiers, address receiver)
        external
        onlyRole(OPERATOR_ROLE)
        nonReentrant
    {
        if (!hasRole(RECEIVER_ROLE, receiver)) revert InvalidReceiver(receiver);

        uint192 totalAmount;

        // Process each identifier and sum withdrawal amounts
        for (uint256 i = 0; i < identifiers.length; ++i) {
            bytes32 id = identifiers[i];
            Deposit storage deposit = deposits[id];
            uint192 initialAmount = deposit.initialAmount;

            if (initialAmount == 0) revert DepositNotFound(id);

            (, uint192 netInterest) = getDepositDetails(id);
            uint192 totalForDeposit = initialAmount + netInterest;

            emit DepositRedeemed(id, totalForDeposit);

            totalAmount += totalForDeposit;
            delete deposits[id];
        }

        _useMyRedemptionQuota(totalAmount);

        // Withdraw the full amount from savings to receiver and confirm the amount
        // (Savings module will silently return less if not enough available)
        uint256 withdrawn = savingsModule.withdraw(receiver, totalAmount);
        if (withdrawn != totalAmount) revert UnexpectedWithdrawalAmount();
    }

    /// @notice Returns the current principal and net interest for a given deposit
    /// @dev Accrual is calculated from `ticksAtDeposit` to current tick count.
    /// @param identifier The unique identifier of the deposit
    /// @return initialAmount The originally deposited amount (principal)
    /// @return netInterest The interest accrued after fee deduction
    function getDepositDetails(bytes32 identifier) public view returns (uint192 initialAmount, uint192 netInterest) {
        Deposit storage deposit = deposits[identifier];

        initialAmount = deposit.initialAmount;
        if (initialAmount == 0) return (0, 0);

        uint40 createdAt = deposit.createdAt;
        uint64 currentTicks = savingsModule.currentTicks();

        uint64 ticksAtDeposit = deposit.ticksAtDeposit;
        uint64 deltaTicks = currentTicks > ticksAtDeposit ? currentTicks - ticksAtDeposit : 0;

        // Total interest accrued over deposit lifetime (accounts for initial delay via `ticksAtDeposit`)
        uint256 totalInterest = (uint256(deltaTicks) * initialAmount) / 1_000_000 / 365 days;

        // Fee is time-based, not tick-based. Converts elapsed time to tick-equivalent.
        uint256 duration = block.timestamp - createdAt;
        uint256 feeableTicks = duration * FEE_ANNUAL_PPM;

        // Cap the fee to ensure it's never higher than the actual earned ticks
        uint256 feeTicks = feeableTicks < deltaTicks ? feeableTicks : deltaTicks;

        uint256 fee = feeTicks * initialAmount / 1_000_000 / 365 days;

        // Net interest must not be negative
        // The following clamp is not strictly required, since we clamp the feeTicks above.
        // It is still included to be explicit and futureproof.
        netInterest = totalInterest > fee ? uint192(totalInterest - fee) : 0;

        return (initialAmount, netInterest);
    }

    /// @notice Forwards ZCHF to the savings module without creating a tracked deposit.
    /// @dev Useful for correcting underfunding or over-withdrawal. Funds are added on behalf of this contract.
    /// @param source The address from which ZCHF should be pulled. Use `address(this)` if funds are already held.
    /// @param amount The amount of ZCHF to forward. Caller must have OPERATOR_ROLE.
    function addZCHF(address source, uint192 amount) public onlyRole(OPERATOR_ROLE) nonReentrant {
        if (amount == 0) revert ZeroAmount();

        // Pull ZCHF from external source if needed
        if (source != address(this)) {
            bool success = ZCHF.transferFrom(source, address(this), amount);
            if (!success) revert TransferFromFailed(source, address(this), amount);
        }

        // Save on behalf of the contract (untracked)
        savingsModule.save(amount);
    }

    /// @notice Moves funds from the savings module to a receiver, either to collect fees or migrate balances.
    /// @dev Reverts if not enough funds are available in the savings module.
    /// @param receiver Must have RECEIVER_ROLE
    /// @param amount The maximum amount of ZCHF to move
    function moveZCHF(address receiver, uint192 amount) public onlyRole(OPERATOR_ROLE) nonReentrant {
        if (amount == 0) revert ZeroAmount();
        if (!hasRole(RECEIVER_ROLE, receiver)) revert InvalidReceiver(receiver);

        uint256 movedAmount = savingsModule.withdraw(receiver, amount);
        if (movedAmount != amount) revert UnexpectedWithdrawalAmount();
    }

    /// @notice Recovers arbitrary ERC-20 tokens or ETH accidentally sent to this contract
    /// @dev If a token doesn't follow the ERC-20 specs, rescue can not be guaranteed
    /// @param token Address of the token to recover (use zero address for ETH)
    /// @param receiver Must have RECEIVER_ROLE
    /// @param amount The amount to recover
    function rescueTokens(address token, address receiver, uint256 amount)
        public
        onlyRole(OPERATOR_ROLE)
        nonReentrant
    {
        if (amount == 0) revert ZeroAmount();
        if (!hasRole(RECEIVER_ROLE, receiver)) revert InvalidReceiver(receiver);
        if (token == address(0)) {
            payable(receiver).transfer(amount);
        } else {
            IERC20(token).transfer(receiver, amount);
        }
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/access/AccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, 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);
        _;
    }

    /// @inheritdoc IERC165
    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` from `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;
        }
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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;
    }
}
"
    },
    "src/RedemptionLimiter.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

/// @title RedemptionLimiter
/// @notice Rolling 24-hour per-user amount limiter (token-bucket / allowance refill).
/// @dev Intended to be inherited by contracts that need simple rate limiting.
/// @author Plusplus AG (dev@plusplus.swiss)
/// @custom:security-contact security@plusplus.swiss
abstract contract RedemptionLimiter {
    /// @notice Per-operator quota for rate-limiting deposit redemptions
    struct RedemptionQuota {
        uint192 availableAmount; // Remaining amount available for redemption
        uint64 lastRefillTime; // Last time the quota was used/refilled
    }

    /// @notice Per-operator redemption quota tracking
    mapping(address => RedemptionQuota) public userRedemptionQuota;
    /// @notice Daily redemption limit per operator (in asset units)
    mapping(address => uint192) public dailyRedemptionLimit;

    /// @notice Emitted when a user's daily limit is (re)configured.
    event DailyRedemptionLimitSet(address indexed user, uint192 dailyLimit);

    /// @notice Thrown when trying to use a quota for a user without a limit set
    error LimitNotSet();
    /// @notice Thrown when trying to consume more than the available quota
    error WithdrawalLimitExceeded();

    /// @notice Configure or update an operator's daily redemption limit and reset their rolling window to full.
    /// @dev Access control is left to the child contract; call this from a role/owner-gated setter.
    /// @param user The operator whose limit is being set.
    /// @param dailyLimit The daily quota (in asset units) for the rolling window.
    function _setDailyRedemptionLimit(address user, uint192 dailyLimit) internal virtual {
        dailyRedemptionLimit[user] = dailyLimit;

        // Initialize/refresh the current window to full capacity.
        RedemptionQuota storage quota = userRedemptionQuota[user];
        quota.availableAmount = dailyLimit;
        quota.lastRefillTime = uint64(block.timestamp);

        emit DailyRedemptionLimitSet(user, dailyLimit);
    }

    /// @notice Consume quota for an arbitrary user
    /// @dev Recomputes the token-bucket refill since the last update, clamps to limit, then deducts.
    ///      Very small time deltas may result in zero refill due to integer division.
    ///      Reverts with {LimitNotSet} if the user's daily limit is zero.
    ///      Reverts with {WithdrawalLimitExceeded} if `amount` exceeds the available quota.
    /// @param user The user whose quota to consume.
    /// @param amount The amount to deduct from the available quota (in asset units).
    function _useRedemptionQuota(address user, uint256 amount) internal virtual {
        uint192 limit = dailyRedemptionLimit[user];
        if (limit == 0) revert LimitNotSet();

        RedemptionQuota memory quota = userRedemptionQuota[user];

        // Refill quota based on time elapsed since last refill
        uint256 nowTs = block.timestamp;
        uint256 timeElapsed = nowTs - quota.lastRefillTime;
        if (timeElapsed > 0) {
            uint256 refillAmount = (limit * timeElapsed) / 1 days;
            uint256 newAvailable = quota.availableAmount + refillAmount;
            if (newAvailable > limit) newAvailable = limit;

            quota.availableAmount = uint192(newAvailable);
            quota.lastRefillTime = uint64(nowTs);
        }

        // Check if enough quota is available
        if (amount > quota.availableAmount) revert WithdrawalLimitExceeded();

        quota.availableAmount -= uint192(amount);
        userRedemptionQuota[user] = quota;
    }

    /// @notice Convenience helper to consume quota for `msg.sender`.
    /// @dev Calls {_useRedemptionQuota} with `user = msg.sender`.
    /// @param amount The amount to deduct from the caller's available quota.
    function _useMyRedemptionQuota(uint256 amount) internal virtual {
        _useRedemptionQuota(msg.sender, amount);
    }

    /// @notice Compute how much a user could redeem right now, including accrued refill.
    /// @dev Off-chain callers should prefer this view; on-chain callers pay read gas only.
    /// @param user The user to query.
    /// @return available The currently available quota amount in asset units.
    function availableRedemptionQuota(address user) external view returns (uint256 available) {
        uint256 limit = dailyRedemptionLimit[user];
        if (limit == 0) return 0;

        RedemptionQuota memory quota = userRedemptionQuota[user];

        // Calculate potential refill based on time elapsed
        uint256 timeElapsed = block.timestamp - quota.lastRefillTime;
        uint256 refillAmount = (limit * timeElapsed) / 1 days;
        available = uint256(quota.availableAmount) + refillAmount;
        if (available > limit) available = limit;

        return available;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/access/IAccessControl.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 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 to signal 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. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    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;
}
"
    },
    "lib/openzeppelin-contracts/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;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.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 ERC-165 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 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}
"
    }
  },
  "settings": {
    "remappings": [
      "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
      "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
      "forge-std/=lib/forge-std/src/",
      "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
      "openzeppelin-contracts/=lib/openzeppelin-contracts/"
    ],
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "metadata": {
      "useLiteralContent": false,
      "bytecodeHash": "ipfs",
      "appendCBOR": true
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "evmVersion": "prague",
    "viaIR": true
  }
}}

Tags:
ERC165, Proxy, Upgradeable, Factory|addr:0x9e0569f5c3b9e8272d7876a30c81900c51d0bf55|verified:true|block:23540269|tx:0x7875db4169d2a3523e461b979dd4e600d421f57bf05c4c5014ba061d1e33e743|first_check:1760017629

Submitted on: 2025-10-09 15:47:09

Comments

Log in to comment.

No comments yet.