Verified contractExactBUSL-1.1
LikwidMarginPosition
Address0x6bec0c1dc4898484b7f094566ddf8bc82ed7abe8
- Balance
0 ETH
- Transactions
4
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- prague
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,445,398
- Creation transaction
- 0x96828a0f3c…0a0f6570e1
64 files
- src/LikwidMarginPosition.solmain31.28 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol16.1 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol997 B
- lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol792 B
- lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Utils.sol1.92 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol19.28 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol879 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.15 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- lib/solmate/src/auth/Owned.sol1.47 KB
- src/base/BasePositionManager.sol4.6 KB
- src/base/ImmutableState.sol478 B
- src/interfaces/IBasePositionManager.sol431 B
- src/interfaces/IExtsload.sol1.02 KB
- src/interfaces/IExttload.sol699 B
- src/interfaces/IImmutableState.sol253 B
- src/interfaces/IMarginBase.sol1.31 KB
- src/interfaces/IMarginPositionManager.sol11.84 KB
- src/interfaces/IVault.sol14.01 KB
- src/interfaces/callback/IUnlockCallback.sol488 B
- src/interfaces/external/IERC6909Claims.sol3.16 KB
- src/libraries/CurrencyPoolLibrary.sol2.27 KB
- src/libraries/CurrentStateLibrary.sol6.6 KB
- src/libraries/CustomRevert.sol5.17 KB
- src/libraries/FeeLibrary.sol1.47 KB
- src/libraries/FixedPoint96.sol366 B
- src/libraries/InterestMath.sol6.5 KB
- src/libraries/LendPosition.sol2.17 KB
- src/libraries/LiquidityMath.sol2.01 KB
- src/libraries/MarginPosition.sol9.83 KB
- src/libraries/Math.sol12.99 KB
- src/libraries/PairPosition.sol2.49 KB
- src/libraries/PerLibrary.sol1.37 KB
- src/libraries/PositionLibrary.sol2.64 KB
- src/libraries/PriceMath.sol2.28 KB
- src/libraries/ProtocolFeeLibrary.sol3.48 KB
- src/libraries/SafeCast.sol2.35 KB
- src/libraries/StateLibrary.sol12.7 KB
- src/libraries/SwapMath.sol8.83 KB
- src/libraries/TimeLibrary.sol503 B
- src/types/BalanceDelta.sol2.34 KB
- src/types/Currency.sol5.01 KB
- src/types/FeeTypes.sol151 B
- src/types/InsuranceFunds.sol2.37 KB
- src/types/MarginActions.sol165 B
- src/types/MarginBalanceDelta.sol463 B
- src/types/MarginLevels.sol4.04 KB
- src/types/MarginState.sol6.51 KB
- src/types/PoolId.sol539 B
- src/types/PoolKey.sol628 B
- src/types/PoolState.sol663 B
- src/types/Reserves.sol6.7 KB
- src/types/Slot0.sol4.43 KB
src/LikwidMarginPosition.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.26;
// Local
import {BasePositionManager} from "./base/BasePositionManager.sol";
import {IMarginPositionManager} from "./interfaces/IMarginPositionManager.sol";
import {IVault} from "./interfaces/IVault.sol";
import {CurrencyPoolLibrary} from "./libraries/CurrencyPoolLibrary.sol";
import {CustomRevert} from "./libraries/CustomRevert.sol";
import {FeeLibrary} from "./libraries/FeeLibrary.sol";
import {MarginPosition} from "./libraries/MarginPosition.sol";
import {Math} from "./libraries/Math.sol";
import {PerLibrary} from "./libraries/PerLibrary.sol";
import {PositionLibrary} from "./libraries/PositionLibrary.sol";
import {SafeCast} from "./libraries/SafeCast.sol";
import {StateLibrary} from "./libraries/StateLibrary.sol";
import {CurrentStateLibrary} from "./libraries/CurrentStateLibrary.sol";
import {TimeLibrary} from "./libraries/TimeLibrary.sol";
import {SwapMath} from "./libraries/SwapMath.sol";
import {MarginActions} from "./types/MarginActions.sol";
import {BalanceDelta, toBalanceDelta} from "./types/BalanceDelta.sol";
import {Currency, CurrencyLibrary} from "./types/Currency.sol";
import {MarginLevels, MarginLevelsLibrary} from "./types/MarginLevels.sol";
import {PoolId} from "./types/PoolId.sol";
import {PoolKey} from "./types/PoolKey.sol";
import {Reserves} from "./types/Reserves.sol";
import {PoolState} from "./types/PoolState.sol";
import {MarginBalanceDelta} from "./types/MarginBalanceDelta.sol";
contract LikwidMarginPosition is IMarginPositionManager, BasePositionManager {
using SafeCast for *;
using CurrencyLibrary for Currency;
using CurrencyPoolLibrary for Currency;
using PerLibrary for uint256;
using FeeLibrary for uint24;
using CustomRevert for bytes4;
using PositionLibrary for address;
using MarginLevelsLibrary for MarginLevels;
using TimeLibrary for uint32;
using MarginPosition for MarginPosition.State;
uint8 constant MAX_LEVERAGE = 5; // 5x
uint8 constant MAX_MIRROR_RATIO = 80; // 80%
uint24 constant MARGIN_MINIMUM_RATIO = 10000000; // 1/1000_0000
mapping(uint256 tokenId => MarginPosition.State positionInfo) private positionInfos;
MarginLevels public marginLevels;
constructor(address initialOwner, IVault _vault)
BasePositionManager("LIKWIDMarginPositionManager", "LMPM", initialOwner, _vault)
{
MarginLevels _marginLevels;
_marginLevels = _marginLevels.setMinMarginLevel(1170000);
_marginLevels = _marginLevels.setMinBorrowLevel(1400000);
_marginLevels = _marginLevels.setLiquidateLevel(1100000);
_marginLevels = _marginLevels.setLiquidationRatio(950000);
_marginLevels = _marginLevels.setCallerProfit(10000);
marginLevels = _marginLevels;
}
function _unlockCallback(bytes calldata data) internal override returns (bytes memory) {
(MarginActions action, bytes memory params) = abi.decode(data, (MarginActions, bytes));
if (action == MarginActions.LIQUIDATE_BURN) {
return _handleLiquidateBurn(params);
} else {
return _handleMargin(params);
}
}
function getPositionState(uint256 tokenId) external view returns (MarginPosition.State memory position) {
PoolId poolId = poolIds[tokenId];
PoolState memory state = _getPoolState(poolId);
position = positionInfos[tokenId];
(uint256 borrowCumulativeLast, uint256 depositCumulativeLast) =
_getPoolCumulativeValues(state, position.marginForOne);
position.marginAmount =
Math.mulDiv(position.marginAmount, depositCumulativeLast, position.depositCumulativeLast).toUint128();
position.marginTotal =
Math.mulDiv(position.marginTotal, depositCumulativeLast, position.depositCumulativeLast).toUint128();
position.debtAmount =
Math.mulDivRoundingUp(position.debtAmount, borrowCumulativeLast, position.borrowCumulativeLast).toUint128();
position.depositCumulativeLast = depositCumulativeLast;
position.borrowCumulativeLast = borrowCumulativeLast;
}
/// @inheritdoc IMarginPositionManager
function addMargin(PoolKey memory key, IMarginPositionManager.CreateParams calldata params)
external
payable
ensure(params.deadline)
returns (uint256 tokenId, uint256 borrowAmount, uint256 swapFeeAmount)
{
tokenId = _mintPosition(key, params.recipient);
positionInfos[tokenId].marginForOne = params.marginForOne;
(borrowAmount, swapFeeAmount) = _margin(
msg.sender,
params.recipient,
IMarginPositionManager.MarginParams({
tokenId: tokenId,
leverage: params.leverage,
marginAmount: params.marginAmount,
borrowAmount: params.borrowAmount,
borrowAmountMax: params.borrowAmountMax,
deadline: params.deadline
})
);
}
function _margin(address sender, address tokenOwner, IMarginPositionManager.MarginParams memory params)
internal
returns (uint256 borrowAmount, uint256 swapFeeAmount)
{
if (params.leverage > MAX_LEVERAGE) {
ExceedMaxLeverage.selector.revertWith();
}
_requireAuth(tokenOwner, params.tokenId);
PoolId poolId = poolIds[params.tokenId];
PoolState memory poolState = _getPoolState(poolId);
if (poolState.lpFee < 3000) revert LowFeePoolMarginBanned();
PoolKey memory key = poolKeys[poolId];
MarginPosition.State storage position = positionInfos[params.tokenId];
MarginBalanceDelta memory delta;
delta.action = MarginActions.MARGIN;
delta.marginForOne = position.marginForOne;
uint256 marginReserve = poolState.pairReserves.reserve01(position.marginForOne);
if (params.marginAmount < marginReserve / MARGIN_MINIMUM_RATIO) {
MarginBelowMinimum.selector.revertWith();
}
uint256 minLevel;
if (params.leverage > 0) {
minLevel = marginLevels.minMarginLevel();
(borrowAmount, delta.marginFeeAmount, swapFeeAmount) =
_executeAddLeverage(params, poolState, position, delta);
} else {
minLevel = marginLevels.minBorrowLevel();
borrowAmount = _executeAddCollateralAndBorrow(params, poolState, position, delta, minLevel);
}
if (params.borrowAmountMax > 0 && borrowAmount > params.borrowAmountMax) {
ExceedBorrowAmountMax.selector.revertWith();
}
delta.swapFeeAmount = swapFeeAmount;
bytes memory callbackData = abi.encode(sender, key, delta);
bytes memory data = abi.encode(delta.action, callbackData);
vault.unlock(data);
_checkMinLevelAfterUnlock(poolId, position, minLevel);
emit Margin(
key.toId(),
tokenOwner,
params.tokenId,
position.marginAmount,
position.marginTotal,
position.debtAmount,
position.marginForOne
);
}
/// @inheritdoc IMarginPositionManager
function margin(IMarginPositionManager.MarginParams memory params)
external
payable
ensure(params.deadline)
returns (uint256 borrowAmount, uint256 swapFeeAmount)
{
(borrowAmount, swapFeeAmount) = _margin(msg.sender, msg.sender, params);
}
function _executeAddLeverage(
IMarginPositionManager.MarginParams memory params,
PoolState memory poolState,
MarginPosition.State storage position,
MarginBalanceDelta memory delta
) internal returns (uint256 borrowAmount, uint256 marginFeeAmount, uint256 swapFeeAmount) {
uint256 marginReserves = poolState.realReserves.reserve01(position.marginForOne);
uint256 marginTotal = params.marginAmount * params.leverage;
if (marginTotal > marginReserves) ReservesNotEnough.selector.revertWith();
delta.marginTotal = marginTotal.toUint128();
uint256 marginWithoutFee;
(marginWithoutFee, marginFeeAmount) = poolState.marginFee.deduct(marginTotal);
(borrowAmount,, swapFeeAmount) = SwapMath.getAmountIn(
poolState.pairReserves, poolState.truncatedReserves, poolState.lpFee, position.marginForOne, marginTotal
);
params.borrowAmount = borrowAmount.toUint128();
uint256 borrowCumulativeLast;
uint256 depositCumulativeLast;
if (position.marginForOne) {
borrowCumulativeLast = poolState.borrow0CumulativeLast;
depositCumulativeLast = poolState.deposit1CumulativeLast;
} else {
borrowCumulativeLast = poolState.borrow1CumulativeLast;
depositCumulativeLast = poolState.deposit0CumulativeLast;
}
uint256 borrowMirrorReserves = poolState.mirrorReserves.reserve01(!position.marginForOne) + borrowAmount;
uint256 borrowRealReserves = poolState.realReserves.reserve01(!position.marginForOne);
if (Math.mulDiv(borrowMirrorReserves, 100, borrowRealReserves + borrowMirrorReserves) > MAX_MIRROR_RATIO) {
MirrorTooMuch.selector.revertWith();
}
position.update(
borrowCumulativeLast,
depositCumulativeLast,
params.marginAmount.toInt128(),
marginWithoutFee,
params.borrowAmount,
0
);
int128 amount = -params.marginAmount.toInt128();
int128 lendAmount = amount - marginWithoutFee.toInt128();
if (position.marginForOne) {
delta.marginDelta = toBalanceDelta(0, amount);
delta.pairDelta = toBalanceDelta(-borrowAmount.toInt128(), marginWithoutFee.toInt128());
delta.lendDelta = toBalanceDelta(0, lendAmount);
delta.mirrorDelta = toBalanceDelta(-borrowAmount.toInt128(), 0);
} else {
delta.marginDelta = toBalanceDelta(amount, 0);
delta.pairDelta = toBalanceDelta(marginWithoutFee.toInt128(), -borrowAmount.toInt128());
delta.lendDelta = toBalanceDelta(lendAmount, 0);
delta.mirrorDelta = toBalanceDelta(0, -borrowAmount.toInt128());
}
}
function _executeAddCollateralAndBorrow(
IMarginPositionManager.MarginParams memory params,
PoolState memory poolState,
MarginPosition.State storage position,
MarginBalanceDelta memory delta,
uint256 minBorrowLevel
) internal returns (uint256 borrowAmount) {
(uint256 borrowMaxAmount,) = SwapMath.getAmountOut(
poolState.pairReserves, poolState.lpFee, !position.marginForOne, params.marginAmount
);
if (minBorrowLevel > PerLibrary.ONE_MILLION) {
borrowMaxAmount = Math.mulDiv(borrowMaxAmount, PerLibrary.ONE_MILLION, minBorrowLevel);
}
uint256 borrowRealReserves = poolState.realReserves.reserve01(!position.marginForOne);
borrowMaxAmount = Math.min(borrowMaxAmount, borrowRealReserves * 20 / 100);
if (params.borrowAmount == type(uint256).max) params.borrowAmount = borrowMaxAmount.toUint128();
if (params.borrowAmount > borrowMaxAmount) BorrowTooMuch.selector.revertWith();
borrowAmount = params.borrowAmount;
uint256 borrowCumulativeLast;
uint256 depositCumulativeLast;
if (position.marginForOne) {
borrowCumulativeLast = poolState.borrow0CumulativeLast;
depositCumulativeLast = poolState.deposit1CumulativeLast;
} else {
borrowCumulativeLast = poolState.borrow1CumulativeLast;
depositCumulativeLast = poolState.deposit0CumulativeLast;
}
uint256 borrowMirrorReserves = poolState.mirrorReserves.reserve01(!position.marginForOne) + borrowAmount;
borrowRealReserves -= borrowAmount;
if (Math.mulDiv(borrowMirrorReserves, 100, borrowRealReserves + borrowMirrorReserves) > MAX_MIRROR_RATIO) {
MirrorTooMuch.selector.revertWith();
}
position.update(
borrowCumulativeLast, depositCumulativeLast, params.marginAmount.toInt128(), 0, params.borrowAmount, 0
);
int128 amount0Delta;
int128 amount1Delta;
int128 amount = -params.marginAmount.toInt128();
if (position.marginForOne) {
amount1Delta = amount;
amount0Delta = borrowAmount.toInt128();
delta.lendDelta = toBalanceDelta(0, amount);
delta.mirrorDelta = toBalanceDelta(-borrowAmount.toInt128(), 0);
} else {
amount0Delta = amount;
amount1Delta = borrowAmount.toInt128();
delta.lendDelta = toBalanceDelta(amount, 0);
delta.mirrorDelta = toBalanceDelta(0, -borrowAmount.toInt128());
}
delta.marginDelta = toBalanceDelta(amount0Delta, amount1Delta);
}
/// @inheritdoc IMarginPositionManager
function repay(uint256 tokenId, uint256 repayAmount, uint256 deadline) external payable ensure(deadline) {
_requireAuth(msg.sender, tokenId);
PoolId poolId = poolIds[tokenId];
PoolKey memory key = poolKeys[poolId];
PoolState memory poolState = _getPoolState(poolId);
MarginPosition.State storage position = positionInfos[tokenId];
(uint256 borrowCumulativeLast, uint256 depositCumulativeLast) =
_getPoolCumulativeValues(poolState, position.marginForOne);
(uint256 releaseAmount, uint256 realRepayAmount) =
position.update(borrowCumulativeLast, depositCumulativeLast, 0, 0, 0, repayAmount);
int128 amount0Delta;
int128 amount1Delta;
MarginBalanceDelta memory delta;
if (position.marginForOne) {
amount0Delta = -realRepayAmount.toInt128();
amount1Delta = releaseAmount.toInt128();
delta.lendDelta = toBalanceDelta(0, amount1Delta);
delta.mirrorDelta = toBalanceDelta(realRepayAmount.toInt128(), 0);
} else {
amount0Delta = releaseAmount.toInt128();
amount1Delta = -realRepayAmount.toInt128();
delta.lendDelta = toBalanceDelta(amount0Delta, 0);
delta.mirrorDelta = toBalanceDelta(0, realRepayAmount.toInt128());
}
delta.action = MarginActions.REPAY;
delta.marginForOne = position.marginForOne;
delta.marginDelta = toBalanceDelta(amount0Delta, amount1Delta);
bytes memory callbackData = abi.encode(msg.sender, key, delta);
bytes memory data = abi.encode(delta.action, callbackData);
vault.unlock(data);
_checkMinLevelAfterUnlock(poolId, position, marginLevels.liquidateLevel());
emit Repay(
key.toId(),
msg.sender,
tokenId,
position.marginAmount,
position.marginTotal,
position.debtAmount,
releaseAmount,
realRepayAmount
);
}
/// @inheritdoc IMarginPositionManager
function close(uint256 tokenId, uint24 closeMillionth, uint256 closeAmountMin, uint256 deadline)
external
ensure(deadline)
{
_requireAuth(msg.sender, tokenId);
PoolId poolId = poolIds[tokenId];
PoolState memory poolState = _getPoolState(poolId);
MarginPosition.State storage position = positionInfos[tokenId];
(uint256 borrowCumulativeLast, uint256 depositCumulativeLast) =
_getPoolCumulativeValues(poolState, position.marginForOne);
uint24 liquidateLevel = marginLevels.liquidateLevel();
_checkMinLevel(
poolState.truncatedReserves, borrowCumulativeLast, depositCumulativeLast, position, liquidateLevel
);
(uint256 releaseAmount, uint256 repayAmount, uint256 closeAmount, uint256 lostAmount, uint256 swapFeeAmount) = position.close(
poolState.pairReserves,
poolState.truncatedReserves,
poolState.lpFee,
borrowCumulativeLast,
depositCumulativeLast,
0,
closeMillionth
);
if (lostAmount > 0 || (closeAmountMin > 0 && closeAmount < closeAmountMin)) {
InsufficientCloseReceived.selector.revertWith();
}
int128 amount0Delta;
int128 amount1Delta;
MarginBalanceDelta memory delta;
if (position.marginForOne) {
amount1Delta = closeAmount.toInt128();
delta.lendDelta = toBalanceDelta(0, releaseAmount.toInt128());
delta.mirrorDelta = toBalanceDelta(repayAmount.toInt128(), 0);
delta.pairDelta = toBalanceDelta(repayAmount.toInt128(), -(releaseAmount - closeAmount).toInt128());
} else {
amount0Delta = closeAmount.toInt128();
delta.lendDelta = toBalanceDelta(releaseAmount.toInt128(), 0);
delta.mirrorDelta = toBalanceDelta(0, repayAmount.toInt128());
delta.pairDelta = toBalanceDelta(-(releaseAmount - closeAmount).toInt128(), repayAmount.toInt128());
}
delta.action = MarginActions.CLOSE;
delta.swapFeeAmount = swapFeeAmount;
delta.marginForOne = position.marginForOne;
delta.marginDelta = toBalanceDelta(amount0Delta, amount1Delta);
PoolKey memory key = poolKeys[poolId];
bytes memory callbackData = abi.encode(msg.sender, key, delta);
bytes memory data = abi.encode(delta.action, callbackData);
vault.unlock(data);
_checkMinLevelAfterUnlock(poolId, position, liquidateLevel);
emit Close(
key.toId(),
msg.sender,
tokenId,
position.marginAmount,
position.marginTotal,
position.debtAmount,
releaseAmount,
repayAmount,
closeAmount
);
}
/// @inheritdoc IMarginPositionManager
function liquidateCall(uint256 tokenId, uint256 deadline)
external
payable
ensure(deadline)
returns (uint256 profit, uint256 repayAmount)
{
_requireOwned(tokenId);
PoolId poolId = poolIds[tokenId];
PoolState memory poolState = _getPoolState(poolId);
MarginPosition.State storage position = positionInfos[tokenId];
(bool liquidated, uint256 marginAmount, uint256 marginTotal, uint256 debtAmount) =
_checkLiquidate(poolState, position);
if (!liquidated) {
PositionNotLiquidated.selector.revertWith();
}
PoolKey memory key = poolKeys[poolId];
(uint128 reserve0, uint128 reserve1) = poolState.truncatedReserves.reserves();
(uint256 reserveBorrow, uint256 reserveMargin) =
position.marginForOne ? (reserve0, reserve1) : (reserve1, reserve0);
uint24 _liquidationRatio = marginLevels.liquidationRatio();
profit = marginAmount + marginTotal;
repayAmount = Math.mulDivRoundingUp(reserveBorrow, profit, reserveMargin);
uint256 needPayAmount = repayAmount.mulDivMillion(_liquidationRatio);
(uint256 borrowCumulativeLast, uint256 depositCumulativeLast) =
_getPoolCumulativeValues(poolState, position.marginForOne);
uint256 releaseAmount;
(releaseAmount, repayAmount) = position.update(borrowCumulativeLast, depositCumulativeLast, 0, 0, 0, debtAmount);
if (profit != releaseAmount) {
InsufficientReceived.selector.revertWith();
}
uint256 lostAmount;
uint256 fundAmount;
if (debtAmount > needPayAmount) {
lostAmount = debtAmount - needPayAmount;
} else {
fundAmount = needPayAmount - debtAmount;
}
int128 amount0Delta;
int128 amount1Delta;
MarginBalanceDelta memory delta;
if (position.marginForOne) {
amount0Delta = -needPayAmount.toInt128();
amount1Delta = releaseAmount.toInt128();
delta.lendDelta = toBalanceDelta(0, amount1Delta);
delta.mirrorDelta = toBalanceDelta(debtAmount.toInt128(), 0);
if (lostAmount > 0) {
delta.fundsDelta = toBalanceDelta(-lostAmount.toInt128(), 0);
} else {
delta.fundsDelta = toBalanceDelta(fundAmount.toInt128(), 0);
}
} else {
amount0Delta = releaseAmount.toInt128();
amount1Delta = -needPayAmount.toInt128();
delta.lendDelta = toBalanceDelta(amount0Delta, 0);
delta.mirrorDelta = toBalanceDelta(0, debtAmount.toInt128());
if (lostAmount > 0) {
delta.fundsDelta = toBalanceDelta(0, -lostAmount.toInt128());
} else {
delta.fundsDelta = toBalanceDelta(0, fundAmount.toInt128());
}
}
delta.action = MarginActions.LIQUIDATE_CALL;
delta.marginForOne = position.marginForOne;
delta.marginDelta = toBalanceDelta(amount0Delta, amount1Delta);
bytes memory callbackData = abi.encode(msg.sender, key, delta);
bytes memory data = abi.encode(delta.action, callbackData);
vault.unlock(data);
emit LiquidateCall(
key.toId(),
msg.sender,
tokenId,
marginAmount,
marginTotal,
debtAmount,
poolState.truncatedReserves,
poolState.pairReserves,
releaseAmount,
repayAmount,
needPayAmount,
lostAmount,
fundAmount
);
}
/// @inheritdoc IMarginPositionManager
function liquidateBurn(uint256 tokenId, uint256 deadline) external ensure(deadline) returns (uint256 profit) {
_requireOwned(tokenId);
PoolId poolId = poolIds[tokenId];
PoolState memory poolState = _getPoolState(poolId);
MarginPosition.State storage position = positionInfos[tokenId];
(bool liquidated, uint256 marginAmount, uint256 marginTotal, uint256 debtAmount) =
_checkLiquidate(poolState, position);
if (!liquidated) {
PositionNotLiquidated.selector.revertWith();
}
PoolKey memory key = poolKeys[poolId];
uint256 assetsAmount = marginAmount + marginTotal;
profit = assetsAmount.mulDivMillion(marginLevels.callerProfit());
uint256 releaseAmount;
uint256 repayAmount;
uint256 lostAmount;
uint256 closeAmount;
Reserves pairReserves = poolState.pairReserves;
Reserves truncatedReserves = poolState.truncatedReserves;
uint24 lpFee = poolState.lpFee;
{
uint256 swapFeeAmount;
(uint256 borrowCumulativeLast, uint256 depositCumulativeLast) =
_getPoolCumulativeValues(poolState, position.marginForOne);
(releaseAmount, repayAmount, closeAmount, lostAmount, swapFeeAmount) = position.close(
pairReserves,
truncatedReserves,
lpFee,
borrowCumulativeLast,
depositCumulativeLast,
profit,
uint24(PerLibrary.ONE_MILLION)
);
MarginBalanceDelta memory delta;
delta.swapFeeAmount = swapFeeAmount;
if (position.marginForOne) {
delta.marginDelta = toBalanceDelta(0, profit.toInt128());
delta.lendDelta = toBalanceDelta(0, (releaseAmount + profit).toInt128());
delta.mirrorDelta = toBalanceDelta(repayAmount.toInt128(), 0);
delta.pairDelta =
toBalanceDelta((repayAmount - lostAmount).toInt128(), -(releaseAmount - closeAmount).toInt128());
delta.fundsDelta = toBalanceDelta(-lostAmount.toInt128(), closeAmount.toInt128());
} else {
delta.marginDelta = toBalanceDelta(profit.toInt128(), 0);
delta.lendDelta = toBalanceDelta((releaseAmount + profit).toInt128(), 0);
delta.mirrorDelta = toBalanceDelta(0, repayAmount.toInt128());
delta.pairDelta =
toBalanceDelta(-(releaseAmount - closeAmount).toInt128(), (repayAmount - lostAmount).toInt128());
delta.fundsDelta = toBalanceDelta(closeAmount.toInt128(), -lostAmount.toInt128());
}
delta.action = MarginActions.LIQUIDATE_BURN;
delta.marginForOne = position.marginForOne;
bytes memory callbackData = abi.encode(msg.sender, key, delta, profit);
bytes memory data = abi.encode(delta.action, callbackData);
vault.unlock(data);
}
emit LiquidateBurn(
key.toId(),
msg.sender,
tokenId,
marginAmount,
marginTotal,
debtAmount,
truncatedReserves,
pairReserves,
releaseAmount,
repayAmount,
profit,
lostAmount,
closeAmount
);
}
/// @inheritdoc IMarginPositionManager
function modify(uint256 tokenId, int128 changeAmount, uint256 deadline) external payable ensure(deadline) {
_requireAuth(msg.sender, tokenId);
PoolId poolId = poolIds[tokenId];
PoolKey memory key = poolKeys[poolId];
PoolState memory poolState = _getPoolState(poolId);
MarginPosition.State storage position = positionInfos[tokenId];
MarginBalanceDelta memory delta;
(uint256 borrowCumulativeLast, uint256 depositCumulativeLast) =
_getPoolCumulativeValues(poolState, position.marginForOne);
position.update(borrowCumulativeLast, depositCumulativeLast, changeAmount, 0, 0, 0);
int128 amount0Delta;
int128 amount1Delta;
if (position.marginForOne) {
amount1Delta = -changeAmount.toInt128();
delta.lendDelta = toBalanceDelta(0, amount1Delta);
} else {
amount0Delta = -changeAmount.toInt128();
delta.lendDelta = toBalanceDelta(amount0Delta, 0);
}
delta.action = MarginActions.MODIFY;
delta.marginForOne = position.marginForOne;
delta.marginDelta = toBalanceDelta(amount0Delta, amount1Delta);
bytes memory callbackData = abi.encode(msg.sender, key, delta);
bytes memory data = abi.encode(delta.action, callbackData);
vault.unlock(data);
if (changeAmount < 0) {
_checkMinLevelAfterUnlock(poolId, position, marginLevels.minBorrowLevel());
}
emit Modify(
key.toId(),
msg.sender,
tokenId,
position.marginAmount,
position.marginTotal,
position.debtAmount,
changeAmount
);
}
function _handleMargin(bytes memory _data) internal returns (bytes memory) {
(address sender, PoolKey memory key, MarginBalanceDelta memory params) =
abi.decode(_data, (address, PoolKey, MarginBalanceDelta));
(BalanceDelta delta) = vault.marginBalance(key, params);
_processDelta(sender, sender, key, delta, 0, 0, 0, 0);
return "";
}
function _handleLiquidateBurn(bytes memory _data) internal returns (bytes memory) {
(address sender, PoolKey memory key, MarginBalanceDelta memory params, uint256 callerProfitAmount) =
abi.decode(_data, (address, PoolKey, MarginBalanceDelta, uint256));
vault.marginBalance(key, params);
if (callerProfitAmount > 0) {
Currency marginCurrency = params.marginForOne ? key.currency1 : key.currency0;
marginCurrency.take(vault, sender, callerProfitAmount, false);
}
return abi.encode(callerProfitAmount);
}
function _getPoolState(PoolId poolId) internal view returns (PoolState memory state) {
state = CurrentStateLibrary.getState(vault, poolId);
}
/// @dev Gets the last cumulative borrow and deposit values for a given position.
/// @param poolState The current state of the pool.
/// @param marginForOne Whether the margin is on token1.
/// @return borrowCumulativeLast The last cumulative borrow value.
/// @return depositCumulativeLast The last cumulative deposit value.
function _getPoolCumulativeValues(PoolState memory poolState, bool marginForOne)
private
pure
returns (uint256 borrowCumulativeLast, uint256 depositCumulativeLast)
{
if (marginForOne) {
borrowCumulativeLast = poolState.borrow0CumulativeLast;
depositCumulativeLast = poolState.deposit1CumulativeLast;
} else {
borrowCumulativeLast = poolState.borrow1CumulativeLast;
depositCumulativeLast = poolState.deposit0CumulativeLast;
}
}
function _checkLiquidate(PoolState memory state, MarginPosition.State memory position)
internal
view
returns (bool liquidated, uint256 marginAmount, uint256 marginTotal, uint256 debtAmount)
{
(uint256 borrowCumulativeLast, uint256 depositCumulativeLast) =
_getPoolCumulativeValues(state, position.marginForOne);
// use truncatedReserves
uint256 level = position.marginLevel(state.truncatedReserves, borrowCumulativeLast, depositCumulativeLast);
liquidated = level <= marginLevels.liquidateLevel();
if (liquidated) {
marginAmount = Math.mulDiv(position.marginAmount, depositCumulativeLast, position.depositCumulativeLast);
marginTotal = Math.mulDiv(position.marginTotal, depositCumulativeLast, position.depositCumulativeLast);
debtAmount = Math.mulDivRoundingUp(position.debtAmount, borrowCumulativeLast, position.borrowCumulativeLast);
}
}
function _checkMinLevel(
Reserves pairReserves,
uint256 borrowCumulativeLast,
uint256 depositCumulativeLast,
MarginPosition.State memory position,
uint256 minLevel
) internal pure {
uint256 level = position.marginLevel(pairReserves, borrowCumulativeLast, depositCumulativeLast);
if (level < minLevel) {
InvalidLevel.selector.revertWith();
}
}
function _checkMinLevelAfterUnlock(PoolId poolId, MarginPosition.State memory position, uint256 minLevel)
internal
view
{
Reserves pairReserves = StateLibrary.getPairReserves(vault, poolId);
Reserves truncatedReserves = StateLibrary.getTruncatedReserves(vault, poolId);
uint256 pairLevel = position.marginLevel(pairReserves);
uint256 truncatedLevel = position.marginLevel(truncatedReserves);
uint256 level = Math.min(pairLevel, truncatedLevel);
if (level < minLevel) {
InvalidLevel.selector.revertWith();
}
}
// ******************** OWNER CALL ********************
function setMarginLevel(bytes32 _marginLevel) external onlyOwner {
MarginLevels newMarginLevels = MarginLevels.wrap(_marginLevel);
if (!newMarginLevels.isValidMarginLevels()) InvalidLevel.selector.revertWith();
bytes32 old = MarginLevels.unwrap(marginLevels);
marginLevels = newMarginLevels;
emit MarginLevelChanged(old, _marginLevel);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "./IERC721.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {ERC721Utils} from "./utils/ERC721Utils.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
mapping(uint256 tokenId => address) private _owners;
mapping(address owner => uint256) private _balances;
mapping(uint256 tokenId => address) private _tokenApprovals;
mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc IERC721
function balanceOf(address owner) public view virtual returns (uint256) {
if (owner == address(0)) {
revert ERC721InvalidOwner(address(0));
}
return _balances[owner];
}
/// @inheritdoc IERC721
function ownerOf(uint256 tokenId) public view virtual returns (address) {
return _requireOwned(tokenId);
}
/// @inheritdoc IERC721Metadata
function name() public view virtual returns (string memory) {
return _name;
}
/// @inheritdoc IERC721Metadata
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/// @inheritdoc IERC721Metadata
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
_requireOwned(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/// @inheritdoc IERC721
function approve(address to, uint256 tokenId) public virtual {
_approve(to, tokenId, _msgSender());
}
/// @inheritdoc IERC721
function getApproved(uint256 tokenId) public view virtual returns (address) {
_requireOwned(tokenId);
return _getApproved(tokenId);
}
/// @inheritdoc IERC721
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/// @inheritdoc IERC721
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return _operatorApprovals[owner][operator];
}
/// @inheritdoc IERC721
function transferFrom(address from, address to, uint256 tokenId) public virtual {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
address previousOwner = _update(to, tokenId, _msgSender());
if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/// @inheritdoc IERC721
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/// @inheritdoc IERC721
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
transferFrom(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
* core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
*/
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
return _tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
* particular (ignoring whether it is owned by `owner`).
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
return
spender != address(0) &&
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
}
/**
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
* Reverts if:
* - `spender` does not have approval from `owner` for `tokenId`.
* - `spender` does not have approval to manage all of `owner`'s assets.
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
if (!_isAuthorized(owner, spender, tokenId)) {
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else {
revert ERC721InsufficientApproval(spender, tokenId);
}
}
}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
*
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
* remain consistent with one another.
*/
function _increaseBalance(address account, uint128 value) internal virtual {
unchecked {
_balances[account] += value;
}
}
/**
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
*
* Emits a {Transfer} event.
*
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
*/
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
address from = _ownerOf(tokenId);
// Perform (optional) operator check
if (auth != address(0)) {
_checkAuthorized(from, auth, tokenId);
}
// Execute the update
if (from != address(0)) {
// Clear approval. No need to re-authorize or emit the Approval event
_approve(address(0), tokenId, address(0), false);
unchecked {
_balances[from] -= 1;
}
}
if (to != address(0)) {
unchecked {
_balances[to] += 1;
}
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
return from;
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner != address(0)) {
revert ERC721InvalidSender(address(0));
}
}
/**
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal {
address previousOwner = _update(address(0), tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
* are aware of the ERC-721 standard to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is like {safeTransferFrom} in the sense that it invokes
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `tokenId` token must exist and be owned by `from`.
* - `to` cannot be the zero address.
* - `from` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId) internal {
_safeTransfer(from, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
* either the owner of the token, or approved to operate on all tokens held by this owner.
*
* Emits an {Approval} event.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address to, uint256 tokenId, address auth) internal {
_approve(to, tokenId, auth, true);
}
/**
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
* emitted in the context of transfers.
*/
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
// Avoid reading the owner unless necessary
if (emitEvent || auth != address(0)) {
address owner = _requireOwned(tokenId);
// We do not use _isAuthorized because single-token approvals should not be able to call approve
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
revert ERC721InvalidApprover(auth);
}
if (emitEvent) {
emit Approval(owner, to, tokenId);
}
}
_tokenApprovals[tokenId] = to;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Requirements:
* - operator can't be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
if (operator == address(0)) {
revert ERC721InvalidOperator(operator);
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
* Returns the owner.
*
* Overrides to ownership logic should be done to {_ownerOf}.
*/
function _requireOwned(uint256 tokenId) internal view returns (address) {
address owner = _ownerOf(tokenId);
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
return owner;
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity >=0.5.0;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity >=0.6.2;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/utils/ERC721Utils.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";
/**
* @dev Library that provide common ERC-721 utility functions.
*
* See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
*
* _Available since v5.1._
*/
library ERC721Utils {
/**
* @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
*
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
* Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC721Received(
address operator,
address from,
address to,
uint256 tokenId,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
// Token rejected
revert IERC721Errors.ERC721InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC721Receiver implementer
revert IERC721Errors.ERC721InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(reason, 0x20), mload(reason))
}
}
}
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
lib/solmate/src/auth/Owned.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OwnershipTransferred(address indexed user, address indexed newOwner);
/*//////////////////////////////////////////////////////////////
OWNERSHIP STORAGE
//////////////////////////////////////////////////////////////*/
address public owner;
modifier onlyOwner() virtual {
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(address _owner) {
owner = _owner;
emit OwnershipTransferred(address(0), _owner);
}
/*//////////////////////////////////////////////////////////////
OWNERSHIP LOGIC
//////////////////////////////////////////////////////////////*/
function transferOwnership(address newOwner) public virtual onlyOwner {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
src/base/BasePositionManager.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.26;
// Openzeppelin
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// Solmate
import {Owned} from "solmate/src/auth/Owned.sol";
// Local
import {IBasePositionManager} from "../interfaces/IBasePositionManager.sol";
import {ImmutableState} from "./ImmutableState.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {Currency, CurrencyLibrary} from "../types/Currency.sol";
import {IVault} from "../interfaces/IVault.sol";
import {IUnlockCallback} from "../interfaces/callback/IUnlockCallback.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
import {CurrencyPoolLibrary} from "../libraries/CurrencyPoolLibrary.sol";
abstract contract BasePositionManager is IBasePositionManager, ImmutableState, IUnlockCallback, ERC721, Owned {
using CurrencyPoolLibrary for Currency;
using CustomRevert for bytes4;
uint256 public nextId = 1;
mapping(uint256 tokenId => PoolId poolId) public poolIds;
mapping(PoolId poolId => PoolKey poolKey) public poolKeys;
constructor(string memory name_, string memory symbol_, address initialOwner, IVault _vault)
ImmutableState(_vault)
Owned(initialOwner)
ERC721(name_, symbol_)
{}
modifier ensure(uint256 deadline) {
_ensure(deadline);
_;
}
function _ensure(uint256 deadline) internal view {
require(deadline == 0 || deadline >= block.timestamp, "EXPIRED");
}
/// @notice Only allow calls from the LikwidVault contract
modifier onlyVault() {
_onlyVault();
_;
}
function _onlyVault() internal view {
if (msg.sender != address(vault)) revert NotVault();
}
function _requireAuth(address spender, uint256 tokenId) internal view {
if (spender != ownerOf(tokenId)) {
NotOwner.selector.revertWith();
}
}
function _clearNative(address spender) internal {
// clear any native currency left in the contract
uint256 balance = address(this).balance;
if (balance > 0) {
CurrencyLibrary.ADDRESS_ZERO.transfer(spender, balance);
}
}
function _processDelta(
address sender,
address recipient,
PoolKey memory key,
BalanceDelta delta,
uint256 amount0Min,
uint256 amount1Min,
uint256 amount0Max,
uint256 amount1Max
) internal returns (uint256 amount0, uint256 amount1) {
amount0 = delta.amount0() < 0 ? uint256(-int256(delta.amount0())) : uint256(int256(delta.amount0()));
if ((amount0Min > 0 && amount0 < amount0Min) || (amount0Max > 0 && amount0 > amount0Max)) {
PriceSlippageTooHigh.selector.revertWith();
}
if (delta.amount0() < 0) {
key.currency0.settle(vault, sender, amount0, false);
} else if (delta.amount0() > 0) {
key.currency0.take(vault, recipient, amount0, false);
}
amount1 = delta.amount1() < 0 ? uint256(-int256(delta.amount1())) : uint256(int256(delta.amount1()));
if ((amount1Min > 0 && amount1 < amount1Min) || (amount1Max > 0 && amount1 > amount1Max)) {
PriceSlippageTooHigh.selector.revertWith();
}
if (delta.amount1() < 0) {
key.currency1.settle(vault, sender, amount1, false);
} else if (delta.amount1() > 0) {
key.currency1.take(vault, recipient, amount1, false);
}
_clearNative(sender);
}
function _mintPosition(PoolKey memory key, address to) internal returns (uint256 tokenId) {
tokenId = nextId++;
_mint(to, tokenId);
PoolId poolId = key.toId();
poolIds[tokenId] = poolId;
if (poolKeys[poolId].currency1 == Currency.wrap(address(0))) {
poolKeys[poolId] = key;
} else {
PoolKey memory existingKey = poolKeys[poolId];
if (!(existingKey.currency0 == key.currency0 && existingKey.currency1 == key.currency1
&& existingKey.fee == key.fee && existingKey.marginFee == key.marginFee)) {
MismatchedPoolKey.selector.revertWith();
}
}
}
function _unlockCallback(bytes calldata data) internal virtual returns (bytes memory) {}
/// @inheritdoc IUnlockCallback
function unlockCallback(bytes calldata data) external onlyVault returns (bytes memory) {
return _unlockCallback(data);
}
}
src/base/ImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IVault} from "../interfaces/IVault.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";
/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
/// @inheritdoc IImmutableState
IVault public immutable vault;
constructor(IVault _vault) {
vault = _vault;
}
}
src/interfaces/IBasePositionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IImmutableState} from "./IImmutableState.sol";
interface IBasePositionManager is IImmutableState {
error NotOwner();
error NotVault();
error InvalidCallback();
error PriceSlippageTooHigh();
error MismatchedPoolKey();
function poolIds(uint256 tokenId) external view returns (PoolId poolId);
}
src/interfaces/IExtsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
src/interfaces/IExttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
src/interfaces/IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IVault} from "./IVault.sol";
/// @title Interface for ImmutableState
interface IImmutableState {
/// @notice The vault contract
function vault() external view returns (IVault);
}
src/interfaces/IMarginBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {MarginState} from "../types/MarginState.sol";
/// @notice Interface for all interest-fee related functions in the pool manager
interface IMarginBase {
error Unauthorized();
event MarginControllerUpdated(address indexed marginController);
/// @notice Emitted when the rate state is updated
/// @param newMarginState The new rate state being set
/// @dev This event is emitted when the rate state is updated, allowing external observers to
event MarginStateUpdated(MarginState indexed newMarginState);
event InsuranceFundPercentageUpdated(PoolId poolId, uint8 insuranceFundPercentage);
/// @notice Sets the rate state for interest fees
/// @param newMarginState The new rate state to set
/// @dev This function allows the owner to update the rate state, which is used to
/// calculate interest fees. It emits a MarginStateUpdated event upon success.
/// @dev Only the owner can call this function.
/// @dev Reverts if the caller is not the owner.
function setMarginState(MarginState newMarginState) external;
function marginState() external view returns (MarginState);
function marginController() external view returns (address);
}
src/interfaces/IMarginPositionManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {Reserves} from "../types/Reserves.sol";
import {MarginLevels} from "../types/MarginLevels.sol";
import {IBasePositionManager} from "./IBasePositionManager.sol";
import {MarginPosition} from "../libraries/MarginPosition.sol";
interface IMarginPositionManager is IBasePositionManager {
/// @notice Thrown when the provided level is invalid
error InvalidLevel();
/// @notice Thrown when the received borrow amount is insufficient
error InsufficientBorrowReceived();
/// @notice Thrown when the received close amount is insufficient
error InsufficientCloseReceived();
/// @notice Thrown when the received amount is insufficient
error InsufficientReceived();
/// @notice Thrown when the position is already liquidated
error PositionLiquidated();
/// @notice Thrown when the position is not liquidated
error PositionNotLiquidated();
/// @notice Thrown when the mirror amount is too high
error MirrorTooMuch();
/// @notice Thrown when the borrow amount is too high
error BorrowTooMuch();
/// @notice Thrown when the reserves are not enough
error ReservesNotEnough();
/// @notice Thrown when margin is banned for low fee pools
error LowFeePoolMarginBanned();
/// @notice Thrown when the margin is below the minimum required
error MarginBelowMinimum();
/// @notice Thrown when the leverage exceeds the maximum allowed
error ExceedMaxLeverage();
/// @notice Thrown when the borrow amount exceeds the maximum allowed
error ExceedBorrowAmountMax();
/// @notice Emitted when the margin level is changed
/// @param oldLevel The old margin level
/// @param newLevel The new margin level
event MarginLevelChanged(bytes32 oldLevel, bytes32 newLevel);
/// @notice Emitted when the margin fee is changed
/// @param oldFee The old margin fee
/// @param newFee The new margin fee
event MarginFeeChanged(uint24 oldFee, uint24 newFee);
/// @notice Emitted when a margin position is created or increased
/// @param poolId The ID of the pool
/// @param owner The owner of the position
/// @param tokenId The ID of the position token
/// @param marginAmount The amount of margin added
/// @param marginTotal The total margin of the position
/// @param debtAmount The total debt of the position
/// @param marginForOne Whether the margin is for currency1
event Margin(
PoolId indexed poolId,
address indexed owner,
uint256 tokenId,
uint256 marginAmount,
uint256 marginTotal,
uint256 debtAmount,
bool marginForOne
);
/// @notice Emitted when a margin position is repaid
/// @param poolId The ID of the pool
/// @param sender The address of the repayer
/// @param tokenId The ID of the position token
/// @param marginAmount The amount of margin in the position
/// @param marginTotal The total margin of the position
/// @param debtAmount The total debt of the position
/// @param releaseAmount The amount of margin released
/// @param repayAmount The amount of debt repaid
event Repay(
PoolId indexed poolId,
address indexed sender,
uint256 tokenId,
uint256 marginAmount,
uint256 marginTotal,
uint256 debtAmount,
uint256 releaseAmount,
uint256 repayAmount
);
/// @notice Emitted when a margin position is closed
/// @param poolId The ID of the pool
/// @param sender The address of the closer
/// @param tokenId The ID of the position token
/// @param marginAmount The amount of margin in the position
/// @param marginTotal The total margin of the position
/// @param debtAmount The total debt of the position
/// @param releaseAmount The amount of margin released
/// @param repayAmount The amount of debt repaid
/// @param closeAmount The amount received after closing
event Close(
PoolId indexed poolId,
address indexed sender,
uint256 tokenId,
uint256 marginAmount,
uint256 marginTotal,
uint256 debtAmount,
uint256 releaseAmount,
uint256 repayAmount,
uint256 closeAmount
);
/// @notice Emitted when a margin position is modified
/// @param poolId The ID of the pool
/// @param sender The address of the modifier
/// @param tokenId The ID of the position token
/// @param marginAmount The amount of margin in the position
/// @param marginTotal The total margin of the position
/// @param debtAmount The total debt of the position
/// @param changeAmount The amount of change in the position
event Modify(
PoolId indexed poolId,
address indexed sender,
uint256 tokenId,
uint256 marginAmount,
uint256 marginTotal,
uint256 debtAmount,
int256 changeAmount
);
/// @notice Emitted when a margin position is liquidated by burning
/// @param poolId The ID of the pool
/// @param sender The address of the liquidator
/// @param tokenId The ID of the position token
/// @param marginAmount The amount of margin in the position
/// @param marginTotal The total margin of the position
/// @param debtAmount The total debt of the position
/// @param truncatedReserves The truncated reserves of the pool
/// @param pairReserves The pair reserves of the pool
/// @param releaseAmount The amount of margin released
/// @param repayAmount The amount of debt repaid
/// @param profitAmount The profit from the liquidation
/// @param lostAmount The loss from the liquidation
/// @param fundAmount The amount added to the insurance fund
event LiquidateBurn(
PoolId indexed poolId,
address indexed sender,
uint256 tokenId,
uint256 marginAmount,
uint256 marginTotal,
uint256 debtAmount,
Reserves truncatedReserves,
Reserves pairReserves,
uint256 releaseAmount,
uint256 repayAmount,
uint256 profitAmount,
uint256 lostAmount,
uint256 fundAmount
);
/// @notice Emitted when a margin position is liquidated by calling
/// @param poolId The ID of the pool
/// @param sender The address of the liquidator
/// @param tokenId The ID of the position token
/// @param marginAmount The amount of margin in the position
/// @param marginTotal The total margin of the position
/// @param debtAmount The total debt of the position
/// @param truncatedReserves The truncated reserves of the pool
/// @param pairReserves The pair reserves of the pool
/// @param releaseAmount The amount of margin released
/// @param repayAmount The amount of debt repaid
/// @param needRepayAmount The amount of debt that needs to be repaid
/// @param lostAmount The loss from the liquidation
/// @param fundAmount The amount added to the insurance fund
event LiquidateCall(
PoolId indexed poolId,
address indexed sender,
uint256 tokenId,
uint256 marginAmount,
uint256 marginTotal,
uint256 debtAmount,
Reserves truncatedReserves,
Reserves pairReserves,
uint256 releaseAmount,
uint256 repayAmount,
uint256 needRepayAmount,
uint256 lostAmount,
uint256 fundAmount
);
/// @notice Gets the state of a position
/// @param tokenId The ID of the position token
/// @return position The state of the position
function getPositionState(uint256 tokenId) external view returns (MarginPosition.State memory position);
struct CreateParams {
/// @notice true: currency1 is marginToken, false: currency0 is marginToken
bool marginForOne;
/// @notice Leverage factor of the margin position.
uint24 leverage;
/// @notice The amount of margin
uint256 marginAmount;
/// @notice The borrow amount of the margin position.When the parameter is passed in, it is 0.
uint256 borrowAmount;
/// @notice The maximum borrow amount of the margin position.
uint256 borrowAmountMax;
/// @notice The address of recipient
address recipient;
/// @notice Deadline for the transaction
uint256 deadline;
}
/// @notice Create/Add a position
/// @param key The key of pool
/// @param params The parameters of the margin position
/// @return tokenId The id of position
/// @return borrowAmount The borrow amount
/// @return swapFeeAmount The swap amount in margin
function addMargin(PoolKey memory key, IMarginPositionManager.CreateParams calldata params)
external
payable
returns (uint256 tokenId, uint256 borrowAmount, uint256 swapFeeAmount);
struct MarginParams {
uint256 tokenId;
/// @notice Leverage factor of the margin position.
uint24 leverage;
/// @notice The amount of margin
uint256 marginAmount;
/// @notice The borrow amount of the margin position.When the parameter is passed in, it is 0.
uint256 borrowAmount;
/// @notice The maximum borrow amount of the margin position.
uint256 borrowAmountMax;
/// @notice Deadline for the transaction
uint256 deadline;
}
/// @notice Margin a position
/// @param params The parameters of the margin position
/// @return borrowAmount The borrow amount
/// @return swapFeeAmount The swap amount in margin
function margin(IMarginPositionManager.MarginParams memory params)
external
payable
returns (uint256 borrowAmount, uint256 swapFeeAmount);
/// @notice Release the margin position by repaying the debt
/// @param tokenId The id of position
/// @param repayAmount The amount to repay
/// @param deadline Deadline for the transaction
function repay(uint256 tokenId, uint256 repayAmount, uint256 deadline) external payable;
/// @notice Close the margin position
/// @param tokenId The id of position
/// @param closeMillionth The repayment ratio is calculated as one millionth
/// @param closeAmountMin The minimum close amount (margin) to be received after closing the position
/// @param deadline Deadline for the transaction
function close(uint256 tokenId, uint24 closeMillionth, uint256 closeAmountMin, uint256 deadline) external;
/// @notice Liquidates a position by burning the position token.
/// @param tokenId The ID of the position to liquidate.
/// @param deadline The deadline for the liquidation.
/// @return profit The profit from the liquidation.
function liquidateBurn(uint256 tokenId, uint256 deadline) external returns (uint256 profit);
/// @notice Liquidates a position by making a call.
/// @param tokenId The ID of the position to liquidate.
/// @param deadline The deadline for the liquidation.
/// @return profit The profit from the liquidation.
/// @return repayAmount The amount repaid.
function liquidateCall(uint256 tokenId, uint256 deadline)
external
payable
returns (uint256 profit, uint256 repayAmount);
/// @notice Modify the margin position
/// @param tokenId The id of position
/// @param changeAmount The amount to modify
/// @param deadline Deadline for the transaction
function modify(uint256 tokenId, int128 changeAmount, uint256 deadline) external payable;
/// @notice Gets the margin levels
/// @return marginLevel The margin levels
function marginLevels() external view returns (MarginLevels marginLevel);
}
src/interfaces/IVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {MarginBalanceDelta} from "../types/MarginBalanceDelta.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {InsuranceFunds} from "../types/InsuranceFunds.sol";
import {Reserves} from "../types/Reserves.sol";
import {PoolId} from "../types/PoolId.sol";
import {IMarginBase} from "./IMarginBase.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
/// @notice Interface for the LikwidVault
interface IVault is IERC6909Claims, IMarginBase, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when trying to initialize a pool that is already initialized
error PoolAlreadyInitialized(PoolId id);
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error VaultLocked();
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when trying to amount of 0
error AmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param marginFee The fee collected upon every margin in the pool, denominated in hundredths of a bip
event Initialize(
PoolId indexed id, Currency indexed currency0, Currency indexed currency1, uint24 fee, uint24 marginFee
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param callerDelta The caller delta
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int256 callerDelta, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 balance of the pool
/// @param fee The swap fee in hundredths of a bip
event Swap(PoolId indexed id, address indexed sender, int128 amount0, int128 amount1, uint24 fee);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice Emitted for fees
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param currency The currency of the fee
/// @param sender The address that paid the fee
/// @param feeType The type of fee
/// @param feeAmount The amount of the lp fee
/// @param protocolFeeAmount The amount of the protocol fee
event Fees(
PoolId indexed id,
Currency indexed currency,
address indexed sender,
uint8 feeType,
uint256 feeAmount,
uint256 protocolFeeAmount
);
/// @notice Emitted for lends between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the lend call
/// @param lendingForOne False if lending currency0, true if lending currency1
/// @param lendingAmount The amount lent, negative for deposit, positive for withdraw
/// @param depositCumulativeLast The deposit cumulative at the time of the lend
/// @param salt The extra data to make lends unique
event Lend(
PoolId indexed id,
address indexed sender,
bool lendingForOne,
int128 lendingAmount,
uint256 depositCumulativeLast,
bytes32 salt
);
/// @notice Emitted when margin balance is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param marginType The type of margin operation
/// @param realReserves The real reserves of the pool
/// @param mirrorReserves The mirror reserves of the pool
/// @param pairReserves The pair reserves of the pool
/// @param lendReserves The lend reserves of the pool
/// @param protocolInterestReserves The protocol interest reserves of the pool
/// @param insuranceFunds The insurance funds of the pool
event MarginBalance(
PoolId indexed id,
uint8 marginType,
Reserves realReserves,
Reserves mirrorReserves,
Reserves pairReserves,
Reserves lendReserves,
Reserves protocolInterestReserves,
InsuranceFunds insuranceFunds
);
/// @notice Emitted when interest is updated for a pool
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param realReserves The real reserves of the pool
/// @param mirrorReserves The mirror reserves of the pool
/// @param pairReserves The pair reserves of the pool
/// @param lendReserves The lend reserves of the pool
/// @param protocolInterestReserves The protocol interest reserves of the pool
/// @param insuranceFunds The insurance funds of the pool
event PoolUpdated(
PoolId indexed id,
Reserves realReserves,
Reserves mirrorReserves,
Reserves pairReserves,
Reserves lendReserves,
Reserves protocolInterestReserves,
InsuranceFunds insuranceFunds
);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
function initialize(PoolKey memory key) external;
struct ModifyLiquidityParams {
uint256 amount0;
uint256 amount1;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return finalLiquidityDelta The actual change in liquidity of the pool after the modification
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params)
external
returns (BalanceDelta callerDelta, int128 finalLiquidityDelta);
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// Whether to use the mirror reserves for the swap
bool useMirror;
bytes32 salt;
}
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @return swapDelta The balance delta of the address swapping
/// @return swapFee The cost of swap transactions is measured in parts per million (ppm) of the swapped amount
/// @return feeAmount The amount of lp fee charged for the swap
function swap(PoolKey memory key, SwapParams memory params)
external
returns (BalanceDelta swapDelta, uint24 swapFee, uint256 feeAmount);
/// @notice Donate the given currency amounts to the insurance funds of a pool
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1) external returns (BalanceDelta);
struct LendParams {
/// False if lend token0,true if lend token1
bool lendForOne;
/// The amount to lend, negative for deposit, positive for withdraw
int128 lendAmount;
bytes32 salt;
}
/// @notice Lends tokens to a pool.
/// @dev Allows a user to lend tokens to a pool and earn interest.
/// @param key The key of the pool to lend to.
/// @param params The parameters for the lending operation, including the amount to lend.
/// @return lendDelta The change in the lender's balance.
function lend(PoolKey memory key, LendParams memory params) external returns (BalanceDelta lendDelta);
function marginBalance(PoolKey memory key, MarginBalanceDelta memory params)
external
returns (BalanceDelta marginDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
}
src/interfaces/callback/IUnlockCallback.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
src/interfaces/external/IERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
src/libraries/CurrencyPoolLibrary.sol
// SPDX-License-Identifier: MIT
// Likwid Contracts
pragma solidity ^0.8.20;
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {Currency} from "../types/Currency.sol";
import {IVault} from "../interfaces/IVault.sol";
import {PoolId, PoolIdLibrary} from "../types/PoolId.sol";
library CurrencyPoolLibrary {
using PoolIdLibrary for PoolId;
using SafeERC20 for IERC20;
error InsufficientValue();
/// @notice Settle (pay) a currency to the PoolManager
/// @param currency Currency to settle
/// @param manager IVault to settle to
/// @param payer Address of the payer, the token sender
/// @param amount Amount to send
/// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
function settle(Currency currency, IVault manager, address payer, uint256 amount, bool burn) internal {
// for native currencies or burns, calling sync is not required
// short circuit for ERC-6909 burns to support ERC-6909-wrapped native tokens
if (burn) {
manager.burn(payer, currency.toId(), amount);
} else if (currency.isAddressZero()) {
manager.settle{value: amount}();
} else {
manager.sync(currency);
IERC20 token = IERC20(Currency.unwrap(currency));
if (payer != address(this)) {
token.safeTransferFrom(payer, address(manager), amount);
} else {
token.safeTransfer(address(manager), amount);
}
manager.settle();
}
}
/// @notice Take (receive) a currency from the PoolManager
/// @param currency Currency to take
/// @param manager IVault to take from
/// @param recipient Address of the recipient, the token receiver
/// @param amount Amount to receive
/// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
function take(Currency currency, IVault manager, address recipient, uint256 amount, bool claims) internal {
claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
}
}
src/libraries/CurrentStateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IVault} from "../interfaces/IVault.sol";
import {IMarginBase} from "../interfaces/IMarginBase.sol";
import {Slot0, Slot0Library} from "../types/Slot0.sol";
import {Reserves, ReservesLibrary, toReserves} from "../types/Reserves.sol";
import {PoolState} from "../types/PoolState.sol";
import {TimeLibrary} from "./TimeLibrary.sol";
import {InterestMath} from "./InterestMath.sol";
import {PriceMath} from "./PriceMath.sol";
import {SafeCast} from "./SafeCast.sol";
/// @notice Library for fetching the current state of a pool from the vault
library CurrentStateLibrary {
using SafeCast for *;
using Slot0Library for Slot0;
using ReservesLibrary for Reserves;
using TimeLibrary for uint32;
/// @notice The storage slot of the `defaultProtocolFee` in the LikwidVault contract.
bytes32 public constant DEFAULT_PROTOCOL_FEE_SLOT = bytes32(uint256(6));
/// @notice The storage slot of the `_pools` mapping in the LikwidVault contract.
bytes32 public constant POOLS_SLOT = bytes32(uint256(10));
function getState(IVault vault, PoolId poolId) internal view returns (PoolState memory state) {
bytes32 poolStateSlot = keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
// 1. Get slot0 and defaultProtocolFee
Slot0 slot0 = Slot0.wrap(vault.extsload(poolStateSlot));
state.totalSupply = slot0.totalSupply();
state.lastUpdated = slot0.lastUpdated();
state.protocolFee = slot0.protocolFee();
state.lpFee = slot0.lpFee();
state.marginFee = slot0.marginFee();
if (state.protocolFee == 0) {
uint256 value = uint256(vault.extsload(DEFAULT_PROTOCOL_FEE_SLOT));
state.protocolFee = uint24(value >> 160);
}
// 2. Get all other data in one call
bytes32 startSlot = bytes32(uint256(poolStateSlot) + 1); // BORROW_0_CUMULATIVE_LAST_OFFSET
bytes32[] memory data = vault.extsload(startSlot, 11); // read 13 slots
uint256 borrow0CumulativeBefore = uint256(data[0]);
uint256 borrow1CumulativeBefore = uint256(data[1]);
uint256 deposit0CumulativeBefore = uint256(data[2]);
uint256 deposit1CumulativeBefore = uint256(data[3]);
state.realReserves = Reserves.wrap(uint256(data[4]));
state.mirrorReserves = Reserves.wrap(uint256(data[5]));
state.pairReserves = Reserves.wrap(uint256(data[6]));
Reserves _truncatedReserves = Reserves.wrap(uint256(data[7]));
state.lendReserves = Reserves.wrap(uint256(data[8]));
state.interestReserves = Reserves.wrap(uint256(data[9]));
state.protocolInterestReserves = Reserves.wrap(uint256(data[10]));
// 3. Get marginState
state.marginState = IMarginBase(address(vault)).marginState();
// 4. Get timeElapsed
uint256 timeElapsed = state.lastUpdated.getTimeElapsed();
(uint256 mirrorReserve0, uint256 mirrorReserve1) = state.mirrorReserves.reserves();
(uint256 pairReserve0, uint256 pairReserve1) = state.pairReserves.reserves();
(uint256 lendReserve0, uint256 lendReserve1) = state.lendReserves.reserves();
(uint256 interestReserve0, uint256 interestReserve1) = state.interestReserves.reserves();
(uint256 protocolInterestReserve0, uint256 protocolInterestReserve1) = state.protocolInterestReserves.reserves();
(uint256 borrow0CumulativeLast, uint256 borrow1CumulativeLast) = InterestMath.getBorrowRateCumulativeLast(
timeElapsed,
borrow0CumulativeBefore,
borrow1CumulativeBefore,
state.marginState,
state.realReserves,
state.mirrorReserves
);
InterestMath.InterestUpdateParams memory params0 = InterestMath.InterestUpdateParams({
mirrorReserve: mirrorReserve0,
borrowCumulativeLast: borrow0CumulativeLast,
borrowCumulativeBefore: borrow0CumulativeBefore,
interestReserve: interestReserve0,
pairReserve: pairReserve0,
lendReserve: lendReserve0,
protocolInterestReserve: protocolInterestReserve0,
depositCumulativeLast: deposit0CumulativeBefore,
protocolFee: state.protocolFee
});
InterestMath.InterestUpdateResult memory result0 = InterestMath.updateInterestForOne(params0);
if (result0.changed) {
mirrorReserve0 = result0.newMirrorReserve;
pairReserve0 = result0.newPairReserve;
lendReserve0 = result0.newLendReserve;
}
interestReserve0 = result0.newInterestReserve;
state.deposit0CumulativeLast = result0.newDepositCumulativeLast;
state.borrow0CumulativeLast = borrow0CumulativeLast;
InterestMath.InterestUpdateParams memory params1 = InterestMath.InterestUpdateParams({
mirrorReserve: mirrorReserve1,
borrowCumulativeLast: borrow1CumulativeLast,
borrowCumulativeBefore: borrow1CumulativeBefore,
interestReserve: interestReserve1,
pairReserve: pairReserve1,
lendReserve: lendReserve1,
protocolInterestReserve: protocolInterestReserve1,
depositCumulativeLast: deposit1CumulativeBefore,
protocolFee: state.protocolFee
});
InterestMath.InterestUpdateResult memory result1 = InterestMath.updateInterestForOne(params1);
if (result1.changed) {
mirrorReserve1 = result1.newMirrorReserve;
pairReserve1 = result1.newPairReserve;
lendReserve1 = result1.newLendReserve;
}
interestReserve1 = result1.newInterestReserve;
state.borrow1CumulativeLast = borrow1CumulativeLast;
state.deposit1CumulativeLast = result1.newDepositCumulativeLast;
if (result0.changed || result1.changed) {
state.mirrorReserves = toReserves(mirrorReserve0.toUint128(), mirrorReserve1.toUint128());
state.pairReserves = toReserves(pairReserve0.toUint128(), pairReserve1.toUint128());
state.lendReserves = toReserves(lendReserve0.toUint128(), lendReserve1.toUint128());
}
state.truncatedReserves = PriceMath.transferReserves(
_truncatedReserves, state.pairReserves, timeElapsed, state.marginState.priceMoveSpeedPPM()
);
state.interestReserves = toReserves(interestReserve0.toUint128(), interestReserve1.toUint128());
state.lastUpdated = uint32(block.timestamp);
}
}
src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
src/libraries/FeeLibrary.sol
// SPDX-License-Identifier: MIT
// Likwid Contracts
pragma solidity ^0.8.0;
import {Math} from "./Math.sol";
import {PerLibrary} from "./PerLibrary.sol";
library FeeLibrary {
function deductFrom(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithoutFee) {
uint256 ratio = PerLibrary.ONE_MILLION - fee;
amountWithoutFee = Math.mulDiv(amount, ratio, PerLibrary.ONE_MILLION);
}
function deduct(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithoutFee, uint256 feeAmount) {
amountWithoutFee = deductFrom(fee, amount);
feeAmount = amount - amountWithoutFee;
}
function attachFrom(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithFee) {
uint256 ratio = PerLibrary.ONE_MILLION - fee;
amountWithFee = Math.mulDiv(amount, PerLibrary.ONE_MILLION, ratio);
}
function attach(uint24 fee, uint256 amount) internal pure returns (uint256 amountWithFee, uint256 feeAmount) {
amountWithFee = attachFrom(fee, amount);
feeAmount = amountWithFee - amount;
}
function part(uint24 fee, uint256 amount) internal pure returns (uint256 feeAmount) {
feeAmount = Math.mulDiv(amount, uint256(fee), PerLibrary.ONE_MILLION);
}
function bound(uint24 fee, uint256 amount) internal pure returns (uint256 lower, uint256 upper) {
lower = deductFrom(fee, amount);
upper = attachFrom(fee, amount);
}
}
src/libraries/FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
src/libraries/InterestMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {FeeTypes} from "../types/FeeTypes.sol";
import {Reserves} from "../types/Reserves.sol";
import {MarginState} from "../types/MarginState.sol";
import {Math} from "./Math.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
import {FeeLibrary} from "./FeeLibrary.sol";
import {PerLibrary} from "./PerLibrary.sol";
import {CustomRevert} from "./CustomRevert.sol";
import {ProtocolFeeLibrary} from "./ProtocolFeeLibrary.sol";
library InterestMath {
using CustomRevert for bytes4;
using FeeLibrary for uint24;
using PerLibrary for uint256;
function getBorrowRateByReserves(MarginState marginState, uint256 borrowReserve, uint256 mirrorReserve)
internal
pure
returns (uint256 rate)
{
rate = marginState.rateBase();
if (mirrorReserve == 0) {
return rate;
}
uint256 useLevel = Math.mulDiv(mirrorReserve, PerLibrary.ONE_MILLION, borrowReserve);
if (useLevel >= marginState.useHighLevel()) {
rate += uint256(useLevel - marginState.useHighLevel()) * marginState.mHigh() / 100;
useLevel = marginState.useHighLevel();
}
if (useLevel >= marginState.useMiddleLevel()) {
rate += uint256(useLevel - marginState.useMiddleLevel()) * marginState.mMiddle() / 100;
useLevel = marginState.useMiddleLevel();
}
return rate + useLevel * marginState.mLow() / 100;
}
function getBorrowRateCumulativeLast(
uint256 timeElapsed,
uint256 rate0CumulativeBefore,
uint256 rate1CumulativeBefore,
MarginState marginState,
Reserves realReserves,
Reserves mirrorReserve
) internal pure returns (uint256 rate0CumulativeLast, uint256 rate1CumulativeLast) {
if (timeElapsed == 0) {
return (rate0CumulativeBefore, rate1CumulativeBefore);
}
(uint256 realReserve0, uint256 realReserve1) = realReserves.reserves();
(uint256 mirrorReserve0, uint256 mirrorReserve1) = mirrorReserve.reserves();
uint256 rate0 = getBorrowRateByReserves(marginState, realReserve0 + mirrorReserve0, mirrorReserve0);
uint256 rate0LastYear = PerLibrary.YEAR_TRILLION_SECONDS + rate0 * timeElapsed * PerLibrary.ONE_MILLION;
rate0CumulativeLast = Math.mulDiv(rate0CumulativeBefore, rate0LastYear, PerLibrary.YEAR_TRILLION_SECONDS);
uint256 rate1 = getBorrowRateByReserves(marginState, realReserve1 + mirrorReserve1, mirrorReserve1);
uint256 rate1LastYear = PerLibrary.YEAR_TRILLION_SECONDS + rate1 * timeElapsed * PerLibrary.ONE_MILLION;
rate1CumulativeLast = Math.mulDiv(rate1CumulativeBefore, rate1LastYear, PerLibrary.YEAR_TRILLION_SECONDS);
}
struct InterestUpdateParams {
uint256 mirrorReserve;
uint256 borrowCumulativeLast;
uint256 borrowCumulativeBefore;
uint256 interestReserve;
uint256 pairReserve;
uint256 lendReserve;
uint256 protocolInterestReserve;
uint256 depositCumulativeLast;
uint24 protocolFee;
}
struct InterestUpdateResult {
uint256 newMirrorReserve;
uint256 newPairReserve;
uint256 newLendReserve;
uint256 newInterestReserve;
uint256 newProtocolInterestReserve;
uint256 newDepositCumulativeLast;
uint256 protocolInterest;
uint256 pairInterest;
bool changed;
}
function updateInterestForOne(InterestUpdateParams memory params)
internal
pure
returns (InterestUpdateResult memory result)
{
result.newMirrorReserve = params.mirrorReserve;
result.newPairReserve = params.pairReserve;
result.newLendReserve = params.lendReserve;
result.newInterestReserve = params.interestReserve;
result.newProtocolInterestReserve = params.protocolInterestReserve;
result.newDepositCumulativeLast = params.depositCumulativeLast;
uint256 totalMirrorReserveX96 = (params.mirrorReserve + params.protocolInterestReserve) * FixedPoint96.Q96;
if (totalMirrorReserveX96 > 0 && params.borrowCumulativeLast > params.borrowCumulativeBefore) {
uint256 allInterestX96 = Math.mulDiv(
totalMirrorReserveX96, params.borrowCumulativeLast, params.borrowCumulativeBefore
) - totalMirrorReserveX96 + params.interestReserve;
uint256 poolPartInterestX96 = Math.mulDiv(
allInterestX96, params.mirrorReserve, params.mirrorReserve + params.protocolInterestReserve
);
uint256 protocolPartInterestX96 = allInterestX96 - poolPartInterestX96;
(uint256 protocolInterestX96,) =
ProtocolFeeLibrary.splitFee(params.protocolFee, FeeTypes.INTERESTS, poolPartInterestX96);
if (protocolInterestX96 == 0 || protocolInterestX96 > FixedPoint96.Q96) {
uint256 grossAmount = allInterestX96 / FixedPoint96.Q96;
if (grossAmount == 0) {
result.newInterestReserve = allInterestX96;
return result;
}
uint256 remainder = allInterestX96 - grossAmount * FixedPoint96.Q96;
// Update protocol interest reserve
result.protocolInterest = (protocolInterestX96 + protocolPartInterestX96) / FixedPoint96.Q96;
result.newProtocolInterestReserve += result.protocolInterest;
// Subtract protocol interest from all interest
grossAmount -= result.protocolInterest;
result.pairInterest =
Math.mulDiv(grossAmount, params.pairReserve, params.pairReserve + params.lendReserve);
if (grossAmount > result.pairInterest) {
uint256 lendingInterest = grossAmount - result.pairInterest;
result.newDepositCumulativeLast = Math.mulDiv(
params.depositCumulativeLast, params.lendReserve + lendingInterest, params.lendReserve
);
result.newLendReserve += lendingInterest;
}
result.newMirrorReserve += grossAmount;
result.newPairReserve += result.pairInterest;
result.changed = true;
result.newInterestReserve = remainder;
} else {
result.newInterestReserve = allInterestX96;
}
}
}
}
src/libraries/LendPosition.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.0;
import {Math} from "./Math.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {CustomRevert} from "./CustomRevert.sol";
import {PositionLibrary} from "./PositionLibrary.sol";
import {SafeCast} from "./SafeCast.sol";
/// @title LendPosition
/// @notice Positions represent an owner address' lend tokens
library LendPosition {
using CustomRevert for bytes4;
using PositionLibrary for address;
using SafeCast for *;
using LendPosition for State;
error CannotUpdateEmptyPosition();
error WithdrawOverflow();
struct State {
uint128 lendAmount;
uint256 depositCumulativeLast;
}
function get(mapping(bytes32 => State) storage self, address owner, bool lendForOne, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = owner.calculatePositionKey(lendForOne, salt);
position = self[positionKey];
}
function update(State storage self, bool lendForOne, uint256 depositCumulativeLast, BalanceDelta delta)
internal
returns (uint256)
{
int128 amount;
if (lendForOne) {
amount = delta.amount1();
} else {
amount = delta.amount0();
}
if ((delta == BalanceDeltaLibrary.ZERO_DELTA && self.lendAmount == 0) || amount == 0) {
CannotUpdateEmptyPosition.selector.revertWith();
}
uint256 lendAmount;
if (self.depositCumulativeLast != 0) {
lendAmount = Math.mulDiv(self.lendAmount, depositCumulativeLast, self.depositCumulativeLast);
}
if (amount < 0) {
// deposit
lendAmount += uint128(-amount);
} else {
// withdraw
if (uint128(amount) > lendAmount) {
WithdrawOverflow.selector.revertWith();
}
lendAmount -= uint128(amount);
}
self.lendAmount = lendAmount.toUint128();
self.depositCumulativeLast = depositCumulativeLast;
return self.lendAmount;
}
}
src/libraries/LiquidityMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Math library for liquidity
library LiquidityMath {
/// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
/// @param x The liquidity before change
/// @param y The delta by which liquidity should be changed
/// @return z The liquidity delta
function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
assembly ("memory-safe") {
z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
if shr(128, z) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 4)
}
}
}
function addInvestment(uint256 prev, int128 amount0, int128 amount1) internal pure returns (uint256 current) {
assembly ("memory-safe") {
// Unpack prev into two 128-bit values
let prevAmount0 := shr(128, prev)
let prevAmount1 := and(prev, 0xffffffffffffffffffffffffffffffff)
// Add deltas, checking for int128 overflow
let currentAmount0 := add(signextend(15, prevAmount0), signextend(15, amount0))
if iszero(eq(signextend(15, currentAmount0), currentAmount0)) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 4)
}
let currentAmount1 := add(signextend(15, prevAmount1), signextend(15, amount1))
if iszero(eq(signextend(15, currentAmount1), currentAmount1)) {
// revert SafeCastOverflow()
mstore(0, 0x93dafdf1)
revert(0x1c, 4)
}
// Pack the results back into a uint256
current :=
or(
shl(128, and(currentAmount0, 0xffffffffffffffffffffffffffffffff)),
and(currentAmount1, 0xffffffffffffffffffffffffffffffff)
)
}
}
}
src/libraries/MarginPosition.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.0;
import {Math} from "./Math.sol";
import {Reserves} from "../types/Reserves.sol";
import {CustomRevert} from "./CustomRevert.sol";
import {SwapMath} from "./SwapMath.sol";
import {PerLibrary} from "./PerLibrary.sol";
import {SafeCast} from "./SafeCast.sol";
/// @title MarginPosition
/// @notice Positions represent an owner address' margin positions
library MarginPosition {
using CustomRevert for bytes4;
using SafeCast for *;
error CannotUpdateEmptyPosition();
error InvalidBorrowAmount();
error ChangeMarginAction();
error NoChangeInPosition();
error PositionLiquidated();
error ReservesNotPositive();
struct State {
bool marginForOne;
uint128 marginAmount;
uint128 marginTotal;
uint256 depositCumulativeLast;
uint128 debtAmount;
uint256 borrowCumulativeLast;
}
function marginLevel(
State memory self,
Reserves pairReserves,
uint256 borrowCumulativeLast,
uint256 depositCumulativeLast
) internal pure returns (uint256 level) {
if (self.debtAmount == 0) {
level = type(uint256).max;
} else {
if (!pairReserves.bothPositive()) {
ReservesNotPositive.selector.revertWith();
}
uint256 marginTotal;
uint256 positionValue;
uint256 debtAmount;
uint256 repayAmount;
(uint128 reserve0, uint128 reserve1) = pairReserves.reserves();
(uint256 reserveBorrow, uint256 reserveMargin) =
self.marginForOne ? (reserve0, reserve1) : (reserve1, reserve0);
if (self.depositCumulativeLast != 0 && depositCumulativeLast != 0) {
uint256 marginAmount = Math.mulDiv(self.marginAmount, depositCumulativeLast, self.depositCumulativeLast);
marginTotal = Math.mulDiv(self.marginTotal, depositCumulativeLast, self.depositCumulativeLast);
positionValue = marginAmount + marginTotal;
} else {
marginTotal = self.marginTotal;
positionValue = self.marginAmount + marginTotal;
}
if (self.borrowCumulativeLast != 0 && borrowCumulativeLast != 0) {
debtAmount = Math.mulDivRoundingUp(self.debtAmount, borrowCumulativeLast, self.borrowCumulativeLast);
} else {
debtAmount = self.debtAmount;
}
if (marginTotal > 0) {
repayAmount = Math.mulDiv(reserveBorrow, positionValue, reserveMargin);
} else {
uint256 numerator = positionValue * reserveBorrow;
uint256 denominator = reserveMargin + positionValue;
repayAmount = numerator / denominator;
}
level = Math.mulDiv(repayAmount, PerLibrary.ONE_MILLION, debtAmount);
}
}
function marginLevel(State memory self, Reserves pairReserves) internal pure returns (uint256 level) {
level = marginLevel(self, pairReserves, 0, 0);
}
function update(
State storage self,
uint256 borrowCumulativeLast,
uint256 depositCumulativeLast,
int128 marginChangeAmount,
uint256 marginWithoutFee,
uint256 borrowAmount,
uint256 repayAmount
) internal returns (uint256 releaseAmount, uint256 realRepayAmount) {
uint256 marginAmount;
uint256 marginTotal;
uint256 positionValue;
uint256 debtAmount;
if (self.depositCumulativeLast != 0) {
marginAmount = Math.mulDiv(self.marginAmount, depositCumulativeLast, self.depositCumulativeLast);
marginTotal = Math.mulDiv(self.marginTotal, depositCumulativeLast, self.depositCumulativeLast);
positionValue = marginAmount + marginTotal;
// margin or borrow
if (borrowAmount > 0) {
// A position can only be used for either borrow(leverage==0) or margin(leverage>0), but not both.
if ((marginTotal > 0 && marginWithoutFee == 0) || (marginTotal == 0 && marginWithoutFee > 0)) {
// when margin, marginWithoutFee should >0
// when borrow, marginWithoutFee should ==0
ChangeMarginAction.selector.revertWith();
}
}
}
if (self.borrowCumulativeLast != 0) {
debtAmount = Math.mulDivRoundingUp(self.debtAmount, borrowCumulativeLast, self.borrowCumulativeLast);
}
if (repayAmount > 0) {
if (repayAmount > debtAmount) {
realRepayAmount = debtAmount;
releaseAmount = positionValue;
} else {
releaseAmount = Math.mulDiv(positionValue, repayAmount.toUint128(), debtAmount);
realRepayAmount = repayAmount;
}
debtAmount -= realRepayAmount;
if (marginTotal > 0) {
uint256 marginAmountReleased = Math.mulDiv(releaseAmount, marginAmount, positionValue);
marginAmount = marginAmount - marginAmountReleased;
if (releaseAmount > marginAmountReleased) {
uint256 marginTotalReleased = releaseAmount - marginAmountReleased;
marginTotal = marginTotal - marginTotalReleased;
}
} else {
marginAmount = marginAmount - releaseAmount;
}
} else {
if (marginChangeAmount > 0) {
// modify
marginAmount += uint128(marginChangeAmount);
// margin or borrow
if (borrowAmount > 0) {
marginTotal += marginWithoutFee;
debtAmount += borrowAmount;
}
} else if (marginChangeAmount < 0) {
// repay or modify
marginAmount -= uint128(-marginChangeAmount);
}
}
self.marginAmount = marginAmount.toUint128();
self.marginTotal = marginTotal.toUint128();
self.depositCumulativeLast = depositCumulativeLast;
self.debtAmount = debtAmount.toUint128();
self.borrowCumulativeLast = borrowCumulativeLast;
}
function close(
State storage self,
Reserves pairReserves,
Reserves truncatedReserves,
uint24 lpFee,
uint256 borrowCumulativeLast,
uint256 depositCumulativeLast,
uint256 rewardAmount,
uint24 closeMillionth
)
internal
returns (
uint256 releaseAmount,
uint256 repayAmount,
uint256 closeAmount,
uint256 lostAmount,
uint256 swapFeeAmount
)
{
if (closeMillionth == 0 || closeMillionth > PerLibrary.ONE_MILLION) {
PerLibrary.InvalidMillionth.selector.revertWith();
}
if (self.debtAmount > 0) {
uint256 marginAmount;
uint256 marginTotal;
uint256 positionValue;
uint256 debtAmount;
if (self.depositCumulativeLast != 0) {
marginAmount = Math.mulDiv(self.marginAmount, depositCumulativeLast, self.depositCumulativeLast);
marginTotal = Math.mulDiv(self.marginTotal, depositCumulativeLast, self.depositCumulativeLast);
positionValue = marginAmount + marginTotal;
}
if (self.borrowCumulativeLast != 0) {
debtAmount = Math.mulDivRoundingUp(self.debtAmount, borrowCumulativeLast, self.borrowCumulativeLast);
}
positionValue -= rewardAmount;
releaseAmount = Math.mulDiv(positionValue, closeMillionth, PerLibrary.ONE_MILLION);
repayAmount = Math.mulDivRoundingUp(debtAmount, closeMillionth, PerLibrary.ONE_MILLION);
uint256 payedAmount;
(payedAmount,, swapFeeAmount) =
SwapMath.getAmountOut(pairReserves, truncatedReserves, lpFee, !self.marginForOne, releaseAmount);
if (releaseAmount < positionValue && repayAmount > payedAmount) {
PositionLiquidated.selector.revertWith();
} else {
// releaseAmount == positionValue or repayAmount <= payedAmount
(uint256 costAmount,, uint256 swapFees) =
SwapMath.getAmountIn(pairReserves, truncatedReserves, lpFee, !self.marginForOne, repayAmount);
if (releaseAmount > costAmount) {
closeAmount = releaseAmount - costAmount;
swapFeeAmount = swapFees;
} else if (repayAmount > payedAmount) {
lostAmount = repayAmount - payedAmount;
}
}
if (marginTotal > 0) {
uint256 marginAmountReleased = Math.mulDiv(marginAmount, closeMillionth, PerLibrary.ONE_MILLION);
marginAmount = marginAmount - marginAmountReleased;
if (releaseAmount + rewardAmount > marginAmountReleased) {
uint256 marginTotalReleased = releaseAmount + rewardAmount - marginAmountReleased;
marginTotal = marginTotal - marginTotalReleased;
}
} else {
marginAmount =
Math.mulDiv(marginAmount, PerLibrary.ONE_MILLION - closeMillionth, PerLibrary.ONE_MILLION);
}
debtAmount -= repayAmount;
self.marginAmount = marginAmount.toUint128();
self.marginTotal = marginTotal.toUint128();
self.depositCumulativeLast = depositCumulativeLast;
self.debtAmount = debtAmount.toUint128();
self.borrowCumulativeLast = borrowCumulativeLast;
}
}
}
src/libraries/Math.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Panic} from "@openzeppelin/contracts/utils/Panic.sol";
import {SafeCast} from "./SafeCast.sol";
library Math {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly ("memory-safe") {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly ("memory-safe") {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly ("memory-safe") {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (0 - denominator) & denominator;
// Divide denominator by power of two
assembly ("memory-safe") {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly ("memory-safe") {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly ("memory-safe") {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the preconditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) != 0) {
require(++result > 0);
}
}
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
}
src/libraries/PairPosition.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.0;
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {CustomRevert} from "./CustomRevert.sol";
import {PositionLibrary} from "./PositionLibrary.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
/// @title PairPosition
/// @notice A library for managing liquidity positions in a pair.
/// @dev Positions represent an owner's liquidity contribution.
library PairPosition {
using CustomRevert for bytes4;
using PositionLibrary for address;
error CannotUpdateEmptyPosition();
/// @dev Represents the state of a liquidity position.
struct State {
// The amount of liquidity in the position.
uint128 liquidity;
// The total investment value, used for tracking returns.
uint256 totalInvestment;
}
/// @notice Retrieves a position's state from storage.
/// @param self The mapping of position keys to position states.
/// @param owner The owner of the position.
/// @param salt A unique salt for the position.
/// @return position A storage pointer to the position's state.
function get(mapping(bytes32 => State) storage self, address owner, bytes32 salt)
internal
view
returns (State storage position)
{
bytes32 positionKey = owner.calculatePositionKey(salt);
position = self[positionKey];
}
/// @notice Updates a position's state with new liquidity and investment amounts.
/// @param self A storage pointer to the position's state to update.
/// @param liquidityDelta The change in liquidity.
/// @param delta The change in the balance of tokens.
/// @return The updated total investment value.
function update(State storage self, int128 liquidityDelta, BalanceDelta delta) internal returns (uint256) {
// If there's no change in liquidity and the position is empty, revert.
// This prevents creating empty positions or "poking" them without effect.
if (liquidityDelta == 0 && self.liquidity == 0) {
CannotUpdateEmptyPosition.selector.revertWith();
}
if (liquidityDelta != 0) {
self.liquidity = LiquidityMath.addDelta(self.liquidity, liquidityDelta);
}
// Update the total investment and store it.
self.totalInvestment = LiquidityMath.addInvestment(self.totalInvestment, -delta.amount0(), -delta.amount1());
return self.totalInvestment;
}
}
src/libraries/PerLibrary.sol
// SPDX-License-Identifier: MIT
// Likwid Contracts
pragma solidity ^0.8.0;
import {Math} from "./Math.sol";
library PerLibrary {
error InvalidMillionth();
uint256 public constant ONE_MILLION = 10 ** 6;
uint256 public constant ONE_TRILLION = 10 ** 12;
uint256 public constant YEAR_TRILLION_SECONDS = ONE_TRILLION * 365 * 24 * 3600;
function mulMillion(uint256 x) internal pure returns (uint256 y) {
y = x * ONE_MILLION;
}
function divMillion(uint256 x) internal pure returns (uint256 y) {
y = x / ONE_MILLION;
}
function mulMillionDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = Math.mulDiv(x, ONE_MILLION, y);
}
function mulDivMillion(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = Math.mulDiv(x, y, ONE_MILLION);
}
function upperMillion(uint256 x, uint256 per) internal pure returns (uint256 z) {
z = Math.mulDiv(x, ONE_MILLION + per, ONE_MILLION);
}
function lowerMillion(uint256 x, uint256 per) internal pure returns (uint256 z) {
if (per >= ONE_MILLION) {
return z;
}
z = Math.mulDiv(x, ONE_MILLION - per, ONE_MILLION);
}
function isWithinTolerance(uint256 a, uint256 b, uint256 t) internal pure returns (bool) {
return a >= b ? (a - b) <= t : (b - a) <= t;
}
}
src/libraries/PositionLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.0;
/// @title PositionLibrary
/// @notice A library for creating unique identifiers for positions.
library PositionLibrary {
/// @notice Calculates a unique position key for an owner and a salt.
/// @param owner The owner of the position.
/// @param salt A unique salt for the position.
/// @return positionKey The unique identifier for the position.
function calculatePositionKey(address owner, bytes32 salt) internal pure returns (bytes32 positionKey) {
// This assembly block is a gas-optimized version of:
// positionKey = keccak256(abi.encodePacked(owner, salt));
assembly ("memory-safe") {
// Use the scratch space (0x00-0x3f) to store the arguments to hash.
mstore(0x00, owner)
mstore(0x20, salt)
// Hash the 20 bytes of owner and 32 bytes of salt.
// An address is 20 bytes, but stored in a 32-byte word. It's right-aligned,
// so we skip the first 12(0x0c) zero bytes.
// The total length to hash is 20 (owner) + 32 (salt) = 52 bytes (0x34).
positionKey := keccak256(0x0c, 0x34)
}
}
function calculatePositionKey(address owner, bool isForOne, bytes32 salt)
internal
pure
returns (bytes32 positionKey)
{
assembly ("memory-safe") {
// abi.encodePacked(owner, isForOne, salt) is 53 bytes:
// | owner (20 bytes) | isForOne (1 byte) | salt (32 bytes) |
// We construct the first 32 bytes of the packed data:
// | owner (20 bytes) | isForOne (1 byte) | salt (first 11 bytes) |
// Shift owner left by 12 bytes (96 bits) to align it to the start of the word.
let word1 := shl(96, owner)
// Shift isForOne left by 11 bytes (88 bits) to place it right after the owner.
word1 := or(word1, shl(88, isForOne))
// Take the top 11 bytes (88 bits) of the salt and place them after isForOne.
word1 := or(word1, shr(168, salt))
// We construct the second 32 bytes of the packed data:
// | salt (last 21 bytes) | padding (11 bytes) |
// Shift the salt left by 88 bits to get the last 21 bytes at the start of the word.
let word2 := shl(88, salt)
// Use the scratch space (0x00-0x3f) to store the arguments to hash.
mstore(0x00, word1)
mstore(0x20, word2)
// Hash the 53 bytes of packed data
positionKey := keccak256(0x00, 0x35)
}
}
}
src/libraries/PriceMath.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.26;
import {Math} from "./Math.sol";
import {SafeCast} from "./SafeCast.sol";
import {PerLibrary} from "./PerLibrary.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
import {Reserves, toReserves} from "../types/Reserves.sol";
library PriceMath {
using SafeCast for *;
using PerLibrary for *;
function transferReserves(
Reserves originReserves,
Reserves destReserves,
uint256 timeElapsed,
uint24 priceMoveSpeedPPM
) internal pure returns (Reserves result) {
if (destReserves.bothPositive()) {
if (!originReserves.bothPositive()) {
result = destReserves;
} else {
uint256 priceMoved = priceMoveSpeedPPM * (timeElapsed ** 2);
(uint256 truncatedReserve0, uint256 truncatedReserve1) = originReserves.reserves();
uint256 price0X96 = Math.mulDiv(truncatedReserve1, FixedPoint96.Q96, truncatedReserve0);
uint256 price1X96 = Math.mulDiv(truncatedReserve0, FixedPoint96.Q96, truncatedReserve1);
uint256 maxPrice0X96 = price0X96.upperMillion(priceMoved);
uint256 maxPrice1X96 = price1X96.upperMillion(priceMoved);
uint128 newTruncatedReserve0 = 0;
uint128 newTruncatedReserve1 = destReserves.reserve1();
uint128 minTruncatedReserve0 =
Math.mulDiv(newTruncatedReserve1, FixedPoint96.Q96, maxPrice0X96).toUint128();
uint128 maxTruncatedReserve0 =
Math.mulDiv(newTruncatedReserve1, maxPrice1X96, FixedPoint96.Q96).toUint128();
uint256 _reserve0 = destReserves.reserve0();
if (_reserve0 < minTruncatedReserve0) {
newTruncatedReserve0 = minTruncatedReserve0;
} else if (_reserve0 > maxTruncatedReserve0) {
newTruncatedReserve0 = maxTruncatedReserve0;
} else {
newTruncatedReserve0 = _reserve0.toUint128();
}
result = toReserves(newTruncatedReserve0, newTruncatedReserve1);
}
} else {
result = destReserves;
}
}
}
src/libraries/ProtocolFeeLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {FeeTypes} from "../types/FeeTypes.sol";
import {Math} from "./Math.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @notice A library for handling protocol fees represented as a packed uint24 value.
library ProtocolFeeLibrary {
using CustomRevert for bytes4;
error InvalidProtocolFee(uint8 fee);
// Each fee is a uint8, representing a percentage of the total fee, scaled by FEE_DENOMINATOR.
// For example, a value of 100 means 100/200 = 50% protocol fee.
// The maximum value of 200 represents a 100% protocol fee.
uint8 internal constant MAX_PROTOCOL_FEE = 200;
uint256 internal constant FEE_DENOMINATOR = 200;
uint24 internal constant SWAP_FEE_THRESHOLD = 201;
uint24 internal constant MARGIN_FEE_THRESHOLD = 201 << 8;
uint24 internal constant INTEREST_FEE_THRESHOLD = 201 << 16;
function getProtocolSwapFee(uint24 self) internal pure returns (uint8) {
return uint8(self & 0xff);
}
function getProtocolMarginFee(uint24 self) internal pure returns (uint8) {
return uint8(self >> 8);
}
function getProtocolInterestFee(uint24 self) internal pure returns (uint8) {
return uint8(self >> 16);
}
function isValidProtocolFee(uint24 self) internal pure returns (bool valid) {
// Equivalent to: getProtocolSwapFee(self) <= MAX_PROTOCOL_FEE && getProtocolMarginFee(self) <= MAX_PROTOCOL_FEE && getProtocolInterestFee(self) <= MAX_PROTOCOL_FEE
assembly ("memory-safe") {
let isProtocolSwapFeeOk := lt(and(self, 0xff), SWAP_FEE_THRESHOLD)
let isProtocolMarginFeeOk := lt(and(self, 0xff00), MARGIN_FEE_THRESHOLD)
let isProtocolInterestFeeOk := lt(and(self, 0xff0000), INTEREST_FEE_THRESHOLD)
valid := and(and(isProtocolSwapFeeOk, isProtocolMarginFeeOk), isProtocolInterestFeeOk)
}
}
function getProtocolFee(uint24 self, FeeTypes feeType) internal pure returns (uint8) {
if (feeType == FeeTypes.SWAP) {
return getProtocolSwapFee(self);
} else if (feeType == FeeTypes.MARGIN) {
return getProtocolMarginFee(self);
} else if (feeType == FeeTypes.INTERESTS) {
return getProtocolInterestFee(self);
}
return 0; // Default case, should not happen
}
function setProtocolFee(uint24 self, FeeTypes feeType, uint8 newFee) internal pure returns (uint24) {
if (newFee > MAX_PROTOCOL_FEE) {
InvalidProtocolFee.selector.revertWith(newFee);
}
if (feeType == FeeTypes.SWAP) {
return (self & 0xffff00) | newFee; // Set swap fee
} else if (feeType == FeeTypes.MARGIN) {
return (self & 0xff00ff) | (uint24(newFee) << 8); // Set margin fee
} else if (feeType == FeeTypes.INTERESTS) {
return (self & 0x00ffff) | (uint24(newFee) << 16); // Set interest fee
}
return self; // Default case, should not happen
}
function splitFee(uint24 self, FeeTypes feeType, uint256 feeAmount)
internal
pure
returns (uint256 protocolFee, uint256 remainingFee)
{
uint8 protocolFeePercent = getProtocolFee(self, feeType);
if (protocolFeePercent == 0) {
return (0, feeAmount);
}
protocolFee = Math.mulDiv(feeAmount, protocolFeePercent, FEE_DENOMINATOR);
remainingFee = feeAmount - protocolFee;
}
}
src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
error SafeCastOverflow();
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) revert SafeCastOverflow();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) revert SafeCastOverflow();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) revert SafeCastOverflow();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) revert SafeCastOverflow();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) revert SafeCastOverflow();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) revert SafeCastOverflow();
return int128(int256(x));
}
}
src/libraries/StateLibrary.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolId} from "../types/PoolId.sol";
import {IVault} from "../interfaces/IVault.sol";
import {Slot0, Slot0Library} from "../types/Slot0.sol";
import {Reserves, ReservesLibrary} from "../types/Reserves.sol";
import {InsuranceFunds} from "../types/InsuranceFunds.sol";
import {PairPosition} from "./PairPosition.sol";
import {LendPosition} from "./LendPosition.sol";
import {PositionLibrary} from "./PositionLibrary.sol";
import {SafeCast} from "./SafeCast.sol";
/// @title A helper library to provide state getters for a Likwid pool
/// @notice This library provides functions to read the state of a Likwid pool from storage.
library StateLibrary {
using SafeCast for *;
using Slot0Library for Slot0;
using ReservesLibrary for Reserves;
using PositionLibrary for address;
/// @notice The storage slot of the `lastStageTimestampStore` mapping in the MarginBase contract.
/// @dev This is an assumption. If the storage layout of MarginBase changes, this value needs to be updated.
bytes32 public constant LAST_STAGE_TIMESTAMP_STORE_SLOT = bytes32(uint256(3));
/// @notice The storage slot of the `liquidityLockedQueue` mapping in the MarginBase contract.
/// @dev This is an assumption. If the storage layout of MarginBase changes, this value needs to be updated.
bytes32 public constant LIQUIDITY_LOCKED_QUEUE_SLOT = bytes32(uint256(4));
/// @notice The storage slot of the `defaultProtocolFee` in the LikwidVault contract.
bytes32 public constant DEFAULT_PROTOCOL_FEE_SLOT = bytes32(uint256(6));
/// @notice The storage slot of the `_pools` mapping in the LikwidVault contract.
bytes32 public constant POOLS_SLOT = bytes32(uint256(10));
// Offsets for fields within the Pool.State struct
uint256 internal constant BORROW_0_CUMULATIVE_LAST_OFFSET = 1;
uint256 internal constant BORROW_1_CUMULATIVE_LAST_OFFSET = 2;
uint256 internal constant DEPOSIT_0_CUMULATIVE_LAST_OFFSET = 3;
uint256 internal constant DEPOSIT_1_CUMULATIVE_LAST_OFFSET = 4;
uint256 internal constant REAL_RESERVES_OFFSET = 5;
uint256 internal constant MIRROR_RESERVES_OFFSET = 6;
uint256 internal constant PAIR_RESERVES_OFFSET = 7;
uint256 internal constant TRUNCATED_RESERVES_OFFSET = 8;
uint256 internal constant LEND_RESERVES_OFFSET = 9;
uint256 internal constant INTEREST_RESERVES_OFFSET = 10;
uint256 internal constant PROTOCOL_INTEREST_RESERVES_OFFSET = 11;
uint256 internal constant INSURANCE_FUND_UPPER_LIMIT_OFFSET = 12;
uint256 internal constant INSURANCE_FUNDS_OFFSET = 13;
uint256 internal constant POSITIONS_OFFSET = 14;
uint256 internal constant LEND_POSITIONS_OFFSET = 15;
/**
* @notice Get the unpacked Slot0 of the pool.
* @dev Corresponds to pools[poolId].slot0
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return totalSupply The total supply of liquidity tokens.
* @return lastUpdated The timestamp of the last update.
* @return protocolFee The protocol fee of the pool.
* @return lpFee The swap fee of the pool.
* @return marginFee The margin fee of the pool.
* @return insuranceFundPercentage The insurance fund percentage of the pool.
*/
function getSlot0(IVault vault, PoolId poolId)
internal
view
returns (
uint128 totalSupply,
uint32 lastUpdated,
uint24 protocolFee,
uint24 lpFee,
uint24 marginFee,
uint8 insuranceFundPercentage
)
{
bytes32 stateSlot = _getPoolStateSlot(poolId);
Slot0 slot0 = Slot0.wrap(vault.extsload(stateSlot));
totalSupply = slot0.totalSupply();
lastUpdated = slot0.lastUpdated();
lpFee = slot0.lpFee();
marginFee = slot0.marginFee();
uint256 value = uint256(vault.extsload(DEFAULT_PROTOCOL_FEE_SLOT));
uint24 defaultProtocolFee = uint24(value >> 160);
protocolFee = slot0.protocolFee(defaultProtocolFee);
insuranceFundPercentage = slot0.insuranceFundPercentage();
}
/**
* @notice Retrieves the cumulative borrow and deposit rates of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return borrow0CumulativeLast The cumulative borrow rate for currency 0.
* @return borrow1CumulativeLast The cumulative borrow rate for currency 1.
* @return deposit0CumulativeLast The cumulative deposit rate for currency 0.
* @return deposit1CumulativeLast The cumulative deposit rate for currency 1.
*/
function getBorrowDepositCumulative(IVault vault, PoolId poolId)
internal
view
returns (
uint256 borrow0CumulativeLast,
uint256 borrow1CumulativeLast,
uint256 deposit0CumulativeLast,
uint256 deposit1CumulativeLast
)
{
bytes32 stateSlot = _getPoolStateSlot(poolId);
bytes32 startSlot = bytes32(uint256(stateSlot) + BORROW_0_CUMULATIVE_LAST_OFFSET);
bytes32[] memory data = vault.extsload(startSlot, 4);
assembly ("memory-safe") {
borrow0CumulativeLast := mload(add(data, 0x20))
borrow1CumulativeLast := mload(add(data, 0x40))
deposit0CumulativeLast := mload(add(data, 0x60))
deposit1CumulativeLast := mload(add(data, 0x80))
}
}
/**
* @notice Retrieves the pair reserves of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed pair reserves of the pool.
*/
function getPairReserves(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + PAIR_RESERVES_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the real reserves of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed real reserves of the pool.
*/
function getRealReserves(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + REAL_RESERVES_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the mirror reserves of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed mirror reserves of the pool.
*/
function getMirrorReserves(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + MIRROR_RESERVES_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the truncated reserves of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed truncated reserves of the pool.
*/
function getTruncatedReserves(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + TRUNCATED_RESERVES_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the lending reserves of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed lending reserves of the pool.
*/
function getLendReserves(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + LEND_RESERVES_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the interest reserves of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed interest reserves of the pool.
*/
function getInterestReserves(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + INTEREST_RESERVES_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the protocol interest reserves of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed protocol interest reserves of the pool.
*/
function getProtocolInterestReserves(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + PROTOCOL_INTEREST_RESERVES_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the insurance fund upper limit of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed insurance fund upper limit of the pool.
*/
function getInsuranceFundUpperLimit(IVault vault, PoolId poolId) internal view returns (Reserves) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + INSURANCE_FUND_UPPER_LIMIT_OFFSET);
return Reserves.wrap(uint256(vault.extsload(slot)));
}
/**
* @notice Retrieves the insurance funds of a pool.
* @param vault The vault contract.
* @param poolId The ID of the pool.
* @return The packed insurance funds of the pool.
*/
function getInsuranceFunds(IVault vault, PoolId poolId) internal view returns (InsuranceFunds) {
bytes32 slot = bytes32(uint256(_getPoolStateSlot(poolId)) + INSURANCE_FUNDS_OFFSET);
return InsuranceFunds.wrap(int256(uint256(vault.extsload(slot))));
}
function getLastStageTimestamp(IVault vault, PoolId poolId) internal view returns (uint256) {
bytes32 slot = keccak256(abi.encodePacked(PoolId.unwrap(poolId), LAST_STAGE_TIMESTAMP_STORE_SLOT));
return uint256(vault.extsload(slot));
}
function getPairPositionState(IVault vault, PoolId poolId, address owner, bytes32 salt)
internal
view
returns (PairPosition.State memory _position)
{
bytes32 positionKey = owner.calculatePositionKey(salt);
bytes32 poolStateSlot = _getPoolStateSlot(poolId);
bytes32 positionsMappingSlot = bytes32(uint256(poolStateSlot) + POSITIONS_OFFSET);
bytes32 positionSlot = keccak256(abi.encodePacked(positionKey, positionsMappingSlot));
bytes32[] memory data = vault.extsload(positionSlot, 2);
_position.liquidity = uint128(uint256(data[0]));
_position.totalInvestment = uint256(data[1]);
}
function getLendPositionState(IVault vault, PoolId poolId, address owner, bool lendForOne, bytes32 salt)
internal
view
returns (LendPosition.State memory _position)
{
bytes32 positionKey = owner.calculatePositionKey(lendForOne, salt);
bytes32 poolStateSlot = _getPoolStateSlot(poolId);
bytes32 positionsMappingSlot = bytes32(uint256(poolStateSlot) + LEND_POSITIONS_OFFSET);
bytes32 positionSlot = keccak256(abi.encodePacked(positionKey, positionsMappingSlot));
bytes32[] memory data = vault.extsload(positionSlot, 2);
uint256 slot0 = uint256(data[0]);
_position.lendAmount = uint128(slot0);
_position.depositCumulativeLast = uint256(data[1]);
}
function getRawStageLiquidities(IVault vault, PoolId poolId) internal view returns (uint256[] memory liquidities) {
bytes32 dequeSlot = keccak256(abi.encodePacked(PoolId.unwrap(poolId), LIQUIDITY_LOCKED_QUEUE_SLOT));
bytes32 dequeValue = vault.extsload(dequeSlot);
uint128 front;
uint128 back;
assembly ("memory-safe") {
front := and(dequeValue, 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff)
back := shr(128, dequeValue)
}
uint256 len = back - front;
liquidities = new uint256[](len);
bytes32 valuesSlot = bytes32(uint256(dequeSlot) + 1);
for (uint256 i = 0; i < len; i++) {
uint256 valueIndex = front + i;
bytes32 valueSlot = keccak256(abi.encodePacked(valueIndex, valuesSlot));
liquidities[i] = uint256(vault.extsload(valueSlot));
}
}
/**
* @notice Calculates the storage slot for a specific pool's state.
* @param poolId The ID of the pool.
* @return The storage slot of the Pool.State struct.
*/
function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
}
}
src/libraries/SwapMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Reserves} from "../types/Reserves.sol";
import {Math} from "./Math.sol";
import {FeeLibrary} from "./FeeLibrary.sol";
import {PerLibrary} from "./PerLibrary.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
import {CustomRevert} from "./CustomRevert.sol";
library SwapMath {
using CustomRevert for bytes4;
using FeeLibrary for uint24;
using PerLibrary for uint256;
/// @notice The maximum swap fee in hundredths of a bip (1e6 = 100%).
uint256 internal constant MAX_SWAP_FEE = 1e6;
error InsufficientLiquidity();
error InsufficientInputAmount();
/**
* @notice Calculates the absolute difference between two prices.
* @param price The current price.
* @param lastPrice The previous price.
* @return priceDiff The absolute difference.
*/
function differencePrice(uint256 price, uint256 lastPrice) internal pure returns (uint256 priceDiff) {
priceDiff = price > lastPrice ? price - lastPrice : lastPrice - price;
}
/**
* @notice Calculates the degree of price change caused by a swap, used for dynamic fee calculation.
* @dev This function calculates price impact based on reserves and swap amounts.
* @param pairReserves The current reserves of the pair.
* @param truncatedReserves The reserves at the last fee calculation checkpoint.
* @param lpFee The base liquidity provider fee.
* @param zeroForOne The direction of the swap.
* @param amountIn The amount of tokens being swapped in.
* @param amountOut The amount of tokens being swapped out.
* @return degree The calculated degree of price change.
*/
function getPriceDegree(
Reserves pairReserves,
Reserves truncatedReserves,
uint24 lpFee,
bool zeroForOne,
uint256 amountIn,
uint256 amountOut
) internal pure returns (uint256 degree) {
if (truncatedReserves.bothPositive()) {
uint256 lastPrice0X96 = truncatedReserves.getPrice0X96();
uint256 lastPrice1X96 = truncatedReserves.getPrice1X96();
(uint256 _reserve0, uint256 _reserve1) = pairReserves.reserves();
if (_reserve0 == 0 || _reserve1 == 0) {
return degree;
}
if (amountIn > 0) {
(amountOut,) = getAmountOut(pairReserves, lpFee, zeroForOne, amountIn);
} else if (amountOut > 0) {
(amountIn,) = getAmountIn(pairReserves, lpFee, zeroForOne, amountOut);
}
unchecked {
if (zeroForOne) {
_reserve1 -= amountOut;
_reserve0 += amountIn;
} else {
_reserve0 -= amountOut;
_reserve1 += amountIn;
}
}
uint256 price0X96 = Math.mulDiv(_reserve1, FixedPoint96.Q96, _reserve0);
uint256 price1X96 = Math.mulDiv(_reserve0, FixedPoint96.Q96, _reserve1);
uint256 degree0 = differencePrice(price0X96, lastPrice0X96).mulMillionDiv(lastPrice0X96);
uint256 degree1 = differencePrice(price1X96, lastPrice1X96).mulMillionDiv(lastPrice1X96);
degree = Math.max(degree0, degree1);
}
}
/**
* @notice Calculates a dynamic fee based on the degree of price change.
* @dev The fee increases with the price impact (degree).
* @param swapFee The base swap fee.
* @param degree The degree of price change.
* @return _fee The calculated dynamic fee.
*/
function dynamicFee(uint24 swapFee, uint256 degree) internal pure returns (uint24 _fee) {
_fee = swapFee;
if (degree > MAX_SWAP_FEE) {
_fee = uint24(MAX_SWAP_FEE) - 10000;
} else if (degree > 100000) {
uint256 dFee = Math.mulDiv((degree * 10) ** 3, _fee, MAX_SWAP_FEE ** 3);
if (dFee >= MAX_SWAP_FEE) {
_fee = uint24(MAX_SWAP_FEE) - 10000;
} else {
_fee = uint24(dFee);
}
}
}
/**
* @notice Calculates the output amount and fee for a given input amount and fixed fee.
* @param pairReserves The reserves of the token pair.
* @param lpFee The liquidity provider fee.
* @param zeroForOne The direction of the swap.
* @param amountIn The amount of input tokens.
* @return amountOut The calculated amount of output tokens.
* @return feeAmount The amount of fees paid.
*/
function getAmountOut(Reserves pairReserves, uint24 lpFee, bool zeroForOne, uint256 amountIn)
internal
pure
returns (uint256 amountOut, uint256 feeAmount)
{
if (amountIn == 0) InsufficientInputAmount.selector.revertWith();
(uint128 _reserve0, uint128 _reserve1) = pairReserves.reserves();
(uint256 reserveIn, uint256 reserveOut) = zeroForOne ? (_reserve0, _reserve1) : (_reserve1, _reserve0);
if (reserveIn == 0 || reserveOut == 0) InsufficientLiquidity.selector.revertWith();
uint256 amountInWithoutFee;
(amountInWithoutFee, feeAmount) = lpFee.deduct(amountIn);
uint256 numerator = amountInWithoutFee * reserveOut;
uint256 denominator = reserveIn + amountInWithoutFee;
amountOut = numerator / denominator;
}
/**
* @notice Calculates the output amount using a dynamic fee based on price impact.
* @param pairReserves The current reserves of the pair.
* @param truncatedReserves The reserves at the last fee calculation checkpoint.
* @param lpFee The base liquidity provider fee.
* @param zeroForOne The direction of the swap.
* @param amountIn The amount of input tokens.
* @return amountOut The calculated amount of output tokens.
* @return fee The dynamic fee applied.
* @return feeAmount The amount of fees paid.
*/
function getAmountOut(
Reserves pairReserves,
Reserves truncatedReserves,
uint24 lpFee,
bool zeroForOne,
uint256 amountIn
) internal pure returns (uint256 amountOut, uint24 fee, uint256 feeAmount) {
uint256 degree = getPriceDegree(pairReserves, truncatedReserves, lpFee, zeroForOne, amountIn, 0);
fee = dynamicFee(lpFee, degree);
(amountOut, feeAmount) = getAmountOut(pairReserves, fee, zeroForOne, amountIn);
}
/**
* @notice Calculates the required input amount and fee for a given output amount and fixed fee.
* @param pairReserves The reserves of the token pair.
* @param lpFee The liquidity provider fee.
* @param zeroForOne The direction of the swap.
* @param amountOut The desired amount of output tokens.
* @return amountIn The required amount of input tokens.
* @return feeAmount The amount of fees paid from the input tokens.
*/
function getAmountIn(Reserves pairReserves, uint24 lpFee, bool zeroForOne, uint256 amountOut)
internal
pure
returns (uint256 amountIn, uint256 feeAmount)
{
(uint128 _reserve0, uint128 _reserve1) = pairReserves.reserves();
(uint256 reserveIn, uint256 reserveOut) = zeroForOne ? (_reserve0, _reserve1) : (_reserve1, _reserve0);
if (reserveIn == 0 || reserveOut == 0) InsufficientLiquidity.selector.revertWith();
if (amountOut >= reserveOut) InsufficientLiquidity.selector.revertWith();
uint256 amountInWithoutFee = Math.mulDiv(reserveIn, amountOut, reserveOut - amountOut) + 1;
uint256 numerator = amountInWithoutFee * MAX_SWAP_FEE;
uint256 denominator = MAX_SWAP_FEE - lpFee;
amountIn = (numerator + denominator - 1) / denominator;
feeAmount = amountIn - amountInWithoutFee;
}
/**
* @notice Calculates the required input amount using a dynamic fee based on price impact.
* @param pairReserves The current reserves of the pair.
* @param truncatedReserves The reserves at the last fee calculation checkpoint.
* @param lpFee The base liquidity provider fee.
* @param zeroForOne The direction of the swap.
* @param amountOut The desired amount of output tokens.
* @return amountIn The required amount of input tokens.
* @return fee The dynamic fee applied.
* @return feeAmount The amount of fees paid.
*/
function getAmountIn(
Reserves pairReserves,
Reserves truncatedReserves,
uint24 lpFee,
bool zeroForOne,
uint256 amountOut
) internal pure returns (uint256 amountIn, uint24 fee, uint256 feeAmount) {
uint256 degree = getPriceDegree(pairReserves, truncatedReserves, lpFee, zeroForOne, 0, amountOut);
fee = dynamicFee(lpFee, degree);
(amountIn, feeAmount) = getAmountIn(pairReserves, fee, zeroForOne, amountOut);
}
}
src/libraries/TimeLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.0;
library TimeLibrary {
function getTimeElapsed(uint32 blockTimestampLast) internal view returns (uint256 timeElapsed) {
uint32 blockTimestamp = uint32(block.timestamp);
if (blockTimestampLast <= blockTimestamp) {
timeElapsed = uint256(blockTimestamp - blockTimestampLast);
} else {
timeElapsed = uint256(2 ** 32 - blockTimestampLast + blockTimestamp);
}
}
}
src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
if (!success) {
revert NativeTransferFailed();
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
if (!success) {
revert ERC20TransferFailed();
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
src/types/FeeTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
enum FeeTypes {
SWAP,
MARGIN,
INTERESTS,
MARGIN_SWAP,
MARGIN_CLOSE_SWAP
}
src/types/InsuranceFunds.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
import {
BalanceDelta,
toBalanceDelta as toBalanceDeltaInternal,
add as addInternal,
sub as subInternal,
eq as eqInternal,
neq as neqInternal,
BalanceDeltaLibrary
} from "./BalanceDelta.sol";
/// @dev Two `int128` values packed into a single `int256`. Serves as a semantic alias for BalanceDelta for insurance funds.
type InsuranceFunds is int256;
using {add as +, sub as -, eq as ==, neq as !=} for InsuranceFunds global;
using InsuranceFundsLibrary for InsuranceFunds global;
using SafeCast for int256;
function toInsuranceFunds(int128 _amount0, int128 _amount1) pure returns (InsuranceFunds) {
return InsuranceFunds.wrap(BalanceDelta.unwrap(toBalanceDeltaInternal(_amount0, _amount1)));
}
function add(InsuranceFunds a, InsuranceFunds b) pure returns (InsuranceFunds) {
BalanceDelta bdA = BalanceDelta.wrap(InsuranceFunds.unwrap(a));
BalanceDelta bdB = BalanceDelta.wrap(InsuranceFunds.unwrap(b));
return InsuranceFunds.wrap(BalanceDelta.unwrap(addInternal(bdA, bdB)));
}
function sub(InsuranceFunds a, InsuranceFunds b) pure returns (InsuranceFunds) {
BalanceDelta bdA = BalanceDelta.wrap(InsuranceFunds.unwrap(a));
BalanceDelta bdB = BalanceDelta.wrap(InsuranceFunds.unwrap(b));
return InsuranceFunds.wrap(BalanceDelta.unwrap(subInternal(bdA, bdB)));
}
function eq(InsuranceFunds a, InsuranceFunds b) pure returns (bool) {
return eqInternal(BalanceDelta.wrap(InsuranceFunds.unwrap(a)), BalanceDelta.wrap(InsuranceFunds.unwrap(b)));
}
function neq(InsuranceFunds a, InsuranceFunds b) pure returns (bool) {
return neqInternal(BalanceDelta.wrap(InsuranceFunds.unwrap(a)), BalanceDelta.wrap(InsuranceFunds.unwrap(b)));
}
library InsuranceFundsLibrary {
InsuranceFunds public constant ZERO_DELTA = InsuranceFunds.wrap(0);
function amount0(InsuranceFunds f) internal pure returns (int128) {
return BalanceDeltaLibrary.amount0(BalanceDelta.wrap(InsuranceFunds.unwrap(f)));
}
function amount1(InsuranceFunds f) internal pure returns (int128) {
return BalanceDeltaLibrary.amount1(BalanceDelta.wrap(InsuranceFunds.unwrap(f)));
}
function unpack(InsuranceFunds f) internal pure returns (int128, int128) {
return (f.amount0(), f.amount1());
}
}
src/types/MarginActions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
enum MarginActions {
MARGIN,
REPAY,
CLOSE,
MODIFY,
LIQUIDATE_BURN,
LIQUIDATE_CALL
}
src/types/MarginBalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {MarginActions} from "./MarginActions.sol";
import {BalanceDelta} from "./BalanceDelta.sol";
struct MarginBalanceDelta {
MarginActions action;
bool marginForOne;
uint128 marginTotal;
uint256 marginFeeAmount;
uint256 swapFeeAmount;
BalanceDelta marginDelta;
BalanceDelta mirrorDelta;
BalanceDelta pairDelta;
BalanceDelta lendDelta;
BalanceDelta fundsDelta;
}
src/types/MarginLevels.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
type MarginLevels is bytes32;
using MarginLevelsLibrary for MarginLevels global;
/// @notice Library for getting and setting values in the MarginLevels type
library MarginLevelsLibrary {
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint8 internal constant MIN_BORROW_LEVEL_OFFSET = 24;
uint8 internal constant LIQUIDATE_LEVEL_OFFSET = 48;
uint8 internal constant LIQUIDATION_RATIO_OFFSET = 72;
uint8 internal constant CALLER_PROFIT_OFFSET = 96;
function isValidMarginLevels(MarginLevels _packed) internal pure returns (bool valid) {
uint24 _liquidateLevel = liquidateLevel(_packed);
uint24 one = 10 ** 6;
valid = _liquidateLevel >= one && minMarginLevel(_packed) > _liquidateLevel
&& minBorrowLevel(_packed) > _liquidateLevel && liquidationRatio(_packed) <= one
&& callerProfit(_packed) <= one;
}
// #### GETTERS ####
function minMarginLevel(MarginLevels _packed) internal pure returns (uint24 _minMarginLevel) {
assembly ("memory-safe") {
_minMarginLevel := and(MASK_24_BITS, _packed)
}
}
function minBorrowLevel(MarginLevels _packed) internal pure returns (uint24 _minBorrowLevel) {
assembly ("memory-safe") {
_minBorrowLevel := and(MASK_24_BITS, shr(MIN_BORROW_LEVEL_OFFSET, _packed))
}
}
function liquidateLevel(MarginLevels _packed) internal pure returns (uint24 _liquidateLevel) {
assembly ("memory-safe") {
_liquidateLevel := and(MASK_24_BITS, shr(LIQUIDATE_LEVEL_OFFSET, _packed))
}
}
function liquidationRatio(MarginLevels _packed) internal pure returns (uint24 _liquidationRatio) {
assembly ("memory-safe") {
_liquidationRatio := and(MASK_24_BITS, shr(LIQUIDATION_RATIO_OFFSET, _packed))
}
}
function callerProfit(MarginLevels _packed) internal pure returns (uint24 _callerProfit) {
assembly ("memory-safe") {
_callerProfit := and(MASK_24_BITS, shr(CALLER_PROFIT_OFFSET, _packed))
}
}
// #### SETTERS ####
function setMinMarginLevel(MarginLevels _packed, uint24 _minMarginLevel)
internal
pure
returns (MarginLevels _result)
{
assembly ("memory-safe") {
_result := or(and(not(MASK_24_BITS), _packed), and(MASK_24_BITS, _minMarginLevel))
}
}
function setMinBorrowLevel(MarginLevels _packed, uint24 _minBorrowLevel)
internal
pure
returns (MarginLevels _result)
{
assembly ("memory-safe") {
_result := or(
and(not(shl(MIN_BORROW_LEVEL_OFFSET, MASK_24_BITS)), _packed),
shl(MIN_BORROW_LEVEL_OFFSET, and(MASK_24_BITS, _minBorrowLevel))
)
}
}
function setLiquidateLevel(MarginLevels _packed, uint24 _liquidateLevel)
internal
pure
returns (MarginLevels _result)
{
assembly ("memory-safe") {
_result := or(
and(not(shl(LIQUIDATE_LEVEL_OFFSET, MASK_24_BITS)), _packed),
shl(LIQUIDATE_LEVEL_OFFSET, and(MASK_24_BITS, _liquidateLevel))
)
}
}
function setLiquidationRatio(MarginLevels _packed, uint24 _liquidationRatio)
internal
pure
returns (MarginLevels _result)
{
assembly ("memory-safe") {
_result := or(
and(not(shl(LIQUIDATION_RATIO_OFFSET, MASK_24_BITS)), _packed),
shl(LIQUIDATION_RATIO_OFFSET, and(MASK_24_BITS, _liquidationRatio))
)
}
}
function setCallerProfit(MarginLevels _packed, uint24 _callerProfit) internal pure returns (MarginLevels _result) {
assembly ("memory-safe") {
_result := or(
and(not(shl(CALLER_PROFIT_OFFSET, MASK_24_BITS)), _packed),
shl(CALLER_PROFIT_OFFSET, and(MASK_24_BITS, _callerProfit))
)
}
}
}
src/types/MarginState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
type MarginState is bytes32;
using MarginStateLibrary for MarginState global;
/// @notice Library for getting and setting values in the MarginState type
library MarginStateLibrary {
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint8 internal constant USE_MIDDLE_LEVEL_OFFSET = 24;
uint8 internal constant USE_HIGH_LEVEL_OFFSET = 48;
uint8 internal constant M_LOW_OFFSET = 72;
uint8 internal constant M_MIDDLE_OFFSET = 96;
uint8 internal constant M_HIGH_OFFSET = 120;
uint8 internal constant PRICE_MOVE_SPEED_PPM_OFFSET = 144;
uint8 internal constant STAGE_DURATION = 168;
uint8 internal constant STAGE_SIZE = 192;
uint8 internal constant STAGE_LEAVE_PART = 216;
// #### GETTERS ####
function rateBase(MarginState _packed) internal pure returns (uint24 _rateBase) {
assembly ("memory-safe") {
_rateBase := and(MASK_24_BITS, _packed)
}
}
function useMiddleLevel(MarginState _packed) internal pure returns (uint24 _useMiddleLevel) {
assembly ("memory-safe") {
_useMiddleLevel := and(MASK_24_BITS, shr(USE_MIDDLE_LEVEL_OFFSET, _packed))
}
}
function useHighLevel(MarginState _packed) internal pure returns (uint24 _useHighLevel) {
assembly ("memory-safe") {
_useHighLevel := and(MASK_24_BITS, shr(USE_HIGH_LEVEL_OFFSET, _packed))
}
}
function mLow(MarginState _packed) internal pure returns (uint24 _mLow) {
assembly ("memory-safe") {
_mLow := and(MASK_24_BITS, shr(M_LOW_OFFSET, _packed))
}
}
function mMiddle(MarginState _packed) internal pure returns (uint24 _mMiddle) {
assembly ("memory-safe") {
_mMiddle := and(MASK_24_BITS, shr(M_MIDDLE_OFFSET, _packed))
}
}
function mHigh(MarginState _packed) internal pure returns (uint24 _mHigh) {
assembly ("memory-safe") {
_mHigh := and(MASK_24_BITS, shr(M_HIGH_OFFSET, _packed))
}
}
function priceMoveSpeedPPM(MarginState _packed) internal pure returns (uint24 _priceMoveSpeedPPM) {
assembly ("memory-safe") {
_priceMoveSpeedPPM := and(MASK_24_BITS, shr(PRICE_MOVE_SPEED_PPM_OFFSET, _packed))
}
}
function stageDuration(MarginState _packed) internal pure returns (uint24 _stageDuration) {
assembly ("memory-safe") {
_stageDuration := and(MASK_24_BITS, shr(STAGE_DURATION, _packed))
}
}
function stageSize(MarginState _packed) internal pure returns (uint24 _stageSize) {
assembly ("memory-safe") {
_stageSize := and(MASK_24_BITS, shr(STAGE_SIZE, _packed))
}
}
function stageLeavePart(MarginState _packed) internal pure returns (uint24 _stageLeavePart) {
assembly ("memory-safe") {
_stageLeavePart := and(MASK_24_BITS, shr(STAGE_LEAVE_PART, _packed))
}
}
// #### SETTERS ####
function setRateBase(MarginState _packed, uint24 _rateBase) internal pure returns (MarginState _result) {
assembly ("memory-safe") {
_result := or(and(not(MASK_24_BITS), _packed), and(MASK_24_BITS, _rateBase))
}
}
function setUseMiddleLevel(MarginState _packed, uint24 _useMiddleLevel)
internal
pure
returns (MarginState _result)
{
assembly ("memory-safe") {
_result := or(
and(not(shl(USE_MIDDLE_LEVEL_OFFSET, MASK_24_BITS)), _packed),
shl(USE_MIDDLE_LEVEL_OFFSET, and(MASK_24_BITS, _useMiddleLevel))
)
}
}
function setUseHighLevel(MarginState _packed, uint24 _useHighLevel) internal pure returns (MarginState _result) {
assembly ("memory-safe") {
_result := or(
and(not(shl(USE_HIGH_LEVEL_OFFSET, MASK_24_BITS)), _packed),
shl(USE_HIGH_LEVEL_OFFSET, and(MASK_24_BITS, _useHighLevel))
)
}
}
function setMLow(MarginState _packed, uint24 _mLow) internal pure returns (MarginState _result) {
assembly ("memory-safe") {
_result := or(
and(not(shl(M_LOW_OFFSET, MASK_24_BITS)), _packed),
shl(M_LOW_OFFSET, and(MASK_24_BITS, _mLow))
)
}
}
function setMMiddle(MarginState _packed, uint24 _mMiddle) internal pure returns (MarginState _result) {
assembly ("memory-safe") {
_result := or(
and(not(shl(M_MIDDLE_OFFSET, MASK_24_BITS)), _packed),
shl(M_MIDDLE_OFFSET, and(MASK_24_BITS, _mMiddle))
)
}
}
function setMHigh(MarginState _packed, uint24 _mHigh) internal pure returns (MarginState _result) {
assembly ("memory-safe") {
_result := or(
and(not(shl(M_HIGH_OFFSET, MASK_24_BITS)), _packed),
shl(M_HIGH_OFFSET, and(MASK_24_BITS, _mHigh))
)
}
}
function setPriceMoveSpeedPPM(MarginState _packed, uint24 _priceMoveSpeedPPM)
internal
pure
returns (MarginState _result)
{
assembly ("memory-safe") {
_result := or(
and(not(shl(PRICE_MOVE_SPEED_PPM_OFFSET, MASK_24_BITS)), _packed),
shl(PRICE_MOVE_SPEED_PPM_OFFSET, and(MASK_24_BITS, _priceMoveSpeedPPM))
)
}
}
function setStageDuration(MarginState _packed, uint24 _stageDuration) internal pure returns (MarginState _result) {
assembly ("memory-safe") {
_result := or(
and(not(shl(STAGE_DURATION, MASK_24_BITS)), _packed),
shl(STAGE_DURATION, and(MASK_24_BITS, _stageDuration))
)
}
}
function setStageSize(MarginState _packed, uint24 _stageSize) internal pure returns (MarginState _result) {
assembly ("memory-safe") {
_result := or(
and(not(shl(STAGE_SIZE, MASK_24_BITS)), _packed),
shl(STAGE_SIZE, and(MASK_24_BITS, _stageSize))
)
}
}
function setStageLeavePart(MarginState _packed, uint24 _stageLeavePart)
internal
pure
returns (MarginState _result)
{
assembly ("memory-safe") {
_result := or(
and(not(shl(STAGE_LEAVE_PART, MASK_24_BITS)), _packed),
shl(STAGE_LEAVE_PART, and(MASK_24_BITS, _stageLeavePart))
)
}
}
}
src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0x80 represents the total size of the poolKey struct (4 slots of 32 bytes)
poolId := keccak256(poolKey, 0x80)
}
}
}
src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. E.g., 0.3% = 3_000
uint24 fee;
/// @notice The pool LP margin fee, capped at 1_000_000. E.g., 0.3% = 3_000
uint24 marginFee;
}
src/types/PoolState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {MarginState} from "./MarginState.sol";
import {Reserves} from "./Reserves.sol";
struct PoolState {
MarginState marginState;
uint128 totalSupply;
uint32 lastUpdated;
uint24 lpFee;
uint24 marginFee;
uint24 protocolFee;
uint256 borrow0CumulativeLast;
uint256 borrow1CumulativeLast;
uint256 deposit0CumulativeLast;
uint256 deposit1CumulativeLast;
Reserves realReserves;
Reserves mirrorReserves;
Reserves pairReserves;
Reserves truncatedReserves;
Reserves lendReserves;
Reserves interestReserves;
Reserves protocolInterestReserves;
}
src/types/Reserves.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Math} from "../libraries/Math.sol";
import {FixedPoint96} from "../libraries/FixedPoint96.sol";
import {SafeCast} from "../libraries/SafeCast.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "./BalanceDelta.sol";
import {InsuranceFunds} from "./InsuranceFunds.sol";
/// @dev Two `uint128` values packed into a single `uint256` where the upper 128 bits represent reserve0
/// and the lower 128 bits represent reserve1.
type Reserves is uint256;
using {add as +, eq as ==, neq as !=} for Reserves global;
using SafeCast for uint256;
using ReservesLibrary for Reserves global;
/// @notice Creates a Reserves object from two uint128 values.
/// @param _reserve0 The value for the upper 128 bits.
/// @param _reserve1 The value for the lower 128 bits.
/// @return A Reserves object.
function toReserves(uint128 _reserve0, uint128 _reserve1) pure returns (Reserves) {
return Reserves.wrap((uint256(_reserve0) << 128) | _reserve1);
}
function eq(Reserves a, Reserves b) pure returns (bool) {
return Reserves.unwrap(a) == Reserves.unwrap(b);
}
function neq(Reserves a, Reserves b) pure returns (bool) {
return Reserves.unwrap(a) != Reserves.unwrap(b);
}
function add(Reserves a, Reserves b) pure returns (Reserves) {
uint256 res0;
uint256 res1;
assembly ("memory-safe") {
let mask := 0xffffffffffffffffffffffffffffffff
let a0 := shr(128, a)
let a1 := and(a, mask)
let b0 := shr(128, b)
let b1 := and(b, mask)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toReserves(res0.toUint128(), res1.toUint128());
}
enum ReservesType {
REAL,
MIRROR,
PAIR,
LEND
}
/// @notice A library for handling the Reserves type, which packs two uint128 values into a single uint256.
library ReservesLibrary {
Reserves public constant ZERO_RESERVES = Reserves.wrap(0);
struct UpdateParam {
ReservesType _type;
BalanceDelta delta;
}
error NotEnoughReserves();
error InvalidReserves();
/// @notice Retrieves the reserve0 value from a Reserves object.
/// @param self The Reserves object.
/// @return The reserve0 value (upper 128 bits).
function reserve0(Reserves self) internal pure returns (uint128) {
return uint128(Reserves.unwrap(self) >> 128);
}
/// @notice Retrieves the reserve1 value from a Reserves object.
/// @param self The Reserves object.
/// @return The reserve1 value (lower 128 bits).
function reserve1(Reserves self) internal pure returns (uint128) {
return uint128(Reserves.unwrap(self));
}
/// @notice Retrieves one of the reserves based on a boolean flag.
/// @param self The Reserves object.
/// @param forOne If true, returns reserve1; otherwise, returns reserve0.
/// @return The selected reserve value.
function reserve01(Reserves self, bool forOne) internal pure returns (uint128) {
return forOne ? self.reserve1() : self.reserve0();
}
/// @notice Retrieves both reserve values from a Reserves object.
/// @param self The Reserves object.
/// @return _reserve0 The reserve0 value.
/// @return _reserve1 The reserve1 value.
function reserves(Reserves self) internal pure returns (uint128 _reserve0, uint128 _reserve1) {
_reserve0 = self.reserve0();
_reserve1 = self.reserve1();
}
/// @notice Updates the reserve0 value in a Reserves object.
/// @param self The Reserves object to update.
/// @param newReserve0 The new value for reserve0.
/// @return The updated Reserves object.
function updateReserve0(Reserves self, uint128 newReserve0) internal pure returns (Reserves) {
return toReserves(newReserve0, self.reserve1());
}
/// @notice Updates the reserve1 value in a Reserves object.
/// @param self The Reserves object to update.
/// @param newReserve1 The new value for reserve1.
/// @return The updated Reserves object.
function updateReserve1(Reserves self, uint128 newReserve1) internal pure returns (Reserves) {
return toReserves(self.reserve0(), newReserve1);
}
/// @notice Applies a balance delta to the reserves.
/// @param self The Reserves object.
/// @param delta The balance delta to apply.
/// @return The updated Reserves object.
function applyDelta(Reserves self, BalanceDelta delta) internal pure returns (Reserves) {
(uint256 r0, uint256 r1) = self.reserves();
int128 d0 = delta.amount0();
int128 d1 = delta.amount1();
unchecked {
if (d0 > 0) {
uint128 amount0 = uint128(d0);
if (r0 < amount0) {
revert NotEnoughReserves();
}
r0 -= amount0;
} else if (d0 < 0) {
r0 += uint128(-d0);
}
if (d1 > 0) {
uint128 amount1 = uint128(d1);
if (r1 < amount1) {
revert NotEnoughReserves();
}
r1 -= amount1;
} else if (d1 < 0) {
r1 += uint128(-d1);
}
}
return toReserves(r0.toUint128(), r1.toUint128());
}
function applyFunds(Reserves self, InsuranceFunds funds) internal pure returns (Reserves) {
BalanceDelta delta = BalanceDeltaLibrary.ZERO_DELTA - BalanceDelta.wrap(InsuranceFunds.unwrap(funds));
return self.applyDelta(delta);
}
/// @notice Calculates the price of token0 in terms of token1, scaled by Q96.
/// @param self The Reserves object.
/// @return The price of token0, scaled by Q96.
function getPrice0X96(Reserves self) internal pure returns (uint256) {
(uint128 r0, uint128 r1) = self.reserves();
if (r0 == 0 || r1 == 0) revert InvalidReserves();
return Math.mulDiv(r1, FixedPoint96.Q96, r0);
}
/// @notice Calculates the price of token1 in terms of token0, scaled by Q96.
/// @param self The Reserves object.
/// @return The price of token1, scaled by Q96.
function getPrice1X96(Reserves self) internal pure returns (uint256) {
(uint128 r0, uint128 r1) = self.reserves();
if (r0 == 0 || r1 == 0) revert InvalidReserves();
return Math.mulDiv(r0, FixedPoint96.Q96, r1);
}
/// @notice Checks if both reserves are positive.
/// @param self The Reserves object.
/// @return True if both reserves are positive, false otherwise.
function bothPositive(Reserves self) internal pure returns (bool) {
(uint128 r0, uint128 r1) = self.reserves();
return r0 > 0 && r1 > 0;
}
}
src/types/Slot0.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
type Slot0 is bytes32;
using Slot0Library for Slot0 global;
/// @notice Library for getting and setting values in the Slot0 type
library Slot0Library {
uint128 internal constant MASK_128_BITS = 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint32 internal constant MASK_32_BITS = 0xFFFFFFFF;
uint24 internal constant MASK_24_BITS = 0xFFFFFF;
uint8 internal constant MASK_8_BITS = 0xFF;
uint8 internal constant LAST_UPDATED_OFFSET = 128;
uint8 internal constant PROTOCOL_FEE_OFFSET = 160;
uint8 internal constant LP_FEE_OFFSET = 184;
uint8 internal constant MARGIN_FEE_OFFSET = 208;
uint8 internal constant INSURANCE_FUND_PERCENTAGE_OFFSET = 232;
// #### GETTERS ####
function totalSupply(Slot0 _packed) internal pure returns (uint128 _totalSupply) {
assembly ("memory-safe") {
_totalSupply := and(MASK_128_BITS, _packed)
}
}
function lastUpdated(Slot0 _packed) internal pure returns (uint32 _timestampLast) {
assembly ("memory-safe") {
_timestampLast := and(MASK_32_BITS, shr(LAST_UPDATED_OFFSET, _packed))
}
}
function protocolFee(Slot0 _packed) internal pure returns (uint24 _protocolFee) {
assembly ("memory-safe") {
_protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed))
}
}
function protocolFee(Slot0 _packed, uint24 defaultFee) internal pure returns (uint24 _protocolFee) {
_protocolFee = protocolFee(_packed);
_protocolFee = _protocolFee == 0 ? defaultFee : _protocolFee;
}
function lpFee(Slot0 _packed) internal pure returns (uint24 _lpFee) {
assembly ("memory-safe") {
_lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed))
}
}
function marginFee(Slot0 _packed) internal pure returns (uint24 _marginFee) {
assembly ("memory-safe") {
_marginFee := and(MASK_24_BITS, shr(MARGIN_FEE_OFFSET, _packed))
}
}
function insuranceFundPercentage(Slot0 _packed) internal pure returns (uint8 _insuranceFundPercentage) {
assembly ("memory-safe") {
_insuranceFundPercentage := and(MASK_8_BITS, shr(INSURANCE_FUND_PERCENTAGE_OFFSET, _packed))
}
}
// #### SETTERS ####
function setTotalSupply(Slot0 _packed, uint128 _totalSupply) internal pure returns (Slot0 _result) {
assembly ("memory-safe") {
_result := or(and(not(MASK_128_BITS), _packed), and(MASK_128_BITS, _totalSupply))
}
}
function setLastUpdated(Slot0 _packed, uint32 _lastUpdated) internal pure returns (Slot0 _result) {
assembly ("memory-safe") {
_result :=
or(
and(not(shl(LAST_UPDATED_OFFSET, MASK_32_BITS)), _packed),
shl(LAST_UPDATED_OFFSET, and(MASK_32_BITS, _lastUpdated))
)
}
}
function setProtocolFee(Slot0 _packed, uint24 _protocolFee) internal pure returns (Slot0 _result) {
assembly ("memory-safe") {
_result :=
or(
and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed),
shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee))
)
}
}
function setLpFee(Slot0 _packed, uint24 _lpFee) internal pure returns (Slot0 _result) {
assembly ("memory-safe") {
_result :=
or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee)))
}
}
function setMarginFee(Slot0 _packed, uint24 _marginFee) internal pure returns (Slot0 _result) {
assembly ("memory-safe") {
_result :=
or(
and(not(shl(MARGIN_FEE_OFFSET, MASK_24_BITS)), _packed),
shl(MARGIN_FEE_OFFSET, and(MASK_24_BITS, _marginFee))
)
}
}
function setInsuranceFundPercentage(Slot0 _packed, uint8 _insuranceFundPercentage)
internal
pure
returns (Slot0 _result)
{
assembly ("memory-safe") {
_result :=
or(
and(not(shl(INSURANCE_FUND_PERCENTAGE_OFFSET, MASK_8_BITS)), _packed),
shl(INSURANCE_FUND_PERCENTAGE_OFFSET, and(MASK_8_BITS, _insuranceFundPercentage))
)
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"solmate/=lib/solmate/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.