Verified contractExactBUSL-1.1
LikwidVault
Address0x065d449ec9d139740343990b7e1cf05fa830e4ba
- Balance
0.0003 ETH
- Transactions
7
- 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
- 0x49bc6af0da…29ab5a747f
49 files
- src/LikwidVault.solmain15.56 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/solmate/src/auth/Owned.sol1.47 KB
- src/base/ERC6909.sol3.5 KB
- src/base/ERC6909Claims.sol958 B
- src/base/Extsload.sol2.61 KB
- src/base/Exttload.sol1.6 KB
- src/base/MarginBase.sol9.81 KB
- src/base/NoDelegateCall.sol1.14 KB
- src/base/ProtocolFees.sol3.55 KB
- src/interfaces/IExtsload.sol1.02 KB
- src/interfaces/IExttload.sol699 B
- src/interfaces/IMarginBase.sol1.31 KB
- src/interfaces/IProtocolFees.sol3.39 KB
- src/interfaces/IVault.sol14.01 KB
- src/interfaces/callback/IUnlockCallback.sol488 B
- src/interfaces/external/IERC6909Claims.sol3.16 KB
- src/libraries/CurrencyGuard.sol1.49 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/Math.sol12.99 KB
- src/libraries/PairPosition.sol2.49 KB
- src/libraries/PerLibrary.sol1.37 KB
- src/libraries/Pool.sol32.38 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/StageMath.sol1.42 KB
- src/libraries/SwapMath.sol8.83 KB
- src/libraries/TimeLibrary.sol503 B
- src/libraries/external/DoubleEndedQueue.sol6.26 KB
- 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/MarginState.sol6.51 KB
- src/types/PoolId.sol539 B
- src/types/PoolKey.sol628 B
- src/types/Reserves.sol6.7 KB
- src/types/Slot0.sol4.43 KB
src/LikwidVault.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity 0.8.28;
import {Currency, CurrencyLibrary} from "./types/Currency.sol";
import {PoolKey} from "./types/PoolKey.sol";
import {MarginBalanceDelta} from "./types/MarginBalanceDelta.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "./types/BalanceDelta.sol";
import {PoolId} from "./types/PoolId.sol";
import {FeeTypes} from "./types/FeeTypes.sol";
import {MarginActions} from "./types/MarginActions.sol";
import {IVault} from "./interfaces/IVault.sol";
import {IUnlockCallback} from "./interfaces/callback/IUnlockCallback.sol";
import {SafeCast} from "./libraries/SafeCast.sol";
import {CurrencyGuard} from "./libraries/CurrencyGuard.sol";
import {Pool} from "./libraries/Pool.sol";
import {ERC6909Claims} from "./base/ERC6909Claims.sol";
import {NoDelegateCall} from "./base/NoDelegateCall.sol";
import {ProtocolFees} from "./base/ProtocolFees.sol";
import {Extsload} from "./base/Extsload.sol";
import {Exttload} from "./base/Exttload.sol";
import {CustomRevert} from "./libraries/CustomRevert.sol";
/// @title Likwid vault
/// @notice Holds the property for all likwid pools
contract LikwidVault is IVault, ProtocolFees, NoDelegateCall, ERC6909Claims, Extsload, Exttload {
using CustomRevert for bytes4;
using SafeCast for *;
using CurrencyGuard for Currency;
using BalanceDeltaLibrary for BalanceDelta;
using Pool for Pool.State;
mapping(PoolId id => Pool.State) private _pools;
/// transient storage
bool transient unlocked;
uint256 transient nonzeroDeltaCount;
/// @notice This will revert if the contract is locked
modifier onlyWhenUnlocked() {
_onlyWhenUnlocked();
_;
}
function _onlyWhenUnlocked() internal view {
if (!unlocked) VaultLocked.selector.revertWith();
}
constructor(address initialOwner) ProtocolFees(initialOwner) {
protocolFeeController = initialOwner;
}
/// @inheritdoc IVault
function unlock(bytes calldata data) external override returns (bytes memory result) {
if (unlocked) revert AlreadyUnlocked();
unlocked = true;
// the caller does everything in this callback, including paying what they owe via calls to settle
result = IUnlockCallback(msg.sender).unlockCallback(data);
if (nonzeroDeltaCount != 0) revert CurrencyNotSettled();
unlocked = false;
}
/// @inheritdoc IVault
function initialize(PoolKey memory key) external noDelegateCall {
if (key.currency0 >= key.currency1) {
CurrenciesOutOfOrderOrEqual.selector
.revertWith(Currency.unwrap(key.currency0), Currency.unwrap(key.currency1));
}
PoolId id = key.toId();
_pools[id].initialize(key.fee, key.marginFee);
emit Initialize(id, key.currency0, key.currency1, key.fee, key.marginFee);
}
/// @inheritdoc IVault
function modifyLiquidity(PoolKey memory key, IVault.ModifyLiquidityParams memory params)
external
onlyWhenUnlocked
noDelegateCall
returns (BalanceDelta callerDelta, int128 finalLiquidityDelta)
{
Pool.State storage pool = _getAndUpdatePool(key);
PoolId id = key.toId();
uint256 liquidityBefore = pool.slot0.totalSupply();
(callerDelta, finalLiquidityDelta) = pool.modifyLiquidity(
Pool.ModifyLiquidityParams({
owner: msg.sender,
amount0: params.amount0,
amount1: params.amount1,
liquidityDelta: params.liquidityDelta.toInt128(),
salt: params.salt
})
);
uint256 liquidityAfter = pool.slot0.totalSupply();
if (liquidityAfter > liquidityBefore) {
_handleAddLiquidity(id, liquidityAfter - liquidityBefore);
} else if (liquidityAfter < liquidityBefore) {
_handleRemoveLiquidity(id, liquidityBefore - liquidityAfter);
}
int256 liquidityDelta = liquidityAfter.toInt256() - liquidityBefore.toInt256();
emit ModifyLiquidity(id, msg.sender, BalanceDelta.unwrap(callerDelta), liquidityDelta, params.salt);
_appendPoolBalanceDelta(key, msg.sender, callerDelta);
}
/// @inheritdoc IVault
function swap(PoolKey memory key, IVault.SwapParams memory params)
external
onlyWhenUnlocked
noDelegateCall
returns (BalanceDelta swapDelta, uint24 swapFee, uint256 feeAmount)
{
if (params.amountSpecified == 0) AmountCannotBeZero.selector.revertWith();
PoolId id = key.toId();
Pool.State storage pool = _getAndUpdatePool(key);
uint256 amountToProtocol;
(swapDelta, amountToProtocol, swapFee, feeAmount) = pool.swap(
Pool.SwapParams({
sender: msg.sender,
zeroForOne: params.zeroForOne,
amountSpecified: params.amountSpecified,
useMirror: params.useMirror,
salt: params.salt
}),
defaultProtocolFee
);
if (params.useMirror) {
BalanceDelta realDelta;
int128 lendAmount;
if (params.zeroForOne) {
realDelta = toBalanceDelta(swapDelta.amount0(), 0);
lendAmount = -swapDelta.amount1();
} else {
realDelta = toBalanceDelta(0, swapDelta.amount1());
lendAmount = -swapDelta.amount0();
}
_appendPoolBalanceDelta(key, msg.sender, realDelta);
uint256 depositCumulativeLast =
params.zeroForOne ? pool.deposit1CumulativeLast : pool.deposit0CumulativeLast;
emit Lend(id, msg.sender, params.zeroForOne, lendAmount, depositCumulativeLast, params.salt);
} else {
_appendPoolBalanceDelta(key, msg.sender, swapDelta);
}
Currency feeCurrency = params.zeroForOne ? key.currency0 : key.currency1;
if (feeAmount > 0 || amountToProtocol > 0) {
emit Fees(id, feeCurrency, msg.sender, uint8(FeeTypes.SWAP), feeAmount, amountToProtocol);
}
if (amountToProtocol > 0) {
_updateProtocolFees(feeCurrency, amountToProtocol);
}
emit Swap(id, msg.sender, swapDelta.amount0(), swapDelta.amount1(), swapFee);
}
function donate(PoolKey memory key, uint256 amount0, uint256 amount1)
external
onlyWhenUnlocked
noDelegateCall
returns (BalanceDelta delta)
{
PoolId poolId = key.toId();
Pool.State storage pool = _getAndUpdatePool(key);
pool.checkPoolInitialized();
delta = pool.donate(amount0, amount1);
_appendPoolBalanceDelta(key, msg.sender, delta);
emit Donate(poolId, msg.sender, amount0, amount1);
}
/// @inheritdoc IVault
function lend(PoolKey memory key, IVault.LendParams memory params)
external
onlyWhenUnlocked
noDelegateCall
returns (BalanceDelta lendDelta)
{
if (params.lendAmount == 0) AmountCannotBeZero.selector.revertWith();
PoolId id = key.toId();
Pool.State storage pool = _getAndUpdatePool(key);
uint256 depositCumulativeLast;
(lendDelta, depositCumulativeLast) = pool.lend(
Pool.LendParams({
sender: msg.sender, lendForOne: params.lendForOne, lendAmount: params.lendAmount, salt: params.salt
})
);
_appendPoolBalanceDelta(key, msg.sender, lendDelta);
emit Lend(id, msg.sender, params.lendForOne, params.lendAmount, depositCumulativeLast, params.salt);
}
/// @inheritdoc IVault
function marginBalance(PoolKey memory key, MarginBalanceDelta memory params)
external
onlyWhenUnlocked
onlyManager
noDelegateCall
returns (BalanceDelta marginDelta)
{
PoolId id = key.toId();
Pool.State storage pool = _getAndUpdatePool(key);
uint256 marginFeesToProtocol;
uint256 swapFeesToProtocol;
uint256 protocolInterest0;
uint256 protocolInterest1;
(marginDelta, marginFeesToProtocol, swapFeesToProtocol, protocolInterest0, protocolInterest1) =
pool.margin(params, defaultProtocolFee);
bool isMargin = params.action == MarginActions.MARGIN;
(Currency marginCurrency, Currency borrowCurrency) =
params.marginForOne ? (key.currency1, key.currency0) : (key.currency0, key.currency1);
Currency swapCurrency = isMargin ? borrowCurrency : marginCurrency;
if (params.marginFeeAmount > 0 || marginFeesToProtocol > 0) {
if (marginFeesToProtocol > 0) {
_updateProtocolFees(marginCurrency, marginFeesToProtocol);
}
emit Fees(
id, marginCurrency, msg.sender, uint8(FeeTypes.MARGIN), params.marginFeeAmount, marginFeesToProtocol
);
}
if (params.swapFeeAmount > 0 || swapFeesToProtocol > 0) {
uint8 feeType = isMargin ? uint8(FeeTypes.MARGIN_SWAP) : uint8(FeeTypes.MARGIN_CLOSE_SWAP);
if (swapFeesToProtocol > 0) {
_updateProtocolFees(swapCurrency, swapFeesToProtocol);
}
emit Fees(id, swapCurrency, msg.sender, feeType, params.swapFeeAmount, swapFeesToProtocol);
}
if (protocolInterest0 > 0) {
_updateProtocolFees(key.currency0, protocolInterest0);
}
if (protocolInterest1 > 0) {
_updateProtocolFees(key.currency1, protocolInterest1);
}
_appendPoolBalanceDelta(key, msg.sender, marginDelta);
emit MarginBalance(
id,
uint8(params.action),
pool.realReserves,
pool.mirrorReserves,
pool.pairReserves,
pool.lendReserves,
pool.protocolInterestReserves,
pool.insuranceFunds
);
}
/// @inheritdoc IVault
function sync(Currency currency) external {
// address(0) is used for the native currency
if (currency.isAddressZero()) {
syncedCurrency = CurrencyLibrary.ADDRESS_ZERO;
} else {
uint256 balance = currency.balanceOfSelf();
syncedCurrency = currency;
syncedReserves = balance;
}
}
/// @inheritdoc IVault
function take(Currency currency, address to, uint256 amount) external onlyWhenUnlocked {
unchecked {
// negation must be safe as amount is not negative
_appendDelta(currency, msg.sender, -amount.toInt256());
currency.transfer(to, amount);
}
}
/// @inheritdoc IVault
function settle() external payable onlyWhenUnlocked returns (uint256) {
return _settle(msg.sender);
}
/// @inheritdoc IVault
function settleFor(address recipient) external payable onlyWhenUnlocked returns (uint256) {
return _settle(recipient);
}
/// @inheritdoc IVault
function clear(Currency currency, uint256 amount) external onlyWhenUnlocked {
int256 current = currency.currentDelta(msg.sender);
int256 amountDelta = amount.toInt256();
if (amountDelta != current) revert MustClearExactPositiveDelta();
// negation must be safe as amountDelta is positive
unchecked {
_appendDelta(currency, msg.sender, -(amountDelta));
}
}
/// @inheritdoc IVault
function mint(address to, uint256 id, uint256 amount) external onlyWhenUnlocked {
unchecked {
Currency currency = CurrencyLibrary.fromId(id);
// negation must be safe as amount is not negative
_appendDelta(currency, msg.sender, -amount.toInt256());
_mint(to, currency.toId(), amount);
}
}
/// @inheritdoc IVault
function burn(address from, uint256 id, uint256 amount) external onlyWhenUnlocked {
Currency currency = CurrencyLibrary.fromId(id);
_appendDelta(currency, msg.sender, amount.toInt256());
_burnFrom(from, currency.toId(), amount);
}
/// @notice Settles a user's balance for a specific currency.
/// @dev Internal function to _handle the logic of settling a user's balance.
/// @param recipient The address of the user to settle the balance for.
/// @return paid The amount paid to the user.
function _settle(address recipient) internal returns (uint256 paid) {
Currency currency = syncedCurrency;
if (currency.isAddressZero()) {
paid = msg.value;
} else {
if (msg.value > 0) revert NonzeroNativeValue();
uint256 reservesBefore = syncedReserves;
uint256 reservesNow = currency.balanceOfSelf();
paid = reservesNow - reservesBefore;
syncedCurrency = CurrencyLibrary.ADDRESS_ZERO; // reset synced currency
}
_appendDelta(currency, recipient, paid.toInt256());
}
/// @notice Appends a balance delta in a currency for a target address
/// @param currency The currency to update the balance for.
/// @param target The address whose balance is to be updated.
/// @param delta The change in balance.
function _appendDelta(Currency currency, address target, int256 delta) internal {
if (delta == 0) return;
(int256 previous, int256 current) = currency.appendDelta(target, delta.toInt128());
if (current == 0) {
nonzeroDeltaCount -= 1;
} else if (previous == 0) {
nonzeroDeltaCount += 1;
}
}
/// @notice Appends the deltas of 2 currencies to a target address
/// @param key The key of the pool.
/// @param target The address whose balance is to be updated.
/// @param delta The change in balance for both currencies.
function _appendPoolBalanceDelta(PoolKey memory key, address target, BalanceDelta delta) internal {
_appendDelta(key.currency0, target, delta.amount0());
_appendDelta(key.currency1, target, delta.amount1());
}
/// @notice Implementation of the _getAndUpdatePool function defined in ProtocolFees
/// @param key The key of the pool to retrieve.
/// @return _pool The state of the pool.
function _getAndUpdatePool(PoolKey memory key) internal override returns (Pool.State storage _pool) {
PoolId id = key.toId();
_pool = _pools[id];
_pool.checkPoolInitialized();
(uint256 pairInterest0, uint256 pairInterest1, uint256 protocolInterest0, uint256 protocolInterest1) =
_pool.updateInterests(marginState, defaultProtocolFee);
if (pairInterest0 > 0 || protocolInterest0 > 0) {
emit Fees(id, key.currency0, address(this), uint8(FeeTypes.INTERESTS), pairInterest0, protocolInterest0);
}
if (pairInterest1 > 0 || protocolInterest1 > 0) {
emit Fees(id, key.currency1, address(this), uint8(FeeTypes.INTERESTS), pairInterest1, protocolInterest1);
}
emit PoolUpdated(
id,
_pool.realReserves,
_pool.mirrorReserves,
_pool.pairReserves,
_pool.lendReserves,
_pool.protocolInterestReserves,
_pool.insuranceFunds
);
}
/// @notice Implementation of the _isUnlocked function defined in ProtocolFees
/// @return A boolean indicating whether the contract is unlocked.
function _isUnlocked() internal view override returns (bool) {
return unlocked;
}
}
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/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/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/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/ERC6909.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC6909Claims} from "../interfaces/external/IERC6909Claims.sol";
/// @notice Minimalist and gas efficient standard ERC6909 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC6909.sol)
/// @dev Copied from the commit at 4b47a19038b798b4a33d9749d25e570443520647
/// @dev This contract has been modified from the implementation at the above link.
abstract contract ERC6909 is IERC6909Claims {
/*//////////////////////////////////////////////////////////////
ERC6909 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address owner => mapping(address operator => bool isOperator)) public isOperator;
mapping(address owner => mapping(uint256 id => uint256 balance)) public balanceOf;
mapping(address owner => mapping(address spender => mapping(uint256 id => uint256 amount))) public allowance;
/*//////////////////////////////////////////////////////////////
ERC6909 LOGIC
//////////////////////////////////////////////////////////////*/
function transfer(address receiver, uint256 id, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender][id] -= amount;
balanceOf[receiver][id] += amount;
emit Transfer(msg.sender, msg.sender, receiver, id, amount);
return true;
}
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) public virtual returns (bool) {
if (msg.sender != sender && !isOperator[sender][msg.sender]) {
uint256 allowed = allowance[sender][msg.sender][id];
if (allowed != type(uint256).max) allowance[sender][msg.sender][id] = allowed - amount;
}
balanceOf[sender][id] -= amount;
balanceOf[receiver][id] += amount;
emit Transfer(msg.sender, sender, receiver, id, amount);
return true;
}
function approve(address spender, uint256 id, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender][id] = amount;
emit Approval(msg.sender, spender, id, amount);
return true;
}
function setOperator(address operator, bool approved) public virtual returns (bool) {
isOperator[msg.sender][operator] = approved;
emit OperatorSet(msg.sender, operator, approved);
return true;
}
/*//////////////////////////////////////////////////////////////
ERC165 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == 0x01ffc9a7 // ERC165 Interface ID for ERC165
|| interfaceId == 0x0f632fb3; // ERC165 Interface ID for ERC6909
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address receiver, uint256 id, uint256 amount) internal virtual {
balanceOf[receiver][id] += amount;
emit Transfer(msg.sender, address(0), receiver, id, amount);
}
function _burn(address sender, uint256 id, uint256 amount) internal virtual {
balanceOf[sender][id] -= amount;
emit Transfer(msg.sender, sender, address(0), id, amount);
}
}
src/base/ERC6909Claims.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ERC6909} from "./ERC6909.sol";
/// @notice ERC6909Claims inherits ERC6909 and implements an internal burnFrom function
abstract contract ERC6909Claims is ERC6909 {
/// @notice Burn `amount` tokens of token type `id` from `from`.
/// @dev if sender is not `from` they must be an operator or have sufficient allowance.
/// @param from The address to burn tokens from.
/// @param id The currency to burn.
/// @param amount The amount to burn.
function _burnFrom(address from, uint256 id, uint256 amount) internal {
address sender = msg.sender;
if (from != sender && !isOperator[from][sender]) {
uint256 senderAllowance = allowance[from][sender][id];
if (senderAllowance != type(uint256).max) {
allowance[from][sender][id] = senderAllowance - amount;
}
}
_burn(from, id, amount);
}
}
src/base/Extsload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IExtsload} from "../interfaces/IExtsload.sol";
/// @notice Enables public storage access for efficient state retrieval by external contracts.
/// https://eips.ethereum.org/EIPS/eip-2330#rationale
abstract contract Extsload is IExtsload {
/// @inheritdoc IExtsload
function extsload(bytes32 slot) external view returns (bytes32) {
assembly ("memory-safe") {
mstore(0, sload(slot))
return(0, 0x20)
}
}
/// @inheritdoc IExtsload
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory) {
assembly ("memory-safe") {
let memptr := mload(0x40)
let start := memptr
// A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas.
let length := shl(5, nSlots)
// The abi offset of dynamic array in the returndata is 32.
mstore(memptr, 0x20)
// Store the length of the array returned
mstore(add(memptr, 0x20), nSlots)
// update memptr to the first location to hold a result
memptr := add(memptr, 0x40)
let end := add(memptr, length)
for {} 1 {} {
mstore(memptr, sload(startSlot))
memptr := add(memptr, 0x20)
startSlot := add(startSlot, 1)
if iszero(lt(memptr, end)) { break }
}
return(start, sub(end, start))
}
}
/// @inheritdoc IExtsload
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory) {
assembly ("memory-safe") {
let memptr := mload(0x40)
let start := memptr
// for abi encoding the response - the array will be found at 0x20
mstore(memptr, 0x20)
// next we store the length of the return array
mstore(add(memptr, 0x20), slots.length)
// update memptr to the first location to hold an array entry
memptr := add(memptr, 0x40)
// A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas.
let end := add(memptr, shl(5, slots.length))
let calldataptr := slots.offset
for {} 1 {} {
mstore(memptr, sload(calldataload(calldataptr)))
memptr := add(memptr, 0x20)
calldataptr := add(calldataptr, 0x20)
if iszero(lt(memptr, end)) { break }
}
return(start, sub(end, start))
}
}
}
src/base/Exttload.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IExttload} from "../interfaces/IExttload.sol";
/// @notice Enables public transient storage access for efficient state retrieval by external contracts.
/// https://eips.ethereum.org/EIPS/eip-2330#rationale
abstract contract Exttload is IExttload {
/// @inheritdoc IExttload
function exttload(bytes32 slot) external view returns (bytes32) {
assembly ("memory-safe") {
mstore(0, tload(slot))
return(0, 0x20)
}
}
/// @inheritdoc IExttload
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory) {
assembly ("memory-safe") {
let memptr := mload(0x40)
let start := memptr
// for abi encoding the response - the array will be found at 0x20
mstore(memptr, 0x20)
// next we store the length of the return array
mstore(add(memptr, 0x20), slots.length)
// update memptr to the first location to hold an array entry
memptr := add(memptr, 0x40)
// A left bit-shift of 5 is equivalent to multiplying by 32 but costs less gas.
let end := add(memptr, shl(5, slots.length))
let calldataptr := slots.offset
for {} 1 {} {
mstore(memptr, tload(calldataload(calldataptr)))
memptr := add(memptr, 0x20)
calldataptr := add(calldataptr, 0x20)
if iszero(lt(memptr, end)) { break }
}
return(start, sub(end, start))
}
}
}
src/base/MarginBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Owned} from "solmate/src/auth/Owned.sol";
import {PoolId} from "../types/PoolId.sol";
import {MarginState} from "../types/MarginState.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {DoubleEndedQueue} from "../libraries/external/DoubleEndedQueue.sol";
import {IMarginBase} from "../interfaces/IMarginBase.sol";
import {Math} from "../libraries/Math.sol";
import {SafeCast} from "../libraries/SafeCast.sol";
import {StageMath} from "../libraries/StageMath.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
import {Pool} from "../libraries/Pool.sol";
abstract contract MarginBase is IMarginBase, Owned {
using SafeCast for *;
using StageMath for uint256;
using CustomRevert for bytes4;
using DoubleEndedQueue for DoubleEndedQueue.Uint256Deque;
using Pool for Pool.State;
error LiquidityLocked();
MarginState public marginState;
address public marginController;
mapping(PoolId id => uint256) private lastStageTimestampStore; // Timestamp of the last stage
mapping(PoolId id => DoubleEndedQueue.Uint256Deque) private liquidityLockedQueue;
modifier onlyManager() {
_onlyManager();
_;
}
function _onlyManager() internal view {
if (msg.sender != marginController) Unauthorized.selector.revertWith();
}
uint24 private constant PRICE_MOVE_SPEED_PPM = 3000; // 0.3% per step
uint24 private constant RATE_BASE = 20000; // 2%
uint24 private constant USE_MIDDLE_LEVEL = 300000; // 30%
uint24 private constant USE_HIGH_LEVEL = 700000; // 70%
uint24 private constant M_LOW = 10;
uint24 private constant M_MIDDLE = 100;
uint24 private constant M_HIGH = 10000;
uint24 private constant STAGE_DURATION = 12 hours; // default: 12 hour seconds
uint24 private constant STAGE_SIZE = 5; // default: 5 stages
uint24 private constant STAGE_LEAVE_PART = 5; // default: 5, meaning 20% of the total liquidity is free
constructor(address initialOwner) Owned(initialOwner) {
MarginState _marginState = marginState.setPriceMoveSpeedPPM(PRICE_MOVE_SPEED_PPM);
_marginState = _marginState.setRateBase(RATE_BASE);
_marginState = _marginState.setUseMiddleLevel(USE_MIDDLE_LEVEL);
_marginState = _marginState.setUseHighLevel(USE_HIGH_LEVEL);
_marginState = _marginState.setMLow(M_LOW);
_marginState = _marginState.setMMiddle(M_MIDDLE);
_marginState = _marginState.setMHigh(M_HIGH);
_marginState = _marginState.setStageDuration(STAGE_DURATION);
_marginState = _marginState.setStageSize(STAGE_SIZE);
_marginState = _marginState.setStageLeavePart(STAGE_LEAVE_PART);
marginState = _marginState;
}
/// @notice Gets the amount of released and next-to-be-released liquidity.
/// @dev Internal view function to calculate the amount of liquidity that is currently released and the amount that will be released in the next stage.
/// @param id The ID of the pool.
/// @return releasedLiquidity The amount of liquidity that is currently released.
/// @return nextReleasedLiquidity The amount of liquidity that will be released in the next stage.
function _getReleasedLiquidity(PoolId id)
internal
view
returns (uint128 releasedLiquidity, uint128 nextReleasedLiquidity)
{
releasedLiquidity = type(uint128).max;
if (uint256(marginState.stageDuration()) * marginState.stageSize() > 0) {
DoubleEndedQueue.Uint256Deque storage queue = liquidityLockedQueue[id];
uint256 lastStageTimestamp = lastStageTimestampStore[id];
if (!queue.empty()) {
uint256 currentStage = queue.front();
(, releasedLiquidity) = currentStage.decode();
if (
queue.length() > 1 && currentStage.isFree(marginState.stageLeavePart())
&& block.timestamp >= lastStageTimestamp + marginState.stageDuration()
) {
uint256 nextStage = queue.at(1);
(, nextReleasedLiquidity) = nextStage.decode();
}
}
}
}
/// @notice Handles the addition of liquidity to a pool.
/// @dev Locks the liquidity according to the staging mechanism.
/// @param id The ID of the pool.
/// @param liquidityAdded The amount of liquidity to add.
function _handleAddLiquidity(PoolId id, uint256 liquidityAdded) internal {
uint256 stageSize = marginState.stageSize();
if (uint256(marginState.stageDuration()) * stageSize == 0) {
return; // No locking if stageDuration or stageSize is zero
}
uint256 lastStageTimestamp = lastStageTimestampStore[id];
if (lastStageTimestamp == 0) {
// Initialize lastStageTimestamp if it's not set
lastStageTimestampStore[id] = block.timestamp;
}
DoubleEndedQueue.Uint256Deque storage queue = liquidityLockedQueue[id];
uint128 lockAmount = Math.ceilDiv(liquidityAdded, stageSize).toUint128(); // Ensure at least 1 unit is locked per stage
uint256 zeroStage = 0;
if (queue.empty()) {
for (uint32 i = 0; i < stageSize; i++) {
queue.pushBack(zeroStage.add(lockAmount));
}
} else {
uint256 queueSize = Math.min(queue.length(), stageSize);
// If the queue is not empty, we need to update the existing stages
// and add new stages if necessary
for (uint256 i = 0; i < queueSize; i++) {
uint256 stage = queue.at(i);
queue.set(i, stage.add(lockAmount));
}
for (uint256 i = queueSize; i < stageSize; i++) {
queue.pushBack(zeroStage.add(lockAmount));
}
}
}
/// @notice Handles the removal of liquidity from a pool.
/// @dev Checks if the requested amount of liquidity is available for withdrawal and updates the liquidity queue.
/// @param id The ID of the pool.
/// @param liquidityRemoved The amount of liquidity to remove .
function _handleRemoveLiquidity(PoolId id, uint256 liquidityRemoved) internal {
if (uint256(marginState.stageDuration()) * marginState.stageSize() > 0) {
(uint128 releasedLiquidity, uint128 nextReleasedLiquidity) = _getReleasedLiquidity(id);
uint256 availableLiquidity = releasedLiquidity + nextReleasedLiquidity;
if (availableLiquidity < liquidityRemoved) {
LiquidityLocked.selector.revertWith();
}
DoubleEndedQueue.Uint256Deque storage queue = liquidityLockedQueue[id];
if (!queue.empty()) {
if (nextReleasedLiquidity > 0) {
// If next stage is free, we can release the next stage liquidity
uint256 currentStage = queue.popFront(); // Remove the current stage
uint256 nextStage = queue.front();
(, uint128 currentLiquidity) = currentStage.decode();
if (currentLiquidity > liquidityRemoved) {
nextStage = nextStage.add((currentLiquidity - liquidityRemoved).toUint128());
} else {
nextStage = nextStage.sub((liquidityRemoved - currentLiquidity).toUint128());
}
queue.set(0, nextStage);
// Update lastStageTimestamp to the next stage time
lastStageTimestampStore[id] = block.timestamp;
} else {
// If next stage is not free, we just reduce the current stage liquidity
uint256 currentStage = queue.front();
uint256 afterStage;
if (queue.length() == 1) {
afterStage = currentStage.subTotal(liquidityRemoved.toUint128());
} else {
afterStage = currentStage.sub(liquidityRemoved.toUint128());
}
if (!currentStage.isFree(marginState.stageLeavePart()) || queue.length() == 1) {
// Update lastStageTimestamp
lastStageTimestampStore[id] = block.timestamp;
}
queue.set(0, afterStage);
}
}
}
}
/// @dev abstract internal function to allow the ProtocolFees contract to access the lock
function _isUnlocked() internal virtual returns (bool);
/// @dev abstract internal function to allow the ProtocolFees contract to access pool state
function _getAndUpdatePool(PoolKey memory key) internal virtual returns (Pool.State storage);
// ******************** OWNER CALL ********************
/// @notice Sets the margin controller address.
/// @dev Only the owner can call this function.
/// @param controller The address of the new margin controller.
function setMarginController(address controller) external onlyOwner {
if (marginController == address(0)) {
marginController = controller;
emit MarginControllerUpdated(controller);
}
}
/// @inheritdoc IMarginBase
function setMarginState(MarginState newMarginState) external onlyOwner {
marginState = newMarginState;
emit MarginStateUpdated(newMarginState);
}
function setInsuranceFundPercentage(PoolKey memory key, uint8 insuranceFundPercentage) external onlyOwner {
Pool.State storage pool = _getAndUpdatePool(key);
pool.setInsuranceFundPercentage(insuranceFundPercentage);
emit InsuranceFundPercentageUpdated(key.toId(), insuranceFundPercentage);
}
}
src/base/NoDelegateCall.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Prevents delegatecall to a contract
/// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract
abstract contract NoDelegateCall {
error DelegateCallNotAllowed();
/// @dev The original address of this contract
address private immutable ORIGINAL;
constructor() {
// Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.
// In other words, this variable won't change when it's checked at runtime.
ORIGINAL = address(this);
}
/// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,
/// and the use of immutable means the address bytes are copied in every place the modifier is used.
function checkNotDelegateCall() private view {
if (address(this) != ORIGINAL) revert DelegateCallNotAllowed();
}
/// @notice Prevents delegatecall into the modified method
modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
}
src/base/ProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {FeeTypes} from "../types/FeeTypes.sol";
import {Currency} from "../types/Currency.sol";
import {IProtocolFees} from "../interfaces/IProtocolFees.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {ProtocolFeeLibrary} from "../libraries/ProtocolFeeLibrary.sol";
import {MarginBase} from "./MarginBase.sol";
import {Pool} from "../libraries/Pool.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
/// @notice Contract handling the setting and accrual of protocol fees
abstract contract ProtocolFees is IProtocolFees, MarginBase {
using ProtocolFeeLibrary for uint24;
using Pool for Pool.State;
using CustomRevert for bytes4;
Currency transient syncedCurrency;
uint256 transient syncedReserves;
/// @inheritdoc IProtocolFees
mapping(Currency currency => uint256 amount) public protocolFeesAccrued;
/// @inheritdoc IProtocolFees
address public protocolFeeController;
uint24 public defaultProtocolFee;
constructor(address initialOwner) MarginBase(initialOwner) {
defaultProtocolFee = defaultProtocolFee.setProtocolFee(FeeTypes.SWAP, 20).setProtocolFee(FeeTypes.MARGIN, 40)
.setProtocolFee(FeeTypes.INTERESTS, 10); // 10% SWAP,20% MARGIN,5% INTERESTS
}
/// @inheritdoc IProtocolFees
function setProtocolFeeController(address controller) external onlyOwner {
protocolFeeController = controller;
emit ProtocolFeeControllerUpdated(controller);
}
/// @inheritdoc IProtocolFees
function setDefaultProtocolFee(FeeTypes feeType, uint8 newFee) external onlyOwner {
uint24 newProtocolFee = defaultProtocolFee.setProtocolFee(feeType, newFee);
if (!newProtocolFee.isValidProtocolFee()) ProtocolFeeTooLarge.selector.revertWith(newProtocolFee);
defaultProtocolFee = newProtocolFee;
emit DefaultProtocolFeeUpdated(uint8(feeType), newFee);
}
/// @inheritdoc IProtocolFees
function setProtocolFee(PoolKey memory key, FeeTypes feeType, uint8 newFee) external {
if (msg.sender != protocolFeeController) InvalidCaller.selector.revertWith();
Pool.State storage pool = _getAndUpdatePool(key);
uint24 newProtocolFee = pool.slot0.protocolFee(defaultProtocolFee).setProtocolFee(feeType, newFee);
if (!newProtocolFee.isValidProtocolFee()) ProtocolFeeTooLarge.selector.revertWith(newProtocolFee);
pool.setProtocolFee(newProtocolFee);
emit ProtocolFeeUpdated(key.toId(), newProtocolFee);
}
/// @inheritdoc IProtocolFees
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected)
{
if (msg.sender != protocolFeeController) InvalidCaller.selector.revertWith();
if (!currency.isAddressZero() && syncedCurrency == currency) {
// prevent transfer between the sync and settle balanceOfs (native settle uses msg.value)
ProtocolFeeCurrencySynced.selector.revertWith();
}
if (recipient == address(0)) InvalidRecipient.selector.revertWith();
amountCollected = (amount > protocolFeesAccrued[currency]) ? protocolFeesAccrued[currency] : amount;
protocolFeesAccrued[currency] -= amountCollected;
currency.transfer(recipient, amountCollected);
}
function _updateProtocolFees(Currency currency, uint256 amount) internal {
unchecked {
protocolFeesAccrued[currency] += amount;
}
}
}
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/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/IProtocolFees.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {FeeTypes} from "../types/FeeTypes.sol";
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Thrown when the recipient address is invalid (e.g., zero address).
error InvalidRecipient();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the default protocol fee is updated.
event DefaultProtocolFeeUpdated(uint8 feeType, uint8 newFee);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the default protocol fee
/// @param feeType The fee type to set a protocol fee for
/// @param newFee The new protocol fee
function setDefaultProtocolFee(FeeTypes feeType, uint8 newFee) external;
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param feeType The type of fee to set (swap, margin, or interest)
/// @param newFee The new protocol fee to set, represented as an integer between 0 and 200 (inclusive) where 200 represents a 100% protocol fee
function setProtocolFee(PoolKey memory key, FeeTypes feeType, uint8 newFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
/// @notice Returns the default vault of protocol fee
/// @return uint24 The current protocol fee default vault
function defaultProtocolFee() external view returns (uint24);
}
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/CurrencyGuard.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity 0.8.28;
import {Currency} from "../types/Currency.sol";
library CurrencyGuard {
/// @dev uint256 internal constant CURRENCY_DELTA = uint256(keccak256("CURRENCY_DELTA")) - 1;
uint256 internal constant CURRENCY_DELTA = 0xd9bd4e389ed8cbf1cf078cf6e39b899ba664e27ad65dbc00c572373981e91d5e;
/// @dev ref: https://docs.soliditylang.org/en/v0.8.24/internals/layout_in_storage.html#mappings-and-dynamic-arrays
/// simulating mapping index but with a single hash
/// save one keccak256 hash compared to built-in nested mapping
function _currencyDeltaSlot(Currency currency, address target) internal pure returns (bytes32 hashSlot) {
hashSlot = keccak256(abi.encode(currency, target, CURRENCY_DELTA));
}
function currentDelta(Currency currency, address target) internal view returns (int256 delta) {
bytes32 hashSlot = _currencyDeltaSlot(currency, target);
assembly ("memory-safe") {
delta := tload(hashSlot)
}
}
function appendDelta(Currency currency, address target, int128 delta)
internal
returns (int256 previous, int256 current)
{
bytes32 hashSlot = _currencyDeltaSlot(currency, target);
assembly ("memory-safe") {
previous := tload(hashSlot)
}
current = previous + delta;
assembly ("memory-safe") {
tstore(hashSlot, current)
}
}
}
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/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/Pool.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {InsuranceFunds, toInsuranceFunds} from "../types/InsuranceFunds.sol";
import {FeeTypes} from "../types/FeeTypes.sol";
import {MarginActions} from "../types/MarginActions.sol";
import {MarginState} from "../types/MarginState.sol";
import {MarginBalanceDelta} from "../types/MarginBalanceDelta.sol";
import {ReservesType, Reserves, toReserves, ReservesLibrary} from "../types/Reserves.sol";
import {Slot0} from "../types/Slot0.sol";
import {CustomRevert} from "./CustomRevert.sol";
import {FeeLibrary} from "./FeeLibrary.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
import {Math} from "./Math.sol";
import {PairPosition} from "./PairPosition.sol";
import {LendPosition} from "./LendPosition.sol";
import {PerLibrary} from "./PerLibrary.sol";
import {ProtocolFeeLibrary} from "./ProtocolFeeLibrary.sol";
import {TimeLibrary} from "./TimeLibrary.sol";
import {SafeCast} from "./SafeCast.sol";
import {SwapMath} from "./SwapMath.sol";
import {InterestMath} from "./InterestMath.sol";
import {PriceMath} from "./PriceMath.sol";
/// @title A library for managing Likwid pools.
/// @notice This library contains all the functions for interacting with a Likwid pool.
library Pool {
using CustomRevert for bytes4;
using SafeCast for *;
using SwapMath for *;
using FeeLibrary for uint24;
using PerLibrary for uint256;
using TimeLibrary for uint32;
using Pool for State;
using PairPosition for PairPosition.State;
using PairPosition for mapping(bytes32 => PairPosition.State);
using LendPosition for LendPosition.State;
using LendPosition for mapping(bytes32 => LendPosition.State);
using ProtocolFeeLibrary for uint24;
error InvalidFee();
/// @notice Thrown when trying to initialize an already initialized pool
error PoolAlreadyInitialized();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when trying to remove more liquidity than available in the pool
error InsufficientLiquidity();
error InsufficientAmount();
error InconsistentReserves();
uint128 internal constant INITIAL_LIQUIDITY = 1000;
uint8 internal constant DEFAULT_INSURANCE_FUND_PERCENTAGE = 30; // 30%
struct State {
Slot0 slot0;
/// @notice The cumulative borrow rate of the first currency in the pool.
uint256 borrow0CumulativeLast;
/// @notice The cumulative borrow rate of the second currency in the pool.
uint256 borrow1CumulativeLast;
/// @notice The cumulative deposit rate of the first currency in the pool.
uint256 deposit0CumulativeLast;
/// @notice The cumulative deposit rate of the second currency in the pool.
uint256 deposit1CumulativeLast;
Reserves realReserves;
Reserves mirrorReserves;
Reserves pairReserves;
Reserves truncatedReserves;
Reserves lendReserves;
Reserves interestReserves;
/// @notice The reserves allocated for protocol interest
Reserves protocolInterestReserves;
Reserves insuranceFundUpperLimit;
InsuranceFunds insuranceFunds;
/// @notice The positions in the pool, mapped by a hash of the owner's address and a salt.
mapping(bytes32 positionKey => PairPosition.State) positions;
mapping(bytes32 positionKey => LendPosition.State) lendPositions;
}
struct ModifyLiquidityParams {
// the address that owns the position
address owner;
uint256 amount0;
uint256 amount1;
// any change in liquidity
int128 liquidityDelta;
// used to distinguish positions of the same owner, at the same tick range
bytes32 salt;
}
/// @notice Initializes the pool with a given fee
/// @param self The pool state
/// @param lpFee The initial fee for the pool
/// @param marginFee The initial margin fee for the pool
function initialize(State storage self, uint24 lpFee, uint24 marginFee) internal {
if (self.borrow0CumulativeLast != 0) PoolAlreadyInitialized.selector.revertWith();
if (lpFee >= PerLibrary.ONE_MILLION || marginFee >= PerLibrary.ONE_MILLION) {
InvalidFee.selector.revertWith();
}
self.slot0 = Slot0.wrap(bytes32(0)).setLastUpdated(uint32(block.timestamp)).setLpFee(lpFee)
.setMarginFee(marginFee).setInsuranceFundPercentage(DEFAULT_INSURANCE_FUND_PERCENTAGE);
self.borrow0CumulativeLast = FixedPoint96.Q96;
self.borrow1CumulativeLast = FixedPoint96.Q96;
self.deposit0CumulativeLast = FixedPoint96.Q96;
self.deposit1CumulativeLast = FixedPoint96.Q96;
}
/// @notice Sets the protocol fee for the pool
/// @param self The pool state
/// @param protocolFee The new protocol fee
function setProtocolFee(State storage self, uint24 protocolFee) internal {
self.checkPoolInitialized();
self.slot0 = self.slot0.setProtocolFee(protocolFee);
}
/// @notice Sets the insurance fund percentage for the pool
/// @param self The pool state
/// @param insuranceFundPercentage The new insurance fund percentage
function setInsuranceFundPercentage(State storage self, uint8 insuranceFundPercentage) internal {
self.checkPoolInitialized();
self.slot0 = self.slot0.setInsuranceFundPercentage(insuranceFundPercentage);
}
/// @notice Adds or removes liquidity from the pool
/// @param self The pool state
/// @param params The parameters for modifying liquidity
/// @return delta The change in balances
function modifyLiquidity(State storage self, ModifyLiquidityParams memory params)
internal
returns (BalanceDelta delta, int128 finalLiquidityDelta)
{
if (params.liquidityDelta == 0 && params.amount0 == 0 && params.amount1 == 0) {
return (BalanceDelta.wrap(0), 0);
}
Slot0 _slot0 = self.slot0;
Reserves _pairReserves = self.pairReserves;
(uint128 _reserve0, uint128 _reserve1) = _pairReserves.reserves();
uint128 totalSupply = _slot0.totalSupply();
if (params.liquidityDelta < 0) {
// --- Remove Liquidity ---
uint256 liquidityToRemove = uint256(-int256(params.liquidityDelta));
if (liquidityToRemove > totalSupply) InsufficientLiquidity.selector.revertWith();
uint256 amount0Out = Math.mulDiv(liquidityToRemove, _reserve0, totalSupply);
uint256 amount1Out = Math.mulDiv(liquidityToRemove, _reserve1, totalSupply);
delta = toBalanceDelta(amount0Out.toInt128(), amount1Out.toInt128());
self.slot0 = _slot0.setTotalSupply(totalSupply - liquidityToRemove.toUint128());
finalLiquidityDelta = params.liquidityDelta;
} else {
// --- Add Liquidity ---
uint256 amount0In;
uint256 amount1In;
uint256 liquidityAdded;
if (totalSupply == 0) {
totalSupply = INITIAL_LIQUIDITY; // Initial liquidity boost to prevent precision issues
amount0In = params.amount0;
amount1In = params.amount1;
liquidityAdded = Math.sqrt(amount0In * amount1In);
} else {
uint256 amount1FromAmount0 = Math.mulDiv(params.amount0, _reserve1, _reserve0);
if (amount1FromAmount0 <= params.amount1) {
amount0In = params.amount0;
amount1In = amount1FromAmount0;
} else {
amount0In = Math.mulDiv(params.amount1, _reserve0, _reserve1);
amount1In = params.amount1;
}
liquidityAdded = Math.min(
Math.mulDiv(amount0In, totalSupply, _reserve0), Math.mulDiv(amount1In, totalSupply, _reserve1)
);
}
delta = toBalanceDelta(-amount0In.toInt128(), -amount1In.toInt128());
self.slot0 = _slot0.setTotalSupply(totalSupply + liquidityAdded.toUint128());
finalLiquidityDelta = liquidityAdded.toInt128();
}
ReservesLibrary.UpdateParam[] memory deltaParams = new ReservesLibrary.UpdateParam[](2);
deltaParams[0] = ReservesLibrary.UpdateParam(ReservesType.REAL, delta);
deltaParams[1] = ReservesLibrary.UpdateParam(ReservesType.PAIR, delta);
self.updateReserves(deltaParams);
self.positions.get(params.owner, params.salt).update(finalLiquidityDelta, delta);
// Initialize truncated reserves if not set
if (self.truncatedReserves == ReservesLibrary.ZERO_RESERVES) {
self.truncatedReserves = self.pairReserves;
}
}
struct SwapParams {
address sender;
// zeroForOne Whether to swap token0 for token1
bool zeroForOne;
// The amount to swap, negative for exact input, positive for exact output
int256 amountSpecified;
// Whether to use the mirror reserves for the swap
bool useMirror;
bytes32 salt;
}
/// @notice Swaps tokens in the pool
/// @param self The pool state
/// @param params The parameters for the swap
/// @return swapDelta The change in balances
/// @return amountToProtocol The amount of fees to be sent to the protocol
/// @return swapFee The fee for the swap
/// @return feeAmount The total fee amount for the swap.
function swap(State storage self, SwapParams memory params, uint24 defaultProtocolFee)
internal
returns (BalanceDelta swapDelta, uint256 amountToProtocol, uint24 swapFee, uint256 feeAmount)
{
Reserves _pairReserves = self.pairReserves;
Reserves _truncatedReserves = self.truncatedReserves;
Slot0 _slot0 = self.slot0;
uint24 _lpFee = _slot0.lpFee();
bool exactIn = params.amountSpecified < 0;
uint256 amountIn;
uint256 amountOut;
if (exactIn) {
amountIn = uint256(-params.amountSpecified);
(amountOut, swapFee, feeAmount) =
SwapMath.getAmountOut(_pairReserves, _truncatedReserves, _lpFee, params.zeroForOne, amountIn);
} else {
amountOut = uint256(params.amountSpecified);
(amountIn, swapFee, feeAmount) =
SwapMath.getAmountIn(_pairReserves, _truncatedReserves, _lpFee, params.zeroForOne, amountOut);
}
(amountToProtocol, feeAmount) =
ProtocolFeeLibrary.splitFee(_slot0.protocolFee(defaultProtocolFee), FeeTypes.SWAP, feeAmount);
int128 amount0Delta;
int128 amount1Delta;
BalanceDelta protocolFeeDelta;
if (params.zeroForOne) {
amount0Delta = -amountIn.toInt128();
amount1Delta = amountOut.toInt128();
protocolFeeDelta = toBalanceDelta(amountToProtocol.toInt128(), 0);
} else {
amount0Delta = amountOut.toInt128();
amount1Delta = -amountIn.toInt128();
protocolFeeDelta = toBalanceDelta(0, amountToProtocol.toInt128());
}
ReservesLibrary.UpdateParam[] memory deltaParams;
swapDelta = toBalanceDelta(amount0Delta, amount1Delta);
if (!params.useMirror) {
BalanceDelta changeDelta = swapDelta + protocolFeeDelta;
deltaParams = new ReservesLibrary.UpdateParam[](2);
deltaParams[0] = ReservesLibrary.UpdateParam(ReservesType.REAL, changeDelta);
deltaParams[1] = ReservesLibrary.UpdateParam(ReservesType.PAIR, changeDelta);
} else {
deltaParams = new ReservesLibrary.UpdateParam[](3);
BalanceDelta realDelta;
BalanceDelta lendDelta;
if (params.zeroForOne) {
realDelta = toBalanceDelta(amount0Delta, 0);
lendDelta = toBalanceDelta(0, -amount1Delta);
} else {
realDelta = toBalanceDelta(0, amount1Delta);
lendDelta = toBalanceDelta(-amount0Delta, 0);
}
deltaParams[0] = ReservesLibrary.UpdateParam(ReservesType.REAL, realDelta + protocolFeeDelta);
// pair MIRROR<=>lend MIRROR
deltaParams[1] = ReservesLibrary.UpdateParam(ReservesType.LEND, lendDelta);
deltaParams[2] = ReservesLibrary.UpdateParam(ReservesType.PAIR, swapDelta + protocolFeeDelta);
uint256 depositCumulativeLast;
if (params.zeroForOne) {
depositCumulativeLast = self.deposit1CumulativeLast;
} else {
depositCumulativeLast = self.deposit0CumulativeLast;
}
self.lendPositions.get(params.sender, params.zeroForOne, params.salt)
.update(params.zeroForOne, depositCumulativeLast, lendDelta);
}
self.updateReserves(deltaParams);
}
function donate(State storage self, uint256 amount0, uint256 amount1) internal returns (BalanceDelta delta) {
if (amount0 == 0 && amount1 == 0) {
return BalanceDelta.wrap(0);
}
self.insuranceFunds = self.insuranceFunds + toInsuranceFunds(amount0.toInt128(), amount1.toInt128());
delta = toBalanceDelta(-amount0.toInt128(), -amount1.toInt128());
ReservesLibrary.UpdateParam[] memory deltaParams = new ReservesLibrary.UpdateParam[](1);
deltaParams[0] = ReservesLibrary.UpdateParam(ReservesType.REAL, delta);
self.updateReserves(deltaParams);
}
struct LendParams {
address sender;
/// 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 the pool.
/// @param self The pool state.
/// @param params The parameters for the lending operation.
/// @return lendDelta The change in the lender's balance.
/// @return depositCumulativeLast The last cumulative deposit rate.
function lend(State storage self, LendParams memory params)
internal
returns (BalanceDelta lendDelta, uint256 depositCumulativeLast)
{
int128 amount0Delta;
int128 amount1Delta;
if (params.lendForOne) {
amount1Delta = params.lendAmount;
depositCumulativeLast = self.deposit1CumulativeLast;
} else {
amount0Delta = params.lendAmount;
depositCumulativeLast = self.deposit0CumulativeLast;
}
lendDelta = toBalanceDelta(amount0Delta, amount1Delta);
ReservesLibrary.UpdateParam[] memory deltaParams = new ReservesLibrary.UpdateParam[](2);
deltaParams[0] = ReservesLibrary.UpdateParam(ReservesType.REAL, lendDelta);
deltaParams[1] = ReservesLibrary.UpdateParam(ReservesType.LEND, lendDelta);
self.updateReserves(deltaParams);
self.lendPositions.get(params.sender, params.lendForOne, params.salt)
.update(params.lendForOne, depositCumulativeLast, lendDelta);
}
function margin(State storage self, MarginBalanceDelta memory params, uint24 defaultProtocolFee)
internal
returns (
BalanceDelta marginDelta,
uint256 marginToProtocol,
uint256 swapToProtocol,
uint256 protocolInterest0,
uint256 protocolInterest1
)
{
if (
(params.action != MarginActions.CLOSE && params.action != MarginActions.LIQUIDATE_BURN)
&& params.marginDelta == BalanceDeltaLibrary.ZERO_DELTA
) {
InsufficientAmount.selector.revertWith();
}
Slot0 _slot0 = self.slot0;
marginDelta = params.marginDelta;
bool isMargin = params.action == MarginActions.MARGIN;
if (isMargin) {
(marginToProtocol, params.marginFeeAmount) = ProtocolFeeLibrary.splitFee(
_slot0.protocolFee(defaultProtocolFee), FeeTypes.MARGIN, params.marginFeeAmount
);
}
(swapToProtocol, params.swapFeeAmount) =
ProtocolFeeLibrary.splitFee(_slot0.protocolFee(defaultProtocolFee), FeeTypes.SWAP, params.swapFeeAmount);
BalanceDelta protocolDelta;
int128 amount0Delta;
int128 amount1Delta;
if (params.marginForOne) {
if (isMargin) {
amount0Delta = swapToProtocol.toInt128();
amount1Delta = marginToProtocol.toInt128();
} else {
amount1Delta = swapToProtocol.toInt128();
}
} else {
if (isMargin) {
amount0Delta = marginToProtocol.toInt128();
amount1Delta = swapToProtocol.toInt128();
} else {
amount0Delta = swapToProtocol.toInt128();
}
}
protocolDelta = toBalanceDelta(amount0Delta, amount1Delta);
ReservesLibrary.UpdateParam[] memory deltaParams = new ReservesLibrary.UpdateParam[](4);
deltaParams[0] = ReservesLibrary.UpdateParam(ReservesType.REAL, marginDelta + protocolDelta);
deltaParams[1] = ReservesLibrary.UpdateParam(ReservesType.PAIR, params.pairDelta + protocolDelta);
deltaParams[2] = ReservesLibrary.UpdateParam(ReservesType.LEND, params.lendDelta);
deltaParams[3] = ReservesLibrary.UpdateParam(ReservesType.MIRROR, params.mirrorDelta);
(protocolInterest0, protocolInterest1) =
self.updateReserves(deltaParams, InsuranceFunds.wrap(BalanceDelta.unwrap(params.fundsDelta)));
}
/// @notice Reverts if the given pool has not been initialized
/// @param self The pool state
function checkPoolInitialized(State storage self) internal view {
if (self.borrow0CumulativeLast == 0) PoolNotInitialized.selector.revertWith();
}
/// @notice Updates the interest rates for the pool.
/// @param self The pool state.
/// @param marginState The current rate state.
/// @return pairInterest0 The interest earned by the pair for token0.
/// @return pairInterest1 The interest earned by the pair for token1.
function updateInterests(State storage self, MarginState marginState, uint24 defaultProtocolFee)
internal
returns (uint256 pairInterest0, uint256 pairInterest1, uint256 protocolInterest0, uint256 protocolInterest1)
{
Slot0 _slot0 = self.slot0;
uint256 timeElapsed = _slot0.lastUpdated().getTimeElapsed();
if (timeElapsed == 0) return (0, 0, 0, 0);
uint24 protocolFee = _slot0.protocolFee(defaultProtocolFee);
Reserves _realReserves = self.realReserves;
Reserves _mirrorReserves = self.mirrorReserves;
Reserves _interestReserves = self.interestReserves;
Reserves _protocolInterestReserves = self.protocolInterestReserves;
Reserves _pairReserves = self.pairReserves;
Reserves _lendReserves = self.lendReserves;
uint256 borrow0CumulativeBefore = self.borrow0CumulativeLast;
uint256 borrow1CumulativeBefore = self.borrow1CumulativeLast;
(uint256 borrow0CumulativeLast, uint256 borrow1CumulativeLast) = InterestMath.getBorrowRateCumulativeLast(
timeElapsed, borrow0CumulativeBefore, borrow1CumulativeBefore, marginState, _realReserves, _mirrorReserves
);
(uint256 pairReserve0, uint256 pairReserve1) = _pairReserves.reserves();
(uint256 lendReserve0, uint256 lendReserve1) = _lendReserves.reserves();
(uint256 mirrorReserve0, uint256 mirrorReserve1) = _mirrorReserves.reserves();
(uint256 interestReserve0, uint256 interestReserve1) = _interestReserves.reserves();
(uint256 protocolInterestReserve0, uint256 protocolInterestReserve1) = _protocolInterestReserves.reserves();
InterestMath.InterestUpdateResult memory result0 = InterestMath.updateInterestForOne(
InterestMath.InterestUpdateParams({
mirrorReserve: mirrorReserve0,
borrowCumulativeLast: borrow0CumulativeLast,
borrowCumulativeBefore: borrow0CumulativeBefore,
interestReserve: interestReserve0,
pairReserve: pairReserve0,
lendReserve: lendReserve0,
protocolInterestReserve: protocolInterestReserve0,
depositCumulativeLast: self.deposit0CumulativeLast,
protocolFee: protocolFee
})
);
if (result0.changed) {
mirrorReserve0 = result0.newMirrorReserve;
pairReserve0 = result0.newPairReserve;
lendReserve0 = result0.newLendReserve;
self.deposit0CumulativeLast = result0.newDepositCumulativeLast;
protocolInterestReserve0 = result0.newProtocolInterestReserve;
protocolInterest0 = result0.protocolInterest;
pairInterest0 = result0.pairInterest;
}
InterestMath.InterestUpdateResult memory result1 = InterestMath.updateInterestForOne(
InterestMath.InterestUpdateParams({
mirrorReserve: mirrorReserve1,
borrowCumulativeLast: borrow1CumulativeLast,
borrowCumulativeBefore: borrow1CumulativeBefore,
interestReserve: interestReserve1,
pairReserve: pairReserve1,
lendReserve: lendReserve1,
protocolInterestReserve: protocolInterestReserve1,
depositCumulativeLast: self.deposit1CumulativeLast,
protocolFee: protocolFee
})
);
if (result1.changed) {
mirrorReserve1 = result1.newMirrorReserve;
pairReserve1 = result1.newPairReserve;
lendReserve1 = result1.newLendReserve;
self.deposit1CumulativeLast = result1.newDepositCumulativeLast;
protocolInterestReserve1 = result1.newProtocolInterestReserve;
protocolInterest1 = result1.protocolInterest;
pairInterest1 = result1.pairInterest;
}
if (result0.changed || result1.changed) {
_pairReserves = toReserves(pairReserve0.toUint128(), pairReserve1.toUint128());
self.pairReserves = _pairReserves;
self.mirrorReserves = toReserves(mirrorReserve0.toUint128(), mirrorReserve1.toUint128());
self.lendReserves = toReserves(lendReserve0.toUint128(), lendReserve1.toUint128());
self.protocolInterestReserves =
toReserves(protocolInterestReserve0.toUint128(), protocolInterestReserve1.toUint128());
}
Reserves _truncatedReserves = self.truncatedReserves;
self.truncatedReserves =
PriceMath.transferReserves(_truncatedReserves, _pairReserves, timeElapsed, marginState.priceMoveSpeedPPM());
if (borrow0CumulativeBefore < borrow0CumulativeLast) {
self.borrow0CumulativeLast = borrow0CumulativeLast;
}
if (borrow1CumulativeBefore < borrow1CumulativeLast) {
self.borrow1CumulativeLast = borrow1CumulativeLast;
}
if (interestReserve0 != result0.newInterestReserve || interestReserve1 != result1.newInterestReserve) {
self.interestReserves =
toReserves(result0.newInterestReserve.toUint128(), result1.newInterestReserve.toUint128());
}
self.slot0 = self.slot0.setLastUpdated(uint32(block.timestamp));
}
/// @notice Updates the reserves of the pool.
/// @param self The pool state.
/// @param params An array of parameters for updating the reserves.
/// @param fundsDelta The input change in insurance funds.
function updateReserves(State storage self, ReservesLibrary.UpdateParam[] memory params, InsuranceFunds fundsDelta)
internal
returns (uint256 protocolInterest0, uint256 protocolInterest1)
{
if (params.length == 0) return (protocolInterest0, protocolInterest1);
Reserves _realReserves = self.realReserves;
Reserves _mirrorReserves = self.mirrorReserves;
Reserves _pairReserves = self.pairReserves;
Reserves _lendReserves = self.lendReserves;
Reserves _protocolInterestReserves = self.protocolInterestReserves;
BalanceDelta _realOddDelta = BalanceDelta.wrap(0);
for (uint256 i = 0; i < params.length; i++) {
ReservesType _type = params[i]._type;
BalanceDelta delta = params[i].delta;
if (_type == ReservesType.REAL) {
_realReserves = _realReserves.applyDelta(delta);
} else if (_type == ReservesType.MIRROR) {
int128 d0 = delta.amount0();
int128 d1 = delta.amount1();
(uint128 mirror0, uint128 mirror1) = _mirrorReserves.reserves();
(uint128 pInterest0, uint128 pInterest1) = _protocolInterestReserves.reserves();
if (d0 > 0) {
uint256 amount = uint256(uint128(d0));
uint256 total = uint256(mirror0) + pInterest0;
if (total > 0) {
if (amount <= total) {
uint256 mirrorPart = Math.mulDiv(amount, mirror0, total);
uint256 pInterestPart = amount - mirrorPart;
_realOddDelta = _realOddDelta + toBalanceDelta(pInterestPart.toInt128(), 0);
mirror0 -= mirrorPart.toUint128();
pInterest0 -= pInterestPart.toUint128();
protocolInterest0 += pInterestPart;
} else {
_realOddDelta = _realOddDelta + toBalanceDelta(pInterest0.toInt128(), 0);
fundsDelta = fundsDelta + toInsuranceFunds((amount - total).toInt128(), 0);
protocolInterest0 += pInterest0;
mirror0 = 0;
pInterest0 = 0;
}
} else {
_realOddDelta = _realOddDelta + toBalanceDelta(d0, 0);
}
} else if (d0 < 0) {
mirror0 += uint128(-d0);
}
if (d1 > 0) {
uint256 amount = uint256(uint128(d1));
uint256 total = uint256(mirror1) + pInterest1;
if (total > 0) {
if (amount <= total) {
uint256 mirrorPart = Math.mulDiv(amount, mirror1, total);
uint256 pInterestPart = amount - mirrorPart;
_realOddDelta = _realOddDelta + toBalanceDelta(0, pInterestPart.toInt128());
mirror1 -= mirrorPart.toUint128();
pInterest1 -= pInterestPart.toUint128();
protocolInterest1 += pInterestPart;
} else {
_realOddDelta = _realOddDelta + toBalanceDelta(0, pInterest1.toInt128());
fundsDelta = fundsDelta + toInsuranceFunds(0, (amount - total).toInt128());
protocolInterest1 += pInterest1;
mirror1 = 0;
pInterest1 = 0;
}
} else {
_realOddDelta = _realOddDelta + toBalanceDelta(0, d1);
}
} else if (d1 < 0) {
mirror1 += uint128(-d1);
}
_mirrorReserves = toReserves(mirror0, mirror1);
_protocolInterestReserves = toReserves(pInterest0, pInterest1);
} else if (_type == ReservesType.PAIR) {
_pairReserves = _pairReserves.applyDelta(delta);
} else if (_type == ReservesType.LEND) {
_lendReserves = _lendReserves.applyDelta(delta);
}
}
_realReserves = _realReserves.applyDelta(_realOddDelta);
Reserves _insuranceFundUpperLimit = self.insuranceFundUpperLimit;
self._updateReservesConsistent(
_realReserves, _mirrorReserves, _pairReserves, _lendReserves, _insuranceFundUpperLimit, fundsDelta
);
self.protocolInterestReserves = _protocolInterestReserves;
}
function updateReserves(State storage self, ReservesLibrary.UpdateParam[] memory params)
internal
returns (uint256 protocolInterest0, uint256 protocolInterest1)
{
return self.updateReserves(params, InsuranceFunds.wrap(0));
}
function _distributeExcessFunds(
int128 currentFund,
int128 fundDelta,
uint256 limit,
uint128 pairReserve,
uint128 lendReserve
) private pure returns (int128 newFund, uint128 pairAdd, uint128 lendAdd) {
newFund = currentFund + fundDelta;
if (fundDelta > 0 && newFund > 0) {
uint128 newFundU = uint128(newFund);
if (newFundU > limit) {
uint256 excess = newFundU - limit;
uint128 fundDeltaU = uint128(fundDelta);
if (excess > fundDeltaU) {
excess = fundDeltaU;
}
uint256 totalReserve = uint256(pairReserve) + uint256(lendReserve);
if (totalReserve > 0) {
uint256 pairAddAmount = Math.mulDiv(excess, pairReserve, totalReserve);
pairAdd = pairAddAmount.toUint128();
lendAdd = (excess - pairAddAmount).toUint128();
}
newFund = (newFundU - excess).toInt128();
}
}
}
function _updateReservesConsistent(
State storage self,
Reserves _realReserves,
Reserves _mirrorReserves,
Reserves _pairReserves,
Reserves _lendReserves,
Reserves _insuranceFundUpperLimit,
InsuranceFunds fundsDelta
) internal {
InsuranceFunds _insuranceFunds = self.insuranceFunds;
uint8 insuranceFundPercentage = self.slot0.insuranceFundPercentage();
Reserves reserves0 = _realReserves + _mirrorReserves;
(uint256 r0, uint256 r1) = reserves0.reserves();
(uint256 limit0, uint256 limit1) = _insuranceFundUpperLimit.reserves();
uint256 newInsuranceFundLimit0 = Math.mulDiv(r0, insuranceFundPercentage, 100);
uint256 newInsuranceFundLimit1 = Math.mulDiv(r1, insuranceFundPercentage, 100);
if (limit0 < newInsuranceFundLimit0) {
limit0 = newInsuranceFundLimit0;
}
if (limit1 < newInsuranceFundLimit1) {
limit1 = newInsuranceFundLimit1;
}
_insuranceFundUpperLimit = toReserves(limit0.toUint128(), limit1.toUint128());
(int128 insuranceFund0, int128 insuranceFund1) = _insuranceFunds.unpack();
(int128 fundsDelta0, int128 fundsDelta1) = fundsDelta.unpack();
(uint128 pairR0, uint128 pairR1) = _pairReserves.reserves();
(uint128 lendR0, uint128 lendR1) = _lendReserves.reserves();
uint128 pairAdd0;
uint128 lendAdd0;
(insuranceFund0, pairAdd0, lendAdd0) =
_distributeExcessFunds(insuranceFund0, fundsDelta0, limit0, pairR0, lendR0);
uint128 pairAdd1;
uint128 lendAdd1;
(insuranceFund1, pairAdd1, lendAdd1) =
_distributeExcessFunds(insuranceFund1, fundsDelta1, limit1, pairR1, lendR1);
if (pairAdd0 > 0 || pairAdd1 > 0) {
_pairReserves = _pairReserves + toReserves(pairAdd0, pairAdd1);
}
if (lendAdd0 > 0 || lendAdd1 > 0) {
_lendReserves = _lendReserves + toReserves(lendAdd0, lendAdd1);
}
_insuranceFunds = toInsuranceFunds(insuranceFund0, insuranceFund1);
Reserves reserves1 = (_pairReserves + _lendReserves).applyFunds(_insuranceFunds);
if (reserves0 != reserves1) {
InconsistentReserves.selector.revertWith();
}
self.realReserves = _realReserves;
self.mirrorReserves = _mirrorReserves;
self.pairReserves = _pairReserves;
self.lendReserves = _lendReserves;
self.insuranceFundUpperLimit = _insuranceFundUpperLimit;
self.insuranceFunds = _insuranceFunds;
}
}
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/StageMath.sol
// SPDX-License-Identifier: BUSL-1.1
// Likwid Contracts
pragma solidity ^0.8.26;
library StageMath {
function add(uint256 stage, uint128 amount) internal pure returns (uint256) {
(uint128 _total, uint128 _liquidity) = decode(stage);
_total += amount;
_liquidity += amount;
return (uint256(_total) << 128) | uint256(_liquidity);
}
function sub(uint256 stage, uint128 amount) internal pure returns (uint256) {
(uint128 _total, uint128 _liquidity) = decode(stage);
_liquidity -= amount;
return (uint256(_total) << 128) | uint256(_liquidity);
}
function subTotal(uint256 stage, uint128 amount) internal pure returns (uint256) {
(uint128 _total, uint128 _liquidity) = decode(stage);
_total -= amount;
_liquidity -= amount;
return (uint256(_total) << 128) | uint256(_liquidity);
}
function isFree(uint256 stage, uint32 leavePart) internal pure returns (bool) {
(uint128 total, uint128 liquidity) = decode(stage);
if (leavePart == 0) {
leavePart = 2;
}
return total / leavePart >= liquidity;
}
function decode(uint256 stage) internal pure returns (uint128 total, uint128 liquidity) {
if (stage == 0) {
return (0, 0);
}
total = uint128(stage >> 128);
liquidity = uint128(stage & ((1 << 128) - 1));
}
}
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/libraries/external/DoubleEndedQueue.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Panic} from "@openzeppelin/contracts/utils/Panic.sol";
/**
* @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of
* the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and
* FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that
* the existing queue contents are left in storage.
*
* The struct is called `Uint256Deque`. Other types can be cast to and from `uint256`. This data structure can only be
* used in storage, and not in memory.
* ```solidity
* DoubleEndedQueue.Uint256Deque queue;
* ```
*/
library DoubleEndedQueue {
/**
* @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access.
*
* Struct members have an underscore prefix indicating that they are "private" and should not be read or written to
* directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and
* lead to unexpected behavior.
*
* The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around.
*/
struct Uint256Deque {
uint128 _begin;
uint128 _end;
mapping(uint128 index => uint256) _data;
}
/**
* @dev Inserts an item at the end of the queue.
*
* Reverts with {Panic-RESOURCE_ERROR} if the queue is full.
*/
function pushBack(Uint256Deque storage deque, uint256 value) internal {
unchecked {
uint128 backIndex = deque._end;
if (backIndex + 1 == deque._begin) Panic.panic(Panic.RESOURCE_ERROR);
deque._data[backIndex] = value;
deque._end = backIndex + 1;
}
}
/**
* @dev Removes the item at the end of the queue and returns it.
*
* Reverts with {Panic-EMPTY_ARRAY_POP} if the queue is empty.
*/
function popBack(Uint256Deque storage deque) internal returns (uint256 value) {
unchecked {
uint128 backIndex = deque._end;
if (backIndex == deque._begin) Panic.panic(Panic.EMPTY_ARRAY_POP);
--backIndex;
value = deque._data[backIndex];
delete deque._data[backIndex];
deque._end = backIndex;
}
}
/**
* @dev Inserts an item at the beginning of the queue.
*
* Reverts with {Panic-RESOURCE_ERROR} if the queue is full.
*/
function pushFront(Uint256Deque storage deque, uint256 value) internal {
unchecked {
uint128 frontIndex = deque._begin - 1;
if (frontIndex == deque._end) Panic.panic(Panic.RESOURCE_ERROR);
deque._data[frontIndex] = value;
deque._begin = frontIndex;
}
}
/**
* @dev Removes the item at the beginning of the queue and returns it.
*
* Reverts with {Panic-EMPTY_ARRAY_POP} if the queue is empty.
*/
function popFront(Uint256Deque storage deque) internal returns (uint256 value) {
unchecked {
uint128 frontIndex = deque._begin;
if (frontIndex == deque._end) Panic.panic(Panic.EMPTY_ARRAY_POP);
value = deque._data[frontIndex];
delete deque._data[frontIndex];
deque._begin = frontIndex + 1;
}
}
/**
* @dev Returns the item at the beginning of the queue.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the queue is empty.
*/
function front(Uint256Deque storage deque) internal view returns (uint256 value) {
if (empty(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
return deque._data[deque._begin];
}
/**
* @dev Returns the item at the end of the queue.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the queue is empty.
*/
function back(Uint256Deque storage deque) internal view returns (uint256 value) {
if (empty(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
unchecked {
return deque._data[deque._end - 1];
}
}
/**
* @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at
* `length(deque) - 1`.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the index is out of bounds.
*/
function at(Uint256Deque storage deque, uint256 index) internal view returns (uint256 value) {
if (index >= length(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
// By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128
unchecked {
return deque._data[deque._begin + uint128(index)];
}
}
/**
* @dev Sets the item at a position in the queue given by `index`, with the first item at 0 and last item at
* `length(deque) - 1`.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the index is out of bounds.
*/
function set(Uint256Deque storage deque, uint256 index, uint256 value) internal {
if (index >= length(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
// By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128
unchecked {
deque._data[deque._begin + uint128(index)] = value;
}
}
/**
* @dev Resets the queue back to being empty.
*
* NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses
* out on potential gas refunds.
*/
function clear(Uint256Deque storage deque) internal {
deque._begin = 0;
deque._end = 0;
}
/**
* @dev Returns the number of items in the queue.
*/
function length(Uint256Deque storage deque) internal view returns (uint256) {
unchecked {
return uint256(deque._end - deque._begin);
}
}
/**
* @dev Returns true if the queue is empty.
*/
function empty(Uint256Deque storage deque) internal view returns (bool) {
return deque._end == deque._begin;
}
}
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/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/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.