Skip to content
Verified contractPartialMIT

SpendingLimitPolicy

Address0x3e1acac3d72e19f7e180adf06cbdce633e0c3bc4
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.38

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,389,563
Creation transaction
0x0d3f72ee06…ab62dcc550

src/SpendingLimitPolicy.sol

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

import {PackedUserOperation} from "account-abstraction/interfaces/PackedUserOperation.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {IERC7579Execution} from "@openzeppelin/contracts/interfaces/draft-IERC7579.sol";
import {DateTimeLib} from "solady/utils/DateTimeLib.sol";
import {LibERC7579} from "solady/accounts/LibERC7579.sol";
import {PolicyBase} from "kernel-7579-plugins/base/PolicyBase.sol";

/// @title SpendingLimitPolicy — ERC-7579 Policy enforcing per-account calendar-aligned spending limits.
/// @notice Validates `ERC-20.transfer(*, amount)` calls from the smart account in the ERC-4337 validation phase.
///         Two distinct semantic modes coexist per (account, token):
///         - **Accumulator periods (Daily / Weekly / Monthly / Overall):** auto-reset the accumulator at
///           calendar boundaries (Daily / Weekly / Monthly only — Overall never auto-resets; manual reset via
///           `resetLimit` is allowed for Overall but rejected for OneTime); assert `spent + amount ≤ amount_cap`;
///           commit `spent += amount`.
///         - **Per-transaction cap (OneTime):** assert `amount ≤ amount_cap` independently for each spend; no
///           accumulator state, no auto-reset. Multiple spends each ≤ cap are permitted. `resetLimit(*, OneTime)`
///           reverts `CannotResetOneTimeLimit` (no accumulator to reset). The cap is changed by re-issuing
///           `setLimit` (overwrites `amount`) or cleared by `removeLimit`.
///         Validation is a two-pass loop: pass 1 verifies all limits in memory (with auto-reset for
///         accumulator periods); pass 2 commits `spent += amount` for accumulator periods only (skips OneTime).
///         **No configured limits ⇒ spend permitted.** When `(account, token)` has zero limit entries
///         across all periods, both passes are no-ops and the policy returns success — per FR-005, "no
///         configured limit" means "no constraint to enforce". The DestinationPolicy on the same
///         Session 2 still gates the recipient. Fail-closed only fires for the orthogonal "policy not
///         installed for this account" invariant (status != Live).
///         Admin methods (setLimit / resetLimit / removeLimit) are called as SELF-CALLS by the smart account
///         via Session 3 (2-of-2 holder + spender WeightedECDSASigner). `msg.sender == account` for both
///         validation and admin paths.
/// @dev    Ported from the retired `SpendingLimit.sol` executor. Drops: `_execute`-based token moves
///         (policy-first — account calls ERC-20.transfer directly through Kernel execute), native ETH
///         handling (ERC-20-only per clarify Q2), grace window (no staged activation — limits effective
///         immediately when set through Session 3 2-of-2), close/destination coupling (moved to other modules).
contract SpendingLimitPolicy is PolicyBase {
    /*//////////////////////////////////////////////////////////////
                                  TYPES
    //////////////////////////////////////////////////////////////*/

    enum Period {
        OneTime, // 0 — per-transaction cap; no accumulator; resetLimit rejected
        Daily, // 1 — accumulator; auto-resets at account-local midnight
        Weekly, // 2 — accumulator; auto-resets at account-local Monday midnight
        Monthly, // 3 — accumulator; auto-resets at account-local first-of-month midnight
        Overall // 4 — accumulator; never auto-resets; resetLimit allowed
    }

    struct Limit {
        uint128 amount; // cap (per-period accumulator OR per-transaction max for OneTime); 0 ⇒ unset
        uint128 spent; // accumulator — accumulator periods only; unused for OneTime
        uint32 lastResetTime; // unix ts of last reset/boundary; unused for OneTime + Overall
        uint16 resetOffset; // Daily: minutes-into-day; Weekly: day*1440 + minutes; Monthly: same; unused for OneTime + Overall
        bool exists; // explicit flag — amount=0 is indistinguishable from unset otherwise
    }

    enum Status {
        NA,
        Live
    }

    /*//////////////////////////////////////////////////////////////
                                STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(address account => mapping(address token => mapping(uint8 period => Limit))) internal _limits;

    /// @dev Permission install status per (id, account). Required for checkUserOpPolicy to gate.
    mapping(bytes32 id => mapping(address account => Status)) public status;

    uint8 internal constant PERIOD_COUNT = 5;

    /*//////////////////////////////////////////////////////////////
                                EVENTS
    //////////////////////////////////////////////////////////////*/

    event LimitSet(
        address indexed account, address indexed token, uint128 amount, Period period, uint16 resetOffset
    );
    event LimitRemoved(address indexed account, address indexed token, Period period);
    event LimitReset(address indexed account, address indexed token, Period period);
    event Spent(address indexed account, address indexed token, uint128 amount);

    /*//////////////////////////////////////////////////////////////
                                ERRORS
    //////////////////////////////////////////////////////////////*/

    error LimitNotSet();
    error InvalidAmount();
    error InvalidResetOffset();
    error CannotResetOneTimeLimit();

    /*//////////////////////////////////////////////////////////////
                            SELF-CALL ADMIN
    //////////////////////////////////////////////////////////////*/

    /// @notice Configure a per-(token, period) spending limit. Called via Session 3 UserOp —
    ///         `msg.sender` is the smart account. Limits are effective immediately (no grace window).
    function setLimit(address token, uint128 amount, Period period, uint16 resetOffset) external {
        if (amount == 0) revert InvalidAmount();
        _validateResetOffset(period, resetOffset);

        _limits[msg.sender][token][uint8(period)] = Limit({
            amount: amount,
            spent: 0,
            lastResetTime: uint32(block.timestamp),
            resetOffset: resetOffset,
            exists: true
        });

        emit LimitSet(msg.sender, token, amount, period, resetOffset);
    }

    /// @notice Remove a limit. Idempotent — removing a non-existent limit is a no-op (no revert).
    function removeLimit(address token, Period period) external {
        delete _limits[msg.sender][token][uint8(period)];
        emit LimitRemoved(msg.sender, token, period);
    }

    /// @notice Manually reset the `spent` accumulator. Rejects for OneTime limits.
    function resetLimit(address token, Period period) external {
        Limit storage limit = _limits[msg.sender][token][uint8(period)];
        if (!limit.exists) revert LimitNotSet();
        if (period == Period.OneTime) revert CannotResetOneTimeLimit();

        limit.spent = 0;
        limit.lastResetTime = uint32(block.timestamp);
        emit LimitReset(msg.sender, token, period);
    }

    /*//////////////////////////////////////////////////////////////
                        POLICY VALIDATION (CHECK)
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc PolicyBase
    function checkUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp)
        external
        payable
        override
        returns (uint256)
    {
        if (status[id][msg.sender] != Status.Live) return 1;

        // Decode Kernel execute calldata — SINGLE mode only.
        // Layout: selector(4) | mode(32) | offset(32) | length(32) | exec payload
        //   exec payload for SINGLE: target(20) | value(32) | innerCallData
        bytes calldata cd = userOp.callData;
        if (cd.length < 4 + 32 + 32 + 32) return 1;

        // Fail closed on every selector other than ERC-7579 `execute`.
        // `executeUserOp(...)`, `executeFromExecutor(...)`, `installModule(...)`
        // and friends would land on different bytes than our SINGLE-mode
        // decoder assumes — without this guard a crafted `installModule` call
        // could pass policy validation while the actual dispatch installs
        // arbitrary modules.
        if (bytes4(cd[0:4]) != IERC7579Execution.execute.selector) return 1;

        // Mode constraints: CALLTYPE_SINGLE (not BATCH/DELEGATECALL) and
        // EXECTYPE_DEFAULT (not TRY/STATIC). Anything else changes the
        // execution semantics from what our SINGLE-mode decoder assumes.
        bytes32 mode = bytes32(cd[4:36]);
        if (LibERC7579.getCallType(mode) != LibERC7579.CALLTYPE_SINGLE) return 1;
        if (LibERC7579.getExecType(mode) != LibERC7579.EXECTYPE_DEFAULT) return 1;

        uint256 offset = uint256(bytes32(cd[36:68]));
        uint256 lenPos = 4 + offset;
        if (lenPos + 32 > cd.length) return 1;
        uint256 execLen = uint256(bytes32(cd[lenPos:lenPos + 32]));
        uint256 execStart = lenPos + 32;
        if (execStart + execLen > cd.length || execLen < 20 + 32) return 1;

        address token = address(bytes20(cd[execStart:execStart + 20]));
        bytes calldata inner = cd[execStart + 20 + 32:execStart + execLen];

        if (inner.length != 68) return 1;
        if (bytes4(inner[0:4]) != IERC20.transfer.selector) return 1;

        uint128 amount = uint128(uint256(bytes32(inner[36:68])));
        if (amount == 0) return 1;

        // Pass 1: validate all configured limits on (msg.sender, token).
        // OneTime is a per-transaction cap (no accumulator); accumulator periods get
        // calendar-aligned auto-reset applied in-place before the spent+amount check.
        // If no limits exist for (account, token), pass 1 is a no-op and we fall
        // through to a successful return — "no configured limit ⇒ no constraint"
        // per FR-005. The DestinationPolicy on the same session still gates the
        // recipient.
        for (uint8 p; p < PERIOD_COUNT; p++) {
            Limit storage limit = _limits[msg.sender][token][p];
            if (!limit.exists) continue;
            if (Period(p) == Period.OneTime) {
                if (amount > limit.amount) return 1;
            } else {
                _tryReset(Period(p), limit);
                if (limit.spent + amount > limit.amount) return 1;
            }
        }

        // Pass 2: commit accumulator updates. OneTime is stateless — skip.
        for (uint8 p; p < PERIOD_COUNT; p++) {
            Limit storage limit = _limits[msg.sender][token][p];
            if (!limit.exists) continue;
            if (Period(p) == Period.OneTime) continue;
            limit.spent += amount;
        }

        emit Spent(msg.sender, token, amount);
        return 0; // SIG_VALIDATION_SUCCESS
    }

    /// @inheritdoc PolicyBase
    function checkSignaturePolicy(bytes32, address, bytes32, bytes calldata) external view override returns (uint256) {
        return 1;
    }

    function _policyOninstall(bytes32 id, bytes calldata) internal override {
        status[id][msg.sender] = Status.Live;
    }

    function _policyOnUninstall(bytes32 id, bytes calldata) internal override {
        status[id][msg.sender] = Status.NA;
    }

    /*//////////////////////////////////////////////////////////////
                              VIEW FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function getLimit(address account, address token, Period period) external view returns (Limit memory) {
        return _limits[account][token][uint8(period)];
    }

    function getAvailable(address account, address token, Period period) external view returns (uint128) {
        Limit memory limit = _limits[account][token][uint8(period)];
        if (!limit.exists) return 0;
        if (_shouldResetView(period, limit)) return limit.amount;
        return limit.amount > limit.spent ? limit.amount - limit.spent : 0;
    }

    function getLimits(address account, address token) external view returns (Limit[5] memory limits) {
        for (uint8 p; p < PERIOD_COUNT; p++) {
            limits[p] = _limits[account][token][p];
        }
    }

    function isInitialized(address) external pure returns (bool) {
        return true; // scope-level policy — always "initialized" once deployed
    }

    function usedIds(address) external pure returns (uint256) {
        return 0;
    }

    /*//////////////////////////////////////////////////////////////
                          INTERNAL — RESET LOGIC
    //////////////////////////////////////////////////////////////*/

    function _tryReset(Period period, Limit storage limit) internal {
        if (period == Period.OneTime || period == Period.Overall) return;
        if (_shouldReset(period, limit.lastResetTime, limit.resetOffset)) {
            limit.spent = 0;
            limit.lastResetTime = uint32(block.timestamp);
        }
    }

    function _shouldReset(Period period, uint32 lastResetTime, uint16 resetOffset) internal view returns (bool) {
        if (period == Period.OneTime || period == Period.Overall) return false;

        uint256 now_ = block.timestamp;
        uint256 last = uint256(lastResetTime);

        if (period == Period.Daily) {
            uint256 resetSec = uint256(resetOffset % 1440) * 60;
            return (now_ - resetSec) / 86_400 != (last - resetSec) / 86_400;
        }

        if (period == Period.Weekly) {
            uint256 resetDay = uint256(resetOffset / 1440);
            uint256 resetSec = uint256(resetOffset % 1440) * 60;
            uint256 dayShift = (11 - resetDay) % 7;
            return ((now_ - resetSec) / 86_400 + dayShift) / 7 != ((last - resetSec) / 86_400 + dayShift) / 7;
        }

        // Monthly
        (uint256 curYear, uint256 curMonth) = _monthlyPeriod(now_, resetOffset);
        (uint256 lastYear, uint256 lastMonth) = _monthlyPeriod(last, resetOffset);
        return curYear != lastYear || curMonth != lastMonth;
    }

    /// @dev View-only variant for `getAvailable` (operates on in-memory Limit).
    function _shouldResetView(Period period, Limit memory limit) internal view returns (bool) {
        return _shouldReset(period, limit.lastResetTime, limit.resetOffset);
    }

    function _monthlyPeriod(uint256 ts, uint16 resetOffset) internal pure returns (uint256 year, uint256 month) {
        uint256 resetDay = uint256(resetOffset / 1440);
        uint256 minute = uint256(resetOffset % 1440);

        (year, month,) = DateTimeLib.timestampToDate(ts);

        uint256 maxDay = DateTimeLib.daysInMonth(year, month);
        uint256 effectiveDay = resetDay > maxDay ? maxDay : resetDay;
        uint256 resetTs = DateTimeLib.dateTimeToTimestamp(year, month, effectiveDay, minute / 60, minute % 60, 0);

        if (ts < resetTs) {
            if (month == 1) {
                year -= 1;
                month = 12;
            } else {
                month -= 1;
            }
        }
    }

    function _validateResetOffset(Period period, uint16 resetOffset) internal pure {
        if (period == Period.OneTime || period == Period.Overall) return;

        if (period == Period.Daily) {
            if (resetOffset >= 1440) revert InvalidResetOffset();
            return;
        }

        uint256 day = uint256(resetOffset / 1440);

        if (period == Period.Weekly) {
            if (day < 1 || day > 7) revert InvalidResetOffset();
            return;
        }

        if (period == Period.Monthly) {
            if (day < 1 || day > 31) revert InvalidResetOffset();
        }
    }

    /*//////////////////////////////////////////////////////////////
                                METADATA
    //////////////////////////////////////////////////////////////*/

    function name() external pure returns (string memory) {
        return "SpendingLimitPolicy";
    }

    function version() external pure returns (string memory) {
        return "0.1.0";
    }
}

lib/account-abstraction/contracts/interfaces/PackedUserOperation.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.5;

/**
 * User Operation struct
 * @param sender                - The sender account of this request.
 * @param nonce                 - Unique value the sender uses to verify it is not a replay.
 * @param initCode              - If set, the account contract will be created by this constructor/
 * @param callData              - The method call to execute on this account.
 * @param accountGasLimits      - Packed gas limits for validateUserOp and gas limit passed to the callData method call.
 * @param preVerificationGas    - Gas not calculated by the handleOps method, but added to the gas paid.
 *                                Covers batch overhead.
 * @param gasFees               - packed gas fields maxPriorityFeePerGas and maxFeePerGas - Same as EIP-1559 gas parameters.
 * @param paymasterAndData      - If set, this field holds the paymaster address, verification gas limit, postOp gas limit and paymaster-specific extra data
 *                                The paymaster will pay for the transaction instead of the sender.
 * @param signature             - Sender-verified signature over the entire request, the EntryPoint address and the chain ID.
 */
struct PackedUserOperation {
    address sender;
    uint256 nonce;
    bytes initCode;
    bytes callData;
    bytes32 accountGasLimits;
    uint256 preVerificationGas;
    bytes32 gasFees;
    bytes paymasterAndData;
    bytes signature;
}

lib/kernel-7579-plugins/src/base/PolicyBase.sol

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

import {IPolicy} from "src/interfaces/IERC7579Modules.sol";
import {PackedUserOperation} from "account-abstraction/interfaces/PackedUserOperation.sol";

abstract contract PolicyBase is IPolicy {
    function onInstall(bytes calldata data) external payable {
        bytes32 id = bytes32(data[0:32]);
        bytes calldata _data = data[32:];
        _policyOninstall(id, _data);
    }

    function onUninstall(bytes calldata data) external payable {
        bytes32 id = bytes32(data[0:32]);
        bytes calldata _data = data[32:];
        _policyOnUninstall(id, _data);
    }

    function isModuleType(uint256 id) external pure virtual returns (bool) {
        return id == 5;
    }

    function checkUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp)
        external
        payable
        virtual
        returns (uint256);
    function checkSignaturePolicy(bytes32 id, address sender, bytes32 hash, bytes calldata sig)
        external
        view
        virtual
        returns (uint256);

    function _policyOninstall(bytes32 id, bytes calldata _data) internal virtual;
    function _policyOnUninstall(bytes32 id, bytes calldata _data) internal virtual;
}

lib/kernel-7579-plugins/src/interfaces/IERC7579Modules.sol

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

import {PackedUserOperation} from "account-abstraction/interfaces/PackedUserOperation.sol";

interface IModule {
    error AlreadyInitialized(address smartAccount);
    error NotInitialized(address smartAccount);

    /**
     * @dev This function is called by the smart account during installation of the module
     * @param data arbitrary data that may be required on the module during `onInstall`
     * initialization
     *
     * MUST revert on error (i.e. if module is already enabled)
     */
    function onInstall(bytes calldata data) external payable;

    /**
     * @dev This function is called by the smart account during uninstallation of the module
     * @param data arbitrary data that may be required on the module during `onUninstall`
     * de-initialization
     *
     * MUST revert on error
     */
    function onUninstall(bytes calldata data) external payable;

    /**
     * @dev Returns boolean value if module is a certain type
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     *
     * MUST return true if the module is of the given type and false otherwise
     */
    function isModuleType(uint256 moduleTypeId) external view returns (bool);
}

interface IValidator is IModule {
    error InvalidTargetAddress(address target);

    /**
     * @dev Validates a transaction on behalf of the account.
     *         This function is intended to be called by the MSA during the ERC-4337 validation phase
     *         Note: solely relying on bytes32 hash and signature is not sufficient for some
     * validation implementations (i.e. SessionKeys often need access to userOp.calldata)
     * @param userOp The user operation to be validated. The userOp MUST NOT contain any metadata.
     * The MSA MUST clean up the userOp before sending it to the validator.
     * @param userOpHash The hash of the user operation to be validated
     * @return return value according to ERC-4337
     */
    function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external payable returns (uint256);

    /**
     * Validator can be used for ERC-1271 validation
     */
    function isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data)
        external
        view
        returns (bytes4);
}

interface IExecutor is IModule {}

interface IHook is IModule {
    function preCheck(address msgSender, uint256 msgValue, bytes calldata msgData)
        external
        payable
        returns (bytes memory hookData);

    function postCheck(bytes calldata hookData) external payable;
}

interface IFallback is IModule {}

interface IPolicy is IModule {
    function checkUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp) external payable returns (uint256);
    function checkSignaturePolicy(bytes32 id, address sender, bytes32 hash, bytes calldata sig)
        external
        view
        returns (uint256);
}

interface ISigner is IModule {
    function checkUserOpSignature(bytes32 id, PackedUserOperation calldata userOp, bytes32 userOpHash)
        external
        payable
        returns (uint256);
    function checkSignature(bytes32 id, address sender, bytes32 hash, bytes calldata sig) external view returns (bytes4);
}

interface IStatelessValidator is IModule {
    function validateSignatureWithData(bytes32 hash, bytes calldata signature, bytes calldata data)
        external
        view
        returns (bool);
}

interface IStatelessValidatorWithSender is IModule {
    function validateSignatureWithDataWithSender(
        address sender,
        bytes32 hash,
        bytes calldata signature,
        bytes calldata data
    ) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC4337.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (interfaces/draft-IERC4337.sol)

pragma solidity >=0.8.4;

/**
 * @dev A https://github.com/ethereum/ercs/blob/master/ERCS/erc-4337.md#useroperation[user operation] is composed of the following elements:
 * - `sender` (`address`): The account making the operation
 * - `nonce` (`uint256`): Anti-replay parameter (see “Semi-abstracted Nonce Support” )
 * - `factory` (`address`): account factory, only for new accounts
 * - `factoryData` (`bytes`): data for account factory (only if account factory exists)
 * - `callData` (`bytes`): The data to pass to the sender during the main execution call
 * - `callGasLimit` (`uint256`): The amount of gas to allocate the main execution call
 * - `verificationGasLimit` (`uint256`): The amount of gas to allocate for the verification step
 * - `preVerificationGas` (`uint256`): Extra gas to pay the bundler
 * - `maxFeePerGas` (`uint256`): Maximum fee per gas (similar to EIP-1559 max_fee_per_gas)
 * - `maxPriorityFeePerGas` (`uint256`): Maximum priority fee per gas (similar to EIP-1559 max_priority_fee_per_gas)
 * - `paymaster` (`address`): Address of paymaster contract, (or empty, if account pays for itself)
 * - `paymasterVerificationGasLimit` (`uint256`): The amount of gas to allocate for the paymaster validation code
 * - `paymasterPostOpGasLimit` (`uint256`): The amount of gas to allocate for the paymaster post-operation code
 * - `paymasterData` (`bytes`): Data for paymaster (only if paymaster exists)
 * - `signature` (`bytes`): Data passed into the account to verify authorization
 *
 * When passed to on-chain contracts, the following packed version is used.
 * - `sender` (`address`)
 * - `nonce` (`uint256`)
 * - `initCode` (`bytes`): concatenation of factory address and factoryData (or empty)
 * - `callData` (`bytes`)
 * - `accountGasLimits` (`bytes32`): concatenation of verificationGas (16 bytes) and callGas (16 bytes)
 * - `preVerificationGas` (`uint256`)
 * - `gasFees` (`bytes32`): concatenation of maxPriorityFeePerGas (16 bytes) and maxFeePerGas (16 bytes)
 * - `paymasterAndData` (`bytes`): concatenation of paymaster fields (or empty)
 *   For EntryPoint v0.9+, may optionally include `paymasterSignature` at the end:
 *   `paymaster || paymasterVerificationGasLimit || paymasterPostOpGasLimit || paymasterData || paymasterSignature || paymasterSignatureSize || PAYMASTER_SIG_MAGIC`
 * - `signature` (`bytes`)
 */
struct PackedUserOperation {
    address sender;
    uint256 nonce;
    bytes initCode; // `abi.encodePacked(factory, factoryData)`
    bytes callData;
    bytes32 accountGasLimits; // `abi.encodePacked(verificationGasLimit, callGasLimit)` 16 bytes each
    uint256 preVerificationGas;
    bytes32 gasFees; // `abi.encodePacked(maxPriorityFeePerGas, maxFeePerGas)` 16 bytes each
    bytes paymasterAndData; // `abi.encodePacked(paymaster, paymasterVerificationGasLimit, paymasterPostOpGasLimit, paymasterData[, paymasterSignature, paymasterSignatureSize, PAYMASTER_SIG_MAGIC])` (20 bytes, 16 bytes, 16 bytes, dynamic[, dynamic, 2 bytes, 8 bytes])
    bytes signature;
}

/**
 * @dev Aggregates and validates multiple signatures for a batch of user operations.
 *
 * A contract could implement this interface with custom validation schemes that allow signature aggregation,
 * enabling significant optimizations and gas savings for execution and transaction data cost.
 *
 * Bundlers and clients whitelist supported aggregators.
 *
 * See https://eips.ethereum.org/EIPS/eip-7766[ERC-7766]
 */
interface IAggregator {
    /**
     * @dev Validates the signature for a user operation.
     * Returns an alternative signature that should be used during bundling.
     */
    function validateUserOpSignature(
        PackedUserOperation calldata userOp
    ) external view returns (bytes memory sigForUserOp);

    /**
     * @dev Returns an aggregated signature for a batch of user operation's signatures.
     */
    function aggregateSignatures(
        PackedUserOperation[] calldata userOps
    ) external view returns (bytes memory aggregatesSignature);

    /**
     * @dev Validates that the aggregated signature is valid for the user operations.
     *
     * Requirements:
     *
     * - The aggregated signature MUST match the given list of operations.
     */
    function validateSignatures(PackedUserOperation[] calldata userOps, bytes calldata signature) external view;
}

/**
 * @dev Handle nonce management for accounts.
 *
 * Nonces are used in accounts as a replay protection mechanism and to ensure the order of user operations.
 * To avoid limiting the number of operations an account can perform, the interface allows using parallel
 * nonces by using a `key` parameter.
 *
 * See https://eips.ethereum.org/EIPS/eip-4337#semi-abstracted-nonce-support[ERC-4337 semi-abstracted nonce support].
 */
interface IEntryPointNonces {
    /**
     * @dev Returns the nonce for a `sender` account and a `key`.
     *
     * Nonces for a certain `key` are always increasing.
     */
    function getNonce(address sender, uint192 key) external view returns (uint256 nonce);
}

/**
 * @dev Handle stake management for entities (i.e. accounts, paymasters, factories).
 *
 * The EntryPoint must implement the following API to let entities like paymasters have a stake,
 * and thus have more flexibility in their storage access
 * (see https://eips.ethereum.org/EIPS/eip-4337#reputation-scoring-and-throttlingbanning-for-global-entities[reputation, throttling and banning.])
 */
interface IEntryPointStake {
    /**
     * @dev Returns the balance of the account.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Deposits `msg.value` to the account.
     */
    function depositTo(address account) external payable;

    /**
     * @dev Withdraws `withdrawAmount` from the account to `withdrawAddress`.
     */
    function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount) external;

    /**
     * @dev Adds stake to the account with an unstake delay of `unstakeDelaySec`.
     */
    function addStake(uint32 unstakeDelaySec) external payable;

    /**
     * @dev Unlocks the stake of the account.
     */
    function unlockStake() external;

    /**
     * @dev Withdraws the stake of the account to `withdrawAddress`.
     */
    function withdrawStake(address payable withdrawAddress) external;
}

/**
 * @dev Entry point for user operations.
 *
 * User operations are validated and executed by this contract.
 */
interface IEntryPoint is IEntryPointNonces, IEntryPointStake {
    /**
     * @dev A user operation at `opIndex` failed with `reason`.
     */
    error FailedOp(uint256 opIndex, string reason);

    /**
     * @dev A user operation at `opIndex` failed with `reason` and `inner` returned data.
     */
    error FailedOpWithRevert(uint256 opIndex, string reason, bytes inner);

    /**
     * @dev Batch of aggregated user operations per aggregator.
     */
    struct UserOpsPerAggregator {
        PackedUserOperation[] userOps;
        IAggregator aggregator;
        bytes signature;
    }

    /**
     * @dev Executes a batch of user operations.
     * @param beneficiary Address to which gas is refunded upon completing the execution.
     */
    function handleOps(PackedUserOperation[] calldata ops, address payable beneficiary) external;

    /**
     * @dev Executes a batch of aggregated user operations per aggregator.
     * @param beneficiary Address to which gas is refunded upon completing the execution.
     */
    function handleAggregatedOps(
        UserOpsPerAggregator[] calldata opsPerAggregator,
        address payable beneficiary
    ) external;
}

/**
 * @dev Base interface for an ERC-4337 account.
 */
interface IAccount {
    /**
     * @dev Validates a user operation.
     *
     * * MUST validate the caller is a trusted EntryPoint
     * * MUST validate that the signature is a valid signature of the userOpHash, and SHOULD
     *   return SIG_VALIDATION_FAILED (and not revert) on signature mismatch. Any other error MUST revert.
     * * MUST pay the entryPoint (caller) at least the “missingAccountFunds” (which might
     *   be zero, in case the current account’s deposit is high enough)
     *
     * Returns an encoded packed validation data that is composed of the following elements:
     *
     * - `authorizer` (`address`): 0 for success, 1 for failure, otherwise the address of an authorizer contract
     * - `validUntil` (`uint48`): The UserOp is valid only up to this time. Zero for “infinite”.
     * - `validAfter` (`uint48`): The UserOp is valid only after this time.
     */
    function validateUserOp(
        PackedUserOperation calldata userOp,
        bytes32 userOpHash,
        uint256 missingAccountFunds
    ) external returns (uint256 validationData);
}

/**
 * @dev Support for executing user operations by prepending the {executeUserOp} function selector
 * to the UserOperation's `callData`.
 */
interface IAccountExecute {
    /**
     * @dev Executes a user operation.
     */
    function executeUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external;
}

/**
 * @dev Interface for a paymaster contract that agrees to pay for the gas costs of a user operation.
 *
 * NOTE: A paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.
 */
interface IPaymaster {
    enum PostOpMode {
        opSucceeded,
        opReverted,
        postOpReverted
    }

    /**
     * @dev Validates whether the paymaster is willing to pay for the user operation. See
     * {IAccount-validateUserOp} for additional information on the return value.
     *
     * NOTE: Bundlers will reject this method if it modifies the state, unless it's whitelisted.
     */
    function validatePaymasterUserOp(
        PackedUserOperation calldata userOp,
        bytes32 userOpHash,
        uint256 maxCost
    ) external returns (bytes memory context, uint256 validationData);

    /**
     * @dev Verifies the sender is the entrypoint.
     * @param actualGasCost the actual amount paid (by account or paymaster) for this UserOperation
     * @param actualUserOpFeePerGas total gas used by this UserOperation (including preVerification, creation, validation and execution)
     */
    function postOp(
        PostOpMode mode,
        bytes calldata context,
        uint256 actualGasCost,
        uint256 actualUserOpFeePerGas
    ) external;
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC7579.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (interfaces/draft-IERC7579.sol)

pragma solidity >=0.8.4;

import {PackedUserOperation} from "./draft-IERC4337.sol";

uint256 constant VALIDATION_SUCCESS = 0;
uint256 constant VALIDATION_FAILED = 1;
uint256 constant MODULE_TYPE_VALIDATOR = 1;
uint256 constant MODULE_TYPE_EXECUTOR = 2;
uint256 constant MODULE_TYPE_FALLBACK = 3;
uint256 constant MODULE_TYPE_HOOK = 4;

/// @dev Minimal configuration interface for ERC-7579 modules
interface IERC7579Module {
    /**
     * @dev This function is called by the smart account during installation of the module
     * @param data arbitrary data that may be passed to the module during `onInstall` initialization
     *
     * MUST revert on error (e.g. if module is already enabled)
     */
    function onInstall(bytes calldata data) external;

    /**
     * @dev This function is called by the smart account during uninstallation of the module
     * @param data arbitrary data that may be passed to the module during `onUninstall` de-initialization
     *
     * MUST revert on error
     */
    function onUninstall(bytes calldata data) external;

    /**
     * @dev Returns boolean value if module is a certain type
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     *
     * MUST return true if the module is of the given type and false otherwise
     */
    function isModuleType(uint256 moduleTypeId) external view returns (bool);
}

/**
 * @dev ERC-7579 Validation module (type 1).
 *
 * A module that implements logic to validate user operations and signatures.
 */
interface IERC7579Validator is IERC7579Module {
    /**
     * @dev Validates a UserOperation
     * @param userOp the ERC-4337 PackedUserOperation
     * @param userOpHash the hash of the ERC-4337 PackedUserOperation
     *
     * MUST validate that the signature is a valid signature of the userOpHash
     * SHOULD return ERC-4337's SIG_VALIDATION_FAILED (and not revert) on signature mismatch
     * See {IAccount-validateUserOp} for additional information on the return value
     */
    function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external returns (uint256);

    /**
     * @dev Validates a signature using ERC-1271
     * @param sender the address that sent the ERC-1271 request to the smart account
     * @param hash the hash of the ERC-1271 request
     * @param signature the signature of the ERC-1271 request
     *
     * MUST return the ERC-1271 `MAGIC_VALUE` if the signature is valid
     * MUST NOT modify state
     */
    function isValidSignatureWithSender(
        address sender,
        bytes32 hash,
        bytes calldata signature
    ) external view returns (bytes4);
}

/**
 * @dev ERC-7579 Hooks module (type 4).
 *
 * A module that implements logic to execute before and after the account executes a user operation,
 * either individually or batched.
 */
interface IERC7579Hook is IERC7579Module {
    /**
     * @dev Called by the smart account before execution
     * @param msgSender the address that called the smart account
     * @param value the value that was sent to the smart account
     * @param msgData the data that was sent to the smart account
     *
     * MAY return arbitrary data in the `hookData` return value
     */
    function preCheck(
        address msgSender,
        uint256 value,
        bytes calldata msgData
    ) external returns (bytes memory hookData);

    /**
     * @dev Called by the smart account after execution
     * @param hookData the data that was returned by the `preCheck` function
     *
     * MAY validate the `hookData` to validate transaction context of the `preCheck` function
     */
    function postCheck(bytes calldata hookData) external;
}

struct Execution {
    address target;
    uint256 value;
    bytes callData;
}

/**
 * @dev ERC-7579 Execution.
 *
 * Accounts should implement this interface so that the Entrypoint and ERC-7579 modules can execute operations.
 */
interface IERC7579Execution {
    /**
     * @dev Executes a transaction on behalf of the account.
     * @param mode The encoded execution mode of the transaction. See account/utils/draft-ERC7579Utils.sol (Mode encoding via encodeMode/decodeMode) for details
     * @param executionCalldata The encoded execution call data
     *
     * MUST ensure adequate authorization control: e.g. onlyEntryPointOrSelf if used with ERC-4337
     * If a mode is requested that is not supported by the Account, it MUST revert
     */
    function execute(bytes32 mode, bytes calldata executionCalldata) external payable;

    /**
     * @dev Executes a transaction on behalf of the account.
     *         This function is intended to be called by Executor Modules
     * @param mode The encoded execution mode of the transaction. See account/utils/draft-ERC7579Utils.sol (Mode encoding via encodeMode/decodeMode) for details
     * @param executionCalldata The encoded execution call data
     * @return returnData An array with the returned data of each executed subcall
     *
     * MUST ensure adequate authorization control: i.e. onlyExecutorModule
     * If a mode is requested that is not supported by the Account, it MUST revert
     */
    function executeFromExecutor(
        bytes32 mode,
        bytes calldata executionCalldata
    ) external payable returns (bytes[] memory returnData);
}

/**
 * @dev ERC-7579 Account Config.
 *
 * Accounts should implement this interface to expose information that identifies the account, supported modules and capabilities.
 */
interface IERC7579AccountConfig {
    /**
     * @dev Returns the account id of the smart account
     * @return accountImplementationId the account id of the smart account
     *
     * MUST return a non-empty string
     * The accountId SHOULD be structured like so:
     *        "vendorname.accountname.semver"
     * The id SHOULD be unique across all smart accounts
     */
    function accountId() external view returns (string memory accountImplementationId);

    /**
     * @dev Function to check if the account supports a certain execution mode (see above)
     * @param encodedMode the encoded mode
     *
     * MUST return true if the account supports the mode and false otherwise
     */
    function supportsExecutionMode(bytes32 encodedMode) external view returns (bool);

    /**
     * @dev Function to check if the account supports a certain module typeId
     * @param moduleTypeId the module type ID according to the ERC-7579 spec
     *
     * MUST return true if the account supports the module type and false otherwise
     */
    function supportsModule(uint256 moduleTypeId) external view returns (bool);
}

/**
 * @dev ERC-7579 Module Config.
 *
 * Accounts should implement this interface to allow installing and uninstalling modules.
 */
interface IERC7579ModuleConfig {
    event ModuleInstalled(uint256 moduleTypeId, address module);
    event ModuleUninstalled(uint256 moduleTypeId, address module);

    /**
     * @dev Installs a Module of a certain type on the smart account
     * @param moduleTypeId the module type ID according to the ERC-7579 spec
     * @param module the module address
     * @param initData arbitrary data that may be passed to the module during `onInstall`
     * initialization.
     *
     * MUST implement authorization control
     * MUST call `onInstall` on the module with the `initData` parameter if provided
     * MUST emit ModuleInstalled event
     * MUST revert if the module is already installed or the initialization on the module failed
     */
    function installModule(uint256 moduleTypeId, address module, bytes calldata initData) external;

    /**
     * @dev Uninstalls a Module of a certain type on the smart account
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     * @param module the module address
     * @param deInitData arbitrary data that may be passed to the module during `onUninstall`
     * deinitialization.
     *
     * MUST implement authorization control
     * MUST call `onUninstall` on the module with the `deInitData` parameter if provided
     * MUST emit ModuleUninstalled event
     * MUST revert if the module is not installed or the deInitialization on the module failed
     */
    function uninstallModule(uint256 moduleTypeId, address module, bytes calldata deInitData) external;

    /**
     * @dev Returns whether a module is installed on the smart account
     * @param moduleTypeId the module type ID according the ERC-7579 spec
     * @param module the module address
     * @param additionalContext arbitrary data that may be passed to determine if the module is installed
     *
     * MUST return true if the module is installed and false otherwise
     */
    function isModuleInstalled(
        uint256 moduleTypeId,
        address module,
        bytes calldata additionalContext
    ) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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);
}

lib/solady/src/accounts/LibERC7579.sol

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

/// @notice Library for handling ERC7579 mode and execution data.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/accounts/LibERC7579.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/main/contracts/account/utils/draft-ERC7579Utils.sol)
library LibERC7579 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Cannot decode `executionData`.
    error DecodingError();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev A single execution.
    bytes1 internal constant CALLTYPE_SINGLE = 0x00;

    /// @dev A batch of executions.
    bytes1 internal constant CALLTYPE_BATCH = 0x01;

    /// @dev A single `staticcall` execution.
    bytes1 internal constant CALLTYPE_STATICCALL = 0xfe;

    /// @dev A `delegatecall` execution.
    bytes1 internal constant CALLTYPE_DELEGATECALL = 0xff;

    /// @dev Default execution type that reverts on failure.
    bytes1 internal constant EXECTYPE_DEFAULT = 0x00;

    /// @dev Execution type that does not revert on failure.
    bytes1 internal constant EXECTYPE_TRY = 0x01;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      MODE OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Encodes the fields into a mode.
    function encodeMode(bytes1 callType, bytes1 execType, bytes4 selector, bytes22 payload)
        internal
        pure
        returns (bytes32 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := or(shl(8, byte(0, callType)), byte(0, execType))
            result := or(shr(224, selector), shl(64, result))
            result := or(shr(80, payload), shl(176, result))
        }
    }

    /// @dev Returns the call type of the mode.
    function getCallType(bytes32 mode) internal pure returns (bytes1) {
        return bytes1(mode);
    }

    /// @dev Returns the call type of the mode.
    function getExecType(bytes32 mode) internal pure returns (bytes1) {
        return mode[1];
    }

    /// @dev Returns the selector of the mode.
    function getSelector(bytes32 mode) internal pure returns (bytes4) {
        return bytes4(bytes32(uint256(mode) << 48));
    }

    /// @dev Returns the payload stored in the mode.
    function getPayload(bytes32 mode) internal pure returns (bytes22) {
        return bytes22(bytes32(uint256(mode) << 80));
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                 EXECUTION DATA OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Decodes a single call execution.
    /// Reverts if `executionData` is not correctly encoded.
    function decodeSingle(bytes calldata executionData)
        internal
        pure
        returns (address target, uint256 value, bytes calldata data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(gt(executionData.length, 0x33)) {
                mstore(0x00, 0xba597e7e) // `DecodingError()`.
                revert(0x1c, 0x04)
            }
            target := shr(96, calldataload(executionData.offset))
            value := calldataload(add(executionData.offset, 0x14))
            data.offset := add(executionData.offset, 0x34)
            data.length := sub(executionData.length, 0x34)
        }
    }

    /// @dev Decodes a single call execution without bounds checks.
    function decodeSingleUnchecked(bytes calldata executionData)
        internal
        pure
        returns (address target, uint256 value, bytes calldata data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            target := shr(96, calldataload(executionData.offset))
            value := calldataload(add(executionData.offset, 0x14))
            data.offset := add(executionData.offset, 0x34)
            data.length := sub(executionData.length, 0x34)
        }
    }

    /// @dev Decodes a single delegate execution.
    /// Reverts if `executionData` is not correctly encoded.
    function decodeDelegate(bytes calldata executionData)
        internal
        pure
        returns (address target, bytes calldata data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(gt(executionData.length, 0x13)) {
                mstore(0x00, 0xba597e7e) // `DecodingError()`.
                revert(0x1c, 0x04)
            }
            target := shr(96, calldataload(executionData.offset))
            data.offset := add(executionData.offset, 0x14)
            data.length := sub(executionData.length, 0x14)
        }
    }

    /// @dev Decodes a single delegate execution without bounds checks.
    function decodeDelegateUnchecked(bytes calldata executionData)
        internal
        pure
        returns (address target, bytes calldata data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            target := shr(96, calldataload(executionData.offset))
            data.offset := add(executionData.offset, 0x14)
            data.length := sub(executionData.length, 0x14)
        }
    }

    /// @dev Decodes a batch.
    /// Reverts if `executionData` is not correctly encoded.
    function decodeBatch(bytes calldata executionData)
        internal
        pure
        returns (bytes32[] calldata pointers)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let u := calldataload(executionData.offset)
            let s := add(executionData.offset, u)
            let e := sub(add(executionData.offset, executionData.length), 0x20)
            pointers.offset := add(s, 0x20)
            pointers.length := calldataload(s)
            if or(shr(64, u), gt(add(s, shl(5, pointers.length)), e)) {
                mstore(0x00, 0xba597e7e) // `DecodingError()`.
                revert(0x1c, 0x04)
            }
            if pointers.length {
                // Perform bounds checks on the decoded `pointers`.
                // Loop runs out-of-gas if `pointers.length` is big enough to cause overflows.
                for { let i := pointers.length } 1 {} {
                    i := sub(i, 1)
                    let p := calldataload(add(pointers.offset, shl(5, i)))
                    let c := add(pointers.offset, p)
                    let q := calldataload(add(c, 0x40))
                    let o := add(c, q)
                    // forgefmt: disable-next-item
                    if or(shr(64, or(calldataload(o), or(p, q))),
                        or(gt(add(c, 0x40), e), gt(add(o, calldataload(o)), e))) {
                        mstore(0x00, 0xba597e7e) // `DecodingError()`.
                        revert(0x1c, 0x04)
                    }
                    if iszero(i) { break }
                }
            }
        }
    }

    /// @dev Decodes a batch without bounds checks.
    /// This function can be used in `execute`, if the validation phase has already
    /// decoded the `executionData` with checks via `decodeBatch`.
    function decodeBatchUnchecked(bytes calldata executionData)
        internal
        pure
        returns (bytes32[] calldata pointers)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let o := add(executionData.offset, calldataload(executionData.offset))
            pointers.offset := add(o, 0x20)
            pointers.length := calldataload(o)
        }
    }

    /// @dev Decodes a batch and optional `opData`.
    /// Reverts if `executionData` is not correctly encoded.
    function decodeBatchAndOpData(bytes calldata executionData)
        internal
        pure
        returns (bytes32[] calldata pointers, bytes calldata opData)
    {
        opData = emptyCalldataBytes();
        pointers = decodeBatch(executionData);
        if (hasOpData(executionData)) {
            /// @solidity memory-safe-assembly
            assembly {
                let e := sub(add(executionData.offset, executionData.length), 0x20)
                let p := calldataload(add(0x20, executionData.offset))
                let q := add(executionData.offset, p)
                opData.offset := add(q, 0x20)
                opData.length := calldataload(q)
                if or(shr(64, or(opData.length, p)), gt(add(q, opData.length), e)) {
                    mstore(0x00, 0xba597e7e) // `DecodingError()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Decodes a batch without bounds checks.
    /// This function can be used in `execute`, if the validation phase has already
    /// decoded the `executionData` with checks via `decodeBatchAndOpData`.
    function decodeBatchAndOpDataUnchecked(bytes calldata executionData)
        internal
        pure
        returns (bytes32[] calldata pointers, bytes calldata opData)
    {
        opData = emptyCalldataBytes();
        pointers = decodeBatchUnchecked(executionData);
        if (hasOpData(executionData)) {
            /// @solidity memory-safe-assembly
            assembly {
                let q := add(executionData.offset, calldataload(add(0x20, executionData.offset)))
                opData.offset := add(q, 0x20)
                opData.length := calldataload(q)
            }
        }
    }

    /// @dev Returns whether the `executionData` has optional `opData`.
    function hasOpData(bytes calldata executionData) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result :=
                iszero(or(lt(executionData.length, 0x40), lt(calldataload(executionData.offset), 0x40)))
        }
    }

    /// @dev Returns the `i`th execution at `pointers`, without bounds checks.
    /// The bounds check is excluded as this function is intended to be called in a bounded loop.
    function getExecution(bytes32[] calldata pointers, uint256 i)
        internal
        pure
        returns (address target, uint256 value, bytes calldata data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let c := add(pointers.offset, calldataload(add(pointers.offset, shl(5, i))))
            target := calldataload(c)
            value := calldataload(add(c, 0x20))
            let o := add(c, calldataload(add(c, 0x40)))
            data.offset := add(o, 0x20)
            data.length := calldataload(o)
        }
    }

    /// @dev Reencodes `executionData` such that it has `opData` added to it.
    /// Like `abi.encode(abi.decode(executionData, (Call[])), opData)`.
    /// Useful for forwarding `executionData` with extra `opData`.
    /// This function does not perform any check on the validity of `executionData`.
    function reencodeBatch(bytes calldata executionData, bytes memory opData)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := add(0x64, mload(0x40)) // Give some space for `reencodeBatchAsExecuteCalldata`.
            let s := calldataload(executionData.offset) // Offset of `calls`.
            let n := sub(executionData.length, s) // Byte length of `calls`.
            mstore(add(result, 0x20), 0x40) // Store the new offset of `calls`.
            calldatacopy(add(result, 0x60), add(executionData.offset, s), n)
            mstore(add(result, 0x40), add(0x40, n)) // Store the new offset of `opData`.
            let o := add(add(result, 0x60), n) // Start offset of `opData` destination in memory.
            let d := sub(opData, o) // Offset difference between `opData` source and `o`.
            let end := add(mload(opData), add(0x20, o)) // End of `opData` destination in memory.
            for {} 1 {} {
                mstore(o, mload(add(o, d)))
                o := add(o, 0x20)
                if iszero(lt(o, end)) { break }
            }
            mstore(result, sub(o, add(result, 0x20))) // Store the length of `result`.
            calldatacopy(end, calldatasize(), 0x40) // Zeroize the bytes after `end`.
            mstore(0x40, add(0x20, o)) // Allocate memory.
        }
    }

    /// @dev `abi.encodeWithSignature("execute(bytes32,bytes)", mode, reencodeBatch(executionData, opData))`.
    function reencodeBatchAsExecuteCalldata(
        bytes32 mode,
        bytes calldata executionData,
        bytes memory opData
    ) internal pure returns (bytes memory result) {
        result = reencodeBatch(executionData, opData);
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(result)
            result := sub(result, 0x64)
            mstore(add(result, 0x44), 0x40) // Offset of `executionData`.
            mstore(add(result, 0x24), mode)
            mstore(add(result, 0x04), 0xe9ae5c53) // `execute(bytes32,bytes)`.
            mstore(result, add(0x64, n))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          HELPERS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Helper function to return empty calldata bytes.
    function emptyCalldataBytes() internal pure returns (bytes calldata result) {
        /// @solidity memory-safe-assembly
        assembly {
            result.offset := 0
            result.length := 0
        }
    }
}

lib/solady/src/utils/DateTimeLib.sol

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

/// @notice Library for date time operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DateTimeLib.sol)
/// @author Modified from BokkyPooBahsDateTimeLibrary (https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary)
/// @dev
/// Conventions:
/// --------------------------------------------------------------------+
/// Unit      | Range                | Notes                            |
/// --------------------------------------------------------------------|
/// timestamp | 0..0x1e18549868c76ff | Unix timestamp.                  |
/// epochDay  | 0..0x16d3e098039     | Days since 1970-01-01.           |
/// year      | 1970..0xffffffff     | Gregorian calendar year.         |
/// month     | 1..12                | Gregorian calendar month.        |
/// day       | 1..31                | Gregorian calendar day of month. |
/// weekday   | 1..7                 | The day of the week (1-indexed). |
/// --------------------------------------------------------------------+
/// All timestamps of days are rounded down to 00:00:00 UTC.
library DateTimeLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // Weekdays are 1-indexed, adhering to ISO 8601.

    uint256 internal constant MON = 1;
    uint256 internal constant TUE = 2;
    uint256 internal constant WED = 3;
    uint256 internal constant THU = 4;
    uint256 internal constant FRI = 5;
    uint256 internal constant SAT = 6;
    uint256 internal constant SUN = 7;

    // Months and days of months are 1-indexed, adhering to ISO 8601.

    uint256 internal constant JAN = 1;
    uint256 internal constant FEB = 2;
    uint256 internal constant MAR = 3;
    uint256 internal constant APR = 4;
    uint256 internal constant MAY = 5;
    uint256 internal constant JUN = 6;
    uint256 internal constant JUL = 7;
    uint256 internal constant AUG = 8;
    uint256 internal constant SEP = 9;
    uint256 internal constant OCT = 10;
    uint256 internal constant NOV = 11;
    uint256 internal constant DEC = 12;

    // These limits are large enough for most practical purposes.
    // Inputs that exceed these limits result in undefined behavior.

    uint256 internal constant MAX_SUPPORTED_YEAR = 0xffffffff;
    uint256 internal constant MAX_SUPPORTED_EPOCH_DAY = 0x16d3e098039;
    uint256 internal constant MAX_SUPPORTED_TIMESTAMP = 0x1e18549868c76ff;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                    DATE TIME OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the number of days since 1970-01-01 from (`year`,`month`,`day`).
    /// See: https://howardhinnant.github.io/date_algorithms.html
    /// Note: Inputs outside the supported ranges result in undefined behavior.
    /// Use {isSupportedDate} to check if the inputs are supported.
    function dateToEpochDay(uint256 year, uint256 month, uint256 day)
        internal
        pure
        returns (uint256 epochDay)
    {
        /// @solidity memory-safe-assembly
        assembly {
            year := sub(year, lt(month, 3))
            let doy := add(shr(11, add(mul(62719, mod(add(month, 9), 12)), 769)), day)
            let yoe := mod(year, 400)
            let doe := sub(add(add(mul(yoe, 365), shr(2, yoe)), doy), div(yoe, 100))
            epochDay := sub(add(mul(div(year, 400), 146097), doe), 719469)
        }
    }

    /// @dev Returns (`year`,`month`,`day`) from the number of days since 1970-01-01.
    /// Note: Inputs outside the supported ranges result in undefined behavior.
    /// Use {isSupportedDays} to check if the inputs is supported.
    function epochDayToDate(uint256 epochDay)
        internal
        pure
        returns (uint256 year, uint256 month, uint256 day)
    {
        /// @solidity memory-safe-assembly
        assembly {
            epochDay := add(epochDay, 719468)
            let doe := mod(epochDay, 146097)
            let yoe :=
                div(sub(sub(add(doe, div(doe, 36524)), div(doe, 1460)), eq(doe, 146096)), 365)
            let doy := sub(doe, sub(add(mul(365, yoe), shr(2, yoe)), div(yoe, 100)))
            let mp := div(add(mul(5, doy), 2), 153)
            day := add(sub(doy, shr(11, add(mul(mp, 62719), 769))), 1)
            month := byte(mp, shl(160, 0x030405060708090a0b0c0102))
            year := add(add(yoe, mul(div(epochDay, 146097), 400)), lt(month, 3))
        }
    }

    /// @dev Returns the unix timestamp from (`year`,`month`,`day`).
    /// Note: Inputs outside the supported ranges result in undefined behavior.
    /// Use {isSupportedDate} to check if the inputs are supported.
    function dateToTimestamp(uint256 year, uint256 month, uint256 day)
        internal
        pure
        returns (uint256 result)
    {
        unchecked {
            result = dateToEpochDay(year, month, day) * 86400;
        }
    }

    /// @dev Returns (`year`,`month`,`day`) from the given unix timestamp.
    /// Note: Inputs outside the supported ranges result in undefined behavior.
    /// Use {isSupportedTimestamp} to check if the inputs are supported.
    function timestampToDate(uint256 timestamp)
        internal
        pure
        returns (uint256 year, uint256 month, uint256 day)
    {
        (year, month, day) = epochDayToDate(timestamp / 86400);
    }

    /// @dev Returns the unix timestamp from
    /// (`year`,`month`,`day`,`hour`,`minute`,`second`).
    /// Note: Inputs outside the supported ranges result in undefined behavior.
    /// Use {isSupportedDateTime} to check if the inputs are supported.
    function dateTimeToTimestamp(
        uint256 year,
        uint256 month,
        uint256 day,
        uint256 hour,
        uint256 minute,
        uint256 second
    ) internal pure returns (uint256 result) {
        unchecked {
            result = dateToEpochDay(year, month, day) * 86400 + hour * 3600 + minute * 60 + second;
        }
    }

    /// @dev Returns (`year`,`month`,`day`,`hour`,`minute`,`second`)
    /// from the given unix timestamp.
    /// Note: Inputs outside the supported ranges result in undefined behavior.
    /// Use {isSupportedTimestamp} to check if the inputs are supported.
    function timestampToDateTime(uint256 timestamp)
        internal
        pure
        returns (
            uint256 year,
            uint256 month,
            uint256 day,
            uint256 hour,
            uint256 minute,
            uint256 second
        )
    {
        unchecked {
            (year, month, day) = epochDayToDate(timestamp / 86400);
            uint256 secs = timestamp % 86400;
            hour = secs / 3600;
            secs = secs % 3600;
            minute = secs / 60;
            second = secs % 60;
        }
    }

    /// @dev Returns if the `year` is leap.
    function isLeapYear(uint256 year) internal pure returns (bool leap) {
        /// @solidity memory-safe-assembly
        assembly {
            leap := iszero(and(add(mul(iszero(mod(year, 25)), 12), 3), year))
        }
    }

    /// @dev Returns number of days in given `month` of `year`.
    function daysInMonth(uint256 year, uint256 month) internal pure returns (uint256 result) {
        bool flag = isLeapYear(year);
        /// @solidity memory-safe-assembly
        assembly {
            // `daysInMonths = [31,28,31,30,31,30,31,31,30,31,30,31]`.
            // `result = daysInMonths[month - 1] + isLeapYear(year)`.
            result :=
                add(byte(month, shl(152, 0x1f1c1f1e1f1e1f1f1e1f1e1f)), and(eq(month, 2), flag))
        }
    }

    /// @dev Returns the weekday from the unix timestamp.
    /// Monday: 1, Tuesday: 2, ....., Sunday: 7.
    function weekday(uint256 timestamp) internal pure returns (uint256 result) {
        unchecked {
            result = ((timestamp / 86400 + 3) % 7) + 1;
        }
    }

    /// @dev Returns if (`year`,`month`,`day`) is a supported date.
    /// - `1970 <= year <= MAX_SUPPORTED_YEAR`.
    /// - `1 <= month <= 12`.
    /// - `1 <= day <= daysInMonth(year, month)`.
    function isSupportedDate(uint256 year, uint256 month, uint256 day)
        internal
        pure
        returns (bool result)
    {
        uint256 md = daysInMonth(year, month);
        /// @solidity memory-safe-assembly
        assembly {
            result :=
                and(
                    lt(sub(year, 1970), sub(MAX_SUPPORTED_YEAR, 1969)),
                    and(lt(sub(month, 1), 12), lt(sub(day, 1), md))
                )
        }
    }

    /// @dev Returns if (`year`,`month`,`day`,`hour`,`minute`,`second`) is a supported date time.
    /// - `1970 <= year <= MAX_SUPPORTED_YEAR`.
    /// - `1 <= month <= 12`.
    /// - `1 <= day <= daysInMonth(year, month)`.
    /// - `hour < 24`.
    /// - `minute < 60`.
    /// - `second < 60`.
    function isSupportedDateTime(
        uint256 year,
        uint256 month,
        uint256 day,
        uint256 hour,
        uint256 minute,
        uint256 second
    ) internal pure returns (bool result) {
        if (isSupportedDate(year, month, day)) {
            /// @solidity memory-safe-assembly
            assembly {
                result := and(lt(hour, 24), and(lt(minute, 60), lt(second, 60)))
            }
        }
    }

    /// @dev Returns if `epochDay` is a supported unix epoch day.
    function isSupportedEpochDay(uint256 epochDay) internal pure returns (bool result) {
        unchecked {
            result = epochDay < MAX_SUPPORTED_EPOCH_DAY + 1;
        }
    }

    /// @dev Returns if `timestamp` is a supported unix timestamp.
    function isSupportedTimestamp(uint256 timestamp) internal pure returns (bool result) {
        unchecked {
            result = timestamp < MAX_SUPPORTED_TIMESTAMP + 1;
        }
    }

    /// @dev Returns the unix timestamp of the given `n`th weekday `wd`, in `month` of `year`.
    /// Example: 3rd Friday of Feb 2022 is `nthWeekdayInMonthOfYearTimestamp(2022, 2, 3, 5)`
    /// Note: `n` is 1-indexed for traditional consistency.
    /// Invalid weekdays (i.e. `wd == 0 || wd > 7`) result in undefined behavior.
    function nthWeekdayInMonthOfYearTimestamp(uint256 year, uint256 month, uint256 n, uint256 wd)
        internal
        pure
        returns (uint256 result)
    {
        uint256 d = dateToEpochDay(year, month, 1);
        uint256 md = daysInMonth(year, month);
        /// @solidity memory-safe-assembly
        assembly {
            let diff := sub(wd, add(mod(add(d, 3), 7), 1))
            let date := add(mul(sub(n, 1), 7), add(mul(gt(diff, 6), 7), diff))
            result := mul(mul(86400, add(date, d)), and(lt(date, md), iszero(iszero(n))))
        }
    }

    /// @dev Returns the unix timestamp of the most recent Monday.
    function mondayTimestamp(uint256 timestamp) internal pure returns (uint256 result) {
        uint256 t = timestamp;
        /// @solidity memory-safe-assembly
        assembly {
            let day := div(t, 86400)
            result := mul(mul(sub(day, mod(add(day, 3), 7)), 86400), gt(t, 345599))
        }
    }

    /// @dev Returns whether the unix timestamp falls on a Saturday or Sunday.
    /// To check whether it is a week day, just take the negation of the result.
    function isWeekEnd(uint256 timestamp) internal pure returns (bool result) {
        result = weekday(timestamp) > FRI;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              DATE TIME ARITHMETIC OPERATIONS               */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Adds `numYears` to the unix timestamp, and returns the result.
    /// Note: The result will share the same Gregorian calendar month,
    /// but different Gregorian calendar years for non-zero `numYears`.
    /// If the Gregorian calendar month of the result has less days
    /// than the Gregorian calendar month day of the `timestamp`,
    /// the result's month day will be the maximum possible value for the month.
    /// (e.g. from 29th Feb to 28th Feb)
    function addYears(uint256 timestamp, uint256 numYears) internal pure returns (uint256 result) {
        (uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
        result = _offsetted(year + numYears, month, day, timestamp);
    }

    /// @dev Adds `numMonths` to the unix timestamp, and returns the result.
    /// Note: If the Gregorian calendar month of the result has less days
    /// than the Gregorian calendar month day of the `timestamp`,
    /// the result's month day will be the maximum possible value for the month.
    /// (e.g. from 29th Feb to 28th Feb)
    function addMonths(uint256 timestamp, uint256 numMonths)
        internal
        pure
        returns (uint256 result)
    {
        (uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
        month = _sub(month + numMonths, 1);
        result = _offsetted(year + month / 12, _add(month % 12, 1), day, timestamp);
    }

    /// @dev Adds `numDays` to the unix timestamp, and returns the result.
    function addDays(uint256 timestamp, uint256 numDays) internal pure returns (uint256 result) {
        result = timestamp + numDays * 86400;
    }

    /// @dev Adds `numHours` to the unix timestamp, and returns the result.
    function addHours(uint256 timestamp, uint256 numHours) internal pure returns (uint256 result) {
        result = timestamp + numHours * 3600;
    }

    /// @dev Adds `numMinutes` to the unix timestamp, and returns the result.
    function addMinutes(uint256 timestamp, uint256 numMinutes)
        internal
        pure
        returns (uint256 result)
    {
        result = timestamp + numMinutes * 60;
    }

    /// @dev Adds `numSeconds` to the unix timestamp, and returns the result.
    function addSeconds(uint256 timestamp, uint256 numSeconds)
        internal
        pure
        returns (uint256 result)
    {
        result = timestamp + numSeconds;
    }

    /// @dev Subtracts `numYears` from the unix timestamp, and returns the result.
    /// Note: The result will share the same Gregorian calendar month,
    /// but different Gregorian calendar years for non-zero `numYears`.
    /// If the Gregorian calendar month of the result has less days
    /// than the Gregorian calendar month day of the `timestamp`,
    /// the result's month day will be the maximum possible value for the month.
    /// (e.g. from 29th Feb to 28th Feb)
    function subYears(uint256 timestamp, uint256 numYears) internal pure returns (uint256 result) {
        (uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
        result = _offsetted(year - numYears, month, day, timestamp);
    }

    /// @dev Subtracts `numYears` from the unix timestamp, and returns the result.
    /// Note: If the Gregorian calendar month of the result has less days
    /// than the Gregorian calendar month day of the `timestamp`,
    /// the result's month day will be the maximum possible value for the month.
    /// (e.g. from 29th Feb to 28th Feb)
    function subMonths(uint256 timestamp, uint256 numMonths)
        internal
        pure
        returns (uint256 result)
    {
        (uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
        uint256 yearMonth = _totalMonths(year, month) - _add(numMonths, 1);
        result = _offsetted(yearMonth / 12, _add(yearMonth % 12, 1), day, timestamp);
    }

    /// @dev Subtracts `numDays` from the unix timestamp, and returns the result.
    function subDays(uint256 timestamp, uint256 numDays) internal pure returns (uint256 result) {
        result = timestamp - numDays * 86400;
    }

    /// @dev Subtracts `numHours` from the unix timestamp, and returns the result.
    function subHours(uint256 timestamp, uint256 numHours) internal pure returns (uint256 result) {
        result = timestamp - numHours * 3600;
    }

    /// @dev Subtracts `numMinutes` from the unix timestamp, and returns the result.
    function subMinutes(uint256 timestamp, uint256 numMinutes)
        internal
        pure
        returns (uint256 result)
    {
        result = timestamp - numMinutes * 60;
    }

    /// @dev Subtracts `numSeconds` from the unix timestamp, and returns the result.
    function subSeconds(uint256 timestamp, uint256 numSeconds)
        internal
        pure
        returns (uint256 result)
    {
        result = timestamp - numSeconds;
    }

    /// @dev Returns the difference in Gregorian calendar years
    /// between `fromTimestamp` and `toTimestamp`.
    /// Note: Even if the true time difference is less than a year,
    /// the difference can be non-zero is the timestamps are
    /// from different Gregorian calendar years
    function diffYears(uint256 fromTimestamp, uint256 toTimestamp)
        internal
        pure
        returns (uint256 result)
    {
        toTimestamp - fromTimestamp;
        (uint256 fromYear,,) = epochDayToDate(fromTimestamp / 86400);
        (uint256 toYear,,) = epochDayToDate(toTimestamp / 86400);
        result = _sub(toYear, fromYear);
    }

    /// @dev Returns the difference in Gregorian calendar months
    /// between `fromTimestamp` and `toTimestamp`.
    /// Note: Even if the true time difference is less than a month,
    /// the difference can be non-zero is the timestamps are
    /// from different Gregorian calendar months.
    function diffMonths(uint256 fromTimestamp, uint256 toTimestamp)
        internal
        pure
        returns (uint256 result)
    {
        toTimestamp - fromTimestamp;
        (uint256 fromYear, uint256 fromMonth,) = epochDayToDate(fromTimestamp / 86400);
        (uint256 toYear, uint256 toMonth,) = epochDayToDate(toTimestamp / 86400);
        result = _sub(_totalMonths(toYear, toMonth), _totalMonths(fromYear, fromMonth));
    }

    /// @dev Returns the difference in days between `fromTimestamp` and `toTimestamp`.
    function diffDays(uint256 fromTimestamp, uint256 toTimestamp)
        internal
        pure
        returns (uint256 result)
    {
        result = (toTimestamp - fromTimestamp) / 86400;
    }

    /// @dev Returns the difference in hours between `fromTimestamp` and `toTimestamp`.
    function diffHours(uint256 fromTimestamp, uint256 toTimestamp)
        internal
        pure
        returns (uint256 result)
    {
        result = (toTimestamp - fromTimestamp) / 3600;
    }

    /// @dev Returns the difference in minutes between `fromTimestamp` and `toTimestamp`.
    function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp)
        internal
        pure
        returns (uint256 result)
    {
        result = (toTimestamp - fromTimestamp) / 60;
    }

    /// @dev Returns the difference in seconds between `fromTimestamp` and `toTimestamp`.
    function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp)
        internal
        pure
        returns (uint256 result)
    {
        result = toTimestamp - fromTimestamp;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      PRIVATE HELPERS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unchecked arithmetic for computing the total number of months.
    function _totalMonths(uint256 numYears, uint256 numMonths)
        private
        pure
        returns (uint256 total)
    {
        unchecked {
            total = numYears * 12 + numMonths;
        }
    }

    /// @dev Unchecked arithmetic for adding two numbers.
    function _add(uint256 a, uint256 b) private pure returns (uint256 c) {
        unchecked {
            c = a + b;
        }
    }

    /// @dev Unchecked arithmetic for subtracting two numbers.
    function _sub(uint256 a, uint256 b) private pure returns (uint256 c) {
        unchecked {
            c = a - b;
        }
    }

    /// @dev Returns the offsetted timestamp.
    function _offsetted(uint256 year, uint256 month, uint256 day, uint256 timestamp)
        private
        pure
        returns (uint256 result)
    {
        uint256 dm = daysInMonth(year, month);
        if (day >= dm) {
            day = dm;
        }
        result = dateToEpochDay(year, month, day) * 86400 + (timestamp % 86400);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "account-abstraction/=lib/account-abstraction/contracts/",
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/",
    "kernel-7579-plugins/=lib/kernel-7579-plugins/src/",
    "lib/kernel-7579-plugins/src/:src/=lib/kernel-7579-plugins/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.