/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/pragmasolidity 0.6.10;pragmaexperimentalABIEncoderV2;import { Address } from"@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from"@openzeppelin/contracts/math/Math.sol";
import { SafeCast } from"@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from"@openzeppelin/contracts/math/SafeMath.sol";
import { BaseExtension } from"../lib/BaseExtension.sol";
import { IBaseManager } from"../interfaces/IBaseManager.sol";
import { IChainlinkAggregatorV3 } from"../interfaces/IChainlinkAggregatorV3.sol";
import { ILeverageModule } from"../interfaces/ILeverageModule.sol";
import { IProtocolDataProvider } from"../interfaces/IProtocolDataProvider.sol";
import { ISetToken } from"../interfaces/ISetToken.sol";
import { PreciseUnitMath } from"../lib/PreciseUnitMath.sol";
import { StringArrayUtils } from"../lib/StringArrayUtils.sol";
/**
* @title AaveLeverageStrategyExtension
* @author Set Protocol
*
* Smart contract that enables trustless leverage tokens. This extension is paired with the AaveLeverageModule from Set protocol where module
* interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow asset
* is available on Aave. This extension contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance
* function at different leverage thresholds.
*
*/contractAaveLeverageStrategyExtensionisBaseExtension{
usingAddressforaddress;
usingPreciseUnitMathforuint256;
usingSafeMathforuint256;
usingSafeCastforint256;
usingStringArrayUtilsforstring[];
/* ============ Enums ============ */enumShouldRebalance {
NONE, // Indicates no rebalance action can be taken
REBALANCE, // Indicates rebalance() function can be successfully called
ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called
RIPCORD // Indicates ripcord() function can be successfully called
}
/* ============ Structs ============ */structActionInfo {
uint256 collateralBalance; // Balance of underlying held in Aave in base units (e.g. USDC 10e6)uint256 borrowBalance; // Balance of underlying borrowed from Aave in base unitsuint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18)uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18)uint256 collateralPrice; // Price of collateral in precise units (10e18) from Chainlinkuint256 borrowPrice; // Price of borrow asset in precise units (10e18) from Chainlinkuint256 setTotalSupply; // Total supply of SetToken
}
structLeverageInfo {
ActionInfo action;
uint256 currentLeverageRatio; // Current leverage ratio of Setuint256 slippageTolerance; // Allowable percent trade slippage in preciseUnits (1% = 10^16)uint256 twapMaxTradeSize; // Max trade size in collateral units allowed for rebalance actionstring exchangeName; // Exchange to use for trade
}
structContractSettings {
ISetToken setToken; // Instance of leverage token
ILeverageModule leverageModule; // Instance of Aave leverage module
IProtocolDataProvider aaveProtocolDataProvider; // Instance of Aave protocol data provider
IChainlinkAggregatorV3 collateralPriceOracle; // Chainlink oracle feed that returns prices in 8 decimals for collateral asset
IChainlinkAggregatorV3 borrowPriceOracle; // Chainlink oracle feed that returns prices in 8 decimals for borrow asset
IERC20 targetCollateralAToken; // Instance of target collateral aToken asset
IERC20 targetBorrowDebtToken; // Instance of target borrow variable debt token assetaddress collateralAsset; // Address of underlying collateraladdress borrowAsset; // Address of underlying borrow assetuint256 collateralDecimalAdjustment; // Decimal adjustment for chainlink oracle of the collateral asset. Equal to 28-collateralDecimals (10^18 * 10^18 / 10^decimals / 10^8)uint256 borrowDecimalAdjustment; // Decimal adjustment for chainlink oracle of the borrowing asset. Equal to 28-borrowDecimals (10^18 * 10^18 / 10^decimals / 10^8)
}
structMethodologySettings {
uint256 targetLeverageRatio; // Long term target ratio in precise units (10e18)uint256 minLeverageRatio; // In precise units (10e18). If current leverage is below, rebalance target is this ratiouint256 maxLeverageRatio; // In precise units (10e18). If current leverage is above, rebalance target is this ratiouint256 recenteringSpeed; // % at which to rebalance back to target leverage in precise units (10e18)uint256 rebalanceInterval; // Period of time required since last rebalance timestamp in seconds
}
structExecutionSettings {
uint256 unutilizedLeveragePercentage; // Percent of max borrow left unutilized in precise units (1% = 10e16)uint256 slippageTolerance; // % in precise units to price min token receive amount from trade quantitiesuint256 twapCooldownPeriod; // Cooldown period required since last trade timestamp in seconds
}
structExchangeSettings {
uint256 twapMaxTradeSize; // Max trade size in collateral base unitsuint256 exchangeLastTradeTimestamp; // Timestamp of last trade made with this exchangeuint256 incentivizedTwapMaxTradeSize; // Max trade size for incentivized rebalances in collateral base unitsbytes leverExchangeData; // Arbitrary exchange data passed into rebalance function for levering upbytes deleverExchangeData; // Arbitrary exchange data passed into rebalance function for delevering
}
structIncentiveSettings {
uint256 etherReward; // ETH reward for incentivized rebalancesuint256 incentivizedLeverageRatio; // Leverage ratio for incentivized rebalancesuint256 incentivizedSlippageTolerance; // Slippage tolerance percentage for incentivized rebalancesuint256 incentivizedTwapCooldownPeriod; // TWAP cooldown in seconds for incentivized rebalances
}
/* ============ Events ============ */eventEngaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
eventRebalanced(uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional
);
eventRebalanceIterated(uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional
);
eventRipcordCalled(uint256 _currentLeverageRatio,
uint256 _newLeverageRatio,
uint256 _rebalanceNotional,
uint256 _etherIncentive
);
eventDisengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional);
eventMethodologySettingsUpdated(uint256 _targetLeverageRatio,
uint256 _minLeverageRatio,
uint256 _maxLeverageRatio,
uint256 _recenteringSpeed,
uint256 _rebalanceInterval
);
eventExecutionSettingsUpdated(uint256 _unutilizedLeveragePercentage,
uint256 _twapCooldownPeriod,
uint256 _slippageTolerance
);
eventIncentiveSettingsUpdated(uint256 _etherReward,
uint256 _incentivizedLeverageRatio,
uint256 _incentivizedSlippageTolerance,
uint256 _incentivizedTwapCooldownPeriod
);
eventExchangeUpdated(string _exchangeName,
uint256 twapMaxTradeSize,
uint256 exchangeLastTradeTimestamp,
uint256 incentivizedTwapMaxTradeSize,
bytes leverExchangeData,
bytes deleverExchangeData
);
eventExchangeAdded(string _exchangeName,
uint256 twapMaxTradeSize,
uint256 exchangeLastTradeTimestamp,
uint256 incentivizedTwapMaxTradeSize,
bytes leverExchangeData,
bytes deleverExchangeData
);
eventExchangeRemoved(string _exchangeName
);
/* ============ Modifiers ============ *//**
* Throws if rebalance is currently in TWAP`
*/modifiernoRebalanceInProgress() virtual{
require(twapLeverageRatio ==0, "Rebalance is currently in progress");
_;
}
/* ============ State Variables ============ */
ContractSettings internal strategy; // Struct of contracts used in the strategy (SetToken, price oracles, leverage module etc)
MethodologySettings internal methodology; // Struct containing methodology parameters
ExecutionSettings internal execution; // Struct containing execution parametersmapping(string=> ExchangeSettings) internal exchangeSettings; // Mapping from exchange name to exchange settings
IncentiveSettings internal incentive; // Struct containing incentive parameters for ripcordstring[] public enabledExchanges; // Array containing enabled exchangesuint256public twapLeverageRatio; // Stored leverage ratio to keep track of target between TWAP rebalancesuint256public globalLastTradeTimestamp; // Last rebalance timestamp. Current timestamp must be greater than this variable + rebalance interval to rebalance/* ============ Constructor ============ *//**
* Instantiate addresses, methodology parameters, execution parameters, and incentive parameters.
*
* @param _manager Address of IBaseManager contract
* @param _strategy Struct of contract addresses
* @param _methodology Struct containing methodology parameters
* @param _execution Struct containing execution parameters
* @param _incentive Struct containing incentive parameters for ripcord
* @param _exchangeNames List of initial exchange names
* @param _exchangeSettings List of structs containing exchange parameters for the initial exchanges
*/constructor(
IBaseManager _manager,
ContractSettings memory _strategy,
MethodologySettings memory _methodology,
ExecutionSettings memory _execution,
IncentiveSettings memory _incentive,
string[] memory _exchangeNames,
ExchangeSettings[] memory _exchangeSettings
)
publicBaseExtension(_manager)
{
strategy = _strategy;
methodology = _methodology;
execution = _execution;
incentive = _incentive;
for (uint256 i =0; i < _exchangeNames.length; i++) {
_validateExchangeSettings(_exchangeSettings[i]);
exchangeSettings[_exchangeNames[i]] = _exchangeSettings[i];
enabledExchanges.push(_exchangeNames[i]);
}
_validateNonExchangeSettings(methodology, execution, incentive);
}
/* ============ External Functions ============ *//**
* OPERATOR ONLY: Engage to target leverage ratio for the first time. SetToken will borrow debt position from Aave and trade for collateral asset. If target
* leverage ratio is above max borrow or max trade size, then TWAP is kicked off. To complete engage if TWAP, any valid caller must call iterateRebalance until target
* is met.
*
* @param _exchangeName the exchange used for trading
*/functionengage(stringmemory _exchangeName) externalonlyOperator{
ActionInfo memory engageInfo = _createActionInfo();
require(engageInfo.setTotalSupply >0, "SetToken must have > 0 supply");
require(engageInfo.collateralBalance >0, "Collateral balance must be > 0");
require(engageInfo.borrowBalance ==0, "Debt must be 0");
LeverageInfo memory leverageInfo = LeverageInfo({
action: engageInfo,
currentLeverageRatio: PreciseUnitMath.preciseUnit(), // 1x leverage in precise units
slippageTolerance: execution.slippageTolerance,
twapMaxTradeSize: exchangeSettings[_exchangeName].twapMaxTradeSize,
exchangeName: _exchangeName
});
// Calculate total rebalance units and kick off TWAP if above max borrow or max trade size
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true);
_lever(leverageInfo, chunkRebalanceNotional);
_updateRebalanceState(
chunkRebalanceNotional,
totalRebalanceNotional,
methodology.targetLeverageRatio,
_exchangeName
);
emit Engaged(
leverageInfo.currentLeverageRatio,
methodology.targetLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA AND ALLOWED CALLER: Rebalance product. If current leverage ratio is between the max and min bounds, then rebalance
* can only be called once the rebalance interval has elapsed since last timestamp. If outside the max and min, rebalance can be called anytime to bring leverage
* ratio back to the max or min bounds. The methodology will determine whether to delever or lever.
*
* Note: If the calculated current leverage ratio is above the incentivized leverage ratio or in TWAP then rebalance cannot be called. Instead, you must call
* ripcord() which is incentivized with a reward in Ether or iterateRebalance().
*
* @param _exchangeName the exchange used for trading
*/functionrebalance(stringmemory _exchangeName) externalonlyEOAonlyAllowedCaller(msg.sender) {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
// use globalLastTradeTimestamps to prevent multiple rebalances being called with different exchanges during the epoch rebalance
_validateNormalRebalance(leverageInfo, methodology.rebalanceInterval, globalLastTradeTimestamp);
_validateNonTWAP();
uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio);
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _handleRebalance(leverageInfo, newLeverageRatio);
_updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio, _exchangeName);
emit Rebalanced(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA AND ALLOWED CALLER: Iterate a rebalance when in TWAP. TWAP cooldown period must have elapsed. If price moves advantageously, then exit without rebalancing
* and clear TWAP state. This function can only be called when below incentivized leverage ratio and in TWAP state.
*
* @param _exchangeName the exchange used for trading
*/functioniterateRebalance(stringmemory _exchangeName) externalonlyEOAonlyAllowedCaller(msg.sender) {
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
// Use the exchangeLastTradeTimestamp since cooldown periods are measured on a per-exchange basis, allowing it to rebalance multiple time in quick// succession with different exchanges
_validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod, exchangeSettings[_exchangeName].exchangeLastTradeTimestamp);
_validateTWAP();
uint256 chunkRebalanceNotional;
uint256 totalRebalanceNotional;
if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) {
(chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio);
}
// If not advantageous, then rebalance is skipped and chunk and total rebalance notional are both 0, which means TWAP state is// cleared
_updateIterateState(chunkRebalanceNotional, totalRebalanceNotional, _exchangeName);
emit RebalanceIterated(
leverageInfo.currentLeverageRatio,
twapLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* ONLY EOA: In case the current leverage ratio exceeds the incentivized leverage threshold, the ripcord function can be called by anyone to return leverage ratio
* back to the max leverage ratio. This function typically would only be called during times of high downside volatility and / or normal keeper malfunctions. The caller
* of ripcord() will receive a reward in Ether. The ripcord function uses it's own TWAP cooldown period, slippage tolerance and TWAP max trade size which are typically
* looser than in regular rebalances.
*
* @param _exchangeName the exchange used for trading
*/functionripcord(stringmemory _exchangeName) externalonlyEOA{
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
incentive.incentivizedSlippageTolerance,
exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize,
_exchangeName
);
// Use the exchangeLastTradeTimestamp so it can ripcord quickly with multiple exchanges
_validateRipcord(leverageInfo, exchangeSettings[_exchangeName].exchangeLastTradeTimestamp);
( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false);
_delever(leverageInfo, chunkRebalanceNotional);
_updateRipcordState(_exchangeName);
uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward);
emit RipcordCalled(
leverageInfo.currentLeverageRatio,
methodology.maxLeverageRatio,
chunkRebalanceNotional,
etherTransferred
);
}
/**
* OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeem
* collateral position and trade for debt position to repay Aave. If the chunk rebalance size is less than the total notional size, then this function will
* delever and repay entire borrow balance on Aave. If chunk rebalance size is above max borrow or max trade size, then operator must
* continue to call this function to complete repayment of loan. The function iterateRebalance will not work.
*
* Note: Delever to 0 will likely result in additional units of the borrow asset added as equity on the SetToken due to oracle price / market price mismatch
*
* @param _exchangeName the exchange used for trading
*/functiondisengage(stringmemory _exchangeName) externalonlyOperator{
LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(
execution.slippageTolerance,
exchangeSettings[_exchangeName].twapMaxTradeSize,
_exchangeName
);
uint256 newLeverageRatio = PreciseUnitMath.preciseUnit();
(
uint256 chunkRebalanceNotional,
uint256 totalRebalanceNotional
) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false);
if (totalRebalanceNotional > chunkRebalanceNotional) {
_delever(leverageInfo, chunkRebalanceNotional);
} else {
_deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional);
}
emit Disengaged(
leverageInfo.currentLeverageRatio,
newLeverageRatio,
chunkRebalanceNotional,
totalRebalanceNotional
);
}
/**
* OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newMethodologySettings Struct containing methodology parameters
*/functionsetMethodologySettings(MethodologySettings memory _newMethodologySettings) externalonlyOperatornoRebalanceInProgress{
methodology = _newMethodologySettings;
_validateNonExchangeSettings(methodology, execution, incentive);
emit MethodologySettingsUpdated(
methodology.targetLeverageRatio,
methodology.minLeverageRatio,
methodology.maxLeverageRatio,
methodology.recenteringSpeed,
methodology.rebalanceInterval
);
}
/**
* OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newExecutionSettings Struct containing execution parameters
*/functionsetExecutionSettings(ExecutionSettings memory _newExecutionSettings) externalonlyOperatornoRebalanceInProgress{
execution = _newExecutionSettings;
_validateNonExchangeSettings(methodology, execution, incentive);
emit ExecutionSettingsUpdated(
execution.unutilizedLeveragePercentage,
execution.twapCooldownPeriod,
execution.slippageTolerance
);
}
/**
* OPERATOR ONLY: Set incentive settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be
* in a rebalance.
*
* @param _newIncentiveSettings Struct containing incentive parameters
*/functionsetIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) externalonlyOperatornoRebalanceInProgress{
incentive = _newIncentiveSettings;
_validateNonExchangeSettings(methodology, execution, incentive);
emit IncentiveSettingsUpdated(
incentive.etherReward,
incentive.incentivizedLeverageRatio,
incentive.incentivizedSlippageTolerance,
incentive.incentivizedTwapCooldownPeriod
);
}
/**
* OPERATOR ONLY: Add a new enabled exchange for trading during rebalances. New exchanges will have their exchangeLastTradeTimestamp set to 0. Adding
* exchanges during rebalances is allowed, as it is not possible to enter an unexpected state while doing so.
*
* @param _exchangeName Name of the exchange
* @param _exchangeSettings Struct containing exchange parameters
*/functionaddEnabledExchange(stringmemory _exchangeName,
ExchangeSettings memory _exchangeSettings
)
externalonlyOperator{
require(exchangeSettings[_exchangeName].twapMaxTradeSize ==0, "Exchange already enabled");
_validateExchangeSettings(_exchangeSettings);
exchangeSettings[_exchangeName].twapMaxTradeSize = _exchangeSettings.twapMaxTradeSize;
exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize = _exchangeSettings.incentivizedTwapMaxTradeSize;
exchangeSettings[_exchangeName].leverExchangeData = _exchangeSettings.leverExchangeData;
exchangeSettings[_exchangeName].deleverExchangeData = _exchangeSettings.deleverExchangeData;
exchangeSettings[_exchangeName].exchangeLastTradeTimestamp =0;
enabledExchanges.push(_exchangeName);
emit ExchangeAdded(
_exchangeName,
_exchangeSettings.twapMaxTradeSize,
_exchangeSettings.exchangeLastTradeTimestamp,
_exchangeSettings.incentivizedTwapMaxTradeSize,
_exchangeSettings.leverExchangeData,
_exchangeSettings.deleverExchangeData
);
}
/**
* OPERATOR ONLY: Removes an exchange. Reverts if the exchange is not already enabled. Removing exchanges during rebalances is allowed,
* as it is not possible to enter an unexpected state while doing so.
*
* @param _exchangeName Name of exchange to remove
*/functionremoveEnabledExchange(stringmemory _exchangeName) externalonlyOperator{
require(exchangeSettings[_exchangeName].twapMaxTradeSize !=0, "Exchange not enabled");
delete exchangeSettings[_exchangeName];
enabledExchanges.removeStorage(_exchangeName);
emit ExchangeRemoved(_exchangeName);
}
/**
* OPERATOR ONLY: Updates the settings of an exchange. Reverts if exchange is not already added. When updating an exchange, exchangeLastTradeTimestamp
* is preserved. Updating exchanges during rebalances is allowed, as it is not possible to enter an unexpected state while doing so. Note: Need to
* pass in all existing parameters even if only changing a few settings.
*
* @param _exchangeName Name of the exchange
* @param _exchangeSettings Struct containing exchange parameters
*/functionupdateEnabledExchange(stringmemory _exchangeName,
ExchangeSettings memory _exchangeSettings
)
externalonlyOperator{
require(exchangeSettings[_exchangeName].twapMaxTradeSize !=0, "Exchange not enabled");
_validateExchangeSettings(_exchangeSettings);
exchangeSettings[_exchangeName].twapMaxTradeSize = _exchangeSettings.twapMaxTradeSize;
exchangeSettings[_exchangeName].incentivizedTwapMaxTradeSize = _exchangeSettings.incentivizedTwapMaxTradeSize;
exchangeSettings[_exchangeName].leverExchangeData = _exchangeSettings.leverExchangeData;
exchangeSettings[_exchangeName].deleverExchangeData = _exchangeSettings.deleverExchangeData;
emit ExchangeUpdated(
_exchangeName,
_exchangeSettings.twapMaxTradeSize,
_exchangeSettings.exchangeLastTradeTimestamp,
_exchangeSettings.incentivizedTwapMaxTradeSize,
_exchangeSettings.leverExchangeData,
_exchangeSettings.deleverExchangeData
);
}
/**
* OPERATOR ONLY: Withdraw entire balance of ETH in this contract to operator. Rebalance must not be in progress
*/functionwithdrawEtherBalance() externalonlyOperatornoRebalanceInProgress{
msg.sender.transfer(address(this).balance);
}
receive() externalpayable{}
/* ============ External Getter Functions ============ *//**
* Get current leverage ratio. Current leverage ratio is defined as the USD value of the collateral divided by the USD value of the SetToken. Prices for collateral
* and borrow asset are retrieved from the Chainlink Price Oracle.
*
* return currentLeverageRatio Current leverage ratio in precise units (10e18)
*/functiongetCurrentLeverageRatio() publicviewreturns(uint256) {
ActionInfo memory currentLeverageInfo = _createActionInfo();
return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue);
}
/**
* Calculates the chunk rebalance size. This can be used by external contracts and keeper bots to calculate the optimal exchange to rebalance with.
* Note: this function does not take into account timestamps, so it may return a nonzero value even when shouldRebalance would return ShouldRebalance.NONE for
* all exchanges (since minimum delays have not elapsed)
*
* @param _exchangeNames Array of exchange names to get rebalance sizes for
*
* @return sizes Array of total notional chunk size. Measured in the asset that would be sold
* @return sellAsset Asset that would be sold during a rebalance
* @return buyAsset Asset that would be purchased during a rebalance
*/functiongetChunkRebalanceNotional(string[] calldata _exchangeNames
)
externalviewreturns(uint256[] memory sizes, address sellAsset, address buyAsset)
{
uint256 newLeverageRatio;
uint256 currentLeverageRatio = getCurrentLeverageRatio();
bool isRipcord =false;
// if over incentivized leverage ratio, always ripcordif (currentLeverageRatio > incentive.incentivizedLeverageRatio) {
newLeverageRatio = methodology.maxLeverageRatio;
isRipcord =true;
// if we are in an ongoing twap, use the cached twapLeverageRatio as our target leverage
} elseif (twapLeverageRatio >0) {
newLeverageRatio = twapLeverageRatio;
// if all else is false, then we would just use the normal rebalance new leverage ratio calculation
} else {
newLeverageRatio = _calculateNewLeverageRatio(currentLeverageRatio);
}
ActionInfo memory actionInfo = _createActionInfo();
bool isLever = newLeverageRatio > currentLeverageRatio;
sizes =newuint256[](_exchangeNames.length);
for (uint256 i =0; i < _exchangeNames.length; i++) {
LeverageInfo memory leverageInfo = LeverageInfo({
action: actionInfo,
currentLeverageRatio: currentLeverageRatio,
slippageTolerance: isRipcord ? incentive.incentivizedSlippageTolerance : execution.slippageTolerance,
twapMaxTradeSize: isRipcord ?
exchangeSettings[_exchangeNames[i]].incentivizedTwapMaxTradeSize :
exchangeSettings[_exchangeNames[i]].twapMaxTradeSize,
exchangeName: _exchangeNames[i]
});
(uint256 collateralNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, isLever);
// _calculateBorrowUnits can convert both unit and notional values
sizes[i] = isLever ? _calculateBorrowUnits(collateralNotional, leverageInfo.action) : collateralNotional;
}
sellAsset = isLever ? strategy.borrowAsset : strategy.collateralAsset;
buyAsset = isLever ? strategy.collateralAsset : strategy.borrowAsset;
}
/**
* Get current Ether incentive for when current leverage ratio exceeds incentivized leverage ratio and ripcord can be called. If ETH balance on the contract is
* below the etherReward, then return the balance of ETH instead.
*
* return etherReward Quantity of ETH reward in base units (10e18)
*/functiongetCurrentEtherIncentive() externalviewreturns(uint256) {
uint256 currentLeverageRatio = getCurrentLeverageRatio();
if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
// If ETH reward is below the balance on this contract, then return ETH balance on contract insteadreturn incentive.etherReward <address(this).balance ? incentive.etherReward : address(this).balance;
} else {
return0;
}
}
/**
* Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()
* 3 = call ripcord()
*
* @return (string[] memory, ShouldRebalance[] memory) List of exchange names and a list of enums representing whether that exchange should rebalance
*/functionshouldRebalance() externalviewreturns(string[] memory, ShouldRebalance[] memory) {
uint256 currentLeverageRatio = getCurrentLeverageRatio();
return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio);
}
/**
* Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the
* logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with
* 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance(), 3 = call ripcord()
*
* @param _customMinLeverageRatio Min leverage ratio passed in by caller
* @param _customMaxLeverageRatio Max leverage ratio passed in by caller
*
* @return (string[] memory, ShouldRebalance[] memory) List of exchange names and a list of enums representing whether that exchange should rebalance
*/functionshouldRebalanceWithBounds(uint256 _customMinLeverageRatio,
uint256 _customMaxLeverageRatio
)
externalviewreturns(string[] memory, ShouldRebalance[] memory)
{
require (
_customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio,
"Custom bounds must be valid"
);
uint256 currentLeverageRatio = getCurrentLeverageRatio();
return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio);
}
/**
* Gets the list of enabled exchanges
*/functiongetEnabledExchanges() externalviewreturns (string[] memory) {
return enabledExchanges;
}
/**
* Explicit getter functions for parameter structs are defined as workaround to issues fetching structs that have dynamic types.
*/functiongetStrategy() externalviewreturns (ContractSettings memory) { return strategy; }
functiongetMethodology() externalviewreturns (MethodologySettings memory) { return methodology; }
functiongetExecution() externalviewreturns (ExecutionSettings memory) { return execution; }
functiongetIncentive() externalviewreturns (IncentiveSettings memory) { return incentive; }
functiongetExchangeSettings(stringmemory _exchangeName) externalviewreturns (ExchangeSettings memory) {
return exchangeSettings[_exchangeName];
}
/* ============ Internal Functions ============ *//**
* Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on AaveLeverageModule
*
*/function_lever(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal{
uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);
uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action);
uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance);
bytesmemory leverCallData =abi.encodeWithSignature(
"lever(address,address,address,uint256,uint256,string,bytes)",
address(strategy.setToken),
strategy.borrowAsset,
strategy.collateralAsset,
borrowUnits,
minReceiveCollateralUnits,
_leverageInfo.exchangeName,
exchangeSettings[_leverageInfo.exchangeName].leverExchangeData
);
invokeManager(address(strategy.leverageModule), leverCallData);
}
/**
* Calculate delever units Invoke delever on AaveLeverageModule.
*/function_delever(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal{
uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply);
uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action);
bytesmemory deleverCallData =abi.encodeWithSignature(
"delever(address,address,address,uint256,uint256,string,bytes)",
address(strategy.setToken),
strategy.collateralAsset,
strategy.borrowAsset,
collateralRebalanceUnits,
minRepayUnits,
_leverageInfo.exchangeName,
exchangeSettings[_leverageInfo.exchangeName].deleverExchangeData
);
invokeManager(address(strategy.leverageModule), deleverCallData);
}
/**
* Invoke deleverToZeroBorrowBalance on AaveLeverageModule.
*/function_deleverToZeroBorrowBalance(
LeverageInfo memory _leverageInfo,
uint256 _chunkRebalanceNotional
)
internal{
// Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance functionuint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional
.preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance))
.preciseDiv(_leverageInfo.action.setTotalSupply);
bytesmemory deleverToZeroBorrowBalanceCallData =abi.encodeWithSignature(
"deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)",
address(strategy.setToken),
strategy.collateralAsset,
strategy.borrowAsset,
maxCollateralRebalanceUnits,
_leverageInfo.exchangeName,
exchangeSettings[_leverageInfo.exchangeName].deleverExchangeData
);
invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData);
}
/**
* Check whether to delever or lever based on the current vs new leverage ratios. Used in the rebalance() and iterateRebalance() functions
*
* return uint256 Calculated notional to trade
* return uint256 Total notional to rebalance over TWAP
*/function_handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internalreturns(uint256, uint256) {
uint256 chunkRebalanceNotional;
uint256 totalRebalanceNotional;
if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) {
(
chunkRebalanceNotional,
totalRebalanceNotional
) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false);
_delever(_leverageInfo, chunkRebalanceNotional);
} else {
(
chunkRebalanceNotional,
totalRebalanceNotional
) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true);
_lever(_leverageInfo, chunkRebalanceNotional);
}
return (chunkRebalanceNotional, totalRebalanceNotional);
}
/**
* Create the leverage info struct to be used in internal functions
*
* return LeverageInfo Struct containing ActionInfo and other data
*/function_getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize, stringmemory _exchangeName) internalviewreturns(LeverageInfo memory) {
// Assume if maxTradeSize is 0, then the exchange is not enabled. This is enforced by addEnabledExchange and updateEnabledExchangerequire(_maxTradeSize >0, "Must be valid exchange");
ActionInfo memory actionInfo = _createActionInfo();
require(actionInfo.setTotalSupply >0, "SetToken must have > 0 supply");
require(actionInfo.collateralBalance >0, "Collateral balance must be > 0");
require(actionInfo.borrowBalance >0, "Borrow balance must exist");
// Get current leverage ratiouint256 currentLeverageRatio = _calculateCurrentLeverageRatio(
actionInfo.collateralValue,
actionInfo.borrowValue
);
return LeverageInfo({
action: actionInfo,
currentLeverageRatio: currentLeverageRatio,
slippageTolerance: _slippageTolerance,
twapMaxTradeSize: _maxTradeSize,
exchangeName: _exchangeName
});
}
/**
* Create the action info struct to be used in internal functions
*
* return ActionInfo Struct containing data used by internal lever and delever functions
*/function_createActionInfo() internalviewvirtualreturns(ActionInfo memory) {
ActionInfo memory rebalanceInfo;
// Calculate prices from chainlink. Chainlink returns prices with 8 decimal places, but we need 36 - underlyingDecimals decimal places.// This is so that when the underlying amount is multiplied by the received price, the collateral valuation is normalized to 36 decimals. // To perform this adjustment, we multiply by 10^(36 - 8 - underlyingDecimals)int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();
rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10** strategy.collateralDecimalAdjustment);
int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();
rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10** strategy.borrowDecimalAdjustment);
rebalanceInfo.collateralBalance = strategy.targetCollateralAToken.balanceOf(address(strategy.setToken));
rebalanceInfo.borrowBalance = strategy.targetBorrowDebtToken.balanceOf(address(strategy.setToken));
rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance);
rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance);
rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply();
return rebalanceInfo;
}
/**
* Validate non-exchange settings in constructor and setters when updating.
*/function_validateNonExchangeSettings(
MethodologySettings memory _methodology,
ExecutionSettings memory _execution,
IncentiveSettings memory _incentive
)
internalvirtualpure{
require (
_methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio >0,
"Must be valid min leverage"
);
require (
_methodology.maxLeverageRatio >= _methodology.targetLeverageRatio,
"Must be valid max leverage"
);
require (
_methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed >0,
"Must be valid recentering speed"
);
require (
_execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(),
"Unutilized leverage must be <100%"
);
require (
_execution.slippageTolerance <= PreciseUnitMath.preciseUnit(),
"Slippage tolerance must be <100%"
);
require (
_incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(),
"Incentivized slippage tolerance must be <100%"
);
require (
_incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio,
"Incentivized leverage ratio must be > max leverage ratio"
);
require (
_methodology.rebalanceInterval >= _execution.twapCooldownPeriod,
"Rebalance interval must be greater than TWAP cooldown period"
);
require (
_execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod,
"TWAP cooldown must be greater than incentivized TWAP cooldown"
);
}
/**
* Validate an ExchangeSettings struct when adding or updating an exchange. Does not validate that twapMaxTradeSize < incentivizedMaxTradeSize since
* it may be useful to disable exchanges for ripcord by setting incentivizedMaxTradeSize to 0.
*/function_validateExchangeSettings(ExchangeSettings memory _settings) internalpure{
require(_settings.twapMaxTradeSize !=0, "Max TWAP trade size must not be 0");
}
/**
* Validate that current leverage is below incentivized leverage ratio and cooldown / rebalance period has elapsed or outsize max/min bounds. Used
* in rebalance() and iterateRebalance() functions
*/function_validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown, uint256 _lastTradeTimestamp) internalview{
require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio");
require(
block.timestamp.sub(_lastTradeTimestamp) > _coolDown
|| _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio
|| _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio,
"Cooldown not elapsed or not valid leverage ratio"
);
}
/**
* Validate that current leverage is above incentivized leverage ratio and incentivized cooldown period has elapsed in ripcord()
*/function_validateRipcord(LeverageInfo memory _leverageInfo, uint256 _lastTradeTimestamp) internalview{
require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio");
// If currently in the midst of a TWAP rebalance, ensure that the cooldown period has elapsedrequire(_lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) <block.timestamp, "TWAP cooldown must have elapsed");
}
/**
* Validate TWAP in the iterateRebalance() function
*/function_validateTWAP() internalview{
require(twapLeverageRatio >0, "Not in TWAP state");
}
/**
* Validate not TWAP in the rebalance() function
*/function_validateNonTWAP() internalview{
require(twapLeverageRatio ==0, "Must call iterate");
}
/**
* Check if price has moved advantageously while in the midst of the TWAP rebalance. This means the current leverage ratio has moved over/under
* the stored TWAP leverage ratio on lever/delever so there is no need to execute a rebalance. Used in iterateRebalance()
*/function_isAdvantageousTWAP(uint256 _currentLeverageRatio) internalviewreturns (bool) {
return (
(twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio)
|| (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio)
);
}
/**
* Calculate the current leverage ratio given a valuation of the collateral and borrow asset, which is calculated as collateral USD valuation / SetToken USD valuation
*
* return uint256 Current leverage ratio
*/function_calculateCurrentLeverageRatio(uint256 _collateralValue,
uint256 _borrowValue
)
internalpurereturns(uint256)
{
return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue));
}
/**
* Calculate the new leverage ratio. The methodology reduces the size of each rebalance by weighting
* the current leverage ratio against the target leverage ratio by the recentering speed percentage. The lower the recentering speed, the slower
* the leverage token will move towards the target leverage each rebalance.
*
* return uint256 New leverage ratio
*/function_calculateNewLeverageRatio(uint256 _currentLeverageRatio) internalviewreturns(uint256) {
// CLRt+1 = max(MINLR, min(MAXLR, CLRt * (1 - RS) + TLR * RS))// a: TLR * RS// b: (1- RS) * CLRt// c: (1- RS) * CLRt + TLR * RS// d: min(MAXLR, CLRt * (1 - RS) + TLR * RS)uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed);
uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio);
uint256 c = a.add(b);
uint256 d = Math.min(c, methodology.maxLeverageRatio);
return Math.max(methodology.minLeverageRatio, d);
}
/**
* Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units.
*
* return uint256 Chunked rebalance notional in collateral units
* return uint256 Total rebalance notional in collateral units
*/function_calculateChunkRebalanceNotional(
LeverageInfo memory _leverageInfo,
uint256 _newLeverageRatio,
bool _isLever
)
internalviewvirtualreturns (uint256, uint256)
{
// Calculate absolute value of difference between new and current leverage ratiouint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio);
uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance);
uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever);
uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize);
return (chunkRebalanceNotional, totalRebalanceNotional);
}
/**
* Calculate the max borrow / repay amount allowed in base units for lever / delever. This is due to overcollateralization requirements on
* assets deposited in lending protocols for borrowing.
*
* For lever, max borrow is calculated as:
* (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals
*
* For delever, max repay is calculated as:
* Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD
*
* Net borrow limit for levering is calculated as:
* The collateral value in USD * Aave collateral factor * (1 - unutilized leverage %)
*
* Net repay limit for delevering is calculated as:
* The collateral value in USD * Aave liquiditon threshold * (1 - unutilized leverage %)
*
* return uint256 Max borrow notional denominated in collateral asset
*/function_calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internalvirtualviewreturns(uint256) {
// Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)
( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));
// Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14// for example ETH has an LTV value of 8000 which represents 80%if (_isLever) {
uint256 netBorrowLimit = _actionInfo.collateralValue
.preciseMul(maxLtvRaw.mul(10**14))
.preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));
return netBorrowLimit
.sub(_actionInfo.borrowValue)
.preciseDiv(_actionInfo.collateralPrice);
} else {
uint256 netRepayLimit = _actionInfo.collateralValue
.preciseMul(liquidationThresholdRaw.mul(10**14))
.preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));
return _actionInfo.collateralBalance
.preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))
.preciseDiv(netRepayLimit);
}
}
/**
* Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price.
* Output is measured to borrow unit decimals.
*
* return uint256 Position units to borrow
*/function_calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internalpurereturns (uint256) {
return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice);
}
/**
* Calculate the min receive units in collateral units for lever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
* Output is measured in collateral asset decimals.
*
* return uint256 Min position units to receive after lever trade
*/function_calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internalpurereturns (uint256) {
return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
}
/**
* Derive the min repay units from collateral units for delever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance
* and pair price (collateral oracle price / borrow oracle price). Output is measured in borrow unit decimals.
*
* return uint256 Min position units to repay in borrow asset
*/function_calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internalvirtualpurereturns (uint256) {
return _collateralRebalanceUnits
.preciseMul(_actionInfo.collateralPrice)
.preciseDiv(_actionInfo.borrowPrice)
.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));
}
/**
* Update last trade timestamp and if chunk rebalance size is less than total rebalance notional, store new leverage ratio to kick off TWAP. Used in
* the engage() and rebalance() functions
*/function_updateRebalanceState(uint256 _chunkRebalanceNotional,
uint256 _totalRebalanceNotional,
uint256 _newLeverageRatio,
stringmemory _exchangeName
)
internal{
_updateLastTradeTimestamp(_exchangeName);
if (_chunkRebalanceNotional < _totalRebalanceNotional) {
twapLeverageRatio = _newLeverageRatio;
}
}
/**
* Update last trade timestamp and if chunk rebalance size is equal to the total rebalance notional, end TWAP by clearing state. This function is used
* in iterateRebalance()
*/function_updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, stringmemory _exchangeName) internal{
_updateLastTradeTimestamp(_exchangeName);
// If the chunk size is equal to the total notional meaning that rebalances are not chunked, then clear TWAP state.if (_chunkRebalanceNotional == _totalRebalanceNotional) {
delete twapLeverageRatio;
}
}
/**
* Update last trade timestamp and if currently in a TWAP, delete the TWAP state. Used in the ripcord() function.
*/function_updateRipcordState(stringmemory _exchangeName) internal{
_updateLastTradeTimestamp(_exchangeName);
// If TWAP leverage ratio is stored, then clear state. This may happen if we are currently in a TWAP rebalance, and the leverage ratio moves above the// incentivized threshold for ripcord.if (twapLeverageRatio >0) {
delete twapLeverageRatio;
}
}
/**
* Update globalLastTradeTimestamp and exchangeLastTradeTimestamp values. This function updates both the exchange-specific and global timestamp so that the
* epoch rebalance can use the global timestamp (since the global timestamp is always equal to the most recently used exchange timestamp). This allows for
* multiple rebalances to occur simultaneously since only the exchange-specific timestamp is checked for non-epoch rebalances.
*/function_updateLastTradeTimestamp(stringmemory _exchangeName) internal{
globalLastTradeTimestamp =block.timestamp;
exchangeSettings[_exchangeName].exchangeLastTradeTimestamp =block.timestamp;
}
/**
* Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required
* incentive quantity, then transfer contract balance instead to prevent reverts.
*
* return uint256 Amount of ETH transferred to caller
*/function_transferEtherRewardToCaller(uint256 _etherReward) internalreturns(uint256) {
uint256 etherToTransfer = _etherReward <address(this).balance ? _etherReward : address(this).balance;
msg.sender.transfer(etherToTransfer);
return etherToTransfer;
}
/**
* Internal function returning the ShouldRebalance enum used in shouldRebalance and shouldRebalanceWithBounds external getter functions
*
* return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action
*/function_shouldRebalance(uint256 _currentLeverageRatio,
uint256 _minLeverageRatio,
uint256 _maxLeverageRatio
)
internalviewreturns(string[] memory, ShouldRebalance[] memory)
{
ShouldRebalance[] memory shouldRebalanceEnums =new ShouldRebalance[](enabledExchanges.length);
for (uint256 i =0; i < enabledExchanges.length; i++) {
// If none of the below conditions are satisfied, then should not rebalance
shouldRebalanceEnums[i] = ShouldRebalance.NONE;
// If above ripcord threshold, then check if incentivized cooldown period has elapsedif (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) {
if (exchangeSettings[enabledExchanges[i]].exchangeLastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) <block.timestamp) {
shouldRebalanceEnums[i] = ShouldRebalance.RIPCORD;
}
} else {
// If TWAP, then check if the cooldown period has elapsedif (twapLeverageRatio >0) {
if (exchangeSettings[enabledExchanges[i]].exchangeLastTradeTimestamp.add(execution.twapCooldownPeriod) <block.timestamp) {
shouldRebalanceEnums[i] = ShouldRebalance.ITERATE_REBALANCE;
}
} else {
// If not TWAP, then check if the rebalance interval has elapsed OR current leverage is above max leverage OR current leverage is below// min leverageif (
block.timestamp.sub(globalLastTradeTimestamp) > methodology.rebalanceInterval
|| _currentLeverageRatio > _maxLeverageRatio
|| _currentLeverageRatio < _minLeverageRatio
) {
shouldRebalanceEnums[i] = ShouldRebalance.REBALANCE;
}
}
}
}
return (enabledExchanges, shouldRebalanceEnums);
}
}
// SPDX-License-Identifier: MITpragmasolidity >=0.6.2 <0.8.0;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in// construction, since the code is only stored at the end of the// constructor execution.uint256 size;
// solhint-disable-next-line no-inline-assemblyassembly { size :=extcodesize(account) }
return size >0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data, stringmemory errorMessage) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value, stringmemory errorMessage) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data, stringmemory errorMessage) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data, stringmemory errorMessage) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytesmemory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function_verifyCallResult(bool success, bytesmemory returndata, stringmemory errorMessage) privatepurereturns(bytesmemory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly// solhint-disable-next-line no-inline-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Contract Source Code
File 4 of 21: AddressArrayUtils.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/pragmasolidity 0.6.10;/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*
* CHANGELOG:
* - 4/27/21: Added validatePairsWithArray methods
*/libraryAddressArrayUtils{
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/functionindexOf(address[] memory A, address a) internalpurereturns (uint256, bool) {
uint256 length = A.length;
for (uint256 i =0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/functioncontains(address[] memory A, address a) internalpurereturns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/functionhasDuplicate(address[] memory A) internalpurereturns(bool) {
require(A.length>0, "A is empty");
for (uint256 i =0; i < A.length-1; i++) {
address current = A[i];
for (uint256 j = i +1; j < A.length; j++) {
if (current == A[j]) {
returntrue;
}
}
}
returnfalse;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/functionremove(address[] memory A, address a)
internalpurereturns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/functionremoveStorage(address[] storage A, address a)
internal{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length-1; // If the array would be empty, the previous line would throw, so no underflow hereif (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/functionpop(address[] memory A, uint256 index)
internalpurereturns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses =newaddress[](length -1);
for (uint256 i =0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index +1; j < length; j++) {
newAddresses[j -1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/functionextend(address[] memory A, address[] memory B) internalpurereturns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses =newaddress[](aLength + bLength);
for (uint256 i =0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j =0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/functionvalidatePairsWithArray(address[] memory A, uint[] memory B) internalpure{
require(A.length== B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/functionvalidatePairsWithArray(address[] memory A, bool[] memory B) internalpure{
require(A.length== B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/functionvalidatePairsWithArray(address[] memory A, string[] memory B) internalpure{
require(A.length== B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/functionvalidatePairsWithArray(address[] memory A, address[] memory B) internalpure{
require(A.length== B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/functionvalidatePairsWithArray(address[] memory A, bytes[] memory B) internalpure{
require(A.length== B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/function_validateLengthAndUniqueness(address[] memory A) internalpure{
require(A.length>0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
Contract Source Code
File 5 of 21: BaseExtension.sol
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/pragmasolidity 0.6.10;import { AddressArrayUtils } from"../lib/AddressArrayUtils.sol";
import { IBaseManager } from"../interfaces/IBaseManager.sol";
/**
* @title BaseExtension
* @author Set Protocol
*
* Abstract class that houses common extension-related state and functions.
*/abstractcontractBaseExtension{
usingAddressArrayUtilsforaddress[];
/* ============ Events ============ */eventCallerStatusUpdated(addressindexed _caller, bool _status);
eventAnyoneCallableUpdated(boolindexed _status);
/* ============ Modifiers ============ *//**
* Throws if the sender is not the SetToken operator
*/modifieronlyOperator() {
require(msg.sender== manager.operator(), "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/modifieronlyMethodologist() {
require(msg.sender== manager.methodologist(), "Must be methodologist");
_;
}
/**
* Throws if caller is a contract, can be used to stop flash loan and sandwich attacks
*/modifieronlyEOA() {
require(msg.sender==tx.origin, "Caller must be EOA Address");
_;
}
/**
* Throws if not allowed caller
*/modifieronlyAllowedCaller(address _caller) {
require(isAllowedCaller(_caller), "Address not permitted to call");
_;
}
/* ============ State Variables ============ */// Instance of manager contract
IBaseManager public manager;
// Boolean indicating if anyone can call functionboolpublic anyoneCallable;
// Mapping of addresses allowed to call functionmapping(address=>bool) public callAllowList;
/* ============ Constructor ============ */constructor(IBaseManager _manager) public{ manager = _manager; }
/* ============ External Functions ============ *//**
* OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions
*
* @param _callers Array of caller addresses to toggle status
* @param _statuses Array of statuses for each caller
*/functionupdateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) externalonlyOperator{
require(_callers.length== _statuses.length, "Array length mismatch");
require(_callers.length>0, "Array length must be > 0");
require(!_callers.hasDuplicate(), "Cannot duplicate callers");
for (uint256 i =0; i < _callers.length; i++) {
address caller = _callers[i];
bool status = _statuses[i];
callAllowList[caller] = status;
emit CallerStatusUpdated(caller, status);
}
}
/**
* OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist
*
* @param _status Boolean indicating whether to allow anyone call
*/functionupdateAnyoneCallable(bool _status) externalonlyOperator{
anyoneCallable = _status;
emit AnyoneCallableUpdated(_status);
}
/* ============ Internal Functions ============ *//**
* Invoke manager to transfer tokens from manager to other contract.
*
* @param _token Token being transferred from manager contract
* @param _amount Amount of token being transferred
*/functioninvokeManagerTransfer(address _token, address _destination, uint256 _amount) internal{
manager.transferTokens(_token, _destination, _amount);
}
/**
* Invoke call from manager
*
* @param _module Module to interact with
* @param _encoded Encoded byte data
*/functioninvokeManager(address _module, bytesmemory _encoded) internal{
manager.interactManager(_module, _encoded);
}
/**
* Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved.
*
* return bool Boolean indicating if allowed caller
*/functionisAllowedCaller(address _caller) internalviewvirtualreturns (bool) {
return anyoneCallable || callAllowList[_caller];
}
}
Contract Source Code
File 6 of 21: Datatypes.sol
// SPDX-License-Identifier: BUSL-1.1pragmasolidity 0.6.10;libraryDataTypes{
structReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in rayuint128 liquidityIndex;
//the current supply rate. Expressed in rayuint128 currentLiquidityRate;
//variable borrow index. Expressed in rayuint128 variableBorrowIndex;
//the current variable borrow rate. Expressed in rayuint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in rayuint128 currentStableBorrowRate;
//timestamp of last updateuint40 lastUpdateTimestamp;
//the id of the reserve. Represents the position in the list of the active reservesuint16 id;
//aToken addressaddress aTokenAddress;
//stableDebtToken addressaddress stableDebtTokenAddress;
//variableDebtToken addressaddress variableDebtTokenAddress;
//address of the interest rate strategyaddress interestRateStrategyAddress;
//the current treasury balance, scaleduint128 accruedToTreasury;
//the outstanding unbacked aTokens minted through the bridging featureuint128 unbacked;
//the outstanding debt borrowed against this asset in isolation modeuint128 isolationModeTotalDebt;
}
structReserveConfigurationMap {
//bit 0-15: LTV//bit 16-31: Liq. threshold//bit 32-47: Liq. bonus//bit 48-55: Decimals//bit 56: reserve is active//bit 57: reserve is frozen//bit 58: borrowing is enabled//bit 59: stable rate borrowing enabled//bit 60: asset is paused//bit 61: borrowing in isolation mode is enabled//bit 62-63: reserved//bit 64-79: reserve factor//bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap//bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap//bit 152-167 liquidation protocol fee//bit 168-175 eMode category//bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled//bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals//bit 252-255 unuseduint256 data;
}
structUserConfigurationMap {
/**
* @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.
* The first bit indicates if an asset is used as collateral by the user, the second whether an
* asset is borrowed by the user.
*/uint256 data;
}
structEModeCategory {
// each eMode category has a custom ltv and liquidation thresholduint16 ltv;
uint16 liquidationThreshold;
uint16 liquidationBonus;
// each eMode category may or may not have a custom oracle to override the individual assets price oraclesaddress priceSource;
string label;
}
enumInterestRateMode {
NONE,
STABLE,
VARIABLE
}
structReserveCache {
uint256 currScaledVariableDebt;
uint256 nextScaledVariableDebt;
uint256 currPrincipalStableDebt;
uint256 currAvgStableBorrowRate;
uint256 currTotalStableDebt;
uint256 nextAvgStableBorrowRate;
uint256 nextTotalStableDebt;
uint256 currLiquidityIndex;
uint256 nextLiquidityIndex;
uint256 currVariableBorrowIndex;
uint256 nextVariableBorrowIndex;
uint256 currLiquidityRate;
uint256 currVariableBorrowRate;
uint256 reserveFactor;
ReserveConfigurationMap reserveConfiguration;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
uint40 reserveLastUpdateTimestamp;
uint40 stableDebtLastUpdateTimestamp;
}
structExecuteLiquidationCallParams {
uint256 reservesCount;
uint256 debtToCover;
address collateralAsset;
address debtAsset;
address user;
bool receiveAToken;
address priceOracle;
uint8 userEModeCategory;
address priceOracleSentinel;
}
structExecuteSupplyParams {
address asset;
uint256 amount;
address onBehalfOf;
uint16 referralCode;
}
structExecuteBorrowParams {
address asset;
address user;
address onBehalfOf;
uint256 amount;
InterestRateMode interestRateMode;
uint16 referralCode;
bool releaseUnderlying;
uint256 maxStableRateBorrowSizePercent;
uint256 reservesCount;
address oracle;
uint8 userEModeCategory;
address priceOracleSentinel;
}
structExecuteRepayParams {
address asset;
uint256 amount;
InterestRateMode interestRateMode;
address onBehalfOf;
bool useATokens;
}
structExecuteWithdrawParams {
address asset;
uint256 amount;
address to;
uint256 reservesCount;
address oracle;
uint8 userEModeCategory;
}
structExecuteSetUserEModeParams {
uint256 reservesCount;
address oracle;
uint8 categoryId;
}
structFinalizeTransferParams {
address asset;
addressfrom;
address to;
uint256 amount;
uint256 balanceFromBefore;
uint256 balanceToBefore;
uint256 reservesCount;
address oracle;
uint8 fromEModeCategory;
}
structFlashloanParams {
address receiverAddress;
address[] assets;
uint256[] amounts;
uint256[] interestRateModes;
address onBehalfOf;
bytes params;
uint16 referralCode;
uint256 flashLoanPremiumToProtocol;
uint256 flashLoanPremiumTotal;
uint256 maxStableRateBorrowSizePercent;
uint256 reservesCount;
address addressesProvider;
uint8 userEModeCategory;
bool isAuthorizedFlashBorrower;
}
structFlashloanSimpleParams {
address receiverAddress;
address asset;
uint256 amount;
bytes params;
uint16 referralCode;
uint256 flashLoanPremiumToProtocol;
uint256 flashLoanPremiumTotal;
}
structFlashLoanRepaymentParams {
uint256 amount;
uint256 totalPremium;
uint256 flashLoanPremiumToProtocol;
address asset;
address receiverAddress;
uint16 referralCode;
}
structCalculateUserAccountDataParams {
UserConfigurationMap userConfig;
uint256 reservesCount;
address user;
address oracle;
uint8 userEModeCategory;
}
structValidateBorrowParams {
ReserveCache reserveCache;
UserConfigurationMap userConfig;
address asset;
address userAddress;
uint256 amount;
InterestRateMode interestRateMode;
uint256 maxStableLoanPercent;
uint256 reservesCount;
address oracle;
uint8 userEModeCategory;
address priceOracleSentinel;
bool isolationModeActive;
address isolationModeCollateralAddress;
uint256 isolationModeDebtCeiling;
}
structValidateLiquidationCallParams {
ReserveCache debtReserveCache;
uint256 totalDebt;
uint256 healthFactor;
address priceOracleSentinel;
}
structCalculateInterestRatesParams {
uint256 unbacked;
uint256 liquidityAdded;
uint256 liquidityTaken;
uint256 totalStableDebt;
uint256 totalVariableDebt;
uint256 averageStableBorrowRate;
uint256 reserveFactor;
address reserve;
address aToken;
}
structInitReserveParams {
address asset;
address aTokenAddress;
address stableDebtAddress;
address variableDebtAddress;
address interestRateStrategyAddress;
uint16 reservesCount;
uint16 maxNumberReserves;
}
}
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/pragmasolidity 0.6.10;pragmaexperimental"ABIEncoderV2";import { ISetToken } from"./ISetToken.sol";
interfaceIBaseManager{
functionsetToken() externalreturns(ISetToken);
functionmethodologist() externalreturns(address);
functionoperator() externalreturns(address);
functioninteractManager(address _module, bytescalldata _encoded) external;
functiontransferTokens(address _token, address _destination, uint256 _amount) external;
}
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address recipient, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` 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.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(address sender, address recipient, uint256 amount) externalreturns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache License, Version 2.0pragmasolidity 0.6.10;pragmaexperimental"ABIEncoderV2";import { IERC20 } from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/interfaceISetTokenisIERC20{
/* ============ Enums ============ */enumModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ *//**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/structPosition {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/structComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address=> ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/structExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */functionaddComponent(address _component) external;
functionremoveComponent(address _component) external;
functioneditDefaultPositionUnit(address _component, int256 _realUnit) external;
functionaddExternalPositionModule(address _component, address _positionModule) external;
functionremoveExternalPositionModule(address _component, address _positionModule) external;
functioneditExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
functioneditExternalPositionData(address _component, address _positionModule, bytescalldata _data) external;
functioninvoke(address _target, uint256 _value, bytescalldata _data) externalreturns(bytesmemory);
functioneditPositionMultiplier(int256 _newMultiplier) external;
functionmint(address _account, uint256 _quantity) external;
functionburn(address _account, uint256 _quantity) external;
functionlock() external;
functionunlock() external;
functionaddModule(address _module) external;
functionremoveModule(address _module) external;
functioninitializeModule() external;
functionsetManager(address _manager) external;
functionmanager() externalviewreturns (address);
functionmoduleStates(address _module) externalviewreturns (ModuleState);
functiongetModules() externalviewreturns (address[] memory);
functiongetDefaultPositionRealUnit(address _component) externalviewreturns(int256);
functiongetExternalPositionRealUnit(address _component, address _positionModule) externalviewreturns(int256);
functiongetComponents() externalviewreturns(address[] memory);
functiongetExternalPositionModules(address _component) externalviewreturns(address[] memory);
functiongetExternalPositionData(address _component, address _positionModule) externalviewreturns(bytesmemory);
functionisExternalPositionModule(address _component, address _module) externalviewreturns(bool);
functionisComponent(address _component) externalviewreturns(bool);
functionpositionMultiplier() externalviewreturns (int256);
functiongetPositions() externalviewreturns (Position[] memory);
functiongetTotalComponentRealUnits(address _component) externalviewreturns(int256);
functionisInitializedModule(address _module) externalviewreturns(bool);
functionisPendingModule(address _module) externalviewreturns(bool);
functionisLocked() externalviewreturns (bool);
}
Contract Source Code
File 16 of 21: Math.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
/**
* @dev Returns the largest of two numbers.
*/functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/functionaverage(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b) / 2 can overflow, so we distributereturn (a /2) + (b /2) + ((a %2+ b %2) /2);
}
}
Contract Source Code
File 17 of 21: PreciseUnitMath.sol
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/pragmasolidity 0.6.10;pragmaexperimentalABIEncoderV2;import { SafeMath } from"@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from"@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/libraryPreciseUnitMath{
usingSafeMathforuint256;
usingSignedSafeMathforint256;
// The number One in precise units.uint256constantinternal PRECISE_UNIT =10**18;
int256constantinternal PRECISE_UNIT_INT =10**18;
// Max unsigned integer valueuint256constantinternal MAX_UINT_256 =type(uint256).max;
// Max and min signed integer valueint256constantinternal MAX_INT_256 =type(int256).max;
int256constantinternal MIN_INT_256 =type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/functionpreciseUnit() internalpurereturns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/functionpreciseUnitInt() internalpurereturns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/functionmaxUint256() internalpurereturns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/functionmaxInt256() internalpurereturns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/functionminInt256() internalpurereturns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/functionpreciseMul(uint256 a, uint256 b) internalpurereturns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/functionpreciseMul(int256 a, int256 b) internalpurereturns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/functionpreciseMulCeil(uint256 a, uint256 b) internalpurereturns (uint256) {
if (a ==0|| b ==0) {
return0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/functionpreciseDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/functionpreciseDiv(int256 a, int256 b) internalpurereturns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/functionpreciseDivCeil(uint256 a, uint256 b) internalpurereturns (uint256) {
require(b !=0, "Cant divide by 0");
return a >0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/functiondivDown(int256 a, int256 b) internalpurereturns (int256) {
require(b !=0, "Cant divide by 0");
require(a != MIN_INT_256 || b !=-1, "Invalid input");
int256 result = a.div(b);
if (a ^ b <0&& a % b !=0) {
result -=1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/functionconservativePreciseMul(int256 a, int256 b) internalpurereturns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/functionconservativePreciseDiv(int256 a, int256 b) internalpurereturns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/functionsafePower(uint256 a,
uint256 pow
)
internalpurereturns (uint256)
{
require(a >0, "Value must be positive");
uint256 result =1;
for (uint256 i =0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
Contract Source Code
File 18 of 21: SafeCast.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/librarySafeCast{
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/functiontoUint128(uint256 value) internalpurereturns (uint128) {
require(value <2**128, "SafeCast: value doesn\'t fit in 128 bits");
returnuint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/functiontoUint64(uint256 value) internalpurereturns (uint64) {
require(value <2**64, "SafeCast: value doesn\'t fit in 64 bits");
returnuint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/functiontoUint32(uint256 value) internalpurereturns (uint32) {
require(value <2**32, "SafeCast: value doesn\'t fit in 32 bits");
returnuint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/functiontoUint16(uint256 value) internalpurereturns (uint16) {
require(value <2**16, "SafeCast: value doesn\'t fit in 16 bits");
returnuint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/functiontoUint8(uint256 value) internalpurereturns (uint8) {
require(value <2**8, "SafeCast: value doesn\'t fit in 8 bits");
returnuint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/functiontoUint256(int256 value) internalpurereturns (uint256) {
require(value >=0, "SafeCast: value must be positive");
returnuint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/functiontoInt128(int256 value) internalpurereturns (int128) {
require(value >=-2**127&& value <2**127, "SafeCast: value doesn\'t fit in 128 bits");
returnint128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/functiontoInt64(int256 value) internalpurereturns (int64) {
require(value >=-2**63&& value <2**63, "SafeCast: value doesn\'t fit in 64 bits");
returnint64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/functiontoInt32(int256 value) internalpurereturns (int32) {
require(value >=-2**31&& value <2**31, "SafeCast: value doesn\'t fit in 32 bits");
returnint32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/functiontoInt16(int256 value) internalpurereturns (int16) {
require(value >=-2**15&& value <2**15, "SafeCast: value doesn\'t fit in 16 bits");
returnint16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/functiontoInt8(int256 value) internalpurereturns (int8) {
require(value >=-2**7&& value <2**7, "SafeCast: value doesn\'t fit in 8 bits");
returnint8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/functiontoInt256(uint256 value) internalpurereturns (int256) {
require(value <2**255, "SafeCast: value doesn't fit in an int256");
returnint256(value);
}
}
Contract Source Code
File 19 of 21: SafeMath.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/librarySafeMath{
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/functiontryAdd(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/functiontrySub(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/functiontryMul(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the// benefit is lost if 'b' is also tested.// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522if (a ==0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/functiontryDiv(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
if (b ==0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/functiontryMod(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
if (b ==0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/functionadd(uint256 a, uint256 b) internalpurereturns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/functionsub(uint256 a, uint256 b) internalpurereturns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/functionmul(uint256 a, uint256 b) internalpurereturns (uint256) {
if (a ==0) return0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functiondiv(uint256 a, uint256 b) internalpurereturns (uint256) {
require(b >0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functionmod(uint256 a, uint256 b) internalpurereturns (uint256) {
require(b >0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/functionsub(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functiondiv(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b >0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functionmod(uint256 a, uint256 b, stringmemory errorMessage) internalpurereturns (uint256) {
require(b >0, errorMessage);
return a % b;
}
}
Contract Source Code
File 20 of 21: SignedSafeMath.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.6.0 <0.8.0;/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/librarySignedSafeMath{
int256constantprivate _INT256_MIN =-2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/functionmul(int256 a, int256 b) internalpurereturns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the// benefit is lost if 'b' is also tested.// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522if (a ==0) {
return0;
}
require(!(a ==-1&& b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/functiondiv(int256 a, int256 b) internalpurereturns (int256) {
require(b !=0, "SignedSafeMath: division by zero");
require(!(b ==-1&& a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/functionsub(int256 a, int256 b) internalpurereturns (int256) {
int256 c = a - b;
require((b >=0&& c <= a) || (b <0&& c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/functionadd(int256 a, int256 b) internalpurereturns (int256) {
int256 c = a + b;
require((b >=0&& c >= a) || (b <0&& c < a), "SignedSafeMath: addition overflow");
return c;
}
}
Contract Source Code
File 21 of 21: StringArrayUtils.sol
/*
Copyright 2021 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/pragmasolidity 0.6.10;/**
* @title StringArrayUtils
* @author Set Protocol
*
* Utility functions to handle String Arrays
*/libraryStringArrayUtils{
/**
* Finds the index of the first occurrence of the given element.
* @param A The input string to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/functionindexOf(string[] memory A, stringmemory a) internalpurereturns (uint256, bool) {
uint256 length = A.length;
for (uint256 i =0; i < length; i++) {
if (keccak256(bytes(A[i])) ==keccak256(bytes(a))) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* @param A The input array to search
* @param a The string to remove
*/functionremoveStorage(string[] storage A, stringmemory a)
internal{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("String not in array.");
} else {
uint256 lastIndex = A.length-1; // If the array would be empty, the previous line would throw, so no underflow hereif (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
}