Skip to content
Verified contractExactAGPL-3.0-or-later

NFATHaloFacet

Address0xfb0b4ff6507d57a0ac7bd10b53c1f2de827f87c1
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
AGPL-3.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,442,690
Creation transaction
0x2fe2c233f8…31bfe72586

src/facets/nfat-halo/NFATHaloFacet.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

import { ApproveLib }            from "../../libraries/ApproveLib.sol";
import { makeAddressAddressKey } from "../../libraries/RateLimitHelpers.sol";

import { IALMProxy } from "../../interfaces/IALMProxy.sol";

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

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

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

interface IERC20Like {

    function balanceOf(address account) external view returns (uint256);

}

interface IFacilityLike {

    function gem() external view returns (address);

    function issue(address to, uint256 tokenId, uint256 amount) external;

    function repay(uint256 tokenId, uint256 amount) external;

}

contract NFATHaloFacet is INFATHaloFacet, Facet {

    /**********************************************************************************************/
    /*** Facet Storage Domain                                                                   ***/
    /**********************************************************************************************/

    /// @custom:storage-location erc7201:sky.pau.storage.NFATHaloFacet.v1
    struct FacetStorage {
        mapping (address facility => Parameters params)                         parameters;
        mapping (address facility => FacilityState state)                       states;
        mapping (address facility => mapping (uint256 tokenId => Position pos)) positions;
    }

    // keccak256(abi.encode(uint256(keccak256("sky.pau.storage.NFATHaloFacet.v1")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 internal constant FACET_STORAGE_LOCATION =
        0x9374587c30f7383b766c0ada49451c0a4d8cea55cebbd6eec5b0112712b60800;

    function _getFacetStorage() internal pure returns (FacetStorage storage $) {
        assembly {
            $.slot := FACET_STORAGE_LOCATION
        }
    }

    /**********************************************************************************************/
    /*** Constants                                                                              ***/
    /**********************************************************************************************/

    bytes32 internal constant _LIMIT_ISSUE           = keccak256("LIMIT_NFAT_HALO_ISSUE");
    bytes32 internal constant _LIMIT_REPAY_PRINCIPAL = keccak256("LIMIT_NFAT_HALO_REPAY_PRINCIPAL");
    bytes32 internal constant _LIMIT_REPAY_INTEREST  = keccak256("LIMIT_NFAT_HALO_REPAY_INTEREST");

    uint256 internal constant _INTEREST_RATE_PRECISION = 1e18;
    uint256 internal constant _YEAR                    = 365 days;

    /// @inheritdoc IFacet
    string public constant override VERSION = "1.0.0";

    /**********************************************************************************************/
    /*** External Interactive Admin Functions                                                   ***/
    /**********************************************************************************************/

    /// @inheritdoc INFATHaloFacet
    function setMaxAnnualGrowthRate(address facility, uint256 maxAnnualGrowthRate)
        external
        override
        nonReentrant
        onlyRole(DEFAULT_ADMIN_ROLE)
    {
        require(facility != address(0), "NFATHaloFacet/facility-zero-address");

        _checkpointFacility(facility);

        _getFacetStorage().parameters[facility].maxAnnualGrowthRate = maxAnnualGrowthRate;

        emit NFATHaloMaxAnnualGrowthRateSet(facility, maxAnnualGrowthRate);
    }

    /**********************************************************************************************/
    /*** External Interactive Allocator Functions                                               ***/
    /**********************************************************************************************/

    /// @inheritdoc INFATHaloFacet
    function issue(address facility, address to, uint256 tokenId, uint256 amount)
        external
        override
        nonReentrant
        onlyRole(ALLOCATOR_ROLE)
    {
        require(amount != 0, "NFATHaloFacet/zero-amount");

        _checkpointFacility(facility);

        address proxy = _getSharedControllerStorage().proxy;
        address gem   = IFacilityLike(facility).gem();

        FacetStorage storage $        = _getFacetStorage();
        Position     storage position = $.positions[facility][tokenId];

        require(!position.issued, "NFATHaloFacet/position-exists");

        uint256 startingBalance = IERC20Like(gem).balanceOf(proxy);

        IALMProxy(proxy).doCall(
            facility,
            abi.encodeCall(IFacilityLike.issue, (to, tokenId, amount))
        );

        uint256 received = IERC20Like(gem).balanceOf(proxy) - startingBalance;

        position.issued               = true;
        position.outstandingPrincipal = received;
        position.interestIndex        = $.states[facility].interestIndex;

        _decreaseRateLimit(getIssueRateLimitKey(facility, to), received);

        emit NFATHaloIssue(facility, to, tokenId, received);
    }

    /// @inheritdoc INFATHaloFacet
    function repayPrincipal(address facility, uint256 tokenId, uint256 amount)
        external
        override
        nonReentrant
        onlyRole(ALLOCATOR_ROLE)
    {
        require(amount != 0, "NFATHaloFacet/zero-amount");

        Position storage position = _checkpointPosition(facility, tokenId);

        require(amount <= position.outstandingPrincipal, "NFATHaloFacet/principal-exceeded");

        address gem = IFacilityLike(facility).gem();

        uint256 spent = _doFacilityRepay(facility, gem, tokenId, amount);

        position.outstandingPrincipal -= spent;

        _decreaseRateLimit(getRepayPrincipalRateLimitKey(facility, gem), spent);

        emit NFATHaloRepayPrincipal(facility, tokenId, spent);
    }

    /// @inheritdoc INFATHaloFacet
    function repayInterest(address facility, uint256 tokenId, uint256 amount)
        external
        override
        nonReentrant
        onlyRole(ALLOCATOR_ROLE)
    {
        require(amount != 0, "NFATHaloFacet/zero-amount");

        Position storage position = _checkpointPosition(facility, tokenId);

        require(amount <= position.maxOutstandingInterest, "NFATHaloFacet/max-interest-exceeded");

        address gem = IFacilityLike(facility).gem();

        uint256 spent = _doFacilityRepay(facility, gem, tokenId, amount);

        position.maxOutstandingInterest -= spent;

        _decreaseRateLimit(getRepayInterestRateLimitKey(facility, gem), spent);

        emit NFATHaloRepayInterest(facility, tokenId, spent);
    }

    /**********************************************************************************************/
    /*** External View/Pure Functions                                                           ***/
    /**********************************************************************************************/

    /// @inheritdoc INFATHaloFacet
    function getMaxAnnualGrowthRate(address facility) external view override returns (uint256) {
        return _getFacetStorage().parameters[facility].maxAnnualGrowthRate;
    }

    /// @inheritdoc INFATHaloFacet
    function getFacilityState(address facility)
        external
        view
        override
        returns (uint256 interestIndex, uint256 lastUpdated)
    {
        FacilityState storage state = _getFacetStorage().states[facility];
        return (state.interestIndex, state.lastUpdated);
    }

    /// @inheritdoc INFATHaloFacet
    function getPosition(address facility, uint256 tokenId)
        external
        view
        override
        returns (
            bool    issued,
            uint256 outstandingPrincipal,
            uint256 maxOutstandingInterest,
            uint256 interestIndex
        )
    {
        Position storage position = _getFacetStorage().positions[facility][tokenId];

        return (
            position.issued,
            position.outstandingPrincipal,
            position.maxOutstandingInterest,
            position.interestIndex
        );
    }

    /// @inheritdoc INFATHaloFacet
    function getCurrentMaxOutstandingInterest(address facility, uint256 tokenId)
        external
        view
        override
        returns (uint256)
    {
        Position storage position = _getFacetStorage().positions[facility][tokenId];

        require(position.issued, "NFATHaloFacet/position-not-found");

        uint256 currentIndex = _getCurrentInterestIndex(facility);
        uint256 deltaIndex   = currentIndex - position.interestIndex;

        return
            position.maxOutstandingInterest +
            position.outstandingPrincipal * deltaIndex / _INTEREST_RATE_PRECISION;
    }

    /// @inheritdoc INFATHaloFacet
    function getIssueRateLimitKey(address facility, address to)
        public
        pure
        override
        returns (bytes32)
    {
        return makeAddressAddressKey(_LIMIT_ISSUE, facility, to);
    }

    /// @inheritdoc INFATHaloFacet
    function getRepayInterestRateLimitKey(address facility, address gem)
        public
        pure
        override
        returns (bytes32)
    {
        return makeAddressAddressKey(_LIMIT_REPAY_INTEREST, gem, facility);
    }

    /// @inheritdoc INFATHaloFacet
    function getRepayPrincipalRateLimitKey(address facility, address gem)
        public
        pure
        override
        returns (bytes32)
    {
        return makeAddressAddressKey(_LIMIT_REPAY_PRINCIPAL, gem, facility);
    }

    /**********************************************************************************************/
    /*** Internal Interactive Functions                                                         ***/
    /**********************************************************************************************/

    function _checkpointFacility(address facility) internal {
        FacilityState storage state = _getFacetStorage().states[facility];

        uint256 lastUpdated = state.lastUpdated;

        if (lastUpdated == block.timestamp) return;

        state.interestIndex = _getCurrentInterestIndex(facility);
        state.lastUpdated   = block.timestamp;
    }

    function _checkpointPosition(address facility, uint256 tokenId)
        internal
        returns (Position storage position)
    {
        _checkpointFacility(facility);

        FacetStorage storage $ = _getFacetStorage();

        position = $.positions[facility][tokenId];

        require(position.issued, "NFATHaloFacet/position-not-found");

        uint256 currentIndex = $.states[facility].interestIndex;

        position.maxOutstandingInterest +=
            position.outstandingPrincipal * (currentIndex - position.interestIndex)
            / _INTEREST_RATE_PRECISION;

        position.interestIndex = currentIndex;
    }

    function _doFacilityRepay(address facility, address gem, uint256 tokenId, uint256 amount)
        internal
        returns (uint256 spent)
    {
        address proxy = _getSharedControllerStorage().proxy;

        ApproveLib.approve(gem, proxy, facility, amount);

        uint256 startingBalance = IERC20Like(gem).balanceOf(proxy);

        IALMProxy(proxy).doCall(facility, abi.encodeCall(IFacilityLike.repay, (tokenId, amount)));

        ApproveLib.approve(gem, proxy, facility, 0);

        spent = startingBalance - IERC20Like(gem).balanceOf(proxy);
    }

    /**********************************************************************************************/
    /*** Internal View/Pure Functions                                                           ***/
    /**********************************************************************************************/

    function _getCurrentInterestIndex(address facility) internal view returns (uint256) {
        FacetStorage  storage $     = _getFacetStorage();
        FacilityState storage state = $.states[facility];

        uint256 lastUpdated = state.lastUpdated;

        if (lastUpdated == 0) return state.interestIndex;

        return
            state.interestIndex +
            $.parameters[facility].maxAnnualGrowthRate * (block.timestamp - lastUpdated) / _YEAR;
    }

}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

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

src/ControllerSharedStorage.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

abstract contract ControllerSharedStorage {

    /**********************************************************************************************/
    /*** Shared Controller Storage Domain                                                       ***/
    /**********************************************************************************************/

    /// @custom:storage-location erc7201:sky.pau.storage.SharedController
    struct SharedControllerStorage {
        address accessControls;
        address proxy;
        address rateLimits;
    }

    // keccak256(abi.encode(uint256(keccak256("sky.pau.storage.SharedController")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 internal constant SHARED_CONTROLLER_STORAGE_LOCATION =
        0x77adf60bdbfedf206f8b8310f3d364080b7f61dcc0e46caac13c29bb1eb5cc00;

    function _getSharedControllerStorage()
        internal
        pure
        returns (SharedControllerStorage storage $)
    {
        assembly {
            $.slot := SHARED_CONTROLLER_STORAGE_LOCATION
        }
    }

}

src/facets/Facet.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

import {
    ReentrancyGuardUpgradeable
} from "../../lib/oz-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol";

import { IAccessControls } from "../interfaces/IAccessControls.sol";
import { IRateLimits }     from "../interfaces/IRateLimits.sol";

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

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

abstract contract Facet is IFacet, ControllerSharedStorage, ReentrancyGuardUpgradeable {

    /**********************************************************************************************/
    /*** Constants                                                                              ***/
    /**********************************************************************************************/

    /// @inheritdoc IFacet
    bytes32 public constant override DEFAULT_ADMIN_ROLE = 0x00;

    /// @inheritdoc IFacet
    bytes32 public constant override ALLOCATOR_ROLE = keccak256("ALLOCATOR_ROLE");

    /**********************************************************************************************/
    /*** Modifiers                                                                              ***/
    /**********************************************************************************************/

    modifier onlyRole(bytes32 role) {
        address accessControls = _getSharedControllerStorage().accessControls;

        require(
            IAccessControls(accessControls).hasRole(role, msg.sender),
            AccessControlUnauthorizedAccount(msg.sender, role)
        );

        _;
    }

    /**********************************************************************************************/
    /*** Internal Interactive Functions                                                         ***/
    /**********************************************************************************************/

    function _increaseRateLimit(bytes32 key, uint256 amount) internal {
        IRateLimits(_getSharedControllerStorage().rateLimits).triggerRateLimitIncrease(key, amount);
    }

    function _decreaseRateLimit(bytes32 key, uint256 amount) internal {
        IRateLimits(_getSharedControllerStorage().rateLimits).triggerRateLimitDecrease(key, amount);
    }

    function _sweepETH() internal {
        _getSharedControllerStorage().proxy.call{value: address(this).balance}("");
    }

    function _tryIncreaseRateLimit(bytes32 key, uint256 amount) internal {
        if (!_rateLimitExists(key)) return;

        _increaseRateLimit(key, amount);
    }

    /**********************************************************************************************/
    /*** Internal View/Pure Functions                                                           ***/
    /**********************************************************************************************/

    function _rateLimitExists(bytes32 key) internal view returns (bool) {
        return IRateLimits(
            _getSharedControllerStorage().rateLimits
        ).getRateLimitData(key).maxAmount > 0;
    }

}

src/facets/IFacet.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

/**
 * @title  IFacet
 * @notice Base interface inherited by all PAU facets. Defines shared roles, versioning,
 *         and access control errors.
 */
interface IFacet {

    /**********************************************************************************************/
    /*** Errors                                                                                 ***/
    /**********************************************************************************************/

    /// @notice Thrown when a caller lacks the required access control role.
    error AccessControlUnauthorizedAccount(address caller, bytes32 role);

    /**********************************************************************************************/
    /*** Variables                                                                              ***/
    /**********************************************************************************************/

    /// @notice Role identifier for the default admin (bytes32(0)).
    function DEFAULT_ADMIN_ROLE() external pure returns (bytes32);

    /// @notice Role identifier for allocator accounts authorized to execute facet operations.
    function ALLOCATOR_ROLE() external pure returns (bytes32);

    /// @notice Semantic version string of the facet.
    function VERSION() external pure returns (string memory);

}

src/facets/nfat-halo/INFATHaloFacet.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

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

/**
 * @title  INFATHaloFacet
 * @notice PAU facet for the Halo (recipient) side of an NFAT facility. Issues NFT positions
 *         against prior subscriptions, accrues per-facility interest via a configurable annual
 *         growth rate, and exposes split repayment flows for principal and interest. Operational
 *         entry points are gated on ALLOCATOR_ROLE and rate-limited per (facility, recipient or
 *         gem) tuple.
 */
interface INFATHaloFacet is IFacet {

    /**********************************************************************************************/
    /*** Structs                                                                                ***/
    /**********************************************************************************************/

    /**
     * @notice Per-facility tunable parameters.
     * @param  maxAnnualGrowthRate Max annual growth rate (1e18-scaled APR; 1e18 == 100%/year) used
     *                             to drive interest accrual on issued positions.
     */
    struct Parameters {
        uint256 maxAnnualGrowthRate;
    }

    /**
     * @notice Per-facility checkpoint state used to compute the cumulative interest index.
     * @param  interestIndex Cumulative 1e18-scaled interest accrued per unit of principal as of
     *                       `lastUpdated`. Combine with elapsed time and the current annual
     *                       growth rate to derive the live index.
     * @param  lastUpdated   Timestamp of the last checkpoint. Zero means the facility has never
     *                       been configured via `setMaxAnnualGrowthRate`.
     */
    struct FacilityState {
        uint256 interestIndex;
        uint256 lastUpdated;
    }

    /**
     * @notice Per-NFAT bookkeeping recorded by this facet.
     * @param  issued                 Whether the NFAT position has been issued.
     * @param  outstandingPrincipal   Outstanding principal.
     * @param  maxOutstandingInterest Max outstanding interest.
     * @param  interestIndex          Facility-wide interest index recorded at the last checkpoint.
     */
    struct Position {
        bool    issued;
        uint256 outstandingPrincipal;
        uint256 maxOutstandingInterest;
        uint256 interestIndex;
    }

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

    /**
     * @notice Emitted when the max annual growth rate (1e18-scaled APR) for a facility is updated.
     * @param  facility            Address of the NFAT facility.
     * @param  maxAnnualGrowthRate New max annual growth rate, 1e18 = 100% APR.
     */
    event NFATHaloMaxAnnualGrowthRateSet(address indexed facility, uint256 maxAnnualGrowthRate);

    /**
     * @notice Emitted when an NFAT NFT is issued via this facet.
     * @param  facility Address of the NFAT facility.
     * @param  to       Recipient of the minted NFT (becomes the NFAT owner).
     * @param  tokenId  Identifier of the freshly minted NFAT token.
     * @param  amount   Principal recorded for this token (gem-native decimals).
     */
    event NFATHaloIssue(
        address indexed facility,
        address indexed to,
        uint256 indexed tokenId,
        uint256         amount
    );

    /**
     * @notice Emitted when interest is repaid against an issued NFAT position.
     * @param  facility Address of the NFAT facility.
     * @param  tokenId  Identifier of the NFAT token being repaid against.
     * @param  amount   Interest amount repaid (gem-native decimals).
     */
    event NFATHaloRepayInterest(address indexed facility, uint256 indexed tokenId, uint256 amount);

    /**
     * @notice Emitted when principal is repaid against an issued NFAT position.
     * @param  facility Address of the NFAT facility.
     * @param  tokenId  Identifier of the NFAT token being repaid against.
     * @param  amount   Principal amount repaid (gem-native decimals).
     */
    event NFATHaloRepayPrincipal(address indexed facility, uint256 indexed tokenId, uint256 amount);

    /**********************************************************************************************/
    /*** Interactive Functions                                                                  ***/
    /**********************************************************************************************/

    /**
     * @notice Issues an NFAT NFT and records the recorded principal for `tokenId`. The facility
     *         transfers the gem from itself to its configured recipient — which MUST be the
     *         controller's ALMProxy, so the principal lands back in our custody. Both the
     *         recorded `principal` and the consumed (facility, to) issue rate limit are sized
     *         from the actual ALMProxy gem balance delta, not the requested `amount`.
     * @param  facility Address of the NFAT facility. Its `recipient()` must equal the ALMProxy.
     * @param  to       Address to receive the NFT.
     * @param  tokenId  Token id to mint.
     * @param  amount   Requested principal to pull from the facility's deposit accounting.
     */
    function issue(address facility, address to, uint256 tokenId, uint256 amount) external;

    /**
     * @notice Repays interest against an issued NFAT position. Bounded by `maxOutstandingInterest` after
     *         checkpointing; consumes the (facility, gem) repay-interest rate limit.
     * @param  facility Address of the NFAT facility.
     * @param  tokenId  Identifier of the NFAT token being repaid against.
     * @param  amount   Interest amount to repay. Must be non-zero and <= currently-accrued interest.
     */
    function repayInterest(address facility, uint256 tokenId, uint256 amount) external;

    /**
     * @notice Repays principal owed on an issued NFAT position. Bounded by remaining principal
     *         (`principal - principalRepaid`); consumes the (facility, gem) repay-principal
     *         rate limit.
     * @param  facility Address of the NFAT facility.
     * @param  tokenId  Identifier of the NFAT token being repaid against.
     * @param  amount   Principal amount to repay. Must be non-zero and <= remaining principal.
     */
    function repayPrincipal(address facility, uint256 tokenId, uint256 amount) external;

    /**
     * @notice Sets the annual growth rate (1e18-scaled APR) used for interest accrual on a
     *         facility. Checkpoints the facility before applying the new rate so accrued interest
     *         under the previous rate is preserved.
     * @param  facility            Address of the NFAT facility.
     * @param  maxAnnualGrowthRate New max annual growth rate, 1e18 = 100% APR.
     */
    function setMaxAnnualGrowthRate(address facility, uint256 maxAnnualGrowthRate) external;

    /**********************************************************************************************/
    /*** View/Pure Functions                                                                    ***/
    /**********************************************************************************************/

    /**
     * @notice Returns the configured annual growth rate (1e18-scaled APR) for a facility.
     * @param  facility            Address of the NFAT facility.
     * @return maxAnnualGrowthRate Max annual growth rate, 1e18 = 100% APR. Zero if unset.
     */
    function getMaxAnnualGrowthRate(address facility)
        external
        view
        returns (uint256 maxAnnualGrowthRate);

    /**
     * @notice Returns the last facility-wide interest index checkpoint and time of the checkpoint.
     * @param  facility      Address of the NFAT facility.
     * @return interestIndex Last cumulative 1e18-scaled interest index checkpoint.
     * @return lastUpdated   Timestamp of the last checkpoint. Zero means the facility has never
     *                       been configured.
     */
    function getFacilityState(address facility)
        external
        view
        returns (uint256 interestIndex, uint256 lastUpdated);

    /**
     * @notice Returns the derived issue rate limit key for an NFAT facility and NFT recipient.
     * @param  facility Address of the NFAT facility.
     * @param  to       Address that will receive issued NFAT NFTs under the configured budget.
     * @return key      Derived rate limit key.
     */
    function getIssueRateLimitKey(address facility, address to)
        external
        pure
        returns (bytes32 key);

    /**
     * @notice Returns the outstanding principal, outstanding interest, and interest index for a
     *         given NFAT position.
     * @param  facility               Address of the NFAT facility.
     * @param  tokenId                Identifier of the NFAT token.
     * @return issued                 Whether the NFAT position has been issued.
     * @return outstandingPrincipal   Outstanding principal.
     * @return maxOutstandingInterest Last checkpointed max outstanding interest.
     * @return interestIndex          Last checkpointed facility-wide interest index.
     */
    function getPosition(address facility, uint256 tokenId)
        external
        view
        returns (
            bool    issued,
            uint256 outstandingPrincipal,
            uint256 maxOutstandingInterest,
            uint256 interestIndex
        );

    /**
     * @notice Returns the current outstanding interest for a given NFAT position.
     * @param  facility               Address of the NFAT facility.
     * @param  tokenId                Identifier of the NFAT token.
     * @return maxOutstandingInterest Current max outstanding interest.
     */
    function getCurrentMaxOutstandingInterest(address facility, uint256 tokenId)
        external
        view
        returns (uint256);

    /**
     * @notice Returns the derived repay-interest rate limit key for an NFAT facility and gem.
     * @dev    Keyed on (facility, gem) so a facility cannot change its gem under a configured
     *         rate limit; switching the gem invalidates the key.
     * @param  facility Address of the NFAT facility.
     * @param  gem      Address of the facility's gem token at configuration time.
     * @return key      Derived rate limit key.
     */
    function getRepayInterestRateLimitKey(address facility, address gem)
        external
        pure
        returns (bytes32 key);

    /**
     * @notice Returns the derived repay-principal rate limit key for an NFAT facility and gem.
     * @dev    Keyed on (facility, gem) so a facility cannot change its gem under a configured
     *         rate limit; switching the gem invalidates the key.
     * @param  facility Address of the NFAT facility.
     * @param  gem      Address of the facility's gem token at configuration time.
     * @return key      Derived rate limit key.
     */
    function getRepayPrincipalRateLimitKey(address facility, address gem)
        external
        pure
        returns (bytes32 key);

}

src/interfaces/IALMProxy.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

import {
    IAccessControl
} from "../../lib/openzeppelin-contracts/contracts/access/IAccessControl.sol";

/**
 * @title  IALMProxy
 * @notice Proxy contract that executes calls, value calls, and delegate calls on behalf of the
 *         PAU system. Only accounts with the CONTROLLER role can invoke its functions.
 */
interface IALMProxy is IAccessControl {

    /**********************************************************************************************/
    /*** Custom Errors                                                                          ***/
    /**********************************************************************************************/

    /// @notice Thrown when the admin is the zero address.
    error ZeroAdmin();

    /**********************************************************************************************/
    /*** Interactive Functions                                                                  ***/
    /**********************************************************************************************/

    /**
     * @notice Performs a standard call to the specified `target` with the given `data`.
     *         Reverts if the call fails.
     * @param  target The address of the target contract to call.
     * @param  data   The calldata that will be sent to the target contract.
     * @return result The returned data from the call.
     */
    function doCall(address target, bytes calldata data) external returns (bytes memory result);

    /**
     * @notice This function allows for transferring `value` (ether) along with the call to the
     *         target contract. Reverts if the call fails.
     * @param  target The address of the target contract to call.
     * @param  data   The calldata that will be sent to the target contract.
     * @param  value  The amount of Ether (in wei) to send with the call.
     * @return result The returned data from the call.
     */
    function doCallWithValue(address target, bytes calldata data, uint256 value)
        external
        payable
        returns (bytes memory result);

    /**
     * @notice This function performs a delegate call to the specified `target` with the given
     *         `data`. Reverts if the call fails.
     * @param  target The address of the target contract to delegate call.
     * @param  data   The calldata that will be sent to the target contract.
     * @return result The returned data from the delegate call.
     */
    function doDelegateCall(address target, bytes calldata data)
        external
        returns (bytes memory result);

    /**********************************************************************************************/
    /*** Variables                                                                              ***/
    /**********************************************************************************************/

    /**
     * @notice This function retrieves a constant `bytes32` value that represents the controller.
     * @return The `bytes32` identifier of the controller.
     */
    function CONTROLLER() external view returns (bytes32);

}

src/interfaces/IAccessControls.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

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

/**
 * @title  IAccessControls
 * @notice Role-based access control interface for PAU system, extending OpenZeppelin's
 *         AccessControlEnumerable.
 */
interface IAccessControls is IAccessControlEnumerable {

    /**********************************************************************************************/
    /*** Custom Errors                                                                          ***/
    /**********************************************************************************************/

    /// @notice Thrown when the admin is the zero address.
    error ZeroAdmin();

    /**********************************************************************************************/
    /*** Interactive Admin Functions                                                            ***/
    /**********************************************************************************************/

    /**
     * @notice Sets the admin role for a given role.
     * @param role      The role to set the admin for.
     * @param adminRole The admin role for the given role.
     */
    function setRoleAdmin(bytes32 role, bytes32 adminRole) external;

    /**********************************************************************************************/
    /*** View/Pure Functions                                                                    ***/
    /**********************************************************************************************/

    /**
     * @notice Returns true if the contract supports the given interface.
     * @param  interfaceId The 4-byte interface identifier (ERC-165).
     * @return isSupported True if the interface is supported, false otherwise.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);

}

src/interfaces/IRateLimits.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

import {
    IAccessControl
} from "../../lib/openzeppelin-contracts/contracts/access/IAccessControl.sol";

/**
 * @title  IRateLimits
 * @notice Per-key rate limiting contract for the PAU system. Tracks time-based allowances
 *         that refill linearly and are consumed by controller operations.
 */
interface IRateLimits is IAccessControl {

    /**********************************************************************************************/
    /*** Structs                                                                                ***/
    /**********************************************************************************************/

    /**
     * @notice Struct representing a rate limit.
     *         The current rate limit is calculated using the formula:
     *         `currentRateLimit = min(slope * (block.timestamp - lastUpdated) + lastAmount, maxAmount)`.
     * @param  maxAmount   Maximum allowed amount at any time.
     * @param  slope       The slope of the rate limit, used to calculate the new limit based on
     *                     time passed. [tokens / second]
     * @param  lastAmount  The amount left available at the last update.
     * @param  lastUpdated The timestamp when the rate limit was last updated.
     */
    struct RateLimitData {
        uint256 maxAmount;
        uint256 slope;
        uint256 lastAmount;
        uint256 lastUpdated;
    }

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

    /**
     * @notice Emitted when the rate limit data is set.
     * @param  key         The identifier for the rate limit.
     * @param  maxAmount   The maximum allowed amount for the rate limit.
     * @param  slope       The slope value used in the rate limit calculation.
     * @param  lastAmount  The amount left available at the last update.
     * @param  lastUpdated The timestamp when the rate limit was last updated.
     */
    event RateLimitDataSet(
        bytes32 indexed key,
        uint256         maxAmount,
        uint256         slope,
        uint256         lastAmount,
        uint256         lastUpdated
    );

    /**
     * @notice Emitted when a rate limit decrease is triggered.
     * @param  key              The identifier for the rate limit.
     * @param  amountToDecrease The amount to decrease from the current rate limit.
     * @param  oldRateLimit     The previous rate limit value before triggering.
     * @param  newRateLimit     The new rate limit value after triggering.
     */
    event RateLimitDecreaseTriggered(
        bytes32 indexed key,
        uint256         amountToDecrease,
        uint256         oldRateLimit,
        uint256         newRateLimit
    );

    /**
     * @notice Emitted when a rate limit increase is triggered.
     * @param  key              The identifier for the rate limit.
     * @param  amountToIncrease The amount to increase from the current rate limit.
     * @param  oldRateLimit     The previous rate limit value before triggering.
     * @param  newRateLimit     The new rate limit value after triggering.
     */
    event RateLimitIncreaseTriggered(
        bytes32 indexed key,
        uint256         amountToIncrease,
        uint256         oldRateLimit,
        uint256         newRateLimit
    );

    /**********************************************************************************************/
    /*** Custom Errors                                                                          ***/
    /**********************************************************************************************/

    /// @notice Thrown when the admin is the zero address.
    error ZeroAdmin();

    /**********************************************************************************************/
    /*** Interactive Admin Functions                                                            ***/
    /**********************************************************************************************/

    /**
     * @notice Sets rate limit data for a specific key.
     * @param  key         The identifier for the rate limit.
     * @param  maxAmount   The maximum allowed amount for the rate limit.
     * @param  slope       The slope value used in the rate limit calculation.
     * @param  lastAmount  The amount left available at the last update.
     * @param  lastUpdated The timestamp when the rate limit was last updated.
     */
    function setRateLimitData(
        bytes32 key,
        uint256 maxAmount,
        uint256 slope,
        uint256 lastAmount,
        uint256 lastUpdated
    ) external;

    /**
     * @notice Sets rate limit data for a specific key with
     *        `lastAmount == maxAmount` and `lastUpdated == block.timestamp`.
     * @param  key       The identifier for the rate limit.
     * @param  maxAmount The maximum allowed amount for the rate limit.
     * @param  slope     The slope value used in the rate limit calculation.
     */
    function setRateLimitData(bytes32 key, uint256 maxAmount, uint256 slope) external;

    /**
     * @notice Sets an unlimited rate limit.
     * @param  key The identifier for the rate limit.
     */
    function setUnlimitedRateLimitData(bytes32 key) external;

    /**********************************************************************************************/
    /*** Interactive Controller Functions                                                       ***/
    /**********************************************************************************************/

    /**
     * @notice Triggers the rate limit for a specific key and reduces the available amount by the
     *         provided value.
     * @param  key              The identifier for the rate limit.
     * @param  amountToDecrease The amount to decrease from the current rate limit.
     * @return newLimit         The updated rate limit after the deduction.
     */
    function triggerRateLimitDecrease(bytes32 key, uint256 amountToDecrease)
        external
        returns (uint256 newLimit);

    /**
     * @notice Increases the rate limit for a given key up to the maxAmount. Does not revert if the
     *         new rate limit exceeds the maxAmount.
     * @param  key              The identifier for the rate limit.
     * @param  amountToIncrease The amount to increase from the current rate limit.
     * @return newLimit         The updated rate limit after the addition.
     */
    function triggerRateLimitIncrease(bytes32 key, uint256 amountToIncrease)
        external
        returns (uint256 newLimit);

    /**********************************************************************************************/
    /*** Variables                                                                              ***/
    /**********************************************************************************************/

    /// @notice Role identifier for controller accounts that can increase/decrease rate limits.
    function CONTROLLER() external view returns (bytes32);

    /**********************************************************************************************/
    /*** View/Pure Functions                                                                    ***/
    /**********************************************************************************************/

    /**
     * @notice Retrieves the current rate limit for a specific key.
     * @param  key       The identifier for the rate limit.
     * @return rateLimit The current rate limit value for the given key.
     */
    function getCurrentRateLimit(bytes32 key) external view returns (uint256 rateLimit);

    /**
     * @notice Retrieves the RateLimitData struct associated with a specific key.
     * @param  key  The identifier for the rate limit.
     * @return data The data associated with the rate limit.
     */
    function getRateLimitData(bytes32 key) external view returns (RateLimitData memory data);

}

src/libraries/ApproveLib.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

import { IALMProxy } from "../interfaces/IALMProxy.sol";

interface IERC20Like {

    function approve(address spender, uint256 amount) external returns (bool success);

}

library ApproveLib {

    // NOTE: This logic was inspired by OpenZeppelin's forceApprove in SafeERC20 library.
    function approve(address token, address proxy, address spender, uint256 amount) internal {
        bytes memory approveData = abi.encodeCall(IERC20Like.approve, (spender, amount));

        // Call doCall on proxy to approve the token.
        ( bool success, bytes memory data )
            = proxy.call(abi.encodeCall(IALMProxy.doCall, (token, approveData)));

        bytes memory returnData;

        if (success) {
            // Decode the ABI-encoding of the approve call bytes return data first.
            returnData = abi.decode(data, (bytes));

            // Approve was successful if 1) no return value or 2) true return value.
            if (
                returnData.length == 0 ||
                (returnData.length == 32 && abi.decode(returnData, (bool)))
            ) return;
        }

        // If call was unsuccessful, set to zero and try again.
        IALMProxy(proxy).doCall(token, abi.encodeCall(IERC20Like.approve, (spender, 0)));

        returnData = IALMProxy(proxy).doCall(token, approveData);

        // Revert if approve returns false.
        require(
            returnData.length == 0 || (returnData.length == 32 && abi.decode(returnData, (bool))),
            "ApproveLib/approve-failed"
        );
    }

}

src/libraries/RateLimitHelpers.sol

// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.34;

function makeAddressKey(bytes32 key, address a) pure returns (bytes32) {
    return keccak256(abi.encode(key, a));
}

function makeAddressAddressKey(bytes32 key, address a, address b) pure returns (bytes32) {
    return keccak256(abi.encode(key, a, b));
}

function makeAddressAddressAddressKey(bytes32 key, address a, address b, address c)
    pure
    returns (bytes32)
{
    return keccak256(abi.encode(key, a, b, c));
}

function makeAddressBytes32Key(bytes32 key, address a, bytes32 b) pure returns (bytes32) {
    return keccak256(abi.encode(key, a, b));
}

function makeAddressUint16Key(bytes32 key, address a, uint16 b) pure returns (bytes32) {
    return keccak256(abi.encode(key, a, b));
}

function makeAddressUint16AddressKey(bytes32 key, address a, uint16 b, address c)
    pure
    returns (bytes32)
{
    return keccak256(abi.encode(key, a, b, c));
}

function makeAddressAddressUint32Key(bytes32 key, address a, address b, uint32 c)
    pure
    returns (bytes32)
{
    return keccak256(abi.encode(key, a, b, c));
}

function makeAddressAddressBytes32Uint32Key(bytes32 key, address a, address b, bytes32 c, uint32 d)
    pure
    returns (bytes32)
{
    return keccak256(abi.encode(key, a, b, c, d));
}

function makeBytes32Key(bytes32 key, bytes32 a) pure returns (bytes32) {
    return keccak256(abi.encode(key, a));
}

function makeUint32Key(bytes32 key, uint32 a) pure returns (bytes32) {
    return keccak256(abi.encode(key, a));
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@layerzerolabs/lz-evm-messagelib-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/messagelib/",
    "@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/protocol/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "solidity-bytes-utils/=lib/solidity-bytes-utils/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/grove-basin/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/sparklend-address-registry/lib/forge-std/:ds-test/=lib/grove-basin/lib/xchain-ssr-oracle/lib/sparklend-address-registry/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/:erc4626-tests/=lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/:forge-std/=lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/metamorpho/lib/universal-rewards-distributor/lib/murky/lib/forge-std/:ds-test/=lib/metamorpho/lib/universal-rewards-distributor/lib/murky/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/spark-psm/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/sparklend-address-registry/lib/forge-std/:ds-test/=lib/spark-psm/lib/xchain-ssr-oracle/lib/sparklend-address-registry/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/:erc4626-tests/=lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/:forge-std/=lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/uniswap-v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/uniswap-v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/aave-v3-origin/lib/solidity-utils/lib/forge-std/:ds-test/=lib/aave-v3-origin/lib/solidity-utils/lib/forge-std/lib/ds-test/src/",
    "lib/dss-allocator/lib/dss-test/lib/forge-std/:ds-test/=lib/dss-allocator/lib/dss-test/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/erc20-helpers/lib/forge-std/:ds-test/=lib/grove-basin/lib/erc20-helpers/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/grove-address-registry/lib/forge-std/:ds-test/=lib/grove-basin/lib/grove-address-registry/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/forge-std/:ds-test/=lib/grove-basin/lib/xchain-ssr-oracle/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/:erc4626-tests/=lib/grove-basin/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/:forge-std/=lib/grove-basin/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/sparklend-address-registry/:forge-std/=lib/grove-basin/lib/xchain-ssr-oracle/lib/sparklend-address-registry/lib/forge-std/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/:forge-std/=lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/forge-std/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/:openzeppelin-contracts/=lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/",
    "lib/grove-xchain-helpers/lib/LayerZero-v2/lib/forge-std/:ds-test/=lib/grove-xchain-helpers/lib/LayerZero-v2/lib/forge-std/lib/ds-test/src/",
    "lib/grove-xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/grove-xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/grove-xchain-helpers/lib/solidity-bytes-utils/lib/forge-std/:ds-test/=lib/grove-xchain-helpers/lib/solidity-bytes-utils/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/metamorpho/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho/lib/universal-rewards-distributor/lib/forge-std/:ds-test/=lib/metamorpho/lib/universal-rewards-distributor/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho/lib/universal-rewards-distributor/lib/murky/:forge-std/=lib/metamorpho/lib/universal-rewards-distributor/lib/murky/lib/forge-std/src/",
    "lib/metamorpho/lib/universal-rewards-distributor/lib/murky/:openzeppelin-contracts/=lib/metamorpho/lib/universal-rewards-distributor/lib/murky/lib/openzeppelin-contracts/",
    "lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/:forge-std/=lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/oz-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/oz-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/erc20-helpers/lib/forge-std/:ds-test/=lib/spark-psm/lib/erc20-helpers/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/spark-psm/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/forge-std/:ds-test/=lib/spark-psm/lib/xchain-ssr-oracle/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/:erc4626-tests/=lib/spark-psm/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/:forge-std/=lib/spark-psm/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/sparklend-address-registry/:forge-std/=lib/spark-psm/lib/xchain-ssr-oracle/lib/sparklend-address-registry/lib/forge-std/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/:forge-std/=lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/forge-std/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/:openzeppelin-contracts/=lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/lib/openzeppelin-contracts/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:forge-std/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/spark-vaults-v2/lib/token-tests/lib/dss-test/:dss-interfaces/=lib/spark-vaults-v2/lib/token-tests/lib/dss-test/lib/dss-interfaces/src/",
    "lib/spark-vaults-v2/lib/token-tests/lib/dss-test/:forge-std/=lib/spark-vaults-v2/lib/token-tests/lib/dss-test/lib/forge-std/src/",
    "lib/uniswap-v4-periphery/lib/permit2/lib/forge-gas-snapshot/:forge-std/=lib/uniswap-v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/src/",
    "lib/uniswap-v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/uniswap-v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/uniswap-v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/uniswap-v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:forge-std/=lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/uniswap-v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/uniswap-v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/aave-v3-origin/lib/solidity-utils/:forge-std/=lib/aave-v3-origin/lib/solidity-utils/lib/forge-std/src/",
    "lib/dss-allocator/lib/dss-test/:dss-interfaces/=lib/dss-allocator/lib/dss-test/lib/dss-interfaces/src/",
    "lib/dss-allocator/lib/dss-test/:forge-std/=lib/dss-allocator/lib/dss-test/lib/forge-std/src/",
    "lib/grove-address-registry/lib/forge-std/:ds-test/=lib/grove-address-registry/lib/forge-std/lib/ds-test/src/",
    "lib/grove-basin/lib/erc20-helpers/:forge-std/=lib/grove-basin/lib/erc20-helpers/lib/forge-std/src/",
    "lib/grove-basin/lib/grove-address-registry/:forge-std/=lib/grove-basin/lib/grove-address-registry/lib/forge-std/src/",
    "lib/grove-basin/lib/openzeppelin-contracts/:erc4626-tests/=lib/grove-basin/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/grove-basin/lib/openzeppelin-contracts/:forge-std/=lib/grove-basin/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/grove-basin/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/grove-basin/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/:forge-std/=lib/grove-basin/lib/xchain-ssr-oracle/lib/forge-std/src/",
    "lib/grove-basin/lib/xchain-ssr-oracle/:openzeppelin-contracts/=lib/grove-basin/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/",
    "lib/grove-basin/lib/xchain-ssr-oracle/:sparklend-address-registry/=lib/grove-basin/lib/xchain-ssr-oracle/lib/sparklend-address-registry/",
    "lib/grove-basin/lib/xchain-ssr-oracle/:xchain-helpers/=lib/grove-basin/lib/xchain-ssr-oracle/lib/xchain-helpers/src/",
    "lib/grove-xchain-helpers/lib/LayerZero-v2/:forge-std/=lib/grove-xchain-helpers/lib/LayerZero-v2/lib/forge-std/src/",
    "lib/grove-xchain-helpers/lib/openzeppelin-contracts/:erc4626-tests/=lib/grove-xchain-helpers/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/grove-xchain-helpers/lib/openzeppelin-contracts/:forge-std/=lib/grove-xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/grove-xchain-helpers/lib/solidity-bytes-utils/:forge-std/=lib/grove-xchain-helpers/lib/solidity-bytes-utils/lib/forge-std/src/",
    "lib/layerzero-v2/lib/forge-std/:ds-test/=lib/layerzero-v2/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho/lib/forge-std/:ds-test/=lib/metamorpho/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho/lib/morpho-blue/:forge-std/=lib/metamorpho/lib/morpho-blue/lib/forge-std/src/",
    "lib/metamorpho/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/metamorpho/lib/openzeppelin-contracts/:forge-std/=lib/metamorpho/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/metamorpho/lib/universal-rewards-distributor/:forge-std/=lib/metamorpho/lib/universal-rewards-distributor/lib/forge-std/src/",
    "lib/metamorpho/lib/universal-rewards-distributor/:openzeppelin-contracts/=lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/",
    "lib/nfat/lib/dss-test/:dss-interfaces/=lib/nfat/lib/dss-test/lib/dss-interfaces/src/",
    "lib/nfat/lib/dss-test/:forge-std/=lib/nfat/lib/dss-test/lib/forge-std/src/",
    "lib/nfat/lib/openzeppelin-contracts/:erc4626-tests/=lib/nfat/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/nfat/lib/openzeppelin-contracts/:forge-std/=lib/nfat/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/nfat/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/nfat/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/oz-upgradeable/lib/forge-std/:ds-test/=lib/oz-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/oz-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/oz-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/oz-upgradeable/lib/openzeppelin-contracts/:forge-std/=lib/oz-upgradeable/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/spark-address-registry/lib/forge-std/:ds-test/=lib/spark-address-registry/lib/forge-std/lib/ds-test/src/",
    "lib/spark-psm/lib/erc20-helpers/:forge-std/=lib/spark-psm/lib/erc20-helpers/lib/forge-std/src/",
    "lib/spark-psm/lib/openzeppelin-contracts/:erc4626-tests/=lib/spark-psm/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/spark-psm/lib/openzeppelin-contracts/:forge-std/=lib/spark-psm/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/:forge-std/=lib/spark-psm/lib/xchain-ssr-oracle/lib/forge-std/src/",
    "lib/spark-psm/lib/xchain-ssr-oracle/:openzeppelin-contracts/=lib/spark-psm/lib/xchain-ssr-oracle/lib/openzeppelin-contracts/",
    "lib/spark-psm/lib/xchain-ssr-oracle/:sparklend-address-registry/=lib/spark-psm/lib/xchain-ssr-oracle/lib/sparklend-address-registry/",
    "lib/spark-psm/lib/xchain-ssr-oracle/:xchain-helpers/=lib/spark-psm/lib/xchain-ssr-oracle/lib/xchain-helpers/src/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/:forge-std/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/forge-std/src/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts/:erc4626-tests/=lib/spark-vaults-v2/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts/:forge-std/=lib/spark-vaults-v2/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/spark-vaults-v2/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/spark-vaults-v2/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/spark-vaults-v2/lib/token-tests/:dss-test/=lib/spark-vaults-v2/lib/token-tests/lib/dss-test/src/",
    "lib/uniswap-v4-periphery/lib/permit2/:solmate/=lib/uniswap-v4-periphery/lib/permit2/lib/solmate/",
    "lib/uniswap-v4-periphery/lib/permit2/:forge-std/=lib/uniswap-v4-periphery/lib/permit2/lib/forge-std/src/",
    "lib/uniswap-v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/uniswap-v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/uniswap-v4-periphery/lib/v4-core/:solmate/=lib/uniswap-v4-periphery/lib/v4-core/lib/solmate/",
    "lib/uniswap-v4-periphery/lib/v4-core/:forge-std/=lib/uniswap-v4-periphery/lib/v4-core/lib/forge-std/src/",
    "lib/uniswap-v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/xchain-helpers/lib/openzeppelin-contracts/:erc4626-tests/=lib/xchain-helpers/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/xchain-helpers/lib/openzeppelin-contracts/:forge-std/=lib/xchain-helpers/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/aave-v3-origin/:solidity-utils/=lib/aave-v3-origin/lib/solidity-utils/src/",
    "lib/aave-v3-origin/:forge-std/=lib/aave-v3-origin/lib/forge-std/src/",
    "lib/dss-allocator/:dss-test/=lib/dss-allocator/lib/dss-test/src/",
    "lib/dss-test/:dss-interfaces/=lib/dss-test/lib/dss-interfaces/src/",
    "lib/dss-test/:forge-std/=lib/dss-test/lib/forge-std/src/",
    "lib/grove-address-registry/:forge-std/=lib/grove-address-registry/lib/forge-std/src/",
    "lib/grove-basin/:erc20-helpers/=lib/grove-basin/lib/erc20-helpers/src/",
    "lib/grove-basin/:forge-std/=lib/grove-basin/lib/forge-std/src/",
    "lib/grove-basin/:grove-address-registry/=lib/grove-basin/lib/grove-address-registry/src/",
    "lib/grove-basin/:openzeppelin-contracts/=lib/grove-basin/lib/openzeppelin-contracts/",
    "lib/grove-basin/:xchain-ssr-oracle/=lib/grove-basin/lib/xchain-ssr-oracle/",
    "lib/grove-xchain-helpers/:forge-std/=lib/grove-xchain-helpers/lib/forge-std/src/",
    "lib/grove-xchain-helpers/:openzeppelin-contracts/=lib/grove-xchain-helpers/lib/openzeppelin-contracts/",
    "lib/layerzero-v2/:forge-std/=lib/layerzero-v2/lib/forge-std/src/",
    "lib/metamorpho/:erc4626-tests/=lib/metamorpho/lib/erc4626-tests/",
    "lib/metamorpho/:forge-std/=lib/metamorpho/lib/forge-std/src/",
    "lib/metamorpho/:openzeppelin-contracts/=lib/metamorpho/lib/openzeppelin-contracts/",
    "lib/nfat/:dss-test/=lib/nfat/lib/dss-test/src/",
    "lib/nfat/:openzeppelin-contracts/=lib/nfat/lib/openzeppelin-contracts/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/oz-upgradeable/:erc4626-tests/=lib/oz-upgradeable/lib/erc4626-tests/",
    "lib/oz-upgradeable/:forge-std/=lib/oz-upgradeable/lib/forge-std/src/",
    "lib/oz-upgradeable/:openzeppelin-contracts/=lib/oz-upgradeable/lib/openzeppelin-contracts/",
    "lib/spark-address-registry/:forge-std/=lib/spark-address-registry/lib/forge-std/src/",
    "lib/spark-psm/:erc20-helpers/=lib/spark-psm/lib/erc20-helpers/src/",
    "lib/spark-psm/:forge-std/=lib/spark-psm/lib/forge-std/src/",
    "lib/spark-psm/:openzeppelin-contracts/=lib/spark-psm/lib/openzeppelin-contracts/",
    "lib/spark-psm/:xchain-ssr-oracle/=lib/spark-psm/lib/xchain-ssr-oracle/",
    "lib/spark-vaults-v2/:forge-std/=lib/spark-vaults-v2/lib/forge-std/src/",
    "lib/spark-vaults-v2/:openzeppelin-contracts/=lib/spark-vaults-v2/lib/openzeppelin-contracts/",
    "lib/xchain-helpers/:forge-std/=lib/xchain-helpers/lib/forge-std/src/",
    "lib/xchain-helpers/:openzeppelin-contracts/=lib/xchain-helpers/lib/openzeppelin-contracts/",
    "@ensdomains/=lib/uniswap-v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@layerzerolabs/oft-evm/=lib/grove-xchain-helpers/lib/devtools/packages/oft-evm/",
    "@openzeppelin/=lib/uniswap-v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "@uniswap/v4-core/=lib/uniswap-v4-periphery/lib/v4-core/",
    "LayerZero-v2/=lib/grove-xchain-helpers/lib/",
    "aave-v3-core/=lib/aave-v3-origin/src/core/",
    "aave-v3-origin/=lib/aave-v3-origin/",
    "aave-v3-periphery/=lib/aave-v3-origin/src/periphery/",
    "devtools/=lib/grove-xchain-helpers/lib/devtools/packages/toolbox-foundry/src/",
    "ds-test/=lib/aave-v3-origin/lib/forge-std/lib/ds-test/src/",
    "dss-allocator/=lib/dss-allocator/",
    "dss-interfaces/=lib/dss-test/lib/dss-interfaces/src/",
    "dss-test/=lib/dss-test/src/",
    "erc20-helpers/=lib/grove-basin/lib/erc20-helpers/src/",
    "erc4626-tests/=lib/metamorpho/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/uniswap-v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "grove-address-registry/=lib/grove-address-registry/src/",
    "grove-basin/=lib/grove-basin/",
    "grove-xchain-helpers/=lib/grove-xchain-helpers/src/",
    "halmos-cheatcodes/=lib/grove-basin/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/uniswap-v4-periphery/lib/v4-core/node_modules/hardhat/",
    "layerzero-v2/=lib/layerzero-v2/",
    "layerzerolabs/oapp-evm/=lib/grove-xchain-helpers/lib/devtools/packages/oapp-evm/",
    "metamorpho/=lib/metamorpho/src/",
    "morpho-blue/=lib/metamorpho/lib/morpho-blue/",
    "murky/=lib/metamorpho/lib/universal-rewards-distributor/lib/murky/src/",
    "nfat/=lib/nfat/",
    "openzeppelin-contracts-upgradeable/=lib/spark-vaults-v2/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/metamorpho/lib/universal-rewards-distributor/lib/openzeppelin-contracts/contracts/",
    "oz-upgradeable/=lib/oz-upgradeable/",
    "permit2/=lib/uniswap-v4-periphery/lib/permit2/",
    "solidity-utils/=lib/aave-v3-origin/lib/solidity-utils/",
    "solmate/=lib/uniswap-v4-periphery/lib/permit2/lib/solmate/",
    "spark-address-registry/=lib/spark-address-registry/src/",
    "spark-psm/=lib/spark-psm/",
    "spark-vaults-v2/=lib/spark-vaults-v2/",
    "sparklend-address-registry/=lib/grove-basin/lib/xchain-ssr-oracle/lib/sparklend-address-registry/",
    "token-tests/=lib/spark-vaults-v2/lib/token-tests/src/",
    "uniswap-v4-periphery/=lib/uniswap-v4-periphery/",
    "universal-rewards-distributor/=lib/metamorpho/lib/universal-rewards-distributor/src/",
    "v4-core/=lib/uniswap-v4-periphery/lib/v4-core/src/",
    "xchain-helpers/=lib/xchain-helpers/src/",
    "xchain-ssr-oracle/=lib/grove-basin/lib/xchain-ssr-oracle/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.