Skip to content
Verified contractPartialMIT

Keeper

Address0x0188953557309c3bba2011e26fc0d142c212fda0
Balance

0 ETH

 

Transactions

137

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,675,756
Creation transaction
0xb4e0ce27c7…68fe0fbb4d

src/helpers/keepers/Keeper.sol

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

import { IResupplyPair } from "src/interfaces/IResupplyPair.sol";
import { IResupplyRegistry } from "src/interfaces/IResupplyRegistry.sol";
import { IFeeDepositController } from "src/interfaces/IFeeDepositController.sol";
import { IFeeDeposit } from "src/interfaces/IFeeDeposit.sol";
import { IRetentionReceiver } from "src/interfaces/IRetentionReceiver.sol";
import { IEmissionsController } from "src/interfaces/IEmissionsController.sol";
import { IRouterSwapper } from "src/interfaces/IRouterSwapper.sol";
import { IBorrowLimitController } from "src/interfaces/IBorrowLimitController.sol";

interface IOperator {
    function profit() external view returns (uint256);
    function withdraw_profit() external;
}

interface ISreUsd {
    function lastRewardsDistribution() external view returns (uint256);
    function syncRewardsAndDistribution() external;
}

contract Keeper {
    IResupplyRegistry public constant registry = IResupplyRegistry(0x10101010E0C3171D894B71B3400668aF311e7D94);
    ISreUsd public constant sreUsd = ISreUsd(0x557AB1e003951A73c12D16F0fEA8490E39C33C35);
    uint256 public constant startTime = 1_741_824_000;
    uint256 public constant epochLength = 1 weeks;

    address public owner;
    address[] public operators;
    uint256 public minProfit;
    /// @notice Minimum time between successful Keeper borrow limit updates.
    uint64 public borrowLimitUpdateInterval = 12 hours;
    /// @notice Timestamp of the last successful Keeper borrow limit update.
    uint64 public lastBorrowLimitUpdate;

    /// @notice Emitted after a maintenance action completes successfully.
    event TaskCompleted(bytes4 indexed selector, address indexed subject);
    /// @notice Emitted when a best-effort maintenance action fails.
    event TaskFailed(bytes4 indexed selector, address indexed subject);
    /// @notice Emitted when the minimum interval between borrow limit updates changes.
    event BorrowLimitUpdateIntervalSet(uint64 interval);

    modifier onlyOwner() {
        require(msg.sender == owner, "!owner");
        _;
    }

    constructor(address _owner, address[] memory _operators, uint256 _minProfit) {
        owner = _owner;
        operators = _operators;
        minProfit = _minProfit;
    }

    function setOwner(address _owner) external onlyOwner {
        owner = _owner;
    }

    function setOperators(address[] calldata _operators, uint256 _minProfit) external onlyOwner {
        operators = _operators;
        minProfit = _minProfit;
    }

    /// @dev Setting the interval to zero disables the cooldown.
    function setBorrowLimitUpdateInterval(uint64 _interval) external onlyOwner {
        borrowLimitUpdateInterval = _interval;
        emit BorrowLimitUpdateIntervalSet(_interval);
    }

    function getOperators() external view returns (address[] memory) {
        return operators;
    }

    function work() external {
        bool weeklyWork = canDistributeWeeklyFees();
        if (weeklyWork) {
            IFeeDepositController controller = _getFeeDepositController();
            controller.distribute();
            emit TaskCompleted(IFeeDepositController.distribute.selector, address(controller));
        }

        if (canSyncSreUsdRewards()) {
            sreUsd.syncRewardsAndDistribution();
            emit TaskCompleted(ISreUsd.syncRewardsAndDistribution.selector, address(sreUsd));
        }

        address[] memory pairs = registry.getAllPairAddresses();
        bool checkBorrowLimits = _borrowLimitUpdateIntervalElapsed();
        IBorrowLimitController borrowLimitController;
        if (checkBorrowLimits) borrowLimitController = _getBorrowLimitController();
        bool borrowLimitUpdated;
        for (uint256 i = 0; i < pairs.length; i++) {
            if (canWithdrawFees(pairs[i])) {
                IResupplyPair(pairs[i]).withdrawFees();
                emit TaskCompleted(IResupplyPair.withdrawFees.selector, pairs[i]);
            }
            if (checkBorrowLimits && _canUpdateBorrowLimit(borrowLimitController, pairs[i])) {
                borrowLimitController.updatePairBorrowLimit(pairs[i]);
                borrowLimitUpdated = true;
                emit TaskCompleted(IBorrowLimitController.updatePairBorrowLimit.selector, pairs[i]);
            }
        }
        if (borrowLimitUpdated) lastBorrowLimitUpdate = uint64(block.timestamp);

        if (canClaimRetentionEmissions()) {
            IRetentionReceiver retention = _getRetentionReceiver();
            retention.claimEmissions();
            emit TaskCompleted(IRetentionReceiver.claimEmissions.selector, address(retention));
        }

        if (weeklyWork) {
            for (uint256 i = 0; i < operators.length; i++) {
                if (canWithdrawProfit(operators[i])) {
                    IOperator(operators[i]).withdraw_profit();
                    emit TaskCompleted(IOperator.withdraw_profit.selector, operators[i]);
                }
            }
        }

        _updateSwapperApprovals();
    }

    function canWork() external view returns (bool) {
        if (canDistributeWeeklyFees()) return true;
        if (canSyncSreUsdRewards()) return true;
        if (canClaimRetentionEmissions()) return true;
        address[] memory pairs = registry.getAllPairAddresses();
        bool checkBorrowLimits = _borrowLimitUpdateIntervalElapsed();
        IBorrowLimitController borrowLimitController;
        if (checkBorrowLimits) borrowLimitController = _getBorrowLimitController();
        for (uint256 i = 0; i < pairs.length; i++) {
            if (canWithdrawFees(pairs[i])) return true;
            if (checkBorrowLimits && _canUpdateBorrowLimit(borrowLimitController, pairs[i])) return true;
        }
        return canUpdateSwapperApprovals();
    }

    function canDistributeWeeklyFees() public view returns (bool) {
        return _getFeeDeposit().lastDistributedEpoch() < getEpoch();
    }

    function canWithdrawFees(address _pair) public view returns (bool) {
        if (IResupplyPair(_pair).lastFeeEpoch() >= getEpoch()) return false;
        (address oracle,,) = IResupplyPair(_pair).exchangeRateInfo();
        if (oracle == address(0)) return false;
        return true;
    }

    function canClaimRetentionEmissions() public view returns (bool) {
        IRetentionReceiver retention = _getRetentionReceiver();
        if (!_getEmissionsController().isRegisteredReceiver(address(retention))) return false;
        return getEpoch() > retention.lastEpoch();
    }

    function canWithdrawProfit(address _operator) public view returns (bool) {
        return IOperator(_operator).profit() > minProfit;
    }

    function canUpdateSwapperApprovals() public view returns (bool) {
        for (uint256 i = 0;; i++) {
            try registry.defaultSwappers(i) returns (address swapper) {
                try IRouterSwapper(swapper).canUpdateApprovals() returns (bool _canUpdate) {
                    if (_canUpdate) return true;
                } catch { }
            } catch {
                break;
            }
        }
        return false;
    }

    function canUpdateBorrowLimit(address _pair) public view returns (bool) {
        if (!_borrowLimitUpdateIntervalElapsed()) return false;
        return _canUpdateBorrowLimit(_getBorrowLimitController(), _pair);
    }

    function canSyncSreUsdRewards() public view returns (bool) {
        uint256 lastRewardsDistribution = sreUsd.lastRewardsDistribution();
        if (lastRewardsDistribution < startTime) return false;
        return ((lastRewardsDistribution - startTime) / epochLength) < getEpoch();
    }

    function _getFeeDepositController() internal view returns (IFeeDepositController) {
        return IFeeDepositController(registry.getAddress("FEE_DEPOSIT_CONTROLLER"));
    }

    function _getFeeDeposit() internal view returns (IFeeDeposit) {
        return IFeeDeposit(registry.feeDeposit());
    }

    function _getRetentionReceiver() internal view returns (IRetentionReceiver) {
        return IRetentionReceiver(registry.getAddress("RETENTION_RECEIVER"));
    }

    function _getEmissionsController() internal view returns (IEmissionsController) {
        return IEmissionsController(registry.getAddress("EMISSIONS_CONTROLLER"));
    }

    function _getBorrowLimitController() internal view returns (IBorrowLimitController) {
        return IBorrowLimitController(registry.getAddress("BORROW_LIMIT_CONTROLLER"));
    }

    function _updateSwapperApprovals() internal {
        for (uint256 i = 0;; i++) {
            address swapper;
            try registry.defaultSwappers(i) returns (address _swapper) {
                swapper = _swapper;
            } catch {
                return;
            }

            bool canUpdate;
            try IRouterSwapper(swapper).canUpdateApprovals() returns (bool _canUpdate) {
                canUpdate = _canUpdate;
            } catch {
                continue;
            }

            if (!canUpdate) continue;

            try IRouterSwapper(swapper).updateApprovals() {
                emit TaskCompleted(IRouterSwapper.updateApprovals.selector, swapper);
            } catch {
                emit TaskFailed(IRouterSwapper.updateApprovals.selector, swapper);
            }
        }
    }

    function _canUpdateBorrowLimit(IBorrowLimitController _controller, address _pair) internal view returns (bool) {
        IBorrowLimitController.PairBorrowLimit memory limit = _controller.pairLimits(_pair);
        if (limit.startTime == 0 || block.timestamp < limit.startTime || limit.endTime <= limit.startTime || limit.targetBorrowLimit <= limit.prevBorrowLimit) return false;

        uint256 current = IResupplyPair(_pair).borrowLimit();
        if (current == 0 || current < limit.prevBorrowLimit || current > limit.targetBorrowLimit) return false;
        if (block.timestamp >= limit.endTime) return true;

        uint256 borrowDelta = limit.targetBorrowLimit - limit.prevBorrowLimit;
        uint256 duration = limit.endTime - limit.startTime;
        uint256 previewProgress = (block.timestamp - limit.startTime) * 10_000 / duration;
        uint256 preview = (borrowDelta * previewProgress) / 10_000 + limit.prevBorrowLimit;
        return preview > current;
    }

    function _borrowLimitUpdateIntervalElapsed() internal view returns (bool) {
        return block.timestamp - lastBorrowLimitUpdate >= borrowLimitUpdateInterval;
    }

    function getEpoch() public view returns (uint256) {
        return (block.timestamp - startTime) / epochLength;
    }
}

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

src/interfaces/IBorrowLimitController.sol

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

interface IBorrowLimitController {
    struct PairBorrowLimit {
        uint256 targetBorrowLimit;
        uint256 prevBorrowLimit;
        uint64 startTime;
        uint64 endTime;
    }

    function cancelRamp(address _pair) external;

    function setPairBorrowLimitRamp(address _pair, uint256 _newBorrowLimit, uint256 _endTime) external;

    function updatePairBorrowLimit(address _pair) external;

    function previewNewBorrowLimit(address _pair) external view returns (uint256);

    // View function for public state variable
    function pairLimits(address _pair) external view returns (PairBorrowLimit memory);
}

src/interfaces/IEmissionsController.sol

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

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

interface IEmissionsController {
    // View functions
    function govToken() external view returns (IGovToken);
    function emissionsRate() external view returns (uint256);
    function emissionsPerEpoch(uint256 epoch) external view returns (uint256);
    function getEmissionsSchedule() external view returns (uint256[] memory);
    function getReceiverSplit(address receiver, uint256 epoch) external view returns (uint256);
    function getEpoch() external view returns (uint256);
    function receiverToId(address receiver) external view returns (uint256);
    function idToReceiver(uint256 id) external view returns (Receiver memory);
    function allocated(address receiver) external view returns (uint256, uint256);
    function setReceiverWeights(uint256[] memory _receiverIds, uint256[] memory _newWeights) external;
    function registerReceiver(address _receiver) external;
    function nextReceiverId() external view returns (uint256);
    function isRegisteredReceiver(address receiver) external view returns (bool);
    
    // State-changing functions
    function fetchEmissions() external returns (uint256);
    function setEmissionsSplits(uint256 _amount) external;
    function setEmissionsSchedule(uint256[] memory _rates, uint256 _epochsPer, uint256 _tailRate) external;
    function transferFromAllocation(address _recipient, uint256 _amount) external returns (uint256);

    event EmissionsMinted(uint256 epoch, uint256 amount);
    event EmissionsSplitSet(address receiver, uint256 split);
    event EmissionsScheduleSet(uint256[] rates, uint256 epochsPer, uint256 tailRate);

    struct Receiver {
        bool active;
        address receiver;
        uint256 weight;
    }
}

src/interfaces/IFeeDeposit.sol

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

interface IFeeDeposit {
    function operator() external view returns(address);
    function lastDistributedEpoch() external view returns(uint256);
    function setOperator(address _newAddress) external;
    function distributeFees() external;
    function incrementPairRevenue(uint256 _fees, uint256 _otherFees) external;
    function getEpoch() external view returns(uint256);
}

src/interfaces/IFeeDepositController.sol

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

/// @title IFeeDepositController
/// @notice Interface for the FeeDepositController contract that handles distribution of fees
interface IFeeDepositController {
    /// @notice Struct defining the split percentages for fee distribution
    struct Splits {
        uint40 insurance;
        uint40 treasury;
        uint40 platform;
        uint40 stakedStable;
    }

    /// @notice Emitted when fee distribution splits are updated
    /// @param insurance The percentage (in BPS) allocated to insurance pool
    /// @param treasury The percentage (in BPS) allocated to treasury
    /// @param platform The percentage (in BPS) allocated to platform stakers
    event SplitsSet(uint40 insurance, uint40 treasury, uint40 platform, uint40 stakedStable);
    event AdditionalFeeRatioSet(uint256 ratio);

    /// @notice Returns the address of the registry contract
    function registry() external view returns (address);

    /// @notice Returns the address of the treasury
    function treasury() external view returns (address);

    /// @notice Returns the address of the fee deposit contract
    function feeDeposit() external view returns (address);

    /// @notice Returns the address of the fee token
    function feeToken() external view returns (address);

    /// @notice Returns the basis points constant (10,000)
    function BPS() external view returns (uint256);

    /// @notice Returns the current split configuration
    function splits() external view returns (Splits memory);

    /// @notice Distributes collected fees according to the configured splits
    function distribute() external;

    /// @notice Sets the fee distribution splits between insurance, treasury, and platform
    /// @param _insuranceSplit The percentage (in BPS) to send to insurance pool
    /// @param _treasurySplit The percentage (in BPS) to send to treasury
    /// @param _platformSplit The percentage (in BPS) to send to platform stakers
    /// @param _stakedStableSplit The percentage (in BPS) to send to staked stable
    function setSplits(uint256 _insuranceSplit, uint256 _treasurySplit, uint256 _platformSplit, uint256 _stakedStableSplit) external;


    function setAdditionalFeeRatio(uint256 _additionalFee) external;

    /// @notice Returns the maximum additional fee ratio
    function additionalFeeRatio() external view returns (uint256);

}

src/interfaces/IGovToken.sol

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

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

interface IGovToken is IERC20 {
    // Events
    event MinterSet(address indexed minter);
    event FinalizeMinter();

    // State variables
    function minterFinalized() external view returns (bool);
    function minter() external view returns (address);
    function owner() external view returns (address);
    function core() external view returns (address);
    function globalSupply() external view returns (uint256);

    // Functions
    function mint(address _to, uint256 _amount) external;
    function setMinter(address _minter) external;
    function finalizeMinter() external;
}

src/interfaces/IResupplyPair.sol

pragma solidity 0.8.28;

import { IResupplyPairErrors } from "src/protocol/pair/IResupplyPairErrors.sol";

interface IResupplyPair is IResupplyPairErrors {
    
    struct CurrentRateInfo {
        uint64 lastTimestamp;
        uint64 ratePerSec;
        uint128 lastShares;
    }

    struct VaultAccount {
        uint128 amount;
        uint128 shares;
    }

    struct EarnedData {
        address token;
        uint256 amount;
    }

    function CRV(  ) external view returns (address ) ;
    function CVX(  ) external view returns (address ) ;
    function EXCHANGE_PRECISION(  ) external view returns (uint256 ) ;
    function LIQ_PRECISION(  ) external view returns (uint256 ) ;
    function LTV_PRECISION(  ) external view returns (uint256 ) ;
    function PAIR_DECIMALS(  ) external view returns (uint256 ) ;
    function RATE_PRECISION(  ) external view returns (uint256 ) ;
    function SHARE_REFACTOR_PRECISION(  ) external view returns (uint256 ) ;
    function addCollateral( uint256 _amount,address _borrower ) external   ;
    function addCollateralVault( uint256 _collateralAmount,address _borrower ) external   ;
    function addExtraReward( address _token ) external   ;
    function addInterest( bool _returnAccounting ) external  returns (uint256 _interestEarned, CurrentRateInfo memory _currentRateInfo, uint256 _claimableFees, VaultAccount memory _totalBorrow) ;
    function borrow( uint256 _borrowAmount,uint256 _underlyingAmount,address _receiver ) external  returns (uint256 _shares) ;
    function borrowLimit(  ) external view returns (uint256 ) ;
    function claimableFees(  ) external view returns (uint256 ) ;
    function claimableOtherFees(  ) external view returns (uint256 ) ;
    function claimable_reward( address ,address  ) external view returns (uint256 ) ;
    function collateral(  ) external view returns (address ) ;
    function convexBooster(  ) external view returns (address ) ;
    function convexPid(  ) external view returns (uint256 ) ;
    function core(  ) external view returns (address ) ;
    function currentRateInfo(  ) external view returns (uint64 lastTimestamp, uint64 ratePerSec, uint128 lastShares) ;
    function currentRewardEpoch(  ) external view returns (uint256 ) ;
    function currentUtilization(  ) external view returns (uint256 ) ;
    function earned( address _account ) external  returns (EarnedData[] memory claimable) ;
    function epochLength(  ) external view returns (uint256 ) ;
    function exchangeRateInfo(  ) external view returns (address oracle, uint96 lastTimestamp, uint256 exchangeRate) ;
    function getConstants(  ) external pure returns (uint256 _LTV_PRECISION, uint256 _LIQ_PRECISION, uint256 _EXCHANGE_PRECISION, uint256 _RATE_PRECISION) ;
    function getEpoch(  ) external view returns (uint256 epoch) ;
    function getPairAccounting(  ) external view returns (uint256 _claimableFees, uint128 _totalBorrowAmount, uint128 _totalBorrowShares, uint256 _totalCollateral) ;
    function getReward( address _account,address _forwardTo ) external   ;
    function getReward( address _account ) external   ;
    function getUserSnapshot( address _address ) external  returns (uint256 _borrowShares, uint256 _collateralBalance) ;
    function global_reward_integral( uint256 ,address  ) external view returns (uint256 ) ;
    function invalidateReward( address _token ) external   ;
    function lastFeeEpoch(  ) external view returns (uint256 ) ;
    function leveragedPosition( address _swapperAddress,uint256 _borrowAmount,uint256 _initialUnderlyingAmount,uint256 _amountCollateralOutMin,address[] memory _path ) external  returns (uint256 _totalCollateralBalance) ;
    function liquidate( address _borrower ) external  returns (uint256 _collateralForLiquidator) ;
    function liquidationFee(  ) external view returns (uint256 ) ;
    function maxLTV(  ) external view returns (uint256 ) ;
    function maxRewards(  ) external pure returns (uint256 ) ;
    function minimumBorrowAmount(  ) external view returns (uint256 ) ;
    function minimumLeftoverDebt(  ) external view returns (uint256 ) ;
    function minimumRedemption(  ) external view returns (uint256 ) ;
    function mintFee(  ) external view returns (uint256 ) ;
    function name(  ) external view returns (string memory ) ;
    function owner(  ) external view returns (address ) ;
    function pause(  ) external   ;
    function previewAddInterest(  ) external view returns (uint256 _interestEarned, CurrentRateInfo memory _newCurrentRateInfo, uint256 _claimableFees, VaultAccount memory _totalBorrow) ;
    function protocolRedemptionFee(  ) external view returns (uint256 ) ;
    function rateCalculator(  ) external view returns (address ) ;
    function redeemCollateral( address _caller,uint256 _amount,uint256 _totalFeePct,address _receiver ) external  returns (address _collateralToken, uint256 _collateralFreed) ;
    function redemptionWriteOff(  ) external view returns (address ) ;
    function registry(  ) external view returns (address ) ;
    function removeCollateral( uint256 _collateralAmount,address _receiver ) external   ;
    function removeCollateralVault( uint256 _collateralAmount,address _receiver ) external   ;
    function repay( uint256 _shares,address _borrower ) external  returns (uint256 _amountToRepay) ;
    function repayWithCollateral( address _swapperAddress,uint256 _collateralToSwap,uint256 _amountOutMin,address[] memory _path ) external  returns (uint256 _amountOut) ;
    function rewardLength(  ) external view returns (uint256 ) ;
    function rewardMap( address  ) external view returns (uint256 ) ;
    function rewardRedirect( address  ) external view returns (address ) ;
    function reward_integral_for( uint256 ,address ,address  ) external view returns (uint256 ) ;
    function rewards( uint256  ) external view returns (address reward_token, bool is_non_claimable, uint256 reward_remaining) ;
    function setBorrowLimit( uint256 _limit ) external   ;
    function setConvexPool( uint256 pid ) external   ;
    function setLiquidationFees( uint256 _newLiquidationFee ) external   ;
    function setMaxLTV( uint256 _newMaxLTV ) external   ;
    function setMinimumBorrowAmount( uint256 _min ) external   ;
    function setMinimumLeftoverDebt( uint256 _min ) external   ;
    function setMinimumRedemption( uint256 _min ) external   ;
    function setMintFees( uint256 _newMintFee ) external   ;
    function setOracle( address _newOracle ) external   ;
    function setProtocolRedemptionFee( uint256 _fee ) external   ;
    function setRateCalculator( address _newRateCalculator,bool _updateInterest ) external   ;
    function setRewardRedirect( address _to ) external   ;
    function setSwapper( address _swapper,bool _approval ) external   ;
    function startTime(  ) external view returns (uint256 ) ;
    function swappers( address  ) external view returns (bool ) ;
    function toBorrowAmount( uint256 _shares,bool _roundUp,bool _previewInterest ) external view returns (uint256 _amount) ;
    function toBorrowShares( uint256 _amount,bool _roundUp,bool _previewInterest ) external view returns (uint256 _shares) ;
    function totalBorrow(  ) external view returns (uint128 amount, uint128 shares) ;
    function totalCollateral(  ) external view returns (uint256 _totalCollateralBalance) ;
    function totalDebtAvailable(  ) external view returns (uint256 ) ;
    function underlying(  ) external view returns (address ) ;
    function unpause(  ) external   ;
    function updateExchangeRate(  ) external  returns (uint256 _exchangeRate) ;
    function userBorrowShares( address _account ) external view returns (uint256 borrowShares) ;
    function userCollateralBalance( address _account ) external  returns (uint256 _collateralAmount) ;
    function userRewardEpoch( address  ) external view returns (uint256 ) ;
    function user_checkpoint( address _account,uint256 _epochloops ) external  returns (bool ) ;
    function version(  ) external pure returns (uint256 _major, uint256 _minor, uint256 _patch) ;
    function withdrawFees(  ) external  returns (uint256 _fees, uint256 _otherFees) ;

    event AddCollateral( address indexed borrower,uint256 collateralAmount ) ;
    event AddInterest( uint256 interestEarned,uint256 rate ) ;
    event Borrow( address indexed _borrower,address indexed _receiver,uint256 _borrowAmount,uint256 _sharesAdded,uint256 _mintFees ) ;
    event LeveragedPosition( address indexed _borrower,address _swapperAddress,uint256 _borrowAmount,uint256 _borrowShares,uint256 _initialUnderlyingAmount,uint256 _amountCollateralOut ) ;
    event Liquidate( address indexed _borrower,uint256 _collateralForLiquidator,uint256 _sharesLiquidated,uint256 _amountLiquidatorToRepay ) ;
    event NewEpoch( uint256 indexed _epoch ) ;
    event Redeemed( address indexed _caller,uint256 _amount,uint256 _collateralFreed,uint256 _protocolFee,uint256 _debtReduction ) ;
    event RemoveCollateral( uint256 _collateralAmount,address indexed _receiver,address indexed _borrower ) ;
    event Repay( address indexed payer,address indexed borrower,uint256 amountToRepay,uint256 shares ) ;
    event RepayWithCollateral( address indexed _borrower,address _swapperAddress,uint256 _collateralToSwap,uint256 _amountAssetOut,uint256 _sharesRepaid ) ;
    event RewardAdded( address indexed _rewardToken ) ;
    event RewardInvalidated( address indexed _rewardToken ) ;
    event RewardPaid( address indexed _user,address indexed _rewardToken,address indexed _receiver,uint256 _rewardAmount ) ;
    event RewardRedirected( address indexed _account,address _forward ) ;
    event SetBorrowLimit( uint256 limit ) ;
    event SetConvexPool( uint256 pid ) ;
    event SetLiquidationFees( uint256 oldLiquidationFee,uint256 newLiquidationFee ) ;
    event SetMaxLTV( uint256 oldMaxLTV,uint256 newMaxLTV ) ;
    event SetMinimumBorrowAmount( uint256 min ) ;
    event SetMinimumLeftover( uint256 min ) ;
    event SetMinimumRedemption( uint256 min ) ;
    event SetMintFees( uint256 oldMintFee,uint256 newMintFee ) ;
    event SetOracleInfo( address oldOracle,address newOracle ) ;
    event SetProtocolRedemptionFee( uint256 fee ) ;
    event SetRateCalculator( address oldRateCalculator,address newRateCalculator ) ;
    event SetSwapper( address swapper,bool approval ) ;
    event UpdateExchangeRate( uint256 exchangeRate ) ;
    event UpdateRate( uint256 oldRatePerSec,uint128 oldShares,uint256 newRatePerSec,uint128 newShares ) ;
    event WithdrawFees( address recipient,uint256 interestFees,uint256 otherFees ) ;
}

src/interfaces/IResupplyRegistry.sol

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

interface IResupplyRegistry {
    event AddPair(address pairAddress);
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event SetDeployer(address deployer, bool _bool);
    event DefaultSwappersSet(address[] addresses);
    event EntryUpdated(string indexed key, address indexed addr);
    event WithdrawTo(address indexed user, uint256 amount);

    // Protected keys
    function LIQUIDATION_HANDLER() external pure returns (string memory);
    function FEE_DEPOSIT() external pure returns (string memory);
    function REDEMPTION_HANDLER() external pure returns (string memory);
    function INSURANCE_POOL() external pure returns (string memory);
    function REWARD_HANDLER() external pure returns (string memory);
    function TREASURY() external pure returns (string memory);
    function STAKER() external pure returns (string memory);
    function L2_MANAGER() external pure returns (string memory);
    function VEST_MANAGER() external pure returns (string memory);

    // Other public functions
    function token() external view returns (address);
    function govToken() external view returns (address);
    function getAddress(string memory key) external view returns (address);
    function getAllKeys() external view returns (string[] memory);
    function getAllAddresses() external view returns (address[] memory);
    function getProtectedKeys() external pure returns (string[] memory);
    function keyExists(string memory) external view returns (bool);
    function hashToKey(bytes32) external view returns (string memory);
    function setAddress(string memory key, address addr) external;
    function acceptOwnership() external;
    function addPair(address _pairAddress) external;
    function registeredPairs(uint256) external view returns (address);
    function pairsByName(string memory) external view returns (address);
    function registeredPairsLength() external view returns (uint256);
    function getAllPairAddresses() external view returns (address[] memory _deployedPairsArray);
    function defaultSwappers(uint256 _index) external view returns (address);
    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function renounceOwnership() external;
    function transferOwnership(address newOwner) external;
    function claimFees(address _pair) external;
    function claimRewards(address _pair) external;
    function claimInsuranceRewards() external;
    function withdrawTo(address _asset, uint256 _amount, address _to) external;
    function mint(address receiver, uint256 amount) external;
    function burn(address target, uint256 amount) external;
    function liquidationHandler() external view returns(address);
    function feeDeposit() external view returns(address);
    function redemptionHandler() external view returns(address);
    function rewardHandler() external view returns(address);
    function insurancePool() external view returns(address);
    function setRewardClaimer(address _newAddress) external;
    function setRedemptionHandler(address _newAddress) external;
    function setFeeDeposit(address _newAddress) external;
    function setLiquidationHandler(address _newAddress) external;
    function setInsurancePool(address _newAddress) external;
    function setStaker(address _newAddress) external;
    function setTreasury(address _newAddress) external;
    function staker() external view returns(address);
    function treasury() external view returns(address);
    function l2manager() external view returns(address);
    function setRewardHandler(address _newAddress) external;
    function setVestManager(address _newAddress) external;
    function setDefaultSwappers(address[] memory _swappers) external;
    function collateralId(address _collateral) external view returns(uint256);
    function core() external view returns(address);

    error NameMustBeUnique();
    error ProtectedKey(string key);
}

src/interfaces/IRetentionReceiver.sol

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

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

interface IRetentionReceiver {
    // Events
    event TreasuryAllocationPerEpochSet(uint256 _treasuryAllocationPerEpoch);

    // View functions
    function emissionsController() external view returns (address);
    function registry() external view returns (address);
    function govToken() external view returns (IERC20);
    function name() external view returns (string memory);
    function retentionRewards() external view returns (address);
    function MAX_REWARDS() external view returns (uint256);
    function treasuryAllocationPerEpoch() external view returns (uint256);
    function distributedRewards() external view returns (uint256);
    function lastEpoch() external view returns (uint256);
    function getEpoch() external view returns (uint256);
    function getReceiverId() external view returns (uint256);
    function claimableEmissions() external view returns (uint256);

    // State changing functions
    function allocateEmissions() external returns (uint256 amount);
    function claimEmissions() external returns (uint256 amount);
    function setTreasuryAllocationPerEpoch(uint256 _treasuryAllocationPerEpoch) external;
    function sweepERC20(address token) external;
}

src/interfaces/IRouterSwapper.sol

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

interface IRouterSwapper {
    function name() external view returns (string memory);
    function swap(address account, uint256 amountIn, address[] memory path, address to) external;
    function updateApprovals() external;
    function revokeApprovals() external;
    function canUpdateApprovals() external view returns (bool);
    function encode(bytes memory payload, address sellToken, address buyToken) external pure returns (address[] memory path);
    function decode(address[] memory path) external pure returns (bytes memory payload);
    function recoverERC20(address token, uint256 amount) external;
    function router() external view returns (address);
    function registry() external view returns (address);
    function reusd() external view returns (address);
    function nextPairIndex() external view returns (uint256);
    function approvalsRevoked() external view returns (bool);
}

src/protocol/pair/IResupplyPairErrors.sol

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

interface IResupplyPairErrors {
    error Insolvent(uint256 _borrow, uint256 _collateral, uint256 _exchangeRate);
    error BorrowerSolvent();
    error InsufficientDebtAvailable(uint256 _assets, uint256 _request);
    error SlippageTooHigh(uint256 _minOut, uint256 _actual);
    error BadSwapper();
    error InvalidReceiver();
    error InvalidLiquidator();
    error InvalidRedemptionHandler();
    error InvalidParameter();
    error InvalidPath(address _expected, address _actual);
    error InsufficientDebtToRedeem();
    error MinimumRedemption();
    error InsufficientBorrowAmount();
    error OnlyProtocolOrOwner();
    error InvalidExchangeRate();
    error FeesAlreadyDistributed();
    error IncorrectStakeBalance();
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "ds-test/=node_modules/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "frax-std/=node_modules/frax-standard-solidity/src/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "@openzeppelin/foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@axelar-network/=node_modules/@axelar-network/",
    "@chainlink/=node_modules/@chainlink/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@layerzerolabs/=node_modules/@layerzerolabs/",
    "@mean-finance/=node_modules/@mean-finance/",
    "@rari-capital/=node_modules/@rari-capital/",
    "@uniswap/=node_modules/@uniswap/",
    "base64-sol/=node_modules/base64-sol/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "frax-standard-solidity/=node_modules/frax-standard-solidity/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hardhat-deploy/=node_modules/hardhat-deploy/",
    "hardhat/=node_modules/hardhat/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "solidity-stringutils/=lib/surl/lib/solidity-stringutils/",
    "surl/=lib/surl/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.