Skip to main content

SaturationAndGeometricTWAPState

Git Source

Inherits: Initializable, ISaturationAndGeometricTWAPState, OwnableUpgradeable

State Variables

midTermIntervalConfig

uint24 public midTermIntervalConfig;

longTermIntervalConfig

uint24 public longTermIntervalConfig;

satDataGivenPair

mapping(address => Saturation.SaturationStruct) internal satDataGivenPair;

TWAPDataGivenPair

mapping(address => GeometricTWAP.Observations) internal TWAPDataGivenPair;

maxNewPositionSaturationInMAG2

mapping(address => mapping(address => uint256)) maxNewPositionSaturationInMAG2;

lastUsedActiveLiquidityInLAssets

mapping(address => mapping(address => uint256)) lastUsedActiveLiquidityInLAssets;

isPairInitialized

mapping(address => bool) internal isPairInitialized;

Functions

constructor

constructor();

initialize

function initialize(uint24 _midTermIntervalConfig, uint24 _longTermIntervalConfig, address _owner) public initializer;

isInitialized

modifier isInitialized();

_isInitialized

function _isInitialized() internal view;

init

initializes the sat and TWAP struct

initCheck can be removed once the tree structure is fixed

function init(
int16 firstTick
) external;

setNewPositionSaturation

function setNewPositionSaturation(address pair, uint256 maxDesiredSaturationMag2) external;

getTree

function getTree(address pairAddress, bool netDebtX) private view returns (Saturation.Tree storage);

getTreeLeafDetails

function getTreeLeafDetails(
address pairAddress,
bool netDebtX,
uint256 leafIndex
)
external
view
returns (
Saturation.SaturationPair memory saturation,
uint256 currentPenaltyInBorrowLSharesPerSatInQ72,
uint128 totalSatInLAssets,
uint16 highestSetLeaf,
uint16[] memory tranches
);

getTrancheDetails

function getTrancheDetails(
address pairAddress,
bool netDebtX,
int16 tranche
) external view returns (uint16 leaf, Saturation.SaturationPair memory saturation);

getAccount

function getAccount(
address pairAddress,
bool netDebtX,
address accountAddress
) external view returns (Saturation.Account memory);

update

update the borrow position of an account and potentially check (and revert) if the resulting sat is too high

run accruePenalties before running this function

function update(
Validation.InputParams memory inputParams,
address account,
bool skipMinOrMaxTickCheck
) public virtual isInitialized;

Parameters

NameTypeDescription
inputParamsValidation.InputParamscontains the position and pair params, like account borrows/deposits, current price and active liquidity
accountaddressfor which is position is being updated
skipMinOrMaxTickCheckbool

scaleDesiredSaturation

Scales the desired saturation threshold based on changes in Active Liquidity Assets (ALA).

When liquidity is burned from the pool, ALA decreases. Without scaling, this would cause existing positions to appear more saturated (since saturation = borrows / ALA), potentially triggering unwarranted liquidation premiums. This function scales the desired saturation proportionally to ALA changes to maintain the position's relative health. The scaling formula: scaled = lastUsedALA * desiredSat / currentALA

function scaleDesiredSaturation(
address pair,
address account,
uint256 currentALA,
bool capAtPenaltyStart
) internal view returns (uint256 desiredSaturationInMAG2);

Parameters

NameTypeDescription
pairaddressThe address of the pair contract.
accountaddressThe account whose saturation threshold is being scaled.
currentALAuint256The current active liquidity assets in the pool.
capAtPenaltyStartboolIf true, caps the scaled value at START_SATURATION_PENALTY_RATIO_IN_MAG2. Used in _update() to prevent excessive. Set to false in calcSatChangeRatioBips() for accurate premium calculations.

Returns

NameTypeDescription
desiredSaturationInMAG2uint256The scaled desired saturation threshold.

accruePenalties

accrue penalties since last accrual based on all over saturated positions

function accruePenalties(
address account,
uint256 externalLiquidity,
uint256 duration,
uint256 allAssetsDepositL,
uint256 allAssetsBorrowL,
uint256 allSharesBorrowL
) external isInitialized returns (uint112 penaltyInBorrowLShares, uint112 accountPenaltyInBorrowLShares);

Parameters

NameTypeDescription
accountaddress
externalLiquidityuint256Swap liquidity outside this pool
durationuint256since last accrual of penalties
allAssetsDepositLuint256allAsset[DEPOSIT_L]
allAssetsBorrowLuint256allAsset[BORROW_L]
allSharesBorrowLuint256allShares[BORROW_L]

calcSatChangeRatioBips

Calculate the ratio by which the saturation has changed for account.

function calcSatChangeRatioBips(
Validation.InputParams memory inputParams,
uint256 liqSqrtPriceInXInQ72,
uint256 liqSqrtPriceInYInQ72,
address pairAddress,
address account
) external view virtual isInitialized returns (uint256 ratioNetXBips, uint256 ratioNetYBips);

Parameters

NameTypeDescription
inputParamsValidation.InputParamsThe params containing the position of account.
liqSqrtPriceInXInQ72uint256The liquidation price.
liqSqrtPriceInYInQ72uint256
pairAddressaddressThe address of the pair
accountaddressThe account for which we are calculating the saturation change ratio.

Returns

NameTypeDescription
ratioNetXBipsuint256The ratio representing the change in netX saturation for account.
ratioNetYBipsuint256The ratio representing the change in netY saturation for account.

getObservations

function getObservations(
address pairAddress
) external view returns (GeometricTWAP.Observations memory);

configLongTermInterval

Configures the interval of long-term observations.

This function is used to set the long-term interval between observations for the long-term buffer.

function configLongTermInterval(address pairAddress, uint24 _longTermIntervalConfig) external onlyOwner;

Parameters

NameTypeDescription
pairAddressaddressThe address of the pair for which the long-term interval is being configured.
_longTermIntervalConfiguint24The desired duration for each long-term period. The size is set as a factor of the mid-term interval to ensure a sufficient buffer, requiring at least 16 * 12 = 192 seconds per period, resulting in a total of ~25 minutes (192 * 8 = 1536 seconds) for the long-term buffer.

recordObservation

Records a new observation tick value and updates the observation data.

This function is used to record new observation data for the contract. It ensures that the provided tick value is stored appropriately in both mid-term and long-term observations, updates interval counters, and handles tick cumulative values based on the current interval configuration. Ensures that this function is called in chronological order, with increasing timestamps. Returns in case the provided block timestamp is less than or equal to the last recorded timestamp.

function recordObservation(int16 newTick, uint32 timeElapsed) public virtual isInitialized returns (bool);

Parameters

NameTypeDescription
newTickint16The new tick value to be recorded, representing the most recent update of reserveXAssets and reserveYAssets.
timeElapseduint32The time elapsed since the last observation.

Returns

NameTypeDescription
<none>boolbool indicating whether the observation was recorded or not.

getTickRange

Gets the min and max range of tick values from the stored oracle observations.

This function calculates the minimum and maximum tick values among three observed ticks: long-term tick, mid-term tick, and current tick.

function getTickRange(
address pair,
int16 currentTick,
bool includeLongTermTick
) external view virtual returns (int16, int16);

Parameters

NameTypeDescription
pairaddressThe address of the pair for which the tick range is being calculated.
currentTickint16The current (most recent) tick based on the current reserves.
includeLongTermTickboolBoolean value indicating whether to include the long-term tick in the range.

Returns

NameTypeDescription
<none>int16minTick The minimum tick value among the three observed ticks.
<none>int16maxTick The maximum tick value among the three observed ticks.

getLendingStateTickAndCheckpoint

Gets the tick value representing the TWAP since the last lending update and checkpoints the current lending cumulative sum as self.lendingCumulativeSum and the current block timestamp as self.lastLendingTimestamp.

See getLendingStateTick for implementation details which was separated to allow view access without any state updates.

function getLendingStateTickAndCheckpoint(
uint32 timeElapsedSinceUpdate,
uint32 timeElapsedSinceLendingUpdate
) external isInitialized returns (int16 lendingStateTick, uint256 maxSatInWads);

Parameters

NameTypeDescription
timeElapsedSinceUpdateuint32The time elapsed since the last price update.
timeElapsedSinceLendingUpdateuint32The time elapsed since the last lending update.

Returns

NameTypeDescription
lendingStateTickint16The tick value representing the TWAP since the last lending update.
maxSatInWadsuint256

getObservedMidTermTick

Retrieves the mid-term tick value based on the stored observations.

function getObservedMidTermTick(
bool isLongTermBufferInitialized
) external view returns (int16);

Parameters

NameTypeDescription
isLongTermBufferInitializedboolBoolean value which represents whether long-term buffer is filled or not.

Returns

NameTypeDescription
<none>int16midTermTick The mid-term tick value.

getLendingStateTick

Gets the tick value representing the TWAP since the last lending update.

function getLendingStateTick(
int56 newTick,
uint32 timeElapsedSinceUpdate,
uint32 timeElapsedSinceLendingUpdate
) external view returns (int16 lendingStateTick, uint256 maxSatInWads);

Parameters

NameTypeDescription
newTickint56The new tick value to be recorded, representing the most recent update of reserveXAssets and reserveYAssets.
timeElapsedSinceUpdateuint32The time elapsed since the last price update.
timeElapsedSinceLendingUpdateuint32The time elapsed since the last lending update.

Returns

NameTypeDescription
lendingStateTickint16The tick value representing the TWAP since the last lending update.
maxSatInWadsuint256The maximum saturation in WADs.

liquidationCheckHardPremiums

function liquidationCheckHardPremiums(
Validation.InputParams memory inputParams,
address borrower,
Liquidation.HardLiquidationParams memory hardLiquidationParams,
uint256 actualRepaidLiquidityAssets
) external view returns (bool badDebt);