diff --git a/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md b/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md index ebb7b742..e4da673b 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..e2af8812 100644 --- a/docs/developer-guide/contracts/SaturationAndGeometricTWAPState.sol/contract.SaturationAndGeometricTWAPState.md +++ b/docs/developer-guide/contracts/SaturationAndGeometricTWAPState.sol/contract.SaturationAndGeometricTWAPState.md @@ -1,22 +1,22 @@ # 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/SaturationAndGeometricTWAPState.sol) **Inherits:** -[ISaturationAndGeometricTWAPState](/docs/developer-guide/contracts/interfaces/ISaturationAndGeometricTWAPState.sol/interface.ISaturationAndGeometricTWAPState.md), Ownable +Initializable, [ISaturationAndGeometricTWAPState](/docs/developer-guide/contracts/interfaces/ISaturationAndGeometricTWAPState.sol/interface.ISaturationAndGeometricTWAPState.md), OwnableUpgradeable ## State Variables ### midTermIntervalConfig ```solidity -uint24 public immutable midTermIntervalConfig; +uint24 public midTermIntervalConfig; ``` ### longTermIntervalConfig ```solidity -uint24 public immutable longTermIntervalConfig; +uint24 public longTermIntervalConfig; ``` @@ -41,6 +41,13 @@ mapping(address => mapping(address => uint256)) maxNewPositionSaturationInMAG2; ``` +### lastUsedActiveLiquidityInLAssets + +```solidity +mapping(address => mapping(address => uint256)) lastUsedActiveLiquidityInLAssets; +``` + + ### isPairInitialized ```solidity @@ -53,7 +60,14 @@ mapping(address => bool) internal isPairInitialized; ```solidity -constructor(uint24 _midTermIntervalConfig, uint24 _longTermIntervalConfig) Ownable(msg.sender); +constructor(); +``` + +### initialize + + +```solidity +function initialize(uint24 _midTermIntervalConfig, uint24 _longTermIntervalConfig, address _owner) public initializer; ``` ### isInitialized @@ -90,16 +104,6 @@ function init( function setNewPositionSaturation(address pair, uint256 maxDesiredSaturationMag2) external; ``` -### getNewPositionSaturation - - -```solidity -function getNewPositionSaturation( - address pair, - address account -) internal view returns (uint256 maxDesiredSaturationInMAG2); -``` - ### getTree @@ -107,11 +111,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 +125,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 @@ -162,7 +161,11 @@ update the borrow position of an account and potentially check (and revert) if t ```solidity -function update(Validation.InputParams memory inputParams, address account) external virtual; +function update( + Validation.InputParams memory inputParams, + address account, + bool skipMinOrMaxTickCheck +) public virtual isInitialized; ``` **Parameters** @@ -170,14 +173,43 @@ 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| +|`skipMinOrMaxTickCheck`|`bool`|| -### _update +### 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 _update(Validation.InputParams memory inputParams, address account) internal isInitialized; +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 +310,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) public virtual isInitialized returns (bool); ``` **Parameters** @@ -325,17 +357,6 @@ function getTickRange( |``|`int16`|maxTick The maximum tick value among the three observed ticks.| -### _getTickRange - - -```solidity -function _getTickRange( - address pair, - int16 currentTick, - bool includeLongTermTick -) internal view returns (int16, int16); -``` - ### getLendingStateTickAndCheckpoint Gets the tick value representing the TWAP since the last @@ -390,30 +411,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..eb28cca6 100644 --- a/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.AmmalgamFactory.md +++ b/docs/developer-guide/contracts/factories/AmmalgamFactory.sol/contract.AmmalgamFactory.md @@ -1,43 +1,50 @@ # 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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; +IHookRegistry public immutable hookRegistry; ``` -### pluginRegistry +### liquidityTokenFactory ```solidity -address public immutable pluginRegistry; +ITokenFactory private immutable liquidityTokenFactory; ``` -### feeTo +### depositTokenFactory ```solidity -address public feeTo; +ITokenFactory private immutable depositTokenFactory; ``` -### feeToSetter +### debtTokenFactory ```solidity -address public feeToSetter; +ITokenFactory private immutable debtTokenFactory; +``` + + +### liquidityDebtTokenFactory + +```solidity +ITokenFactory private immutable liquidityDebtTokenFactory; ``` @@ -55,6 +62,20 @@ IFactoryCallback.TokenFactoryConfig private config; ``` +### feeTo + +```solidity +address public feeTo; +``` + + +### feeToSetter + +```solidity +address public feeToSetter; +``` + + ### getPair ```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 @@ -186,6 +241,12 @@ error PairExists(); error BytecodeLengthZero(); ``` +### NewSatProxyIsZeroAddress + +```solidity +error NewSatProxyIsZeroAddress(); +``` + ### FailedOnDeploy ```solidity @@ -204,3 +265,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..23883ec7 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..56ef6566 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..d03a11a4 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..b4f7cefe 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..47b6b223 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..eb0090f8 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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 @@ -74,7 +107,7 @@ update the borrow position of an account and potentially check (and revert) if t ```solidity -function update(Validation.InputParams memory inputParams, address account) external; +function update(Validation.InputParams memory inputParams, address account, bool skipMinOrMaxTickCheck) external; ``` **Parameters** @@ -82,6 +115,7 @@ 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| +|`skipMinOrMaxTickCheck`|`bool`| whether to skip the min/max tick check during validation| ### accruePenalties @@ -265,30 +299,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..c58f8117 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..e0e8bd89 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..2d12d803 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,8 +1,8 @@ # 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/interfaces/factories/IAmmalgamFactory.sol) **Inherits:** -[IFactoryCallback](/docs/developer-guide/contracts/interfaces/factories/IFactoryCallback.sol/interface.IFactoryCallback.md) +[IFactoryCallback](/docs/developer-guide/contracts/interfaces/factories/IFactoryCallback.sol/interface.IFactoryCallback.md), [IBeaconCallback](/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IBeaconCallback.md) ## Functions @@ -122,6 +122,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.IBeaconCallback.md b/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IBeaconCallback.md new file mode 100644 index 00000000..421065de --- /dev/null +++ b/docs/developer-guide/contracts/interfaces/factories/IAmmalgamFactory.sol/interface.IBeaconCallback.md @@ -0,0 +1,22 @@ +# IBeaconCallback +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/interfaces/factories/IAmmalgamFactory.sol) + + +## 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.| + + 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..9d511c39 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..45b5a57e 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..7f135598 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..5afcdb5d 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..b0574afe --- /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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..56e05ec1 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..3b9d4484 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/interfaces/tokens/ITokenController.sol) The interface of a ERC20 facade for multiple token types with functionality similar to ERC1155. @@ -25,7 +25,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 +35,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 +107,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 +192,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 +205,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..570121df 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..1ae56dd5 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..d4f9173f 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..116ba75a 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..0902dab9 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..1427a1cf 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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. +borrowed. \n 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: \n +```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 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, \n ```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. \n 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. +at which its LTV would reach LTVMAX, which is its liquidation (=liq) price. \n 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. +end for net debt of x and on the left of the end for net debt of Y. \n 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 +allow the insertion up to some max, set at 90% or the configuration set by the user. \n +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 @@ -63,6 +69,9 @@ its level ## 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 +79,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 +90,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 +99,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 +108,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 +117,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 +127,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 +146,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 +156,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 +165,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 +175,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 +185,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 +194,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 +203,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 +212,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 +221,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 +230,8 @@ uint256 internal constant LOWEST_LEVEL_INDEX = 2; ### LEAFS +$$1 << LEAFS_IN_BITS$$ + ```solidity uint256 internal constant LEAFS = 4096; @@ -196,6 +239,8 @@ uint256 internal constant LEAFS = 4096; ### CHILDREN_PER_NODE +$$1 << 4$$ + ```solidity uint256 internal constant CHILDREN_PER_NODE = 16; @@ -203,6 +248,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 +257,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 +277,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,68 +305,107 @@ 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_Q72 - 1$$ constant needed in formula. + ```solidity uint256 private constant B_Q72_MINUS_ONE = 0x1008040201008040200; ``` +### Q183 +A large number that will not overflow when multiplied by `B_Q72_MINUS_ONE` +$$\left\lfloor \frac{ 2^{ 128 } }{ B_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; +``` + + ## Functions ### initializeSaturationStruct @@ -346,7 +445,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 +456,8 @@ function update( SaturationStruct storage satStruct, Validation.InputParams memory inputParams, address account, - uint256 userSaturationRatioMAG2 + uint256 userSaturationRatioMAG2, + bool skipMinOrMaxTickCheck ) internal; ``` **Parameters** @@ -367,11 +468,13 @@ function update( |`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| |`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 +484,7 @@ function updateTreeGivenAccountTrancheAndSat( address account, int256 newEndOfLiquidationInTicks, uint256 activeLiquidityInLAssets, + int256 minOrMaxTick, uint256 userSaturationRatioMAG2 ) internal; ``` @@ -393,6 +497,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`|| @@ -425,7 +530,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,10 +558,12 @@ 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 @@ -472,7 +580,8 @@ function addSatToTranche( int256 newEndOfLiquidationInTicks, SaturationPair memory newSaturation, uint256 activeLiquidityInLAssets, - uint256 userSaturationRatioMAG2 + uint256 userSaturationRatioMAG2, + int256 minOrMaxTick ) internal returns (bool highestSetLeafAdded); ``` **Parameters** @@ -486,6 +595,7 @@ function addSatToTranche( |`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 +604,28 @@ function addSatToTranche( |`highestSetLeafAdded`|`bool`|flag indicating whether we removed sat from the highest leaf xor not| +### getUsableTicksAndLastTranche + + +```solidity +function getUsableTicksAndLastTranche( + int256 trancheDirection, + int256 endOfLiquidationTick +) internal pure returns (uint256 usableTicks, int256 lastTranche); +``` + +### restrictUsableTicksForMinOrMaxTick + + +```solidity +function restrictUsableTicksForMinOrMaxTick( + uint256 initialUsableTicks, + int256 trancheDirection, + int256 nextTranche, + int256 minOrMaxTick +) internal pure returns (uint256 usableTicks); +``` + ### getAddSatToTrancheStateUpdatesParams convenience struct holding the params needed to run `addSatToTrancheStateUpdates` @@ -502,12 +634,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 +647,12 @@ function getAddSatToTrancheStateUpdatesParams( |Name|Type|Description| |----|----|-----------| |`tree`|`Tree`|that is being read from or written to| +|`account`|`address`|who's 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 +663,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 @@ -685,7 +818,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 @@ -707,7 +841,8 @@ function accrueAccountPenalty(Tree storage tree, address account) internal retur ### 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 @@ -918,31 +1053,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 +1084,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 +1107,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 +1139,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 +1198,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 +1228,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 @@ -1160,14 +1289,15 @@ function calcSatChangeRatioBips( 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 +1310,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 @@ -1240,7 +1370,7 @@ function calcSatAvailableToAddToTranche( uint128 targetSatToAddInLAssets, uint128 currentTrancheSatInLAssets, uint256 userSaturationRatioMAG2, - uint256 quarters + uint256 usableTicks ) internal pure returns (uint128 satAvailableToAddInLAssets); ``` **Parameters** @@ -1249,9 +1379,9 @@ function calcSatAvailableToAddToTranche( |----|----|-----------| |`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`|| +|`currentTrancheSatInLAssets`|`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** @@ -1260,17 +1390,21 @@ function calcSatAvailableToAddToTranche( |`satAvailableToAddInLAssets`|`uint128`| considering the `currentTrancheSatInLAssets` and the max a tranche can have| -### 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 desiredThresholdMag2, - bool netDebtX + bool netDebtX, + bool skipLiqStartsPastPriceCheck ) internal pure returns (int256 endOfLiquidationInTicks, SaturationPair memory saturation); ``` **Parameters** @@ -1278,9 +1412,10 @@ function calcLastTrancheAndSaturation( |Name|Type|Description| |----|----|-----------| |`inputParams`|`Validation.InputParams`| the input params| -|`liqSqrtPriceInXInQ72`|`uint256`| the liq sqrt price in X| +|`liqSqrtPriceInXInQ72`|`uint256`| the midpoint of liquidation sqrt price in X| |`desiredThresholdMag2`|`uint256`| the desired threshold| |`netDebtX`|`bool`| whether the net debt is X or Y| +|`skipLiqStartsPastPriceCheck`|`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** @@ -1298,15 +1433,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 +1453,70 @@ 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{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) +debtX \left(\frac{ b^{tSpan - t_1} }{ B-1 }\right) +\text{ when debt is in X asset }\\ +debtY \left(\frac{ b^{tSpan + t_0} }{ B-1 }\right) \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.\n +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 +1587,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)* +*This implements the penalty rate function \n +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 +1616,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 +1628,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 CannotUpdateZeroAddress(); +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 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 +1675,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 +1694,8 @@ struct Tree { ``` ### Leaf +a leaf contains multiple tranches and contains the total sat and penalty for the leaf + ```solidity struct Leaf { @@ -1588,6 +1706,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 +1721,8 @@ struct Account { ``` ### CalcLiqSqrtPriceHandleAllABCNonZeroStruct +used in memory to avoid stack overflow in `calcLiqSqrtPriceQ72()`. + ```solidity struct CalcLiqSqrtPriceHandleAllABCNonZeroStruct { @@ -1613,6 +1736,8 @@ struct CalcLiqSqrtPriceHandleAllABCNonZeroStruct { ``` ### AddSatToTrancheStateUpdatesStruct +used in memory to avoid stack overflow in `addSatToTranche()`. + ```solidity struct AddSatToTrancheStateUpdatesStruct { @@ -1625,3 +1750,14 @@ struct AddSatToTrancheStateUpdatesStruct { } ``` +### 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..8c5457b6 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..199f1596 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..0ea353c3 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..c1fd6328 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..286c7c9e 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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,19 @@ uint256 constant B_IN_Q72 = 0x1008040201008040201; ``` ### TRANCHE_B_IN_Q72 -*In Saturation we combine 100 ticks to make one tranche. -```python ->>> hex(int(mpm.nint(mpm.fdiv(2**9, 2**9-1)**100 * 2**72))) -```* - - -```solidity -uint256 constant TRANCHE_B_IN_Q72 = 0x13746bb4eee2a5b6cd4; -``` - -### 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. +*In Saturation we combine 25 ticks to make one tranche. ```python >>> hex(int(mpm.nint(mpm.fdiv(2**9, 2**9-1)**25 * 2**72))) ```* ```solidity -uint256 constant TRANCHE_QUARTER_B_IN_Q72 = 0x10cd2b2ae53a69d3552; +uint256 constant TRANCHE_B_IN_Q72 = 0x10cd2b2ae53a69d3552; ``` ### 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 +102,14 @@ uint256 constant Q64 = 0x10000000000000000; uint256 constant Q72 = 0x1000000000000000000; ``` +### Q88 +*2**88.* + + +```solidity +uint256 constant Q88 = 0x10000000000000000000000; +``` + ### Q112 *2**112.* @@ -130,11 +127,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 +150,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 +297,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 +328,94 @@ 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; +``` + +### INDEX_FULL_IMPL +*index implementation for default full functionality* + + +```solidity +uint256 constant INDEX_FULL_IMPL = 0; +``` + +### INDEX_LOCKED_LOANS +*index implementation that locks borrowing, withdrawing, burning, except liquidation* + + +```solidity +uint256 constant INDEX_LOCKED_LOANS = 1; +``` + +### INDEX_BLOCK_ALL_TRANSFERS +*index implementation that blocks all transfers: withdraw, burn, borrow and liquidation* + + +```solidity +uint256 constant INDEX_BLOCK_ALL_TRANSFERS = 2; +``` + +### INDEX_FROZEN +*index implementation that freezes any function calling the pair: mints, swaps, ..etc* + + +```solidity +uint256 constant INDEX_FROZEN = 3; ``` diff --git a/docs/developer-guide/contracts/proxy/BeaconController.sol/contract.BeaconController.md b/docs/developer-guide/contracts/proxy/BeaconController.sol/contract.BeaconController.md new file mode 100644 index 00000000..fc4c301d --- /dev/null +++ b/docs/developer-guide/contracts/proxy/BeaconController.sol/contract.BeaconController.md @@ -0,0 +1,160 @@ +# BeaconController +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/proxy/BeaconController.sol) + +**Inherits:** +[IBeaconController](/docs/developer-guide/contracts/proxy/BeaconController.sol/interface.IBeaconController.md), AccessControl + + +## State Variables +### ADMIN_ROLE + +```solidity +bytes32 public constant ADMIN_ROLE = AccessControl.DEFAULT_ADMIN_ROLE; +``` + + +### MULTISIG_ROLE + +```solidity +bytes32 public constant MULTISIG_ROLE = keccak256('MULTISIG_ROLE'); +``` + + +### ADMIN_OR_MULTISIG_ROLE + +```solidity +bytes32 public constant ADMIN_OR_MULTISIG_ROLE = keccak256('ADMIN_OR_MULTISIG_ROLE'); +``` + + +### upgradeableBeacon + +```solidity +UpgradeableBeacon public immutable upgradeableBeacon; +``` + + +### _allowedIndex + +```solidity +mapping(address => uint256) private _allowedIndex; +``` + + +### _allowedList + +```solidity +address[] private _allowedList; +``` + + +## Functions +### constructor + + +```solidity +constructor(address timelock, address multisig, address initialImpl, address[] memory initialAllowed); +``` + +### upgradeTo + + +```solidity +function upgradeTo( + address implementation +) external onlyRole(ADMIN_ROLE); +``` + +### upgradeToAllowed + + +```solidity +function upgradeToAllowed( + address impl +) external onlyRole(MULTISIG_ROLE); +``` + +### allowedList + + +```solidity +function allowedList() external view returns (address[] memory); +``` + +### isAllowed + + +```solidity +function isAllowed( + address impl +) public view returns (bool); +``` + +### addToAllowedList + + +```solidity +function addToAllowedList( + address implementation +) external onlyRole(ADMIN_ROLE); +``` + +### removeFromAllowedList + + +```solidity +function removeFromAllowedList( + address implementation +) external onlyRole(ADMIN_OR_MULTISIG_ROLE); +``` + +### _addToAllowedList + + +```solidity +function _addToAllowedList( + address impl +) private; +``` + +### _removeFromAllowedList + + +```solidity +function _removeFromAllowedList( + address impl +) private; +``` + +## Events +### AllowedAdded + +```solidity +event AllowedAdded(address indexed implementation, address indexed by); +``` + +### AllowedRemoved + +```solidity +event AllowedRemoved(address indexed implementation, address indexed by); +``` + +## Errors +### ZERO_ADDRESS + +```solidity +error ZERO_ADDRESS(); +``` + +### NOT_ALLOWED + +```solidity +error NOT_ALLOWED(); +``` + +### ALREADY_ALLOWED + +```solidity +error ALREADY_ALLOWED(); +``` + diff --git a/docs/developer-guide/contracts/proxy/BeaconController.sol/interface.IBeaconController.md b/docs/developer-guide/contracts/proxy/BeaconController.sol/interface.IBeaconController.md new file mode 100644 index 00000000..ff4e9e47 --- /dev/null +++ b/docs/developer-guide/contracts/proxy/BeaconController.sol/interface.IBeaconController.md @@ -0,0 +1,83 @@ +# IBeaconController +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/proxy/BeaconController.sol) + + +## Functions +### upgradeTo + +a wrapper around UpgradeableBeacon to delegate to its upgradeTo function. + + +```solidity +function upgradeTo( + address implementation +) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`implementation`|`address`|the new implementation address to set in the beacon.| + + +### upgradeToAllowed + +allows upgrades to a set of pre-approved implementations only with different +privileges than upgradeTo. + + +```solidity +function upgradeToAllowed( + address implementation +) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`implementation`|`address`|the new implementation address to set in the beacon.| + + +### allowedList + +gets the list of allowed implementations for emergency upgrades. + + +```solidity +function allowedList() external view returns (address[] memory); +``` + +### addToAllowedList + +adds an implementation to the allowed list. + + +```solidity +function addToAllowedList( + address implementation +) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`implementation`|`address`|the implementation address to add.| + + +### removeFromAllowedList + +removes an implementation from the allowed list. + + +```solidity +function removeFromAllowedList( + address implementation +) external; +``` +**Parameters** + +|Name|Type|Description| +|----|----|-----------| +|`implementation`|`address`|the implementation address to remove.| + + diff --git a/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.InitializablePair.md b/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.InitializablePair.md new file mode 100644 index 00000000..84a05d8e --- /dev/null +++ b/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.InitializablePair.md @@ -0,0 +1,43 @@ +# InitializablePair +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/proxy/PairBeaconProxy.sol) + +**Inherits:** +[IPairInitializable](/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/interface.IPairInitializable.md), Initializable + + +## Functions +### constructor + + +```solidity +constructor(); +``` + +### initialize + + +```solidity +function initialize() external initializer; +``` + +### _initialize + + +```solidity +function _initialize() internal virtual; +``` + +### reInitialize + + +```solidity +function reInitialize() external reinitializer(_getInitializedVersion() + 1); +``` + +### _reInitialize + + +```solidity +function _reInitialize() internal virtual; +``` + 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..8041b155 --- /dev/null +++ b/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.PairBeaconProxy.md @@ -0,0 +1,97 @@ +# PairBeaconProxy +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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(IPairInitializable.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; +``` + +### _initialize + + +```solidity +function _initialize( + address beaconImplementation +) external; +``` + +### _staticCall + +Adapted version of OZ Proxy._delegate() + + +```solidity +function _staticCall( + address implementation +) internal virtual; +``` + +### _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; +``` + +### receive + + +```solidity +receive() external payable; +``` + +## Errors +### EthTransferNotAllowed + +```solidity +error EthTransferNotAllowed(); +``` + +### AccessDenied + +```solidity +error AccessDenied(); +``` + diff --git a/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/interface.IPairInitializable.md b/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/interface.IPairInitializable.md new file mode 100644 index 00000000..0b661e12 --- /dev/null +++ b/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/interface.IPairInitializable.md @@ -0,0 +1,19 @@ +# IPairInitializable +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/proxy/PairBeaconProxy.sol) + + +## Functions +### initialize + + +```solidity +function initialize() external; +``` + +### reInitialize + + +```solidity +function reInitialize() external; +``` + diff --git a/docs/developer-guide/contracts/proxy/PairBlockAllTransfers.sol/contract.PairBlockAllTransfers.md b/docs/developer-guide/contracts/proxy/PairBlockAllTransfers.sol/contract.PairBlockAllTransfers.md new file mode 100644 index 00000000..2fa3ff6c --- /dev/null +++ b/docs/developer-guide/contracts/proxy/PairBlockAllTransfers.sol/contract.PairBlockAllTransfers.md @@ -0,0 +1,83 @@ +# PairBlockAllTransfers +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/proxy/PairBlockAllTransfers.sol) + +**Inherits:** +[AmmalgamPair](/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md) + + +## Functions +### withdraw + + +```solidity +function withdraw( + address +) public pure override; +``` + +### burn + + +```solidity +function burn( + address +) public pure override returns (uint256, uint256); +``` + +### 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); +``` + +### liquidate + + +```solidity +function liquidate( + address, + address, + uint256, + uint256, + uint256, + uint256, + uint256, + uint256, + uint256, + uint256 +) public pure override; +``` + +## Errors +### WITHDRAW_BLOCKED + +```solidity +error WITHDRAW_BLOCKED(); +``` + +### BURN_BLOCKED + +```solidity +error BURN_BLOCKED(); +``` + +### BORROW_BLOCKED + +```solidity +error BORROW_BLOCKED(); +``` + +### LIQUIDATION_BLOCKED + +```solidity +error LIQUIDATION_BLOCKED(); +``` + diff --git a/docs/developer-guide/contracts/proxy/PairFrozen.sol/contract.PairFrozen.md b/docs/developer-guide/contracts/proxy/PairFrozen.sol/contract.PairFrozen.md new file mode 100644 index 00000000..6b0fd0b6 --- /dev/null +++ b/docs/developer-guide/contracts/proxy/PairFrozen.sol/contract.PairFrozen.md @@ -0,0 +1,22 @@ +# PairFrozen +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/proxy/PairFrozen.sol) + +**Inherits:** +[InitializablePair](/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.InitializablePair.md) + + +## Functions +### fallback + + +```solidity +fallback() external; +``` + +## Errors +### FROZEN + +```solidity +error FROZEN(); +``` + diff --git a/docs/developer-guide/contracts/proxy/PairLockedLoans.sol/contract.PairLockedLoans.md b/docs/developer-guide/contracts/proxy/PairLockedLoans.sol/contract.PairLockedLoans.md new file mode 100644 index 00000000..b4554b34 --- /dev/null +++ b/docs/developer-guide/contracts/proxy/PairLockedLoans.sol/contract.PairLockedLoans.md @@ -0,0 +1,59 @@ +# PairLockedLoans +[Git Source](https://github.com/Ammalgam-Protocol/core-v1/blob/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/proxy/PairLockedLoans.sol) + +**Inherits:** +[AmmalgamPair](/docs/developer-guide/contracts/AmmalgamPair.sol/contract.AmmalgamPair.md) + + +## Functions +### 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); +``` + +### withdraw + + +```solidity +function withdraw( + address +) external pure override; +``` + +### burn + + +```solidity +function burn( + address +) external pure override returns (uint256, uint256); +``` + +## Errors +### BORROW_LOCKED + +```solidity +error BORROW_LOCKED(); +``` + +### WITHDRAW_LOCKED + +```solidity +error WITHDRAW_LOCKED(); +``` + +### BURN_LOCKED + +```solidity +error BURN_LOCKED(); +``` + 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..eebca610 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..cc8b388c 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..713e625e 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..c8246039 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..f534188e 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..873ae308 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..4fae72a7 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..2628ec1b --- /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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/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..c6f5f2ce 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/tokens/TokenController.sol) **Inherits:** -[ITokenController](/docs/developer-guide/contracts/interfaces/tokens/ITokenController.sol/interface.ITokenController.md) +[InitializablePair](/docs/developer-guide/contracts/proxy/PairBeaconProxy.sol/contract.InitializablePair.md), [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,68 @@ uint32 internal lastLendingTimestamp; ``` -### missingXAssets - -```solidity -uint112 internal missingXAssets; -``` - - -### missingYAssets - -```solidity -uint112 internal missingYAssets; -``` - - -### lastPenaltyTimestamp - -```solidity -uint32 internal lastPenaltyTimestamp; -``` - - ### lastReserveLiquidity ```solidity -uint128 internal lastReserveLiquidity; -``` - - -### lastActiveLiquidityAssets - -```solidity -uint128 internal lastActiveLiquidityAssets; +uint112 internal lastReserveLiquidity; ``` ### 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; -``` - - -### saturationAndGeometricTWAPState - -```solidity -ISaturationAndGeometricTWAPState internal immutable saturationAndGeometricTWAPState; +uint112 public override externalLiquidity; ``` ## Functions -### constructor +### _initialize ```solidity -constructor(); +function _initialize() internal virtual override; ``` ### onlyFeeToSetter @@ -244,14 +216,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 +232,7 @@ function updateAssets(uint256 tokenType, uint128 assets) private; ```solidity function updateExternalLiquidity( uint112 _externalLiquidity -) external onlyFeeToSetter; +) external virtual onlyFeeToSetter; ``` ### mintId @@ -283,7 +255,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 +280,85 @@ 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); +``` + +### 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 totalAssets() public view returns (uint128[6] memory); +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 +366,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 +382,7 @@ function updateTokenController( uint32 deltaLendingTimestamp, uint256 _reserveXAssets, uint256 _reserveYAssets -) internal returns (uint112 updatedReservesX, uint112 updatedReservesY); +) internal returns (uint256 updatedReservesX, uint256 updatedReservesY); ``` ### updateReferenceReserve @@ -394,7 +398,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 +438,10 @@ function getNetBalances(uint256 _reserveXAssets, uint256 _reserveYAssets) intern ```solidity -function missingAssets() internal view returns (uint112, uint112); -``` - -### updateMissingAssets - - -```solidity -function updateMissingAssets() internal; +function missingAssets() internal view returns (uint112 missingXAssets, uint112 missingYAssets); ``` -### getDepositAndBorrowAndActiveLiquidityAssets +### getDepositAndActiveLiquidityAssets Get the deposit, borrow, and active liquidity assets. @@ -452,91 +449,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 +### getUpdatedReferenceReserves -Get the adjusted active liquidity which is the active liquidity without the swap fees. - -*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); -``` +|``|`uint112`|_referenceReserveX The updated reference reserve X.| +|``|`uint112`|_referenceReserveY The updated reference reserve Y.| -### getCurrentReserveLiquidity - - -```solidity -function getCurrentReserveLiquidity(uint256 _reserveXAssets, uint256 _reserveYAssets) private pure returns (uint256); -``` - -### 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..ee09a454 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,22 @@ # 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/61b1ab7701fa14fd2a7118a53d1bf31ffec17c1a/contracts/utils/deployHelper.sol) ### deployFactory(address) ```solidity function deployFactory( address deployer -) returns (AmmalgamFactory); +) returns (AmmalgamFactory, TimelockController); ``` -### deployFactory(address, IPairFactory, address) +### deployFactory(address, TimelockController, IAmmalgamPair, ISaturationAndGeometricTWAPState) ```solidity function deployFactory( address deployer, - IPairFactory pairFactory, - address saturationAndGeometricTWAPState -) returns (AmmalgamFactory); + TimelockController timelock, + IAmmalgamPair pairImplementation, + ISaturationAndGeometricTWAPState satProxy +) returns (AmmalgamFactory, TimelockController); ``` 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); -``` -