Skip to content
Verified contractExactMIT

ServicePayments

Address0x87633bac04fb1534b9d4310438482f5f963e2ca5
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,501,100
Creation transaction
0xbb2a2f0c59…de6d0a556e

src/ServicePayments.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

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

/// @notice Fee payments for actions the payer performs in a separate transaction.
/// @dev Nothing but the fee happens on chain here; the payment is matched to the later action off
/// chain through `paramsHash`. This contract never touches the payer's tokens.
/// An item is either fixed (`base > 0`, `perUnit == 0`), paid with `pay`, or per unit (`base == 0`,
/// `perUnit > 0`), paid with `payUnits` for `perUnit * units`.
contract ServicePayments is FeeGate {
    /// @notice Largest `units` one `payUnits` call may charge (MultiSender's recipient cap).
    uint256 public constant MAX_UNITS = 500;

    error ZeroParamsHash();
    error UnitsRequired(bytes32 priceId);
    error InvalidUnits(uint256 units);

    constructor(address initialOwner, address treasury_, address initialGuardian)
        FeeGate(initialOwner, treasury_, initialGuardian)
    {}

    /// @notice Pays the current fee of an enabled fixed item.
    /// @param priceId Item in this contract's price table.
    /// @param paramsHash Client computed hash of the action parameters. Not verified on chain.
    /// @param refTag Opaque tag copied into `FeePaid`.
    function pay(bytes32 priceId, bytes32 paramsHash, bytes32 refTag)
        external
        payable
        whenNotPaused
        nonReentrant
        onlyPayer
        balanceNeutral
    {
        if (paramsHash == bytes32(0)) revert ZeroParamsHash();
        if (_prices[priceId].perUnit != 0) revert UnitsRequired(priceId);
        _chargeFee(priceId, 0, msg.value, paramsHash, refTag);
    }

    /// @notice Pays the current fee of an enabled per-unit item for `units` units.
    /// @param priceId Per-unit item in this contract's price table.
    /// @param units How many units the action covers, 1 to `MAX_UNITS`. Copied into `FeePaid`.
    /// @param paramsHash Client computed hash of the action parameters. Not verified on chain.
    /// @param refTag Opaque tag copied into `FeePaid`.
    function payUnits(bytes32 priceId, uint256 units, bytes32 paramsHash, bytes32 refTag)
        external
        payable
        whenNotPaused
        nonReentrant
        onlyPayer
        balanceNeutral
    {
        if (paramsHash == bytes32(0)) revert ZeroParamsHash();
        if (units == 0 || units > MAX_UNITS) revert InvalidUnits(units);
        if (_prices[priceId].base != 0) revert PerUnitNotSupported(priceId);
        _chargeFee(priceId, units, msg.value, paramsHash, refTag);
    }

    /// @dev Fixed (`base > 0`, `perUnit == 0`) or per unit (`base == 0`, `perUnit > 0`), never both.
    function _validatePriceShape(bytes32 id, uint96 newBase, uint96 newPerUnit) internal pure override {
        if (newBase == 0 && newPerUnit == 0) revert ZeroFee(id);
        if (newBase != 0 && newPerUnit != 0) revert PerUnitNotSupported(id);
    }
}

node_modules/@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

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

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

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

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

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

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

node_modules/@openzeppelin/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

node_modules/@openzeppelin/contracts/utils/Context.sol

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

node_modules/@openzeppelin/contracts/utils/Pausable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol

// 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/FeeGate.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

/// @notice On-chain price table, access gate, pause switch and fee charge shared by every paid contract.
/// @dev Each concrete contract has its own table, gate, previewer list, pause flag and guardian.
/// The fee is forwarded to the immutable treasury in the same call; the contract never holds a balance.
abstract contract FeeGate is Ownable2Step, Pausable, ReentrancyGuard {
    /// @dev Two storage slots. `version == 0` means the item was never priced.
    struct PriceEntry {
        uint96 base;
        uint96 perUnit;
        uint32 version;
        bool enabled;
        bool prevEnabled;
        uint96 prevBase;
        uint96 prevPerUnit;
        uint48 changedAt;
    }

    /// @notice How long the previous price stays payable after a change.
    uint256 public constant PRICE_GRACE = 15 minutes;
    /// @notice Largest factor one `setPrices` write may move a non-zero price component, up or down.
    uint256 public constant MAX_PRICE_STEP = 5;
    /// @notice Largest number of ids per `setPrices` call and of accounts per `setPreviewers` call.
    uint256 public constant MAX_BATCH = 32;

    /// @notice Receives every fee: a multisig or a plain wallet. Fixed at construction; does not follow
    /// ownership transfers.
    address public immutable treasury;
    /// @notice May only pause.
    address public guardian;
    /// @notice While true, only previewers may pay. Starts true and can only be switched off once.
    bool public restricted;
    mapping(address account => bool allowed) public isPreviewer;

    mapping(bytes32 priceId => PriceEntry) internal _prices;

    event FeePaid(
        bytes32 indexed priceId,
        address indexed payer,
        bytes32 indexed refTag,
        uint256 amount,
        uint256 units,
        uint32 priceVersion,
        bytes32 paramsHash
    );
    event PriceSet(bytes32 indexed priceId, uint32 version, uint96 base, uint96 perUnit, bool enabled);
    event PreviewerSet(address indexed account, bool allowed);
    event OpenedToPublic();
    event GuardianSet(address indexed previous, address indexed next);

    error NotOpen();
    error WrongFee(uint256 paid, uint256 expected);
    error ZeroFee(bytes32 priceId);
    error PriceDisabled(bytes32 priceId);
    error PriceStepTooLarge(bytes32 priceId);
    error PriceChangeTooSoon(bytes32 priceId);
    error PerUnitNotSupported(bytes32 priceId);
    error DuplicatePriceId(bytes32 priceId);
    error ZeroPriceId();
    error LengthMismatch();
    error EmptyBatch();
    error BatchTooLarge();
    error ZeroAddress();
    error AlreadyOpen();
    error NotGuardian();
    error RenounceDisabled();
    error FeeForwardFailed();
    error BalanceMismatch();

    /// @param initialOwner Runs the price table, the gate, pause and unpause: a multisig or a plain wallet.
    /// Never zero.
    /// @param treasury_ Receives every fee in the same call: a multisig or a plain wallet, no code required.
    /// Never zero. May equal the owner.
    /// @param initialGuardian The pause-only account. May be zero.
    constructor(address initialOwner, address treasury_, address initialGuardian)
        Ownable(_requireNonZero(initialOwner))
    {
        treasury = _requireNonZero(treasury_);
        restricted = true;
        guardian = initialGuardian;
        emit GuardianSet(address(0), initialGuardian);
    }

    // ---------------------------------------------------------------------------------------------
    // Paid entry point helpers
    // ---------------------------------------------------------------------------------------------

    /// @dev Gate on the direct caller. Applied after `whenNotPaused` and `nonReentrant`.
    modifier onlyPayer() {
        if (!canPay(msg.sender)) revert NotOpen();
        _;
    }

    /// @dev The native balance after the call must equal the balance before it, excluding this call's value.
    modifier balanceNeutral() {
        uint256 balanceBefore = address(this).balance - msg.value;
        _;
        // Compared by difference on purpose: forced or stray balance cancels out.
        // slither-disable-next-line incorrect-equality
        if (address(this).balance != balanceBefore) revert BalanceMismatch();
    }

    /// @dev Checks `paid` against the current price, or the previous price inside the grace window,
    /// emits `FeePaid` and forwards `paid` to the treasury. Nothing runs between the event and the
    /// forwarding call, so the treasury's receive log directly follows `FeePaid` in the receipt.
    function _chargeFee(bytes32 priceId, uint256 units, uint256 paid, bytes32 paramsHash, bytes32 refTag) internal {
        PriceEntry storage e = _prices[priceId];
        if (!e.enabled) revert PriceDisabled(priceId);

        uint256 current = _fee(e.base, e.perUnit, units);
        uint32 usedVersion = 0;
        if (paid == current) {
            usedVersion = e.version;
        } else if (
            e.prevEnabled && block.timestamp < uint256(e.changedAt) + PRICE_GRACE
                && paid == _fee(e.prevBase, e.prevPerUnit, units)
        ) {
            usedVersion = e.version - 1;
        } else {
            revert WrongFee(paid, current);
        }
        if (paid == 0) revert ZeroFee(priceId);

        emit FeePaid(priceId, msg.sender, refTag, paid, units, usedVersion, paramsHash);
        // The destination is the immutable treasury. All gas is forwarded: a Safe proxy needs more than 2300.
        // slither-disable-next-line arbitrary-send-eth,low-level-calls
        (bool ok,) = treasury.call{value: paid}("");
        if (!ok) revert FeeForwardFailed();
    }

    /// @dev Charges several fixed price items (units 0) with one payment. `paid` must equal the sum of
    /// the current fees, or, while any item is in its grace window, the sum in which every item still in
    /// grace takes its previous fee and every other item its current fee. Each item then gets its own
    /// `FeePaid` (with the version actually used) immediately followed by its own forwarding call, in
    /// list order, so the treasury's receive log still directly follows every `FeePaid`.
    /// The caller passes a non-empty list of distinct ids.
    function _chargeFeeSet(bytes32[] memory ids, uint256 paid, bytes32 paramsHash, bytes32 refTag) internal {
        uint256 n = ids.length;
        uint256 current = 0;
        uint256 previous = 0;
        for (uint256 i = 0; i < n; ++i) {
            PriceEntry storage e = _prices[ids[i]];
            if (!e.enabled) revert PriceDisabled(ids[i]);
            current += e.base;
            previous += _inGrace(e) ? e.prevBase : e.base;
        }
        bool usePrevious = false;
        if (paid != current) {
            if (previous == current || paid != previous) revert WrongFee(paid, current);
            usePrevious = true;
        }
        if (paid == 0) revert ZeroFee(ids[0]);

        for (uint256 i = 0; i < n; ++i) {
            _payItem(ids[i], usePrevious, paramsHash, refTag);
        }
    }

    /// @dev One item of `_chargeFeeSet`: its `FeePaid`, then its forwarding call.
    function _payItem(bytes32 id, bool usePrevious, bytes32 paramsHash, bytes32 refTag) private {
        PriceEntry storage e = _prices[id];
        bool usePrev = usePrevious && _inGrace(e);
        uint256 amount = usePrev ? e.prevBase : e.base;
        emit FeePaid(id, msg.sender, refTag, amount, 0, usePrev ? e.version - 1 : e.version, paramsHash);
        // The destination is the immutable treasury. All gas is forwarded: a Safe proxy needs more than 2300.
        // slither-disable-next-line arbitrary-send-eth,low-level-calls
        (bool ok,) = treasury.call{value: amount}("");
        if (!ok) revert FeeForwardFailed();
    }

    /// @dev Quote of `_chargeFeeSet`: the current sum, the grace sum while it differs from the current sum
    /// (else zero), the first moment the grace sum stops being accepted, and whether every item is enabled.
    function _quoteFeeSet(bytes32[] memory ids)
        internal
        view
        returns (uint256 fee, uint256 previousFee, uint64 graceEndsAt, bool enabled)
    {
        enabled = true;
        uint256 endsAt = type(uint256).max;
        uint256 n = ids.length;
        for (uint256 i = 0; i < n; ++i) {
            PriceEntry storage e = _prices[ids[i]];
            if (!e.enabled) enabled = false;
            fee += e.base;
            if (_inGrace(e)) {
                previousFee += e.prevBase;
                uint256 itemEnd = uint256(e.changedAt) + PRICE_GRACE;
                if (itemEnd < endsAt) endsAt = itemEnd;
            } else {
                previousFee += e.base;
            }
        }
        if (!enabled || previousFee == fee) {
            previousFee = 0;
        } else {
            graceEndsAt = uint64(endsAt);
        }
    }

    /// @dev Whether the previous price of an item is still accepted.
    function _inGrace(PriceEntry storage e) private view returns (bool) {
        return e.prevEnabled && block.timestamp < uint256(e.changedAt) + PRICE_GRACE;
    }

    /// @dev Current fee of an item for `units`, without the enabled check.
    function _currentFee(bytes32 priceId, uint256 units) internal view returns (uint256) {
        PriceEntry storage e = _prices[priceId];
        return _fee(e.base, e.perUnit, units);
    }

    function _fee(uint256 base, uint256 perUnit, uint256 units) internal pure returns (uint256) {
        uint256 variable = perUnit * units;
        return variable > base ? variable : base;
    }

    // ---------------------------------------------------------------------------------------------
    // Owner and guardian
    // ---------------------------------------------------------------------------------------------

    /// @notice Writes prices. Every write moves the current values to `prev*` and bumps `version`.
    function setPrices(
        bytes32[] calldata ids,
        uint96[] calldata bases,
        uint96[] calldata perUnits,
        bool[] calldata enabledFlags
    ) external onlyOwner {
        uint256 n = ids.length;
        if (bases.length != n || perUnits.length != n || enabledFlags.length != n) revert LengthMismatch();
        if (n == 0) revert EmptyBatch();
        if (n > MAX_BATCH) revert BatchTooLarge();

        for (uint256 i = 0; i < n; ++i) {
            bytes32 id = ids[i];
            if (id == bytes32(0)) revert ZeroPriceId();
            for (uint256 j = 0; j < i; ++j) {
                if (ids[j] == id) revert DuplicatePriceId(id);
            }
            _writePrice(id, bases[i], perUnits[i], enabledFlags[i]);
        }
    }

    function _writePrice(bytes32 id, uint96 newBase, uint96 newPerUnit, bool newEnabled) private {
        _validatePriceShape(id, newBase, newPerUnit);

        PriceEntry storage e = _prices[id];
        uint32 oldVersion = e.version;
        if (oldVersion != 0) {
            _checkStep(id, e.base, newBase);
            _checkStep(id, e.perUnit, newPerUnit);
            // changedAt is never ahead of the block, so `>=` means "written in this second".
            if (e.changedAt >= block.timestamp) revert PriceChangeTooSoon(id);
        }

        uint32 newVersion = oldVersion + 1;
        e.prevBase = e.base;
        e.prevPerUnit = e.perUnit;
        e.prevEnabled = e.enabled;
        e.base = newBase;
        e.perUnit = newPerUnit;
        e.enabled = newEnabled;
        e.version = newVersion;
        e.changedAt = uint48(block.timestamp);

        emit PriceSet(id, newVersion, newBase, newPerUnit, newEnabled);
    }

    /// @dev A non-zero component may move at most `MAX_PRICE_STEP` times up or down per write.
    /// A zero component is free to move.
    function _checkStep(bytes32 id, uint256 oldValue, uint256 newValue) private pure {
        if (oldValue == 0) return;
        if (newValue > oldValue * MAX_PRICE_STEP || newValue * MAX_PRICE_STEP < oldValue) {
            revert PriceStepTooLarge(id);
        }
    }

    /// @dev Contract specific rule for a price entry, applied to every write, enabled or not.
    function _validatePriceShape(bytes32 id, uint96 newBase, uint96 newPerUnit) internal pure virtual;

    /// @dev Shape of a fixed price item: no per unit component and a non-zero base.
    function _requireFixedShape(bytes32 id, uint96 newBase, uint96 newPerUnit) internal pure {
        if (newPerUnit != 0) revert PerUnitNotSupported(id);
        if (newBase == 0) revert ZeroFee(id);
    }

    /// @notice Adds or removes accounts that may pay while the contract is restricted.
    function setPreviewers(address[] calldata accounts, bool allowed) external onlyOwner {
        uint256 n = accounts.length;
        if (n == 0) revert EmptyBatch();
        if (n > MAX_BATCH) revert BatchTooLarge();
        for (uint256 i = 0; i < n; ++i) {
            address account = accounts[i];
            if (account == address(0)) revert ZeroAddress();
            isPreviewer[account] = allowed;
            emit PreviewerSet(account, allowed);
        }
    }

    /// @notice Lets everyone pay. One way: nothing can restrict the contract again.
    function openToPublic() external onlyOwner {
        if (!restricted) revert AlreadyOpen();
        restricted = false;
        emit OpenedToPublic();
    }

    /// @notice Stops every paid entry point. Guardian or owner.
    function pause() external {
        if (msg.sender != guardian && msg.sender != owner()) revert NotGuardian();
        _pause();
    }

    /// @notice Resumes paid entry points. Owner only.
    function unpause() external onlyOwner {
        _unpause();
    }

    /// @notice Replaces the guardian. Zero removes it.
    function setGuardian(address newGuardian) external onlyOwner {
        address previous = guardian;
        guardian = newGuardian;
        emit GuardianSet(previous, newGuardian);
    }

    /// @notice Disabled: the contract always has an owner.
    function renounceOwnership() public pure override {
        revert RenounceDisabled();
    }

    // ---------------------------------------------------------------------------------------------
    // Views
    // ---------------------------------------------------------------------------------------------

    /// @notice Fee for `units` now, and the previous fee while it is still accepted.
    /// @return fee Current fee.
    /// @return previousFee Previous fee if the grace window is open now, else zero.
    /// @return graceEndsAt First timestamp at which the previous fee is rejected, or zero.
    /// @return enabled Whether the item is enabled. Pause is not considered.
    function quoteFee(bytes32 id, uint256 units)
        external
        view
        returns (uint256 fee, uint256 previousFee, uint64 graceEndsAt, bool enabled)
    {
        PriceEntry storage e = _prices[id];
        fee = _fee(e.base, e.perUnit, units);
        enabled = e.enabled;
        uint256 endsAt = uint256(e.changedAt) + PRICE_GRACE;
        if (enabled && e.prevEnabled && block.timestamp < endsAt) {
            previousFee = _fee(e.prevBase, e.prevPerUnit, units);
            graceEndsAt = uint64(endsAt);
        }
    }

    /// @notice The full price entry of an item.
    function getPrice(bytes32 id) external view returns (PriceEntry memory) {
        return _prices[id];
    }

    /// @notice Gate only: whether `account` passes the restricted mode check.
    function canPay(address account) public view returns (bool) {
        return !restricted || isPreviewer[account];
    }

    function _requireNonZero(address account) private pure returns (address) {
        if (account == address(0)) revert ZeroAddress();
        return account;
    }
}
Compiler settingsShow
{
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "forge-std/=node_modules/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.