diff --git a/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md b/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md index ebb7b742..9ce8bce5 100644 --- a/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md +++ b/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md @@ -1,59 +1,59 @@ # AmmalgamPair -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/AmmalgamPair.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/AmmalgamPair.sol) **Inherits:** [IAmmalgamPair](/docs/developer-guide/contracts/interfaces/IAmmalgamPair.sol/interface.IAmmalgamPair.md), [TokenController](/docs/developer-guide/contracts/tokens/TokenController.sol/contract.TokenController.md) ## State Variables -### BUFFER +### ZERO_DEPOSIT_DUE_TO_NETTING ```solidity -uint256 private constant BUFFER = 95; +uint256 private constant ZERO_DEPOSIT_DUE_TO_NETTING = 0; ``` -### INVERSE_BUFFER +### UNLOCKED ```solidity -uint256 private constant INVERSE_BUFFER = 5; +uint256 private constant UNLOCKED = 0; ``` -### INVERSE_BUFFER_SQUARED +### LOCKED ```solidity -uint256 private constant INVERSE_BUFFER_SQUARED = 25; +uint256 private constant LOCKED = 1; ``` -### BUFFER_NUMERATOR +### locked ```solidity -uint256 private constant BUFFER_NUMERATOR = 100; +uint256 private transient locked; ``` -### unlocked +## Functions +### lock + ```solidity -uint256 private unlocked = 1; +modifier lock(); ``` - -## Functions ### _lock ```solidity -function _lock() private view; +function _lock() private; ``` -### lock +### _unlock ```solidity -modifier lock(); +function _unlock() private; ``` ### mint @@ -62,7 +62,7 @@ modifier lock(); ```solidity function mint( address to -) external lock returns (uint256 liquidityShares); +) external virtual lock returns (uint256 liquidityShares); ``` ### burn @@ -71,21 +71,22 @@ function mint( ```solidity function burn( address to -) external lock returns (uint256 amountXAssets, uint256 amountYAssets); +) external virtual lock returns (uint256 amountXAssets, uint256 amountYAssets); ``` ### swap ```solidity -function swap(uint256 amountXOut, uint256 amountYOut, address to, bytes calldata data) external lock; +function swap(uint256 amountXOut, uint256 amountYOut, address to, bytes calldata data) external virtual lock; ``` ### calculateAmountIn helper method to calculate amountIn for swap -*Adds jump, saves on runtime size* +*Adds jump, saves on runtime size. Must check that `reserve > amountOut`, +which happens in swap where function is called.* ```solidity @@ -140,16 +141,20 @@ function calculateBalanceAfterFees( helper method to calculate balance adjustment for missing assets -*When assets are depleted, we should multiply (reserve - missing) by +*For swap, when assets are depleted, we should multiply (reserve - missing) by BUFFER_NUMERATOR / INVERSE_BUFFER, but instead of divide here, we multiply the other side of the K comparison, see `calculateBalanceAfterFees` where we multiply by -INVERSE_BUFFER.* +INVERSE_BUFFER. +For updateObservation, different scaled `buffer` and `bufferNumerator` values +are supplied so the adjusted reserve reflects observation-specific logic.* ```solidity function calculateReserveAdjustmentsForMissingAssets( uint256 reserve, - uint256 missing + uint256 missing, + uint256 buffer, + uint256 bufferNumerator ) private pure returns (uint256 reserveAdjustment); ``` **Parameters** @@ -158,28 +163,23 @@ function calculateReserveAdjustmentsForMissingAssets( |----|----|-----------| |`reserve`|`uint256`|the starting reserve| |`missing`|`uint256`|the missing assets, zero if deposits > borrows of X or Y| +|`buffer`|`uint256`| Scaling factor applied to the reserve for the depletion comparison.| +|`bufferNumerator`|`uint256`| Scaling factor applied to the missing amount for the comparison and for computing the depleted-case adjusted reserve.| +**Returns** -### deposit +|Name|Type|Description| +|----|----|-----------| +|`reserveAdjustment`|`uint256`|The adjusted reserve value used for swap or updateObservation depends on the buffer, bufferNumerator to be passed in.| -```solidity -function deposit( - address to -) external lock; -``` - -### updateDepositShares +### deposit ```solidity -function updateDepositShares( - uint256 depositedTokenType, - uint256 amountAssets, - uint256 reserveAssets, - uint256 _missingAssets, +function deposit( address to -) private returns (uint256 adjustReserves); +) external virtual lock; ``` ### withdraw @@ -190,7 +190,7 @@ withdraw X and/or Y ```solidity function withdraw( address to -) external lock; +) external virtual lock; ``` ### updateWithdrawShares @@ -208,7 +208,7 @@ function updateWithdrawShares( ```solidity -function borrow(address to, uint256 amountXAssets, uint256 amountYAssets, bytes calldata data) external lock; +function borrow(address to, uint256 amountXAssets, uint256 amountYAssets, bytes calldata data) external virtual lock; ``` ### borrowHelper @@ -216,12 +216,11 @@ function borrow(address to, uint256 amountXAssets, uint256 amountYAssets, bytes ```solidity function borrowHelper( - Validation.VerifyMaxBorrowXYParams memory maxBorrowParams, address to, uint256 amountAssets, uint256 reserve, - uint256 borrowedTokenType, - uint256 depositedTokenType + uint256 depositedTokenType, + uint256 borrowedTokenType ) private returns (uint256 amountShares); ``` @@ -245,7 +244,7 @@ function borrowLiquidity( address to, uint256 borrowAmountLAssets, bytes calldata data -) external lock returns (uint256, uint256); +) external virtual lock returns (uint256 borrowedLXAssets, uint256 borrowedLYAssets); ``` ### repay @@ -254,7 +253,7 @@ function borrowLiquidity( ```solidity function repay( address onBehalfOf -) external lock returns (uint256 repayXInXAssets, uint256 repayYInYAssets); +) external virtual lock returns (uint256 repayXInXAssets, uint256 repayYInYAssets); ``` ### _repay @@ -275,10 +274,8 @@ function _repay( function repayHelper( address onBehalfOf, uint256 repayInAssets, - uint256 reserveInAssets, - uint256 missingInAssets, uint256 borrowTokenType -) private returns (uint256 adjustedReservesInAssets, uint256 netRepayInAssets); +) private returns (uint256 actualRepayInAssets); ``` ### repayLiquidity @@ -287,7 +284,7 @@ function repayHelper( ```solidity function repayLiquidity( address onBehalfOf -) external lock returns (uint256 repaidLXInXAssets, uint256 repaidLYInYAssets, uint256 repayLiquidityAssets); +) external virtual lock returns (uint256 repaidLXInXAssets, uint256 repaidLYInYAssets, uint256 repayLiquidityAssets); ``` ### _repayLiquidity @@ -316,7 +313,7 @@ function liquidate( uint256 repayXInXAssets, uint256 repayYInYAssets, uint256 liquidationType -) external lock; +) external virtual lock; ``` **Parameters** @@ -331,7 +328,7 @@ function liquidate( |`repayLYInYAssets`|`uint256`|The amount of LY to be repaid by the liquidator.| |`repayXInXAssets`|`uint256`|The amount of X to be repaid by the liquidator.| |`repayYInYAssets`|`uint256`|The amount of Y to be repaid by the liquidator.| -|`liquidationType`|`uint256`|The type of liquidation to be performed: HARD, SOFT, LEVERAGE| +|`liquidationType`|`uint256`|The type of liquidation to be performed: HARD, SATURATION, LEVERAGE| ### liquidateHard @@ -371,13 +368,13 @@ function repayCallback(uint256 repayXAssets, uint256 repayYAssets) private; function verifyRepay(uint256 actualX, uint256 expectedX, uint256 actualY, uint256 expectedY) private pure; ``` -### liquidateSoft +### resetSaturation Liquidation based on change of saturation because of time. ```solidity -function liquidateSoft( +function resetSaturation( Validation.InputParams memory inputParams, address borrower, address to, @@ -423,16 +420,17 @@ function liquidateLeverage( |`repayL`|`bool`|Flag indicating whether the repay by the liquidator is L xor X+Y.| -### liquidationTransferAll +### finalizeLiquidation ```solidity -function liquidationTransferAll( +function finalizeLiquidation( address borrower, address to, uint256 depositLToBeTransferredInLAssets, uint256 depositXToBeTransferredInXAssets, - uint256 depositYToBeTransferredInYAssets + uint256 depositYToBeTransferredInYAssets, + bool isBadDebt ) private; ``` @@ -467,35 +465,14 @@ function liquidationTransfer( ```solidity function skim( address to -) external lock; +) external virtual lock; ``` ### sync ```solidity -function sync() external lock; -``` - -### _sync - - -```solidity -function _sync() private; -``` - -### depletionReserveAdjustmentWhenAssetIsAdded - -*When assets are depleted, a user can deposit the depleted asset and earn additional deposit credit for moving -the swap curve from the adjusted amount due to assets being depleted to the original curve.* - - -```solidity -function depletionReserveAdjustmentWhenAssetIsAdded( - uint256 amountAssets, - uint256 reserveAssets, - uint256 _missingAssets -) private pure returns (uint256 adjustReserves_); +function sync() external virtual lock; ``` ### accrueSaturationPenaltiesAndInterest @@ -503,20 +480,14 @@ function depletionReserveAdjustmentWhenAssetIsAdded( ```solidity function accrueSaturationPenaltiesAndInterest( - address affectedAccount + address affectedAccount, + uint256 minimumTimeBeforeUpdate ) private returns (uint256 _reserveXAssets, uint256 _reserveYAssets, uint256 balanceXAssets, uint256 balanceYAssets); ``` ### updateObservation -```solidity -function updateObservation(uint256 _reserveXAssets, uint256 _reserveYAssets) private; -``` - -### updateObservation - - ```solidity function updateObservation( uint256 _reserveXAssets, @@ -530,14 +501,14 @@ function updateObservation( ```solidity -function validateOnUpdate(address validate, address update, bool isBorrow) external; +function validateOnUpdate(address validate, address update, bool alwaysUpdate) public virtual; ``` ### validateSolvency ```solidity -function validateSolvency(address validate, bool isBorrow) private; +function validateSolvency(address validate, bool alwaysUpdate) private; ``` ### getInputParamsAndUpdateSaturation @@ -554,7 +525,7 @@ function getInputParamsAndUpdateSaturation(address toUpdate, bool alwaysUpdate) function getInputParams( address toCheck, bool includeLongTermPrice -) internal view returns (Validation.InputParams memory inputParams, bool hasBorrow); +) internal view returns (Validation.InputParams memory inputParams); ``` ### transferAssets @@ -564,20 +535,44 @@ function getInputParams( function transferAssets(address to, uint256 amountXAssets, uint256 amountYAssets) private; ``` -### calcMinLiquidityConsideringDepletion +### calculateMinimumLiquidityAssets ```solidity -function calcMinLiquidityConsideringDepletion( +function calculateMinimumLiquidityAssets( uint256 amountXAssets, uint256 amountYAssets, uint256 _reserveXAssets, uint256 _reserveYAssets, - uint256 activeLiquidityAssets, - uint256 depositLiquidityAssets, - uint256 depositLiquidityShares, + uint256 liquidityAssetsNumerator, bool isRoundingUp -) private view returns (uint256 liquidityAssets, uint256 liquidityShares); +) private pure returns (uint256 liquidityAssets); +``` + +### checkMaxBorrowForLiquidity + + +```solidity +function checkMaxBorrowForLiquidity( + uint256 reserveX, + uint256 reserveY, + uint256 totalDepositedLAssets, + uint256 totalBorrowedLAssets, + uint256 newBorrowLAssets +) private view; +``` + +### checkMaxBorrow + + +```solidity +function checkMaxBorrow( + uint256 depositedAssets, + uint256 borrowedAssets, + uint256 reserve, + uint256 totalDepositedLAssets, + uint256 totalBorrowedLiquidityAssets +) private pure; ``` ## Errors @@ -635,9 +630,3 @@ error K(); error InsufficientRepayLiquidity(); ``` -### Overflow - -```solidity -error Overflow(); -``` - diff --git a/docs/developer-guide/contracts/SaturationAndGeometricTWAPState.sol/contract.SaturationAndGeometricTWAPState.md b/docs/developer-guide/contracts/SaturationAndGeometricTWAPState.sol/contract.SaturationAndGeometricTWAPState.md index f6ffe5d1..1a7c1daa 100644 --- a/docs/developer-guide/contracts/SaturationAndGeometricTWAPState.sol/contract.SaturationAndGeometricTWAPState.md +++ b/docs/developer-guide/contracts/SaturationAndGeometricTWAPState.sol/contract.SaturationAndGeometricTWAPState.md @@ -1,5 +1,5 @@ # SaturationAndGeometricTWAPState -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/SaturationAndGeometricTWAPState.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/SaturationAndGeometricTWAPState.sol) **Inherits:** [ISaturationAndGeometricTWAPState](/docs/developer-guide/contracts/interfaces/ISaturationAndGeometricTWAPState.sol/interface.ISaturationAndGeometricTWAPState.md), Ownable @@ -41,6 +41,13 @@ mapping(address => mapping(address => uint256)) maxNewPositionSaturationInMAG2; ``` +### lastUsedActiveLiquidityInLAssets + +```solidity +mapping(address => mapping(address => uint256)) lastUsedActiveLiquidityInLAssets; +``` + + ### isPairInitialized ```solidity @@ -107,11 +114,11 @@ function getNewPositionSaturation( function getTree(address pairAddress, bool netDebtX) private view returns (Saturation.Tree storage); ``` -### getLeafDetails +### getTreeLeafDetails ```solidity -function getLeafDetails( +function getTreeLeafDetails( address pairAddress, bool netDebtX, uint256 leafIndex @@ -121,17 +128,12 @@ function getLeafDetails( returns ( Saturation.SaturationPair memory saturation, uint256 currentPenaltyInBorrowLSharesPerSatInQ72, + uint128 totalSatInLAssets, + uint16 highestSetLeaf, uint16[] memory tranches ); ``` -### getTreeDetails - - -```solidity -function getTreeDetails(address pairAddress, bool netDebtX) external view returns (uint16, uint128); -``` - ### getTrancheDetails @@ -156,13 +158,19 @@ function getAccount( ### update -update the borrow position of an account and potentially check (and revert) if the resulting sat is too high +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* ```solidity -function update(Validation.InputParams memory inputParams, address account) external virtual; +function update( + Validation.InputParams memory inputParams, + address account, + uint256 fragileLiquidityAssets, + bool skipMinOrMaxTickCheck +) external virtual; ``` **Parameters** @@ -170,14 +178,56 @@ function update(Validation.InputParams memory inputParams, address account) exte |----|----|-----------| |`inputParams`|`Validation.InputParams`| contains the position and pair params, like account borrows/deposits, current price and active liquidity| |`account`|`address`| for which is position is being updated| +|`fragileLiquidityAssets`|`uint256`| the amount of fragile liquidity that should be excluded from active liquidity assets since it may need to be liquidated.| +|`skipMinOrMaxTickCheck`|`bool`|| ### _update ```solidity -function _update(Validation.InputParams memory inputParams, address account) internal isInitialized; +function _update( + Validation.InputParams memory inputParams, + address account, + uint256 fragileLiquidityAssets, + bool skipMinOrMaxTickCheck +) internal isInitialized; +``` + +### 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* + + +```solidity +function scaleDesiredSaturation( + address pair, + address account, + uint256 currentALA, + bool capAtPenaltyStart +) internal view returns (uint256 desiredSaturationInMAG2); ``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`pair`|`address`|The address of the pair contract.| +|`account`|`address`|The account whose saturation threshold is being scaled.| +|`currentALA`|`uint256`|The current active liquidity assets in the pool.| +|`capAtPenaltyStart`|`bool`|If `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** + +|Name|Type|Description| +|----|----|-----------| +|`desiredSaturationInMAG2`|`uint256`|The scaled desired saturation threshold.| + ### accruePenalties @@ -278,7 +328,7 @@ provided block timestamp is less than or equal to the last recorded timestamp.* ```solidity -function recordObservation(int16 newTick, uint32 timeElapsed) external isInitialized returns (bool); +function recordObservation(int16 newTick, uint32 timeElapsed) external virtual isInitialized returns (bool); ``` **Parameters** @@ -294,6 +344,13 @@ function recordObservation(int16 newTick, uint32 timeElapsed) external isInitial |``|`bool`|bool indicating whether the observation was recorded or not.| +### _recordObservation + + +```solidity +function _recordObservation(int16 newTick, uint32 timeElapsed) internal isInitialized returns (bool); +``` + ### getTickRange Gets the min and max range of tick values from the stored oracle observations. @@ -390,30 +447,6 @@ function getObservedMidTermTick( |``|`int16`|midTermTick The mid-term tick value.| -### boundTick - -*The function ensures that `newTick` stays within the bounds -determined by `lastTick` and a dynamically calculated factor.* - - -```solidity -function boundTick( - int16 newTick -) external view returns (int16); -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`newTick`|`int16`|The proposed new tick value to be adjusted within valid bounds.| - -**Returns** - -|Name|Type|Description| -|----|----|-----------| -|``|`int16`|The adjusted tick value constrained within the allowable range.| - - ### getLendingStateTick Gets the tick value representing the TWAP since the last lending update. diff --git a/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.AmmalgamFactory.md b/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.AmmalgamFactory.md index 266d4d6f..de7709e3 100644 --- a/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.AmmalgamFactory.md +++ b/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.AmmalgamFactory.md @@ -1,29 +1,22 @@ # AmmalgamFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/factories/AmmalgamFactory.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/factories/AmmalgamFactory.sol) **Inherits:** [IAmmalgamFactory](/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IAmmalgamFactory.md) ## State Variables -### tokenFactory +### pairBeacon ```solidity -address public immutable tokenFactory; +IBeacon public immutable override pairBeacon; ``` -### pairFactory +### hookRegistry ```solidity -address public immutable pairFactory; -``` - - -### pluginRegistry - -```solidity -address public immutable pluginRegistry; +IHookRegistry public immutable hookRegistry; ``` @@ -48,6 +41,34 @@ ISaturationAndGeometricTWAPState public immutable saturationAndGeometricTWAPStat ``` +### liquidityTokenFactory + +```solidity +ITokenFactory private immutable liquidityTokenFactory; +``` + + +### depositTokenFactory + +```solidity +ITokenFactory private immutable depositTokenFactory; +``` + + +### debtTokenFactory + +```solidity +ITokenFactory private immutable debtTokenFactory; +``` + + +### liquidityDebtTokenFactory + +```solidity +ITokenFactory private immutable liquidityDebtTokenFactory; +``` + + ### config ```solidity @@ -83,10 +104,13 @@ modifier onlyFeeToSetter(); ```solidity constructor( address _feeToSetter, - address _tokenFactory, - address _pairFactory, - address _pluginRegistry, - address _saturationAndGeometricTWAPState + IBeacon _pairBeacon, + IHookRegistry _hookRegistry, + ISaturationAndGeometricTWAPState _saturationAndGeometricTWAPState, + ITokenFactory _liquidityTokenFactory, + ITokenFactory _depositTokenFactory, + ITokenFactory _borrowTokenFactory, + ITokenFactory _liquidityDebtTokenFactory ); ``` @@ -118,6 +142,17 @@ function getConfig() private view returns (IFactoryCallback.TokenFactoryConfig m function generateTokensWithinFactory() external returns (IERC20, IERC20, IAmmalgamERC20[6] memory); ``` +### createAllTokens + + +```solidity +function createAllTokens( + address pair, + address tokenX, + address tokenY +) private returns (IAmmalgamERC20[6] memory tokens); +``` + ### setFeeTo @@ -136,6 +171,26 @@ function setFeeToSetter( ) external onlyFeeToSetter; ``` +### createPairFromSalt + + +```solidity +function createPairFromSalt( + bytes32 salt +) private returns (address pair); +``` + +### createToken + + +```solidity +function createToken( + address tokenFactory, + address asset, + ERC20BaseConfig memory _config +) private returns (IAmmalgamERC20); +``` + ## Events ### NewFeeTo @@ -204,3 +259,9 @@ error Forbidden(); error NewTokensFailed(); ``` +### ERC20TokenFactoryFailed + +```solidity +error ERC20TokenFactoryFailed(); +``` + diff --git a/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.PairFactory.md b/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.PairFactory.md deleted file mode 100644 index 798d080c..00000000 --- a/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.PairFactory.md +++ /dev/null @@ -1,19 +0,0 @@ -# PairFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/factories/AmmalgamFactory.sol) - -**Inherits:** -[IPairFactory](/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IPairFactory.md) - -Implementation of the for the IPairFactory interface. - - -## Functions -### createPair - - -```solidity -function createPair( - bytes32 salt -) external returns (address pair); -``` - diff --git a/docs/developer-guide/contracts/factories/ERC20DebtLiquidityTokenFactory.sol/contract.ERC20DebtLiquidityTokenFactory.md b/docs/developer-guide/contracts/factories/ERC20DebtLiquidityTokenFactory.sol/contract.ERC20DebtLiquidityTokenFactory.md index 28836404..5085eeb2 100644 --- a/docs/developer-guide/contracts/factories/ERC20DebtLiquidityTokenFactory.sol/contract.ERC20DebtLiquidityTokenFactory.md +++ b/docs/developer-guide/contracts/factories/ERC20DebtLiquidityTokenFactory.sol/contract.ERC20DebtLiquidityTokenFactory.md @@ -1,5 +1,5 @@ # ERC20DebtLiquidityTokenFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/factories/ERC20DebtLiquidityTokenFactory.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/factories/ERC20DebtLiquidityTokenFactory.sol) **Inherits:** [ITokenFactory](/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md) diff --git a/docs/developer-guide/contracts/factories/ERC20LiquidityTokenFactory.sol/contract.ERC20LiquidityTokenFactory.md b/docs/developer-guide/contracts/factories/ERC20LiquidityTokenFactory.sol/contract.ERC20LiquidityTokenFactory.md index 47bf72a5..2dfaf49c 100644 --- a/docs/developer-guide/contracts/factories/ERC20LiquidityTokenFactory.sol/contract.ERC20LiquidityTokenFactory.md +++ b/docs/developer-guide/contracts/factories/ERC20LiquidityTokenFactory.sol/contract.ERC20LiquidityTokenFactory.md @@ -1,5 +1,5 @@ # ERC20LiquidityTokenFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/factories/ERC20LiquidityTokenFactory.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/factories/ERC20LiquidityTokenFactory.sol) **Inherits:** [ITokenFactory](/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md) diff --git a/docs/developer-guide/contracts/factories/ERC4626DebtTokenFactory.sol/contract.ERC4626DebtTokenFactory.md b/docs/developer-guide/contracts/factories/ERC4626DebtTokenFactory.sol/contract.ERC4626DebtTokenFactory.md index bd914638..1c5af825 100644 --- a/docs/developer-guide/contracts/factories/ERC4626DebtTokenFactory.sol/contract.ERC4626DebtTokenFactory.md +++ b/docs/developer-guide/contracts/factories/ERC4626DebtTokenFactory.sol/contract.ERC4626DebtTokenFactory.md @@ -1,5 +1,5 @@ # ERC4626DebtTokenFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/factories/ERC4626DebtTokenFactory.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/factories/ERC4626DebtTokenFactory.sol) **Inherits:** [ITokenFactory](/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md) diff --git a/docs/developer-guide/contracts/factories/ERC4626DepositTokenFactory.sol/contract.ERC4626DepositTokenFactory.md b/docs/developer-guide/contracts/factories/ERC4626DepositTokenFactory.sol/contract.ERC4626DepositTokenFactory.md index 14eb8d4e..01e6a525 100644 --- a/docs/developer-guide/contracts/factories/ERC4626DepositTokenFactory.sol/contract.ERC4626DepositTokenFactory.md +++ b/docs/developer-guide/contracts/factories/ERC4626DepositTokenFactory.sol/contract.ERC4626DepositTokenFactory.md @@ -1,5 +1,5 @@ # ERC4626DepositTokenFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/factories/ERC4626DepositTokenFactory.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/factories/ERC4626DepositTokenFactory.sol) **Inherits:** [ITokenFactory](/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md) diff --git a/docs/developer-guide/contracts/factories/NewTokensFactory.sol/contract.NewTokensFactory.md b/docs/developer-guide/contracts/factories/NewTokensFactory.sol/contract.NewTokensFactory.md deleted file mode 100644 index 6c186556..00000000 --- a/docs/developer-guide/contracts/factories/NewTokensFactory.sol/contract.NewTokensFactory.md +++ /dev/null @@ -1,79 +0,0 @@ -# NewTokensFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/factories/NewTokensFactory.sol) - -**Inherits:** -[INewTokensFactory](/docs/developer-guide/contracts/interfaces/factories/INewTokensFactory.sol/interface.INewTokensFactory.md) - - -## State Variables -### liquidityTokenFactory - -```solidity -ITokenFactory private immutable liquidityTokenFactory; -``` - - -### depositTokenFactory - -```solidity -ITokenFactory private immutable depositTokenFactory; -``` - - -### debtTokenFactory - -```solidity -ITokenFactory private immutable debtTokenFactory; -``` - - -### liquidityDebtTokenFactory - -```solidity -ITokenFactory private immutable liquidityDebtTokenFactory; -``` - - -## Functions -### constructor - - -```solidity -constructor( - ITokenFactory _liquidityTokenFactory, - ITokenFactory _depositTokenFactory, - ITokenFactory _borrowTokenFactory, - ITokenFactory _liquidityDebtTokenFactory -); -``` - -### createAllTokens - - -```solidity -function createAllTokens( - address pair, - address pluginRegistry, - address tokenX, - address tokenY -) external returns (IAmmalgamERC20[6] memory tokens); -``` - -### createToken - - -```solidity -function createToken( - address tokenFactory, - address asset, - ERC20BaseConfig memory config -) private returns (IAmmalgamERC20); -``` - -## Errors -### ERC20TokenFactoryFailed - -```solidity -error ERC20TokenFactoryFailed(); -``` - diff --git a/docs/developer-guide/contracts/interfaces/IAmmalgamPair.sol/interface.IAmmalgamPair.md b/docs/developer-guide/contracts/interfaces/IAmmalgamPair.sol/interface.IAmmalgamPair.md index 7cc0206f..28f93ac8 100644 --- a/docs/developer-guide/contracts/interfaces/IAmmalgamPair.sol/interface.IAmmalgamPair.md +++ b/docs/developer-guide/contracts/interfaces/IAmmalgamPair.sol/interface.IAmmalgamPair.md @@ -1,8 +1,8 @@ # IAmmalgamPair -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/IAmmalgamPair.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/IAmmalgamPair.sol) **Inherits:** -[ITokenController](/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md), [ITransferValidator](/docs/developer-guide/contracts/interfaces/callbacks/ITransferValidator.sol/interface.ITransferValidator.md) +[ITransferValidator](/docs/developer-guide/contracts/interfaces/callbacks/ITransferValidator.sol/interface.ITransferValidator.md) ## Functions @@ -152,7 +152,7 @@ Handles liquidity borrowing from the contract. ```solidity function borrowLiquidity( address to, - uint256 borrowAmountLShares, + uint256 borrowAmountLAssets, bytes calldata data ) external returns (uint256, uint256); ``` @@ -161,7 +161,7 @@ function borrowLiquidity( |Name|Type|Description| |----|----|-----------| |`to`|`address`|| -|`borrowAmountLShares`|`uint256`|Amount of liquidity to borrow.| +|`borrowAmountLAssets`|`uint256`|Amount of liquidity to borrow.| |`data`|`bytes`|Call data to be sent to external contract if flash loan is desired.| **Returns** @@ -287,7 +287,7 @@ function liquidate( |`repayLY`|`uint256`|The amount of L tokens repaid in Y.| |`repayX`|`uint256`|The amount of X tokens repaid.| |`repayY`|`uint256`|The amount of Y tokens repaid.| -|`liquidationType`|`uint256`|The type of liquidation to be performed: HARD, SOFT, LEVERAGE| +|`liquidationType`|`uint256`|The type of liquidation to be performed: HARD, SATURATION, LEVERAGE| ## Events @@ -349,5 +349,5 @@ event Liquidate( |`repayLY`|`uint256`|The amount of L tokens repaid in Y.| |`repayX`|`uint256`|The amount of X tokens repaid.| |`repayY`|`uint256`|The amount of Y tokens repaid.| -|`liquidationType`|`uint256`|The type of liquidation to be performed: HARD, SOFT, LEVERAGE| +|`liquidationType`|`uint256`|The type of liquidation to be performed: HARD, SATURATION, LEVERAGE| diff --git a/docs/developer-guide/contracts/interfaces/ISaturationAndGeometricTWAPState.sol/interface.ISaturationAndGeometricTWAPState.md b/docs/developer-guide/contracts/interfaces/ISaturationAndGeometricTWAPState.sol/interface.ISaturationAndGeometricTWAPState.md index 9ae04a6f..d2b43139 100644 --- a/docs/developer-guide/contracts/interfaces/ISaturationAndGeometricTWAPState.sol/interface.ISaturationAndGeometricTWAPState.md +++ b/docs/developer-guide/contracts/interfaces/ISaturationAndGeometricTWAPState.sol/interface.ISaturationAndGeometricTWAPState.md @@ -1,8 +1,26 @@ # ISaturationAndGeometricTWAPState -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/ISaturationAndGeometricTWAPState.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/ISaturationAndGeometricTWAPState.sol) ## Functions +### midTermIntervalConfig + +Exposes the public getter for the configured mid-term interval (in seconds) + + +```solidity +function midTermIntervalConfig() external view returns (uint24); +``` + +### longTermIntervalConfig + +Exposes the public getter for the configured long-term interval (in seconds) + + +```solidity +function longTermIntervalConfig() external view returns (uint24); +``` + ### init initializes the sat (allocating storage for all nodes) and twap structs @@ -21,11 +39,13 @@ function init( function setNewPositionSaturation(address pair, uint256 maxDesiredSaturationInMAG2) external; ``` -### getLeafDetails +### getTreeLeafDetails + +get the details of a specific to the tree and leaf in the saturation state. ```solidity -function getLeafDetails( +function getTreeLeafDetails( address pairAddress, bool netDebtX, uint256 leaf @@ -35,16 +55,29 @@ function getLeafDetails( returns ( Saturation.SaturationPair memory saturation, uint256 currentPenaltyInBorrowLSharesPerSatInQ72, + uint128 totalSatInLAssets, + uint16 highestSetLeaf, uint16[] memory tranches ); ``` +**Parameters** -### getTreeDetails +|Name|Type|Description| +|----|----|-----------| +|`pairAddress`|`address`| the pair for which the tree is being queried| +|`netDebtX`|`bool`| whether to query the netDebtX or netDebtY side of the tree| +|`leaf`|`uint256`| the leaf index to query, you can use zero if you don't need the leaf details| +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`saturation`|`Saturation.SaturationPair`| the saturation details for the specified leaf| +|`currentPenaltyInBorrowLSharesPerSatInQ72`|`uint256`| the current penalty per sat in borrowL shares for the specified leaf| +|`totalSatInLAssets`|`uint128`| the total saturation in L assets for the specified tree| +|`highestSetLeaf`|`uint16`| the highest set leaf index for the specified tree| +|`tranches`|`uint16[]`| the list of tranches set in the specified leaf| -```solidity -function getTreeDetails(address pairAddress, bool netX) external view returns (uint16, uint128); -``` ### getTrancheDetails @@ -70,11 +103,17 @@ function getAccount( ### update -update the borrow position of an account and potentially check (and revert) if the resulting sat is too high +update the borrow position of an account and potentially check (and revert) if the +resulting sat is too high ```solidity -function update(Validation.InputParams memory inputParams, address account) external; +function update( + Validation.InputParams memory inputParams, + address account, + uint256 fragileLiquidityAssets, + bool skipMinOrMaxTickCheck +) external; ``` **Parameters** @@ -82,6 +121,8 @@ function update(Validation.InputParams memory inputParams, address account) exte |----|----|-----------| |`inputParams`|`Validation.InputParams`| contains the position and pair params, like account borrows/deposits, current price and active liquidity| |`account`|`address`| for which is position is being updated| +|`fragileLiquidityAssets`|`uint256`| liquidity that may require seized in a liquidation to be excluded from available liquidity.| +|`skipMinOrMaxTickCheck`|`bool`| whether to skip the min/max tick check during validation| ### accruePenalties @@ -265,30 +306,6 @@ function getObservedMidTermTick( |`midTermTick`|`int16`|The mid-term tick value.| -### boundTick - -*The function ensures that `newTick` stays within the bounds -determined by `lastTick` and a dynamically calculated factor.* - - -```solidity -function boundTick( - int16 newTick -) external view returns (int16); -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`newTick`|`int16`|The proposed new tick value to be adjusted within valid bounds.| - -**Returns** - -|Name|Type|Description| -|----|----|-----------| -|``|`int16`|The adjusted tick value constrained within the allowable range.| - - ### getLendingStateTick Gets the tick value representing the TWAP since the last lending update. diff --git a/docs/developer-guide/contracts/interfaces/callbacks/IAmmalgamCallee.sol/interface.ICallback.md b/docs/developer-guide/contracts/interfaces/callbacks/IAmmalgamCallee.sol/interface.ICallback.md index 8c9c4e57..e7478e60 100644 --- a/docs/developer-guide/contracts/interfaces/callbacks/IAmmalgamCallee.sol/interface.ICallback.md +++ b/docs/developer-guide/contracts/interfaces/callbacks/IAmmalgamCallee.sol/interface.ICallback.md @@ -1,5 +1,5 @@ # ICallback -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/callbacks/IAmmalgamCallee.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/callbacks/IAmmalgamCallee.sol) *This interface should be implemented by anyone wishing to use callbacks in the `swap`, `borrow`, and `borrowLiquidity` functions in the IAmmalgamPair interface.* @@ -33,6 +33,10 @@ function ammalgamSwapCallV1( ### ammalgamBorrowCallV1 +The callback in the `AmmalgamPair.borrow()` function transfers borrowed `amountXAssets` and `amountYAssets` +to the borrower which doesn't include the initial lending fee. The `amountXShares` and `amountYShares` +minted debt shares for the `borrower` include the initial lending fee. + ```solidity function ammalgamBorrowCallV1( @@ -51,13 +55,17 @@ function ammalgamBorrowCallV1( |`sender`|`address`|| |`amountXAssets`|`uint256`|The amount of token X involved in the borrow.| |`amountYAssets`|`uint256`|The amount of token Y involved in the borrow.| -|`amountXShares`|`uint256`|The shares of token X involved in the borrow.| -|`amountYShares`|`uint256`|The shares of token Y involved in the borrow.| +|`amountXShares`|`uint256`|The shares of token X involved in the borrow including the initial lending fee.| +|`amountYShares`|`uint256`|The shares of token Y involved in the borrow including the initial lending fee.| |`data`|`bytes`|The calldata provided to the borrow function.| ### ammalgamBorrowLiquidityCallV1 +The callback in the `AmmalgamPair.borrowLiquidity()` function transfers borrowed +`amountXAssets` and `amountYAssets` to the borrower which doesn't include the initial lending fee. +The `amountLShares` minted debt shares for the `borrower` include the initial lending fee. + ```solidity function ammalgamBorrowLiquidityCallV1( @@ -73,10 +81,10 @@ function ammalgamBorrowLiquidityCallV1( |Name|Type|Description| |----|----|-----------| |`sender`|`address`|| -|`amountXAssets`|`uint256`|The amount of token X involved in the borrow.| -|`amountYAssets`|`uint256`|The amount of token Y involved in the borrow.| -|`amountLShares`|`uint256`|The shares of liquidity involved in the borrow.| -|`data`|`bytes`|The calldata provided to the borrow function.| +|`amountXAssets`|`uint256`|The amount of token X involved in the borrow liquidity.| +|`amountYAssets`|`uint256`|The amount of token Y involved in the borrow liquidity.| +|`amountLShares`|`uint256`|The shares of liquidity involved in the borrow liquidity including the initial lending fee.| +|`data`|`bytes`|The calldata provided to the borrow liquidity function.| ### ammalgamLiquidateCallV1 diff --git a/docs/developer-guide/contracts/interfaces/callbacks/ITransferValidator.sol/interface.ITransferValidator.md b/docs/developer-guide/contracts/interfaces/callbacks/ITransferValidator.sol/interface.ITransferValidator.md index 507058f3..2611e96d 100644 --- a/docs/developer-guide/contracts/interfaces/callbacks/ITransferValidator.sol/interface.ITransferValidator.md +++ b/docs/developer-guide/contracts/interfaces/callbacks/ITransferValidator.sol/interface.ITransferValidator.md @@ -1,5 +1,5 @@ # ITransferValidator -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/callbacks/ITransferValidator.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/callbacks/ITransferValidator.sol) This interface is intended for validating the solvency of an account when transfers occur. @@ -14,7 +14,7 @@ of existing debt or collateral that would leave any individual address with insu ```solidity -function validateOnUpdate(address validate, address update, bool isBorrow) external; +function validateOnUpdate(address validate, address update, bool alwaysUpdate) external; ``` **Parameters** @@ -22,6 +22,6 @@ function validateOnUpdate(address validate, address update, bool isBorrow) exter |----|----|-----------| |`validate`|`address`|The address of the account being checked for solvency and having its saturation updated| |`update`|`address`|The address of the account having its saturation updated| -|`isBorrow`|`bool`|| +|`alwaysUpdate`|`bool`|Whether to always update the saturation, even if the account is not borrowing| diff --git a/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IAmmalgamFactory.md b/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IAmmalgamFactory.md index 33cd0b36..89abe84e 100644 --- a/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IAmmalgamFactory.md +++ b/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IAmmalgamFactory.md @@ -1,11 +1,28 @@ # IAmmalgamFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/factories/IAmmalgamFactory.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/factories/IAmmalgamFactory.sol) **Inherits:** [IFactoryCallback](/docs/developer-guide/contracts/interfaces/factories/IFactoryCallback.sol/interface.IFactoryCallback.md) ## Functions +### pairBeacon + +Returns the public immutable address of the pair beacon contract. Used as a callback +in the creation of a new pair to ensure we can maintain the create2 deterministic address +that also require no args in the constructor. + + +```solidity +function pairBeacon() external view returns (IBeacon beacon); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`beacon`|`IBeacon`|The address of the pair beacon.| + + ### getPair Returns the pair address for two tokens. @@ -122,6 +139,21 @@ function setFeeToSetter( |`newFeeToSetter`|`address`|The new fee setter address.| +### hookRegistry + +Returns the public immutable address of the hook registry contract. + + +```solidity +function hookRegistry() external view returns (IHookRegistry); +``` +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`IHookRegistry`|The address of the hook registry.| + + ## Events ### PairCreated Emitted when a new pair is created. diff --git a/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IPairFactory.md b/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IPairFactory.md deleted file mode 100644 index 0f0ad0d8..00000000 --- a/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IPairFactory.md +++ /dev/null @@ -1,17 +0,0 @@ -# IPairFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/factories/IAmmalgamFactory.sol) - -An interface to minimize code around the AmmalgamPair creation due to -its large size. - - -## Functions -### createPair - - -```solidity -function createPair( - bytes32 salt -) external returns (address pair); -``` - diff --git a/docs/developer-guide/contracts/interfaces/factories/IFactoryCallback.sol/interface.IFactoryCallback.md b/docs/developer-guide/contracts/interfaces/factories/IFactoryCallback.sol/interface.IFactoryCallback.md index d6f9c375..94ced556 100644 --- a/docs/developer-guide/contracts/interfaces/factories/IFactoryCallback.sol/interface.IFactoryCallback.md +++ b/docs/developer-guide/contracts/interfaces/factories/IFactoryCallback.sol/interface.IFactoryCallback.md @@ -1,5 +1,5 @@ # IFactoryCallback -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/factories/IFactoryCallback.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/factories/IFactoryCallback.sol) This interface provides methods for getting the token factory configuration. @@ -71,7 +71,6 @@ the addresses of tokenX, tokenY, and the factory itself. struct TokenFactoryConfig { address tokenX; address tokenY; - address factory; } ``` diff --git a/docs/developer-guide/contracts/interfaces/factories/INewTokensFactory.sol/interface.INewTokensFactory.md b/docs/developer-guide/contracts/interfaces/factories/INewTokensFactory.sol/interface.INewTokensFactory.md deleted file mode 100644 index bf482e9e..00000000 --- a/docs/developer-guide/contracts/interfaces/factories/INewTokensFactory.sol/interface.INewTokensFactory.md +++ /dev/null @@ -1,36 +0,0 @@ -# INewTokensFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/factories/INewTokensFactory.sol) - -Interface for the NewTokensFactory contract, which is responsible for creating new instances of AmmalgamERC20 tokens. - - -## Functions -### createAllTokens - -Creates new instances of AmmalgamERC20 tokens for the given token addresses. - - -```solidity -function createAllTokens( - address pair, - address pluginRegistry, - address tokenX, - address tokenY -) external returns (IAmmalgamERC20[6] memory); -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`pair`|`address`|| -|`pluginRegistry`|`address`|| -|`tokenX`|`address`|The address of tokenX.| -|`tokenY`|`address`|The address of tokenY.| - -**Returns** - -|Name|Type|Description| -|----|----|-----------| -|``|`IAmmalgamERC20[6]`|An array of IAmmalgamERC20 tokens consisting of [liquidityToken, depositXToken, depositYToken, borrowXToken, borrowYToken, borrowLToken].| - - diff --git a/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md b/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md index 09ee8ac9..4f85c328 100644 --- a/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md +++ b/docs/developer-guide/contracts/interfaces/factories/ITokenFactory.sol/interface.ITokenFactory.md @@ -1,5 +1,5 @@ # ITokenFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/factories/ITokenFactory.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/factories/ITokenFactory.sol) ## Functions diff --git a/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md b/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md index 7296a647..ebc7d050 100644 --- a/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md +++ b/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md @@ -1,5 +1,5 @@ # IAmmalgamERC20 -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/tokens/IAmmalgamERC20.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/tokens/IAmmalgamERC20.sol) **Inherits:** IERC20, IERC20Metadata, IERC20Permit diff --git a/docs/developer-guide/contracts/interfaces/tokens/IERC20DebtToken.sol/interface.IERC20DebtToken.md b/docs/developer-guide/contracts/interfaces/tokens/IERC20DebtToken.sol/interface.IERC20DebtToken.md index b3280b19..e08c05fc 100644 --- a/docs/developer-guide/contracts/interfaces/tokens/IERC20DebtToken.sol/interface.IERC20DebtToken.md +++ b/docs/developer-guide/contracts/interfaces/tokens/IERC20DebtToken.sol/interface.IERC20DebtToken.md @@ -1,5 +1,5 @@ # IERC20DebtToken -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/tokens/IERC20DebtToken.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/tokens/IERC20DebtToken.sol) **Inherits:** [IAmmalgamERC20](/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md) diff --git a/docs/developer-guide/contracts/interfaces/tokens/IHookRegistry.sol/interface.IHookRegistry.md b/docs/developer-guide/contracts/interfaces/tokens/IHookRegistry.sol/interface.IHookRegistry.md new file mode 100644 index 00000000..42e1cde4 --- /dev/null +++ b/docs/developer-guide/contracts/interfaces/tokens/IHookRegistry.sol/interface.IHookRegistry.md @@ -0,0 +1,50 @@ +# IHookRegistry +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/tokens/IHookRegistry.sol) + + +## Functions +### updateHook + +This function is restricted to the owner of the contract. + +*Updates the allowed status of a hook.* + +*Emits no events.* + + +```solidity +function updateHook(address hook, bool allowed) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`hook`|`address`|The address of the hook to be updated.| +|`allowed`|`bool`|A boolean value indicating whether the hook should be allowed (true) or disallowed (false).| + + +### isHookAllowed + +*Checks if a hook is allowed.* + +*This function is a view function and does not alter state.* + + +```solidity +function isHookAllowed( + address hook +) external view returns (bool); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`hook`|`address`|The address of the hook to check.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`bool`|A boolean value indicating whether the hook is allowed (true) or disallowed (false).| + + diff --git a/docs/developer-guide/contracts/interfaces/tokens/IPluginRegistry.sol/interface.IPluginRegistry.md b/docs/developer-guide/contracts/interfaces/tokens/IPluginRegistry.sol/interface.IPluginRegistry.md deleted file mode 100644 index c26da94d..00000000 --- a/docs/developer-guide/contracts/interfaces/tokens/IPluginRegistry.sol/interface.IPluginRegistry.md +++ /dev/null @@ -1,50 +0,0 @@ -# IPluginRegistry -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/tokens/IPluginRegistry.sol) - - -## Functions -### updatePlugin - -This function is restricted to the owner of the contract. - -*Updates the allowed status of a plugin.* - -*Emits no events.* - - -```solidity -function updatePlugin(address plugin, bool allowed) external; -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`plugin`|`address`|The address of the plugin to be updated.| -|`allowed`|`bool`|A boolean value indicating whether the plugin should be allowed (true) or disallowed (false).| - - -### isPluginAllowed - -*Checks if a plugin is allowed.* - -*This function is a view function and does not alter state.* - - -```solidity -function isPluginAllowed( - address plugin -) external view returns (bool); -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`plugin`|`address`|The address of the plugin to check.| - -**Returns** - -|Name|Type|Description| -|----|----|-----------| -|``|`bool`|A boolean value indicating whether the plugin is allowed (true) or disallowed (false).| - - diff --git a/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/constants.ITokenController.md b/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/constants.ITokenController.md index e48fd105..7d443c77 100644 --- a/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/constants.ITokenController.md +++ b/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/constants.ITokenController.md @@ -1,5 +1,5 @@ # Constants -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/tokens/ITokenController.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/tokens/ITokenController.sol) ### DEPOSIT_L @@ -43,6 +43,12 @@ uint256 constant BORROW_Y = 5; uint256 constant FIRST_DEBT_TOKEN = 3; ``` +### TOKEN_COUNT + +```solidity +uint256 constant TOKEN_COUNT = 6; +``` + ### ROUNDING_UP ```solidity diff --git a/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md b/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md index b316b0d6..f5daf0b9 100644 --- a/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md +++ b/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md @@ -1,5 +1,5 @@ # ITokenController -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/interfaces/tokens/ITokenController.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/interfaces/tokens/ITokenController.sol) The interface of a ERC20 facade for multiple token types with functionality similar to ERC1155. @@ -7,6 +7,13 @@ The interface of a ERC20 facade for multiple token types with functionality simi ## Functions +### initialize + + +```solidity +function initialize() external; +``` + ### underlyingTokens Get the underlying tokens for the AmmalgamERC20Controller. @@ -25,7 +32,7 @@ function underlyingTokens() external view returns (IERC20, IERC20); ### getReserves -Fetches the current reserves of asset X and asset Y, as well as the block of the last operation. +Fetches the current reserves and the last update timestamp. ```solidity @@ -35,8 +42,8 @@ function getReserves() external view returns (uint112 reserveXAssets, uint112 re |Name|Type|Description| |----|----|-----------| -|`reserveXAssets`|`uint112`|The current reserve of asset X.| -|`reserveYAssets`|`uint112`|The current reserve of asset Y.| +|`reserveXAssets`|`uint112`|The raw reserveX or reserveX plus unaccrued interest.| +|`reserveYAssets`|`uint112`|The raw reserveY or reserveY plus unaccrued interest.| |`lastTimestamp`|`uint32`|The timestamp of the last operation.| @@ -107,23 +114,36 @@ function tokens( |``|`IAmmalgamERC20`|The IAmmalgamERC20 token| -### totalAssets +### totalAssetsAndShares -Computes the current total Assets. +Computes current total assets and shares. -*If the last lending state update is outdated (i.e., not matching the current block timestamp), -the function recalculates the assets based on the duration since the last update, the lending state, -and reserve balances. If the timestamp is current, the previous scaler (without recalculation) is returned.* +*Behavior depends on the `withInterest` flag: +1. If `withInterest` is `false`: Returns stored values (`allAssets`, `allShares`) without adjustments. +2. If `withInterest` is `true`: +- First calls `computeAssetsState()` to recalculate assets and shares (accounts for elapsed time, interest, and lending state). +- Converts protocol fees to shares for DEPOSIT_L/X/Y and adds them to `_allShares`. +- Adds protocol fees to DEPOSIT_L/X/Y in `_allAssets` (updated after shares to avoid double-counting). +3. If `computeAssetsState()` detects no elapsed lending time, it returns stored values without recalculation.* ```solidity -function totalAssets() external view returns (uint128[6] memory); +function totalAssetsAndShares( + bool withInterest +) external view returns (uint112[6] memory _allAssets, uint112[6] memory _allShares); ``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`withInterest`|`bool`|Toggle to enable/disable interest accrual, reserve adjustments, and protocol fee application.| + **Returns** |Name|Type|Description| |----|----|-----------| -|``|`uint128[6]`|totalAssets An array of six `uint128` values representing the total assets for each of the 6 amalgam token types. These values may be adjusted based on the time elapsed since the last update. If the timestamp is up-to-date, the previously calculated total assets are returned without recalculation.| +|`_allAssets`|`uint112[6]`|Array of six `uint128` values: Total assets for each of the 6 Amalgam token types. If `withInterest` is `true`, includes protocol fees for DEPOSIT_L/X/Y.| +|`_allShares`|`uint112[6]`|Array of six `uint112` values: Total shares for each of the 6 Amalgam token types. If `withInterest` is `true`, includes shares converted from protocol fees for DEPOSIT_L/X/Y.| ## Events @@ -179,12 +199,12 @@ event BurnBadDebt(address indexed borrower, uint256 indexed tokenType, uint256 b ```solidity event InterestAccrued( - uint128 depositLAssets, - uint128 depositXAssets, - uint128 depositYAssets, - uint128 borrowLAssets, - uint128 borrowXAssets, - uint128 borrowYAssets + uint112 depositLAssets, + uint112 depositXAssets, + uint112 depositYAssets, + uint112 borrowLAssets, + uint112 borrowXAssets, + uint112 borrowYAssets ); ``` @@ -192,10 +212,10 @@ event InterestAccrued( |Name|Type|Description| |----|----|-----------| -|`depositLAssets`|`uint128`|The amount of total `DEPOSIT_L` assets in the pool after interest accrual| -|`depositXAssets`|`uint128`|The amount of total `DEPOSIT_X` assets in the pool after interest accrual| -|`depositYAssets`|`uint128`|The amount of total `DEPOSIT_Y` assets in the pool after interest accrual| -|`borrowLAssets`|`uint128`|The amount of total `BORROW_L` assets in the pool after interest accrual| -|`borrowXAssets`|`uint128`|The amount of total `BORROW_X` assets in the pool after interest accrual| -|`borrowYAssets`|`uint128`|The amount of total `BORROW_Y` assets in the pool after interest accrual| +|`depositLAssets`|`uint112`|The amount of total `DEPOSIT_L` assets in the pool after interest accrual| +|`depositXAssets`|`uint112`|The amount of total `DEPOSIT_X` assets in the pool after interest accrual| +|`depositYAssets`|`uint112`|The amount of total `DEPOSIT_Y` assets in the pool after interest accrual| +|`borrowLAssets`|`uint112`|The amount of total `BORROW_L` assets in the pool after interest accrual| +|`borrowXAssets`|`uint112`|The amount of total `BORROW_X` assets in the pool after interest accrual| +|`borrowYAssets`|`uint112`|The amount of total `BORROW_Y` assets in the pool after interest accrual| diff --git a/docs/developer-guide/contracts/libraries/Convert.sol/library.Convert.md b/docs/developer-guide/contracts/libraries/Convert.sol/library.Convert.md index 25f00968..1ce39449 100644 --- a/docs/developer-guide/contracts/libraries/Convert.sol/library.Convert.md +++ b/docs/developer-guide/contracts/libraries/Convert.sol/library.Convert.md @@ -1,13 +1,5 @@ # Convert -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/Convert.sol) - - -## State Variables -### BUFFER - -```solidity -uint256 private constant BUFFER = 95; -``` +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/Convert.sol) ## Functions @@ -55,44 +47,3 @@ function toShares( function mulDiv(uint256 x, uint256 y, uint256 z, bool roundingUp) internal pure returns (uint256 result); ``` -### calcLiquidityConsideringDepletion - - -```solidity -function calcLiquidityConsideringDepletion( - uint256 amountOfAssets, - uint256 reserveAssets, - uint256 _missingAssets, - uint256 activeLiquidityAssets, - uint256 depositedLiquidityAssets, - uint256 depositedLiquidityShares, - bool isRoundingUp -) internal pure returns (uint256 liquidityAssets, uint256 liquidityShares); -``` - -### depletionReserveAdjustmentWhenLiquidityIsAdded - -*Minting when assets depleted requires less of the depleted asset as we -give extra credit to minter for bringing the scarce asset. We account -for liquidity as if moving from the unmodified invariant prior to mint -to the where it would move after the mint including the extra credited -scarce asset. -I continue to update the Desmos to help create test cases with easier -numbers to reason about, The current version of desmos is linked below. -The chart could use some clean up and reorganization to be clearer, will -do in the future. -https://www.desmos.com/calculator/etzuxkjeig* - - -```solidity -function depletionReserveAdjustmentWhenLiquidityIsAdded( - uint256 amountAssets, - uint256 reserveAssets, - uint256 _missingAssets, - uint256 activeLiquidityAssets, - uint256 depositedLAssets, - uint256 depositedLShares, - bool roundingUp -) private pure returns (uint256 liquidityAssets, uint256 liquidityShares); -``` - diff --git a/docs/developer-guide/contracts/libraries/GeometricTWAP.sol/library.GeometricTWAP.md b/docs/developer-guide/contracts/libraries/GeometricTWAP.sol/library.GeometricTWAP.md index 0e75e1e5..28cdb827 100644 --- a/docs/developer-guide/contracts/libraries/GeometricTWAP.sol/library.GeometricTWAP.md +++ b/docs/developer-guide/contracts/libraries/GeometricTWAP.sol/library.GeometricTWAP.md @@ -1,5 +1,5 @@ # GeometricTWAP -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/GeometricTWAP.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/GeometricTWAP.sol) ## State Variables @@ -537,6 +537,28 @@ function getCurrentTimestamp() internal view returns (uint32); |``|`uint32`|The current block timestamp as a uint32 value.| +### calculateTickAverageTowardsMidTerm + +*Average the mid-term tick and the new tick, rounding towards the `midTermTick`.* + + +```solidity +function calculateTickAverageTowardsMidTerm(int256 midTermTick, int256 newTick) internal pure returns (int16); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`midTermTick`|`int256`|The midterm tick value| +|`newTick`|`int256`|The new tick value| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`int16`|The calculated average tick value| + + ## Events ### UpdateLendingTick *Emitted when `lendingStateTick` is updated* diff --git a/docs/developer-guide/contracts/libraries/Interest.sol/library.Interest.md b/docs/developer-guide/contracts/libraries/Interest.sol/library.Interest.md index e9279fe8..a2376265 100644 --- a/docs/developer-guide/contracts/libraries/Interest.sol/library.Interest.md +++ b/docs/developer-guide/contracts/libraries/Interest.sol/library.Interest.md @@ -1,9 +1,9 @@ # Interest -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/Interest.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/Interest.sol) This library is used for calculating and accruing interest. -*many calculations are unchecked because we asset values are stored as uint128. We also limit +*many calculations are unchecked because we asset values are stored as uint112. We also limit the max amount amount of interest to ensure that it can not overflow when added to the current assets.* @@ -12,56 +12,56 @@ current assets.* ### OPTIMAL_UTILIZATION ```solidity -uint128 internal constant OPTIMAL_UTILIZATION = 0.8e18; +uint256 internal constant OPTIMAL_UTILIZATION = 0.8e18; ``` ### DANGER_UTILIZATION ```solidity -uint128 internal constant DANGER_UTILIZATION = 0.925e18; +uint256 internal constant DANGER_UTILIZATION = 0.925e18; ``` ### SLOPE1 ```solidity -uint128 internal constant SLOPE1 = 0.1e18; +uint256 internal constant SLOPE1 = 0.1e18; ``` ### SLOPE2 ```solidity -uint128 internal constant SLOPE2 = 2e18; +uint256 internal constant SLOPE2 = 2e18; ``` ### SLOPE3 ```solidity -uint128 internal constant SLOPE3 = 20e18; +uint256 internal constant SLOPE3 = 20e18; ``` ### BASE_OPTIMAL_UTILIZATION ```solidity -uint128 internal constant BASE_OPTIMAL_UTILIZATION = 0.08e18; +uint256 internal constant BASE_OPTIMAL_UTILIZATION = 0.08e18; ``` ### BASE_DANGER_UTILIZATION ```solidity -uint128 internal constant BASE_DANGER_UTILIZATION = 0.33e18; +uint256 internal constant BASE_DANGER_UTILIZATION = 0.33e18; ``` ### LENDING_FEE_RATE ```solidity -uint128 internal constant LENDING_FEE_RATE = 10; +uint256 internal constant LENDING_FEE_RATE = 10; ``` @@ -79,6 +79,13 @@ uint256 private constant LAST_DEPOSIT = 2; ``` +### NO_RESERVES_FOR_L + +```solidity +uint256 private constant NO_RESERVES_FOR_L = 0; +``` + + ### PENALTY_SATURATION_PERCENT_IN_WAD *Maximum percentage for the penalty saturation allowed. This is used to prevent excessive penalties in case of high utilization.* @@ -104,7 +111,7 @@ uint256 private constant SATURATION_PENALTY_BUFFER_IN_WAD = 0.1e18; ```solidity function accrueInterestAndUpdateReservesWithAssets( - uint128[6] storage assets, + uint112[6] storage assets, AccrueInterestParams memory accrueInterestParams ) external returns (uint256 interestXForLP, uint256 interestYForLP, uint256[3] memory protocolFeeAssets); ``` @@ -145,7 +152,7 @@ function getReservesAtTick( ```solidity function getUtilizationsInWads( - uint128[6] memory startingAssets, + uint112[6] memory startingAssets, uint256 reservesXAssets, uint256 reservesYAssets, uint256 satPercentageInWads @@ -157,13 +164,13 @@ function getUtilizationsInWads( ```solidity function accrueInterestWithAssets( - uint128[6] memory assets, + uint112[6] memory assets, AccrueInterestParams memory params ) public pure returns ( - uint128[6] memory newAssets, + uint112[6] memory newAssets, uint256 interestXPortionForLP, uint256 interestYPortionForLP, uint256[3] memory protocolFeeAssets @@ -212,6 +219,7 @@ function mutateUtilizationForSaturation(uint256 utilization, uint256 maxSatInWad function computeInterestAssets( uint256 duration, uint256 utilization, + uint256 reserveAssets, uint256 borrowedAssets, uint256 depositedAssets ) internal pure returns (uint256); @@ -224,7 +232,7 @@ function computeInterestAssets( function computeInterestAssetsGivenRate( uint256 duration, uint256 borrowedAssets, - uint256 depositedAssets, + uint256 maxDepositedOrReserveAssets, uint256 rateInWads ) internal pure returns (uint256); ``` @@ -233,7 +241,7 @@ function computeInterestAssetsGivenRate( ```solidity -function addInterestToAssets(uint256 prevAssets, uint256 interest) internal pure returns (uint128); +function addInterestToAssets(uint256 prevAssets, uint256 interest) internal pure returns (uint112); ``` ### getAnnualInterestRatePerSecondInWads @@ -261,20 +269,6 @@ function getAnnualInterestRatePerSecondInWads( |`interestRate`|`uint256`|The annual interest rate in WADs| -## Events -### InterestAccrued - -```solidity -event InterestAccrued( - uint128 depositLAssets, - uint128 depositXAssets, - uint128 depositYAssets, - uint128 borrowLAssets, - uint128 borrowXAssets, - uint128 borrowYAssets -); -``` - ## Structs ### AccrueInterestParams @@ -282,9 +276,10 @@ event InterestAccrued( struct AccrueInterestParams { uint256 duration; int16 lendingStateTick; - uint256 adjustedActiveLiquidity; uint112[6] shares; uint256 satPercentageInWads; + uint256 reserveXAssets; + uint256 reserveYAssets; } ``` diff --git a/docs/developer-guide/contracts/libraries/Liquidation.sol/library.Liquidation.md b/docs/developer-guide/contracts/libraries/Liquidation.sol/library.Liquidation.md index 5dacc325..a0e53411 100644 --- a/docs/developer-guide/contracts/libraries/Liquidation.sol/library.Liquidation.md +++ b/docs/developer-guide/contracts/libraries/Liquidation.sol/library.Liquidation.md @@ -1,5 +1,5 @@ # Liquidation -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/Liquidation.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/Liquidation.sol) ## State Variables @@ -66,10 +66,10 @@ uint256 internal constant HARD = 0; ``` -### SOFT +### SATURATION ```solidity -uint256 internal constant SOFT = 1; +uint256 internal constant SATURATION = 1; ``` @@ -103,11 +103,11 @@ function calculateNetDebtAndSeizedDeposits( ) internal pure returns (uint256 netDebtInLAssets, uint256 netCollateralInLAssets, bool netDebtX); ``` -### checkSoftPremiums +### checkSaturationPremiums ```solidity -function checkSoftPremiums( +function checkSaturationPremiums( ISaturationAndGeometricTWAPState saturationAndGeometricTWAPState, Validation.InputParams memory inputParams, address borrower, @@ -135,7 +135,7 @@ function liquidateLeverageCalcDeltaAndPremium( |Name|Type|Description| |----|----|-----------| |`inputParams`|`Validation.InputParams`|The params representing the position of the borrower.| -|`depositL`|`bool`|Flag indicating whether the liquidator is transferring depositL.| +|`depositL`|`bool`|Flag indicating whether the liquidator is taking depositL.| |`repayL`|`bool`|Flag indicating whether the liquidator is repaying borrowL.| **Returns** @@ -240,15 +240,15 @@ function calculateNetDebtAndCollateral( ) internal pure returns (uint256 netDebtInLAssets, uint256 netCollateralInLAssets); ``` -### calcSoftPremiumBips +### calcSaturationPremiumBips -Calculate the premium the soft liquidator is receiving given the borrowers deposit and the depositToTransfer to the liquidator. +Calculate the premium the saturation liquidator is receiving given the borrowers deposit and the depositToTransfer to the liquidator. The end premium is the max of the premiums in L, X, Y -If no soft liq is requested (liquidationParams.softDepositLToBeTransferred==liquidationParams.softDepositXToBeTransferred==liquidationParams.softDepositYToBeTransferred==0), the premium will be 0 +If no saturation liq is requested (liquidationParams.saturationDepositLToBeTransferred==liquidationParams.saturationDepositXToBeTransferred==liquidationParams.saturationDepositYToBeTransferred==0), the premium will be 0 ```solidity -function calcSoftPremiumBips( +function calcSaturationPremiumBips( Validation.InputParams memory inputParams, uint256 depositLToTransferInLAssets, uint256 depositXToTransferInXAssets, @@ -271,13 +271,14 @@ function calcSoftPremiumBips( |`premiumInBips`|`uint256`|The premium being received by the liquidator.| -### calcSoftMaxPremiumInBips +### calcSaturationMaxPremiumInBips -Calculate the max premium the soft liquidator can receive given position of `account`. +Calculate the max premium the saturation liquidator can receive given position of +`account`. ```solidity -function calcSoftMaxPremiumInBips( +function calcSaturationMaxPremiumInBips( ISaturationAndGeometricTWAPState saturationAndGeometricTWAPState, Validation.InputParams memory inputParams, address account diff --git a/docs/developer-guide/contracts/libraries/QuadraticSwapFees.sol/library.QuadraticSwapFees.md b/docs/developer-guide/contracts/libraries/QuadraticSwapFees.sol/library.QuadraticSwapFees.md index b1691551..db1ecc4e 100644 --- a/docs/developer-guide/contracts/libraries/QuadraticSwapFees.sol/library.QuadraticSwapFees.md +++ b/docs/developer-guide/contracts/libraries/QuadraticSwapFees.sol/library.QuadraticSwapFees.md @@ -1,15 +1,35 @@ # QuadraticSwapFees -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/QuadraticSwapFees.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/QuadraticSwapFees.sol) **Author:** Will -A library to calculate fees that grow quadratically with respect to price, square root -price to be exact. This library relies on a reference reserve from the start of the block to -determine what the overall growth in price has been in the current block. If one swap were to -pay one fee, that same swap broken into two swaps would pay two fees that would add up to the -one. If the price moves away from the reserve, and then back towards the reserve, the fee is -minimal until the price again crosses the starting price. +A library to calculate fees that grow with respect to price deviation from a reference point. +This library relies on a reference reserve from the start of the block to determine what the overall +growth in price has been in the current block. +Fee Model Overview: +The fee structure uses two distinct models depending on the magnitude of price deviation: +1. Quadratic Fee Model (for moderate price changes): +- Used when price deviation is relatively small +- Fee grows proportionally to the square of the price movement +- This creates a smooth, incentive-aligned fee curve that discourages large single swaps +while keeping fees reasonable for normal market activity +- Key property: If one swap would pay fee `F`, splitting it into two equal swaps would pay +two fees that sum to approximately `F` +2. Linear Fee Model (for extreme price changes): +- Used when price deviation exceeds the quadratic threshold +- Fee grows linearly beyond the threshold point, capping at `MAX_QUADRATIC_FEE_PERCENT` +- This prevents fees from becoming prohibitively expensive for very large swaps while +still maintaining strong economic disincentives against massive price manipulations +- The linear growth provides a more predictable fee structure for extreme market conditions +Why Two Models? +- Quadratic fees alone would become so high that the invariant curve property of being monotonic, leading +larger swaps amounts in would eventually lead to less assets out than smaller swaps in. +- Linear fees alone wouldn't provide enough protection against price manipulation for moderate swaps +Price Movement Behavior: +- If the price moves away from the reference, and then back toward it, the fee is minimal until +the price again crosses the starting reference price +- Only the net price deviation from the start-of-block reference is charged ## State Variables @@ -50,15 +70,24 @@ uint256 internal constant N = 20; ``` +### RESERVE_MULTIPLIER +A reserve multiplier used to determine the boundary at which we switch from quadratic to linear fee. + + +```solidity +uint256 private constant RESERVE_MULTIPLIER = 2; +``` + + ### LINEAR_START_REFERENCE_SCALER the $$\sqrt{price}$$ at which we switch from quadratic fee to a more linear fee. ```math -(MAX\_QUADRATIC\_FEE\_PERCENT + N) / N +(MAX\_QUADRATIC\_FEE\_PERCENT + 2 * N) / N ``` ```solidity -uint256 private constant LINEAR_START_REFERENCE_SCALER = 3; +uint256 private constant LINEAR_START_REFERENCE_SCALER = 4; ``` @@ -90,7 +119,7 @@ uint256 private constant TWO_Q64 = 0x20000000000000000; ### MAX_QUADRATIC_FEE_Q64 -`MAX_QUADRATIC_FEE_PERCENT` in Q64, $$ MAX_QUADRATIC_FEE_PERCENT * Q64 $$ +`MAX_QUADRATIC_FEE_PERCENT` in Q64, $$ MAX\_QUADRATIC\_FEE\_PERCENT * Q64 $$ ```solidity @@ -101,14 +130,128 @@ uint256 private constant MAX_QUADRATIC_FEE_Q64 = 0x280000000000000000; ## Functions ### calculateSwapFeeBipsQ64 -Returns a swap fee given the current reserve reference. +Computes the swap fee based on the `input` amount and the pool's +`currentReserve` and `referenceReserve` for the input asset. +Control flow by scenario: +- `currentReserve >= referenceReserve` (price already at/away from reference): +- If `input + RESERVE_MULTIPLIER * currentReserve < referenceReserve * LINEAR_START_REFERENCE_SCALER`: +Use the quadratic fee model (closer to reference, pre-threshold). +- Otherwise: +Use the linear fee model (farther from reference, post-threshold). +- `currentReserve < referenceReserve` (price at/moving back toward the start-of-block reference): +- If `input + currentReserve <= referenceReserve`: +Does not cross the reference. Only the global minimum fee will apply at the end. +- If `input + currentReserve > referenceReserve`: +Crosses the reference. The portion beyond the reference (`pastBy`) is charged using +either the quadratic or linear model depending on `pastBy`: +- `pastBy > RESERVE_MULTIPLIER * referenceReserve` → use linear fee model +- otherwise → use quadratic fee model +The resulting fee for the beyond-reference portion is then weighted by `pastBy / input`. +```math +\begin{equation*} +f_\phi(X_{in}) = +\begin{cases} +n \cdot \frac{2(X_{0}-X_{R})+X_{in}}{X_{R}} +&\text{if } X_0 \ge X_R \text{ \& } X_{in} + 2 X_{0} \le X_{R}\left(\frac{M_Q +\ 2n}{n}\right) \\ +M_Q \left( 2 - X_R \frac{M_Q}{n\left( X_{in} + 2 (X_0 - X_R) \right)} \right) +&\text {if } X_0 \ge X_R \text{ \& } X_{in} + 2X_{0} \ge X_{R}\left(\frac{M_Q+\ 2n}{n}\right) \\ +\frac{n \cdot \left( \frac{pastBy^2}{X_R} \right)}{X_{in}} +&\text{ if } X_0 + X_{in} \gt X_R \text{ \& } X_{in} + 2 X_{0} \le X_{R}\left(\frac{M_Q +\ 2n}{n}\right) \\ +\frac{M_Q \left( 2 - X_R \frac{M_Q}{n \cdot pastBy} \right) \cdot pastBy}{X_{in}} +&\text{ if } X_0 + X_{in} \gt X_R \text{ \& } X_{in} + 2 X_{0} \ge X_{R}\left(\frac{M_Q +\ 2n}{n}\right) \\ +MinBips &\text{ otherwise } X_0 + X_{in} \le X_R \\ +\end{cases} +\end{equation*} +``` +where: +- `X_in` is the `input` amount +- `X_0` is the `currentReserve` +- `X_R` is the `referenceReserve` +- `M_Q` is `MAX_QUADRATIC_FEE_PERCENT` +- `n` is `N` +- `pastBy` is the amount by which the price has moved past the `referenceReserve` +- `MinBips` is `MIN_FEE_Q64` ```solidity function calculateSwapFeeBipsQ64( uint256 input, - uint256 referenceReserve, - uint256 currentReserve + uint256 currentReserve, + uint256 referenceReserve ) internal pure returns (uint256 fee); ``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`input`|`uint256`|The input amount of the asset (units of the asset).| +|`currentReserve`|`uint256`|The current reserve of the input asset in the pool.| +|`referenceReserve`|`uint256`|The start-of-block reference reserve for the input asset.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`fee`|`uint256`|The swap fee in Q64 bips.| + + +### calculateQuadraticFeeBipsQ64 + +Calculates the quadratic fee in Q64 bips. + +*The quadratic fee model charges fees proportional to the square of price movement. +Refer to `calculateSwapFeeBipsQ64` NatSpec for the quadratic fee formula.* + + +```solidity +function calculateQuadraticFeeBipsQ64( + uint256 input, + uint256 currentReserve, + uint256 referenceReserve +) private pure returns (uint256 fee); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`input`|`uint256`|The input amount of the asset (units of the asset).| +|`currentReserve`|`uint256`|The current reserve of the input asset in the pool.| +|`referenceReserve`|`uint256`|The start-of-block reference reserve for the input asset.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`fee`|`uint256`|The quadratic fee in Q64 bips.| + + +### calculateLinearFeeBipsQ64 + +Calculates the linear fee in Q64 bips. + +*The linear fee model charges fees that grow linearly (not quadratically) for extreme price deviations. +Refer to `calculateSwapFeeBipsQ64` NatSpec for the linear fee formula.* + + +```solidity +function calculateLinearFeeBipsQ64( + uint256 input, + uint256 currentReserve, + uint256 referenceReserve +) private pure returns (uint256 fee); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`input`|`uint256`|The input amount of the asset (units of the asset).| +|`currentReserve`|`uint256`|The current reserve of the input asset in the pool.| +|`referenceReserve`|`uint256`|The start-of-block reference reserve for the input asset.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`fee`|`uint256`|The linear fee in Q64 bips.| + diff --git a/docs/developer-guide/contracts/libraries/Saturation.sol/library.Saturation.md b/docs/developer-guide/contracts/libraries/Saturation.sol/library.Saturation.md index 676b9d84..b34d1057 100644 --- a/docs/developer-guide/contracts/libraries/Saturation.sol/library.Saturation.md +++ b/docs/developer-guide/contracts/libraries/Saturation.sol/library.Saturation.md @@ -1,31 +1,37 @@ # Saturation -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/Saturation.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/Saturation.sol) **Authors:** imi@1m1.io, Will duelingGalois@protonmail.com -Saturation (=sat) is defined as the net borrow. In theory, we would want to divide net +Saturation, or sat, is defined as the net borrow. In theory, we would want to divide net borrow by the total liquidity; in practice, we keep the net borrow only in the tree. The unit of sat is relative to active liquidity assets, or the amount of L deposited less the amount borrowed. When we determine how much a swap moves the price, or square root price, we can define our -equation using ticks, or tranches (100 ticks), where for some base $b$, the square root price -is $b^t$ for some tick $t$. Alternatively for a larger base $B = b^{100}$ we can define the +equation using ticks, or tranches (25 ticks), where for some base $b$, the square root price +is $b^t$ for some tick $t$. Alternatively for a larger base $B = b^{25}$ we can define the square root price as $B^T$ for some tranche $T$. Using the square root price, we can define the -amount of x or y in each tranche as $x = LB^{T_0} - LB^{T_1} $ and $y= \frac{L}{ B^{T_1}} - -\frac{L}{ B^{T_0}}$, where liquidity is $L = \sqrt{reserveX \cdot reserveY}$. If we want to -know how much debt of x or y can be liquidated within one tranche, we can solve these equations -for L and then the amount of x and y are considered the debt we would like to see if it could -be liquidated in one tranche. If saturation with respect to our starting $L$ is smaller, that -amount of debt can be liquidated in one swap in the given tranche. Otherwise it is to big and -can not. Note that we assume $T_1 \text{ and } T_0 \in \mathbb{Z} -$ and $T_0 + 1 = T_1$. Then our definition of saturation relative to L is as follows, +amount of x or y in each tranche as: +```math +\begin{align*} +x = L \cdot B^{T_0} - L \cdot B^{T_1} \\ +y = \frac{L}{ B^{T_1}} - \frac{L}{B^{T_0}} +\end{align*} +``` +where liquidity is $L = \sqrt{reserveX \cdot reserveY}$. If we want to know how much debt of x +or y can be liquidated within one tick, we can solve these equations for L and then the amount +of x and y are considered the debt we would like to see if it could be liquidated in one tick. +If saturation with respect to our starting $L$ is smaller, that amount of debt can be +liquidated in one swap in the given ticks. Otherwise it is too big and can not. Note that we +assume $$t_1 \text{ and } t_0 \in \mathbb{Z}$$ and $$t_0 + 1 = t_1$$. Then our definition of +saturation relative to L is as follows, ```math \begin{equation} saturationRelativeToL = \begin{cases} -\frac{debtX}{B^{T_{1}}}\left(\frac{B}{B-1}\right) \\ -debtY\cdot B^{T_{0}}\cdot\left(\frac{B}{B-1}\right) +\frac{ debtX }{ b^{ t_1 } } \left( \frac{ b }{ b - 1 } \right) \\ +debtY \cdot b^{ t_0 } \cdot \left( \frac{ b }{ b - 1 } \right) \end{cases} \end{equation} ``` @@ -33,25 +39,25 @@ Saturation is kept in a tree, starting with a root, levels and leafs. We keep 2 net X borrows, another for net Y borrows. The price is always the price of Y in units of X. Mostly, the code works with the sqrt of price. A net X borrow refers to a position that if liquidated would cause the price to become smaller; the opposite for net Y positions. Ticks are -along the price dimension and int16. Tranches are 100 ticks, stored as int16. +along the price dimension and int16. Tranches are 25 ticks, stored as int16. Leafs (uint16) split the sat, which is uint112, into intervals. From left to right, the leafs of the tree cover the sat space in increasing order. Each account with a position has a price at which its LTV would reach LTVMAX, which is its liquidation (=liq) price. To place a debt into the appropriate tranche, we think of each debt and its respective -collateral as a serries of sums, where each item in the series fits in one tranche. Using +collateral as a series of sums, where each item in the series fits in one tranche. Using formulas above, we determine the number of ticks a debt would cross if liquidated. This is considered the span of the liquidation. Using this value we then determine the start and end points of the liquidation, where the start would be closer to the prices, on the right of the end for net debt of x and on the left of the end for net debt of Y. -Once we have the liquidation start, end, and span, we begin to place the debt, one tranche at -a time moving towards the price. In this process we compare the prior recorded saturation and +Once we have the liquidation start, end, and span, we begin to place the debt, one tranche at a +time moving towards the price. In this process we compare the prior recorded saturation and allow the insertion up to some max, set at 90% or the configuration set by the user. -A Tranche contains multiple accounts and thus a total sat. The tranches' sat assigns it to a +A Tranche contains multiple accounts and thus a total sat. The tranche's sat assigns it to a leaf. Each leaf can contain multiple tranches and thus has a total actual sat whilst representing a specific sat per tranche range. Leafs and thus tranches and thus accounts above a certain sat threshold are considered over saturated. These accounts are penalized for being in an over saturated tranche. Each account, tranche and leaf has a total penalty that needs to -be repaid to flatten the position fully. Sat is distributed over multiple tranches, in case a +be repaid to close the position fully. Sat is distributed over multiple tranches, in case a single tranche does not have enough available sat left. Sat is kept cumulatively in the tree, meaning a node contains the sum of the sat of its parents. Updating a sat at the bottom of the tree requires updating all parents. Penalty is kept as a path sum, in uints of LAssets, meaning @@ -59,10 +65,79 @@ the penalty of an account is the sum of the penalties of all its parents. Updati for a range of leafs only requires updating the appropriate parent. Position (=pos) refers to the relative index of a child within its parent. Index refers to the index of a node in within its level +The formula for allocating saturation is derived from, +```math +\begin{align*} +X = L \cdot \left( b^{t_e} - b^{t_s} \right) \\ +Y = L \cdot \left( \frac{1}{b^{t_s}} - \frac{1}{b^{t_e}} \right) +\end{align*} +``` +for the start and end of liquidation $$t_s$$ and $$t_e$$ respectively. When we consider our +buckets of TICKS_PER_TRANCHE we can rewrite this as a series where each boundary of each +tranche $$T_i$$ where $$T_0 = t_e \% TICKS_PER_TRANCHE$$ for a net debt of X and $$T_0 = (-t_e) +\% TICKS_PER_TRANCHE$$ for a net debt of Y and $$T_i = T_{i-1} + TICKS_PER_TRANCHE$$ for each +subsequent tranche and $$B= b^{TICKS_PER_TRANCHE}$$. Thus we can rewrite the equations as: +```math +\begin{align*} +X &= +L \left(b^{T_1} - b^{t_e} \right) ++ L \left( b^{T_2} - b^{T_1}\right) ++ ... ++ L \left( b^{T_n} - b^{T_{n-1}}\right) ++ L \left(b^{t_s}-b^{T_n} \right) +\\ +\Large\frac{X}{b^{t_e}(B-1)} &= +\Large L \left( +\frac{B \cdot b^{t_e-T_0} - 1}{B-1} ++ \frac{ \sum_{i=1}^{n-1} B^{i} }{ b^{t_e-T_0} } ++ \frac{B^{n} \left( +\frac{b^{t_s}}{B^{n} \cdot b^{T_0}}-1 \right) }{ b^{t_e-T_0}(B-1)} +\right) +\end{align*} +``` +We then define the left side of this equation as total saturation $T_{sat}$ or newSaturation as +we call it in the parameter passed in. Saturation is relative to the saturation in one tranche. +The right side of the equation defines the saturation in each tranche $s_i$, starting at the +furthest point from the tranche and moving forward. +```math +\begin{align*} +T_{sat} &= +s_0 ++ \frac{\sum_{i=1}^{n-1} s_i \cdot B^{i}}{b^{t_e-T_0}} ++ \frac{B^n \cdot s_n}{b^{t_e-T_0}} +\\ +\frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 &= +\left(\sum_{i=2}^{n-1} s_i \cdot B^{i-1} \right) ++ B^{n-1} \cdot s_n +\\ +\frac{\frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 }{ B } -s_2 &= +\left(\sum_{i=2}^{n-1} s_i \cdot B^{i-2} \right) ++ B^{n-2} \cdot s_n +\end{align*} +``` +When calculating the case for Y, the result is almost identical, except our definition for +$T_{sat}$ requires us to multiply by $$b^{t_e}$$ rather than divide. +The above shows the logic applied in this function. We can allocate saturation across each +tranche until the total remaining saturation is depleted. We allow less than the ideal +saturation to be consumed if there is less available. Extra saturation is then carried forward +to tranches closer to the price, requiring part of the position to be liquidated sooner as +needed based on the available liquidity. +Two critical nuances of this algorithm is that we reduce by a factor of $$B$$ after each +iteration and we multiply one time by $$b^{t_e - T_0}$$ after we allocate $$s_0$$ one time. The +reduction of $$B$$ each iteration reflects the increase in the size of each tranche relative to +a unit of X or Y as you move from one tranche to the next towards the price. The one time +multiplication of $$b^{t_e - T_0}$$ is an adjustment for the offset of the start of liquidation +relative to the start of the second tranche to minimize the impact of the reduction by $$B$$ +since the first portion of saturation does not use an entire tranche. +If saturation reaches the minOrMaxTick, we revert as the position is already reaching the limit +of our probable price range and may require immediate liquidation if opened. ## State Variables ### SATURATION_TIME_BUFFER_IN_MAG2 +time budget added to sat before adding it to the tree; compensates for the fact that +the liq price moves closer to the current price over time. + ```solidity uint256 internal constant SATURATION_TIME_BUFFER_IN_MAG2 = 101; @@ -70,6 +145,10 @@ uint256 internal constant SATURATION_TIME_BUFFER_IN_MAG2 = 101; ### MAX_SATURATION_RATIO_IN_MAG2 +percentage of max sat per tranche considered healthy; max sat per +tranche is $$liquidity \frac{B-1}{2}$$ with B the tranche basis, which is the max +sat such that the liquidation would not cause a swap larger than a tranche + ```solidity uint256 internal constant MAX_SATURATION_RATIO_IN_MAG2 = 95; @@ -77,6 +156,8 @@ uint256 internal constant MAX_SATURATION_RATIO_IN_MAG2 = 95; ### START_SATURATION_PENALTY_RATIO_IN_MAG2 +percentage of max sat per tranche where penalization begins + ```solidity uint256 internal constant START_SATURATION_PENALTY_RATIO_IN_MAG2 = 85; @@ -84,6 +165,8 @@ uint256 internal constant START_SATURATION_PENALTY_RATIO_IN_MAG2 = 85; ### MAX_INITIAL_SATURATION_MAG2 +maximum initial saturation percentage when adding a new position + ```solidity uint256 internal constant MAX_INITIAL_SATURATION_MAG2 = 90; @@ -91,6 +174,8 @@ uint256 internal constant MAX_INITIAL_SATURATION_MAG2 = 90; ### EXPECTED_SATURATION_LTV_MAG2 +The amount of LTV we expect liquidations to occur at + ```solidity uint256 internal constant EXPECTED_SATURATION_LTV_MAG2 = 85; @@ -98,6 +183,9 @@ uint256 internal constant EXPECTED_SATURATION_LTV_MAG2 = 85; ### EXPECTED_SATURATION_LTV_MAG2_TIMES_SAT_BUFFER_SQUARED +$$EXPECTED_SATURATION_LTV_MAG2 * SATURATION_TIME_BUFFER_IN_MAG2 ** 2$$, a constant +used in calculations. + ```solidity uint256 internal constant EXPECTED_SATURATION_LTV_MAG2_TIMES_SAT_BUFFER_SQUARED = 867_085; @@ -105,20 +193,18 @@ uint256 internal constant EXPECTED_SATURATION_LTV_MAG2_TIMES_SAT_BUFFER_SQUARED ### EXPECTED_SATURATION_LTV_PLUS_ONE_MAG2 - -```solidity -uint256 internal constant EXPECTED_SATURATION_LTV_PLUS_ONE_MAG2 = 185; -``` +$$EXPECTED_SATURATION_LTV_MAG2 + 100$$, a constant used in calculations. -### PENALTY_FACTOR_IN_MAG2 - ```solidity -uint256 private constant PENALTY_FACTOR_IN_MAG2 = 10; +uint256 internal constant EXPECTED_SATURATION_LTV_PLUS_ONE_MAG2 = 185; ``` ### SAT_CHANGE_OF_BASE_Q128 +a constant used to change the log base from the tick math base to the saturation to +leaf base. + ```solidity uint256 private constant SAT_CHANGE_OF_BASE_Q128 = 0xa39713406ef781154a9e682c2331a7c03; @@ -126,6 +212,9 @@ uint256 private constant SAT_CHANGE_OF_BASE_Q128 = 0xa39713406ef781154a9e682c233 ### SAT_CHANGE_OF_BASE_TIMES_SHIFT +a constant used to shift when changing the base from tick math base to the +saturation leaf base. + ```solidity uint256 private constant SAT_CHANGE_OF_BASE_TIMES_SHIFT = 0xb3f2fb93ad437464387b0c308d1d05537; @@ -133,6 +222,8 @@ uint256 private constant SAT_CHANGE_OF_BASE_TIMES_SHIFT = 0xb3f2fb93ad437464387b ### TICK_OFFSET +tick offset added to ensure leaf calculation starts from 0 at the lowest leaf + ```solidity int16 private constant TICK_OFFSET = 1112; @@ -140,6 +231,9 @@ int16 private constant TICK_OFFSET = 1112; ### LOWEST_POSSIBLE_IN_PENALTY +the lowest possible saturation is always in penalty +$$MAX_ASSETS * START_SATURATION_PENALTY_RATIO_IN_MAG2 / TICKS_PER_TRANCHE$$ + ```solidity uint256 internal constant LOWEST_POSSIBLE_IN_PENALTY = 0xd9999999999999999999999999999999; @@ -147,6 +241,9 @@ uint256 internal constant LOWEST_POSSIBLE_IN_PENALTY = 0xd9999999999999999999999 ### MIN_LIQ_TO_REACH_PENALTY +the minimum liquidity to reach the possibility of being in penalty. +$$MINIMUM_LIQUIDITY * START_SATURATION_PENALTY_RATIO_IN_MAG2 / TICKS_PER_TRANCHE$$ + ```solidity uint256 private constant MIN_LIQ_TO_REACH_PENALTY = 850; @@ -154,6 +251,8 @@ uint256 private constant MIN_LIQ_TO_REACH_PENALTY = 850; ### INT_ONE +Constant number one as an int type. Used for rounding or iterating direction. + ```solidity int256 private constant INT_ONE = 1; @@ -161,6 +260,8 @@ int256 private constant INT_ONE = 1; ### INT_NEGATIVE_ONE +Constant number negative one. Used for rounding or iterating direction. + ```solidity int256 private constant INT_NEGATIVE_ONE = -1; @@ -168,6 +269,8 @@ int256 private constant INT_NEGATIVE_ONE = -1; ### INT_ZERO +Constant number zero as an int type. Used for rounding or iterating direction. + ```solidity int256 private constant INT_ZERO = 0; @@ -175,6 +278,8 @@ int256 private constant INT_ZERO = 0; ### LEVELS_WITHOUT_LEAFS +Tree leafs are on level LEVELS_WITHOUT_LEAFS; root is level 0 + ```solidity uint256 internal constant LEVELS_WITHOUT_LEAFS = 3; @@ -182,6 +287,8 @@ uint256 internal constant LEVELS_WITHOUT_LEAFS = 3; ### LOWEST_LEVEL_INDEX +for convenience, since used a lot, ==LEVELS_WITHOUT_LEAFS - 1 + ```solidity uint256 internal constant LOWEST_LEVEL_INDEX = 2; @@ -189,6 +296,8 @@ uint256 internal constant LOWEST_LEVEL_INDEX = 2; ### LEAFS +$$1 << LEAFS_IN_BITS$$ + ```solidity uint256 internal constant LEAFS = 4096; @@ -196,6 +305,8 @@ uint256 internal constant LEAFS = 4096; ### CHILDREN_PER_NODE +$$1 << 4$$ + ```solidity uint256 internal constant CHILDREN_PER_NODE = 16; @@ -203,6 +314,8 @@ uint256 internal constant CHILDREN_PER_NODE = 16; ### CHILDREN_AT_THIRD_LEVEL +$$1 << (2 * 4)$$ + ```solidity uint256 private constant CHILDREN_AT_THIRD_LEVEL = 256; @@ -210,13 +323,19 @@ uint256 private constant CHILDREN_AT_THIRD_LEVEL = 256; ### TICKS_PER_TRANCHE +$$Bt = (1 - 2^{-9})^{-1}$$ is the base for ticks, then the tranche base is +$$BT = Bt^TICKS_PER_TRANCHE$$, int only to not need casting below, equals TICKS_PER_TRANCHE + ```solidity -int256 private constant TICKS_PER_TRANCHE = 100; +int256 private constant TICKS_PER_TRANCHE = 25; ``` ### TRANCHE_BASE_OVER_BASE_MINUS_ONE_Q72 +for convenience, used to determine max sat per tranche to not cross in liq swap: +$$\frac{B}{B-1}$$ + ```solidity uint256 constant TRANCHE_BASE_OVER_BASE_MINUS_ONE_Q72 = 0x5a19b9039a07efd7b39; @@ -224,20 +343,27 @@ uint256 constant TRANCHE_BASE_OVER_BASE_MINUS_ONE_Q72 = 0x5a19b9039a07efd7b39; ### MIN_TRANCHE +`TickMath.MIN_TICK / TICKS_PER_TRANCHE - 1;` // -1 to floor + ```solidity -int256 internal constant MIN_TRANCHE = -199; +int256 internal constant MIN_TRANCHE = -795; ``` ### MAX_TRANCHE +`TickMath.MAX_TICK / TICKS_PER_TRANCHE;` + ```solidity -int256 internal constant MAX_TRANCHE = 198; +int256 internal constant MAX_TRANCHE = 794; ``` ### FIELD_NODE_MASK +constants for bit reading and writing in nodes. +`type(uint256).max >> (TOTAL_BITS - FIELD_BITS);` + ```solidity uint256 private constant FIELD_NODE_MASK = 0xffff; @@ -245,65 +371,104 @@ uint256 private constant FIELD_NODE_MASK = 0xffff; ### SATURATION_MAX_BUFFER_TRANCHES +Buffer space (in tranches) allowed above the highest used tranche before hitting +maxLeaf limit + ```solidity uint8 internal constant SATURATION_MAX_BUFFER_TRANCHES = 3; ``` -### QUARTER_MINUS_ONE +### QUARTER_OF_MAG2 +Twenty-five percent magnitude of two. + ```solidity -uint256 private constant QUARTER_MINUS_ONE = 24; +uint256 private constant QUARTER_OF_MAG2 = 25; ``` -### QUARTER_OF_MAG2 +### QUARTER_MINUS_ONE +Twenty-five percent minus one magnitude of two. + ```solidity -uint256 private constant QUARTER_OF_MAG2 = 25; +uint256 private constant QUARTER_MINUS_ONE = 24; ``` ### NUMBER_OF_QUARTERS +quarters per tranche. + ```solidity uint256 private constant NUMBER_OF_QUARTERS = 4; ``` -### SOFT_LIQUIDATION_SCALER +### SATURATION_LIQUIDATION_SCALER +We make the penalty slightly larger to hit our desired premium for exceeding the +time buffer. + ```solidity -uint256 private constant SOFT_LIQUIDATION_SCALER = 10_020; +uint256 private constant SATURATION_LIQUIDATION_SCALER = 10_020; ``` -### TWO_Q64 +### TWO_Q72 +$$2 * 2**72 * 2$$, used in saturation formula. + ```solidity -uint256 private constant TWO_Q64 = 0x20000000000000000; +uint256 private constant TWO_Q72 = 0x2000000000000000000; ``` -### FOUR_Q128 +### FOUR_Q144 +$$4 * 2**128$$, needed in quadratic formula is saturation. + ```solidity -uint256 private constant FOUR_Q128 = 0x400000000000000000000000000000000; +uint256 private constant FOUR_Q144 = 0x4000000000000000000000000000000000000; ``` -### MAG4_TIMES_Q64 +### MAG4_TIMES_Q72 +$$MAG4 * Q72$$ constant needed in formula. + ```solidity -uint256 private constant MAG4_TIMES_Q64 = 0x27100000000000000000; +uint256 private constant MAG4_TIMES_Q72 = 0x2710000000000000000000; ``` -### B_Q72_MINUS_ONE +### B_SQUARED_Q72_MINUS_ONE +$$b^2 \cdot Q72 - 1$$ used to round up results of `TickMath.getTickAtPrice()`. + ```solidity -uint256 private constant B_Q72_MINUS_ONE = 0x1008040201008040200; +uint256 private constant B_SQUARED_Q72_MINUS_ONE = 0x10100c08050301c1008; +``` + + +### Q183 +A large number that will not overflow when multiplied by `B_SQUARED_Q72_MINUS_ONE` +$$\left\lfloor \frac{ 2^{ 256 } }{ B_SQUARED_Q72_MINUS_ONE } \right\rfloor$$ + + +```solidity +uint256 private constant Q183 = 0x8000000000000000000000000000000000000000000000; +``` + + +### TICKS_PER_TRANCHE_MAG2 +$$TICKS_PER_TRANCHE * MAG2$$ used for calculating available liquidity. + + +```solidity +uint256 private constant TICKS_PER_TRANCHE_MAG2 = 2500; ``` @@ -346,7 +511,8 @@ function initTree( ### update -update the borrow position of an account and potentially check (and revert) if the resulting sat is too high +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* @@ -356,7 +522,9 @@ function update( SaturationStruct storage satStruct, Validation.InputParams memory inputParams, address account, - uint256 userSaturationRatioMAG2 + uint256 fragileLiquidityAssets, + uint256 userSaturationRatioMAG2, + bool skipMinOrMaxTickCheck ) internal; ``` **Parameters** @@ -366,12 +534,15 @@ function update( |`satStruct`|`SaturationStruct`| main data struct| |`inputParams`|`Validation.InputParams`| contains the position and pair params, like account borrows/deposits, current price and active liquidity| |`account`|`address`| for which is position is being updated| +|`fragileLiquidityAssets`|`uint256`|| |`userSaturationRatioMAG2`|`uint256`|| +|`skipMinOrMaxTickCheck`|`bool`|| ### updateTreeGivenAccountTrancheAndSat -internal update that removes the account from the tree (if it exists) from its prev position and adds it to its new position +internal update that removes the account from the tree (if it exists) from its prev +position and adds it to its new position ```solidity @@ -381,6 +552,7 @@ function updateTreeGivenAccountTrancheAndSat( address account, int256 newEndOfLiquidationInTicks, uint256 activeLiquidityInLAssets, + int256 minOrMaxTick, uint256 userSaturationRatioMAG2 ) internal; ``` @@ -393,6 +565,7 @@ function updateTreeGivenAccountTrancheAndSat( |`account`|`address`| whos position is being considered| |`newEndOfLiquidationInTicks`|`int256`|the new tranche of the account in mag2.| |`activeLiquidityInLAssets`|`uint256`| of the pair| +|`minOrMaxTick`|`int256`|| |`userSaturationRatioMAG2`|`uint256`|| @@ -402,19 +575,14 @@ remove sat from tree, for each tranche in a loop that could hold sat for the acc ```solidity -function removeSatFromTranche( - Tree storage tree, - address account, - int256 trancheDirection -) internal returns (bool highestSetLeafRemoved); +function removeSatFromTranche(Tree storage tree, address account) internal returns (bool highestSetLeafRemoved); ``` **Parameters** |Name|Type|Description| |----|----|-----------| |`tree`|`Tree`|that is being read from or written to| -|`account`|`address`|whos position is being considered| -|`trancheDirection`|`int256`| direction of sat distribution depending on netX/netY| +|`account`|`address`|whose position is being considered| **Returns** @@ -425,7 +593,8 @@ function removeSatFromTranche( ### removeSatFromTrancheStateUpdates -depending on old and new leaf of the tranche, update the sats, fields and penalties of the tree +depending on old and new leaf of the tranche, update the sats, fields and penalties +of the tree ```solidity @@ -452,27 +621,46 @@ function removeSatFromTrancheStateUpdates( ### addSatToTranche -add sat to tree, for each tranche in a loop as needed. we add to each tranche as much as it can bear. +add sat to tree, for each tranche in a loop as needed. we add to each tranche as +much as it can bear. *Saturation Distribution Logic -This function distributes debt across multiple tranches, maintaining two types of saturation: +This function distributes debt across multiple tranches, maintaining two types of +saturation: 1. satInLAssets: The absolute debt amount in L assets (should remain constant total) 2. satRelativeToL: The relative saturation that depends on the tranche's price level As we move between tranches (different price levels), the same absolute debt translates to different relative saturations due to the price-dependent formula. conceptually satInLAssets should not be scaled as it represents actual debt that -doesn't change with price.* +doesn't change with price. +The formula applied here, derived in the introduction, is, +```math +\begin{align*} +T_{sat} &= +s_0 ++ \frac{\sum_{i=1}^{n-1} s_i \cdot B^{i}}{b^{t_e-T_0}} ++ \frac{B^n \cdot s_n}{b^{t_e-T_0}} +\\ +\frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 &= +\left(\sum_{i=2}^{n-1} s_i \cdot B^{i-1} \right) ++ B^{n-1} \cdot s_n +\\ +\frac{\frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 }{ B } -s_2 &= +\left(\sum_{i=2}^{n-1} s_i \cdot B^{i-2} \right) ++ B^{n-2} \cdot s_n +\end{align*} +```* ```solidity function addSatToTranche( Tree storage tree, address account, - int256 trancheDirection, int256 newEndOfLiquidationInTicks, SaturationPair memory newSaturation, uint256 activeLiquidityInLAssets, - uint256 userSaturationRatioMAG2 + uint256 userSaturationRatioMAG2, + int256 minOrMaxTick ) internal returns (bool highestSetLeafAdded); ``` **Parameters** @@ -480,12 +668,12 @@ function addSatToTranche( |Name|Type|Description| |----|----|-----------| |`tree`|`Tree`|that is being read from or written to| -|`account`|`address`|who's position is being considered| -|`trancheDirection`|`int256`|direction of sat distribution depending on netX/netY| +|`account`|`address`|whose position is being considered| |`newEndOfLiquidationInTicks`|`int256`|the new tranche of the account location in MAG2| |`newSaturation`|`SaturationPair`|the new sat of the account, in units of LAssets (absolute) and relative to active liquidity| |`activeLiquidityInLAssets`|`uint256`|of the pair| |`userSaturationRatioMAG2`|`uint256`|| +|`minOrMaxTick`|`int256`|| **Returns** @@ -494,6 +682,28 @@ function addSatToTranche( |`highestSetLeafAdded`|`bool`|flag indicating whether we removed sat from the highest leaf xor not| +### getUsableTicksAndLastTranche + + +```solidity +function getUsableTicksAndLastTranche( + int256 endOfLiquidationTick, + bool netDebtX +) internal pure returns (uint256 usableTicks, int256 lastTranche); +``` + +### restrictUsableTicksForMinOrMaxTick + + +```solidity +function restrictUsableTicksForMinOrMaxTick( + uint256 initialUsableTicks, + int256 nextTranche, + int256 minOrMaxTick, + bool netDebtX +) internal pure returns (uint256 usableTicks); +``` + ### getAddSatToTrancheStateUpdatesParams convenience struct holding the params needed to run `addSatToTrancheStateUpdates` @@ -502,12 +712,12 @@ convenience struct holding the params needed to run `addSatToTrancheStateUpdates ```solidity function getAddSatToTrancheStateUpdatesParams( Tree storage tree, + address account, int256 tranche, SaturationPair memory newSaturation, uint256 activeLiquidityInLAssets, - address account, uint256 userSaturationRatioMAG2, - uint256 quarters + uint256 usableTicks ) internal view returns (AddSatToTrancheStateUpdatesStruct memory addSatToTrancheStateUpdatesParams); ``` **Parameters** @@ -515,12 +725,12 @@ function getAddSatToTrancheStateUpdatesParams( |Name|Type|Description| |----|----|-----------| |`tree`|`Tree`|that is being read from or written to| +|`account`|`address`|whose position is being considered| |`tranche`|`int256`|under consideration| |`newSaturation`|`SaturationPair`|the saturation values to add| |`activeLiquidityInLAssets`|`uint256`|of the pair| -|`account`|`address`|whos position is being considered| |`userSaturationRatioMAG2`|`uint256`|user saturation ratio| -|`quarters`|`uint256`|number of quarters for the calculation| +|`usableTicks`|`uint256`|number of ticks available to use| **Returns** @@ -531,7 +741,8 @@ function getAddSatToTrancheStateUpdatesParams( ### addSatToTrancheStateUpdates -depending on old and new leaf of the tranche, update the sats, fields and penalties of the tree +depending on old and new leaf of the tranche, update the sats, fields and penalties +of the tree ```solidity @@ -627,14 +838,15 @@ recursively add sat up the tree ```solidity -function addSatUpTheTree(Tree storage tree, int256 satInLAssets) internal; +function addSatUpTheTree(Tree storage tree, uint128 satInLAssets, bool add) internal; ``` **Parameters** |Name|Type|Description| |----|----|-----------| |`tree`|`Tree`|that is being read from or written to| -|`satInLAssets`|`int256`| sat to add to the current node, usually uint112, int to allow subtracting sat up the tree| +|`satInLAssets`|`uint128`| sat to add to the current node, usually uint112, int to allow subtracting sat up the tree| +|`add`|`bool`|| ### updatePenalties @@ -685,7 +897,8 @@ function getPenaltySharesPerSatFromLeaf( ### accrueAccountPenalty -calc penalty owed by account for repay, total over all the tranches that might contain this accounts' sat +calc penalty owed by account for repay, total over all the tranches that might +contain this accounts' sat ```solidity @@ -696,7 +909,7 @@ function accrueAccountPenalty(Tree storage tree, address account) internal retur |Name|Type|Description| |----|----|-----------| |`tree`|`Tree`|that is being read from or written to| -|`account`|`address`| who's position is being considered| +|`account`|`address`| whose position is being considered| **Returns** @@ -705,9 +918,27 @@ function accrueAccountPenalty(Tree storage tree, address account) internal retur |`penaltyInBorrowLShares`|`uint256`| the penalty owed by the account| +### trancheDirection + +move in the appropriate direction when iterating. + + +```solidity +function trancheDirection( + bool netDebtX +) private pure returns (int256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`netDebtX`|`bool`|direction flag| + + ### calcNewAccountPenalty -calc penalty owed by account for repay, total over all the tranches that might contain this accounts' sat +calc penalty owed by account for repay, total over all the tranches that might +contain this accounts' sat ```solidity @@ -726,7 +957,7 @@ function calcNewAccountPenalty( |`tree`|`Tree`|that is being read from or written to| |`leaf`|`uint256`| the leaf that the tranche belongs to| |`accountSatInTrancheInLAssets`|`uint256`| the sat of the account in the tranche| -|`account`|`address`| who's position is being considered| +|`account`|`address`| whose position is being considered| |`trancheIndex`|`uint256`| the index of the tranche that is being added to| **Returns** @@ -759,7 +990,7 @@ function calcAndAccrueNewAccountPenalty( |`tree`|`Tree`|that is being read from or written to| |`oldAccountSaturationInTranche`|`SaturationPair`| the old sat of the account in the tranche| |`oldLeaf`|`uint256`| the leaf that the tranche was located in before it was removed| -|`account`|`address`| who's position is being considered| +|`account`|`address`| whose position is being considered| |`trancheIndex`|`uint256`| the index of the tranche that is being added to| |`newTreePenaltyAtOnsetInBorrowLSharesPerSatInQ72PerTranche`|`uint256`| the new penalty at onset in borrow l shares per sat in q72 per tranche| @@ -785,7 +1016,7 @@ function accruePenalties( |Name|Type|Description| |----|----|-----------| |`satStruct`|`SaturationStruct`| main data struct| -|`account`|`address`| who's position is being considered| +|`account`|`address`| whose position is being considered| |`externalLiquidity`|`uint256`| Swap liquidity outside this pool| |`duration`|`uint256`| since last accrual of penalties| |`allAssetsDepositL`|`uint256`| allAsset[DEPOSIT_L]| @@ -900,7 +1131,7 @@ function accrueAndRemoveAccountPenalty( |Name|Type|Description| |----|----|-----------| |`satStruct`|`SaturationStruct`| main data struct| -|`account`|`address`| who's position is being considered| +|`account`|`address`| whose position is being considered| **Returns** @@ -918,31 +1149,27 @@ calculate the max liquidation premium in bips for a hard liquidation uses the tr ```solidity function calculateHardLiquidationPremium( - Saturation.SaturationStruct storage satStruct, + Account memory account, Validation.InputParams memory inputParams, - address borrower, uint256 netBorrowRepaidLAssets, - uint256 netDepositSeizedLAssets, - bool netDebtX -) internal view returns (uint256 maxPremiumInBips, bool allAssetsSeized); + uint256 netDepositSeizedLAssets +) internal pure returns (uint256 maxPremiumInBips, bool allAssetsSeized); ``` **Parameters** |Name|Type|Description| |----|----|-----------| -|`satStruct`|`Saturation.SaturationStruct`| main data struct| +|`account`|`Account`| borrower account from the SaturationStruct| |`inputParams`|`Validation.InputParams`| all user assets and prices| -|`borrower`|`address`|| |`netBorrowRepaidLAssets`|`uint256`| net debt repaid in liquidity assets| |`netDepositSeizedLAssets`|`uint256`| net collateral seized in liquidity assets| -|`netDebtX`|`bool`| whether net debt is in X or Y| **Returns** |Name|Type|Description| |----|----|-----------| |`maxPremiumInBips`|`uint256`| the max premium in bips that| -|`allAssetsSeized`|`bool`|| +|`allAssetsSeized`|`bool`| whether all assets where seized or not| ### mutateInputParamsForPartialLiquidation @@ -953,22 +1180,18 @@ calculation ```solidity function mutateInputParamsForPartialLiquidation( - Saturation.SaturationStruct storage satStruct, + Account memory account, Validation.InputParams memory inputParams, - address borrower, - uint256 netBorrowRepaidLAssets, - bool netDebtX -) internal view returns (uint256 netDepositInLAssets); + uint256 netBorrowRepaidLAssets +) internal pure returns (uint256 netDepositInLAssets); ``` **Parameters** |Name|Type|Description| |----|----|-----------| -|`satStruct`|`Saturation.SaturationStruct`| main data struct| +|`account`|`Account`|borrowers saturation account| |`inputParams`|`Validation.InputParams`| all user assets and prices| -|`borrower`|`address`| borrower address| |`netBorrowRepaidLAssets`|`uint256`| net debt in liquidity assets| -|`netDebtX`|`bool`| whether net debt is in X or Y| ### calcPortionsForPartialLiquidation @@ -980,11 +1203,9 @@ Calculate the percent of debt and collateral that is eligible for ltv calculatio ```solidity function calcPortionsForPartialLiquidation( - Saturation.SaturationStruct storage satStruct, - address borrower, - uint256 netBorrowRepaidLAssets, - bool netDebtX -) internal view returns (uint256 partialBorrow, uint256 totalBorrow, uint256 partialDeposit, uint256 totalDeposit); + Account memory account, + uint256 netBorrowRepaidLAssets +) internal pure returns (uint256 partialBorrow, uint256 totalBorrow, uint256 partialDeposit, uint256 totalDeposit); ``` ### setXorUnsetFieldBitUpTheTree @@ -1014,7 +1235,8 @@ function setXorUnsetFieldBitUpTheTree( ### findHighestSetLeafUpwards -recursive function to find the highest set leaf starting from a leaf, first upwards, until a set field is found, then downwards to find the best set leaf +recursive function to find the highest set leaf starting from a leaf, first +upwards, until a set field is found, then downwards to find the best set leaf ```solidity @@ -1072,11 +1294,13 @@ function findHighestSetLeafDownwards( Calc sqrt price at which positions' LTV would reach LTV_MAX -Output guarantees $ 0 \le liqSqrtPriceXInQ72 \le uint256(type(uint56).max) << 72 $ (fuzz tested and logic) +Output guarantees $$0 \le liqSqrtPriceXInQ72 \le uint256(type(uint56).max) << 72$$ +(fuzz tested and logic) Outside above range, outputs 0 (essentially no liq) -Does not revert if $ LTV_MAX < LTV $, rather $ LTV_MAX < LTV $ causing liq points are returned as 0, as if they do not exist, based on the assumption $ LTV \le LTV_MAX $ +Does not revert if `LTV_MAX < LTV`, rather `LTV_MAX < LTV` causing liq points are +returned as 0, as if they do not exist, based on the assumption `LTV \le LTV_MAX` ```solidity @@ -1100,7 +1324,8 @@ function calcLiqSqrtPriceQ72( ### calcLiqSqrtPriceQ72HandleAllABCNonZero -calc liq price when the quadratic has all 3 terms, netY,netL,netX, i.e. X, Y, L are all significant +calc liq price when the quadratic has all 3 terms, netY,netL,netX, i.e. X, Y, L are +all significant ```solidity @@ -1126,6 +1351,10 @@ function calcLiqSqrtPriceQ72HandleAllABCNonZero( Calculate the ratio by which the saturation has changed for `account`. +*the algorithm here matches that of `addSatToTranche()`, but accumulates the total +saturation to compare it to what is needed. If the allocated total saturation is less than +what is needed, we return the ratio to help determine the saturation adjustment premium.* + ```solidity function calcSatChangeRatioBips( @@ -1156,18 +1385,45 @@ function calcSatChangeRatioBips( |`ratioNetYBips`|`uint256`|The ratio representing the change in netY saturation for account.| +### calculateEndOfLiquidationAdjustment + +a helper function to calculate the one time adjustment for the offset of the end +of the liquidation relative to the the boundary of the tranches. + +*This formula is described in the introduction.* + + +```solidity +function calculateEndOfLiquidationAdjustment( + int256 endOfLiquidationInTicks +) private pure returns (uint256 endOfLiquidationSqrtPriceAdjustment); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`endOfLiquidationInTicks`|`int256`| the tick at which liquidation should end by.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`endOfLiquidationSqrtPriceAdjustment`|`uint256`| the sqrt price adjustment required to be applied.| + + ### calcTotalSatAfterLeafInclusive calc total sat of all accounts/tranches/leafs higher (and same) as the threshold -*iterate through leaves directly since penalty range is fixed (~8 leaves from 85% to 95% sat)* +*iterate through leaves directly since penalty range is fixed (~8 leaves from 85% to +95% sat)* ```solidity function calcTotalSatAfterLeafInclusive( Tree storage tree, uint256 thresholdLeaf -) internal view returns (uint128 satInLAssetsInPenalty); +) internal view returns (uint128 satInPenaltyInLAssets); ``` **Parameters** @@ -1180,7 +1436,7 @@ function calcTotalSatAfterLeafInclusive( |Name|Type|Description| |----|----|-----------| -|`satInLAssetsInPenalty`|`uint128`|total sat of all accounts with tranche in a leaf from at least `thresholdLeaf` (absolute saturation)| +|`satInPenaltyInLAssets`|`uint128`|total sat of all accounts with tranche in a leaf from at least `thresholdLeaf` (absolute saturation)| ### getSatPercentageInWads @@ -1233,63 +1489,132 @@ function satToLeaf( calc how much sat can be added to a tranche such that it is healthy +*There are some important properties of the relationships between the returned values +and the input values, specifically the input `newSaturationRelativeToLAssets` and the +return values `satAvailableToAddRelativeToLAssets` and `targetCapacityRelativeToLAssets`. +For brevity we call these `newSat`, `satAvailable`, and `target` respectively in the +explanation below, +Three cases, +1) $$newSat > trancheSat$$, +2) $$trancheSat >= newSat >= trancheSat - currentTrancheSat$$ +3) $$trancheSat - currentTrancheSat > newSat$$ +if (1) $$newSat > trancheSat $$ then +$$satAvailable = trancheSat - currentTrancheSat$$ +$$target = trancheSat$$ +therefore $$target >= satAvailable$$ +if (2) $$trancheSat >= newSat >= trancheSat - currentTrancheSat$$ then +$$satAvailable = trancheSat - currentTrancheSat$$ +$$target = newSat$$ +therefore $$target >= satAvailable$$ since $$newSat >= trancheSat - currentTrancheSat$$ +if (3) $$trancheSat - currentTrancheSat > newSat$$ then +$$satAvailable = newSat$$ +$$target = newSat$$ +therefore $$target = satAvailable$$ +In all cases $$target >= satAvailable$$. +Also, we know by the limiting $$target = min(trancheSat, newSat)$$ that +$$newSat >= target$$* + ```solidity function calcSatAvailableToAddToTranche( uint256 activeLiquidityInLAssets, - uint128 targetSatToAddInLAssets, - uint128 currentTrancheSatInLAssets, + uint128 newSaturationRelativeToLAssets, + uint128 currentTrancheSatRelativeToLAssets, uint256 userSaturationRatioMAG2, - uint256 quarters -) internal pure returns (uint128 satAvailableToAddInLAssets); + uint256 usableTicks +) internal pure returns (uint128 satAvailableToAddRelativeToLAssets, uint256 targetCapacityRelativeToLAssets); ``` **Parameters** |Name|Type|Description| |----|----|-----------| |`activeLiquidityInLAssets`|`uint256`| of the pair| -|`targetSatToAddInLAssets`|`uint128`| the sat that we want to add| -|`currentTrancheSatInLAssets`|`uint128`| the sat that the tranche already hols| -|`userSaturationRatioMAG2`|`uint256`|| -|`quarters`|`uint256`|| +|`newSaturationRelativeToLAssets`|`uint128`| the sat that we want to add| +|`currentTrancheSatRelativeToLAssets`|`uint128`| the sat that the tranche already holds| +|`userSaturationRatioMAG2`|`uint256`| the user's desired saturation ratio| +|`usableTicks`|`uint256`| the number of usable ticks within the tranche, restricted by either the end of liquidation or the min/max tick.| **Returns** |Name|Type|Description| |----|----|-----------| -|`satAvailableToAddInLAssets`|`uint128`| considering the `currentTrancheSatInLAssets` and the max a tranche can have| +|`satAvailableToAddRelativeToLAssets`|`uint128`| considering the `currentTrancheSatRelativeToLAssets` and the max a tranche can have| +|`targetCapacityRelativeToLAssets`|`uint256`|| -### calcLastTrancheAndSaturation +### calcLastTickAndSaturation -calc the tranche percent and the saturation of the tranche +calc the tick at which the best case liquidation would end and the saturation of +the last tranche containing that tick. Not all the saturation may fit into that tranche, +but we calculate it as if it will which means that adjustments to the saturation will need +to be made if it doesn't fit when placing it into the tree. ```solidity -function calcLastTrancheAndSaturation( +function calcLastTickAndSaturation( Validation.InputParams memory inputParams, - uint256 liqSqrtPriceInXInQ72, + uint256 netXLiqSqrtPriceInXInQ72, + uint256 netYLiqSqrtPriceInXInQ72, uint256 desiredThresholdMag2, - bool netDebtX -) internal pure returns (int256 endOfLiquidationInTicks, SaturationPair memory saturation); + bool netDebtX, + bool skipMinOrMaxTickCheck +) internal pure returns (SaturationPair memory saturation, int256 endOfLiquidationInTicks, int256 currentTickLimit); ``` **Parameters** |Name|Type|Description| |----|----|-----------| |`inputParams`|`Validation.InputParams`| the input params| -|`liqSqrtPriceInXInQ72`|`uint256`| the liq sqrt price in X| +|`netXLiqSqrtPriceInXInQ72`|`uint256`| the midpoint of liquidation sqrt price of debt X in X/Y| +|`netYLiqSqrtPriceInXInQ72`|`uint256`| the midpoint of liquidation sqrt price of debt Y in X/Y| |`desiredThresholdMag2`|`uint256`| the desired threshold| |`netDebtX`|`bool`| whether the net debt is X or Y| +|`skipMinOrMaxTickCheck`|`bool`|when borrowing liquidity, the two liquidations will start facing opposite ways and the current price can only be on one side. When this happens, only one side's liquidation is valid, the other could not occur without the price moving through the valid liquidation. We also skip this check during `calcSatChangeRatioBips()` as we don't want to block liquidations.| **Returns** |Name|Type|Description| |----|----|-----------| -|`endOfLiquidationInTicks`|`int256`| the point at which the liquidation would end.| |`saturation`|`SaturationPair`|the saturation of the tranche| +|`endOfLiquidationInTicks`|`int256`| the point at which the liquidation would end.| +|`currentTickLimit`|`int256`|The point at which the liquidation can not start before due to the current price.| + + +### calculateStartAndEndOfLiquidationPriceQ128 + +Convert from sqrtPrice by squaring, but we don't square the span because we only want +to shift by half of the span to move from the middle of the liquidation to the end. +Division prior to multiplication to avoid overflow since sqrtPriceQ72 is is 128 bits. + + +```solidity +function calculateStartAndEndOfLiquidationPriceQ128( + uint256 liqSqrtPriceQ72, + uint256 sqrtPriceSpanQ72, + bool netDebtX +) internal pure returns (uint256 startOfLiquidationPriceQ128, uint256 endOfLiquidationPriceQ128); +``` + +### liqPriceDividedBySpan + + +```solidity +function liqPriceDividedBySpan( + uint256 liqPriceQ144, + uint256 sqrtPriceSpanQ72 +) private pure returns (uint256 priceQ128); +``` + +### liqPriceMultipliedBySpan +```solidity +function liqPriceMultipliedBySpan( + uint256 liqPriceQ144, + uint256 sqrtPriceSpanQ72 +) private pure returns (uint256 priceQ128); +``` + ### calculateNetDebtAndSpan calc net debt and span @@ -1298,15 +1623,17 @@ calc net debt and span ```solidity function calculateNetDebtAndSpan( Validation.InputParams memory inputParams, + uint256 liqSqrtPriceInXInQ72, uint256 desiredThresholdMag2, bool netDebtX -) internal pure returns (uint256 netDebtXorYAssets, uint256 netDebtLAssets, uint256 trancheSpanInTicks); +) internal pure returns (uint256 netDebtXorYAssets, uint256 netDebtLAssets, uint256 minSqrtPriceSpanQ72); ``` **Parameters** |Name|Type|Description| |----|----|-----------| |`inputParams`|`Validation.InputParams`| the input params| +|`liqSqrtPriceInXInQ72`|`uint256`|| |`desiredThresholdMag2`|`uint256`| the desired threshold| |`netDebtX`|`bool`| whether the net debt is X or Y| @@ -1316,115 +1643,71 @@ function calculateNetDebtAndSpan( |----|----|-----------| |`netDebtXorYAssets`|`uint256`| the net debt| |`netDebtLAssets`|`uint256`| the net debt in L assets| -|`trancheSpanInTicks`|`uint256`| the tranche span percentage| +|`minSqrtPriceSpanQ72`|`uint256`| the tranche span in sqrtPrice| ### calculateSaturation calculate the relative saturation of the position at the end of liquidation. - -*Since we place saturation in tranches starting at the end and moving forward, this -calculates the entire saturation as if it would fit in the last tranche, we then need to -adjust the saturation each time we move to the next tranche by dividing by a factor of -$$B$$. The equation here is slightly different than the equation in our description since -we multiply by a factor of $$B$$ for each tranche we move back away from the start. -thus here we use, where $$TCount$$ is the number of tranches we need to move back, +Since we place saturation in tranches starting at the tick where the liquidation would +end and moving forward to the start of liquidation, this calculates the entire saturation +as if it would fit in the last tranche, we then we will need to adjust the saturation each +time we move forward a tranche to the next tranche by dividing by a factor of $$B$$ when +we allocate the saturation later. The equation here is slightly different than the +equation in our description since we multiply by a factor of $$B$$ for each tranche we +move back from the start of liquidation tick. Thus here we use, where $$tSpan$$ is the +number of tranches we need to move back, ```math -\begin{equation} -saturationRelativeToL = +\begin{equation}T_{sat} = \begin{cases} -\frac{debtX}{B^{T_{1}}}\left(\frac{B^{TCount}}{B-1}\right) \\ -debtY\cdot B^{T_{0}}\cdot\left(\frac{B^{TCount}}{B-1}\right) +\Large\frac{debt}{b^{t_e}(B-1)} +&\text{ when debt is in X asset } +\\ +\Large\frac{debt \cdot b^{t_e}}{B-1} +&\text{ otherwise } \end{cases} \end{equation} ``` As we iterate through tranches, we divide by a factor of $$B$$ such that when we reach the -final tranche, our equation from the start applies.* +final tranche, our equation from the start applies. +Note that we also magnify the debt by the `SATURATION_TIME_BUFFER_IN_MAG2` to account for +the potential growth that will occur over time due to interest. This allows for our +estimate of saturation to be static in spite of the dynamic impact of interest. ```solidity function calculateSaturation( uint256 netDebtXOrYAssets, - uint256 startSqrtPriceQ72, - uint256 trancheSpanInTicks, + uint256 endOfLiquidationSqrtPriceQ72, bool netDebtX -) internal pure returns (uint256 saturation); +) internal pure returns (uint128 saturation); ``` **Parameters** |Name|Type|Description| |----|----|-----------| |`netDebtXOrYAssets`|`uint256`| the net debt in X or Y assets.| -|`startSqrtPriceQ72`|`uint256`| the sqrt price at the start of liquidation| -|`trancheSpanInTicks`|`uint256`| the span of the tranche in ticks.| -|`netDebtX`|`bool`| whether the debt is in X or Y assets| +|`endOfLiquidationSqrtPriceQ72`|`uint256`|the tick at which the liquidation ends.| +|`netDebtX`|`bool`| whether the debt is net in X or Y assets| **Returns** |Name|Type|Description| |----|----|-----------| -|`saturation`|`uint256`| the saturation relative to active liquidity assets.| +|`saturation`|`uint128`| the saturation relative to active liquidity assets.| -### calcMinTrancheSpanInTicks - -calc the minimum tranche count given the collateral, debt, active liquidity and desired threshold +### calculateMinSqrtPriceSpanQ72 ```solidity -function calcMinTrancheSpanInTicks( +function calculateMinSqrtPriceSpanQ72( uint256 collateral, uint256 debt, uint256 activeLiquidityAssets, uint256 desiredThresholdMag2 -) internal pure returns (uint256 trancheSpanInTicks); +) internal pure returns (uint256 sqrtPriceSpanQ72); ``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`collateral`|`uint256`| the collateral amount| -|`debt`|`uint256`| the debt amount| -|`activeLiquidityAssets`|`uint256`| the active liquidity assets| -|`desiredThresholdMag2`|`uint256`| the desired threshold| - -**Returns** - -|Name|Type|Description| -|----|----|-----------| -|`trancheSpanInTicks`|`uint256`| the tranche span a position will need. When greater than TICKS_PER_TRANCHE, multiple tranches are needed.| - - -### calcTrancheAtStartOfLiquidation - -calc the tranche at start of liquidation - - -```solidity -function calcTrancheAtStartOfLiquidation( - uint256 netDebtXorYAssets, - uint256 activeLiquidityAssets, - uint256 trancheSpanInTicks, - uint256 desiredThresholdMag2, - bool netDebtX -) internal pure returns (int256 trancheStartOfLiquidationMag2); -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`netDebtXorYAssets`|`uint256`| the net debt in X or Y assets.| -|`activeLiquidityAssets`|`uint256`| the active liquidity assets| -|`trancheSpanInTicks`|`uint256`| the tranche span percentage| -|`desiredThresholdMag2`|`uint256`| the desired threshold| -|`netDebtX`|`bool`| whether the net debt is X or Y| - -**Returns** - -|Name|Type|Description| -|----|----|-----------| -|`trancheStartOfLiquidationMag2`|`int256`| the tranche at start of liquidation| - ### readFieldBitFromNode @@ -1495,18 +1778,26 @@ function readFieldFromNode( ### calcSaturationPenaltyRatePerSecondInWads -Calculates the penalty scaling factor based on current borrow utilization and saturation +Calculates the penalty scaling factor based on current borrow utilization and +saturation *This implements the penalty rate function -Formula: ((1 - u_0) * f_interestPerSecond(u_1) * allAssetsDepositL) / (WAD * satInLAssetsInPenalty) -Where u_1 = (0.90 - (1 - u_0) * (0.95 - u_s) / 0.95)* +Formula: +```math +((1 - u_0) \cdot f_{interestPerSecond}(u_1) \cdot allAssetsDepositL) / (WAD +\cdot satInPenaltyInLAssets) +``` +Where, +```math +u_1 = (0.90 - (1 - u_0) \cdot (0.95 - u_s) / 0.95) +```* ```solidity function calcSaturationPenaltyRatePerSecondInWads( uint256 currentBorrowUtilizationInWad, uint256 saturationUtilizationInWad, - uint128 satInLAssetsInPenalty, + uint128 satInPenaltyInLAssets, uint256 allAssetsDepositL ) internal pure returns (uint256 penaltyRatePerSecondInWads); ``` @@ -1516,7 +1807,7 @@ function calcSaturationPenaltyRatePerSecondInWads( |----|----|-----------| |`currentBorrowUtilizationInWad`|`uint256`|Current borrow utilization of L (u_0)| |`saturationUtilizationInWad`|`uint256`|Current saturation utilization (u_s)| -|`satInLAssetsInPenalty`|`uint128`|The saturation in L assets in the penalty| +|`satInPenaltyInLAssets`|`uint128`|The saturation in L assets in the penalty| |`allAssetsDepositL`|`uint256`|The total assets deposited in L| **Returns** @@ -1528,19 +1819,44 @@ function calcSaturationPenaltyRatePerSecondInWads( ## Errors ### MaxTrancheOverSaturated +if the largest sat in the trees is too large + ```solidity error MaxTrancheOverSaturated(); ``` -### CannotUpdateZeroAddress +### NegativeSpan +raised if the $$log_b(spanSqrtPrice) < 0$$, this shouldn't be possible. + + +```solidity +error NegativeSpan(); +``` + +### LiquidationPassesMinOrMaxTick +raised if the start of liquidation would occur on the wrong side of the min or max +tick price from the GeometricTWAP. + ```solidity -error CannotUpdateZeroAddress(); +error LiquidationPassesMinOrMaxTick(); +``` + +### SaturationReachesMinOrMaxTick +raised if the the available saturation is not sufficient to keep the start of +liquidation from reaching the wrong side of the min or max tick price from the +GeometricTWAP. + + +```solidity +error SaturationReachesMinOrMaxTick(); ``` ## Structs ### SaturationStruct +final structure containing all the storage data + ```solidity struct SaturationStruct { @@ -1550,18 +1866,9 @@ struct SaturationStruct { } ``` -### SaturationPair -a pair of saturation values used and stored throughout this library. - - -```solidity -struct SaturationPair { - uint128 satInLAssets; - uint128 satRelativeToL; -} -``` - ### Tree +the main storage type of tree struct within the `SaturationStruct`. + ```solidity struct Tree { @@ -1578,6 +1885,8 @@ struct Tree { ``` ### Leaf +a leaf contains multiple tranches and contains the total sat and penalty for the leaf + ```solidity struct Leaf { @@ -1588,6 +1897,9 @@ struct Leaf { ``` ### Account +basic data per account associated with an address stored in the `Tree` struct in a +map as the value associated with the owners address as the key. + ```solidity struct Account { @@ -1600,6 +1912,8 @@ struct Account { ``` ### CalcLiqSqrtPriceHandleAllABCNonZeroStruct +used in memory to avoid stack overflow in `calcLiqSqrtPriceQ72()`. + ```solidity struct CalcLiqSqrtPriceHandleAllABCNonZeroStruct { @@ -1613,6 +1927,8 @@ struct CalcLiqSqrtPriceHandleAllABCNonZeroStruct { ``` ### AddSatToTrancheStateUpdatesStruct +used in memory to avoid stack overflow in `addSatToTranche()`. + ```solidity struct AddSatToTrancheStateUpdatesStruct { @@ -1621,7 +1937,19 @@ struct AddSatToTrancheStateUpdatesStruct { SaturationPair oldTrancheSaturation; SaturationPair newTrancheSaturation; SaturationPair satAvailableToAdd; + uint256 targetCapacityRelativeToLAssets; address account; } ``` +### SaturationPair +a pair of saturation values used and stored throughout this library. + + +```solidity +struct SaturationPair { + uint128 satInLAssets; + uint128 satRelativeToL; +} +``` + diff --git a/docs/developer-guide/contracts/libraries/TickMath.sol/library.TickMath.md b/docs/developer-guide/contracts/libraries/TickMath.sol/library.TickMath.md index 9b8a5330..cf777519 100644 --- a/docs/developer-guide/contracts/libraries/TickMath.sol/library.TickMath.md +++ b/docs/developer-guide/contracts/libraries/TickMath.sol/library.TickMath.md @@ -1,5 +1,5 @@ # TickMath -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/TickMath.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/TickMath.sol) Computes sqrt price for ticks of size B=(1-2^-9)^-1 as fixed point Q72 numbers. Supports prices between 2**-112 and 2**112-1 @@ -106,6 +106,28 @@ function applyMultiplications( ) private pure returns (uint256 valueInQ128); ``` +### getTickFromReserves + +*Get the new tick based on the current reserves.* + + +```solidity +function getTickFromReserves(uint256 reserveXAssets, uint256 reserveYAssets) internal pure returns (int16); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`reserveXAssets`|`uint256`|The current reserve X assets.| +|`reserveYAssets`|`uint256`|The current reserve Y assets.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`int16`|newTick The current tick.| + + ## Errors ### PriceOutOfBounds diff --git a/docs/developer-guide/contracts/libraries/TokenSymbol.sol/library.TokenSymbol.md b/docs/developer-guide/contracts/libraries/TokenSymbol.sol/library.TokenSymbol.md index 24c075f4..d17d5a18 100644 --- a/docs/developer-guide/contracts/libraries/TokenSymbol.sol/library.TokenSymbol.md +++ b/docs/developer-guide/contracts/libraries/TokenSymbol.sol/library.TokenSymbol.md @@ -1,5 +1,5 @@ # TokenSymbol -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/TokenSymbol.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/TokenSymbol.sol) ## Functions diff --git a/docs/developer-guide/contracts/libraries/Uint16Set.sol/library.Uint16Set.md b/docs/developer-guide/contracts/libraries/Uint16Set.sol/library.Uint16Set.md index 09f9de72..8f03b403 100644 --- a/docs/developer-guide/contracts/libraries/Uint16Set.sol/library.Uint16Set.md +++ b/docs/developer-guide/contracts/libraries/Uint16Set.sol/library.Uint16Set.md @@ -1,5 +1,5 @@ # Uint16Set -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/Uint16Set.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/Uint16Set.sol) based on https://github.com/rob-Hitchens/SetTypes/blob/master/contracts/UintSet.sol diff --git a/docs/developer-guide/contracts/libraries/Validation.sol/library.Validation.md b/docs/developer-guide/contracts/libraries/Validation.sol/library.Validation.md index 5fa59855..46045904 100644 --- a/docs/developer-guide/contracts/libraries/Validation.sol/library.Validation.md +++ b/docs/developer-guide/contracts/libraries/Validation.sol/library.Validation.md @@ -1,5 +1,5 @@ # Validation -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/Validation.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/Validation.sol) SPDX-License-Identifier: GPL-3.0-only @@ -71,10 +71,15 @@ uint256 private constant TWO_THOUSAND_FIVE_HUNDRED_Q128 = 0x9c400000000000000000 ## Functions ### getInputParams +Get the input parameters for the validation + +*hasBorrow is set to true here, because we assume that the caller has verified there is +a borrowed asset* + ```solidity function getInputParams( - uint128[6] memory currentAssets, + uint112[6] memory currentAssets, uint256[6] memory userAssets, uint256 reserveXAssets, uint256 reserveYAssets, @@ -83,22 +88,58 @@ function getInputParams( int16 maxTick ) internal pure returns (Validation.InputParams memory inputParams); ``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`currentAssets`|`uint112[6]`|The current assets of the pool| +|`userAssets`|`uint256[6]`|The user assets of the pool| +|`reserveXAssets`|`uint256`|The reserve of the X asset| +|`reserveYAssets`|`uint256`|The reserve of the Y asset| +|`externalLiquidity`|`uint256`|The external liquidity of the pool| +|`minTick`|`int16`|The min tick of the pool| +|`maxTick`|`int16`|The max tick of the pool| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|`inputParams`|`Validation.InputParams`|The input parameters for the validation| + ### getCheckLtvParams +Get the check LTV parameters for needed for `validateLTVAndLeverage()` + +*the sqrt prices are in the input params, but by passing them we allow for the ability +to switch them as needed in liquidation and other cases.* + ```solidity function getCheckLtvParams( - InputParams memory inputParams + uint256[6] memory userAssets, + uint256 activeLiquidityScalerInQ72, + uint256 sqrtPriceMinInQ72, + uint256 sqrtPriceMaxInQ72 ) internal pure returns (CheckLtvParams memory checkLtvParams); ``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`userAssets`|`uint256[6]`|User asset array| +|`activeLiquidityScalerInQ72`|`uint256`|The active liquidity scaler in Q72| +|`sqrtPriceMinInQ72`|`uint256`|The minimum sqrt price in Q72| +|`sqrtPriceMaxInQ72`|`uint256`|The maximum sqrt price in Q72| + ### validateBalanceAndLiqAndNotSameAssetsSuppliedAndBorrowed ```solidity function validateBalanceAndLiqAndNotSameAssetsSuppliedAndBorrowed( - InputParams memory inputParams + uint256[6] memory userAssets, + uint256 activeLiquidityAssets ) internal pure; ``` @@ -118,7 +159,11 @@ check of a balance that can be done from within a token. ```solidity function validateSolvency( - InputParams memory inputParams + uint256[6] memory userAssets, + uint256 sqrtPriceMinInQ72, + uint256 sqrtPriceMaxInQ72, + uint256 activeLiquidityScalerInQ72, + uint256 activeLiquidityAssets ) internal pure; ``` @@ -134,21 +179,12 @@ function verifyNotSameAssetsSuppliedAndBorrowed( ) internal pure; ``` -### verifyMaxBorrowXY - - -```solidity -function verifyMaxBorrowXY( - VerifyMaxBorrowXYParams memory params -) internal pure; -``` - -### verifyMaxBorrowL +### verifyMaxBorrow ```solidity -function verifyMaxBorrowL( - VerifyMaxBorrowLParams memory params +function verifyMaxBorrow( + VerifyMaxBorrowParams memory params ) internal pure; ``` @@ -157,7 +193,10 @@ function verifyMaxBorrowL( ```solidity function getDepositsInL( - InputParams memory inputParams + uint256[6] memory userAssets, + uint256 activeLiquidityScalerInQ72, + uint256 sqrtPriceMinInQ72, + uint256 sqrtPriceMaxInQ72 ) private pure returns (uint256 netDepositedXinLAssets, uint256 netDepositedYinLAssets); ``` @@ -166,24 +205,27 @@ function getDepositsInL( ```solidity function getBorrowedInL( - InputParams memory inputParams + uint256[6] memory userAssets, + uint256 activeLiquidityScalerInQ72, + uint256 sqrtPriceMinInQ72, + uint256 sqrtPriceMaxInQ72 ) private pure returns (uint256 netBorrowedXinLAssets, uint256 netBorrowedYinLAssets); ``` ### convertXToL The original math: -L * activeLiquidityScalerInQ72 = x / (2 * sqrt(p)) +L * activeLiquidityScalerInQ72 = x / sqrt(p) previous equation: -amountLAssets = mulDiv(amount, Q72, 2 * sqrtPriceInXInQ72, rounding); +amountLAssets = mulDiv(amount, Q72, sqrtPriceInXInQ72, rounding); adding activeLiquidityScalerInQ72: -amountLAssets = (amount * Q72 / (2 * sqrtPriceInXInQ72)) / (activeLiquidityScalerInQ72 / Q72); +amountLAssets = (amount * Q72 / sqrtPriceInXInQ72) / (activeLiquidityScalerInQ72 / Q72); simplify to: -(amount * Q72 * Q72) / (2 * sqrtPriceInXInQ72 * activeLiquidityScalerInQ72) +(amount * Q72 * Q72) / (sqrtPriceInXInQ72 * activeLiquidityScalerInQ72) final equation: -amountLAssets = mulDiv(mulDiv(amount, Q72, sqrtPriceInXInQ72, rounding), Q72, 2 * activeLiquidityScalerInQ72, rounding); +amountLAssets = mulDiv(mulDiv(amount, Q72, sqrtPriceInXInQ72, rounding), Q72, activeLiquidityScalerInQ72, rounding); or more simplified (failed for some tests) -amountLAssets = mulDiv(amount, Q72 * Q72, 2 * sqrtPriceInQ72 * activeLiquidityScalerInQ72); +amountLAssets = mulDiv(amount, Q72 * Q72, sqrtPriceInQ72 * activeLiquidityScalerInQ72); ```solidity @@ -209,16 +251,14 @@ function convertLToX( ### convertYToL -The simplified math: L = y * sqrt(p) / 2 -mulDiv(amount, sqrtPriceInXInQ72, 2 * Q72, rounding); -amountLAssets = amount * sqrtPriceInXInQ72Scaled / (2 * Q72) +The simplified math: L = y * sqrt(p) +mulDiv(amount, sqrtPriceInXInQ72, rounding); +amountLAssets = amount * sqrtPriceInXInQ72Scaled / Q72; sqrtPriceInXInQ72Scaled = sqrtPriceInXInQ72 / activeLiquidityScalerInQ72 / Q72; simplify to: -amount * sqrtPriceInXInQ72 / activeLiquidityScalerInQ72 / Q72 / (2 * Q72) -simplify to: -(amount * sqrtPriceInXInQ72 * Q56) / (activeLiquidityScalerInQ72 * 2) +amount * sqrtPriceInXInQ72 / activeLiquidityScalerInQ72 final equation: -amountLAssets = mulDiv(amount, sqrtPriceInXInQ72 * Q56, 2 * activeLiquidityScalerInQ72, rounding); +amountLAssets = mulDiv(amount, sqrtPriceInXInQ72, activeLiquidityScalerInQ72, rounding); ```solidity @@ -307,7 +347,7 @@ L_{in} ``` Using $L_{out}$ described in our method as `debtLiquidityAssets`, $L$ or `activeLiquidityAssets`, and our fee, we use the above equation to solve for the amount of liquidity that -must come in to buy the debt. +must come into buy the debt. ```solidity @@ -388,12 +428,15 @@ error AmmalgamTransferAmtExceedsBalance(); ```solidity struct InputParams { uint256[6] userAssets; + int16 minTick; + int16 maxTick; uint256 sqrtPriceMinInQ72; uint256 sqrtPriceMaxInQ72; uint256 activeLiquidityScalerInQ72; uint256 activeLiquidityAssets; uint256 reservesXAssets; uint256 reservesYAssets; + bool hasBorrow; } ``` @@ -409,27 +452,15 @@ struct CheckLtvParams { } ``` -### VerifyMaxBorrowXYParams +### VerifyMaxBorrowParams ```solidity -struct VerifyMaxBorrowXYParams { - uint256 amount; +struct VerifyMaxBorrowParams { uint256 depositedAssets; uint256 borrowedAssets; uint256 reserve; - uint256 totalLiquidityAssets; - uint256 borrowedLiquidityAssets; -} -``` - -### VerifyMaxBorrowLParams - -```solidity -struct VerifyMaxBorrowLParams { - uint256[6] totalAssets; - uint256 newBorrowedLAssets; - uint256 reserveXAssets; - uint256 reserveYAssets; + uint256 totalDepositedLAssets; + uint256 totalBorrowedLAssets; } ``` diff --git a/docs/developer-guide/contracts/libraries/constants.sol/constants.constants.md b/docs/developer-guide/contracts/libraries/constants.sol/constants.constants.md index a7e798c9..5ddc7b93 100644 --- a/docs/developer-guide/contracts/libraries/constants.sol/constants.constants.md +++ b/docs/developer-guide/contracts/libraries/constants.sol/constants.constants.md @@ -1,5 +1,5 @@ # Constants -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/libraries/constants.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/libraries/constants.sol) ### B_IN_Q72 *This basis was a modification to Uniswap V3's basis, to fit ticks into int16 instead of @@ -35,30 +35,37 @@ uint256 constant B_IN_Q72 = 0x1008040201008040201; ``` ### TRANCHE_B_IN_Q72 -*In Saturation we combine 100 ticks to make one tranche. +*In Saturation we combine 25 ticks to make one tranche. ```python ->>> hex(int(mpm.nint(mpm.fdiv(2**9, 2**9-1)**100 * 2**72))) +>>> hex(int(mpm.nint(mpm.fdiv(2**9, 2**9-1)**25 * 2**72))) ```* ```solidity -uint256 constant TRANCHE_B_IN_Q72 = 0x13746bb4eee2a5b6cd4; +uint256 constant TRANCHE_B_IN_Q72 = 0x10cd2b2ae53a69d3552; ``` -### TRANCHE_QUARTER_B_IN_Q72 -*In Saturation we also use a quarter of a tranche to give some better fidelity without -needing to add a number iterations of multiplications. -```python ->>> hex(int(mpm.nint(mpm.fdiv(2**9, 2**9-1)**25 * 2**72))) -```* +### FRAGILE_LIQUIDITY_DECREMENT_PERCENTAGE +*We decrement the active liquidity used to measure available saturation by this +percentage of fragile liquidity, or liquidity that has some amount of x or y borrowed +against it. Reducing by 100% would ensure that that fragile liquidity could always be +liquidated since burning it would not decrease the saturation. However, this also means +that fragile liquidity adds no value to the risk of the pool, even if it may not be +liquidated until after risk closer to the price. This value also ensures that recursively +leveraging large amounts of x and y against liquidity can not allow more debt to be +borrowed then the underlying stable liquidity not at risk of being seized and burned +during liquidation. Crediting 10% of the fragile liquidity is a compromise to allow some +benefit of leveraged liquidity to increase borrowing capacity without allowing for it to +be vulnerable to allow excessive borrowing.* ```solidity -uint256 constant TRANCHE_QUARTER_B_IN_Q72 = 0x10cd2b2ae53a69d3552; +uint256 constant FRAGILE_LIQUIDITY_DECREMENT_PERCENTAGE = 95; ``` ### LENDING_TICK_NOT_AVAILABLE -*Represents the absence of a valid lending tick, initialized to `int16` minimum value since type(int16).min < MIN_TICK* +*Represents the absence of a valid lending tick, initialized to `int16` minimum value since a +`type(int16).min < MIN_TICK`.* ```solidity @@ -113,6 +120,14 @@ uint256 constant Q64 = 0x10000000000000000; uint256 constant Q72 = 0x1000000000000000000; ``` +### Q88 +*2**88.* + + +```solidity +uint256 constant Q88 = 0x10000000000000000000000; +``` + ### Q112 *2**112.* @@ -130,11 +145,21 @@ uint256 constant Q128 = 0x100000000000000000000000000000000; ``` ### Q144 +*2**144.* + ```solidity uint256 constant Q144 = 0x1000000000000000000000000000000000000; ``` +### Q200 +*2**200.* + + +```solidity +uint256 constant Q200 = 0x100000000000000000000000000000000000000000000000000; +``` + ### BIPS *number of bips in 1, 1 bips = 0.01%.* @@ -143,6 +168,18 @@ uint256 constant Q144 = 0x1000000000000000000000000000000000000; uint256 constant BIPS = 10_000; ``` +### INITIAL_LENDING_FEE_BIPS +*Initial fee applied to all newly opened debts and flash loans. This upfront fee prevents +griefing attacks via "dust" positions—small debts that would be unprofitable for liquidators to close. +The fee accumulates in the protocol, creating an economic incentive to liquidate these positions +if they become eligible for liquidation. +5 bips = 0.05%.* + + +```solidity +uint256 constant INITIAL_LENDING_FEE_BIPS = 5; +``` + ### DEFAULT_MID_TERM_INTERVAL *Default mid-term interval config used at the time of GeometricTWAP initialization.* @@ -278,12 +315,6 @@ uint256 constant SAT_PERCENTAGE_DELTA_6_WAD = 90.4887067368814135e16; uint256 constant SAT_PERCENTAGE_DELTA_7_WAD = 88.6978836489829983e16; ``` -### SAT_PERCENTAGE_DELTA_8_WAD - -```solidity -uint256 constant SAT_PERCENTAGE_DELTA_8_WAD = 86.9425019708228757e16; -``` - ### SAT_PERCENTAGE_DELTA_DEFAULT_WAD ```solidity @@ -315,6 +346,62 @@ uint256 constant MAX_UTILIZATION_PERCENT_IN_WAD = 0.9e18; ### SECONDS_IN_YEAR ```solidity -uint128 constant SECONDS_IN_YEAR = 365 days; +uint256 constant SECONDS_IN_YEAR = 365 days; +``` + +### INTEREST_PERIOD_FOR_SWAP +*The interval for swap to check borrowed interest to update reserves. +Updating once a day would limit rate change in price to 0.003% if one reserve +had max interest and the other had none. +It also would require 40 days to go from 94% depletion to 95% depletion. +ref: https://www.desmos.com/calculator/sxfc3tcz8c* + + +```solidity +uint32 constant INTEREST_PERIOD_FOR_SWAP = 1 days - 1; +``` + +### DEFAULT_INTEREST_PERIOD +*The interval for non-swap to check borrowed interest to update reserves.* + + +```solidity +uint32 constant DEFAULT_INTEREST_PERIOD = 0; +``` + +### BUFFER +*Buffer ratio at which lending of the scarce asset stops. +Derived from 95 / 5.* + + +```solidity +uint256 constant BUFFER = 19; +``` + +### BUFFER_NUMERATOR +*Numerator buffer used for depleted-asset threshold calculations. +Derived from 100 / 5.* + + +```solidity +uint256 constant BUFFER_NUMERATOR = 20; +``` + +### BUFFER_OBS +*Observation buffer used when computing the new tick from reserves. +Derived from 45 / 5.* + + +```solidity +uint256 constant BUFFER_OBS = 9; +``` + +### BUFFER_OBS_NUMERATOR +*Observation buffer numerator used for depleted-asset threshold calculations. +Derived from 50 / 5.* + + +```solidity +uint256 constant BUFFER_OBS_NUMERATOR = 10; ``` diff --git a/docs/developer-guide/contracts/proxy/LockedLoans.sol/contract.AmmalgamPairLockedLoans.md b/docs/developer-guide/contracts/proxy/LockedLoans.sol/contract.AmmalgamPairLockedLoans.md new file mode 100644 index 00000000..236c965c --- /dev/null +++ b/docs/developer-guide/contracts/proxy/LockedLoans.sol/contract.AmmalgamPairLockedLoans.md @@ -0,0 +1,43 @@ +# AmmalgamPairLockedLoans +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/proxy/LockedLoans.sol) + +**Inherits:** +[AmmalgamPair](/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md) + + +## Functions +### constructor + + +```solidity +constructor(); +``` + +### initialize + + +```solidity +function initialize() external override reinitializer(2); +``` + +### borrow + + +```solidity +function borrow(address, uint256, uint256, bytes calldata) public pure override; +``` + +### borrowLiquidity + + +```solidity +function borrowLiquidity(address, uint256, bytes calldata) external pure override returns (uint256, uint256); +``` + +## Errors +### PairBorrowingFrozen + +```solidity +error PairBorrowingFrozen(); +``` + diff --git a/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.PairBeaconProxy.md b/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.PairBeaconProxy.md new file mode 100644 index 00000000..1cd38aae --- /dev/null +++ b/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.PairBeaconProxy.md @@ -0,0 +1,57 @@ +# PairBeaconProxy +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/proxy/PairBeaconProxy.sol) + +**Inherits:** +BeaconProxy + +Proxy contract for Ammalgam Pairs that uses a beacon for implementation management and +self initialization and reinitialization. + +*Inherits from OpenZeppelin's BeaconProxy and overrides the _fallback function to ensure +the implementation is up-to-date with the beacon before delegating calls. If the +implementation changes on the beacon, this proxy knows by storing the implementation at the +time of construction. When a change is made, this proxy will call initialize during the +_fallback call to ensure the new implementation is properly initialized. This reduces the +need to manually upgrade each pair when the beacon changes the implementation.* + + +## Functions +### constructor + +*Initializes the proxy with the beacon address from the factory and calls initialize +on the implementation.* + + +```solidity +constructor() + payable + BeaconProxy( + address(IAmmalgamFactory(msg.sender).pairBeacon()), + abi.encodeWithSelector(ITokenController.initialize.selector) + ); +``` + +### _fallback + +*Overrides the _fallback function to check if the implementation from the beacon +has changed. If it has, it upgrades the implementation and calls initialize on the new +implementation to ensure proper setup.* + + +```solidity +function _fallback() internal override; +``` + +### _setImplementation + +*Adapted from ERC1967Utils. The original function is private, and we need +to set the implementation on first deployment without invoking initialize() +again, since initialization was already performed in the BeaconProxy constructor.* + + +```solidity +function _setImplementation( + address newImplementation +) private; +``` + diff --git a/docs/developer-guide/contracts/proxy/_category_.json b/docs/developer-guide/contracts/proxy/_category_.json new file mode 100644 index 00000000..695c9482 --- /dev/null +++ b/docs/developer-guide/contracts/proxy/_category_.json @@ -0,0 +1 @@ +{ "label": "Proxy", "link": { "type": "generated-index" } } diff --git a/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md b/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md index 57c003ab..10f5cb63 100644 --- a/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md +++ b/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md @@ -1,8 +1,8 @@ # ERC20Base -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/ERC20Base.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/ERC20Base.sol) **Inherits:** -ERC20Plugins, Ownable, ERC20Permit, [IAmmalgamERC20](/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md) +ERC20Hooks, Ownable, ERC20Permit, [IAmmalgamERC20](/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md) ## State Variables @@ -13,10 +13,10 @@ ITransferValidator public immutable pair; ``` -### pluginRegistry +### hookRegistry ```solidity -IPluginRegistry private immutable pluginRegistry; +IHookRegistry private immutable hookRegistry; ``` @@ -27,10 +27,20 @@ uint256 public immutable tokenType; ``` -### transferPenaltyFromPairToBorrower +### ownerTransferSkipValidation +This boolean is reserved for moving collateral to liquidators. And we reuse it +to transfer debt from the pair to a borrower. Since the borrower might already be in trouble +if this is called during a liquidation, we do not call `validateOnUpdate` to avoid failing +on the loan to value check. This also means that saturation is not updated for this penalty +owed. we think this is an acceptable discrepancy since it is only the penalty for over +saturation that is not being included in the saturation update, which should be a negligible +amount with respect to the total debt. Once a position is updated either by the users +actions, or by a saturation liquidation reset, this penalty will be adjusted to the correct +value in the Saturation State. + ```solidity -bool transient transferPenaltyFromPairToBorrower; +bool transient ownerTransferSkipValidation; ``` @@ -41,7 +51,7 @@ bool transient transferPenaltyFromPairToBorrower; ```solidity constructor( ERC20BaseConfig memory config -) ERC20(config.name, config.symbol) ERC20Plugins(10, 500_000) ERC20Permit(config.name) Ownable(config.pair); +) ERC20(config.name, config.symbol) ERC20Hooks(10, 500_000) ERC20Permit(config.name) Ownable(config.pair); ``` ### nonces @@ -73,7 +83,7 @@ function ownerTransfer(address from, address to, uint256 amount) public virtual ```solidity function balanceOf( address account -) public view virtual override(ERC20, ERC20Plugins, IERC20) returns (uint256); +) public view virtual override(ERC20, ERC20Hooks, IERC20) returns (uint256); ``` ### decimals @@ -85,17 +95,37 @@ function decimals() public view virtual override(ERC20, IERC20Metadata) returns ### _update +Updates the pair state based on the transfer. + +*Triggers pair state updates for DEPOSIT_L and debt token transfers +to avoid potential L token accumulation in the pair during burn operations.* + ```solidity -function _update(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Plugins); +function _update(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Hooks); ``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`from`|`address`|The address of the sender.| +|`to`|`address`|The address of the recipient.| +|`amount`|`uint256`|The amount of tokens transferred.| + -### addPlugin +### addHook ```solidity -function addPlugin( - address plugin +function addHook( + address hook ) public override; ``` +## Errors +### HookIsNotAllowed + +```solidity +error HookIsNotAllowed(); +``` + diff --git a/docs/developer-guide/contracts/tokens/ERC20Base.sol/struct.ERC20BaseConfig.md b/docs/developer-guide/contracts/tokens/ERC20Base.sol/struct.ERC20BaseConfig.md index aabb6f47..ffad4f7c 100644 --- a/docs/developer-guide/contracts/tokens/ERC20Base.sol/struct.ERC20BaseConfig.md +++ b/docs/developer-guide/contracts/tokens/ERC20Base.sol/struct.ERC20BaseConfig.md @@ -1,11 +1,11 @@ # ERC20BaseConfig -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/ERC20Base.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/ERC20Base.sol) ```solidity struct ERC20BaseConfig { address pair; - address pluginRegistry; + IHookRegistry hookRegistry; string name; string symbol; uint256 tokenType; diff --git a/docs/developer-guide/contracts/tokens/ERC20DebtBase.sol/abstract.ERC20DebtBase.md b/docs/developer-guide/contracts/tokens/ERC20DebtBase.sol/abstract.ERC20DebtBase.md index 4b7954e2..4772f40d 100644 --- a/docs/developer-guide/contracts/tokens/ERC20DebtBase.sol/abstract.ERC20DebtBase.md +++ b/docs/developer-guide/contracts/tokens/ERC20DebtBase.sol/abstract.ERC20DebtBase.md @@ -1,5 +1,5 @@ # ERC20DebtBase -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/ERC20DebtBase.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/ERC20DebtBase.sol) **Inherits:** [ERC20Base](/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md), [IERC20DebtToken](/docs/developer-guide/contracts/interfaces/tokens/IERC20DebtToken.sol/interface.IERC20DebtToken.md) diff --git a/docs/developer-guide/contracts/tokens/ERC20DebtLiquidityToken.sol/contract.ERC20DebtLiquidityToken.md b/docs/developer-guide/contracts/tokens/ERC20DebtLiquidityToken.sol/contract.ERC20DebtLiquidityToken.md index 8feb8fee..2950764e 100644 --- a/docs/developer-guide/contracts/tokens/ERC20DebtLiquidityToken.sol/contract.ERC20DebtLiquidityToken.md +++ b/docs/developer-guide/contracts/tokens/ERC20DebtLiquidityToken.sol/contract.ERC20DebtLiquidityToken.md @@ -1,5 +1,5 @@ # ERC20DebtLiquidityToken -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/ERC20DebtLiquidityToken.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/ERC20DebtLiquidityToken.sol) **Inherits:** [ERC20DebtBase](/docs/developer-guide/contracts/tokens/ERC20DebtBase.sol/abstract.ERC20DebtBase.md) @@ -34,56 +34,3 @@ function ownerMint( function ownerBurn(address sender, address onBehalfOf, uint256 assets, uint256 shares) public override onlyOwner; ``` -### ownerTransfer - -This function is reserved for moving collateral to liquidators, but here we reuse it -to transfer debt from the pair to a borrower. Since the borrower might already be in trouble -if this is called during a liquidation, we do not call `validateOnUpdate` to avoid failing -on the loan to value check. This also means that saturation is not updated for this penalty -owed. we think this is an acceptable discrepancy since it is only the penalty for over -saturation that is not being included in the saturation update, which should be a negligible -amount with respect to the total debt. Once a position is updated either by the users -actions, or by a soft liquidation, this penalty will be adjusted to the correct value. in -the Saturation State. - - -```solidity -function ownerTransfer(address from, address to, uint256 amount) public override(ERC20Base, IAmmalgamERC20) onlyOwner; -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`from`|`address`|address from which shares are transferred| -|`to`|`address`|address to which shares are transferred| -|`amount`|`uint256`|amount of shares to transfer| - - -### borrowLiquidityCall - -We use the callback to transfer debt to the caller and transfer borrowed assets to the receiver. -This contract never has assets or shares unless they were sent to it by the pair within -the context of this function getting called. Calling this function directly will not do -anything because there are no assets or shares to transfer. - - -```solidity -function borrowLiquidityCall( - address sender, - uint256 assetsX, - uint256 assetsY, - uint256 sharesL, - bytes calldata data -) public; -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`sender`|`address`|| -|`assetsX`|`uint256`|amount of tokenX sent to this contract| -|`assetsY`|`uint256`|amount of tokenY sent to this contract| -|`sharesL`|`uint256`|amount of liquidity debt added to this contract| -|`data`|`bytes`|encoded data containing the caller and receiver addresses| - - diff --git a/docs/developer-guide/contracts/tokens/ERC20LiquidityToken.sol/contract.ERC20LiquidityToken.md b/docs/developer-guide/contracts/tokens/ERC20LiquidityToken.sol/contract.ERC20LiquidityToken.md index a6ecd7b7..55900493 100644 --- a/docs/developer-guide/contracts/tokens/ERC20LiquidityToken.sol/contract.ERC20LiquidityToken.md +++ b/docs/developer-guide/contracts/tokens/ERC20LiquidityToken.sol/contract.ERC20LiquidityToken.md @@ -1,5 +1,5 @@ # ERC20LiquidityToken -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/ERC20LiquidityToken.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/ERC20LiquidityToken.sol) **Inherits:** [ERC20Base](/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md) @@ -17,7 +17,7 @@ constructor( ### ownerMint -*override [ERC20Base-ownerMint](/docs/developer-guide/contracts/tokens/ERC4626DepositToken.sol/contract.ERC4626DepositToken.md#ownermint).* +*override [ERC20Base-ownerMint](/docs/developer-guide/contracts/tokens/ERC4626DebtToken.sol/contract.ERC4626DebtToken.md#ownermint).* ```solidity @@ -26,29 +26,10 @@ function ownerMint(address sender, address to, uint256 assets, uint256 shares) p ### ownerBurn -*override [ERC20Base-ownerBurn](/docs/developer-guide/contracts/tokens/ERC4626DepositToken.sol/contract.ERC4626DepositToken.md#ownerburn).* +*override [ERC20Base-ownerBurn](/docs/developer-guide/contracts/tokens/ERC4626DebtToken.sol/contract.ERC4626DebtToken.md#ownerburn).* ```solidity function ownerBurn(address sender, address to, uint256 assets, uint256 shares) public virtual override onlyOwner; ``` -### ownerTransfer - -Transfers `amount` tokens from the `from` address to the `to` address. - -*override [ERC20Base-ownerTransfer](/docs/developer-guide/contracts/tokens/ERC4626DepositToken.sol/contract.ERC4626DepositToken.md#ownertransfer).* - - -```solidity -function ownerTransfer(address from, address to, uint256 amount) public virtual override onlyOwner; -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`from`|`address`|The account to deduct the tokens from.| -|`to`|`address`|The account to deliver the tokens to.| -|`amount`|`uint256`|The amount of tokens to be transferred.| - - diff --git a/docs/developer-guide/contracts/tokens/ERC4626DebtToken.sol/contract.ERC4626DebtToken.md b/docs/developer-guide/contracts/tokens/ERC4626DebtToken.sol/contract.ERC4626DebtToken.md index ad7283d2..e8b3dbe9 100644 --- a/docs/developer-guide/contracts/tokens/ERC4626DebtToken.sol/contract.ERC4626DebtToken.md +++ b/docs/developer-guide/contracts/tokens/ERC4626DebtToken.sol/contract.ERC4626DebtToken.md @@ -1,5 +1,5 @@ # ERC4626DebtToken -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/ERC4626DebtToken.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/ERC4626DebtToken.sol) **Inherits:** ERC4626, [ERC20DebtBase](/docs/developer-guide/contracts/tokens/ERC20DebtBase.sol/abstract.ERC20DebtBase.md) @@ -69,6 +69,54 @@ function ammalgamBorrowCallV1( |`data`|`bytes`|encoded data containing the caller and receiver addresses| +### previewDeposit + +*Preview the amount of shares that will be minted for a given amount of assets +the user is borrowing, including the initial lending fee.* + + +```solidity +function previewDeposit( + uint256 assets +) public view override returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`assets`|`uint256`|The amount of assets user is borrowing.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The amount of shares that will be minted, including the initial lending fee.| + + +### previewMint + +*Preview the amount of assets required to mint a given amount of shares, +including the initial lending fee.* + + +```solidity +function previewMint( + uint256 shares +) public view override returns (uint256); +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`shares`|`uint256`|The amount of shares to mint.| + +**Returns** + +|Name|Type|Description| +|----|----|-----------| +|``|`uint256`|The amount of assets required to mint the given amount of shares, including the initial lending fee.| + + ### _deposit *ERC4626 facade for [IAmmalgamPair-borrow](/docs/developer-guide/contracts/interfaces/IAmmalgamPair.sol/interface.IAmmalgamPair.md#borrow). @@ -122,6 +170,13 @@ function decimals() public view override(ERC20Base, ERC4626, IERC20Metadata) ret function totalAssets() public view override returns (uint256); ``` +### totalSupply + + +```solidity +function totalSupply() public view override(ERC20, IERC20) returns (uint256); +``` + ### transfer diff --git a/docs/developer-guide/contracts/tokens/ERC4626DepositToken.sol/contract.ERC4626DepositToken.md b/docs/developer-guide/contracts/tokens/ERC4626DepositToken.sol/contract.ERC4626DepositToken.md index 102cac52..c986f686 100644 --- a/docs/developer-guide/contracts/tokens/ERC4626DepositToken.sol/contract.ERC4626DepositToken.md +++ b/docs/developer-guide/contracts/tokens/ERC4626DepositToken.sol/contract.ERC4626DepositToken.md @@ -1,5 +1,5 @@ # ERC4626DepositToken -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/ERC4626DepositToken.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/ERC4626DepositToken.sol) **Inherits:** ERC4626, [ERC20Base](/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md) @@ -15,7 +15,7 @@ constructor(ERC20BaseConfig memory config, address _asset) ERC4626(IERC20(_asset ### ownerMint -*override [AmmalgamERC20Base-ownerMint](/docs/developer-guide/contracts/tokens/ERC20Base.sol/abstract.ERC20Base.md#ownermint).* +*override [ERC20Base-ownerMint](/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md#ownermint).* ```solidity @@ -33,7 +33,7 @@ function ownerMint(address sender, address to, uint256 assets, uint256 shares) p ### ownerBurn -*override [AmmalgamERC20Base-ownerBurn](/docs/developer-guide/contracts/tokens/ERC4626DebtToken.sol/contract.ERC4626DebtToken.md#ownerburn).* +*override [ERC20Base-ownerBurn](/docs/developer-guide/contracts/interfaces/tokens/IAmmalgamERC20.sol/interface.IAmmalgamERC20.md#ownerburn).* ```solidity @@ -49,23 +49,6 @@ function ownerBurn(address sender, address to, uint256 assets, uint256 shares) p |`shares`|`uint256`|The amount of shares that will be burned.| -### ownerTransfer - -Transfers `amount` tokens from the `from` address to the `to` address. - - -```solidity -function ownerTransfer(address from, address to, uint256 amount) public virtual override onlyOwner; -``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`from`|`address`|The account to deduct the tokens from.| -|`to`|`address`|The account to deliver the tokens to.| -|`amount`|`uint256`|The amount of tokens to be transferred.| - - ### _deposit *ERC4626 facade for [IAmmalgamPair-deposit](/docs/developer-guide/contracts/interfaces/IAmmalgamPair.sol/interface.IAmmalgamPair.md#deposit). @@ -116,6 +99,13 @@ function decimals() public view override(ERC20Base, ERC4626) returns (uint8); function totalAssets() public view override returns (uint256); ``` +### totalSupply + + +```solidity +function totalSupply() public view virtual override(ERC20, IERC20) returns (uint256); +``` + ### _convertToShares diff --git a/docs/developer-guide/contracts/tokens/HookRegistry.sol/contract.HookRegistry.md b/docs/developer-guide/contracts/tokens/HookRegistry.sol/contract.HookRegistry.md new file mode 100644 index 00000000..d54655bd --- /dev/null +++ b/docs/developer-guide/contracts/tokens/HookRegistry.sol/contract.HookRegistry.md @@ -0,0 +1,39 @@ +# HookRegistry +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/HookRegistry.sol) + +**Inherits:** +[IHookRegistry](/docs/developer-guide/contracts/interfaces/tokens/IHookRegistry.sol/interface.IHookRegistry.md), Ownable + + +## State Variables +### allowedHooks + +```solidity +mapping(address => bool) allowedHooks; +``` + + +## Functions +### constructor + + +```solidity +constructor() Ownable(msg.sender); +``` + +### updateHook + + +```solidity +function updateHook(address hook, bool allowed) public onlyOwner; +``` + +### isHookAllowed + + +```solidity +function isHookAllowed( + address hook +) public view returns (bool); +``` + diff --git a/docs/developer-guide/contracts/tokens/PluginRegistry.sol/contract.PluginRegistry.md b/docs/developer-guide/contracts/tokens/PluginRegistry.sol/contract.PluginRegistry.md deleted file mode 100644 index 10333f98..00000000 --- a/docs/developer-guide/contracts/tokens/PluginRegistry.sol/contract.PluginRegistry.md +++ /dev/null @@ -1,39 +0,0 @@ -# PluginRegistry -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/PluginRegistry.sol) - -**Inherits:** -[IPluginRegistry](/docs/developer-guide/contracts/interfaces/tokens/IPluginRegistry.sol/interface.IPluginRegistry.md), Ownable - - -## State Variables -### allowedPlugins - -```solidity -mapping(address => bool) allowedPlugins; -``` - - -## Functions -### constructor - - -```solidity -constructor() Ownable(msg.sender); -``` - -### updatePlugin - - -```solidity -function updatePlugin(address plugin, bool allowed) public onlyOwner; -``` - -### isPluginAllowed - - -```solidity -function isPluginAllowed( - address plugin -) public view onlyOwner returns (bool); -``` - diff --git a/docs/developer-guide/contracts/tokens/TokenController.sol/contract.TokenController.md b/docs/developer-guide/contracts/tokens/TokenController.sol/contract.TokenController.md index 06bcb287..8a9bd0be 100644 --- a/docs/developer-guide/contracts/tokens/TokenController.sol/contract.TokenController.md +++ b/docs/developer-guide/contracts/tokens/TokenController.sol/contract.TokenController.md @@ -1,8 +1,8 @@ # TokenController -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/tokens/TokenController.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/tokens/TokenController.sol) **Inherits:** -[ITokenController](/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md) +Initializable, [ITokenController](/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md) *Wrapper of the ERC20 tokens that has some functionality similar to the ERC1155.* @@ -11,56 +11,70 @@ ### tokenX ```solidity -IERC20 private immutable tokenX; +IERC20 private tokenX; ``` ### tokenY ```solidity -IERC20 private immutable tokenY; +IERC20 private tokenY; ``` ### _tokenDepositL ```solidity -IAmmalgamERC20 private immutable _tokenDepositL; +IAmmalgamERC20 private _tokenDepositL; ``` ### _tokenDepositX ```solidity -IAmmalgamERC20 private immutable _tokenDepositX; +IAmmalgamERC20 private _tokenDepositX; ``` ### _tokenDepositY ```solidity -IAmmalgamERC20 private immutable _tokenDepositY; +IAmmalgamERC20 private _tokenDepositY; ``` ### _tokenBorrowL ```solidity -IAmmalgamERC20 private immutable _tokenBorrowL; +IAmmalgamERC20 private _tokenBorrowL; ``` ### _tokenBorrowX ```solidity -IAmmalgamERC20 private immutable _tokenBorrowX; +IAmmalgamERC20 private _tokenBorrowX; ``` ### _tokenBorrowY ```solidity -IAmmalgamERC20 private immutable _tokenBorrowY; +IAmmalgamERC20 private _tokenBorrowY; +``` + + +### factory + +```solidity +IFactoryCallback internal factory; +``` + + +### saturationAndGeometricTWAPState + +```solidity +ISaturationAndGeometricTWAPState internal saturationAndGeometricTWAPState; ``` @@ -74,7 +88,7 @@ uint112[6] private allShares; ### allAssets ```solidity -uint128[6] internal allAssets; +uint112[6] internal allAssets; ``` @@ -120,110 +134,89 @@ uint32 internal lastLendingTimestamp; ``` -### missingXAssets - -```solidity -uint112 internal missingXAssets; -``` - - -### missingYAssets +### lastReserveLiquidity ```solidity -uint112 internal missingYAssets; +uint112 internal lastReserveLiquidity; ``` -### lastPenaltyTimestamp +### externalLiquidity ```solidity -uint32 internal lastPenaltyTimestamp; +uint112 public override externalLiquidity; ``` -### lastReserveLiquidity +### fragileLiquidityShares ```solidity -uint128 internal lastReserveLiquidity; +uint112 internal fragileLiquidityShares; ``` -### lastActiveLiquidityAssets +### isFragileLiquidity ```solidity -uint128 internal lastActiveLiquidityAssets; +mapping(address => bool) internal isFragileLiquidity; ``` ### totalDepositLAssets ```solidity -uint256 internal totalDepositLAssets; +uint112 internal transient totalDepositLAssets; ``` ### totalDepositXAssets ```solidity -uint256 internal totalDepositXAssets; +uint112 internal transient totalDepositXAssets; ``` ### totalDepositYAssets ```solidity -uint256 internal totalDepositYAssets; +uint112 internal transient totalDepositYAssets; ``` ### totalBorrowLAssets ```solidity -uint256 internal totalBorrowLAssets; +uint112 internal transient totalBorrowLAssets; ``` ### totalBorrowXAssets ```solidity -uint256 internal totalBorrowXAssets; +uint112 internal transient totalBorrowXAssets; ``` ### totalBorrowYAssets ```solidity -uint256 internal totalBorrowYAssets; +uint112 internal transient totalBorrowYAssets; ``` -### externalLiquidity - -```solidity -uint112 public override externalLiquidity = 0; -``` - - -### factory - -```solidity -IFactoryCallback internal immutable factory; -``` - +## Functions +### constructor -### saturationAndGeometricTWAPState ```solidity -ISaturationAndGeometricTWAPState internal immutable saturationAndGeometricTWAPState; +constructor(); ``` - -## Functions -### constructor +### initialize ```solidity -constructor(); +function initialize() external virtual override initializer; ``` ### onlyFeeToSetter @@ -244,14 +237,14 @@ function _onlyFeeToSetter() private view; ```solidity -function underlyingTokens() public view override returns (IERC20, IERC20); +function underlyingTokens() public view virtual override returns (IERC20, IERC20); ``` ### updateAssets ```solidity -function updateAssets(uint256 tokenType, uint128 assets) private; +function updateAssets(uint256 tokenType, uint112 assets) private; ``` ### updateExternalLiquidity @@ -260,7 +253,7 @@ function updateAssets(uint256 tokenType, uint128 assets) private; ```solidity function updateExternalLiquidity( uint112 _externalLiquidity -) external onlyFeeToSetter; +) external virtual onlyFeeToSetter; ``` ### mintId @@ -283,7 +276,7 @@ function burnId(uint256 tokenType, address sender, address from, uint256 assets, ```solidity function tokens( uint256 tokenType -) public view override returns (IAmmalgamERC20); +) public view virtual override returns (IAmmalgamERC20); ``` ### balanceOf @@ -308,54 +301,110 @@ function totalShares( ```solidity function rawTotalAssets( uint256 tokenType -) internal view returns (uint128); +) internal view returns (uint112); ``` -### getReserves +### getRawReserves ```solidity -function getReserves() public view returns (uint112 _reserveXAssets, uint112 _reserveYAssets, uint32 _lastTimestamp); +function getRawReserves() internal view returns (uint112 _reserveXAssets, uint112 _reserveYAssets); ``` -### getTickRange +### getReserves ```solidity -function getTickRange() public view returns (int16 minTick, int16 maxTick); +function getReserves() + public + view + virtual + returns (uint112 _reserveXAssets, uint112 _reserveYAssets, uint32 _lastUpdateTimestamp); ``` ### referenceReserves ```solidity -function referenceReserves() public view returns (uint112, uint112); +function referenceReserves() external view virtual returns (uint112, uint112); ``` -### totalAssets +### totalAssetsAndShares -Computes the current total Assets. -*If the last lending state update is outdated (i.e., not matching the current block timestamp), -the function recalculates the assets based on the duration since the last update, the lending state, -and reserve balances. If the timestamp is current, the previous asset (without recalculation) is returned.* +```solidity +function totalAssetsAndShares( + bool withInterest +) public view virtual returns (uint112[6] memory _allAssets, uint112[6] memory _allShares); +``` + +### fragileLiquidityAssets ```solidity -function totalAssets() public view returns (uint128[6] memory); +function fragileLiquidityAssets() internal view returns (uint256 _fragileLiquidityAssets); +``` + +### updateFragileLiquidity + + +```solidity +function updateFragileLiquidity( + address validate +) internal; +``` + +### removeFragileLiquidity + + +```solidity +function removeFragileLiquidity( + address validate +) internal; +``` + +### computeAssetsState + +Recalculates current total assets, reserves, and protocol fees, accounting for elapsed time and interest. + +*Core logic for interest accrual and state updates (used by `totalAssetsAndShares` when `withInterest` is true): +1. Fetches raw reserves before computing interest. +2. If `totalDepositLAssets` is not 0, returns transient asset values immediately (no interest to accrue). +3. Calculates time elapsed since last update (`deltaUpdateTimestamp`) and last lending state check (`deltaLendingTimestamp`). +4. If no time has elapsed since last lending check (`deltaLendingTimestamp == 0`), returns stored values without recalculation. +5. Otherwise: +- Computes the current market tick via `getTickFromReserves()` and bounds it to valid ranges. +- Determines active lending state tick and saturation percentage using `getLendingStateTick()`. +- Calls `Interest.accrueInterestWithAssets()` to calculate interest, update asset values, and compute protocol fees. +- Adds LP-earned interest portions to X and Y reserves.* + + +```solidity +function computeAssetsState() + internal + view + returns ( + uint112[6] memory _allAssets, + uint112 _reserveXAssets, + uint112 _reserveYAssets, + uint256[3] memory protocolFees + ); ``` **Returns** |Name|Type|Description| |----|----|-----------| -|``|`uint128[6]`|totalAssets An array of six `uint128` values representing the total assets for each of the 6 amalgam token types. These values may be adjusted based on the time elapsed since the last update. If the timestamp is up-to-date, the previously calculated total assets are returned without recalculation.| +|`_allAssets`|`uint112[6]`|Array of six `uint112` values: Recalculated total assets for each of the 6 Amalgam token types (post-interest).| +|`_reserveXAssets`|`uint112`|Reserve balance for Asset X, updated with LP-earned interest.| +|`_reserveYAssets`|`uint112`|Reserve balance for Asset Y, updated with LP-earned interest.| +|`protocolFees`|`uint256[3]`|Array of three `uint256` values: Accumulated protocol fees for DEPOSIT_L, DEPOSIT_X, and DEPOSIT_Y (from interest accrual).| ### mintPenalties ```solidity -function mintPenalties(address account, uint32 deltaPenaltyTimestamp) internal; +function mintPenalties(address account, uint32 deltaLendingTimestamp) internal; ``` ### getAssets @@ -363,7 +412,8 @@ function mintPenalties(address account, uint32 deltaPenaltyTimestamp) internal; ```solidity function getAssets( - uint128[6] memory currentAssets, + uint112[6] memory _totalAssets, + uint112[6] memory _totalShares, address toCheck ) internal view returns (uint256[6] memory userAssets); ``` @@ -378,7 +428,7 @@ function updateTokenController( uint32 deltaLendingTimestamp, uint256 _reserveXAssets, uint256 _reserveYAssets -) internal returns (uint112 updatedReservesX, uint112 updatedReservesY); +) internal returns (uint256 updatedReservesX, uint256 updatedReservesY); ``` ### updateReferenceReserve @@ -394,7 +444,7 @@ function updateReferenceReserve( ```solidity -function mintProtocolFees(uint256 tokenType, address feeTo, uint256 protocolFee) private; +function mintProtocolFees(uint256 tokenType, address feeTo, uint256 protocolFee) internal; ``` ### updateReserves @@ -434,17 +484,10 @@ function getNetBalances(uint256 _reserveXAssets, uint256 _reserveYAssets) intern ```solidity -function missingAssets() internal view returns (uint112, uint112); +function missingAssets() internal view returns (uint112 missingXAssets, uint112 missingYAssets); ``` -### updateMissingAssets - - -```solidity -function updateMissingAssets() internal; -``` - -### getDepositAndBorrowAndActiveLiquidityAssets +### getDepositAndActiveLiquidityAssets Get the deposit, borrow, and active liquidity assets. @@ -452,91 +495,49 @@ Get the deposit, borrow, and active liquidity assets. ```solidity -function getDepositAndBorrowAndActiveLiquidityAssets() +function getDepositAndActiveLiquidityAssets() internal view - returns (uint256 depositLiquidityAssets, uint256 borrowLAssets, uint256 currentActiveLiquidityAssets); + returns (uint256 depositLiquidityAssets, uint256 currentActiveLiquidityAssets); ``` **Returns** |Name|Type|Description| |----|----|-----------| |`depositLiquidityAssets`|`uint256`|The deposit liquidity assets.| -|`borrowLAssets`|`uint256`|The borrow liquidity assets.| |`currentActiveLiquidityAssets`|`uint256`|The current active liquidity assets.| -### updateReservesAndActiveLiquidity - -Update the reserves and active liquidity. - -*This function is used to update the last reserves liquidity (RL_0) and last active liquidity assets (ALA_0).* +### burnBadDebt ```solidity -function updateReservesAndActiveLiquidity( - uint256 _reserveXAssets, - uint256 _reserveYAssets -) internal returns (uint256 adjustedActiveLiquidity); +function burnBadDebt(address borrower, uint256 tokenType, uint256 reserve) internal; ``` -**Parameters** - -|Name|Type|Description| -|----|----|-----------| -|`_reserveXAssets`|`uint256`|The reserve X assets.| -|`_reserveYAssets`|`uint256`|The reserve Y assets.| - - -### getAdjustedActiveLiquidity -Get the adjusted active liquidity which is the active liquidity without the swap fees. +### getUpdatedReferenceReserves -*This function is used to get the adjusted active liquidity.* +*Get the updated reference reserves based on the `newTick`.* ```solidity -function getAdjustedActiveLiquidity( - uint256 _reserveXAssets, - uint256 _reserveYAssets -) internal view returns (uint256 adjustedActiveLiquidity); +function getUpdatedReferenceReserves( + int256 newTick +) internal view returns (uint112, uint112); ``` **Parameters** |Name|Type|Description| |----|----|-----------| -|`_reserveXAssets`|`uint256`|The reserve X assets.| -|`_reserveYAssets`|`uint256`|The reserve Y assets.| +|`newTick`|`int256`|The current tick.| **Returns** |Name|Type|Description| |----|----|-----------| -|`adjustedActiveLiquidity`|`uint256`|The adjusted active liquidity.| - - -### getCurrentAndAdjustedActiveLiquidity - - -```solidity -function getCurrentAndAdjustedActiveLiquidity( - uint256 _reserveXAssets, - uint256 _reserveYAssets -) internal view returns (uint256 currentReserveLiquidity, uint256 adjustedActiveLiquidity); -``` - -### getCurrentReserveLiquidity - - -```solidity -function getCurrentReserveLiquidity(uint256 _reserveXAssets, uint256 _reserveYAssets) private pure returns (uint256); -``` +|``|`uint112`|_referenceReserveX The updated reference reserve X.| +|``|`uint112`|_referenceReserveY The updated reference reserve Y.| -### burnBadDebt - - -```solidity -function burnBadDebt(address borrower, uint256 tokenType, uint256 reserve) internal; -``` ## Errors ### Forbidden diff --git a/docs/developer-guide/contracts/utils/deployHelper.sol/function.deployFactory.md b/docs/developer-guide/contracts/utils/deployHelper.sol/function.deployFactory.md index a1ad9d0b..b2f230bd 100644 --- a/docs/developer-guide/contracts/utils/deployHelper.sol/function.deployFactory.md +++ b/docs/developer-guide/contracts/utils/deployHelper.sol/function.deployFactory.md @@ -1,21 +1,20 @@ # function deployFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/utils/deployHelper.sol) +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/974388d084e9a0078440a75c2b625a4b268d530b/contracts/utils/deployHelper.sol) ### deployFactory(address) ```solidity function deployFactory( - address deployer + address owner ) returns (AmmalgamFactory); ``` -### deployFactory(address, IPairFactory, address) +### deployFactory(address, ISaturationAndGeometricTWAPState) ```solidity function deployFactory( - address deployer, - IPairFactory pairFactory, - address saturationAndGeometricTWAPState + address owner, + ISaturationAndGeometricTWAPState saturationAndGeometricTWAPState ) returns (AmmalgamFactory); ``` diff --git a/docs/developer-guide/contracts/utils/deployHelper.sol/function.deployTokenFactory.md b/docs/developer-guide/contracts/utils/deployHelper.sol/function.deployTokenFactory.md deleted file mode 100644 index 7d10babb..00000000 --- a/docs/developer-guide/contracts/utils/deployHelper.sol/function.deployTokenFactory.md +++ /dev/null @@ -1,8 +0,0 @@ -# deployTokenFactory -[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/82dff11576b9df76b675736dba889653cf737de9/contracts/utils/deployHelper.sol) - - -```solidity -function deployTokenFactory() returns (INewTokensFactory); -``` -