Skip to content
Verified contractPartialMIT

Utilities

Address0x8316bdef28d48cea09c21c35e19e2f4bb87d62ac
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

2 more contracts

 

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
22,943,448
Creation transaction
0x08ae97b557…e89690a010

src/protocol/Utilities.sol

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

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IResupplyPair } from "src/interfaces/IResupplyPair.sol";
import { IRateCalculator } from "src/interfaces/IRateCalculator.sol";
import { IResupplyRegistry } from "src/interfaces/IResupplyRegistry.sol";
import { IOracle } from "src/interfaces/IOracle.sol";
import { IRewardHandler } from "src/interfaces/IRewardHandler.sol";
import { IRewards } from "src/interfaces/IRewards.sol";
import { IConvexPoolUtil } from "src/interfaces/convex/IConvexPoolUtil.sol";
import { ICurveExchange } from "src/interfaces/curve/ICurveExchange.sol";
import { ICurveLend } from "src/interfaces/curve/ICurveLend.sol";
import { IFraxLend } from "../interfaces/frax/IFraxLend.sol";
import { ISwapper } from "src/interfaces/ISwapper.sol";
import { ResupplyPairConstants } from "src/protocol/pair/ResupplyPairConstants.sol";
import { IERC4626 } from "src/interfaces/IERC4626.sol";
import { IStakedFrax } from "src/interfaces/frax/IStakedFrax.sol";
import { IPriceWatcher } from "src/interfaces/IPriceWatcher.sol";
import { IInterestRateCalculatorV2 } from "src/interfaces/IInterestRateCalculatorV2.sol";

/*
This is a utility library which is mainly used for off chain calculations
*/
contract Utilities is ResupplyPairConstants{
    address public constant INTEREST_RATE_CALCULATORV1 = address(0x77777777729C405efB6Ac823493e6111F0070D67);
    address public constant convexPoolUtil = address(0x5Fba69a794F395184b5760DAf1134028608e5Cd1);
    address public constant sfrxusd = address(0xcf62F905562626CfcDD2261162a51fd02Fc9c5b6);

    address public immutable registry;
    uint32 public constant TYPE_UNDEFINED = 0;
    uint32 public constant TYPE_SWAP = 1;
    uint32 public constant TYPE_DEPOSIT = 2;
    uint32 public constant TYPE_WITHDRAW = 3;

    constructor(address _registry){
        registry = _registry;
    }

    function sfrxusdRates() public view returns(uint256 fraxPerSecond){
        //on fraxtal need to get pricefeed, on mainnet check directly on sfrxusd
        IStakedFrax.RewardsCycleData memory rdata = IStakedFrax(sfrxusd).rewardsCycleData();
        uint256 sfrxusdtotal = IStakedFrax(sfrxusd).storedTotalAssets();
        if(sfrxusdtotal == 0){
            sfrxusdtotal = 1;
        }
        uint256 maxsfrxusdDistro = IStakedFrax(sfrxusd).maxDistributionPerSecondPerAsset();
        fraxPerSecond = rdata.rewardCycleAmount / (rdata.cycleEnd - rdata.lastSync);
        fraxPerSecond = fraxPerSecond * 1e18 / sfrxusdtotal;
        fraxPerSecond = fraxPerSecond > maxsfrxusdDistro ? maxsfrxusdDistro : fraxPerSecond;
    }

    function getUnderlyingSupplyRate(address _pair) public view returns(uint256 _rate){
        address collateral = IResupplyPair(_pair).collateral();
        (bool success, ) = collateral.staticcall(abi.encodeWithSelector(bytes4(keccak256("collateral_token()"))));
        if(success){
            //curvelend
            _rate = ICurveLend(collateral).lend_apr() / (365 * 86400);
        }else{
            //fraxlend
            (,,,IFraxLend.CurrentRateInfo memory rateInfo, IFraxLend.VaultAccount memory _totalAsset, IFraxLend.VaultAccount memory _totalBorrow) 
                        = IFraxLend(collateral).previewAddInterest();
            
            uint256 fraxlendRate = rateInfo.ratePerSec * (1e5 - rateInfo.feeToProtocolRate) / 1e5;
            if(_totalAsset.amount > 0){
                _rate = fraxlendRate * _totalBorrow.amount / _totalAsset.amount;
            }
        }
    }

    function getPairInterestRate(address _pair) external returns(uint256 _ratePerSecond){
        IInterestRateCalculatorV2 calculator = IInterestRateCalculatorV2(IResupplyPair(_pair).rateCalculator());
        uint256 underlyingRate = getUnderlyingSupplyRate(_pair);

        uint256 rateRatio;
        try calculator.rateRatio() returns (uint256 ratio) {rateRatio = ratio;}
        catch {return 0;} // Handle case where dummy calculator is used
        
        // Incorporate price weight if using V2 calculator
        if(address(calculator) != INTEREST_RATE_CALCULATORV1){
            uint256 rateRatioBase = calculator.rateRatioBase();
            uint256 rateRatioAdditional = calculator.rateRatioAdditional();
            address priceWatcher = IResupplyRegistry(registry).getAddress("PRICE_WATCHER");
            uint256 priceweight =  IPriceWatcher(priceWatcher).findPairPriceWeight(_pair);
            rateRatio = rateRatioBase + (rateRatioAdditional * priceweight / 1e6);
        }

       underlyingRate = underlyingRate / rateRatio;
       uint256 sfrxusdRate = sfrxusdRates() / rateRatio;
       uint256 minimumRate = 2e16 / uint256(365 days);
       _ratePerSecond = sfrxusdRate > minimumRate ? sfrxusdRate : minimumRate;

       _ratePerSecond = underlyingRate > _ratePerSecond ? underlyingRate : _ratePerSecond;
    }

    //get swap amount out of a given route
    function getSwapRouteAmountOut(uint256 _amount, address _swapper, address[] calldata _path) public view returns(uint256 _returnAmount){
        _returnAmount = _amount;
        for(uint256 i=0; i < _path.length-1;){
            (address swappool, int32 tokenInIndex, int32 tokenOutIndex, uint32 swaptype) = ISwapper(_swapper).swapPools(_path[i],_path[i+1]);

            if(swaptype == TYPE_UNDEFINED){
                //assume if i is 0 we want to withdraw
                //assume if i is anything else we want to deposit

                
                if(i==0){
                    swappool = _path[i]; //use current index as the 4626 vault to withdraw from
                    swaptype = TYPE_WITHDRAW;
                }else{
                    swappool = _path[i+1]; //use next index as the 4626 vault to deposit to
                    swaptype = TYPE_DEPOSIT;
                }
            }

            if(swaptype == TYPE_DEPOSIT){
                //if set as a deposit, use 4626 interface
                _returnAmount = IERC4626(swappool).previewDeposit(_returnAmount);
            }else if(swaptype == TYPE_WITHDRAW){
                //if set as a withdraw, use 4626 interface redeem
                _returnAmount = IERC4626(swappool).previewRedeem(_returnAmount);
            }else{
                //curve pool swap, use get_dy
                _returnAmount = ICurveExchange(swappool).get_dy(int128(tokenInIndex), int128(tokenOutIndex), _returnAmount);
            }
            unchecked{ i += 1;}
        }
    }

    //check if given account on given pair is solvent
    function isSolvent(address _pair, address _account) external returns(bool){
        uint256 _maxLTV = IResupplyPair(_pair).maxLTV();

        if (_maxLTV == 0) return true;

        //get borrow shares/amount
        uint256 userBorrowShares = IResupplyPair(_pair).userBorrowShares(_account);
        uint256 borrowerAmount = IResupplyPair(_pair).toBorrowAmount(userBorrowShares, true, true);

        if (borrowerAmount == 0) return true;
        
        //get collateral
        uint256 collateralAmount = IResupplyPair(_pair).userCollateralBalance(_account);
        if (collateralAmount == 0) return false;

        //get exchange rate
        (address oracle, , ) = IResupplyPair(_pair).exchangeRateInfo();
        address collateralVault = IResupplyPair(_pair).collateral();
        uint256 exchangeRate = IOracle(oracle).getPrices(collateralVault);
        //convert price of collateral as debt is priced in terms of collateral amount (inverse)
        exchangeRate = 1e36 / exchangeRate;

        uint256 _ltv = ((borrowerAmount * exchangeRate * LTV_PRECISION) / EXCHANGE_PRECISION) / collateralAmount;
        return _ltv <= _maxLTV;
    }

    //check if a user is solvent after a theoretical leveraged borrow
    //maxltv passed in to simulate enforcing a certain CR
    function isSolventAfterLeverage(address _pair, uint256 _maxLTV, address _account, uint256 _addUnderlying, uint256 _borrowAmount, uint256 _slippage, address _swapper, address[] calldata _path) external returns(bool, uint256, uint256, uint256){

        //get borrow shares/amount
        uint256 userBorrowShares = IResupplyPair(_pair).userBorrowShares(_account);
        uint256 borrowerAmount = IResupplyPair(_pair).toBorrowAmount(userBorrowShares, true, true);

        //add the new borrow amount
        borrowerAmount += _borrowAmount;
        
        //get collateral
        uint256 collateralAmount = IResupplyPair(_pair).userCollateralBalance(_account);
        address collateralVault = IResupplyPair(_pair).collateral();

        //add underlying
        if(_addUnderlying > 0){
            collateralAmount += IERC4626(collateralVault).previewDeposit(_addUnderlying);
        }

        //get exchange rate of the amount borrowed to collateral amount
        uint256 collateralReceived = getSwapRouteAmountOut(_borrowAmount, _swapper, _path);
        //assume a reduction of the returned amount defined by slippage
        collateralReceived = collateralReceived * _slippage / 1e18;

        //add to collateral amount
        collateralAmount += collateralReceived;


        //get exchange rate
        (address oracle, , ) = IResupplyPair(_pair).exchangeRateInfo();
        uint256 exchangeRate = IOracle(oracle).getPrices(collateralVault);
        //convert price of collateral as debt is priced in terms of collateral amount (inverse)
        exchangeRate = 1e36 / exchangeRate;

        uint256 _ltv = ((borrowerAmount * exchangeRate * LTV_PRECISION) / EXCHANGE_PRECISION) / collateralAmount;
        return (_ltv <= _maxLTV, _ltv, borrowerAmount, collateralAmount);
    }


    function apr(uint256 _rate, uint256 _priceOfReward, uint256 _priceOfDeposit) external view returns(uint256 _apr){
        return _rate * 365 days * _priceOfReward / _priceOfDeposit; 
    }

    //get rates for rewards received via collateral deposits
    //note: has an extra 1e18 decimals of precision
    function pairCollateralRewardRates(address _pair) public view returns (address[] memory tokens, uint256[] memory rates) {
        
        uint256 pid = IResupplyPair(_pair).convexPid();
        if(pid == 0){
            return (new address[](0), new uint256[](0));
        }

        //get reward rates on convex pools per collateral token
        (tokens, rates) = IConvexPoolUtil(convexPoolUtil).rewardRates(pid);

        //convert each rate from per collateral token to per debt share
        (,uint128 totalBorrow) = IResupplyPair(_pair).totalBorrow();
        uint256 totalCollateral = IResupplyPair(_pair).totalCollateral();
        if(totalBorrow == 0){
            totalBorrow = 1;
        }
        uint256 cbRatio = totalCollateral * 1e36 / uint256(totalBorrow);
        if(cbRatio == 0){
            cbRatio = 1e18; //if no collateal yet, just pad by 1e18
        }
        uint256 rlength = rates.length;
        for(uint256 i = 0; i < rlength; i++){
            //leave an extra 1e18 of precision by not dividing by 1e18 and let UI do the rest
            rates[i] = rates[i] * cbRatio;
        }
    }

    //get emission reward rates per borrow share on a given pair
    //note: has an extra 1e18 decimals of precision
    function getPairRsupRate(address _pair) external view returns(address[] memory tokens, uint256[] memory rates){
        address rewardHandler = IResupplyRegistry(registry).rewardHandler();
        address pairEmissions = IRewardHandler(rewardHandler).pairEmissions();

        //only 1 token and its known what its address is, but returning
        //arrays here to align with the other rate calls
        tokens = new address[](1);
        tokens[0] = IResupplyRegistry(registry).govToken();
        rates = new uint256[](1);

        if(IRewards(pairEmissions).periodFinish() >= block.timestamp){

            uint256 rewardRate = IRewards(pairEmissions).rewardRate();
            uint256 totalsupply = IRewards(pairEmissions).totalSupply();
            uint256 pairWeight = IRewards(pairEmissions).balanceOf(_pair);
            if(totalsupply == 0){
                totalsupply = 1;
            }

            //reward rate for this pair only
            //add an extra 1e18 padding of precision and let UI do the rest
            rewardRate = rewardRate * pairWeight * 1e36 / totalsupply;
            rates[0] = rewardRate;

            (,uint256 pairShares) = IResupplyPair(_pair).totalBorrow();
            if(pairShares > 0){
                rates[0] = rates[0] * 1e18 / pairShares;
            }
        }
    }

    //get emission rewards and protocol revenue share rates per pool share for the insurance pool
    //note: has an extra 1e18 decimals of precision
    function getInsurancePoolRewardRates() external view returns(address[] memory tokens, uint256[] memory rates){
        address rewardHandler = IResupplyRegistry(registry).rewardHandler();
        address insurancePool = IResupplyRegistry(registry).insurancePool();
        address insuranceEmissions = IRewardHandler(rewardHandler).insuranceEmissions();
        address insuranceRevenue = IRewardHandler(rewardHandler).insuranceRevenue();
        uint256 totalSupply = IRewards(insurancePool).totalSupply();

        tokens = new address[](2);
        tokens[0] = IResupplyRegistry(registry).govToken();
        tokens[1] = IResupplyRegistry(registry).token();
        rates = new uint256[](2);

        //gov token
        uint256 rewardRate = IRewards(insuranceEmissions).rewardRate();
        uint256 totalWeight = IRewards(insuranceEmissions).totalSupply();
        uint256 poolWeight = IRewards(insuranceEmissions).balanceOf(insurancePool);
        if(totalWeight == 0){
            totalWeight = 1;
        }
        //weight should be fully on the insurance pool but just in case..
        //add an extra 1e18 padding of precision and let UI do the rest
        rewardRate = rewardRate * poolWeight * 1e36 / totalWeight;

        if(IRewards(insuranceEmissions).periodFinish() >= block.timestamp){
            rates[0] = rewardRate;
            
            if(totalSupply > 0){
                rates[0] = rates[0] * 1e18 / totalSupply;
            }
        }

        //stable token
        rewardRate = IRewards(insuranceRevenue).rewardRate();
        totalWeight = IRewards(insuranceRevenue).totalSupply();
        poolWeight = IRewards(insuranceRevenue).balanceOf(insurancePool);
        if(totalWeight == 0){
            totalWeight = 1;
        }
        //weight should be fully on the insurance pool but just in case..
        //add an extra 1e18 padding of precision and let UI do the rest
        rewardRate = rewardRate * poolWeight * 1e36 / totalWeight;

        if(IRewards(insuranceRevenue).periodFinish() >= block.timestamp){
            rates[1] = rewardRate;
            
            if(totalSupply > 0){
                rates[1] = rates[1] * 1e18 / totalSupply;
            }
        }
    }
}

node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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

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

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

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

src/interfaces/IERC4626.sol

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

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

interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);
    event Withdraw(
        address indexed caller,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    function asset() external view returns (address);

    function convertToAssets(uint256 shares) external view returns (uint256);

    function convertToShares(uint256 assets) external view returns (uint256);

    function maxDeposit(address) external view returns (uint256);

    function maxMint(address) external view returns (uint256);

    function maxRedeem(address owner) external view returns (uint256);

    function maxWithdraw(address owner) external view returns (uint256);

    function previewDeposit(uint256 assets) external view returns (uint256);

    function previewMint(uint256 shares) external view returns (uint256);

    function previewRedeem(uint256 shares) external view returns (uint256);

    function previewWithdraw(uint256 assets) external view returns (uint256);

    function totalAssets() external view returns (uint256);

    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);

    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
}

src/interfaces/IInterestRateCalculatorV2.sol

pragma solidity 0.8.28;

interface IInterestRateCalculatorV2 {
    function getNewRate(
        address _vault,
        uint256 _deltaTime,
        uint256 _previousShares
    ) external view returns (uint64 _newRatePerSec, uint128 _newShares);

    function minimumRate() external view returns (uint256);

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

    function rateRatio() external view returns (uint256);

    function sfrxusd() external view returns (address);

    function sfrxusdRates() external view returns (uint256 fraxPerSecond);

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

    function rateRatioBase() external view returns (uint256);
    function rateRatioAdditional() external view returns (uint256);

    function version()
        external
        pure
        returns (
            uint256 _major,
            uint256 _minor,
            uint256 _patch
        );
}

src/interfaces/IOracle.sol

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

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

    function getPrices(address _vault) external view returns (uint256 _price);

    function name() external view returns (string memory);
}

src/interfaces/IPriceWatcher.sol

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

interface IPriceWatcher {
    struct PriceData{
        uint64 timestamp;
        uint64 weight;
        uint128 totalWeight;
    }

    function updatePriceData() external;
    function priceDataLength() external view returns(uint256);
    function priceDataAtIndex(uint256 i) external view returns(PriceData memory _pd);
    function latestPriceData() external view returns(PriceData memory _pd);
    function findPairPriceWeight(address _pair) external view returns(uint256);
}

src/interfaces/IRateCalculator.sol

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

interface IRateCalculator {
    function name() external view returns (string memory);

    function version() external view returns (uint256, uint256, uint256);

    function getNewRate(
        address _vault,
        uint256 _deltaTime,
        uint256 _previousShares
    ) external view returns (uint64 _newRatePerSec, uint128 _newShares);
}

src/interfaces/IResupplyPair.sol

pragma solidity 0.8.28;

interface IResupplyPair {
    
    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) ;

    error BadSwapper(  );
    error BorrowerSolvent(  );
    error FeesAlreadyWithdrawn(  );
    error IncorrectStakeBalance(  );
    error Insolvent( uint256 _borrow,uint256 _collateral,uint256 _exchangeRate );
    error InsufficientBorrowAmount(  );
    error InsufficientDebtAvailable( uint256 _assets,uint256 _request );
    error InsufficientDebtToRedeem(  );
    error InvalidLiquidator(  );
    error InvalidParameter(  );
    error InvalidPath( address _expected,address _actual );
    error InvalidReceiver(  );
    error InvalidRedemptionHandler(  );
    error MinimumRedemption(  );
    error OnlyProtocolOrOwner(  );
    error ReentrancyGuardReentrantCall(  );
    error SafeCastOverflowedUintDowncast( uint8 bits,uint256 value );
    error SafeERC20FailedOperation( address token );
    error SlippageTooHigh( uint256 _minOut,uint256 _actual );
    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/IRewardHandler.sol

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

interface IRewardHandler{
    function checkNewRewards(address _pair) external;
    function claimRewards(address _pair) external;
    function claimInsuranceRewards() external;
    function setPairWeight(address _pair, uint256 _amount) external;
    function queueInsuranceRewards() external;
    function queueStakingRewards() external;
    function pairEmissions() external view returns(address);
    function insuranceEmissions() external view returns(address);
    function insuranceRevenue() external view returns(address);
    function debtEmissionsReceiver() external view returns(address);
    function insuranceEmissionReceiver() external view returns(address);
    function pairTimestamp(address _pair) external view returns(uint256);
    function minimumWeights(address _pair) external view returns(uint256);
    function migrateState(address _oldRewardHandler, bool _migrateTimestamp, bool _migrateMinWeights) external;
}

src/interfaces/IRewards.sol

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

interface IRewards{
    struct EarnedData {
        address token;
        uint256 amount;
    }

    function rewardMap(address _token) external view returns(uint256 slot);
    function rewards(uint256 index) external view returns(address reward_token, uint256 reward_remaining, bool is_non_claimable);
    function rewardToken() external view returns(address);
    function periodFinish() external view returns(uint256);
    function rewardRate() external view returns(uint256);
    function totalSupply() external view returns(uint256);
    function balanceOf(address _account) external view returns(uint256);
    function queueNewRewards(uint256 _rewards) external returns(bool);
    function notifyRewardAmount(address _rewardsToken, uint256 _rewardAmount) external;
    function setMinimumWeight(address _account, uint256 _amount) external;
    function setWeight(address _account, uint256 _amount) external returns(bool);
    function setWeights(address[] calldata _account, uint256[] calldata _amount) external;
    function getReward() external;
    function getReward(address _account) external;
    function getReward(address _account, address _forwardTo) external;
    function setRewardRedirect(address _to) external;
    function user_checkpoint(address _account) external;
    function earned(address _account) external returns(EarnedData[] memory claimable);
}

src/interfaces/ISwapper.sol

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

interface ISwapper {
    function swap(
        address account,
        uint256 amountIn,
        address[] calldata path,
        address to
    ) external;

    function swapPools(address tokenIn, address tokenOut) external view returns(address swappool, int32 tokenInIndex, int32 tokenOutIndex, uint32 swaptype);
}

src/interfaces/convex/IConvexPoolUtil.sol

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

interface IConvexPoolUtil {
    function rewardRates(uint256 _pid) external view returns (address[] memory tokens, uint256[] memory rates);
}

src/interfaces/curve/ICurveExchange.sol

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

interface ICurveExchange {

    function exchange(
        int128,
        int128,
        uint256,
        uint256,
        address
    ) external returns (uint256);

    function balanceOf(address _account) external view returns(uint256);
    function get_dy(int128 i, int128 j, uint256 amount) external view returns(uint256);
    function calc_token_amount(uint256[2] calldata _amounts, bool _isDeposit) external view returns(uint256);
    function calc_token_amount(uint256[2] calldata _amounts) external view returns(uint256);
    function calc_withdraw_one_coin(uint256 _amount, int128 _index) external view returns(uint256);
    function calc_withdraw_one_coin(uint256 _amount, uint256 _index) external view returns(uint256);
    function add_liquidity(uint256[] calldata _amounts, uint256 _min_mint_amount, address _receiver) external returns(uint256);
    // function add_liquidity(uint256[2] calldata _amounts, uint256 _min_mint_amount, address _receiver) external returns(uint256);
    // function add_liquidity(uint256[2] calldata _amounts, uint256 _min_mint_amount, bool _useEth, address _receiver) external returns(uint256);
    function remove_liquidity(uint256 _amount, uint256[2] calldata _min_amounts, address _receiver) external returns(uint256[2] calldata);
    function remove_liquidity_one_coin(uint256 _amount, int128 _index, uint256 _min_amount, address _receiver) external returns(uint256);
    function remove_liquidity_one_coin(uint256 _amount, uint256 _index, uint256 _min_amount, address _receiver) external returns(uint256);
    function remove_liquidity_one_coin(uint256 _amount, uint256 _index, uint256 _min_amount, bool _useEth, address _receiver) external returns(uint256);
    function deploy_gauge(address _pool) external returns(address);
    function price_scale() external view returns(uint256);
    function price_oracle() external view returns(uint256);
    function deploy_plain_pool(string calldata _name,string calldata _symbol,address[] calldata _coins,uint256 _A,uint256 _fee,uint256 _offpeg_fee_multiplier,uint256 _ma_exp_time,uint256 _implementation_idx,uint8[] calldata _asset_types,bytes4[] calldata _method_ids,address[] calldata _oracles) external returns(address);
    function coins(uint256 _index) external view returns(address);
}

src/interfaces/curve/ICurveLend.sol

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

interface ICurveLend {

    function lend_apr() external view returns(uint256);
}

src/interfaces/frax/IFraxLend.sol

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

interface IFraxLend {

    struct CurrentRateInfo {
        uint32 lastBlock;
        uint32 feeToProtocolRate; // Fee amount 1e5 precision
        uint64 lastTimestamp;
        uint64 ratePerSec;
        uint64 fullUtilizationRate;
    }

    struct VaultAccount {
        uint128 amount;
        uint128 shares;
    }

    function addInterest(bool) external;

    function previewAddInterest()
        external
        view
        returns (
            uint256 _interestEarned,
            uint256 _feesAmount,
            uint256 _feesShare,
            CurrentRateInfo memory _newCurrentRateInfo,
            VaultAccount memory _totalAsset,
            VaultAccount memory _totalBorrow
        );
}

src/interfaces/frax/IStakedFrax.sol

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

interface IStakedFrax {
    struct RewardsCycleData {
        uint40 cycleEnd; // Timestamp of the end of the current rewards cycle
        uint40 lastSync; // Timestamp of the last time the rewards cycle was synced
        uint216 rewardCycleAmount; // Amount of rewards to be distributed in the current cycle
    }

    function rewardsCycleData() external view returns(RewardsCycleData memory);
    function storedTotalAssets() external view returns(uint256);
    function maxDistributionPerSecondPerAsset() external view returns(uint256);
    function priceFeedVault() external view returns(address);
    function syncRewardsAndDistribution() external;
    function updateVaultTknOracle() external;
    function setMintRedeemFee(uint256 _fee) external;
}

src/protocol/pair/ResupplyPairConstants.sol

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

/**
 * @title ResupplyPairConstants
 * @notice Based on code from Drake Evans and Frax Finance's pair constants (https://github.com/FraxFinance/fraxlend), adapted for Resupply Finance
 */

abstract contract ResupplyPairConstants {

    // Precision settings
    uint256 public constant LTV_PRECISION = 1e5; // 5 decimals
    uint256 public constant LIQ_PRECISION = 1e5;
    uint256 public constant EXCHANGE_PRECISION = 1e18;
    uint256 public constant RATE_PRECISION = 1e18;
    uint256 public constant SHARE_REFACTOR_PRECISION = 1e12;
    uint256 public constant PAIR_DECIMALS = 1e18;
    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 InvalidOraclePrice();
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "ds-test/=node_modules/ds-test/src/",
    "forge-std/=node_modules/forge-std/src/",
    "frax-std/=node_modules/frax-standard-solidity/src/",
    "@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/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@rari-capital/=node_modules/@rari-capital/",
    "@uniswap/=node_modules/@uniswap/",
    "base64-sol/=node_modules/base64-sol/",
    "frax-standard-solidity/=node_modules/frax-standard-solidity/",
    "hardhat-deploy/=node_modules/hardhat-deploy/",
    "hardhat/=node_modules/hardhat/",
    "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.