Sonic Blaze Testnet

Contract Diff Checker

Contract Name:
Metrom

Contract Source Code:

pragma solidity 0.8.28;

import {IERC20} from "oz/token/ERC20/IERC20.sol";
import {SafeERC20} from "oz/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "oz/utils/cryptography/MerkleProof.sol";
import {UUPSUpgradeable} from "oz-up/proxy/utils/UUPSUpgradeable.sol";

import {BaseCampaignsUtils} from "./libraries/BaseCampaignsUtils.sol";
import {
    RewardsCampaigns, RewardsCampaignsUtils, MAX_REWARDS_PER_CAMPAIGN
} from "./libraries/RewardsCampaignsUtils.sol";
import {PointsCampaigns, PointsCampaignsUtils} from "./libraries/PointsCampaignsUtils.sol";
import {
    IMetrom,
    RewardsCampaign,
    Reward,
    PointsCampaign,
    ReadonlyRewardsCampaign,
    ReadonlyPointsCampaign,
    CreateRewardsCampaignBundle,
    CreatePointsCampaignBundle,
    RewardAmount,
    CreatedCampaignReward,
    DistributeRewardsBundle,
    SetMinimumTokenRateBundle,
    ClaimRewardBundle,
    ClaimFeeBundle,
    UNIT
} from "./IMetrom.sol";

/// SPDX-License-Identifier: GPL-3.0-or-later
/// @title Metrom
/// @notice The contract handling all Metrom entities and interactions. It supports
/// creation and update of campaigns as well as claims and recoveries of unassigned
/// rewards for each one of them.
/// @author Federico Luzzi - <[email protected]>
contract Metrom is IMetrom, UUPSUpgradeable {
    using SafeERC20 for IERC20;
    using RewardsCampaignsUtils for RewardsCampaigns;
    using PointsCampaignsUtils for PointsCampaigns;

    /// @inheritdoc IMetrom
    bool public override ossified;

    /// @inheritdoc IMetrom
    address public override owner;

    /// @inheritdoc IMetrom
    address public override pendingOwner;

    /// @inheritdoc IMetrom
    address public override updater;

    /// @inheritdoc IMetrom
    uint32 public override fee;

    /// @inheritdoc IMetrom
    uint32 public override minimumCampaignDuration;

    /// @inheritdoc IMetrom
    uint32 public override maximumCampaignDuration;

    RewardsCampaigns internal rewardsCampaigns;

    /// @inheritdoc IMetrom
    mapping(address account => uint32 rebate) public override feeRebate;

    /// @inheritdoc IMetrom
    mapping(address token => uint256 amount) public override claimableFees;

    /// @inheritdoc IMetrom
    mapping(address token => uint256 minimumRate) public override minimumRewardTokenRate;

    /// @inheritdoc IMetrom
    mapping(address token => uint256 minimumRate) public override minimumFeeTokenRate;

    PointsCampaigns internal pointsCampaigns;

    constructor() {
        _disableInitializers();
    }

    /// @inheritdoc IMetrom
    function initialize(
        address _owner,
        address _updater,
        uint32 _fee,
        uint32 _minimumCampaignDuration,
        uint32 _maximumCampaignDuration
    ) external override initializer {
        if (_owner == address(0)) revert ZeroAddressOwner();
        if (_updater == address(0)) revert ZeroAddressUpdater();
        if (_fee >= UNIT) revert InvalidFee();
        if (_minimumCampaignDuration >= _maximumCampaignDuration) revert InvalidMinimumCampaignDuration();

        owner = _owner;
        updater = _updater;
        minimumCampaignDuration = _minimumCampaignDuration;
        maximumCampaignDuration = _maximumCampaignDuration;
        fee = _fee;

        emit Initialize(_owner, _updater, _fee, _minimumCampaignDuration, _maximumCampaignDuration);
    }

    /// @inheritdoc IMetrom
    function ossify() external {
        if (msg.sender != owner) revert Forbidden();
        ossified = true;
        emit Ossify();
    }

    function _authorizeUpgrade(address) internal view override {
        if (msg.sender != owner) revert Forbidden();
        if (ossified) revert Ossified();
    }

    /// @inheritdoc IMetrom
    function rewardsCampaignById(bytes32 _id) external view override returns (ReadonlyRewardsCampaign memory) {
        return rewardsCampaigns.getExistingReadonly(_id);
    }

    /// @inheritdoc IMetrom
    function pointsCampaignById(bytes32 _id) external view override returns (ReadonlyPointsCampaign memory) {
        return pointsCampaigns.getExistingReadonly(_id);
    }

    /// @inheritdoc IMetrom
    function campaignReward(bytes32 _id, address _token) external view override returns (uint256) {
        return rewardsCampaigns.getRewardOnExistingCampaign(_id, _token).amount;
    }

    /// @inheritdoc IMetrom
    function claimedCampaignReward(bytes32 _id, address _token, address _account)
        external
        view
        override
        returns (uint256)
    {
        return rewardsCampaigns.getRewardOnExistingCampaign(_id, _token).claimed[_account];
    }

    /// @inheritdoc IMetrom
    function createCampaigns(
        CreateRewardsCampaignBundle[] calldata _rewardsCampaignBundles,
        CreatePointsCampaignBundle[] calldata _pointsCampaignBundles
    ) external {
        uint32 _fee = fee;
        uint32 _feeRebate = feeRebate[msg.sender];
        uint32 _resolvedRewardsCampaignFee = uint32(uint64(_fee) * (UNIT - _feeRebate) / UNIT);
        uint32 _minimumCampaignDuration = minimumCampaignDuration;
        uint32 _maximumCampaignDuration = maximumCampaignDuration;

        for (uint256 _i = 0; _i < _rewardsCampaignBundles.length; _i++) {
            CreateRewardsCampaignBundle calldata _rewardsCampaignBundle = _rewardsCampaignBundles[_i];
            (bytes32 _id, CreatedCampaignReward[] memory _createdCampaignRewards) = createRewardsCampaign(
                _rewardsCampaignBundle, _minimumCampaignDuration, _maximumCampaignDuration, _resolvedRewardsCampaignFee
            );
            emit CreateRewardsCampaign(
                _id,
                msg.sender,
                _rewardsCampaignBundle.pool,
                _rewardsCampaignBundle.from,
                _rewardsCampaignBundle.to,
                _rewardsCampaignBundle.specification,
                _createdCampaignRewards
            );
        }

        for (uint256 _i = 0; _i < _pointsCampaignBundles.length; _i++) {
            CreatePointsCampaignBundle calldata _pointsCampaignBundle = _pointsCampaignBundles[_i];
            (bytes32 _id, uint256 _feeAmount) = createPointsCampaign(
                _pointsCampaignBundle, _minimumCampaignDuration, _maximumCampaignDuration, _feeRebate
            );
            emit CreatePointsCampaign(
                _id,
                msg.sender,
                _pointsCampaignBundle.pool,
                _pointsCampaignBundle.from,
                _pointsCampaignBundle.to,
                _pointsCampaignBundle.specification,
                _pointsCampaignBundle.points,
                _pointsCampaignBundle.feeToken,
                _feeAmount
            );
        }
    }

    function createRewardsCampaign(
        CreateRewardsCampaignBundle memory _bundle,
        uint32 _minimumCampaignDuration,
        uint32 _maximumCampaignDuration,
        uint32 _resolvedFee
    ) internal returns (bytes32, CreatedCampaignReward[] memory) {
        uint32 _duration = BaseCampaignsUtils.validate(
            _bundle.pool, _bundle.from, _bundle.to, _minimumCampaignDuration, _maximumCampaignDuration
        );
        if (_bundle.rewards.length == 0) revert NoRewards();
        if (_bundle.rewards.length > MAX_REWARDS_PER_CAMPAIGN) revert TooManyRewards();

        (bytes32 _id, RewardsCampaign storage campaign) = rewardsCampaigns.getNew(_bundle);
        campaign.owner = msg.sender;
        campaign.pool = _bundle.pool;
        campaign.from = _bundle.from;
        campaign.to = _bundle.to;
        campaign.specification = _bundle.specification;

        CreatedCampaignReward[] memory _createdCampaignRewards = new CreatedCampaignReward[](_bundle.rewards.length);
        for (uint256 _j = 0; _j < _bundle.rewards.length; _j++) {
            RewardAmount memory _reward = _bundle.rewards[_j];

            address _token = _reward.token;
            if (_token == address(0)) revert ZeroAddressRewardToken();

            uint256 _amount = _reward.amount;
            if (_amount == 0) revert ZeroRewardAmount();

            {
                // avoids stack too deep
                uint256 _minimumRewardTokenRate = minimumRewardTokenRate[_token];
                if (_minimumRewardTokenRate == 0) revert DisallowedRewardToken();
                if (_amount * 1 hours / _duration < _minimumRewardTokenRate) revert RewardAmountTooLow();
            }

            uint256 _balanceBefore = IERC20(_token).balanceOf(address(this));
            IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
            _amount = IERC20(_token).balanceOf(address(this)) - _balanceBefore;
            if (_amount == 0) revert ZeroRewardAmount();

            uint256 _feeAmount = _amount * _resolvedFee / UNIT;
            uint256 _rewardAmountMinusFees = _amount - _feeAmount;
            claimableFees[_token] += _feeAmount;

            _createdCampaignRewards[_j] =
                CreatedCampaignReward({token: _token, amount: _rewardAmountMinusFees, fee: _feeAmount});

            Reward storage reward = campaign.reward[_token];
            reward.amount += _rewardAmountMinusFees;
        }

        return (_id, _createdCampaignRewards);
    }

    function createPointsCampaign(
        CreatePointsCampaignBundle memory _bundle,
        uint32 _minimumCampaignDuration,
        uint32 _maximumCampaignDuration,
        uint32 _feeRebate
    ) internal returns (bytes32, uint256) {
        uint32 _duration = BaseCampaignsUtils.validate(
            _bundle.pool, _bundle.from, _bundle.to, _minimumCampaignDuration, _maximumCampaignDuration
        );
        if (_bundle.points == 0) revert NoPoints();

        uint256 _minimumFeeTokenRate = minimumFeeTokenRate[_bundle.feeToken];
        if (_minimumFeeTokenRate == 0) revert DisallowedFeeToken();
        uint256 _fullRequiredFeeAmount = _minimumFeeTokenRate * _duration / 1 hours;
        uint256 _requiredFeeAmount = _fullRequiredFeeAmount * (UNIT - _feeRebate) / UNIT;

        (bytes32 _id, PointsCampaign storage campaign) = pointsCampaigns.getNew(_bundle);
        campaign.owner = msg.sender;
        campaign.pool = _bundle.pool;
        campaign.from = _bundle.from;
        campaign.to = _bundle.to;
        campaign.specification = _bundle.specification;
        campaign.points = _bundle.points;

        uint256 _feeAmount = collectPointsCampaignFee(_bundle.feeToken, _requiredFeeAmount);

        return (_id, _feeAmount);
    }

    function collectPointsCampaignFee(address _feeToken, uint256 _requiredFeeAmount) internal returns (uint256) {
        uint256 _balanceBefore = IERC20(_feeToken).balanceOf(address(this));
        IERC20(_feeToken).safeTransferFrom(msg.sender, address(this), _requiredFeeAmount);
        uint256 _collectedFeeAmount = IERC20(_feeToken).balanceOf(address(this)) - _balanceBefore;
        if (_collectedFeeAmount < _requiredFeeAmount) revert FeeAmountTooLow();
        claimableFees[_feeToken] += _collectedFeeAmount;
        return _collectedFeeAmount;
    }

    /// @inheritdoc IMetrom
    function distributeRewards(DistributeRewardsBundle[] calldata _bundles) external override {
        if (msg.sender != updater) revert Forbidden();

        for (uint256 _i; _i < _bundles.length; _i++) {
            DistributeRewardsBundle calldata _bundle = _bundles[_i];
            if (_bundle.root == bytes32(0)) revert ZeroRoot();
            if (_bundle.data == bytes32(0)) revert ZeroData();

            RewardsCampaign storage campaign = rewardsCampaigns.getExisting(_bundle.campaignId);
            campaign.root = _bundle.root;
            campaign.data = _bundle.data;
            emit DistributeReward(_bundle.campaignId, _bundle.root, _bundle.data);
        }
    }

    /// @inheritdoc IMetrom
    function setMinimumTokenRates(
        SetMinimumTokenRateBundle[] calldata _rewardTokenBundles,
        SetMinimumTokenRateBundle[] calldata _feeTokenBundles
    ) external override {
        if (msg.sender != updater) revert Forbidden();

        for (uint256 _i; _i < _rewardTokenBundles.length; _i++) {
            SetMinimumTokenRateBundle calldata _bundle = _rewardTokenBundles[_i];
            if (_bundle.token == address(0)) revert ZeroAddressRewardToken();

            minimumRewardTokenRate[_bundle.token] = _bundle.minimumRate;
            emit SetMinimumRewardTokenRate(_bundle.token, _bundle.minimumRate);
        }

        for (uint256 _i; _i < _feeTokenBundles.length; _i++) {
            SetMinimumTokenRateBundle calldata _bundle = _feeTokenBundles[_i];
            if (_bundle.token == address(0)) revert ZeroAddressFeeToken();

            minimumFeeTokenRate[_bundle.token] = _bundle.minimumRate;
            emit SetMinimumFeeTokenRate(_bundle.token, _bundle.minimumRate);
        }
    }

    function _processRewardClaim(
        RewardsCampaign storage campaign,
        ClaimRewardBundle calldata _bundle,
        address _claimOwner
    ) internal returns (uint256) {
        if (_bundle.receiver == address(0)) revert ZeroAddressReceiver();
        if (_bundle.token == address(0)) revert ZeroAddressRewardToken();
        if (_bundle.amount == 0) revert ZeroAmount();

        bytes32 _leaf = keccak256(bytes.concat(keccak256(abi.encode(_claimOwner, _bundle.token, _bundle.amount))));
        if (!MerkleProof.verifyCalldata(_bundle.proof, campaign.root, _leaf)) revert InvalidProof();

        Reward storage reward = campaign.reward[_bundle.token];
        uint256 _claimAmount = _bundle.amount - reward.claimed[_claimOwner];
        if (_claimAmount == 0) revert ZeroAmount();
        if (_claimAmount > reward.amount) revert TooMuchClaimedAmount();

        reward.claimed[_claimOwner] += _claimAmount;
        reward.amount -= _claimAmount;

        IERC20(_bundle.token).safeTransfer(_bundle.receiver, _claimAmount);

        return _claimAmount;
    }

    /// @inheritdoc IMetrom
    function claimRewards(ClaimRewardBundle[] calldata _bundles) external override {
        for (uint256 _i; _i < _bundles.length; _i++) {
            ClaimRewardBundle calldata _bundle = _bundles[_i];
            uint256 _claimedAmount =
                _processRewardClaim(rewardsCampaigns.getExisting(_bundle.campaignId), _bundle, msg.sender);
            emit ClaimReward(_bundle.campaignId, _bundle.token, _claimedAmount, _bundle.receiver);
        }
    }

    /// @inheritdoc IMetrom
    function recoverRewards(ClaimRewardBundle[] calldata _bundles) external override {
        for (uint256 _i; _i < _bundles.length; _i++) {
            ClaimRewardBundle calldata _bundle = _bundles[_i];

            RewardsCampaign storage campaign = rewardsCampaigns.getExisting(_bundle.campaignId);
            if (msg.sender != campaign.owner) revert Forbidden();

            uint256 _claimedAmount = _processRewardClaim(campaign, _bundle, address(0));
            emit RecoverReward(_bundle.campaignId, _bundle.token, _claimedAmount, _bundle.receiver);
        }
    }

    /// @inheritdoc IMetrom
    function claimFees(ClaimFeeBundle[] calldata _bundles) external {
        if (msg.sender != owner) revert Forbidden();

        for (uint256 _i = 0; _i < _bundles.length; _i++) {
            ClaimFeeBundle calldata _bundle = _bundles[_i];

            if (_bundle.token == address(0)) revert ZeroAddressRewardToken();
            if (_bundle.receiver == address(0)) revert ZeroAddressReceiver();

            uint256 _claimAmount = claimableFees[_bundle.token];
            if (_claimAmount == 0) revert ZeroAmount();

            delete claimableFees[_bundle.token];
            IERC20(_bundle.token).safeTransfer(_bundle.receiver, _claimAmount);
            emit ClaimFee(_bundle.token, _claimAmount, _bundle.receiver);
        }
    }

    /// @inheritdoc IMetrom
    function campaignOwner(bytes32 _id) external view override returns (address) {
        address _owner = rewardsCampaigns.get(_id).owner;
        return _owner == address(0) ? pointsCampaigns.get(_id).owner : _owner;
    }

    /// @inheritdoc IMetrom
    function campaignPendingOwner(bytes32 _id) external view override returns (address) {
        address _pendingOwner = rewardsCampaigns.get(_id).pendingOwner;
        return _pendingOwner == address(0) ? pointsCampaigns.get(_id).pendingOwner : _pendingOwner;
    }

    /// @inheritdoc IMetrom
    function transferCampaignOwnership(bytes32 _id, address _owner) external override {
        if (_owner == address(0)) revert ZeroAddressOwner();

        RewardsCampaign storage rewardsCampaign = rewardsCampaigns.get(_id);
        if (rewardsCampaign.owner != address(0)) {
            if (msg.sender != rewardsCampaign.owner) revert Forbidden();
            rewardsCampaign.pendingOwner = _owner;
            emit TransferCampaignOwnership(_id, _owner);
            return;
        }

        PointsCampaign storage pointsCampaign = pointsCampaigns.get(_id);
        if (pointsCampaign.owner != address(0)) {
            if (msg.sender != pointsCampaign.owner) revert Forbidden();
            pointsCampaign.pendingOwner = _owner;
            emit TransferCampaignOwnership(_id, _owner);
            return;
        }

        revert NonExistentCampaign();
    }

    /// @inheritdoc IMetrom
    function acceptCampaignOwnership(bytes32 _id) external override {
        RewardsCampaign storage rewardsCampaign = rewardsCampaigns.get(_id);
        if (rewardsCampaign.owner != address(0)) {
            if (msg.sender != rewardsCampaign.pendingOwner) revert Forbidden();
            delete rewardsCampaign.pendingOwner;
            rewardsCampaign.owner = msg.sender;
            emit AcceptCampaignOwnership(_id, msg.sender);
            return;
        }

        PointsCampaign storage pointsCampaign = pointsCampaigns.get(_id);
        if (pointsCampaign.owner != address(0)) {
            if (msg.sender != pointsCampaign.pendingOwner) revert Forbidden();
            delete pointsCampaign.pendingOwner;
            pointsCampaign.owner = msg.sender;
            emit AcceptCampaignOwnership(_id, msg.sender);
            return;
        }

        revert NonExistentCampaign();
    }

    /// @inheritdoc IMetrom
    function transferOwnership(address _owner) external override {
        if (_owner == address(0)) revert ZeroAddressOwner();
        if (msg.sender != owner) revert Forbidden();
        pendingOwner = _owner;
        emit TransferOwnership(_owner);
    }

    /// @inheritdoc IMetrom
    function acceptOwnership() external override {
        if (msg.sender != pendingOwner) revert Forbidden();
        delete pendingOwner;
        owner = msg.sender;
        emit AcceptOwnership(msg.sender);
    }

    /// @inheritdoc IMetrom
    function setUpdater(address _updater) external override {
        if (msg.sender != owner) revert Forbidden();
        if (_updater == address(0)) revert ZeroAddressUpdater();
        updater = _updater;
        emit SetUpdater(_updater);
    }

    /// @inheritdoc IMetrom
    function setFee(uint32 _fee) external override {
        if (_fee >= UNIT) revert InvalidFee();
        if (msg.sender != owner) revert Forbidden();
        fee = _fee;
        emit SetFee(_fee);
    }

    /// @inheritdoc IMetrom
    function setFeeRebate(address _account, uint32 _rebate) external override {
        if (_account == address(0)) revert ZeroAddressAccount();
        if (_rebate > UNIT) revert RebateTooHigh();
        if (msg.sender != owner) revert Forbidden();
        feeRebate[_account] = _rebate;
        emit SetFeeRebate(_account, _rebate);
    }

    /// @inheritdoc IMetrom
    function setMinimumCampaignDuration(uint32 _minimumCampaignDuration) external override {
        if (_minimumCampaignDuration >= maximumCampaignDuration) revert InvalidMinimumCampaignDuration();
        if (msg.sender != owner) revert Forbidden();
        minimumCampaignDuration = _minimumCampaignDuration;
        emit SetMinimumCampaignDuration(_minimumCampaignDuration);
    }

    /// @inheritdoc IMetrom
    function setMaximumCampaignDuration(uint32 _maximumCampaignDuration) external override {
        if (_maximumCampaignDuration <= minimumCampaignDuration) revert InvalidMaximumCampaignDuration();
        if (msg.sender != owner) revert Forbidden();
        maximumCampaignDuration = _maximumCampaignDuration;
        emit SetMaximumCampaignDuration(_maximumCampaignDuration);
    }
}

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

pragma solidity ^0.8.20;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

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

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.

pragma solidity ^0.8.20;

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

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     *@dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

pragma solidity 0.8.28;

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

/// SPDX-License-Identifier: GPL-3.0-or-later
/// @title BasesCampaignsUtils
/// @notice Utility functions to be applied to all campaign types.
/// @author Federico Luzzi - <[email protected]>
library BaseCampaignsUtils {
    /// @notice Validates the base parameters used to create a Metrom campaign.
    /// @param _pool The targeted pool for the campaign.
    /// @param _from The starting timestamp for the campaign.
    /// @param _to The ending timestamp for the campaign.
    /// @param _minimumCampaignDuration The minimum allowed campaign duration.
    /// @param _maximumCampaignDuration The maximum allowed campaign duration.
    /// @return The overall campaign duration.
    function validate(
        address _pool,
        uint32 _from,
        uint32 _to,
        uint32 _minimumCampaignDuration,
        uint32 _maximumCampaignDuration
    ) internal view returns (uint32) {
        if (_pool == address(0)) revert IMetrom.ZeroAddressPool();
        if (_from <= block.timestamp) revert IMetrom.StartTimeInThePast();
        if (_to < _from + _minimumCampaignDuration) revert IMetrom.DurationTooShort();
        uint32 _duration = _to - _from;
        if (_duration > _maximumCampaignDuration) revert IMetrom.DurationTooLong();

        return _duration;
    }
}

pragma solidity 0.8.28;

import {BaseCampaignsUtils} from "./BaseCampaignsUtils.sol";
import {
    IMetrom,
    RewardsCampaign,
    CreateRewardsCampaignBundle,
    ReadonlyRewardsCampaign,
    CreateRewardsCampaignBundle,
    Reward
} from "../IMetrom.sol";

/// @dev Represents the maximum number of different rewards allowed for a
/// single campaign.
uint256 constant MAX_REWARDS_PER_CAMPAIGN = 5;

/// @notice Holds the created rewards based campaigns.
struct RewardsCampaigns {
    mapping(bytes32 id => RewardsCampaign) campaigns;
}

/// SPDX-License-Identifier: GPL-3.0-or-later
/// @title RewardsCampaignsUtils
/// @notice Utility functions to be applied to rewards based campaigns.
/// @author Federico Luzzi - <[email protected]>
library RewardsCampaignsUtils {
    /// @notice Given a creation bundle, returns the id of the campaign that would
    /// be created with the bundle if no errors were to be thrown.
    /// @param _bundle The rewards based campaign creation bundle.
    /// @return The generated campaign id.
    function generateId(CreateRewardsCampaignBundle memory _bundle) internal view returns (bytes32) {
        return keccak256(
            abi.encode(msg.sender, _bundle.pool, _bundle.from, _bundle.to, _bundle.specification, _bundle.rewards)
        );
    }

    /// @notice Given a campaign id returns a storage pointer to that campaign in the registry.
    /// This function does not check if the referenced pointer has previously been populated or
    /// not.
    /// @param _self The rewards based campaigns registry.
    /// @param _id The id of the targeted campaign.
    /// @return A storage pointer to the campaign with the given id.
    function get(RewardsCampaigns storage _self, bytes32 _id) internal view returns (RewardsCampaign storage) {
        return _self.campaigns[_id];
    }

    /// @notice Given a campaign creation bundle returns a storage pointer to that campaign in
    /// the registry. This function reverts if the derived campaign pointer has prepopulated data.
    /// @param _self The rewards based campaigns registry.
    /// @param _bundle The creation bundle.
    /// @return The new campaign id.
    /// @return A storage pointer to the campaign with the given id.
    function getNew(RewardsCampaigns storage _self, CreateRewardsCampaignBundle memory _bundle)
        internal
        view
        returns (bytes32, RewardsCampaign storage)
    {
        bytes32 _id = generateId(_bundle);
        RewardsCampaign storage campaign = _self.campaigns[_id];
        if (campaign.owner != address(0)) revert IMetrom.AlreadyExists();
        return (_id, campaign);
    }

    /// @notice Given a campaign id returns a storage pointer to that campaign in the registry.
    /// This function reverts if the given campaign pointer does not have any prepopulated data.
    /// @param _self The rewards based campaigns registry.
    /// @param _id The id of the targeted campaign.
    /// @return A storage pointer to the campaign with the given id.
    function getExisting(RewardsCampaigns storage _self, bytes32 _id) internal view returns (RewardsCampaign storage) {
        RewardsCampaign storage campaign = _self.campaigns[_id];
        if (campaign.owner == address(0)) revert IMetrom.NonExistentCampaign();
        return campaign;
    }

    /// @notice Given a campaign id and a token address returns a storage pointer to the reward
    /// linked to the campaign with the given id and with the given token address. This function
    /// reverts if no campaign with the given id has been created.
    /// @param _self The rewards based campaigns registry.
    /// @param _id The id of the targeted campaign.
    /// @param _token The token address of the targeted reward.
    /// @return A storage pointer to the reward with the given token address for the campaign with
    /// the given id.
    function getRewardOnExistingCampaign(RewardsCampaigns storage _self, bytes32 _id, address _token)
        internal
        view
        returns (Reward storage)
    {
        return getExisting(_self, _id).reward[_token];
    }

    /// @notice Given a campaign id returns a readonly version of it. This function reverts
    /// if the given campaign pointer does not have any prepopulated data.
    /// @param _self The rewards based campaigns registry.
    /// @param _id The id of the targeted campaign.
    /// @return A readonly version of the campaign with the given id.
    function getExistingReadonly(RewardsCampaigns storage _self, bytes32 _id)
        internal
        view
        returns (ReadonlyRewardsCampaign memory)
    {
        RewardsCampaign storage campaign = getExisting(_self, _id);
        return ReadonlyRewardsCampaign({
            owner: campaign.owner,
            pendingOwner: campaign.pendingOwner,
            pool: campaign.pool,
            from: campaign.from,
            to: campaign.to,
            specification: campaign.specification,
            root: campaign.root,
            data: campaign.data
        });
    }
}

pragma solidity 0.8.28;

import {
    IMetrom,
    PointsCampaign,
    CreatePointsCampaignBundle,
    ReadonlyPointsCampaign,
    CreatePointsCampaignBundle
} from "../IMetrom.sol";

/// @notice Holds the created points based campaigns.
struct PointsCampaigns {
    mapping(bytes32 id => PointsCampaign) campaigns;
}

/// SPDX-License-Identifier: GPL-3.0-or-later
/// @title PointsCampaignsUtils
/// @notice Utility functions to be applied to points based campaigns.
/// @author Federico Luzzi - <[email protected]>
library PointsCampaignsUtils {
    /// @notice Given a creation bundle, returns the id of the campaign that would
    /// be created with the bundle if no errors were to be thrown.
    /// @param _bundle The points based campaign creation bundle.
    /// @return The generated campaign id.
    function generateId(CreatePointsCampaignBundle memory _bundle) internal view returns (bytes32) {
        return keccak256(
            abi.encode(msg.sender, _bundle.pool, _bundle.from, _bundle.to, _bundle.specification, _bundle.points)
        );
    }

    /// @notice Given a campaign id returns a storage pointer to that campaign in the registry.
    /// This function does not check if the referenced pointer has previously been populated or
    /// not.
    /// @param _self The points based campaigns registry.
    /// @param _id The id of the targeted campaign.
    /// @return A storage pointer to the campaign with the given id.
    function get(PointsCampaigns storage _self, bytes32 _id) internal view returns (PointsCampaign storage) {
        return _self.campaigns[_id];
    }

    /// @notice Given a campaign creation bundle returns a storage pointer to that campaign in
    /// the registry. This function reverts if the derived campaign pointer has prepopulated data.
    /// @param _self The points based campaigns registry.
    /// @param _bundle The creation bundle.
    /// @return The new campaign id.
    /// @return A storage pointer to the campaign with the given id.
    function getNew(PointsCampaigns storage _self, CreatePointsCampaignBundle memory _bundle)
        internal
        view
        returns (bytes32, PointsCampaign storage)
    {
        bytes32 _id = generateId(_bundle);
        PointsCampaign storage campaign = _self.campaigns[_id];
        if (campaign.owner != address(0)) revert IMetrom.AlreadyExists();
        return (_id, campaign);
    }

    /// @notice Given a campaign id returns a storage pointer to that campaign in the registry.
    /// This function reverts if the given campaign pointer does not have any prepopulated data.
    /// @param _self The points based campaigns registry.
    /// @param _id The id of the targeted campaign.
    /// @return A storage pointer to the campaign with the given id.
    function getExisting(PointsCampaigns storage _self, bytes32 _id) internal view returns (PointsCampaign storage) {
        PointsCampaign storage campaign = _self.campaigns[_id];
        if (campaign.owner == address(0)) revert IMetrom.NonExistentCampaign();
        return campaign;
    }

    /// @notice Given a campaign id returns a readonly version of it. This function reverts
    /// if the given campaign pointer does not have any prepopulated data.
    /// @param _self The points based campaigns registry.
    /// @param _id The id of the targeted campaign.
    /// @return A readonly version of the campaign with the given id.
    function getExistingReadonly(PointsCampaigns storage _self, bytes32 _id)
        internal
        view
        returns (ReadonlyPointsCampaign memory)
    {
        PointsCampaign storage campaign = getExisting(_self, _id);
        return ReadonlyPointsCampaign({
            owner: campaign.owner,
            pendingOwner: campaign.pendingOwner,
            pool: campaign.pool,
            from: campaign.from,
            to: campaign.to,
            specification: campaign.specification,
            points: campaign.points
        });
    }
}

pragma solidity >=0.8.0;

/// @dev Represents the maximum value for fee percentages (100%).
uint32 constant UNIT = 1_000_000;

/// @notice Represents a reward in the contract's state.
/// It keeps track of the remaining amount after fees
/// as well as a mapping of claimed amounts for each user.
struct Reward {
    uint256 amount;
    mapping(address user => uint256 amount) claimed;
}

/// @notice Represents a rewards based campaign in the contract's state, with its owner,
/// target pool, running period, specification, root and data links, as well as rewards
/// information. A particular note must be made for the `specification` and `data` fields.
/// These can optionally contain a SHA256 hash of some JSON content stored on IPFS such that
/// a CID can be constructed from them. `specification` can point to an IPFS JSON file with
/// additional information/parameters on the campaign, while the `data` field must point
/// to a JSON file containing the raw leaves from which the current campaign's Merkle
/// tree and root was calculated.
struct RewardsCampaign {
    address owner;
    address pendingOwner;
    address pool;
    uint32 from;
    uint32 to;
    bytes32 specification;
    bytes32 root;
    bytes32 data;
    mapping(address token => Reward) reward;
}

/// @notice Represents a points based campaign in the contract's state, with its owner,
/// target pool, running period, specification, root and data links, as well as rewards
/// information. A particular note must be made for the `specification` field.
/// This can optionally contain a SHA256 hash of some JSON content stored on IPFS such
/// that a CID can be constructed from it. `specification` can point to an IPFS JSON
/// file with additional information/parameters on the campaign.
struct PointsCampaign {
    address owner;
    address pendingOwner;
    address pool;
    uint32 from;
    uint32 to;
    bytes32 specification;
    uint256 points;
}

/// @notice Represents a readonly rewards based campaign.
struct ReadonlyRewardsCampaign {
    address owner;
    address pendingOwner;
    address pool;
    uint32 from;
    uint32 to;
    bytes32 specification;
    bytes32 root;
    bytes32 data;
}

/// @notice Represents a readonly points based campaign
struct ReadonlyPointsCampaign {
    address owner;
    address pendingOwner;
    address pool;
    uint32 from;
    uint32 to;
    bytes32 specification;
    uint256 points;
}

struct RewardAmount {
    address token;
    uint256 amount;
}

struct CreatedCampaignReward {
    address token;
    uint256 amount;
    uint256 fee;
}

/// @notice Contains data that can be used by anyone to create a rewards based campaign.
struct CreateRewardsCampaignBundle {
    address pool;
    uint32 from;
    uint32 to;
    bytes32 specification;
    RewardAmount[] rewards;
}

/// @notice Contains data that can be used by anyone to create a points based campaign.
struct CreatePointsCampaignBundle {
    address pool;
    uint32 from;
    uint32 to;
    bytes32 specification;
    uint256 points;
    address feeToken;
}

/// @notice Contains data that can be used by the current `updater` to
/// distribute rewards on a campaign by specifying a Merkle root and a data link.
struct DistributeRewardsBundle {
    bytes32 campaignId;
    bytes32 root;
    bytes32 data;
}

/// @notice Contains data that can be used by the current `updater` or the
/// `owner` to update the minimum required rate to be emitted in a campaign for
/// a certain reward token or the minimum fee token rate.
struct SetMinimumTokenRateBundle {
    address token;
    uint256 minimumRate;
}

/// @notice Contains data that can be used by eligible LPs to claim rewards assigned to them
/// on a campaign by specifying data necessary to build a valid Merkle leaf and an inclusion
/// proof.
struct ClaimRewardBundle {
    bytes32 campaignId;
    bytes32[] proof;
    address token;
    uint256 amount;
    address receiver;
}

/// @notice Contains data that can be used by the contract's owner to claim accrued fees.
struct ClaimFeeBundle {
    address token;
    address receiver;
}

/// SPDX-License-Identifier: GPL-3.0-or-later
/// @title Metrom
/// @notice The interface for the contract handling all Metrom entities and interactions.
/// It supports creation and update of campaigns as well as claims and recoveries of unassigned
/// rewards for each one of them.
/// @author Federico Luzzi - <[email protected]>
interface IMetrom {
    /// @notice Emitted at initialization time.
    /// @param owner The initial contract's owner.
    /// @param updater The initial contract's updater.
    /// @param fee The initial contract's rewards campaign fee.
    /// @param minimumCampaignDuration The initial contract's minimum campaign duration.
    /// @param maximumCampaignDuration The initial contract's maximum campaign duration.
    event Initialize(
        address indexed owner,
        address updater,
        uint32 fee,
        uint32 minimumCampaignDuration,
        uint32 maximumCampaignDuration
    );

    /// @notice Emitted when the contract is ossified.
    event Ossify();

    /// @notice Emitted when a rewards based campaign is created.
    /// @param id The id of the campaign.
    /// @param owner The initial owner of the campaign.
    /// @param pool The targeted pool address of the campaign.
    /// @param from From when the campaign will run.
    /// @param to To when the campaign will run.
    /// @param specification The campaign's specification data hash.
    /// @param rewards A list of the reward tokens deposited in the campaign. Each list
    /// item contains the used reward token address along with the after-fee amount and
    /// the fee amount paid.
    event CreateRewardsCampaign(
        bytes32 indexed id,
        address indexed owner,
        address pool,
        uint32 from,
        uint32 to,
        bytes32 specification,
        CreatedCampaignReward[] rewards
    );

    /// @notice Emitted when a points based campaign is created.
    /// @param id The id of the campaign.
    /// @param owner The initial owner of the campaign.
    /// @param pool The targeted pool address of the campaign.
    /// @param from From when the campaign will run.
    /// @param to To when the campaign will run.
    /// @param specification The campaign's specification data hash.
    /// @param points The amount of points to distribute (scaled to account for 18 decimals).
    /// @param feeToken The token used to pay the creation fee.
    /// @param fee The creation fee amount.
    event CreatePointsCampaign(
        bytes32 indexed id,
        address indexed owner,
        address pool,
        uint32 from,
        uint32 to,
        bytes32 specification,
        uint256 points,
        address feeToken,
        uint256 fee
    );

    /// @notice Emitted when the campaigns updater distributes rewards on a campaign.
    /// @param campaignId The id of the campaign. on which the rewards were distributed.
    /// @param root The updated Merkle root for the campaign.
    /// @param data The updated data content hash for the campaign. This can be used to
    /// contruct an IPFS CID for a file that will contain the raw data used to get the raw
    /// data used to contruct the campaign's Merkle tree and verify the Merkle root.
    event DistributeReward(bytes32 indexed campaignId, bytes32 root, bytes32 data);

    /// @notice Emitted when the rates updater or the owner updates the minimum emission
    /// rate of a certain whitelisted reward token required in order to create a rewards based
    /// campaign.
    /// @param token The address of the whitelisted reward token to update.
    /// @param minimumRate The new minimum rate required in order to create a
    /// campaign.
    event SetMinimumRewardTokenRate(address indexed token, uint256 minimumRate);

    /// @notice Emitted when the rates updater or the owner updates the minimum rate for a
    /// certain whitelisted fee token required in order to create a points based campaign.
    /// @param token The address of the whitelisted fee token to update.
    /// @param minimumRate The new minimum rate required in order to create a
    /// campaign.
    event SetMinimumFeeTokenRate(address indexed token, uint256 minimumRate);

    /// @notice Emitted when an eligible LP claims a reward.
    /// @param campaignId The id of the campaign on which the claim is performed.
    /// @param token The claimed token.
    /// @param amount The claimed amount.
    /// @param receiver The claim's receiver.
    event ClaimReward(bytes32 indexed campaignId, address token, uint256 amount, address indexed receiver);

    /// @notice Emitted when the campaign's owner recovers unassigned rewards.
    /// @param campaignId The id of the campaign on which the recovery was performed.
    /// @param token The recovered token.
    /// @param amount The recovered amount.
    /// @param receiver The recovery's receiver.
    event RecoverReward(bytes32 indexed campaignId, address token, uint256 amount, address indexed receiver);

    /// @notice Emitted when Metrom's contract owner claims accrued fees.
    /// @param token The claimed token.
    /// @param amount The claimed amount.
    /// @param receiver The claims's receiver.
    event ClaimFee(address token, uint256 amount, address indexed receiver);

    /// @notice Emitted when a campaign's ownership transfer is initiated.
    /// @param id The targete campaign's id.
    /// @param owner The new desired owner.
    event TransferCampaignOwnership(bytes32 indexed id, address indexed owner);

    /// @notice Emitted when a campaign's current pending owner accepts its ownership.
    /// @param id The targete campaign's id.
    /// @param owner The targete campaign's new owner.
    event AcceptCampaignOwnership(bytes32 indexed id, address indexed owner);

    /// @notice Emitted when Metrom's ownership transfer is initiated.
    /// @param owner The new desired owner.
    event TransferOwnership(address indexed owner);

    /// @notice Emitted when Metrom's current pending owner accepts its ownership.
    /// @param owner The new owner.
    event AcceptOwnership(address indexed owner);

    /// @notice Emitted when Metrom's owner sets a new allowed updater address.
    /// @param updater The new updater.
    event SetUpdater(address indexed updater);

    /// @notice Emitted when Metrom's owner sets a new rewards based campaign fee.
    /// @param fee The new rewards campaign fee.
    event SetFee(uint32 fee);

    /// @notice Emitted when Metrom's owner sets a new address-specific
    /// rebate for the protocol rewards based campaign fees.
    /// @param account The account for which the rebate was set.
    /// @param rebate The rebate.
    event SetFeeRebate(address account, uint32 rebate);

    /// @notice Emitted when Metrom's owner sets a new minimum campaign duration.
    /// @param minimumCampaignDuration The new minimum campaign duration.
    event SetMinimumCampaignDuration(uint32 minimumCampaignDuration);

    /// @notice Emitted when Metrom's owner sets a new maximum campaign duration.
    /// @param maximumCampaignDuration The new maximum campaign duration.
    event SetMaximumCampaignDuration(uint32 maximumCampaignDuration);

    /// @notice Thrown when trying to create a campaign that already exists.
    error AlreadyExists();

    /// @notice Thrown when trying to create a campaign with a non-whitelisted reward token.
    error DisallowedRewardToken();

    /// @notice Thrown when trying to create a campaign with a duration that is too long.
    error DurationTooLong();

    /// @notice Thrown when trying to create a campaign with a duration that is too short.
    error DurationTooShort();

    /// @notice Thrown when the desired operation's execution is forbidden to the caller.
    error Forbidden();

    /// @notice Thrown when the specified fee goes over the maximum allowed amount.
    error InvalidFee();

    /// @notice Thrown when the specified maximum campaign duration is less or equal to
    /// the current minimum campaign duration.
    error InvalidMaximumCampaignDuration();

    /// @notice Thrown when the specified minimum campaign duration is greater than or
    /// equal to the current maximum campaign duration.
    error InvalidMinimumCampaignDuration();

    /// @notice Thrown at claim procession time when the provided Merkle proof is invalid.
    error InvalidProof();

    /// @notice Thrown when creating a points based campaign if a zero points amount was specified.
    error NoPoints();

    /// @notice Thrown when creating a campaign if no rewards were specified.
    error NoRewards();

    /// @notice Thrown when a campaign that was required to exists does not exist.
    error NonExistentCampaign();

    /// @notice Thrown when a campaign reward that was required to exists does not exist.
    error NonExistentReward();

    /// @notice Thrown when trying to upgrade the contract while ossified.
    error Ossified();

    /// @notice Thrown when trying to set a fee rebate that is too high.
    error RebateTooHigh();

    /// @notice Thrown when trying to create a campaign when the specified reward amount is too low.
    error RewardAmountTooLow();

    /// @notice Thrown when trying to create a campaign with a from timestamp in the past.
    error StartTimeInThePast();

    /// @notice Thrown when trying to create a campaign when too many rewards are specified.
    error TooManyRewards();

    /// @notice Thrown when trying to claim a reward that is too much to be claimed.
    error TooMuchClaimedAmount();

    /// @notice Thrown when trying to set the updater to the zero address.
    error ZeroAddressUpdater();

    /// @notice Thrown when trying to set the fee rebate for a zero address account.
    error ZeroAddressAccount();

    /// @notice Thrown when trying to transfer Metrom's or a campaign's ownership to the zero address.
    error ZeroAddressOwner();

    /// @notice Thrown when trying to create a campaign with a zero address pool.
    error ZeroAddressPool();

    /// @notice Thrown when processing a claim with a zero address receiver or when claiming
    /// fees for a zero address receiver.
    error ZeroAddressReceiver();

    /// @notice Thrown when trying to create a points based campaign with a zero address fee token.
    error ZeroAddressFeeToken();

    /// @notice Thrown when trying to create a points based campaign with a disallowed fee token.
    error DisallowedFeeToken();

    /// @notice Thrown when trying to create a points based campaign with a non adequate fee.
    error FeeAmountTooLow();

    /// @notice Thrown when trying to create a campaign with a zero address reward token or
    /// when trying to set the minimum reward token rate for a zero address reward token.
    error ZeroAddressRewardToken();

    /// @notice Thrown at claim processing time when the requested claim amount is 0.
    error ZeroAmount();

    /// @notice Thrown at rewards distribution time when 0-bytes data is specified.
    error ZeroData();

    /// @notice Thrown when trying to create a campaign with a zero reward amount.
    error ZeroRewardAmount();

    /// @notice Thrown at rewards distribution time when the specified root is 0-bytes.
    error ZeroRoot();

    /// @notice Initializes the contract.
    /// @param owner The initial owner.
    /// @param updater The initial updater.
    /// @param fee The initial fee.
    /// @param minimumCampaignDuration The initial minimum campaign duration.
    /// @param maximumCampaignDuration The initial maximum campaign duration.
    function initialize(
        address owner,
        address updater,
        uint32 fee,
        uint32 minimumCampaignDuration,
        uint32 maximumCampaignDuration
    ) external;

    /// @notice Returns whether the contract is upgradeable or not.
    /// @return ossified The upgradeability state of the contract.
    function ossified() external returns (bool ossified);

    /// @notice Makes the contract immutable, de-facto disallowing
    /// any future upgrade. Can only be called by Metrom's owner.
    function ossify() external;

    /// @notice Returns the current owner.
    /// @return owner The current owner.
    function owner() external view returns (address owner);

    /// @notice Returns the current pending owner.
    /// @return pendingOwner The current pending owner.
    function pendingOwner() external view returns (address pendingOwner);

    /// @notice Returns the currently allowed updater.
    /// @return updater The currently allowed updater.
    function updater() external view returns (address updater);

    /// @notice Returns the current fee.
    /// @return fee The current fee.
    function fee() external view returns (uint32 fee);

    /// @notice Returns the current fee rebate for a provided account.
    /// @param account The account for which to fetch the fee rebate.
    /// @return rebate The fee rebate for the provided account.
    function feeRebate(address account) external view returns (uint32 rebate);

    /// @notice Returns the currently enforced minimum campaign duration.
    /// @return minimumCampaignDuration The currently enforced minimum campaign duration.
    function minimumCampaignDuration() external view returns (uint32 minimumCampaignDuration);

    /// @notice Returns the currently enforced minimum campaign duration.
    /// @return maximumCampaignDuration The currently enforced minimum campaign duration.
    function maximumCampaignDuration() external view returns (uint32 maximumCampaignDuration);

    /// @notice Returns the currently claimable fees amount for a specified token.
    /// @param token The token for which to fetch the currently claimable amount.
    /// @return claimable The amount of the specified token that is currently claimable.
    function claimableFees(address token) external returns (uint256 claimable);

    /// @notice Returns the minimum emission rate required in order to create a
    /// campaign with the passed token. Returns 0 if the token is not whitelisted and it
    /// cannot be used to create a campaign.
    /// @param token The reward token's address.
    /// @return minimumRate The reward token's minimum required emission rate.
    function minimumRewardTokenRate(address token) external view returns (uint256 minimumRate);

    /// @notice Returns the minimum fee token rate required in order to create a
    /// points-based campaign with the given token. Returns 0 if the token is not
    /// whitelisted and it cannot be used to create a campaign.
    /// @param token The fee token's address.
    /// @return minimumRate The reward token's minimum required rate.
    function minimumFeeTokenRate(address token) external view returns (uint256 minimumRate);

    /// @notice Returns a points based campaign in readonly format.
    /// @param id The wanted campaign id.
    /// @return campaign The points based campaign in readonly format.
    function pointsCampaignById(bytes32 id) external view returns (ReadonlyPointsCampaign memory campaign);

    /// @notice Returns a rewards based campaign in readonly format.
    /// @param id The wanted campaign id.
    /// @return campaign The rewards based campaign in readonly format.
    function rewardsCampaignById(bytes32 id) external view returns (ReadonlyRewardsCampaign memory campaign);

    /// @notice Returns the reward amount for a campaign and a reward token.
    /// @param id The id of the campaign to query.
    /// @param token The reward token to query.
    /// @return reward The reward amount.
    function campaignReward(bytes32 id, address token) external view returns (uint256 reward);

    /// @notice Returns the amount of claimed reward token for a campaign and a user.
    /// @param id The id of the campaign to query.
    /// @param token The reward token to query.
    /// @param account The claimer account.
    /// @return claimed The claimed amount.
    function claimedCampaignReward(bytes32 id, address token, address account)
        external
        view
        returns (uint256 claimed);

    /// @notice Creates one or more campaigns. The transaction will revert even if one
    /// of the specified bundles results in a creation failure (all or none).
    /// @param rewardsCampaignBundles The bundles containing the data used to create new rewards
    /// based campaigns.
    /// @param pointsCampaignBundles The bundles containing the data used to create new points
    /// based campaigns.
    function createCampaigns(
        CreateRewardsCampaignBundle[] calldata rewardsCampaignBundles,
        CreatePointsCampaignBundle[] calldata pointsCampaignBundles
    ) external;

    /// @notice Distributes rewards on one or more campaigns. The transaction will revert
    /// even if only one of the specified bundles results in a distribution failure (all or none).
    /// @param bundles The bundles containing the data used to distribute the rewards.
    function distributeRewards(DistributeRewardsBundle[] calldata bundles) external;

    /// @notice Sets the minimum rates for both reward and fee tokens.
    /// @param rewardTokenBundles The bundles containing the data used to update the minimum whitelisted
    /// reward token rates.
    /// @param feeTokenBundles The bundles containing the data used to update the minimum fee token rates.
    function setMinimumTokenRates(
        SetMinimumTokenRateBundle[] calldata rewardTokenBundles,
        SetMinimumTokenRateBundle[] calldata feeTokenBundles
    ) external;

    /// @notice Claims outstanding rewards on one or more campaigns. The transaction will revert
    /// even if only one of the specified bundles results in a claim failure (all or none).
    /// @param bundles The bundles containing the data used to claim the rewards.
    function claimRewards(ClaimRewardBundle[] calldata bundles) external;

    /// @notice Can be used by a campaign owner to recover unassigned rewards on one or more
    /// campaigns. The transaction will revert even if only one of the specified bundles results
    /// in a recovery failure (all or none).
    /// @param bundles The bundles containing the data used to claim the recoverable rewards.
    function recoverRewards(ClaimRewardBundle[] calldata bundles) external;

    /// @notice Returns the current owner of a campaign.
    /// @param id The id of the targeted campaign.
    /// @return owner The current owner of the campaign.
    function campaignOwner(bytes32 id) external view returns (address owner);

    /// @notice Returns the current pending owner of a campaign.
    /// @param id The id of the targeted campaign.
    /// @return pendingOwner The current pending owner of the campaign.
    function campaignPendingOwner(bytes32 id) external view returns (address pendingOwner);

    /// @notice Initiates an ownership transfer operation for a campaign. This can only be
    /// called by the current campaign owner.
    /// @param id The id of the targeted campaign.
    /// @param owner The desired new owner of the campaign.
    function transferCampaignOwnership(bytes32 id, address owner) external;

    /// @notice Finalized an ownership transfer operation for a campaign. This can only be
    /// called by the current campaign pending owner to accept ownership of it.
    /// @param id The id of the targeted campaign.
    function acceptCampaignOwnership(bytes32 id) external;

    /// @notice Initiates an ownership transfer operation for the Metrom contract. This can
    /// only be called by the current Metrom owner.
    /// @param owner The desired new owner of Metrom.
    function transferOwnership(address owner) external;

    /// @notice Finalizes an ownership transfer operation for the Metrom contract. This can
    /// only be called by the current Metrom pending owner.
    function acceptOwnership() external;

    /// @notice Can be called by Metrom's owner to claim one or more outstanding fees.
    /// @param bundles The bundles containing the data used to claim the fees.
    function claimFees(ClaimFeeBundle[] calldata bundles) external;

    /// @notice Can be called by Metrom's owner to set a new allowed updater address.
    /// @param updater The new updater address.
    function setUpdater(address updater) external;

    /// @notice Can be called by Metrom's owner to set a new fee value.
    function setFee(uint32 fee) external;

    /// @notice Can be called by Metrom's owner to set a new specific protocol fee
    /// rebate for an account.
    /// @param account The account for which to set the rebate value.
    /// @param rebate The rebate.
    function setFeeRebate(address account, uint32 rebate) external;

    /// @notice Can be called by Metrom's owner to set a new minimum allowed campaign duration.
    /// @param minimumCampaignDuration The new minimum allowed campaign duration.
    function setMinimumCampaignDuration(uint32 minimumCampaignDuration) external;

    /// @notice Can be called by Metrom's owner to set a new maximum allowed campaign duration.
    /// @param maximumCampaignDuration The new maximum allowed campaign duration.
    function setMaximumCampaignDuration(uint32 maximumCampaignDuration) external;
}

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

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/Hashes.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? _efficientKeccak256(a, b) : _efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function _efficientKeccak256(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.22;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

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

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

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

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

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

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

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

Please enter a contract address above to load the contract details and source code.

Context size (optional):