Skip to content
Verified contractPartialApache-2.0

DistributionModule

Address0xd56e9949d77001fa33ceab758bb93e1ab6469e73
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
EVM version
shanghai
License
Apache-2.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
22,039,395
Creation transaction
0xa15744b391…4d63e49784

33 files

src/distribution/DistributionModule.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {SafeERC20} from "openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {ReentrancyGuardUpgradeable} from
    "openzeppelin-contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {PausableUpgradeable} from "openzeppelin-contracts-upgradeable/utils/PausableUpgradeable.sol";
import {Initializable} from "openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol";

import {IUsualSP} from "src/interfaces/token/IUsualSP.sol";
import {IUsualX} from "src/interfaces/vaults/IUsualX.sol";
import {IUsual} from "src/interfaces/token/IUsual.sol";
import {IUsd0PP} from "src/interfaces/token/IUsd0PP.sol";
import {IDaoCollateral} from "src/interfaces/IDaoCollateral.sol";

import {IDistributionModule} from "src/interfaces/distribution/IDistributionModule.sol";
import {IDistributionAllocator} from "src/interfaces/distribution/IDistributionAllocator.sol";
import {IDistributionOperator} from "src/interfaces/distribution/IDistributionOperator.sol";
import {IOffChainDistributionChallenger} from
    "src/interfaces/distribution/IOffChainDistributionChallenger.sol";

import {IRegistryAccess} from "src/interfaces/registry/IRegistryAccess.sol";
import {IRegistryContract} from "src/interfaces/registry/IRegistryContract.sol";
import {CheckAccessControl} from "src/utils/CheckAccessControl.sol";
import {Normalize} from "src/utils/normalize.sol";

import {MerkleProof} from "openzeppelin-contracts/utils/cryptography/MerkleProof.sol";
import {IYieldModule} from "src/interfaces/modules/IYieldModule.sol";
import {
    DEFAULT_ADMIN_ROLE,
    DISTRIBUTION_ALLOCATOR_ROLE,
    DISTRIBUTION_OPERATOR_ROLE,
    DISTRIBUTION_CHALLENGER_ROLE,
    PAUSING_CONTRACTS_ROLE,
    SCALAR_ONE,
    BPS_SCALAR,
    USUAL_DISTRIBUTION_CHALLENGE_PERIOD,
    BASIS_POINT_BASE,
    DISTRIBUTION_FREQUENCY_SCALAR,
    STARTDATE_USUAL_CLAIMING_DISTRIBUTION_MODULE,
    REDIRECTION_ADMIN_ROLE,
    REDIRECTION_DISTRIBUTION_CHALLENGE_PERIOD,
    CONTRACT_YIELD_TREASURY,
    CONTRACT_YIELD_MODULE,
    FEE_RATE_SETTER_ROLE,
    CONTRACT_ORACLE,
    VAULT_UPDATER_ROLE
} from "src/constants.sol";
import {
    AmountIsZero,
    NullMerkleRoot,
    InvalidProof,
    InvalidInput,
    NullAddress,
    SameValue,
    PercentagesSumNotEqualTo100Percent,
    CannotDistributeUsualMoreThanOnceADay,
    NoOffChainDistributionToApprove,
    NoTokensToClaim,
    NotClaimableYet,
    OffChainDistributionRedirectTimeIntervalNotPassed,
    NoInitiatedRedirectedOffChainDistribution,
    NoActiveRedirectedOffChainDistribution,
    InvalidRates,
    AlreadyInitiatedRedirectedOffChainDistribution,
    AlreadyRedirectedOffChainDistribution
} from "src/errors.sol";

import {IERC4626} from "openzeppelin-contracts/interfaces/IERC4626.sol";
import {IOracle} from "src/interfaces/oracles/IOracle.sol";

/// @title DistributionModule
/// @notice This contract provides calculations for treasury yield analysis & distribution
/// @dev Implements upgradeable pattern and uses fixed point arithmetic for calculations
/// @author  Usual Tech team
contract DistributionModule is
    Initializable,
    ReentrancyGuardUpgradeable,
    PausableUpgradeable,
    IOffChainDistributionChallenger,
    IDistributionAllocator,
    IDistributionOperator,
    IDistributionModule
{
    using SafeERC20 for IUsual;
    using SafeERC20 for IERC20Metadata;
    using CheckAccessControl for IRegistryAccess;
    using Normalize for uint256;

    struct DistributionModuleStorageV0 {
        /// @notice Registry access contract
        IRegistryAccess registryAccess;
        /// @notice Registry contract
        IRegistryContract registryContract;
        /// @notice usd0PP contract
        IERC20Metadata usd0PP;
        /// @notice Usual token contract
        IUsual usual;
        /// @notice UsualX contract
        IUsualX usualX;
        /// @notice UsualSP contract
        IUsualSP usualSP;
        /// @notice DAO Collateral contract
        IDaoCollateral daoCollateral;
        /// @notice LBT bucket distribution percentage
        uint256 lbtDistributionShare;
        /// @notice LYT bucket distribution percentage
        uint256 lytDistributionShare;
        /// @notice IYT bucket distribution percentage
        uint256 iytDistributionShare;
        /// @notice Bribe bucket distribution percentage
        uint256 bribeDistributionShare;
        /// @notice Ecosystem bucket distribution percentage
        uint256 ecoDistributionShare;
        /// @notice DAO bucket distribution percentage
        uint256 daoDistributionShare;
        /// @notice Market makers bucket distribution percentage
        uint256 marketMakersDistributionShare;
        /// @notice UsualX bucket distribution percentage
        uint256 usualXDistributionShare;
        /// @notice UsualStar bucket distribution percentage
        uint256 usualStarDistributionShare;
        /// @notice D parameter
        uint256 d;
        /// @notice M0 parameter
        uint256 m0;
        /// @notice p0 parameter: initial price
        uint256 p0;
        /// @notice rate0 parameter: initial rate
        uint256 rate0;
        /// @notice RateMin parameter
        uint256 rateMin;
        /// @notice baseGamma parameter
        uint256 baseGamma;
        /// @notice usd0PP total supply at the time of deployment
        uint256 initialSupplyPp0;
        /// @notice Timestamp of the last on-chain distribution
        uint256 lastOnChainDistributionTimestamp;
        /// @notice Amount of tokens that can be minted for the off-chain distribution
        uint256 offChainDistributionMintCap;
        /// @notice Queue of off-chain distributions
        QueuedOffChainDistribution[] offChainDistributionQueue;
        /// @notice Timestamp of the latest off-chain distribution update that is claimable
        uint256 offChainDistributionTimestamp;
        /// @notice Merkle root of the latest off-chain distribution update that is claimable and after challenge period
        /// @dev Merkle tree should always include the total amount of tokens that account can claim and could claim in the past.
        bytes32 offChainDistributionMerkleRoot;
        /// @notice Mapping of the claimed tokens for each account. Used to prevent double claiming after a new distribution is approved.
        mapping(address offChainClaimer => uint256 amount) claimedByOffChainClaimer;
        /// @notice Mapping of the initiated redirected off-chain distribution
        mapping(address account => address initiatedRedirectedAccount)
            initiatedRedirectedOffChainDistribution;
        /// @notice Mapping of the initiated redirected off-chain distributions starting timestamp
        mapping(address account => uint256 redirectedOffChainDistributionStartingTimestamp)
            initiatedRedirectedOffChainDistributionStartingTimestamp;
        /// @notice Mapping of the accepted & finalized redirected off-chain distributions
        mapping(address account => address acceptedRedirectedAccount)
            activeRedirectedOffChainDistribution;
        /// @notice Rate of fee to send to yield treasury
        uint256 treasuryFeeRate;
        /// @notice Rate of fee to send to UsualX
        uint256 usualXFeeRate;
        /// @notice  Yield Module contract
        IYieldModule yieldModule;
        /// @notice Address of the iUSD0++ vault
        IERC4626 iUsd0ppVault;
        /// @notice Address of the classicalOracle
        IOracle oracle;
        /// @notice iUSD0++ bucket distribution percentage
        uint256 iUSD0ppDistributionShareOfLbt;
    }

    // keccak256(abi.encode(uint256(keccak256("DistributionModule.storage.v0")) - 1)) & ~bytes32(uint256(0xff))
    // solhint-disable-next-line
    bytes32 public constant DistributionModuleStorageV0Location =
        0xfe38e877893749f31d716df8c21b1fcb408307d7596d0d90c0ec8782cacd9b00;

    // solhint-disable
    /// @dev Returns the storage struct of the contract
    function _distributionModuleStorageV0()
        internal
        pure
        returns (DistributionModuleStorageV0 storage $)
    {
        bytes32 position = DistributionModuleStorageV0Location;
        assembly {
            $.slot := position
        }
    }
    // solhint-enable

    /*//////////////////////////////////////////////////////////////
                             Constructor
    //////////////////////////////////////////////////////////////*/

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /*//////////////////////////////////////////////////////////////
                             Initializer
    //////////////////////////////////////////////////////////////*/

    /// @notice Initializes the contract with the initial fee rates
    /// @param initialTreasuryFeeRate Rate of fee to send to yield treasury
    /// @param initialUsualXFeeRate Rate of fee to send to UsualX
    /// @param _iUsd0ppVault Address of the iUSD0++ vault
    function initializeV1(
        uint256 initialTreasuryFeeRate,
        uint256 initialUsualXFeeRate,
        address _iUsd0ppVault
    ) external reinitializer(2) {
        if (initialTreasuryFeeRate + initialUsualXFeeRate > BASIS_POINT_BASE) {
            revert InvalidInput();
        }

        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        // Initialize vault components
        // NOTE: if this vault is not set, it will nullify the vault integration dynamically
        $.iUsd0ppVault = IERC4626(_iUsd0ppVault);
        $.oracle = IOracle($.registryContract.getContract(CONTRACT_ORACLE));
        $.yieldModule = IYieldModule($.registryContract.getContract(CONTRACT_YIELD_MODULE));
        $.treasuryFeeRate = initialTreasuryFeeRate;
        $.usualXFeeRate = initialUsualXFeeRate;
        uint256 burnFeeRate = BASIS_POINT_BASE - initialTreasuryFeeRate - initialUsualXFeeRate;
        emit FeeRatesSet(initialTreasuryFeeRate, initialUsualXFeeRate, burnFeeRate);
    }

    /// @notice Checks if the caller has DISTRIBUTION_ALLOCATOR_ROLE role
    /// @param $ Storage struct of the contract
    function _requireOnlyDistributionAllocator(DistributionModuleStorageV0 storage $)
        internal
        view
    {
        $.registryAccess.onlyMatchingRole(DISTRIBUTION_ALLOCATOR_ROLE);
    }

    /// @notice Ensures that the caller is the pausing contracts role (PAUSING_CONTRACTS_ROLE).
    function _requireOnlyPausingContractsRole() internal view {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        $.registryAccess.onlyMatchingRole(PAUSING_CONTRACTS_ROLE);
    }

    /// @notice Ensures that the caller is the operator role (DISTRIBUTION_OPERATOR_ROLE).
    /// @param $ Storage struct of the contract
    function _requireOnlyOperator(DistributionModuleStorageV0 storage $) internal view {
        $.registryAccess.onlyMatchingRole(DISTRIBUTION_OPERATOR_ROLE);
    }

    /// @notice Ensures that the caller is the redirection-admin-role (REDIRECTION_ADMIN_ROLE).
    /// @param $ Storage struct of the contract
    function _requireOnlyRedirectionAdmin(DistributionModuleStorageV0 storage $) internal view {
        $.registryAccess.onlyMatchingRole(REDIRECTION_ADMIN_ROLE);
    }

    /// @notice Ensures that the caller is the challenger role (DISTRIBUTION_CHALLENGER_ROLE).
    /// @param $ Storage struct of the contract
    function _requireOnlyChallenger(DistributionModuleStorageV0 storage $) internal view {
        $.registryAccess.onlyMatchingRole(DISTRIBUTION_CHALLENGER_ROLE);
    }

    /// @notice Ensures that the caller is the fee rate setter role (FEE_RATE_SETTER_ROLE).
    /// @param $ Storage struct of the contract
    function _requireOnlyFeeRateSetter(DistributionModuleStorageV0 storage $) internal view {
        $.registryAccess.onlyMatchingRole(FEE_RATE_SETTER_ROLE);
    }

    /// @notice Ensures that the caller has the VAULT_UPDATER_ROLE
    /// @param $ Storage struct of the contract
    function _requireOnlyVaultUpdater(DistributionModuleStorageV0 storage $) internal view {
        $.registryAccess.onlyMatchingRole(VAULT_UPDATER_ROLE);
    }

    /// @notice Pauses the contract
    /// @dev Can only be called by the PAUSING_CONTRACTS_ROLE
    function pause() external {
        _requireOnlyPausingContractsRole();
        _pause();
    }

    /// @inheritdoc IDistributionModule
    function unpause() external {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        $.registryAccess.onlyMatchingRole(DEFAULT_ADMIN_ROLE);
        _unpause();
    }

    /// @inheritdoc IDistributionModule
    function getBucketsDistribution()
        external
        view
        returns (
            uint256 lbt,
            uint256 lyt,
            uint256 iyt,
            uint256 bribe,
            uint256 eco,
            uint256 dao,
            uint256 marketMakers,
            uint256 usualX,
            uint256 usualStar
        )
    {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        lbt = $.lbtDistributionShare;
        lyt = $.lytDistributionShare;
        iyt = $.iytDistributionShare;
        bribe = $.bribeDistributionShare;
        eco = $.ecoDistributionShare;
        dao = $.daoDistributionShare;
        marketMakers = $.marketMakersDistributionShare;
        usualX = $.usualXDistributionShare;
        usualStar = $.usualStarDistributionShare;
    }

    /// @inheritdoc IDistributionModule
    function calculateSt(uint256 supplyPpt, uint256 pt) external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return _calculateSt($, supplyPpt, pt);
    }

    /// @inheritdoc IDistributionModule
    function calculateRt() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        (uint256 ratet, uint256 p90Rate) = _getRateAndP90Rate($);
        return _calculateRt($, ratet, p90Rate);
    }

    /// @inheritdoc IDistributionModule
    function calculateKappa() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        (uint256 ratet,) = _getRateAndP90Rate($);
        return _calculateKappa($, ratet);
    }

    function calculateGamma() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return _calculateGamma($);
    }

    /// @inheritdoc IDistributionModule
    function calculateMt(uint256 st, uint256 rt, uint256 kappa) external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        return _calculateMt($, st, rt, kappa);
    }

    /// @inheritdoc IDistributionModule
    function calculateUsualDist()
        public
        view
        returns (uint256 st, uint256 rt, uint256 kappa, uint256 mt, uint256 usualDist)
    {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        (uint256 ratet, uint256 p90Rate) = _getRateAndP90Rate($);
        return _calculateUsualDistribution($, ratet, p90Rate);
    }

    /// @inheritdoc IDistributionModule
    //solhint-disable-next-line
    function claimOffChainDistribution(address account, uint256 amount, bytes32[] calldata proof)
        external
        nonReentrant
        whenNotPaused
    {
        if (account == address(0)) {
            revert NullAddress();
        }
        if (amount == 0) {
            revert AmountIsZero();
        }
        if (block.timestamp < STARTDATE_USUAL_CLAIMING_DISTRIBUTION_MODULE) {
            revert NotClaimableYet();
        }

        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        if ($.offChainDistributionTimestamp == 0) {
            revert NoTokensToClaim();
        }

        if (!_verifyOffChainDistributionMerkleProof($, account, amount, proof)) {
            revert InvalidProof();
        }

        uint256 claimedUpToNow = $.claimedByOffChainClaimer[account];

        if (claimedUpToNow >= amount) {
            revert NoTokensToClaim();
        }

        uint256 amountToSend = amount - claimedUpToNow;

        if (amountToSend > $.offChainDistributionMintCap) {
            revert NoTokensToClaim();
        }

        $.offChainDistributionMintCap -= amountToSend;
        $.claimedByOffChainClaimer[account] = amount;

        emit OffChainDistributionClaimed(account, amountToSend);

        if ($.activeRedirectedOffChainDistribution[account] != address(0)) {
            $.usual.mint($.activeRedirectedOffChainDistribution[account], amountToSend);
            emit OffChainDistributionClaimedAndRedirected(
                account, $.activeRedirectedOffChainDistribution[account], amountToSend
            );
        } else {
            $.usual.mint(account, amountToSend);
        }
    }

    /// @inheritdoc IDistributionModule
    function approveUnchallengedOffChainDistribution() external whenNotPaused {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        uint256 queueLength = $.offChainDistributionQueue.length;
        if (queueLength == 0) {
            revert NoOffChainDistributionToApprove();
        }

        uint256 candidateTimestamp = $.offChainDistributionTimestamp;
        bytes32 candidateMerkleRoot = bytes32(0);

        uint256 amountOfDistributionsToRemove = 0;
        uint256[] memory indicesToRemove = new uint256[](queueLength);

        for (uint256 i; i < queueLength;) {
            QueuedOffChainDistribution storage distribution = $.offChainDistributionQueue[i];

            bool isAfterChallengePeriod =
                block.timestamp >= distribution.timestamp + USUAL_DISTRIBUTION_CHALLENGE_PERIOD;
            bool isNewerThanCandidate = distribution.timestamp > candidateTimestamp;

            if (isAfterChallengePeriod && isNewerThanCandidate) {
                candidateMerkleRoot = distribution.merkleRoot;
                candidateTimestamp = distribution.timestamp;
            }

            if (isAfterChallengePeriod) {
                // NOTE: We store the index to remove to avoid modifying the array while iterating.
                // NOTE: After successful approval queue should have only elements older than challenge period.
                indicesToRemove[amountOfDistributionsToRemove] = i;
                amountOfDistributionsToRemove++;
            }

            unchecked {
                ++i;
            }
        }

        if (candidateTimestamp <= $.offChainDistributionTimestamp) {
            revert NoOffChainDistributionToApprove();
        }

        for (uint256 i = amountOfDistributionsToRemove; i > 0;) {
            uint256 indexToRemove = indicesToRemove[i - 1];

            // NOTE: $.offChainDistributionQueue.length cannot be cached since it can decrease with each loop iteration
            $.offChainDistributionQueue[indexToRemove] =
                $.offChainDistributionQueue[$.offChainDistributionQueue.length - 1];
            $.offChainDistributionQueue.pop();

            unchecked {
                --i;
            }
        }

        $.offChainDistributionMerkleRoot = candidateMerkleRoot;
        $.offChainDistributionTimestamp = candidateTimestamp;

        emit OffChainDistributionApproved(
            $.offChainDistributionTimestamp, $.offChainDistributionMerkleRoot
        );
    }

    /// @inheritdoc IDistributionModule
    function getLastOnChainDistributionTimestamp() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.lastOnChainDistributionTimestamp;
    }

    /// @inheritdoc IDistributionModule
    function getOffChainDistributionData()
        external
        view
        returns (uint256 timestamp, bytes32 merkleRoot)
    {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return ($.offChainDistributionTimestamp, $.offChainDistributionMerkleRoot);
    }

    /// @inheritdoc IDistributionModule
    function getOffChainTokensClaimed(address account) external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.claimedByOffChainClaimer[account];
    }

    /// @inheritdoc IDistributionModule
    function getOffChainDistributionMintCap() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.offChainDistributionMintCap;
    }

    /// @inheritdoc IDistributionModule
    function getOffChainDistributionQueue()
        external
        view
        returns (QueuedOffChainDistribution[] memory)
    {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.offChainDistributionQueue;
    }

    /// @inheritdoc IDistributionAllocator
    function setD(uint256 _d) external {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyDistributionAllocator($);

        if (_d == 0) {
            revert InvalidInput();
        }
        if ($.d == _d) revert SameValue();

        $.d = _d;
        emit ParameterUpdated("d", _d);
    }

    /// @inheritdoc IDistributionAllocator
    function getD() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.d;
    }

    /// @inheritdoc IDistributionAllocator
    function setM0(uint256 _m0) external {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyDistributionAllocator($);

        if (_m0 == 0) {
            revert InvalidInput();
        }

        if ($.m0 == _m0) revert SameValue();
        $.m0 = _m0;
        emit ParameterUpdated("m0", _m0);
    }

    /// @inheritdoc IDistributionAllocator
    function getM0() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.m0;
    }

    /// @inheritdoc IDistributionAllocator
    function setRateMin(uint256 _rateMin) external {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyDistributionAllocator($);

        if (_rateMin == 0) {
            revert InvalidInput();
        }

        if ($.rateMin == _rateMin) revert SameValue();
        $.rateMin = _rateMin;
        emit ParameterUpdated("rateMin", _rateMin);
    }

    /// @inheritdoc IDistributionAllocator
    function getRateMin() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.rateMin;
    }

    /// @inheritdoc IDistributionAllocator
    function setBaseGamma(uint256 _baseGamma) external {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyDistributionAllocator($);

        if (_baseGamma == 0) {
            revert InvalidInput();
        }

        if ($.baseGamma == _baseGamma) revert SameValue();
        $.baseGamma = _baseGamma;
        emit ParameterUpdated("baseGamma", _baseGamma);
    }

    /// @inheritdoc IDistributionAllocator
    function getBaseGamma() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.baseGamma;
    }

    /// @inheritdoc IDistributionAllocator
    function setFeeRates(uint256 _treasuryFeeRate, uint256 _usualXFeeRate) external {
        if (_treasuryFeeRate + _usualXFeeRate > BASIS_POINT_BASE) {
            revert InvalidRates();
        }

        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyFeeRateSetter($);

        if (_treasuryFeeRate == $.treasuryFeeRate && _usualXFeeRate == $.usualXFeeRate) {
            revert SameValue();
        }

        $.treasuryFeeRate = _treasuryFeeRate;
        $.usualXFeeRate = _usualXFeeRate;
        uint256 burnFeeRate = BASIS_POINT_BASE - _treasuryFeeRate - _usualXFeeRate;

        emit FeeRatesSet(_treasuryFeeRate, _usualXFeeRate, burnFeeRate);
    }

    /// @inheritdoc IDistributionAllocator
    function getFeeRates() external view returns (uint256, uint256, uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        uint256 burnFeeRate = BASIS_POINT_BASE - $.treasuryFeeRate - $.usualXFeeRate;
        return ($.treasuryFeeRate, $.usualXFeeRate, burnFeeRate);
    }

    /// @inheritdoc IDistributionAllocator
    function setBucketsDistribution(
        uint256 _lbt,
        uint256 _lyt,
        uint256 _iyt,
        uint256 _bribe,
        uint256 _eco,
        uint256 _dao,
        uint256 _marketMakers,
        uint256 _usualP,
        uint256 _usualStar
    ) external {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        _requireOnlyDistributionAllocator($);

        uint256 total = 0;
        total += _lbt;
        total += _lyt;
        total += _iyt;
        total += _bribe;
        total += _eco;
        total += _dao;
        total += _marketMakers;
        total += _usualP;
        total += _usualStar;

        if (total != BASIS_POINT_BASE) revert PercentagesSumNotEqualTo100Percent();

        _setLbt($, _lbt);
        _setLyt($, _lyt);
        _setIyt($, _iyt);
        _setBribe($, _bribe);
        _setEco($, _eco);
        _setDao($, _dao);
        _setMarketMakers($, _marketMakers);
        _setUsualP($, _usualP);
        _setUsualStar($, _usualStar);
    }

    /// @inheritdoc IDistributionOperator
    function distributeUsualToBuckets() external nonReentrant whenNotPaused {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        (uint256 ratet, uint256 p90Rate) = _getRateAndP90Rate($);
        if (ratet == 0 || ratet > BPS_SCALAR) {
            revert InvalidInput();
        }

        if (p90Rate == 0 || p90Rate >= BPS_SCALAR) {
            revert InvalidInput();
        }

        if (block.timestamp < $.lastOnChainDistributionTimestamp + DISTRIBUTION_FREQUENCY_SCALAR) {
            revert CannotDistributeUsualMoreThanOnceADay();
        }

        (,,,, uint256 usualDistribution) = _calculateUsualDistribution($, ratet, p90Rate);
        uint256 feeSwept = $.usualX.sweepFees() + IUsd0PP(address($.usd0PP)).sweepFees();

        // Update iUSD0++ distribution share before distribution
        _updateiUsd0ppDistributionShare($);

        $.lastOnChainDistributionTimestamp = block.timestamp;

        _distributeToOffChainBucket($, usualDistribution);
        uint256 feeAmountUsualX = _distributeToUsualXBucket($, usualDistribution, feeSwept);
        _distributeToUsualStarBucket($, usualDistribution);
        uint256 feeAmountYieldTreasury = _distributeFeesToYieldTreasury($, feeSwept);
        // Calculate the amount of fees to burn to avoid dust
        uint256 feesToBurn = feeSwept - feeAmountUsualX - feeAmountYieldTreasury;
        _burnFees($, feesToBurn);

        emit DailyDistributionRates(ratet, p90Rate);
    }

    /// @inheritdoc IDistributionOperator
    function queueOffChainUsualDistribution(bytes32 _merkleRoot) external whenNotPaused {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyOperator($);

        if (_merkleRoot == bytes32(0)) {
            revert NullMerkleRoot();
        }

        $.offChainDistributionQueue.push(
            QueuedOffChainDistribution({timestamp: block.timestamp, merkleRoot: _merkleRoot})
        );
        emit OffChainDistributionQueued(block.timestamp, _merkleRoot);
    }

    /// @inheritdoc IDistributionOperator
    function resetOffChainDistributionQueue() external whenNotPaused {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyOperator($);

        delete $.offChainDistributionQueue;
        emit OffChainDistributionQueueReset();
    }

    /// @inheritdoc IOffChainDistributionChallenger
    function challengeOffChainDistribution(uint256 _timestamp) external whenNotPaused {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyChallenger($);

        _markQueuedOffChainDistributionsAsChallenged($, _timestamp);
        emit OffChainDistributionChallenged(_timestamp);
    }

    /// @inheritdoc IDistributionModule
    function getInitiatedRedirectedOffChainDistribution(address account)
        external
        view
        returns (address)
    {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.initiatedRedirectedOffChainDistribution[account];
    }

    /// @inheritdoc IDistributionModule
    function getOngoingRedirectionChallenge(address account) external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.initiatedRedirectedOffChainDistributionStartingTimestamp[account];
    }

    /// @inheritdoc IDistributionModule
    function getRedirectedAccount(address account) external view returns (address) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.activeRedirectedOffChainDistribution[account];
    }

    /// @inheritdoc IDistributionModule
    function redirectOffChainDistribution(address account, address newAccount)
        external
        whenNotPaused
    {
        if (account == newAccount) {
            revert SameValue();
        }
        if (newAccount == address(0)) {
            revert InvalidInput();
        }

        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyRedirectionAdmin($);

        if (
            $.initiatedRedirectedOffChainDistribution[account] != address(0)
                || $.initiatedRedirectedOffChainDistributionStartingTimestamp[account] != 0
        ) {
            revert AlreadyInitiatedRedirectedOffChainDistribution();
        }

        if ($.activeRedirectedOffChainDistribution[account] != address(0)) {
            revert AlreadyRedirectedOffChainDistribution();
        }

        $.initiatedRedirectedOffChainDistribution[account] = newAccount;
        $.initiatedRedirectedOffChainDistributionStartingTimestamp[account] = block.timestamp;
        emit OffChainDistributionRedirectInitialized(account, newAccount, block.timestamp);
    }

    /// @inheritdoc IDistributionModule
    function cancelInitiatedRedirectedOffChainDistribution(address account)
        external
        whenNotPaused
    {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        // Only the account that has been redirected to or the redirection-admin-role can cancel the initialized redirection
        if (msg.sender != account) {
            _requireOnlyRedirectionAdmin($);
        }
        if ($.initiatedRedirectedOffChainDistribution[account] == address(0)) {
            revert NoInitiatedRedirectedOffChainDistribution();
        }

        emit OffChainDistributionRedirectedCancelled(
            account, $.initiatedRedirectedOffChainDistribution[account]
        );

        delete $.initiatedRedirectedOffChainDistribution[account];
        delete $.initiatedRedirectedOffChainDistributionStartingTimestamp[account];
    }

    /// @inheritdoc IDistributionModule
    function removeRedirectedOffChainDistribution(address account) external whenNotPaused {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        if (msg.sender != account) {
            _requireOnlyRedirectionAdmin($);
        }

        if ($.activeRedirectedOffChainDistribution[account] == address(0)) {
            revert NoActiveRedirectedOffChainDistribution();
        }

        delete $.activeRedirectedOffChainDistribution[account];
        emit OffChainDistributionRedirectedRemoved(account);
    }

    /// @inheritdoc IDistributionModule
    function acceptRedirectedOffChainDistribution(address account) external whenNotPaused {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        // Only the account that has been redirected to or the redirection-admin-role can accept the redirection
        if (msg.sender != $.initiatedRedirectedOffChainDistribution[account]) {
            _requireOnlyRedirectionAdmin($);
        }

        if ($.initiatedRedirectedOffChainDistributionStartingTimestamp[account] == 0) {
            revert NoInitiatedRedirectedOffChainDistribution();
        }

        // Check if the challenge time interval has passed
        if (
            $.initiatedRedirectedOffChainDistributionStartingTimestamp[account]
                + REDIRECTION_DISTRIBUTION_CHALLENGE_PERIOD > block.timestamp
        ) {
            revert OffChainDistributionRedirectTimeIntervalNotPassed();
        }

        $.activeRedirectedOffChainDistribution[account] =
            $.initiatedRedirectedOffChainDistribution[account];

        delete $.initiatedRedirectedOffChainDistribution[account];
        delete $.initiatedRedirectedOffChainDistributionStartingTimestamp[account];

        emit OffChainDistributionRedirectedAccepted(
            account, $.activeRedirectedOffChainDistribution[account]
        );
    }

    /// @inheritdoc IDistributionModule
    function updateIUsd0ppVault(address newVault) external {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        _requireOnlyVaultUpdater($);

        if (newVault == address($.iUsd0ppVault)) {
            revert SameValue();
        }

        // Update the iUsd0ppVault
        $.iUsd0ppVault = IERC4626(newVault);
    }

    /// @notice Retrieve the blended weekly interest rate and the 90th percentile weekly interest rate from the Yield Module
    /// @param $ Storage struct of the contract
    /// @return Blended weekly interest rate
    /// @return p90 rate
    function _getRateAndP90Rate(DistributionModuleStorageV0 storage $)
        internal
        view
        returns (uint256, uint256)
    {
        return ($.yieldModule.getBlendedWeeklyInterest(), $.yieldModule.getP90InterestRate());
    }

    /// @notice Marks off-chain distributions older than the specified timestamp as challenged
    /// @param $ Storage struct of the contract
    /// @param _timestamp Timestamp before which the off-chain distribution will be challenged
    function _markQueuedOffChainDistributionsAsChallenged(
        DistributionModuleStorageV0 storage $,
        uint256 _timestamp
    ) internal {
        uint256 i = 0;
        while (i < $.offChainDistributionQueue.length) {
            QueuedOffChainDistribution storage distribution = $.offChainDistributionQueue[i];
            bool isAfterChallengePeriod =
                block.timestamp >= distribution.timestamp + USUAL_DISTRIBUTION_CHALLENGE_PERIOD;

            if (distribution.timestamp < _timestamp && !isAfterChallengePeriod) {
                // Swap with the last element and pop
                $.offChainDistributionQueue[i] =
                    $.offChainDistributionQueue[$.offChainDistributionQueue.length - 1];
                $.offChainDistributionQueue.pop();
                // Don't increment i, as we need to check the swapped element
            } else {
                // Only increment if we didn't remove an element
                i++;
            }
        }
    }

    /// @notice Increases the mint cap for the off-chain distribution by the calculated share of the distribution
    /// @param $ Storage struct of the contract
    /// @param usualDistribution Amount of Usual to distribute to all buckets
    /// @dev If the off-chain buckets share is 0, the function will return without increasing the mint cap
    function _distributeToOffChainBucket(
        DistributionModuleStorageV0 storage $,
        uint256 usualDistribution
    ) internal {
        uint256 offChainBucketsShare =
            BASIS_POINT_BASE - $.usualXDistributionShare - $.usualStarDistributionShare;
        if (offChainBucketsShare == 0) {
            return;
        }

        uint256 amount =
            Math.mulDiv(usualDistribution, offChainBucketsShare, BPS_SCALAR, Math.Rounding.Floor);

        $.offChainDistributionMintCap += amount;

        emit UsualAllocatedForOffChainClaim(amount);
    }

    /// @notice Mints Usual to UsualX and starts the yield distribution by the calculated share of the distribution
    /// @param $ Storage struct of the contract
    /// @param usualDistribution Amount of Usual to distribute to all buckets
    /// @param feeSwept Amount of fees swept from UsualX
    /// @dev If the UsualX share is 0, the function will return without minting Usual to UsualX
    function _distributeToUsualXBucket(
        DistributionModuleStorageV0 storage $,
        uint256 usualDistribution,
        uint256 feeSwept
    ) internal returns (uint256 feeAmount) {
        if ($.usualXDistributionShare == 0) {
            return 0;
        }

        uint256 amount = Math.mulDiv(
            usualDistribution, $.usualXDistributionShare, BPS_SCALAR, Math.Rounding.Floor
        );

        feeAmount = _distributeFeesToUsualX($, feeSwept);

        emit UsualAllocatedForUsualX(amount);

        $.usual.mint(address($.usualX), amount);
        $.usualX.startYieldDistribution(
            amount + feeAmount, block.timestamp, block.timestamp + DISTRIBUTION_FREQUENCY_SCALAR
        );
    }

    /// @notice Mints Usual to this contract, increases the allowance for UsualSP and starts the yield distribution by the calculated share of the distribution
    /// @param $ Storage struct of the contract
    /// @param usualDistribution Amount of Usual to distribute to all buckets
    /// @dev If the UsualStar share is 0, the function will return without minting Usual to this contract
    function _distributeToUsualStarBucket(
        DistributionModuleStorageV0 storage $,
        uint256 usualDistribution
    ) internal {
        if ($.usualStarDistributionShare == 0) {
            return;
        }

        uint256 amount = Math.mulDiv(
            usualDistribution, $.usualStarDistributionShare, BPS_SCALAR, Math.Rounding.Floor
        );

        emit UsualAllocatedForUsualStar(amount);

        $.usual.mint(address(this), amount);
        $.usual.safeIncreaseAllowance(address($.usualSP), amount);

        $.usualSP.startRewardDistribution(
            amount, block.timestamp, block.timestamp + DISTRIBUTION_FREQUENCY_SCALAR
        );
    }

    /// @notice Distributes some of the fee swept from UsualX and Usd0PP to UsualX
    /// @param $ Storage struct of the contract
    /// @param feeSwept Amount of fees swept from UsualX and Usd0PP
    /// @return feeAmount Amount of fees allocated to UsualX
    function _distributeFeesToUsualX(DistributionModuleStorageV0 storage $, uint256 feeSwept)
        internal
        returns (uint256 feeAmount)
    {
        feeAmount = Math.mulDiv(feeSwept, $.usualXFeeRate, BASIS_POINT_BASE, Math.Rounding.Floor);
        if (feeAmount > 0) {
            $.usual.safeTransfer(address($.usualX), feeAmount);
            emit UsualFeeAllocatedToUsualX(feeAmount);
        }
    }

    /// @notice Distributes some of the fee swept from UsualX and Usd0PP to the yield treasury
    /// @param $ Storage struct of the contract
    /// @param feeSwept Amount of fees swept from UsualX and Usd0PP
    function _distributeFeesToYieldTreasury(DistributionModuleStorageV0 storage $, uint256 feeSwept)
        internal
        returns (uint256 feeAmount)
    {
        address yieldTreasury = $.registryContract.getContract(CONTRACT_YIELD_TREASURY);

        feeAmount = Math.mulDiv(feeSwept, $.treasuryFeeRate, BASIS_POINT_BASE, Math.Rounding.Floor);
        if (feeAmount > 0) {
            $.usual.safeTransfer(yieldTreasury, feeAmount);
            emit UsualFeeAllocatedToYieldTreasury(feeAmount);
        }
    }

    /// @notice Burns some of the fee swept from UsualX and Usd0PP
    /// @param $ Storage struct of the contract
    /// @param feesToBurn Amount of fees to burn
    function _burnFees(DistributionModuleStorageV0 storage $, uint256 feesToBurn) internal {
        if (feesToBurn > 0) {
            $.usual.burn(feesToBurn);
            emit UsualFeeBurned(feesToBurn);
        }
    }

    /// @notice Sets the LBT distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _lbt LBT distribution percentage
    function _setLbt(DistributionModuleStorageV0 storage $, uint256 _lbt) internal {
        $.lbtDistributionShare = _lbt;
        emit ParameterUpdated("lbt", _lbt);
    }

    /// @notice Sets the LYT distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _lyt LYT distribution percentage
    function _setLyt(DistributionModuleStorageV0 storage $, uint256 _lyt) internal {
        $.lytDistributionShare = _lyt;
        emit ParameterUpdated("lyt", _lyt);
    }

    /// @notice Sets the IYT distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _iyt IYT distribution percentage
    function _setIyt(DistributionModuleStorageV0 storage $, uint256 _iyt) internal {
        $.iytDistributionShare = _iyt;
        emit ParameterUpdated("iyt", _iyt);
    }

    /// @notice Sets the Bribe distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _bribe Bribe distribution percentage
    function _setBribe(DistributionModuleStorageV0 storage $, uint256 _bribe) internal {
        $.bribeDistributionShare = _bribe;
        emit ParameterUpdated("bribe", _bribe);
    }

    /// @notice Sets the Eco distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _eco Eco distribution percentage
    function _setEco(DistributionModuleStorageV0 storage $, uint256 _eco) internal {
        $.ecoDistributionShare = _eco;
        emit ParameterUpdated("eco", _eco);
    }

    /// @notice Sets the DAO distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _dao DAO distribution percentage
    function _setDao(DistributionModuleStorageV0 storage $, uint256 _dao) internal {
        $.daoDistributionShare = _dao;
        emit ParameterUpdated("dao", _dao);
    }

    /// @notice Sets the MarketMakers distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _marketMakers MarketMakers distribution percentage
    function _setMarketMakers(DistributionModuleStorageV0 storage $, uint256 _marketMakers)
        internal
    {
        $.marketMakersDistributionShare = _marketMakers;
        emit ParameterUpdated("marketMakers", _marketMakers);
    }

    /// @notice Sets the UsualP distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _usualX UsualX distribution percentage
    function _setUsualP(DistributionModuleStorageV0 storage $, uint256 _usualX) internal {
        $.usualXDistributionShare = _usualX;
        emit ParameterUpdated("usualX", _usualX);
    }

    /// @notice Sets the UsualStar distribution percentage
    /// @param $ Storage struct of the contract
    /// @param _usualStar UsualStar distribution percentage
    function _setUsualStar(DistributionModuleStorageV0 storage $, uint256 _usualStar) internal {
        $.usualStarDistributionShare = _usualStar;
        emit ParameterUpdated("usualStar", _usualStar);
    }

    /// @notice Calculates gamma scaled since lastOnChainDistributionTimestamp
    /// @param $ Storage struct of the contract
    /// @return Gamma scale factor
    function _calculateGamma(DistributionModuleStorageV0 storage $)
        internal
        view
        returns (uint256)
    {
        uint256 timePassed = block.timestamp - $.lastOnChainDistributionTimestamp;
        if (timePassed <= DISTRIBUTION_FREQUENCY_SCALAR || $.lastOnChainDistributionTimestamp == 0)
        {
            return Math.mulDiv($.baseGamma, SCALAR_ONE, BPS_SCALAR, Math.Rounding.Floor);
        }
        uint256 denominator =
            Math.mulDiv(SCALAR_ONE, timePassed, DISTRIBUTION_FREQUENCY_SCALAR, Math.Rounding.Floor);
        uint256 numerator = Math.mulDiv($.baseGamma, SCALAR_ONE, BPS_SCALAR, Math.Rounding.Floor);
        return Math.mulDiv(numerator, SCALAR_ONE, denominator, Math.Rounding.Floor);
    }

    /// @notice Calculates the UsualDist value
    /// @dev Raw equation: UsualDist = (d * Mt * supplyPpt * pt) / (365 days)
    /// @param mt Mt value (scaled by SCALAR_ONE)
    /// @param supplyPpt Current supply (scaled by SCALAR_ONE)
    /// @param pt Current price (scaled by SCALAR_ONE)
    /// @return UsualDist value (raw, not scaled)
    function _calculateDistribution(uint256 mt, uint256 supplyPpt, uint256 pt)
        internal
        view
        returns (uint256)
    {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        uint256 totalSupply = _calculateTotalSupply(supplyPpt);
        // NOTE: d has BPS precision
        uint256 result = Math.mulDiv($.d, mt, BPS_SCALAR, Math.Rounding.Floor); // scales mt by BPS_SCALAR then divides by BPS_SCALAR to keep the same scale
        result = Math.mulDiv(result, totalSupply, SCALAR_ONE, Math.Rounding.Floor); // 10**18 * 10**18 / 10**18 = 10**18
        result = Math.mulDiv(result, pt, SCALAR_ONE, Math.Rounding.Floor); // 10**18 * 10**18 / 10**18 = 10**18

        return Math.mulDiv(result, 1, 365, Math.Rounding.Floor);
    }

    /// @notice Returns the price of usd0 token
    /// @dev $1 unless CBR is on
    /// @param $ Storage struct of the contract
    function _getUSD0Price(DistributionModuleStorageV0 storage $) internal view returns (uint256) {
        if ($.daoCollateral.isCBROn()) {
            uint256 cbr = $.daoCollateral.cbrCoef();
            return Math.mulDiv(SCALAR_ONE, cbr, SCALAR_ONE, Math.Rounding.Floor);
        }
        return SCALAR_ONE;
    }

    /// @notice Calculates the Rt value
    /// @param $ Storage struct of the contract
    /// @param ratet Current rate in BPS
    /// @param p90Rate 90th percentile rate (scaled by BPS_SCALAR)
    /// @return Rt value (scaled by SCALAR_ONE)
    function _calculateRt(DistributionModuleStorageV0 storage $, uint256 ratet, uint256 p90Rate)
        internal
        view
        returns (uint256)
    {
        uint256 maxRate = ratet > $.rateMin ? ratet : $.rateMin; // scaled by 10_000
        uint256 minMaxRate = p90Rate < maxRate ? p90Rate : maxRate; // scaled by 10_000
        uint256 result = Math.mulDiv(SCALAR_ONE, minMaxRate, $.rate0, Math.Rounding.Floor); // scales minMaxRate by BPS_SCALAR then divides by $.rate0 to keep the same scale
        return result;
    }

    /// @notice Calculates the St value
    /// @param $ Storage struct of the contract
    /// @param supplyUSD0PP Current supply (scaled by SCALAR_ONE)
    /// @param pt Current price (scaled by SCALAR_ONE)
    /// @return St value (scaled by SCALAR_ONE)
    function _calculateSt(DistributionModuleStorageV0 storage $, uint256 supplyUSD0PP, uint256 pt)
        internal
        view
        returns (uint256)
    {
        uint256 totalSupply = _calculateTotalSupply(supplyUSD0PP);
        // NOTE: everything has 10^18 precision
        uint256 numerator = Math.mulDiv($.initialSupplyPp0, $.p0, SCALAR_ONE); // scaled by 10**18 * 10**18 / 10**18 = 10**18
        uint256 denominator = Math.mulDiv(totalSupply, pt, SCALAR_ONE); // scaled by 10**18 * 10**18 / 10**18 = 10**18
        // NOTE: Good up to 10_000_000_000_000 supply, 10_000_000_000 price, with 10**18 precision
        // NOTE: (2^256-1) > (10000000000000*10**18)*(10000000000*10**18)*10**18
        uint256 result = Math.mulDiv(SCALAR_ONE, numerator, denominator, Math.Rounding.Floor); // scales numerator by 10**18 then divides by 10**18 to keep the same scale

        return result < SCALAR_ONE ? result : SCALAR_ONE;
    }

    /// @notice Calculates the Kappa value
    /// @param $ Storage struct of the contract
    /// @param ratet Current rate in BPS
    /// @return Kappa value (scaled by SCALAR_ONE)
    function _calculateKappa(DistributionModuleStorageV0 storage $, uint256 ratet)
        internal
        view
        returns (uint256)
    {
        uint256 maxRate = ratet > $.rateMin ? ratet : $.rateMin; // scaled by 10_000
        uint256 numerator = Math.mulDiv($.m0, maxRate, BPS_SCALAR); // scaled by 10**18 * 10_000 /10_000 = 10**18
        uint256 denominator = Math.mulDiv(_calculateGamma($), $.rate0, BPS_SCALAR); // scaled by 10**18 * 10**5 / 10**5 = 10**18
        return Math.mulDiv(numerator, SCALAR_ONE, denominator, Math.Rounding.Floor); // scales numerator 10*18 then divides to keep 10**18 scale
    }

    /// @notice Calculates the Mt value
    /// @param $ Storage struct of the contract
    /// @param st St value (scaled by SCALAR_ONE)
    /// @param rt Rt value (scaled by SCALAR_ONE)
    /// @param kappa Kappa value (scaled by SCALAR_ONE)
    /// @return Mt value (scaled by SCALAR_ONE)
    function _calculateMt(
        DistributionModuleStorageV0 storage $,
        uint256 st,
        uint256 rt,
        uint256 kappa
    ) internal view returns (uint256) {
        // (10*10**18*) * 10**18 = 10**37
        uint256 numerator = Math.mulDiv($.m0, st, SCALAR_ONE, Math.Rounding.Floor); // scaled by 10**18 * 10**18 / 10**18 = 10**18
        numerator = Math.mulDiv(numerator, rt, SCALAR_ONE, Math.Rounding.Floor); // scaled by 10**18 * 10**18 / 10**18 = 10**18
        uint256 result = Math.mulDiv(numerator, SCALAR_ONE, _calculateGamma($)); // scales numerator by 10**18  then divides by 10**18  to keep the same scale
        return result < kappa ? result : kappa;
    }

    /// @notice Calculates total supply including both USD0++ and vault value
    /// @param usd0ppSupply Current USD0++ supply
    /// @return Total supply equivalent in USD with 18 decimals precision
    function _calculateTotalSupply(uint256 usd0ppSupply) internal view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();

        return usd0ppSupply + _calculateVaultValueInUSD($);
    }

    /// @notice Calculates the USD value of assets in the vault
    /// @param $ Storage struct of the contract
    /// @return vaultValueUSD The USD value of assets in the vault with 18 decimals precision
    function _calculateVaultValueInUSD(DistributionModuleStorageV0 storage $)
        internal
        view
        returns (uint256 vaultValueUSD)
    {
        // If vault not set, return 0
        if (address($.iUsd0ppVault) == address(0)) {
            return 0;
        }
        uint256 iUsd0ppPrice;
        try $.oracle.getPrice(address($.iUsd0ppVault)) returns (uint256 price) {
            iUsd0ppPrice = price;
        } catch {
            // If the oracle call reverts, set iUsd0ppPrice to 0
            iUsd0ppPrice = 0;
        }

        uint256 totalAssets = $.iUsd0ppVault.totalAssets();

        // Check if the price is valid before calculating vaultValueUSD
        if (iUsd0ppPrice > 0) {
            // Correctly scale the result to 18 decimals
            vaultValueUSD = (totalAssets * iUsd0ppPrice)
                / 10 ** IERC20Metadata($.iUsd0ppVault.asset()).decimals();
        } else {
            // If the oracle call reverts, we treat the vault as empty
            vaultValueUSD = 0;
        }
    }

    /// @notice Calculates all values: St, Rt, Mt, and UsualDist
    /// @param ratet The current interest rate with BPS precision
    /// @param p90Rate The 90th percentile interest rate over the last 60 days with BPS precision
    /// @return st St value (scaled by SCALAR_ONE)
    /// @return rt Rt value (scaled by SCALAR_ONE)
    /// @return kappa Kappa value (scaled by SCALAR_ONE)
    /// @return mt Mt value (scaled by SCALAR_ONE)
    /// @return usualDist UsualDist value (raw, not scaled)
    function _calculateUsualDistribution(
        DistributionModuleStorageV0 storage $,
        uint256 ratet,
        uint256 p90Rate
    )
        internal
        view
        returns (uint256 st, uint256 rt, uint256 kappa, uint256 mt, uint256 usualDist)
    {
        uint256 currentSupplyUsd0PP = $.usd0PP.totalSupply();
        uint256 pt = _getUSD0Price($);

        st = _calculateSt($, currentSupplyUsd0PP, pt);
        rt = _calculateRt($, ratet, p90Rate);
        kappa = _calculateKappa($, ratet);
        mt = _calculateMt($, st, rt, kappa);
        usualDist = _calculateDistribution(mt, currentSupplyUsd0PP, pt);
    }

    /// @notice Verifies the off-chain distribution Merkle proof
    /// @param $ Storage struct of the contract
    /// @param account Account to claim for
    /// @param amount Amount of Usual token to claim
    /// @param proof Merkle proof
    function _verifyOffChainDistributionMerkleProof(
        DistributionModuleStorageV0 storage $,
        address account,
        uint256 amount,
        bytes32[] calldata proof
    ) internal view returns (bool) {
        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(account, amount))));
        return MerkleProof.verify(proof, $.offChainDistributionMerkleRoot, leaf);
    }

    /// @notice Updates the iUSD0++ distribution share based on current supply ratios
    /// @dev This should be called before distribution calculations to ensure up-to-date share
    /// @param $ Storage struct of the contract
    function _updateiUsd0ppDistributionShare(DistributionModuleStorageV0 storage $) internal {
        uint256 currentSupplyUsd0PP = $.usd0PP.totalSupply();
        uint256 adjustedIUsd0ppSupply = _calculateVaultValueInUSD($);
        // Calculate iUSD0++ Share share using the iUSD0++ share factor and LBT portion
        uint256 iUSD0ppShare = _calculateiUSD0ppShare(adjustedIUsd0ppSupply, currentSupplyUsd0PP);

        // Update the iUSD0++ distribution share
        if ($.iUSD0ppDistributionShareOfLbt != iUSD0ppShare) {
            $.iUSD0ppDistributionShareOfLbt = iUSD0ppShare;
            emit ParameterUpdated("iUSD0ppDistributionShareOfLbt", iUSD0ppShare);
        }
    }

    /// @notice Calculates the iUSD0++ share of the distribution
    /// @param adjustediUSD0ppSupply The adjusted supply from iUSD0++ vault
    /// @param supplyPpt The total USD0++ supply
    /// @return iUSD0ppShare The calculated share for iUSD0++ with 18 decimal place precision
    /// @dev Share calculation: adjusted_iUSD0++_supply/(supplyPp_t+adjusted_iUSD0++_supply)
    function _calculateiUSD0ppShare(uint256 adjustediUSD0ppSupply, uint256 supplyPpt)
        internal
        pure
        returns (uint256 iUSD0ppShare)
    {
        // If no iUSD0++ supply, return 0
        if (adjustediUSD0ppSupply == 0) {
            return 0;
        }

        // Calculate iUSD0++ share of LBT: adjusted_iUSD0++_supply[i]/(supplyPp_t[i]+adjusted_iUSD0++_supply[i])
        iUSD0ppShare = Math.mulDiv(
            adjustediUSD0ppSupply,
            SCALAR_ONE,
            supplyPpt + adjustediUSD0ppSupply,
            Math.Rounding.Floor
        );
    }

    /// @notice Gets the current iUSD0++ distribution share of LBT
    /// @return The current iUSD0++ distribution share with 18 decimals precision
    /// @dev This value represents what portion of the LBT distribution should go to iUSD0++ holders
    function getiUSD0ppDistributionShareOfLbt() external view returns (uint256) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return $.iUSD0ppDistributionShareOfLbt;
    }

    /// @inheritdoc IDistributionModule
    function getIUsd0ppVault() external view returns (address) {
        DistributionModuleStorageV0 storage $ = _distributionModuleStorageV0();
        return address($.iUsd0ppVault);
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

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

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

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

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

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

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

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

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

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

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

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

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

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

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

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

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

lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

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

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

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

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

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

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

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

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlDefaultAdminRules.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev External interface of AccessControlDefaultAdminRules declared to support ERC165 detection.
 */
interface IAccessControlDefaultAdminRules is IAccessControl {
    /**
     * @dev The new default admin is not a valid default admin.
     */
    error AccessControlInvalidDefaultAdmin(address defaultAdmin);

    /**
     * @dev At least one of the following rules was violated:
     *
     * - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
     * - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
     * - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
     */
    error AccessControlEnforcedDefaultAdminRules();

    /**
     * @dev The delay for transferring the default admin delay is enforced and
     * the operation must wait until `schedule`.
     *
     * NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
     */
    error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);

    /**
     * @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
     * address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
     * passes.
     */
    event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
     */
    event DefaultAdminTransferCanceled();

    /**
     * @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
     * delay to be applied between default admin transfer after `effectSchedule` has passed.
     */
    event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
     */
    event DefaultAdminDelayChangeCanceled();

    /**
     * @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
     */
    function defaultAdmin() external view returns (address);

    /**
     * @dev Returns a tuple of a `newAdmin` and an accept schedule.
     *
     * After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
     * by calling {acceptDefaultAdminTransfer}, completing the role transfer.
     *
     * A zero value only in `acceptSchedule` indicates no pending admin transfer.
     *
     * NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
     */
    function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);

    /**
     * @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
     *
     * This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
     * the acceptance schedule.
     *
     * NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
     * function returns the new delay. See {changeDefaultAdminDelay}.
     */
    function defaultAdminDelay() external view returns (uint48);

    /**
     * @dev Returns a tuple of `newDelay` and an effect schedule.
     *
     * After the `schedule` passes, the `newDelay` will get into effect immediately for every
     * new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
     *
     * A zero value only in `effectSchedule` indicates no pending delay change.
     *
     * NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
     * will be zero after the effect schedule.
     */
    function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
     * after the current timestamp plus a {defaultAdminDelay}.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a DefaultAdminRoleChangeStarted event.
     */
    function beginDefaultAdminTransfer(address newAdmin) external;

    /**
     * @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a DefaultAdminTransferCanceled event.
     */
    function cancelDefaultAdminTransfer() external;

    /**
     * @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * After calling the function:
     *
     * - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
     * - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
     * - {pendingDefaultAdmin} should be reset to zero values.
     *
     * Requirements:
     *
     * - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
     * - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
     */
    function acceptDefaultAdminTransfer() external;

    /**
     * @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
     * into effect after the current timestamp plus a {defaultAdminDelay}.
     *
     * This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
     * method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
     * set before calling.
     *
     * The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
     * calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
     * complete transfer (including acceptance).
     *
     * The schedule is designed for two scenarios:
     *
     * - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
     * {defaultAdminDelayIncreaseWait}.
     * - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
     *
     * A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event.
     */
    function changeDefaultAdminDelay(uint48 newDelay) external;

    /**
     * @dev Cancels a scheduled {defaultAdminDelay} change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a DefaultAdminDelayChangeCanceled event.
     */
    function rollbackDefaultAdminDelay() external;

    /**
     * @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
     * to take effect. Default to 5 days.
     *
     * When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
     * the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
     * that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
     * be overrode for a custom {defaultAdminDelay} increase scheduling.
     *
     * IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
     * there's a risk of setting a high new delay that goes into effect almost immediately without the
     * possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
     */
    function defaultAdminDelayIncreaseWait() external view returns (uint48);
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol

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

pragma solidity ^0.8.20;

/**
 * @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.
 */
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.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     */
    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 leafs & pre-images are assumed to be sorted.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(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}.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     */
    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.
     *
     * 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).
     */
    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 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proofLen != totalHashes + 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[](totalHashes);
        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 < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

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

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     */
    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 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proofLen != totalHashes + 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[](totalHashes);
        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 < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

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

    /**
     * @dev Sorts the pair (a, b) and hashes the result.
     */
    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

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

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

src/constants.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

/* Roles */
bytes32 constant DEFAULT_ADMIN_ROLE = 0x00;
bytes32 constant PAUSING_CONTRACTS_ROLE = keccak256("PAUSING_CONTRACTS_ROLE");
bytes32 constant EARLY_BOND_UNLOCK_ROLE = keccak256("EARLY_BOND_UNLOCK_ROLE");
bytes32 constant BLACKLIST_ROLE = keccak256("BLACKLIST_ROLE");
bytes32 constant WHITELIST_ROLE = keccak256("WHITELIST_ROLE");
bytes32 constant WITHDRAW_FEE_UPDATER_ROLE = keccak256("WITHDRAW_FEE_UPDATER_ROLE");
bytes32 constant FEE_SWEEPER_ROLE = keccak256("FEE_SWEEPER_ROLE");
bytes32 constant FLOOR_PRICE_UPDATER_ROLE = keccak256("FLOOR_PRICE_UPDATER_ROLE");
bytes32 constant DAO_COLLATERAL = keccak256("DAO_COLLATERAL_CONTRACT");
bytes32 constant USUALSP = keccak256("USUALSP_CONTRACT");
bytes32 constant USD0_MINT = keccak256("USD0_MINT");
bytes32 constant USD0_BURN = keccak256("USD0_BURN");
bytes32 constant USD0PP_MINT = keccak256("USD0PP_MINT");
bytes32 constant USD0PP_BURN = keccak256("USD0PP_BURN");
bytes32 constant USUALS_BURN = keccak256("USUALS_BURN");
bytes32 constant USUAL_MINT = keccak256("USUAL_MINT");
bytes32 constant USUAL_BURN = keccak256("USUAL_BURN");
bytes32 constant USUALX_MINT = keccak256("USUALX_MINT");
bytes32 constant USUALX_BURN = keccak256("USUALX_BURN");
bytes32 constant INTENT_MATCHING_ROLE = keccak256("INTENT_MATCHING_ROLE");
bytes32 constant NONCE_THRESHOLD_SETTER_ROLE = keccak256("NONCE_THRESHOLD_SETTER_ROLE");
bytes32 constant PEG_MAINTAINER_ROLE = keccak256("PEG_MAINTAINER_ROLE");
bytes32 constant PEG_MAINTAINER_UNLIMITED_ROLE = keccak256("PEG_MAINTAINER_UNLIMITED_ROLE");
bytes32 constant USD0PP_CAPPED_UNWRAP_ROLE = keccak256("USD0PP_CAPPED_UNWRAP_ROLE");
bytes32 constant UNWRAP_CAP_ALLOCATOR_ROLE = keccak256("UNWRAP_CAP_ALLOCATOR_ROLE");
bytes32 constant FEE_RATE_SETTER_ROLE = keccak256("FEE_RATE_SETTER_ROLE");
bytes32 constant VAULT_UPDATER_ROLE = keccak256("VAULT_UPDATER_ROLE");
bytes32 constant SWAPPER_ENGINE = keccak256("SWAPPER_ENGINE");
bytes32 constant INTENT_TYPE_HASH = keccak256(
    "SwapIntent(address recipient,address rwaToken,uint256 amountInTokenDecimals,uint256 nonce,uint256 deadline)"
);
bytes32 constant DISTRIBUTION_ALLOCATOR_ROLE = keccak256("DISTRIBUTION_ALLOCATOR_ROLE");
bytes32 constant DISTRIBUTION_OPERATOR_ROLE = keccak256("DISTRIBUTION_OPERATOR_ROLE");
bytes32 constant DISTRIBUTION_CHALLENGER_ROLE = keccak256("DISTRIBUTION_CHALLENGER_ROLE");
bytes32 constant USD0PP_USUAL_DISTRIBUTION_ROLE = keccak256("USD0PP_USUAL_DISTRIBUTION_ROLE");
bytes32 constant USD0PP_DURATION_COST_FACTOR_ROLE = keccak256("USD0PP_DURATION_COST_FACTOR_ROLE");
bytes32 constant USD0PP_TREASURY_ALLOCATION_RATE_ROLE =
    keccak256("USD0PP_TREASURY_ALLOCATION_RATE_ROLE");
bytes32 constant USD0PP_TARGET_REDEMPTION_RATE_ROLE =
    keccak256("USD0PP_TARGET_REDEMPTION_RATE_ROLE");
bytes32 constant REDIRECTION_ADMIN_ROLE = keccak256("REDIRECTION_ADMIN_ROLE");
/* Airdrop Roles */
bytes32 constant AIRDROP_OPERATOR_ROLE = keccak256("AIRDROP_OPERATOR_ROLE");
bytes32 constant AIRDROP_PENALTY_OPERATOR_ROLE = keccak256("AIRDROP_PENALTY_OPERATOR_ROLE");
bytes32 constant USUALSP_OPERATOR_ROLE = keccak256("USUALSP_OPERATOR_ROLE");
bytes32 constant YIELD_MODULE_TOKENOMICS_OPERATOR_ROLE =
    keccak256("YIELD_MODULE_TOKENOMICS_OPERATOR_ROLE");
bytes32 constant YIELD_MODULE_SUPER_ADMIN_ROLE = keccak256("YIELD_MODULE_SUPER_ADMIN_ROLE");
bytes32 constant YIELD_MODULE_P90_INTEREST_ROLE = keccak256("YIELD_MODULE_P90_INTEREST_ROLE");
bytes32 constant YIELD_MODULE_MAX_DATA_AGE_ROLE = keccak256("YIELD_MODULE_MAX_DATA_AGE_ROLE");
bytes32 constant YIELD_MODULE_UPDATER_ROLE = keccak256("YIELD_MODULE_UPDATER_ROLE");
/* Contracts */
bytes32 constant CONTRACT_REGISTRY_ACCESS = keccak256("CONTRACT_REGISTRY_ACCESS");
bytes32 constant CONTRACT_DAO_COLLATERAL = keccak256("CONTRACT_DAO_COLLATERAL");
bytes32 constant CONTRACT_USD0PP = keccak256("CONTRACT_USD0PP");
bytes32 constant CONTRACT_USUALS = keccak256("CONTRACT_USUALS");
bytes32 constant CONTRACT_USUALSP = keccak256("CONTRACT_USUALSP");
bytes32 constant CONTRACT_TOKEN_MAPPING = keccak256("CONTRACT_TOKEN_MAPPING");
bytes32 constant CONTRACT_ORACLE = keccak256("CONTRACT_ORACLE");
bytes32 constant CONTRACT_ORACLE_USUAL = keccak256("CONTRACT_ORACLE_USUAL");
bytes32 constant CONTRACT_DATA_PUBLISHER = keccak256("CONTRACT_DATA_PUBLISHER");
bytes32 constant CONTRACT_TREASURY = keccak256("CONTRACT_TREASURY");
bytes32 constant CONTRACT_YIELD_TREASURY = keccak256("CONTRACT_YIELD_TREASURY");
bytes32 constant CONTRACT_SWAPPER_ENGINE = keccak256("CONTRACT_SWAPPER_ENGINE");
bytes32 constant CONTRACT_AIRDROP_DISTRIBUTION = keccak256("CONTRACT_AIRDROP_DISTRIBUTION");
bytes32 constant CONTRACT_AIRDROP_TAX_COLLECTOR = keccak256("CONTRACT_AIRDROP_TAX_COLLECTOR");
bytes32 constant CONTRACT_DISTRIBUTION_MODULE = keccak256("CONTRACT_DISTRIBUTION_MODULE");
bytes32 constant CONTRACT_YIELD_MODULE = keccak256("CONTRACT_YIELD_MODULE");

/* Registry */
bytes32 constant CONTRACT_REGISTRY = keccak256("CONTRACT_REGISTRY"); // Not set on production

/* Contract tokens */
bytes32 constant CONTRACT_USD0 = keccak256("CONTRACT_USD0");
bytes32 constant CONTRACT_USUAL = keccak256("CONTRACT_USUAL");
bytes32 constant CONTRACT_USDC = keccak256("CONTRACT_USDC");
bytes32 constant CONTRACT_USUALX = keccak256("CONTRACT_USUALX");

/* Token names and symbols */
string constant USUALSSymbol = "USUAL*";
string constant USUALSName = "USUAL Star";

string constant USUALSymbol = "USUAL";
string constant USUALName = "USUAL";

string constant USUALXSymbol = "USUALX";
string constant USUALXName = "USUALX";

/* Constants */
uint256 constant INITIAL_SHARES_MINTING = 10_000e18; // For now, we mint "dead" shares has we started distribution early. This constant will be used to initialize the contract with the correct amount.
uint256 constant SCALAR_ONE = 1e18;
uint256 constant BPS_SCALAR = 10_000; // 10000 basis points = 100%
uint256 constant DISTRIBUTION_FREQUENCY_SCALAR = 1 days;

uint256 constant SCALAR_TEN_KWEI = 10_000;
uint256 constant MAX_REDEEM_FEE = 2500;
uint256 constant MINIMUM_USDC_PROVIDED = 100e6; //minimum of 100 USDC deposit;
// we take 12sec as the average block time
// 1 year = 3600sec * 24 hours * 365 days * 4 years  = 126_144_000 + 1 day // adding a leap day
uint256 constant BOND_DURATION_FOUR_YEAR = 126_230_400; //including a leap day;
uint256 constant USUAL_DISTRIBUTION_CHALLENGE_PERIOD = 1 weeks;
uint256 constant BASIS_POINT_BASE = 10_000;

uint256 constant VESTING_DURATION_THREE_YEARS = 94_608_000; // 3 years
uint256 constant USUALSP_VESTING_STARTING_DATE = 1_732_530_600; // Mon Nov 25 2024 10:30:00 GMT+0000
uint256 constant STARTDATE_USUAL_CLAIMING_USUALSP = 1_764_066_600; // Tue Nov 25 2025 10:30:00 GMT+0000

uint256 constant STARTDATE_USUAL_CLAIMING_DISTRIBUTION_MODULE = 1_734_516_000; // Dec 18 2024 10:00:00  GMT+0000
uint256 constant AIRDROP_INITIAL_START_TIME = 1_734_516_000; // Dec 18 2024 10:00:00  GMT+0000

uint256 constant AIRDROP_VESTING_DURATION_IN_MONTHS = 6;
uint256 constant ONE_YEAR = 31_536_000; // 365 days
uint256 constant SIX_MONTHS = 15_768_000;
uint256 constant ONE_MONTH = 2_628_000; // ONE_YEAR / 12 = 30,4 days
uint64 constant ONE_WEEK = 604_800;
uint256 constant NUMBER_OF_MONTHS_IN_THREE_YEARS = 36;
uint256 constant END_OF_EARLY_UNLOCK_PERIOD = 1_735_686_000; // 31st Dec 2024 23:00:00 GMT+0000
uint256 constant FIRST_AIRDROP_VESTING_CLAIMING_DATE = 1_737_194_400; // 18th Jan 2025 10:00:00 GMT+0000
uint256 constant SECOND_AIRDROP_VESTING_CLAIMING_DATE = 1_739_872_800; // 18th Feb 2025 10:00:00 GMT+0000
uint256 constant THIRD_AIRDROP_VESTING_CLAIMING_DATE = 1_742_292_000; // 18th Mar 2025 10:00:00 GMT+0000
uint256 constant FOURTH_AIRDROP_VESTING_CLAIMING_DATE = 1_744_970_400; // 18th Apr 2025 10:00:00 GMT+0000
uint256 constant FIFTH_AIRDROP_VESTING_CLAIMING_DATE = 1_747_562_400; // 18th May 2025 10:00:00 GMT+0000
uint256 constant SIXTH_AIRDROP_VESTING_CLAIMING_DATE = 1_750_240_800; // 18th Jun 2025 10:00:00 GMT+0000

uint256 constant INITIAL_FLOOR_PRICE = 999_500_000_000_000_000; // 1 USD0++ = 0.9995 USD0

/* UsualX initial withdraw fee */
uint256 constant USUALX_WITHDRAW_FEE = 1000; // in BPS 10%

/* Usual Distribution Bucket Distribution Shares */
uint256 constant LBT_DISTRIBUTION_SHARE = 3552;
uint256 constant LYT_DISTRIBUTION_SHARE = 1026; // USD0/USD0++ AND USD0/USDC summed up
uint256 constant IYT_DISTRIBUTION_SHARE = 0;
uint256 constant BRIBE_DISTRIBUTION_SHARE = 346;
uint256 constant ECO_DISTRIBUTION_SHARE = 0;
uint256 constant DAO_DISTRIBUTION_SHARE = 1620;
uint256 constant MARKET_MAKERS_DISTRIBUTION_SHARE = 0;
uint256 constant USUALX_DISTRIBUTION_SHARE = 1728;
uint256 constant USUALSTAR_DISTRIBUTION_SHARE = 1728;
uint256 constant INITIAL_BASE_GAMMA = 7894; // 78.94

uint256 constant ONE_USDC = 1e6;
uint256 constant MAX_25_PERCENT_WITHDRAW_FEE = 2500; // 25% fee
uint256 constant YIELD_PRECISION = 1 days;

uint256 constant USUALS_TOTAL_SUPPLY = 360_000_000e18;
uint256 constant PRICE_TIMEOUT = 7 days;

address constant SUSDE_CHAINLINK_PRICE_ORACLE = 0xFF3BC18cCBd5999CE63E788A1c250a88626aD099;
uint256 constant CHAINLINK_PRICE_SCALAR = 1e8;

/* Usual burn initial parameters */
uint256 constant INITIAL_USUAL_BURN_DURATION_COST_FACTOR = 180; // 180 days (6 months)
uint256 constant INITIAL_USUAL_BURN_TARGET_REDEMPTION_RATE = 30; // 0.3% in basis points
uint256 constant INITIAL_USUAL_BURN_USUAL_DISTRIBUTION_PER_USD0PP = 9e14; // 0.0009 Usual per USD0PP
uint256 constant USD0PP_NET_OUTFLOWS_ROLLING_WINDOW_DAYS = 7; // 7 days

/* Yield Module */
uint256 constant INITIAL_YIELD_MODULE_MAX_DATA_AGE = 14 days;
uint256 constant DEFAULT_YIELD_FEED_RATE = 0;
/* DistributionModule initial fee rates */
uint256 constant INITIAL_TREASURY_FEE_RATE = 9999; // 99.99% in basis points
uint256 constant INITIAL_USUALX_FEE_RATE = 1; // 0.01% in basis points

/* Token Addresses */
address constant USYC = 0x136471a34f6ef19fE571EFFC1CA711fdb8E49f2b;
address constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address constant USUAL_M = 0x4Cbc25559DbBD1272EC5B64c7b5F48a2405e6470;

/*
 * The maximum relative price difference between two oracle responses allowed in order for the PriceFeed
 * to return to using the Oracle oracle. 18-digit precision.
 */

uint256 constant INITIAL_MAX_DEPEG_THRESHOLD = 100;

/* Maximum number of RWA tokens that can be associated with USD0 */
uint256 constant MAX_RWA_COUNT = 10;

/* Curvepool Addresses */
address constant CURVE_POOL_USD0_USD0PP = 0x1d08E7adC263CfC70b1BaBe6dC5Bb339c16Eec52;
int128 constant CURVE_POOL_USD0_USD0PP_INTEGER_FOR_USD0 = 0;
int128 constant CURVE_POOL_USD0_USD0PP_INTEGER_FOR_USD0PP = 1;

/* Airdrop */

uint256 constant AIRDROP_CLAIMING_PERIOD_LENGTH = 182 days;

/* Distribution */
uint256 constant RATE0 = 400; // 4.00% in basis points
uint256 constant REDIRECTION_DISTRIBUTION_CHALLENGE_PERIOD = 5 days;

/* Hexagate */
address constant HEXAGATE_PAUSER = 0x114644925eD9A6Ab20bF85f36F1a458DF181b57B;

/* Mainnet Usual Deployment */
address constant USUAL_MULTISIG_MAINNET = 0x6e9d65eC80D69b1f508560Bc7aeA5003db1f7FB7;
address constant USUAL_PROXY_ADMIN_MAINNET = 0xaaDa24358620d4638a2eE8788244c6F4b197Ca16;
address constant REGISTRY_CONTRACT_MAINNET = 0x0594cb5ca47eFE1Ff25C7B8B43E221683B4Db34c;
address constant USUALX_REDISTRIBUTION_CONTRACT = 0x351B2AFa5C8e5Ff0644Fef2bEE5cA2B8Df56715A;
address constant TREASURY_MAINNET = 0xdd82875f0840AAD58a455A70B88eEd9F59ceC7c7;

src/errors.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

error AlreadyClaimed();
error NothingToClaim();
error AlreadyWhitelisted();
error AmountTooBig();
error AmountTooLow();
error AmountIsZero();
error Blacklisted();

error ExpiredSignature(uint256 deadline);
error SameValue();

error Invalid();
error InvalidInput();
error InvalidToken();
error InvalidName();
error InvalidSigner(address owner);
error InvalidDeadline(uint256 approvalDeadline, uint256 intentDeadline);
error NoOrdersIdsProvided();
error InvalidSymbol();
error InvalidInputArraysLength();
error InvalidRates();

error NotAuthorized();
error NotClaimableYet();
error NullAddress();
error NullContract();

error OracleNotWorkingNotCurrent();
error OracleNotInitialized();
error OutOfBounds();
error InvalidTimeout();

error RedeemMustNotBePaused();
error RedeemMustBePaused();
error SwapMustNotBePaused();
error SwapMustBePaused();

error StablecoinDepeg();
error DepegThresholdTooHigh();

error BondNotStarted();
error BondFinished();
error BondNotFinished();

error CliffBiggerThanDuration();

error BeginInPast();
error EndTimeBeforeStartTime();
error StartTimeInPast();
error AlreadyStarted();
error CBRIsTooHigh();
error CBRIsNull();

error RedeemFeeTooBig();
error TooManyRWA();

error InsufficientUSD0Balance();
error InsufficientUsualSLiquidAllocation();
error CannotReduceAllocation();
error OrderNotActive();
error NotRequester();
error ApprovalFailed();

error AmountExceedBacking();
error InvalidOrderAmount(address account, uint256 amount);
error PARNotRequired();
error PARNotSuccessful();
error PARUSD0InputExceedsBalance();

error NullMerkleRoot();
error InvalidProof();

error PercentagesSumNotEqualTo100Percent();
error CannotDistributeUsualMoreThanOnceADay();
error NoOffChainDistributionToApprove();
error NoTokensToClaim();

error InvalidOrderId(uint80 roundId);
error NotOwner();
error InvalidClaimingPeriodStartDate();
error InvalidMaxChargeableTax();
error NotInClaimingPeriod();
error ClaimerHasPaidTax();

error ZeroYieldAmount();
error StartTimeNotInFuture();
error StartTimeBeforePeriodFinish();
error CurrentTimeBeforePeriodFinish();
error EndTimeNotAfterStartTime();
error InsufficientAssetsForYield();
error InsufficientAssets();
error InsufficientSupply();

error NotPermittedToEarlyUnlock();
error OutsideEarlyUnlockTimeframe();
error AirdropVoided();
error FloorPriceTooHigh();
error AmountMustBeGreaterThanZero();
error InsufficientUsd0ppBalance();
error UsualAmountTooLow();
error UsualAmountIsZero();
error FloorPriceNotSet();
error UnwrapCapNotSet();
error AmountTooBigForCap();

error StalePrice();
error InvalidPrice();

error YieldSourceNotFound();
error YieldSourceDataTooOld();
error YieldSourceAlreadyExists();
error MaxDataAgeZero();
error InvalidFeed();
error OffChainDistributionRedirectTimeIntervalNotPassed();
error NoInitiatedRedirectedOffChainDistribution();
error AlreadyInitiatedRedirectedOffChainDistribution();
error AlreadyRedirectedOffChainDistribution();
error NoActiveRedirectedOffChainDistribution();

error InvalidWeeklyInterestBps();
error TreasuryAlreadyExists();
error TreasuryNotFound();

src/interfaces/IDaoCollateral.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

struct Approval {
    uint256 deadline;
    uint8 v; // Changes at each new signature because of ERC20 Permit nonce
    bytes32 r;
    bytes32 s;
}

struct Intent {
    address recipient;
    address rwaToken;
    uint256 amountInTokenDecimals;
    uint256 deadline;
    bytes signature;
}

interface IDaoCollateral {
    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Emitted when tokens are swapped.
    /// @param owner The address of the owner
    /// @param tokenSwapped The address of the token swapped
    /// @param amount The amount of tokens swapped
    /// @param amountInUSD The amount in USD
    event Swap(
        address indexed owner, address indexed tokenSwapped, uint256 amount, uint256 amountInUSD
    );

    /// @notice Emitted when tokens are redeemed.
    /// @param redeemer The address of the redeemer
    /// @param rwaToken The address of the rwaToken
    /// @param amountRedeemed The amount of tokens redeemed
    /// @param returnedRwaAmount The amount of rwaToken returned
    /// @param stableFeeAmount The amount of stableToken fee
    event Redeem(
        address indexed redeemer,
        address indexed rwaToken,
        uint256 amountRedeemed,
        uint256 returnedRwaAmount,
        uint256 stableFeeAmount
    );

    /// @notice Emitted when an intent is matched.
    /// @param owner The address of the owner
    /// @param nonce The nonce of the intent
    /// @param tokenSwapped The address of the token swapped
    /// @param amountInTokenDecimals The amount in token decimals
    /// @param amountInUSD The amount in USD
    event IntentMatched(
        address indexed owner,
        uint256 indexed nonce,
        address indexed tokenSwapped,
        uint256 amountInTokenDecimals,
        uint256 amountInUSD
    );

    /// @notice Emitted when an intent and associated nonce is consumed.
    /// @param owner The address of the owner
    /// @param nonce The nonce of the intent
    /// @param tokenSwapped The address of the token swapped
    /// @param totalAmountInTokenDecimals The total amount in token decimals
    event IntentConsumed(
        address indexed owner,
        uint256 indexed nonce,
        address indexed tokenSwapped,
        uint256 totalAmountInTokenDecimals
    );

    /// @notice Emitted when a nonce is invalidated.
    /// @param signer The address of the signer
    /// @param nonceInvalidated The nonce of the intent
    event NonceInvalidated(address indexed signer, uint256 indexed nonceInvalidated);

    /// @notice Emitted when redeem functionality is paused.
    event RedeemPaused();

    /// @notice Emitted when redeem functionality is unpaused.
    event RedeemUnPaused();

    /// @notice Emitted when swap functionality is paused.
    event SwapPaused();

    /// @notice Emitted when swap functionality is unpaused.
    event SwapUnPaused();

    /// @notice Emitted when the Counter Bank Run (CBR) mechanism is activated.
    /// @param cbrCoef The Counter Bank Run (CBR) coefficient.
    event CBRActivated(uint256 cbrCoef);

    /// @notice Emitted when the Counter Bank Run (CBR) mechanism is deactivated.
    event CBRDeactivated();

    /// @notice Emitted when the redeem fee is updated.
    /// @param redeemFee The new redeem fee.
    event RedeemFeeUpdated(uint256 redeemFee);

    /// @notice Emitted when the nonce threshold is set.
    /// @param newThreshold The new threshold value
    event NonceThresholdSet(uint256 newThreshold);

    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Activates the Counter Bank Run (CBR) mechanism.
    /// @param coefficient the CBR coefficient to activate
    function activateCBR(uint256 coefficient) external;

    /// @notice Deactivates the Counter Bank Run (CBR) mechanism.
    function deactivateCBR() external;

    /// @notice Sets the redeem fee.
    /// @param _redeemFee The new redeem fee to set.
    function setRedeemFee(uint256 _redeemFee) external;

    /// @notice Pauses the redeem functionality.
    function pauseRedeem() external;

    /// @notice Unpauses the redeem functionality.
    function unpauseRedeem() external;

    /// @notice Pauses the swap functionality.
    function pauseSwap() external;

    /// @notice Unpauses the swap functionality.
    function unpauseSwap() external;

    /// @notice Pauses the contract.
    function pause() external;

    /// @notice Unpauses the contract.
    function unpause() external;

    /// @notice  swap method
    /// @dev     Function that enable you to swap your rwaToken for stablecoin
    /// @dev     Will exchange RWA (rwaToken) for USD0 (stableToken)
    /// @param   rwaToken  address of the token to swap
    /// @param   amount  amount of rwaToken to swap
    /// @param   minAmountOut minimum amount of stableToken to receive
    function swap(address rwaToken, uint256 amount, uint256 minAmountOut) external;

    /// @notice  swap method with permit
    /// @dev     Function that enable you to swap your rwaToken for stablecoin with permit
    /// @dev     Will exchange RWA (rwaToken) for USD0 (stableToken)
    /// @param   rwaToken  address of the token to swap
    /// @param   amount  amount of rwaToken to swap
    /// @param   deadline The deadline for the permit
    /// @param   v The v value for the permit
    /// @param   r The r value for the permit
    /// @param   s The s value for the permit
    function swapWithPermit(
        address rwaToken,
        uint256 amount,
        uint256 minAmountOut,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /// @notice  redeem method
    /// @dev     Function that enable you to redeem your stable token for rwaToken
    /// @dev     Will exchange USD0 (stableToken) for RWA (rwaToken)
    /// @param   rwaToken address of the token that will be sent to the you
    /// @param   amount  amount of stableToken to redeem
    /// @param   minAmountOut minimum amount of rwaToken to receive
    function redeem(address rwaToken, uint256 amount, uint256 minAmountOut) external;

    /// @notice Swap RWA for USDC through offers on the SwapperContract
    /// @dev Takes USYC, mints USD0 and provides it to the Swapper Contract directly
    /// Sends USD0 to the offer's creator and sends USDC to the recipient
    /// @dev the recipient Address to receive the USDC is msg.sender
    /// @param rwaToken Address of the RWA to swap for USDC
    /// @param amountInTokenDecimals Address of the RWA to swap for USDC
    /// @param orderIdsToTake orderIds to be taken
    /// @param approval ERC20Permit approval data and signature of data
    /// @param partialMatching flag to allow partial matching
    function swapRWAtoStbc(
        address rwaToken,
        uint256 amountInTokenDecimals,
        bool partialMatching,
        uint256[] calldata orderIdsToTake,
        Approval calldata approval
    ) external;

    /// @notice Swap RWA for USDC through offers on the SwapperContract
    /// @dev Takes USYC, mints USD0 and provides it to the Swapper Contract directly
    /// Sends USD0 to the offer's creator and sends USDC to the recipient
    /// @dev the recipient Address to receive the USDC is the offer's creator
    /// @param orderIdsToTake orderIds to be taken
    /// @param approval ERC20Permit approval data and signature of data
    /// @param intent Intent data and signature of data
    /// @param partialMatching flag to allow partial matching
    function swapRWAtoStbcIntent(
        uint256[] calldata orderIdsToTake,
        Approval calldata approval,
        Intent calldata intent,
        bool partialMatching
    ) external;

    // * Getter functions

    /// @notice get the redeem fee percentage
    /// @return the fee value
    function redeemFee() external view returns (uint256);

    /// @notice check if the CBR (Counter Bank Run) is activated
    /// @dev flag indicate the status of the CBR (see documentation for more details)
    /// @return the status of the CBR
    function isCBROn() external view returns (bool);

    /// @notice Returns the cbrCoef value.
    function cbrCoef() external view returns (uint256);

    /// @notice get the status of pause for the redeem function
    /// @return the status of the pause
    function isRedeemPaused() external view returns (bool);

    /// @notice get the status of pause for the swap function
    /// @return the status of the pause
    function isSwapPaused() external view returns (bool);

    // * Restricted functions

    /// @notice  redeem method for DAO
    /// @dev     Function that enables DAO to redeem stableToken for rwaToken
    /// @dev     Will exchange USD0 (stableToken) for RWA (rwaToken)
    /// @param   rwaToken address of the token that will be sent to the you
    /// @param   amount  amount of stableToken to redeem
    function redeemDao(address rwaToken, uint256 amount) external;

    /// @notice Invalidates the current nonce for the message sender
    /// @dev This function increments the nonce counter for the msg.sender and emits a NonceInvalidated event
    function invalidateNonce() external;

    /// @notice Invalidates all nonces up to a certain value for the message sender
    /// @dev This function increments the nonce counter for the msg.sender and emits a NonceInvalidated event
    function invalidateUpToNonce(uint256 newNonce) external;

    /// @notice Returns the amount of tokens taken for the current nonce
    /// @param owner The address of the owner
    /// @return The amount of tokens taken for the current nonce
    function orderAmountTakenCurrentNonce(address owner) external view returns (uint256);

    /// @notice Set the lower bound for the intent nonce to be considered consumed
    /// @dev An intent with an amount less than this threshold after a partial match will be invalidated by incrementing the nonce
    /// @dev emits a NonceThresholdSet event
    /// @param threshold The new threshold value
    function setNonceThreshold(uint256 threshold) external;

    /// @notice Check the current threshold for the intent nonce to be considered consumed
    /// @return The current threshold value
    function nonceThreshold() external view returns (uint256);
}

src/interfaces/distribution/IDistributionAllocator.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IDistributionAllocator {
    /// @notice Sets the buckets distribution percentages for the Usual token emissions
    /// @param _lbt LBT bucket percentage
    /// @param _lyt LYT bucket percentage
    /// @param _iyt IYT bucket percentage
    /// @param _bribe Bribe bucket percentage
    /// @param _eco Eco bucket percentage
    /// @param _dao DAO bucket percentage
    /// @param _marketMakers MarketMakers bucket percentage
    /// @param _usualP UsualP bucket percentage
    /// @param _usualStar UsualStar bucket percentage
    /// @dev The sum of all percentages should be equal to BASIS_POINT_BASE (100% - in basis points)
    /// @dev Can be only called by the DISTRIBUTION_ALLOCATOR role
    function setBucketsDistribution(
        uint256 _lbt,
        uint256 _lyt,
        uint256 _iyt,
        uint256 _bribe,
        uint256 _eco,
        uint256 _dao,
        uint256 _marketMakers,
        uint256 _usualP,
        uint256 _usualStar
    ) external;

    /// @notice Set the fee rates
    /// @param _treasuryFeeRate The treasury fee rate
    /// @param _usualXFeeRate The UsualX fee rate
    function setFeeRates(uint256 _treasuryFeeRate, uint256 _usualXFeeRate) external;

    /// @notice Get the fee rates
    /// @return treasuryFeeRate The treasury fee rate
    /// @return usualXFeeRate The UsualX fee rate
    /// @return burnFeeRate The burn fee rate
    function getFeeRates() external view returns (uint256, uint256, uint256);

    /// @notice Sets D parameter used for the Usual token emissions distribution calculation
    /// @param _d D parameter
    function setD(uint256 _d) external;

    /// @notice Returns the D parameter used for the Usual token emissions distribution calculation
    /// @return d D parameter
    function getD() external view returns (uint256 d);

    /// @notice Sets M0 parameter used for the Usual token emissions distribution calculation
    /// @param _m0 M0 parameter
    function setM0(uint256 _m0) external;

    /// @notice Returns the M0 parameter used for the Usual token emissions distribution calculation
    /// @return m0 M0 parameter
    function getM0() external view returns (uint256 m0);

    /// @notice Sets rateMin parameter used for the Usual token emissions distribution calculation
    /// @param _rateMin rate0 parameter
    function setRateMin(uint256 _rateMin) external;

    /// @notice Returns the rateMin parameter used for the Usual token emissions distribution calculation
    /// @return rateMin rateMin parameter
    function getRateMin() external view returns (uint256 rateMin);

    /// @notice Sets gamma parameter used for the Usual token emissions distribution calculation
    /// @param _gamma rateMin parameter
    function setBaseGamma(uint256 _gamma) external;

    /// @notice Returns the gamma parameter used for the Usual token emissions distribution calculation
    /// @return gamma gamma parameter
    function getBaseGamma() external view returns (uint256 gamma);
}

src/interfaces/distribution/IDistributionModule.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IDistributionModule {
    /*//////////////////////////////////////////////////////////////
                                Structs
    //////////////////////////////////////////////////////////////*/

    struct QueuedOffChainDistribution {
        /// @notice Timestamp of the queued distribution
        uint256 timestamp;
        /// @notice Merkle root of the queued distribution
        bytes32 merkleRoot;
    }

    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Emitted when a parameter used in the distribution calculations is updated
    /// @param parameterName Name of the parameter
    /// @param newValue New value of the parameter
    event ParameterUpdated(string parameterName, uint256 newValue);

    /// @notice Emitted when tokens are allocated to the off-chain distribution bucket
    /// @param amount Amount of tokens allocated
    event UsualAllocatedForOffChainClaim(uint256 amount);

    /// @notice Emitted when tokens are allocated to the UsualX bucket
    /// @param amount Amount of tokens allocated
    event UsualAllocatedForUsualX(uint256 amount);

    /// @notice Emitted when tokens are allocated to the UsualStar bucket
    /// @param amount Amount of tokens allocated
    event UsualAllocatedForUsualStar(uint256 amount);

    /// @notice Emitted when an off-chain distribution is queued by the distribution operator
    /// @param timestamp Timestamp of the distribution
    /// @param merkleRoot Merkle Root of the off-chain distribution
    event OffChainDistributionQueued(uint256 indexed timestamp, bytes32 merkleRoot);

    /// @notice Emitted when an unchallenged off-chain distribution older than the distribution challenge period is approved
    /// @param timestamp Timestamp of the distribution
    /// @param merkleRoot Merkle Root of the off-chain distribution approved
    event OffChainDistributionApproved(uint256 indexed timestamp, bytes32 merkleRoot);

    /// @notice Emitted when an off-chain distribution is claimed by an account
    /// @param account Account that claimed the tokens
    /// @param amount Amount of tokens claimed
    event OffChainDistributionClaimed(address indexed account, uint256 amount);

    /// @notice Emitted when the off-chain distribution queue is reset
    event OffChainDistributionQueueReset();

    /// @notice Emitted when an off-chain distribution is challenged
    /// @param timestamp Timestamp of the challenged distribution
    event OffChainDistributionChallenged(uint256 indexed timestamp);

    /// @notice Emitted when the daily distribution rates are provided
    /// @param ratet Rate at time t
    /// @param p90Rate 90th percentile rate
    event DailyDistributionRates(uint256 ratet, uint256 p90Rate);

    /// @notice Emitted when an off-chain distribution is claimed and redirected by an account
    /// @param redirectedAccount Account that claimed the tokens
    /// @param redirectRecipient Account that received the redirected tokens
    /// @param amount Amount of tokens claimed
    event OffChainDistributionClaimedAndRedirected(
        address indexed redirectedAccount, address indexed redirectRecipient, uint256 amount
    );

    /// @notice Emitted when an off-chain distribution redirection is initialized
    /// @param account Account that initiated the redirection
    /// @param newAccount Account that will receive the redirected tokens
    /// @param startingTimestamp Timestamp of the redirection starting time
    event OffChainDistributionRedirectInitialized(
        address account, address newAccount, uint256 startingTimestamp
    );

    /// @notice Emitted when an off-chain distribution redirection is accepted after the challenge period
    /// @param account Account that will be redirected
    /// @param newAccount Account that will receive the redirected tokens
    event OffChainDistributionRedirectedAccepted(address account, address newAccount);

    /// @notice Emitted when an off-chain distribution redirection is cancelled
    /// @param account Account that would have been redirected
    /// @param newAccount Account that would have received the redirected tokens
    event OffChainDistributionRedirectedCancelled(address account, address newAccount);

    /// @notice Emitted when an off-chain distribution redirection is removed
    /// @param account Account that was redirected
    event OffChainDistributionRedirectedRemoved(address account);

    /// @notice Emitted when the fee rates are set
    /// @param treasuryFeeRate Rate of fee to send to yield treasury
    /// @param usualXFeeRate Rate of fee to send to UsualX
    /// @param burnFeeRate Rate of fee to burn
    event FeeRatesSet(uint256 treasuryFeeRate, uint256 usualXFeeRate, uint256 burnFeeRate);

    /// @notice Emitted when the fee is allocated to be sent to UsualX
    /// @param feeAmount Amount of fee allocated
    event UsualFeeAllocatedToUsualX(uint256 feeAmount);

    /// @notice Emitted when the fee is allocated to be sent to yield treasury
    /// @param feeAmount Amount of fee allocated
    event UsualFeeAllocatedToYieldTreasury(uint256 feeAmount);

    /// @notice Emitted when the fee is allocated to be burned
    /// @param feeAmount Amount of fee allocated
    event UsualFeeBurned(uint256 feeAmount);

    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Pauses the contract
    /// @dev Can only be called by the PAUSING_CONTRACTS_ROLE
    function pause() external;

    /// @notice Unpauses the contract
    /// @dev Can only be called by the DEFAULT_ADMIN_ROLE
    function unpause() external;

    /// @notice Returns the current buckets distribution percentage for the Usual token emissions (in basis points)
    /// @return lbt LBT bucket percentage
    /// @return lyt LYT bucket percentage
    /// @return iyt IYT bucket percentage
    /// @return bribe Bribe bucket percentage
    /// @return eco Eco bucket percentage
    /// @return dao DAO bucket percentage
    /// @return marketMakers MarketMakers bucket percentage
    /// @return usualP UsualP bucket percentage
    /// @return usualStar UsualStar bucket percentage
    function getBucketsDistribution()
        external
        view
        returns (
            uint256 lbt,
            uint256 lyt,
            uint256 iyt,
            uint256 bribe,
            uint256 eco,
            uint256 dao,
            uint256 marketMakers,
            uint256 usualP,
            uint256 usualStar
        );

    /// @notice Calculates the St value
    /// @dev Raw equation: St = min((supplyPp0 * p0) / (supplyPpt * pt), 1)
    /// @param supplyPpt Current supply (scaled by SCALAR_ONE)
    /// @param pt Current price (scaled by SCALAR_ONE)
    /// @return St value (scaled by SCALAR_ONE)
    function calculateSt(uint256 supplyPpt, uint256 pt) external view returns (uint256);

    /// @notice Calculates the Rt value
    /// @dev Raw equation: Rt = min( max(ratet, rateMin), p90Rate ) / rate0
    /// @return Rt value (scaled by SCALAR_ONE)
    function calculateRt() external view returns (uint256);

    /// @notice Calculates the Kappa value
    /// @dev Raw equation: Kappa = m_0*max(rate_t[i],rate_min)/rate_0
    /// @return Kappa value (scaled by SCALAR_ONE)
    function calculateKappa() external view returns (uint256);

    /// @notice Calculates the Gamma value
    /// @return Gamma value (scaled by SCALAR_ONE)
    function calculateGamma() external view returns (uint256);

    /// @notice Calculates the Mt value
    /// @dev Raw equation: Mt = min((m0 * St * Rt)/gamma, kappa)
    /// @param st St value (scaled by SCALAR_ONE)
    /// @param rt Rt value (scaled by SCALAR_ONE)
    /// @param kappa Kappa value (in basis points)
    /// @return Mt value (scaled by SCALAR_ONE)
    function calculateMt(uint256 st, uint256 rt, uint256 kappa) external view returns (uint256);

    /// @notice Calculates all values: St, Rt, Mt, and UsualDist
    /// @return st St value (scaled by SCALAR_ONE)
    /// @return rt Rt value (scaled by SCALAR_ONE)
    /// @return kappa Kappa value (scaled by SCALAR_ONE)
    /// @return mt Mt value (scaled by SCALAR_ONE)
    /// @return usualDist UsualDist value (raw, not scaled)
    function calculateUsualDist()
        external
        view
        returns (uint256 st, uint256 rt, uint256 kappa, uint256 mt, uint256 usualDist);

    /// @notice Claims the Usual token distribution for the given account
    /// @dev If a given account has been redirected, the respective redirected account will receive the distribution instead
    /// @param account The account to claim for
    /// @param amount Total amount of Usual token rewards earned by the account up to this point
    /// @param proof Merkle proof
    function claimOffChainDistribution(address account, uint256 amount, bytes32[] calldata proof)
        external;

    /// @notice Redirects the off-chain distribution for the given account to a new account
    /// @dev This function can only be called by the redirection-admin-role
    /// @dev If the account is already redirected, the function will revert
    /// @dev Redirects cannot be daisy-chained.
    /// @param account The account to redirect
    /// @param newAccount The new account to redirect to
    function redirectOffChainDistribution(address account, address newAccount) external;

    /// @notice Challenges the redirected off-chain distribution for the given account
    /// @dev This function can only be called by the account that has been redirected OR the redirection-admin-role
    /// @param account The account to challenge
    function cancelInitiatedRedirectedOffChainDistribution(address account) external;

    /// @notice Accepts the redirected off-chain distribution for the given account
    /// @param account The redirected account to accept
    function acceptRedirectedOffChainDistribution(address account) external;

    /// @notice Removes the redirected off-chain distribution for the given account
    /// @param account The redirected account to remove
    function removeRedirectedOffChainDistribution(address account) external;

    /// @notice Returns the current off-chain distribution data
    /// @return timestamp Timestamp of the latest unchallanged distribution
    /// @return merkleRoot Merkle root of the latest unchallanged distribution
    function getOffChainDistributionData()
        external
        view
        returns (uint256 timestamp, bytes32 merkleRoot);

    /// @notice Returns the amount of Usual token claimed off-chain by the account up to this point
    /// @param account The account to check
    /// @return amount Amount of Usual token claimed off-chain
    function getOffChainTokensClaimed(address account) external view returns (uint256 amount);

    /// @notice Returns the off-chain distribution queue
    /// @return QueuedOffChainDistribution[] Array of queued off-chain distributions
    function getOffChainDistributionQueue()
        external
        view
        returns (QueuedOffChainDistribution[] memory);

    /// @notice Returns maximum amount of Usual token that can be distributed off-chain
    /// @return amount Maximum amount of Usual token that can be distributed off-chain
    function getOffChainDistributionMintCap() external view returns (uint256 amount);

    /// @notice Returns the timestamp of the last on-chain distribution
    /// @return timestamp Timestamp of the last on-chain distribution
    function getLastOnChainDistributionTimestamp() external view returns (uint256 timestamp);

    /// @notice Approve the latest queue merkle root that is unchallenged and older than challenge period.
    /// @dev Every queued merkle root older than challenge period will be removed.
    function approveUnchallengedOffChainDistribution() external;

    /// @notice Returns the account that has initiated a redirection challenge for a given account
    /// @param account The account to check
    /// @return redirectedAccount The account that initiated the redirection challenge
    function getInitiatedRedirectedOffChainDistribution(address account)
        external
        view
        returns (address redirectedAccount);

    /// @notice Returns the timestamp of the ongoing redirection challenge for a given account
    /// @param account The account to check
    /// @return timestamp The timestamp when the redirection challenge started
    function getOngoingRedirectionChallenge(address account)
        external
        view
        returns (uint256 timestamp);

    /// @notice Returns the account that has been redirected to for a given account
    /// @param account The account to check
    /// @return redirectedAccount The account that the distribution is redirected to
    function getRedirectedAccount(address account)
        external
        view
        returns (address redirectedAccount);

    /// @notice Updates the iUsd0ppVault address
    /// @dev This function can only be called by an address with the VAULT_UPDATER_ROLE.
    /// @param newVault The address of the new iUsd0ppVault. Must not be the same value.
    function updateIUsd0ppVault(address newVault) external;

    /// @notice Returns the current iUsd0ppVault address
    /// @return The address of the current iUsd0ppVault
    function getIUsd0ppVault() external view returns (address);
}

src/interfaces/distribution/IDistributionOperator.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IDistributionOperator {
    /// @notice Distribute Usual token emissions to on-chain and off-chainbuckets based on interest rates and treasury values.
    /// @dev Can be only called by the DISTRIBUTION_OPERATOR role, once per 24 hours.
    function distributeUsualToBuckets() external;

    /// @notice Queue a merkle root that allows off-chain distribution of Usual token to be claimed.
    /// @param _merkleRoot Merkle root of the distribution point
    /// @dev Can be only called by the DISTRIBUTION_OPERATOR role
    function queueOffChainUsualDistribution(bytes32 _merkleRoot) external;

    /// @notice Resets off-chain distribution queue.
    /// @dev Can be only called by the DISTRIBUTION_OPERATOR role
    /// @dev Every queued merkle root will be removed.
    function resetOffChainDistributionQueue() external;
}

src/interfaces/distribution/IOffChainDistributionChallenger.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IOffChainDistributionChallenger {
    /// @notice Challenges all queued off-chain distribution older than specified timestamp.
    /// @param _timestamp Timestamp before which the off-chain distribution will be challenged
    /// @dev Can be only called by the DISTRIBUTION_CHALLENGER role
    function challengeOffChainDistribution(uint256 _timestamp) external;
}

src/interfaces/modules/IYieldModule.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IAggregator} from "src/interfaces/oracles/IAggregator.sol";

interface IYieldModule {
    struct YieldSourceData {
        uint256 lastUpdated; // Last time we updated the rate (block.timestamp)
        uint256 weeklyInterestBps; // Weekly interest rate in basis points
        IAggregator feed; // If using Chainlink aggregator, store it
    }

    /// @notice Adds a new yield source with a Chainlink data feed
    /// @param asset Address of the asset for this yield source
    /// @param feedAddress Chainlink data feed address
    function addYieldSourceWithFeed(address asset, address feedAddress) external;

    /// @notice Adds a new yield source with a weekly interest rate (manual)
    /// @param asset Address of the asset for this yield source
    /// @param weeklyInterestBps Interest rate in basis points (weekly)
    function addYieldSourceWithWeeklyInterest(address asset, uint256 weeklyInterestBps) external;

    /// @notice Removes a yield source
    /// @param asset Address of the asset for this yield source
    function removeYieldSource(address asset) external;

    /// @notice Updates the interest rate for a yield source
    /// @param asset Address of the asset for this yield source
    /// @param weeklyInterestBps Interest rate in basis points (weekly)
    function updateInterestRate(address asset, uint256 weeklyInterestBps) external;

    /// @notice Remove a treasury address
    /// @param treasury address of the treasury
    function removeTreasury(address treasury) external;

    /// @notice Adds a new treasury address
    /// @param treasury address of the treasury
    function addTreasury(address treasury) external;

    /// @notice Updates the Chainlink data feed for a yield source
    /// @param asset Address of the asset for this yield source
    /// @param feedAddress Chainlink data feed address
    function updateFeed(address asset, address feedAddress) external;

    /// @notice Sets the maximum data age for the RWA data
    /// @param maxDataAge The maximum data age in seconds
    function setMaxDataAge(uint256 maxDataAge) external;

    /// @notice Sets the P90 interest rate
    /// @param p90Rate The P90 interest rate in basis points
    function setP90InterestRate(uint256 p90Rate) external;

    /// @notice Returns the maximum data age
    /// @return maxDataAge The maximum data age
    function getMaxDataAge() external view returns (uint256);

    /// @notice Returns the blended weekly interest rate
    /// @dev Rate values are in basis points (1 = 0.01%)
    /// @return blendedWeeklyRateBps The blended weekly interest rate
    function getBlendedWeeklyInterest() external view returns (uint256 blendedWeeklyRateBps);

    /// @notice Returns the interest rates 90th percentile of the last 60 days.
    /// @dev Rate values are in basis points (1 = 0.01%)
    /// @return P90 rate in basis points
    function getP90InterestRate() external view returns (uint256);

    /// @notice Returns the RWA data for a given RWA ID
    /// @param asset The address of the asset
    /// @return yieldSourceData The yield source data
    function getYieldSource(address asset) external view returns (YieldSourceData memory);

    /// @notice Returns the number of yield source data entries
    /// @return length The number of yield source data entries
    function getYieldSourceCount() external view returns (uint256);

    /// @notice Returns all yield source data entries
    /// @return yieldSourceData The yield source data entries
    function getAllYieldSourceData() external view returns (YieldSourceData[] memory);

    /// @notice Returns the number of treasury addresses
    /// @return length The number of treasury addresses
    function getTreasuryCount() external view returns (uint256);

    /// @notice Returns all treasury addresses
    /// @return treasury The treasury addresses
    function getAllTreasury() external view returns (address[] memory);
}

src/interfaces/oracles/IAggregator.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IAggregator {
    function decimals() external view returns (uint8);

    function description() external view returns (string memory);

    function version() external view returns (uint256);

    function getRoundData(uint80 _roundId)
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );

    function latestRoundData()
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
}

src/interfaces/oracles/IOracle.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IOracle {
    /*//////////////////////////////////////////////////////////////
                                Structs
    //////////////////////////////////////////////////////////////*/

    /// @notice Struct representing the oracle information for a token
    struct TokenOracle {
        /// @notice The oracle contract for the token
        address dataSource;
        /// @notice Flag indicating if the token is stable token
        bool isStablecoin;
        /// @notice Timeout in seconds
        uint64 timeout;
    }

    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Event emitted when the value of the max depeg threshold change
    /// @param newMaxDepegThreshold The new max depeg threshold
    event SetMaxDepegThreshold(uint256 newMaxDepegThreshold);

    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Get the latest price of a token from the underlying oracle.
    /// @dev    View function which fetches the latest available oracle price from a Chainlink-compatible feed.
    /// @dev    The result is scaled to 18 decimals.
    /// @param  token The address of the token.
    /// @return The price of the token in USD with 18 decimals.
    function getPrice(address token) external view returns (uint256);

    /// @notice Compute a quote for the specified token and amount.
    /// @dev    This function fetches the latest available price from a Chainlink-compatible feed for the token and computes the quote based on the given amount.
    /// @dev    The quote is computed by multiplying the amount of tokens by the token price.
    /// @dev    The result is returned with as many decimals as the input amount.
    /// @param  token  The address of the token to calculate the quote for.
    /// @param  amount The amount of tokens for which to compute the quote.
    /// @return The computed quote in USD with as many decimals as the input.
    function getQuote(address token, uint256 amount) external returns (uint256);

    /// @notice Get the maximum allowed depeg threshold for stablecoins.
    /// @return The maximum allowed depeg threshold in basis points.
    function getMaxDepegThreshold() external view returns (uint256);

    /// @notice Set the maximum allowed depeg threshold for stablecoins.
    /// @dev    The provided value should be in basis points relative to 1 USD.
    /// @dev    Valid values are from 0 (exact 1:1 peg required) to 10_000 ($0.00-$2.00 allowed).
    /// @dev    getPrice will revert if the price falls outside of this range.
    /// @param  maxAuthorizedDepegPrice The new maximum allowed depeg threshold.
    function setMaxDepegThreshold(uint256 maxAuthorizedDepegPrice) external;
}

src/interfaces/registry/IRegistryAccess.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IAccessControlDefaultAdminRules} from
    "openzeppelin-contracts/access/extensions/IAccessControlDefaultAdminRules.sol";

interface IRegistryAccess is IAccessControlDefaultAdminRules {
    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Set the admin role for a specific role
    /// @param role The role to set the admin for
    /// @param adminRole The admin role to set
    function setRoleAdmin(bytes32 role, bytes32 adminRole) external;
}

src/interfaces/registry/IRegistryContract.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IRegistryContract {
    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice This event is emitted when the address of the contract is set
    /// @param name The name of the contract in bytes32
    /// @param contractAddress The address of the contract
    event SetContract(bytes32 indexed name, address indexed contractAddress);

    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Set the address of the contract
    /// @param name The name of the contract in bytes32
    /// @param contractAddress The address of the contract
    function setContract(bytes32 name, address contractAddress) external;

    /// @notice Get the address of the contract
    /// @param name The name of the contract in bytes32
    /// @return contractAddress The address of the contract
    function getContract(bytes32 name) external view returns (address);
}

src/interfaces/token/IUsd0PP.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Approval as PermitApproval} from "src/interfaces/IDaoCollateral.sol";

interface IUsd0PP is IERC20Metadata {
    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Emitted when a bond is unwrapped.
    /// @param user The address of the user unwrapping the bond.
    /// @param amount The amount of the bond unwrapped.
    event BondUnwrapped(address indexed user, uint256 amount);

    /// @notice Emitted when a bond is unwrapped during the temporary unlock period.
    /// @param user The address of the user unwrapping the bond.
    /// @param amount The amount of the bond unwrapped.
    event BondUnwrappedDuringEarlyUnlock(address indexed user, uint256 amount);

    /// @notice Event emitted when a bond is early redeemed
    /// @param user The address of the user early redeeming the bond
    /// @param usd0ppAmount The amount of USD0++ early redeemed
    event BondUnwrappedEarlyWithUsualBurn(address indexed user, uint256 usd0ppAmount);

    /// @notice Emitted when the PAR mechanism is triggered
    /// @param user The address of the caller triggering the mechanism
    /// @param amount The amount of USD0 supplied to the Curvepool to return to PAR.
    event PARMechanismActivated(address indexed user, uint256 amount);

    /// @notice Emitted when an emergency withdrawal occurs.
    /// @param account The address of the account initiating the emergency withdrawal.
    /// @param balance The balance withdrawn.
    event EmergencyWithdraw(address indexed account, uint256 balance);

    /// @notice Emitted when an address temporary redemption is disabled.
    /// @param user The address of the user being disabled for temporary redemptions.
    event BondEarlyUnlockDisabled(address indexed user);

    /// @notice Event emitted when the floor price is updated
    /// @param newFloorPrice The new floor price value
    event FloorPriceUpdated(uint256 newFloorPrice);

    /// @notice Event emitted when USD0++ is unlocked to USD0
    /// @param user The address of the user unlocking USD0++
    /// @param usd0ppAmount The amount of USD0++ unlocked
    /// @param usd0Amount The amount of USD0 received
    event Usd0ppUnlockedFloorPrice(address indexed user, uint256 usd0ppAmount, uint256 usd0Amount);

    /// @notice Event emitted when the early unlock balances are set.
    /// @param addressesToAllocateTo The addresses to allocate the balances to.
    /// @param earlyUnlockBalances The early unlock balances to allocate.
    event EarlyUnlockBalancesSet(address[] addressesToAllocateTo, uint256[] earlyUnlockBalances);

    /// @notice Event emitted when the early unlock period is set.
    /// @param earlyUnlockStart The start of the early unlock period.
    /// @param earlyUnlockEnd The end of the early unlock period.
    event EarlyUnlockPeriodSet(uint256 earlyUnlockStart, uint256 earlyUnlockEnd);

    /// @notice Emitted when an unwrap cap is set for an address
    /// @param user The address of the user setting the unwrap cap
    /// @param cap The unwrap cap
    event UnwrapCapSet(address indexed user, uint256 cap);

    /// @notice Emitted when USD0++ is unwrapped by a USD0PP_CAPPED_UNWRAP_ROLE address
    /// @param user The address of the user unwrapping the bond
    /// @param amount The amount of USD0++ unwrapped
    /// @param remainingAllowance The remaining allowance of the user
    event CappedUnwrap(address indexed user, uint256 amount, uint256 remainingAllowance);

    /// @notice Event emitted when the daily USD0++ inflow is updated
    /// @param dayIndex Index of the day (unix timestamp / seconds per day)
    /// @param amount The amount of USD0++ inflow
    event DailyUsd0ppInflowUpdated(uint256 dayIndex, uint256 amount);

    /// @notice Event emitted when the daily USD0++ outflow is updated
    /// @param dayIndex Index of the day (unix timestamp / seconds per day)
    /// @param amount The amount of USD0++ outflow
    event DailyUsd0ppOutflowUpdated(uint256 dayIndex, uint256 amount);

    /// @notice Event emitted when the USUAL distribution rate is set
    /// @param newRate The new USUAL distribution rate
    event UsualDistributionPerUsd0ppSet(uint256 newRate);

    /// @notice Event emitted when the duration cost factor is set
    /// @param newFactor The new duration cost factor
    event DurationCostFactorSet(uint256 newFactor);

    /// @notice Event emitted when the target redemption rate is set
    /// @param newRate The new target redemption rate
    event TargetRedemptionRateSet(uint256 newRate);

    // @notice Event emitted when fees are swept
    // @param caller The address calling the sweep
    // @param collector The address receiving the fees
    // @param amount The amount of fees swept
    event FeeSwept(address indexed caller, address indexed collector, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Pauses all token transfers.
    /// @dev Can only be called by an account with the PAUSING_CONTRACTS_ROLE
    function pause() external;

    /// @notice Unpauses all token transfers.
    /// @dev Can only be called by an account with the DEFAULT_ADMIN_ROLE
    function unpause() external;

    /// @notice Sets the early unlock period for the bond.
    /// @param bondEarlyUnlockStart The start time of the early unlock period.
    /// @param bondEarlyUnlockEnd The end time of the early unlock period.
    function setupEarlyUnlockPeriod(uint256 bondEarlyUnlockStart, uint256 bondEarlyUnlockEnd)
        external;

    /// @notice Calculates the number of seconds from beginning to end of the bond period.
    /// @return The number of seconds.
    function totalBondTimes() external view returns (uint256);

    /// @notice get the start time
    /// @dev Used to determine if the bond can be minted.
    /// @return The block timestamp marking when the bond starts.
    function getStartTime() external view returns (uint256);

    /// @notice get the end time
    /// @dev Used to determine if the bond can be unwrapped.
    /// @return The block timestamp marking when the bond ends.
    function getEndTime() external view returns (uint256);

    /// @notice Mints Usd0PP tokens representing bonds.
    /// @dev Transfers collateral USD0 tokens and mints Usd0PP bonds.
    /// @param amountUsd0 The amount of USD0 to mint bonds for.
    function mint(uint256 amountUsd0) external;

    /// @notice Mints Usd0PP tokens representing bonds with permit.
    /// @dev    Transfers collateral Usd0 tokens and mints Usd0PP bonds.
    /// @param  amountUsd0 The amount of Usd0 to mint bonds for.
    /// @param  deadline The deadline for the permit.
    /// @param  v The v value for the permit.
    /// @param  r The r value for the permit.
    /// @param  s The s value for the permit.
    function mintWithPermit(uint256 amountUsd0, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;

    /// @notice Unwraps the bond after maturity, returning the collateral token.
    /// @dev Only the balance of the caller is unwrapped.
    /// @dev Burns bond tokens and transfers collateral back to the user.
    function unwrap() external;

    /// @notice Triggers the PAR mechanism to maintain the peg between USD0 and USD0++ via Curvepool exchange.
    /// @dev This function performs a series of actions: it checks for sufficient USD0 balances, exchanges USD0 for USD0++,
    ///      and unwraps USD0++ back to USD0, which is then burned and any excess sent to the treasury.
    ///      The function reverts if the PAR mechanism does not result in more USD0++ gained overall than USD0 is exchanged for.
    /// @param parUsd0Amount The amount of USD0 to be exchanged for USD0++.
    /// @param minimumPARMechanismGainedAmount The minimum additional amount of USD0++ expected to gain on top of the exchanged amount to account for slippage.
    function triggerPARMechanismCurvepool(
        uint256 parUsd0Amount,
        uint256 minimumPARMechanismGainedAmount
    ) external;

    /// @notice Allows users to early exit and unwrap a specified amount of USD0pp during the temporary exit period.
    /// @dev    Users must have been allocated an early unlock amount by the admin before calling this function.
    /// @dev    The early exit period is defined by `bondEarlyUnlockStart` and `bondEarlyUnlockEnd`.
    /// @dev    This is a one-time option; it consumes the entire allocated amount, even if only partially used.
    /// @dev    Emits `BondUnwrappedDuringEarlyUnlock` and `BondUnwrapped` events.
    /// @dev    Reverts if the current time is not within the early exit period.
    /// @dev    Reverts if `amountToUnwrap` exceeds the user's allocated early unlock amount.
    /// @dev    Reverts if the user does not have sufficient bond balance.
    /// @param amountToUnwrap The amount of bonds the user wants to unwrap.
    function temporaryOneToOneExitUnwrap(uint256 amountToUnwrap) external;

    /// @notice Allocates early unlock amounts to specified addresses, allowing them to early exit bonds during the temporary exit period.
    /// @dev    Only callable by accounts with the `EARLY_BOND_UNLOCK_ROLE`.
    /// @dev    Updates `bondEarlyUnlockAllowedAmount` for each address.
    /// @dev    The early unlock amounts determine the maximum amount each user can unwrap early.
    /// @dev    Reverts if the lengths of `addressesToAllocateTo` and `balancesToAllocate` do not match.
    /// @dev    Potential upper bound on redemption may be applied in future updates.
    /// @param addressesToAllocateTo An array of addresses to allocate early unlock amounts to.
    /// @param balancesToAllocate An array of amounts representing the early unlock amounts for each address.
    function allocateEarlyUnlockBalance(
        address[] calldata addressesToAllocateTo,
        uint256[] calldata balancesToAllocate
    ) external;

    /// @notice Retrieves the disabled status of a user's temporary redemptions.
    /// @dev Returns `true` if the user's temporary redemptions are disabled, `false` otherwise.
    /// @param user The address of the user to check.
    /// @return A boolean indicating whether the user's temporary redemptions are disabled.
    function getBondEarlyUnlockDisabled(address user) external view returns (bool);

    /// @notice Set the disabled status of a user's temporary redemptions. Only callable by the airdrop tax collector contract.
    /// @param user The address of the user to disable temporary redemptions for.
    function setBondEarlyUnlockDisabled(address user) external;

    /// @notice function for executing the emergency withdrawal of Usd0.
    /// @param  safeAccount The address of the account to withdraw the Usd0 to.
    /// @dev    Reverts if the caller does not have the DEFAULT_ADMIN_ROLE role.
    function emergencyWithdraw(address safeAccount) external;

    /// @notice Updates the floor price
    /// @param newFloorPrice The new floor price value (18 decimal places)
    function updateFloorPrice(uint256 newFloorPrice) external;

    /// @notice Unlocks USD0++ to USD0 at the current floor price
    /// @param usd0ppAmount The amount of USD0++ to unlock
    function unlockUsd0ppFloorPrice(uint256 usd0ppAmount) external;

    /// @notice Allows early redemption of USD0++ by burning USUAL
    /// @param usd0ppAmount The amount of USD0++ to redeem
    /// @param maxUsualAmount The maximum amount of USUAL to burn
    function unlockUSD0ppWithUsual(uint256 usd0ppAmount, uint256 maxUsualAmount) external;

    /// @notice Allows early redemption of USD0++ by burning USUAL using permit
    /// @param usd0ppAmount The amount of USD0++ to redeem
    /// @param maxUsualAmount The maximum amount of USUAL to burn
    /// @param usualApproval The approval for the USUAL permit
    /// @param usd0ppApproval The approval for the USD0++ permit
    function unlockUSD0ppWithUsualWithPermit(
        uint256 usd0ppAmount,
        uint256 maxUsualAmount,
        PermitApproval calldata usualApproval,
        PermitApproval calldata usd0ppApproval
    ) external;

    /// @notice Sweeps accumulated fees to the distribution module contract
    /// @return The amount of fees swept
    function sweepFees() external returns (uint256);

    /// @notice Sets the USUAL distribution per USD0++
    /// @param newRate New daily USUAL distribution per USD0++
    function setUsualDistributionPerUsd0pp(uint256 newRate) external;

    /// @notice Sets the duration cost factor
    /// @param newFactor New duration cost factor
    function setDurationCostFactor(uint256 newFactor) external;

    /// @notice Sets the target redemption rate
    /// @param newRate New target redemption rate
    function setTargetRedemptionRate(uint256 newRate) external;

    /// @notice Gets the current floor price
    /// @return The current floor price
    function getFloorPrice() external view returns (uint256);

    /// @notice Sets the unwrap capability for an address
    /// @param user The address to set the capability for
    /// @param cap The total capability amount (in USD0++ tokens)
    function setUnwrapCap(address user, uint256 cap) external;

    /// @notice Gets the unwrap amount capability for an address
    /// @param user The address to get the capability amount
    /// @return The unwrap amount capability
    function getUnwrapCap(address user) external view returns (uint256);

    /// @notice Gets the remaining unwrap allowance for an address
    /// @param user The address to get the remaining of
    /// @return The remaining allowance
    function getRemainingUnwrapAllowance(address user) external view returns (uint256);

    /// @notice Unwraps USD0++ tokens with cap enforcement
    /// @param amount The amount to unwrap
    /// @dev this doesnt count as an outflow, given that the following routing ensures a future inflow.
    function unwrapWithCap(uint256 amount) external;

    /// @notice Gets the current target redemption rate
    /// @return The current target redemption rate
    function getTargetRedemptionRate() external view returns (uint256);

    /// @notice Gets the current usual distribution per USD0++
    /// @return The current usual distribution per USD0++
    function getUsualDistributionPerUsd0pp() external view returns (uint256);

    /// @notice Gets the current duration cost factor
    /// @return The current duration cost factor
    function getDurationCostFactor() external view returns (uint256);

    /// @notice Gets the current daily USD0++ inflows
    /// @param dayIndex The index of the day (unix timestamp / seconds per day)
    /// @return The current daily USD0++ inflows
    function getDailyUsd0ppInflows(uint256 dayIndex) external view returns (uint256);

    /// @notice Gets the current daily USD0++ outflows
    /// @param dayIndex The index of the day (unix timestamp / seconds per day)
    /// @return The current daily USD0++ outflows
    function getDailyUsd0ppOutflows(uint256 dayIndex) external view returns (uint256);

    /// @notice Gets the current accumulated fees
    /// @return The current accumulated fees
    function getAccumulatedFees() external view returns (uint256);

    /// @notice Calculates the current net outflows
    /// @param usd0ppAmount The current redemption amount of USD0++ to include in the calculation
    /// @return The current net outflows
    function calculateNetOutflows(uint256 usd0ppAmount) external view returns (uint256);

    /// @notice Calculates the weekly target redemptions
    /// @param tvl The total value locked
    /// @param targetRedemptionRate The target redemption rate
    /// @return The weekly target redemptions
    function calculateWeeklyTargetRedemptions(uint256 tvl, uint256 targetRedemptionRate)
        external
        view
        returns (uint256);

    /// @notice Calculates the adjustment factor
    /// @param netOutflows The current net outflows
    /// @param weeklyTarget The weekly target redemptions
    /// @return The adjustment factor
    function calculateAdjustmentFactor(uint256 netOutflows, uint256 weeklyTarget)
        external
        view
        returns (uint256);

    /// @notice Calculates the required amount of USUAL to burn for early redemption
    /// @param usd0ppAmount The amount of USD0++ to redeem
    /// @return The required amount of USUAL to burn
    function calculateRequiredUsual(uint256 usd0ppAmount) external view returns (uint256);

    /// @notice Unwraps USD0++ tokens without cap enforcement
    /// @param amount The amount to unwrap
    function unwrapPegMaintainer(uint256 amount) external;
}

src/interfaces/token/IUsual.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IUsual is IERC20Metadata {
    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Emitted when an account is blacklisted
    /// @param account The address that was blacklisted
    event Blacklist(address account);

    /// @notice Emitted when an account is removed from the blacklist
    /// @param account The address that was unblacklisted
    event UnBlacklist(address account);

    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Pauses all token transfers.
    /// @dev Can only be called by an account with the PAUSING_CONTRACTS_ROLE
    function pause() external;

    /// @notice Unpauses all token transfers.
    /// @dev Can only be called by an account with the DEFAULT_ADMIN_ROLE
    function unpause() external;

    /// @notice mint Usual token
    /// @dev Can only be called by USUAL_MINT role
    /// @param to address of the account who want to mint their token
    /// @param amount the amount of tokens to mint
    function mint(address to, uint256 amount) external;

    /// @notice burnFrom Usual token
    /// @dev Can only be called by USUAL_BURN role
    /// @param account address of the account who want to burn
    /// @param amount the amount of tokens to burn
    function burnFrom(address account, uint256 amount) external;

    /// @notice burn Usual token
    /// @dev Can only be called by USUAL_BURN role
    /// @param amount the amount of tokens to burn
    function burn(uint256 amount) external;

    /// @notice blacklist an account
    /// @dev Can only be called by the BLACKLIST_ROLE
    /// @param account address of the account to blacklist
    function blacklist(address account) external;

    /// @notice unblacklist an account
    /// @dev Can only be called by the BLACKLIST_ROLE
    /// @param account address of the account to unblacklist
    function unBlacklist(address account) external;

    /// @notice check if the account is blacklisted
    /// @param account address of the account to check
    /// @return bool
    function isBlacklisted(address account) external view returns (bool);
}

src/interfaces/token/IUsualSP.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IUsualSP {
    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Emitted when an insider claims their original allocation.
    /// @param account The address of the insider.
    /// @param amount The amount of tokens claimed.
    event ClaimedOriginalAllocation(address indexed account, uint256 amount);

    /// @notice Emitted when an allocation is removed
    /// @param account The address of the account whose allocation was removed
    event RemovedOriginalAllocation(address indexed account);

    /// @notice Emitted when a new allocation is set.
    /// @param recipients The addresses of the recipients.
    /// @param allocations The allocations of the recipients.
    /// @param allocationStartTimes The allocation start times of the recipients.
    /// @param cliffDurations The cliff durations of the recipients.
    event NewAllocation(
        address[] recipients,
        uint256[] allocations,
        uint256[] allocationStartTimes,
        uint256[] cliffDurations
    );

    /// @notice Emitted when the stake is made
    /// @param account The address of the user.
    /// @param amount The amount of tokens staked.
    event Stake(address account, uint256 amount);

    /// @notice Emitted when the unstake is made
    /// @param account The address of the user.
    /// @param amount The amount of tokens unstaked.
    event Unstake(address account, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice claim UsualS token from allocation
    /// @dev After the cliff period, the owner can claim UsualS token every month during the vesting period
    function claimOriginalAllocation() external;

    /// @notice stake UsualS token to the contract
    /// @param amount the amount of UsualS token to stake
    function stake(uint256 amount) external;

    /// @notice stake UsualS token to the contract with permit
    /// @param amount the amount of UsualS token to stake
    /// @param deadline the deadline of the permit
    /// @param v the v of the permit
    /// @param r the r of the permit
    /// @param s the s of the permit
    function stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;

    /// @notice unstake UsualS token from the contract
    /// @param amount the amount of UsualS token to unstake
    function unstake(uint256 amount) external;

    /// @notice claim reward from the contract
    /// @return the amount of reward token claimed
    function claimReward() external returns (uint256);

    /// @notice Allocate UsualSP token to the recipients
    /// @dev Can only be called by the admin
    /// @param recipients the list of recipients
    /// @param originalAllocations the list of allocations
    /// @param allocationStartTimes the list of allocation start times
    /// @param cliffDurations the list of cliffDurations
    function allocate(
        address[] calldata recipients,
        uint256[] calldata originalAllocations,
        uint256[] calldata allocationStartTimes,
        uint256[] calldata cliffDurations
    ) external;

    /// @notice Remove the allocation of UsualSP token from the recipients
    /// @dev Can only be called by the admin
    /// @param recipients the list of recipients
    function removeOriginalAllocation(address[] calldata recipients) external;

    /// @notice Pause the contract, preventing claiming.
    /// @dev Can only be called by the admin.
    function pause() external;

    /// @notice Unpause the contract, allowing claiming.
    /// @dev Can only be called by the admin.
    function unpause() external;

    /// @notice claim every UsualS token from UsualS contract
    /// @dev Can only be called by the admin
    function stakeUsualS() external;

    /// @notice start reward distribution
    /// @dev Can only be called by the distribution module contract
    /// @param amount the amount of reward token to distribute
    /// @param startTime the start time of the reward distribution
    /// @param endTime the end time of the reward distribution
    function startRewardDistribution(uint256 amount, uint256 startTime, uint256 endTime) external;

    /// @notice Returns the liquid allocation of an account.
    /// @param account The address of the account.
    /// @return The liquid allocation.
    function getLiquidAllocation(address account) external view returns (uint256);

    /// @notice Returns the total allocation of an account.
    /// @param account The address of the account.
    /// @return The total allocation.
    function balanceOf(address account) external view returns (uint256);

    /// @notice Returns the total staked amount.
    /// @return The total staked amount.
    function totalStaked() external view returns (uint256);

    /// @notice Returns the vesting duration.
    /// @return The duration.
    function getDuration() external view returns (uint256);

    /// @notice Returns the vesting cliff duration for an insider.
    /// @param insider The address of the insider.
    /// @return The cliff duration of the insider.
    function getCliffDuration(address insider) external view returns (uint256);

    /// @notice Returns the claimable amount of an insider.
    /// @param insider The address of the insider.
    /// @return The claimable amount.
    function getClaimableOriginalAllocation(address insider) external view returns (uint256);

    /// @notice Returns the claimed amount of an insider.
    /// @param insider The address of the insider.
    /// @return The claimed amount.
    function getClaimedAllocation(address insider) external view returns (uint256);

    /// @notice Returns the current reward rate (rewards distributed per second)
    /// @return The reward rate
    function getRewardRate() external view returns (uint256);

    /// @notice Returns the allocation start time of an account.
    /// @param account The address of the account.
    /// @return The allocation start time.
    function getAllocationStartTime(address account) external view returns (uint256);
}

src/interfaces/vaults/IUsualX.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IUsualX {
    /*//////////////////////////////////////////////////////////////
                            Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Event emitted when an address is blacklisted
    /// @param account The address that was blacklisted
    event Blacklist(address account);
    /// @notice Event emitted when an address is removed from the blacklist
    /// @param account The address that was removed from the blacklist
    event UnBlacklist(address account);
    /// @notice Event emitted when the withdrawal fee is updated
    /// @param newWithdrawFeeBps The new withdrawal fee in basis points
    event WithdrawFeeUpdated(uint256 newWithdrawFeeBps);
    /// @notice Event emitted when fees are swept
    /// @param caller The address calling the sweep
    /// @param collector The address receiving the fees
    /// @param amount The amount of fees swept
    event FeeSwept(address indexed caller, address indexed collector, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            Functions
    //////////////////////////////////////////////////////////////*/

    /// @notice Pauses the contract.
    /// @dev Can be called by the pauser to pause some contract operations.
    function pause() external;

    /// @notice Unpauses the contract.
    /// @dev Can be called by the admin to unpause some contract operations.
    function unpause() external;

    /// @notice  Adds an address to the blacklist.
    /// @dev     Can only be called by the admin.
    /// @param   account  The address to be blacklisted.
    function blacklist(address account) external;

    /// @notice  Removes an address from the blacklist.
    /// @dev     Can only be called by the admin.
    /// @param   account  The address to be removed from the blacklist.
    function unBlacklist(address account) external;

    /// @notice Checks if an address is blacklisted.
    /// @param account The address to check.
    /// @return bool True if the address is blacklisted.
    function isBlacklisted(address account) external view returns (bool);

    /// @notice Starts a new yield distribution period
    /// @dev Can only be called by the distribution contract
    /// @param yieldAmount The amount of yield to distribute
    /// @param startTime The start time of the new yield period
    /// @param endTime The end time of the new yield period
    function startYieldDistribution(uint256 yieldAmount, uint256 startTime, uint256 endTime)
        external;

    /// @notice Updates the withdrawal fee
    /// @dev Can only be called by addresses with WITHDRAW_FEE_UPDATER_ROLE
    /// @param newWithdrawFeeBps The new withdrawal fee in basis points
    function updateWithdrawFee(uint256 newWithdrawFeeBps) external;

    /// @notice Returns the withdrawal fee in basis points
    /// @return The withdrawal fee in basis points
    function withdrawFeeBps() external view returns (uint256);

    /// @notice Deposits assets with permit from msg.sender and mints shares to receiver.
    /// @param assets The amount of assets to deposit.
    /// @param receiver The address receiving the shares.
    /// @param deadline The deadline for the permit.
    /// @param v The recovery id for the permit.
    /// @param r The r value for the permit.
    /// @param s The s value for the permit.
    /// @return shares The amount of shares minted.
    function depositWithPermit(
        uint256 assets,
        address receiver,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256);

    /// @notice Deposits assets and mints shares to receiver.
    /// @param assets The amount of assets to deposit.
    /// @param receiver The address receiving the shares.
    /// @return shares The amount of shares minted.
    function deposit(uint256 assets, address receiver) external returns (uint256);

    /// @notice Mints shares to receiver.
    /// @param shares The amount of shares to mint.
    /// @param receiver The address receiving the shares.
    /// @return shares The amount of shares minted.
    function mint(uint256 shares, address receiver) external returns (uint256);

    /// @notice Withdraws assets from owner and sends exactly assets of underlying tokens to receiver,
    /// with the withdrawal fee taken in addition.
    /// @param assets The amount of assets to withdraw.
    /// @param receiver The address receiving the assets.
    /// @param owner The address owning the shares.
    /// @return shares The amount of shares burned.
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256);

    /// @notice Redeems shares from owner and sends exactly shares of underlying tokens to receiver,
    /// with the redemption fee taken in addition.
    /// @param shares The amount of shares to redeem.
    /// @param receiver The address receiving the assets.
    /// @param owner The address owning the shares.
    /// @return assets The amount of assets received.
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256);

    /// @notice Returns the amount of assets that would be received for a given amount of shares.
    /// @param assets The amount of shares to convert to assets.
    /// @return shares The amount of shares that would be received.
    function previewWithdraw(uint256 assets) external view returns (uint256);

    /// @notice Returns the maximum amount of assets that can be withdrawn by an address.
    /// @param owner The address to check.
    /// @return assets The maximum amount of assets that can be withdrawn.
    function maxWithdraw(address owner) external view returns (uint256);

    /// @notice Returns the amount of assets that would be received for a given amount of shares.
    /// @param shares The amount of shares to convert to assets.
    /// @return assets The amount of assets that would be received.
    function previewRedeem(uint256 shares) external view returns (uint256);

    /// @notice Sweeps fees to the collector.
    /// @return amount The amount of fees swept.
    function sweepFees() external returns (uint256);

    /// @notice Returns the yield rate.
    /// @return yieldRate The yield rate.
    function getYieldRate() external view returns (uint256);

    /// @notice Returns the accumulated fees.
    /// @return accumulatedFees The accumulated fees.
    function getAccumulatedFees() external view returns (uint256);
}

src/utils/CheckAccessControl.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IRegistryAccess} from "src/interfaces/registry/IRegistryAccess.sol";

import {NotAuthorized} from "src/errors.sol";

/// @title Check Access control library
library CheckAccessControl {
    /// @dev Function to restrict to one access role.
    /// @param registryAccess The registry access contract.
    /// @param role The role being checked.
    function onlyMatchingRole(IRegistryAccess registryAccess, bytes32 role) internal view {
        if (!registryAccess.hasRole(role, msg.sender)) {
            revert NotAuthorized();
        }
    }
}

src/utils/normalize.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {SCALAR_ONE} from "src/constants.sol";

/// @title Normalize decimals between tokens
library Normalize {
    /// @notice Normalize token amount to target decimals
    /// @notice i.e 100 USDC with 6 decimals to 100e18 USDC with 18 decimals
    /// @param tokenAmount The token amount
    /// @param tokenDecimals The token decimals
    /// @param targetDecimals The target decimals
    function tokenAmountToDecimals(uint256 tokenAmount, uint8 tokenDecimals, uint8 targetDecimals)
        internal
        pure
        returns (uint256)
    {
        if (tokenDecimals < targetDecimals) {
            return tokenAmount * (10 ** uint256(targetDecimals - tokenDecimals));
        } else if (tokenDecimals > targetDecimals) {
            return tokenAmount / (10 ** uint256(tokenDecimals - targetDecimals));
        } else {
            return tokenAmount;
        }
    }

    /// @notice Normalize token amount to 18 decimals
    /// @notice i.e 100 USDC with 6 decimals to 100e18 USDC with 18 decimals
    /// @param tokenAmount The token amount
    /// @param tokenDecimals The token decimals
    function tokenAmountToWad(uint256 tokenAmount, uint8 tokenDecimals)
        internal
        pure
        returns (uint256)
    {
        return tokenAmountToDecimals(tokenAmount, tokenDecimals, 18);
    }

    /// @notice Normalize token amount to wad
    /// @notice i.e 10e6 USYC with 6 decimals will result in wadAmount = 10e18 and  tokenDecimals = 6
    /// @param token The token address
    /// @param tokenAmount The token amount
    /// @return wadAmount The normalized token amount in wad
    /// @return tokenDecimals The token decimals
    function tokenAmountToWadWithTokenAddress(uint256 tokenAmount, address token)
        internal
        view
        returns (uint256, uint8)
    {
        uint8 tokenDecimals = uint8(IERC20Metadata(token).decimals());
        uint256 wadAmount = tokenAmountToWad(tokenAmount, uint8(tokenDecimals));
        return (wadAmount, tokenDecimals);
    }

    /// @notice Returns wad amount of token at wad price.
    /// @notice i.e 10e6 USYC with 6 decimals will be wadAmount = 10e18
    /// @notice if wadPrice is 1e18 USD then 10e18 USD0 will be worth 10e18 USD
    /// @param wadAmount The wad amount (18 decimals)
    /// @param wadPrice The wad price (18 decimals)
    /// @return The normalized token amount for price
    function wadAmountByPrice(uint256 wadAmount, uint256 wadPrice)
        internal
        pure
        returns (uint256)
    {
        return Math.mulDiv(wadAmount, wadPrice, SCALAR_ONE, Math.Rounding.Floor);
    }

    /// @notice return how much token we can have for stable amount.
    /// @notice i.e 10 (10e18) USD0 with 18 decimals worth 2$ each (2e18) will return 5e6 USYC with 6 decimals
    /// @param wadStableAmount The wad stable token amount
    /// @param wadPrice The wad price with for the token in stable
    /// @param tokenDecimals The token decimals
    /// @return The token amount for price with token decimals
    function wadTokenAmountForPrice(uint256 wadStableAmount, uint256 wadPrice, uint8 tokenDecimals)
        internal
        pure
        returns (uint256)
    {
        return Math.mulDiv(wadStableAmount, 10 ** tokenDecimals, wadPrice, Math.Rounding.Floor);
    }

    /// @dev Converts a WAD amount to a different number of decimals.
    /// @param wadAmount The WAD amount to convert.
    /// @param targetDecimals The number of decimals to convert to.
    /// @return The converted amount with the target number of decimals.
    function wadAmountToDecimals(uint256 wadAmount, uint8 targetDecimals)
        internal
        pure
        returns (uint256)
    {
        return tokenAmountToDecimals(wadAmount, 18, targetDecimals);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "utils/=lib/utils/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "src/=src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.