Contract Name:
AlgebraPool
Contract Source Code:
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
pragma abicoder v1;
import './base/AlgebraPoolBase.sol';
import './base/ReentrancyGuard.sol';
import './base/Positions.sol';
import './base/SwapCalculation.sol';
import './base/ReservesManager.sol';
import './base/TickStructure.sol';
import './libraries/FullMath.sol';
import './libraries/Constants.sol';
import './libraries/SafeCast.sol';
import './libraries/TickMath.sol';
import './libraries/LiquidityMath.sol';
import './libraries/Plugins.sol';
import './interfaces/plugin/IAlgebraPlugin.sol';
import './interfaces/IAlgebraFactory.sol';
/// @title Algebra concentrated liquidity pool
/// @notice This contract is responsible for liquidity positions, swaps and flashloans
/// @dev Version: Algebra Integral 1.0
contract AlgebraPool is AlgebraPoolBase, TickStructure, ReentrancyGuard, Positions, SwapCalculation, ReservesManager {
using SafeCast for uint256;
using SafeCast for uint128;
using Plugins for uint8;
using Plugins for bytes4;
/// @inheritdoc IAlgebraPoolActions
function initialize(uint160 initialPrice) external override {
int24 tick = TickMath.getTickAtSqrtRatio(initialPrice); // getTickAtSqrtRatio checks validity of initialPrice inside
if (globalState.price != 0) revert alreadyInitialized(); // after initialization, the price can never become zero
globalState.price = initialPrice;
if (plugin != address(0)) {
IAlgebraPlugin(plugin).beforeInitialize(msg.sender, initialPrice).shouldReturn(IAlgebraPlugin.beforeInitialize.selector);
}
(uint16 _communityFee, int24 _tickSpacing, uint16 _fee, address _communityVault) = _getDefaultConfiguration();
uint8 pluginConfig = globalState.pluginConfig;
globalState.tick = tick;
globalState.communityFee = _communityFee;
emit Initialize(initialPrice, tick);
_setFee(_fee);
_setTickSpacing(_tickSpacing);
_setCommunityFeeVault(_communityVault);
if (_communityFee != 0 && _communityVault == address(0)) revert invalidNewCommunityFee(); // the pool should not accumulate a community fee without a vault
_setCommunityFee(_communityFee);
if (pluginConfig.hasFlag(Plugins.AFTER_INIT_FLAG)) {
IAlgebraPlugin(plugin).afterInitialize(msg.sender, initialPrice, tick).shouldReturn(IAlgebraPlugin.afterInitialize.selector);
}
}
/// @inheritdoc IAlgebraPoolActions
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external override onlyValidTicks(bottomTick, topTick) returns (uint256 amount0, uint256 amount1, uint128 liquidityActual) {
if (liquidityDesired == 0) revert zeroLiquidityDesired();
_beforeModifyPos(recipient, bottomTick, topTick, liquidityDesired.toInt128(), data);
_lock();
{
// scope to prevent stack too deep
int24 currentTick = globalState.tick;
uint160 currentPrice = globalState.price;
if (currentPrice == 0) revert notInitialized();
unchecked {
int24 _tickSpacing = tickSpacing;
if (bottomTick % _tickSpacing | topTick % _tickSpacing != 0) revert tickIsNotSpaced();
}
(amount0, amount1, ) = LiquidityMath.getAmountsForLiquidity(bottomTick, topTick, liquidityDesired.toInt128(), currentTick, currentPrice);
}
(uint256 receivedAmount0, uint256 receivedAmount1) = _updateReserves();
_mintCallback(amount0, amount1, data); // IAlgebraMintCallback.algebraMintCallback to msg.sender
receivedAmount0 = amount0 == 0 ? 0 : _balanceToken0() - receivedAmount0;
receivedAmount1 = amount1 == 0 ? 0 : _balanceToken1() - receivedAmount1;
if (receivedAmount0 < amount0) {
liquidityActual = uint128(FullMath.mulDiv(uint256(liquidityDesired), receivedAmount0, amount0));
} else {
liquidityActual = liquidityDesired;
}
if (receivedAmount1 < amount1) {
uint128 liquidityForRA1 = uint128(FullMath.mulDiv(uint256(liquidityDesired), receivedAmount1, amount1));
if (liquidityForRA1 < liquidityActual) liquidityActual = liquidityForRA1;
}
if (liquidityActual == 0) revert zeroLiquidityActual();
// scope to prevent "stack too deep"
{
Position storage _position = getOrCreatePosition(recipient, bottomTick, topTick);
(amount0, amount1) = _updatePositionTicksAndFees(_position, bottomTick, topTick, liquidityActual.toInt128());
}
unchecked {
// return leftovers
if (amount0 > 0) {
if (receivedAmount0 > amount0) _transfer(token0, leftoversRecipient, receivedAmount0 - amount0);
else assert(receivedAmount0 == amount0); // must always be true
}
if (amount1 > 0) {
if (receivedAmount1 > amount1) _transfer(token1, leftoversRecipient, receivedAmount1 - amount1);
else assert(receivedAmount1 == amount1); // must always be true
}
}
_changeReserves(int256(amount0), int256(amount1), 0, 0);
emit Mint(msg.sender, recipient, bottomTick, topTick, liquidityActual, amount0, amount1);
_unlock();
_afterModifyPos(recipient, bottomTick, topTick, liquidityActual.toInt128(), amount0, amount1, data);
}
/// @inheritdoc IAlgebraPoolActions
function burn(
int24 bottomTick,
int24 topTick,
uint128 amount,
bytes calldata data
) external override onlyValidTicks(bottomTick, topTick) returns (uint256 amount0, uint256 amount1) {
if (amount > uint128(type(int128).max)) revert arithmeticError();
int128 liquidityDelta = -int128(amount);
_beforeModifyPos(msg.sender, bottomTick, topTick, liquidityDelta, data);
_lock();
_updateReserves();
Position storage position = getOrCreatePosition(msg.sender, bottomTick, topTick);
(amount0, amount1) = _updatePositionTicksAndFees(position, bottomTick, topTick, liquidityDelta);
if (amount0 | amount1 != 0) {
// since we do not support tokens whose total supply can exceed uint128, these casts are safe
// and, theoretically, unchecked cast prevents a complete blocking of burn
(position.fees0, position.fees1) = (position.fees0 + uint128(amount0), position.fees1 + uint128(amount1));
}
if (amount | amount0 | amount1 != 0) emit Burn(msg.sender, bottomTick, topTick, amount, amount0, amount1);
_unlock();
_afterModifyPos(msg.sender, bottomTick, topTick, liquidityDelta, amount0, amount1, data);
}
function _beforeModifyPos(address owner, int24 bottomTick, int24 topTick, int128 liquidityDelta, bytes calldata data) internal {
if (globalState.pluginConfig.hasFlag(Plugins.BEFORE_POSITION_MODIFY_FLAG)) {
IAlgebraPlugin(plugin).beforeModifyPosition(msg.sender, owner, bottomTick, topTick, liquidityDelta, data).shouldReturn(
IAlgebraPlugin.beforeModifyPosition.selector
);
}
}
function _afterModifyPos(address owner, int24 bTick, int24 tTick, int128 deltaL, uint256 amount0, uint256 amount1, bytes calldata data) internal {
if (globalState.pluginConfig.hasFlag(Plugins.AFTER_POSITION_MODIFY_FLAG)) {
IAlgebraPlugin(plugin).afterModifyPosition(msg.sender, owner, bTick, tTick, deltaL, amount0, amount1, data).shouldReturn(
IAlgebraPlugin.afterModifyPosition.selector
);
}
}
/// @inheritdoc IAlgebraPoolActions
function collect(
address recipient,
int24 bottomTick,
int24 topTick,
uint128 amount0Requested,
uint128 amount1Requested
) external override returns (uint128 amount0, uint128 amount1) {
_lock();
// we don't check tick range validity, because if ticks are incorrect, the position will be empty
Position storage position = getOrCreatePosition(msg.sender, bottomTick, topTick);
(uint128 positionFees0, uint128 positionFees1) = (position.fees0, position.fees1);
if (amount0Requested > positionFees0) amount0Requested = positionFees0;
if (amount1Requested > positionFees1) amount1Requested = positionFees1;
if (amount0Requested | amount1Requested != 0) {
// use one if since fees0 and fees1 are tightly packed
(amount0, amount1) = (amount0Requested, amount1Requested);
unchecked {
// single SSTORE
(position.fees0, position.fees1) = (positionFees0 - amount0, positionFees1 - amount1);
if (amount0 > 0) _transfer(token0, recipient, amount0);
if (amount1 > 0) _transfer(token1, recipient, amount1);
_changeReserves(-int256(uint256(amount0)), -int256(uint256(amount1)), 0, 0);
}
emit Collect(msg.sender, recipient, bottomTick, topTick, amount0, amount1);
}
_unlock();
}
/// @inheritdoc IAlgebraPoolActions
function swap(
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external override returns (int256 amount0, int256 amount1) {
_beforeSwap(recipient, zeroToOne, amountRequired, limitSqrtPrice, false, data);
_lock();
{
// scope to prevent "stack too deep"
(uint256 balance0Before, uint256 balance1Before) = _updateReserves();
uint160 currentPrice;
int24 currentTick;
uint128 currentLiquidity;
uint256 communityFee;
(amount0, amount1, currentPrice, currentTick, currentLiquidity, communityFee) = _calculateSwap(zeroToOne, amountRequired, limitSqrtPrice);
if (zeroToOne) {
unchecked {
if (amount1 < 0) _transfer(token1, recipient, uint256(-amount1)); // amount1 cannot be > 0
}
_swapCallback(amount0, amount1, data); // callback to get tokens from the msg.sender
if (balance0Before + uint256(amount0) > _balanceToken0()) revert insufficientInputAmount();
_changeReserves(amount0, amount1, communityFee, 0); // reflect reserve change and pay communityFee
} else {
unchecked {
if (amount0 < 0) _transfer(token0, recipient, uint256(-amount0)); // amount0 cannot be > 0
}
_swapCallback(amount0, amount1, data); // callback to get tokens from the msg.sender
if (balance1Before + uint256(amount1) > _balanceToken1()) revert insufficientInputAmount();
_changeReserves(amount0, amount1, 0, communityFee); // reflect reserve change and pay communityFee
}
emit Swap(msg.sender, recipient, amount0, amount1, currentPrice, currentLiquidity, currentTick);
}
_unlock();
_afterSwap(recipient, zeroToOne, amountRequired, limitSqrtPrice, amount0, amount1, data);
}
/// @inheritdoc IAlgebraPoolActions
function swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
bytes calldata data
) external override returns (int256 amount0, int256 amount1) {
if (amountToSell < 0) revert invalidAmountRequired(); // we support only exactInput here
_lock();
// firstly we are getting tokens from the original caller of the transaction
// since the pool can get less/more tokens then expected, _amountToSell_ can be changed
{
// scope to prevent "stack too deep"
int256 amountReceived;
if (zeroToOne) {
uint256 balanceBefore = _balanceToken0();
_swapCallback(amountToSell, 0, data); // callback to get tokens from the msg.sender
uint256 balanceAfter = _balanceToken0();
amountReceived = (balanceAfter - balanceBefore).toInt256();
_changeReserves(amountReceived, 0, 0, 0);
} else {
uint256 balanceBefore = _balanceToken1();
_swapCallback(0, amountToSell, data); // callback to get tokens from the msg.sender
uint256 balanceAfter = _balanceToken1();
amountReceived = (balanceAfter - balanceBefore).toInt256();
_changeReserves(0, amountReceived, 0, 0);
}
if (amountReceived != amountToSell) amountToSell = amountReceived;
}
if (amountToSell == 0) revert insufficientInputAmount();
_unlock();
_beforeSwap(recipient, zeroToOne, amountToSell, limitSqrtPrice, true, data);
_lock();
_updateReserves();
uint160 currentPrice;
int24 currentTick;
uint128 currentLiquidity;
uint256 communityFee;
(amount0, amount1, currentPrice, currentTick, currentLiquidity, communityFee) = _calculateSwap(zeroToOne, amountToSell, limitSqrtPrice);
unchecked {
// transfer to the recipient
if (zeroToOne) {
if (amount1 < 0) _transfer(token1, recipient, uint256(-amount1)); // amount1 cannot be > 0
uint256 leftover = uint256(amountToSell - amount0); // return the leftovers
if (leftover != 0) _transfer(token0, leftoversRecipient, leftover);
_changeReserves(-leftover.toInt256(), amount1, communityFee, 0); // reflect reserve change and pay communityFee
} else {
if (amount0 < 0) _transfer(token0, recipient, uint256(-amount0)); // amount0 cannot be > 0
uint256 leftover = uint256(amountToSell - amount1); // return the leftovers
if (leftover != 0) _transfer(token1, leftoversRecipient, leftover);
_changeReserves(amount0, -leftover.toInt256(), 0, communityFee); // reflect reserve change and pay communityFee
}
}
emit Swap(msg.sender, recipient, amount0, amount1, currentPrice, currentLiquidity, currentTick);
_unlock();
_afterSwap(recipient, zeroToOne, amountToSell, limitSqrtPrice, amount0, amount1, data);
}
function _beforeSwap(address recipient, bool zto, int256 amount, uint160 limitPrice, bool payInAdvance, bytes calldata data) internal {
if (globalState.pluginConfig.hasFlag(Plugins.BEFORE_SWAP_FLAG)) {
IAlgebraPlugin(plugin).beforeSwap(msg.sender, recipient, zto, amount, limitPrice, payInAdvance, data).shouldReturn(
IAlgebraPlugin.beforeSwap.selector
);
}
}
function _afterSwap(address recipient, bool zto, int256 amount, uint160 limitPrice, int256 amount0, int256 amount1, bytes calldata data) internal {
if (globalState.pluginConfig.hasFlag(Plugins.AFTER_SWAP_FLAG)) {
IAlgebraPlugin(plugin).afterSwap(msg.sender, recipient, zto, amount, limitPrice, amount0, amount1, data).shouldReturn(
IAlgebraPlugin.afterSwap.selector
);
}
}
/// @inheritdoc IAlgebraPoolActions
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external override {
if (globalState.pluginConfig.hasFlag(Plugins.BEFORE_FLASH_FLAG)) {
IAlgebraPlugin(plugin).beforeFlash(msg.sender, recipient, amount0, amount1, data).shouldReturn(IAlgebraPlugin.beforeFlash.selector);
}
_lock();
uint256 paid0;
uint256 paid1;
{
(uint256 balance0Before, uint256 balance1Before) = _updateReserves();
uint256 fee0;
if (amount0 > 0) {
fee0 = FullMath.mulDivRoundingUp(amount0, Constants.FLASH_FEE, Constants.FEE_DENOMINATOR);
_transfer(token0, recipient, amount0);
}
uint256 fee1;
if (amount1 > 0) {
fee1 = FullMath.mulDivRoundingUp(amount1, Constants.FLASH_FEE, Constants.FEE_DENOMINATOR);
_transfer(token1, recipient, amount1);
}
_flashCallback(fee0, fee1, data); // IAlgebraFlashCallback.algebraFlashCallback to msg.sender
paid0 = _balanceToken0();
if (balance0Before + fee0 > paid0) revert flashInsufficientPaid0();
paid1 = _balanceToken1();
if (balance1Before + fee1 > paid1) revert flashInsufficientPaid1();
unchecked {
paid0 -= balance0Before;
paid1 -= balance1Before;
}
uint256 _communityFee = globalState.communityFee;
if (_communityFee > 0) {
uint256 communityFee0;
if (paid0 > 0) communityFee0 = FullMath.mulDiv(paid0, _communityFee, Constants.COMMUNITY_FEE_DENOMINATOR);
uint256 communityFee1;
if (paid1 > 0) communityFee1 = FullMath.mulDiv(paid1, _communityFee, Constants.COMMUNITY_FEE_DENOMINATOR);
_changeReserves(int256(communityFee0), int256(communityFee1), communityFee0, communityFee1);
}
emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);
}
_unlock();
if (globalState.pluginConfig.hasFlag(Plugins.AFTER_FLASH_FLAG)) {
IAlgebraPlugin(plugin).afterFlash(msg.sender, recipient, amount0, amount1, paid0, paid1, data).shouldReturn(IAlgebraPlugin.afterFlash.selector);
}
}
/// @dev using function to save bytecode
function _checkIfAdministrator() private view {
if (!IAlgebraFactory(factory).hasRoleOrOwner(Constants.POOLS_ADMINISTRATOR_ROLE, msg.sender)) revert notAllowed();
}
// permissioned actions use reentrancy lock to prevent call from callback (to keep the correct order of events, etc.)
/// @inheritdoc IAlgebraPoolPermissionedActions
function setCommunityFee(uint16 newCommunityFee) external override onlyUnlocked {
_checkIfAdministrator();
if (
newCommunityFee > Constants.MAX_COMMUNITY_FEE ||
newCommunityFee == globalState.communityFee ||
(newCommunityFee != 0 && communityVault == address(0))
) revert invalidNewCommunityFee();
_setCommunityFee(newCommunityFee);
}
/// @inheritdoc IAlgebraPoolPermissionedActions
function setTickSpacing(int24 newTickSpacing) external override onlyUnlocked {
_checkIfAdministrator();
if (newTickSpacing <= 0 || newTickSpacing > Constants.MAX_TICK_SPACING || tickSpacing == newTickSpacing) revert invalidNewTickSpacing();
_setTickSpacing(newTickSpacing);
}
/// @inheritdoc IAlgebraPoolPermissionedActions
function setPlugin(address newPluginAddress) external override onlyUnlocked {
_checkIfAdministrator();
_setPluginConfig(0);
_setPlugin(newPluginAddress);
}
/// @inheritdoc IAlgebraPoolPermissionedActions
function setPluginConfig(uint8 newConfig) external override onlyUnlocked {
address _plugin = plugin;
if (_plugin == address(0)) revert pluginIsNotConnected(); // it is not allowed to set plugin config without plugin
if (msg.sender != _plugin) _checkIfAdministrator();
_setPluginConfig(newConfig);
}
/// @inheritdoc IAlgebraPoolPermissionedActions
function setCommunityVault(address newCommunityVault) external override onlyUnlocked {
_checkIfAdministrator();
if (newCommunityVault == address(0) && globalState.communityFee != 0) _setCommunityFee(0); // the pool should not accumulate a community fee without a vault
_setCommunityFeeVault(newCommunityVault); // accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address
}
/// @inheritdoc IAlgebraPoolPermissionedActions
function setFee(uint16 newFee) external override {
bool isDynamicFeeEnabled = globalState.pluginConfig.hasFlag(Plugins.DYNAMIC_FEE);
if (!globalState.unlocked) revert IAlgebraPoolErrors.locked(); // cheaper to check lock here
if (msg.sender == plugin) {
if (!isDynamicFeeEnabled) revert dynamicFeeDisabled();
} else {
if (isDynamicFeeEnabled) revert dynamicFeeActive();
_checkIfAdministrator();
}
_setFee(newFee);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../interfaces/callback/IAlgebraSwapCallback.sol';
import '../interfaces/callback/IAlgebraMintCallback.sol';
import '../interfaces/callback/IAlgebraFlashCallback.sol';
import '../interfaces/plugin/IAlgebraDynamicFeePlugin.sol';
import '../interfaces/IAlgebraPool.sol';
import '../interfaces/IAlgebraFactory.sol';
import '../interfaces/IAlgebraPoolDeployer.sol';
import '../interfaces/IERC20Minimal.sol';
import '../libraries/TickManagement.sol';
import '../libraries/SafeTransfer.sol';
import '../libraries/Constants.sol';
import '../libraries/Plugins.sol';
import './common/Timestamp.sol';
/// @title Algebra pool base abstract contract
/// @notice Contains state variables, immutables and common internal functions
/// @dev Decoupling into a separate abstract contract simplifies testing
abstract contract AlgebraPoolBase is IAlgebraPool, Timestamp {
using TickManagement for mapping(int24 => TickManagement.Tick);
/// @notice The struct with important state values of pool
/// @dev fits into one storage slot
/// @param price The square root of the current price in Q64.96 format
/// @param tick The current tick (price(tick) <= current price). May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @param lastFee The current (last known) fee in hundredths of a bip, i.e. 1e-6 (so 100 is 0.01%). May be obsolete if using dynamic fee plugin
/// @param pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @param communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @param unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
struct GlobalState {
uint160 price;
int24 tick;
uint16 lastFee;
uint8 pluginConfig;
uint16 communityFee;
bool unlocked;
}
/// @inheritdoc IAlgebraPoolImmutables
uint128 public constant override maxLiquidityPerTick = Constants.MAX_LIQUIDITY_PER_TICK;
/// @inheritdoc IAlgebraPoolImmutables
address public immutable override factory;
/// @inheritdoc IAlgebraPoolImmutables
address public immutable override token0;
/// @inheritdoc IAlgebraPoolImmutables
address public immutable override token1;
// ! IMPORTANT security note: the pool state can be manipulated
// ! external contracts using this data must prevent read-only reentrancy
/// @inheritdoc IAlgebraPoolState
uint256 public override totalFeeGrowth0Token;
/// @inheritdoc IAlgebraPoolState
uint256 public override totalFeeGrowth1Token;
/// @inheritdoc IAlgebraPoolState
GlobalState public override globalState;
/// @inheritdoc IAlgebraPoolState
mapping(int24 => TickManagement.Tick) public override ticks;
/// @inheritdoc IAlgebraPoolState
uint32 public override communityFeeLastTimestamp;
/// @dev The amounts of token0 and token1 that will be sent to the vault
uint104 internal communityFeePending0;
uint104 internal communityFeePending1;
/// @inheritdoc IAlgebraPoolState
address public override plugin;
/// @inheritdoc IAlgebraPoolState
address public override communityVault;
/// @inheritdoc IAlgebraPoolState
mapping(int16 => uint256) public override tickTable;
/// @inheritdoc IAlgebraPoolState
int24 public override nextTickGlobal;
/// @inheritdoc IAlgebraPoolState
int24 public override prevTickGlobal;
/// @inheritdoc IAlgebraPoolState
uint128 public override liquidity;
/// @inheritdoc IAlgebraPoolState
int24 public override tickSpacing;
// shares one slot with TickStructure.tickTreeRoot
/// @notice Check that the lower and upper ticks do not violate the boundaries of allowed ticks and are specified in the correct order
modifier onlyValidTicks(int24 bottomTick, int24 topTick) {
TickManagement.checkTickRangeValidity(bottomTick, topTick);
_;
}
constructor() {
address _plugin;
(_plugin, factory, token0, token1) = _getDeployParameters();
(prevTickGlobal, nextTickGlobal) = (TickMath.MIN_TICK, TickMath.MAX_TICK);
globalState.unlocked = true;
if (_plugin != address(0)) {
_setPlugin(_plugin);
}
}
/// @inheritdoc IAlgebraPoolState
/// @dev safe from read-only reentrancy getter function
function safelyGetStateOfAMM()
external
view
override
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick)
{
sqrtPrice = globalState.price;
tick = globalState.tick;
lastFee = globalState.lastFee;
pluginConfig = globalState.pluginConfig;
bool unlocked = globalState.unlocked;
if (!unlocked) revert IAlgebraPoolErrors.locked();
activeLiquidity = liquidity;
nextTick = nextTickGlobal;
previousTick = prevTickGlobal;
}
/// @inheritdoc IAlgebraPoolState
function isUnlocked() external view override returns (bool unlocked) {
return globalState.unlocked;
}
/// @inheritdoc IAlgebraPoolState
function getCommunityFeePending() external view override returns (uint128, uint128) {
return (communityFeePending0, communityFeePending1);
}
/// @inheritdoc IAlgebraPoolState
function fee() external view override returns (uint16 currentFee) {
currentFee = globalState.lastFee;
uint8 pluginConfig = globalState.pluginConfig;
if (Plugins.hasFlag(pluginConfig, Plugins.DYNAMIC_FEE)) return IAlgebraDynamicFeePlugin(plugin).getCurrentFee();
}
/// @dev Gets the parameter values for creating the pool. They are not passed in the constructor to make it easier to use create2 opcode
/// Can be overridden in tests
function _getDeployParameters() internal virtual returns (address, address, address, address) {
return IAlgebraPoolDeployer(msg.sender).getDeployParameters();
}
/// @dev Gets the default settings for pool initialization. Can be overridden in tests
function _getDefaultConfiguration() internal virtual returns (uint16, int24, uint16, address) {
return IAlgebraFactory(factory).defaultConfigurationForPool(address(this));
}
// The main external calls that are used by the pool. Can be overridden in tests
function _balanceToken0() internal view virtual returns (uint256) {
return IERC20Minimal(token0).balanceOf(address(this));
}
function _balanceToken1() internal view virtual returns (uint256) {
return IERC20Minimal(token1).balanceOf(address(this));
}
function _transfer(address token, address to, uint256 amount) internal virtual {
SafeTransfer.safeTransfer(token, to, amount);
}
// These 'callback' functions are wrappers over the callbacks that the pool calls on the msg.sender
// These methods can be overridden in tests
/// @dev Using function to save bytecode
function _swapCallback(int256 amount0, int256 amount1, bytes calldata data) internal virtual {
IAlgebraSwapCallback(msg.sender).algebraSwapCallback(amount0, amount1, data);
}
function _mintCallback(uint256 amount0, uint256 amount1, bytes calldata data) internal virtual {
IAlgebraMintCallback(msg.sender).algebraMintCallback(amount0, amount1, data);
}
function _flashCallback(uint256 fee0, uint256 fee1, bytes calldata data) internal virtual {
IAlgebraFlashCallback(msg.sender).algebraFlashCallback(fee0, fee1, data);
}
// This virtual function is implemented in TickStructure and used in Positions
/// @dev Add or remove a pair of ticks to the corresponding data structure
function _addOrRemoveTicks(int24 bottomTick, int24 topTick, bool toggleBottom, bool toggleTop, int24 currentTick, bool remove) internal virtual;
function _setCommunityFee(uint16 _communityFee) internal {
globalState.communityFee = _communityFee;
emit CommunityFee(_communityFee);
}
function _setCommunityFeeVault(address _communityFeeVault) internal {
communityVault = _communityFeeVault;
emit CommunityVault(_communityFeeVault);
}
function _setFee(uint16 _fee) internal {
globalState.lastFee = _fee;
emit Fee(_fee);
}
function _setTickSpacing(int24 _tickSpacing) internal {
tickSpacing = _tickSpacing;
emit TickSpacing(_tickSpacing);
}
function _setPlugin(address _plugin) internal {
plugin = _plugin;
emit Plugin(_plugin);
}
function _setPluginConfig(uint8 _pluginConfig) internal {
globalState.pluginConfig = _pluginConfig;
emit PluginConfig(_pluginConfig);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
/// @title Abstract contract with modified blockTimestamp functionality
/// @notice Allows the pool and other contracts to get a timestamp truncated to 32 bits
/// @dev Can be overridden in tests to make testing easier
abstract contract Timestamp {
/// @dev This function is created for testing by overriding it.
/// @return A timestamp converted to uint32
function _blockTimestamp() internal view virtual returns (uint32) {
return uint32(block.timestamp); // truncation is desired
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/LiquidityMath.sol';
import '../libraries/TickManagement.sol';
import './AlgebraPoolBase.sol';
/// @title Algebra positions abstract contract
/// @notice Contains the logic of recalculation and change of liquidity positions
/// @dev Relies on method _addOrRemoveTicks, which is implemented in TickStructure
abstract contract Positions is AlgebraPoolBase {
using TickManagement for mapping(int24 => TickManagement.Tick);
struct Position {
uint256 liquidity; // The amount of liquidity concentrated in the range
uint256 innerFeeGrowth0Token; // The last updated fee growth per unit of liquidity
uint256 innerFeeGrowth1Token;
uint128 fees0; // The amount of token0 owed to a LP
uint128 fees1; // The amount of token1 owed to a LP
}
/// @inheritdoc IAlgebraPoolState
mapping(bytes32 => Position) public override positions;
/// @notice This function fetches certain position object
/// @param owner The address owing the position
/// @param bottomTick The position's bottom tick
/// @param topTick The position's top tick
/// @return position The Position object
function getOrCreatePosition(address owner, int24 bottomTick, int24 topTick) internal view returns (Position storage) {
bytes32 key;
assembly {
key := or(shl(24, or(shl(24, owner), and(bottomTick, 0xFFFFFF))), and(topTick, 0xFFFFFF))
}
return positions[key];
}
/// @dev Updates position's ticks and its fees
/// @return amount0 The abs amount of token0 that corresponds to liquidityDelta
/// @return amount1 The abs amount of token1 that corresponds to liquidityDelta
function _updatePositionTicksAndFees(
Position storage position,
int24 bottomTick,
int24 topTick,
int128 liquidityDelta
) internal returns (uint256 amount0, uint256 amount1) {
(uint160 currentPrice, int24 currentTick) = (globalState.price, globalState.tick);
bool toggledBottom;
bool toggledTop;
{
// scope to prevent "stack too deep"
(uint256 _totalFeeGrowth0, uint256 _totalFeeGrowth1) = (totalFeeGrowth0Token, totalFeeGrowth1Token);
if (liquidityDelta != 0) {
toggledBottom = ticks.update(bottomTick, currentTick, liquidityDelta, _totalFeeGrowth0, _totalFeeGrowth1, false); // isTopTick: false
toggledTop = ticks.update(topTick, currentTick, liquidityDelta, _totalFeeGrowth0, _totalFeeGrowth1, true); // isTopTick: true
}
(uint256 feeGrowth0, uint256 feeGrowth1) = ticks.getInnerFeeGrowth(bottomTick, topTick, currentTick, _totalFeeGrowth0, _totalFeeGrowth1);
_recalculatePosition(position, liquidityDelta, feeGrowth0, feeGrowth1);
}
if (liquidityDelta != 0) {
// if liquidityDelta is negative and the tick was toggled, it means that it should not be initialized anymore, so we delete it
if (toggledBottom || toggledTop) {
_addOrRemoveTicks(bottomTick, topTick, toggledBottom, toggledTop, currentTick, liquidityDelta < 0);
}
int128 globalLiquidityDelta;
(amount0, amount1, globalLiquidityDelta) = LiquidityMath.getAmountsForLiquidity(bottomTick, topTick, liquidityDelta, currentTick, currentPrice);
if (globalLiquidityDelta != 0) liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta); // update global liquidity
}
}
/// @notice Increases amounts of tokens owed to owner of the position
/// @param position The position object to operate with
/// @param liquidityDelta The amount on which to increase\decrease the liquidity
/// @param innerFeeGrowth0Token Total fee token0 fee growth per liquidity between position's lower and upper ticks
/// @param innerFeeGrowth1Token Total fee token1 fee growth per liquidity between position's lower and upper ticks
function _recalculatePosition(
Position storage position,
int128 liquidityDelta,
uint256 innerFeeGrowth0Token,
uint256 innerFeeGrowth1Token
) internal {
uint128 liquidityBefore = uint128(position.liquidity);
if (liquidityDelta == 0) {
if (liquidityBefore == 0) return; // Do not recalculate the empty ranges
} else {
// change position liquidity
position.liquidity = LiquidityMath.addDelta(liquidityBefore, liquidityDelta);
}
unchecked {
// update the position
(uint256 lastInnerFeeGrowth0Token, uint256 lastInnerFeeGrowth1Token) = (position.innerFeeGrowth0Token, position.innerFeeGrowth1Token);
uint128 fees0;
if (lastInnerFeeGrowth0Token != innerFeeGrowth0Token) {
position.innerFeeGrowth0Token = innerFeeGrowth0Token;
fees0 = uint128(FullMath.mulDiv(innerFeeGrowth0Token - lastInnerFeeGrowth0Token, liquidityBefore, Constants.Q128));
}
uint128 fees1;
if (lastInnerFeeGrowth1Token != innerFeeGrowth1Token) {
position.innerFeeGrowth1Token = innerFeeGrowth1Token;
fees1 = uint128(FullMath.mulDiv(innerFeeGrowth1Token - lastInnerFeeGrowth1Token, liquidityBefore, Constants.Q128));
}
// To avoid overflow owner has to collect fee before it
if (fees0 | fees1 != 0) {
position.fees0 += fees0;
position.fees1 += fees1;
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './AlgebraPoolBase.sol';
/// @title Algebra reentrancy protection
/// @notice Provides a modifier that protects against reentrancy
abstract contract ReentrancyGuard is AlgebraPoolBase {
/// @notice checks that reentrancy lock is unlocked
modifier onlyUnlocked() {
_checkUnlocked();
_;
}
/// @dev using private function to save bytecode
function _checkUnlocked() internal view {
if (!globalState.unlocked) revert IAlgebraPoolErrors.locked();
}
/// @dev using private function to save bytecode
function _lock() internal {
if (!globalState.unlocked) revert IAlgebraPoolErrors.locked();
globalState.unlocked = false;
}
/// @dev using private function to save bytecode
function _unlock() internal {
globalState.unlocked = true;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/SafeCast.sol';
import './AlgebraPoolBase.sol';
/// @title Algebra reserves management abstract contract
/// @notice Encapsulates logic for tracking and changing pool reserves
/// @dev The reserve mechanism allows the pool to keep track of unexpected increases in balances
abstract contract ReservesManager is AlgebraPoolBase {
using SafeCast for uint256;
/// @dev The tracked token0 and token1 reserves of pool
uint128 internal reserve0;
uint128 internal reserve1;
/// @inheritdoc IAlgebraPoolState
function getReserves() external view returns (uint128, uint128) {
return (reserve0, reserve1);
}
/// @dev updates reserves data and distributes excess in the form of fee to liquidity providers.
/// If any of the balances is greater than uint128, the excess is sent to the communityVault
function _updateReserves() internal returns (uint256 balance0, uint256 balance1) {
(balance0, balance1) = (_balanceToken0(), _balanceToken1());
// we do not support tokens with totalSupply > type(uint128).max, so any excess will be sent to communityVault
// this situation can only occur if the tokens are sent directly to the pool from outside
// **such excessive tokens will be burned if there is no communityVault connected**
if (balance0 > type(uint128).max || balance1 > type(uint128).max) {
unchecked {
address _communityVault = communityVault;
if (balance0 > type(uint128).max) {
_transfer(token0, _communityVault, balance0 - type(uint128).max);
balance0 = type(uint128).max;
}
if (balance1 > type(uint128).max) {
_transfer(token1, _communityVault, balance1 - type(uint128).max);
balance1 = type(uint128).max;
}
}
}
uint128 _liquidity = liquidity;
if (_liquidity == 0) return (balance0, balance1);
(uint128 _reserve0, uint128 _reserve1) = (reserve0, reserve1);
(bool hasExcessToken0, bool hasExcessToken1) = (balance0 > _reserve0, balance1 > _reserve1);
if (hasExcessToken0 || hasExcessToken1) {
unchecked {
if (hasExcessToken0) totalFeeGrowth0Token += FullMath.mulDiv(balance0 - _reserve0, Constants.Q128, _liquidity);
if (hasExcessToken1) totalFeeGrowth1Token += FullMath.mulDiv(balance1 - _reserve1, Constants.Q128, _liquidity);
(reserve0, reserve1) = (uint128(balance0), uint128(balance1));
}
}
}
/// @notice Applies deltas to reserves and pays communityFees
/// @dev Community fee is sent to the vault at a specified frequency or when variables communityFeePending{0,1} overflow
/// @param deltaR0 Amount of token0 to add/subtract to/from reserve0, must not exceed uint128
/// @param deltaR1 Amount of token1 to add/subtract to/from reserve1, must not exceed uint128
/// @param communityFee0 Amount of token0 to pay as communityFee, must not exceed uint128
/// @param communityFee1 Amount of token1 to pay as communityFee, must not exceed uint128
function _changeReserves(int256 deltaR0, int256 deltaR1, uint256 communityFee0, uint256 communityFee1) internal {
if (communityFee0 | communityFee1 != 0) {
unchecked {
// overflow is desired since we do not support tokens with totalSupply > type(uint128).max
uint256 _cfPending0 = uint256(communityFeePending0) + communityFee0;
uint256 _cfPending1 = uint256(communityFeePending1) + communityFee1;
uint32 currentTimestamp = _blockTimestamp();
// underflow in timestamps is desired
if (
currentTimestamp - communityFeeLastTimestamp >= Constants.COMMUNITY_FEE_TRANSFER_FREQUENCY ||
_cfPending0 > type(uint104).max ||
_cfPending1 > type(uint104).max
) {
address _communityVault = communityVault;
if (_cfPending0 > 0) _transfer(token0, _communityVault, _cfPending0);
if (_cfPending1 > 0) _transfer(token1, _communityVault, _cfPending1);
communityFeeLastTimestamp = currentTimestamp;
(deltaR0, deltaR1) = (deltaR0 - _cfPending0.toInt256(), deltaR1 - _cfPending1.toInt256());
(_cfPending0, _cfPending1) = (0, 0);
}
// the previous block guarantees that no overflow occurs
(communityFeePending0, communityFeePending1) = (uint104(_cfPending0), uint104(_cfPending1));
}
}
if (deltaR0 | deltaR1 == 0) return;
(uint256 _reserve0, uint256 _reserve1) = (reserve0, reserve1);
if (deltaR0 != 0) _reserve0 = (uint256(int256(_reserve0) + deltaR0)).toUint128();
if (deltaR1 != 0) _reserve1 = (uint256(int256(_reserve1) + deltaR1)).toUint128();
(reserve0, reserve1) = (uint128(_reserve0), uint128(_reserve1));
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/PriceMovementMath.sol';
import '../libraries/LowGasSafeMath.sol';
import '../libraries/SafeCast.sol';
import './AlgebraPoolBase.sol';
/// @title Algebra swap calculation abstract contract
/// @notice Contains _calculateSwap encapsulating internal logic of swaps
abstract contract SwapCalculation is AlgebraPoolBase {
using TickManagement for mapping(int24 => TickManagement.Tick);
using SafeCast for uint256;
using LowGasSafeMath for uint256;
using LowGasSafeMath for int256;
struct SwapCalculationCache {
uint256 communityFee; // The community fee of the selling token, uint256 to minimize casts
bool crossedAnyTick; // If we have already crossed at least one active tick
int256 amountRequiredInitial; // The initial value of the exact input\output amount
int256 amountCalculated; // The additive amount of total output\input calculated through the swap
uint256 totalFeeGrowthInput; // The initial totalFeeGrowth + the fee growth during a swap
uint256 totalFeeGrowthOutput; // The initial totalFeeGrowth for output token, should not change during swap
bool exactInput; // Whether the exact input or output is specified
uint16 fee; // The current fee value in hundredths of a bip, i.e. 1e-6
int24 prevInitializedTick; // The previous initialized tick in linked list
int24 nextInitializedTick; // The next initialized tick in linked list
}
struct PriceMovementCache {
uint256 stepSqrtPrice; // The Q64.96 sqrt of the price at the start of the step, uint256 to minimize casts
uint256 nextTickPrice; // The Q64.96 sqrt of the price calculated from the _nextTick_, uint256 to minimize casts
uint256 input; // The additive amount of tokens that have been provided
uint256 output; // The additive amount of token that have been withdrawn
uint256 feeAmount; // The total amount of fee earned within a current step
}
function _calculateSwap(
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice
) internal returns (int256 amount0, int256 amount1, uint160 currentPrice, int24 currentTick, uint128 currentLiquidity, uint256 communityFeeAmount) {
if (amountRequired == 0) revert zeroAmountRequired();
if (amountRequired == type(int256).min) revert invalidAmountRequired(); // to avoid problems when changing sign
SwapCalculationCache memory cache;
(cache.amountRequiredInitial, cache.exactInput) = (amountRequired, amountRequired > 0);
// load from one storage slot
(currentLiquidity, cache.prevInitializedTick, cache.nextInitializedTick) = (liquidity, prevTickGlobal, nextTickGlobal);
// load from one storage slot too
(currentPrice, currentTick, cache.fee, cache.communityFee) = (globalState.price, globalState.tick, globalState.lastFee, globalState.communityFee);
if (currentPrice == 0) revert notInitialized();
if (zeroToOne) {
if (limitSqrtPrice >= currentPrice || limitSqrtPrice <= TickMath.MIN_SQRT_RATIO) revert invalidLimitSqrtPrice();
cache.totalFeeGrowthInput = totalFeeGrowth0Token;
} else {
if (limitSqrtPrice <= currentPrice || limitSqrtPrice >= TickMath.MAX_SQRT_RATIO) revert invalidLimitSqrtPrice();
cache.totalFeeGrowthInput = totalFeeGrowth1Token;
}
PriceMovementCache memory step;
unchecked {
// swap until there is remaining input or output tokens or we reach the price limit
do {
int24 nextTick = zeroToOne ? cache.prevInitializedTick : cache.nextInitializedTick;
step.stepSqrtPrice = currentPrice;
step.nextTickPrice = TickMath.getSqrtRatioAtTick(nextTick);
(currentPrice, step.input, step.output, step.feeAmount) = PriceMovementMath.movePriceTowardsTarget(
zeroToOne, // if zeroToOne then the price is moving down
currentPrice,
(zeroToOne == (step.nextTickPrice < limitSqrtPrice)) // move the price to the nearest of the next tick and the limit price
? limitSqrtPrice
: uint160(step.nextTickPrice), // cast is safe
currentLiquidity,
amountRequired,
cache.fee
);
if (cache.exactInput) {
amountRequired -= (step.input + step.feeAmount).toInt256(); // decrease remaining input amount
cache.amountCalculated = cache.amountCalculated.sub(step.output.toInt256()); // decrease calculated output amount
} else {
amountRequired += step.output.toInt256(); // increase remaining output amount (since its negative)
cache.amountCalculated = cache.amountCalculated.add((step.input + step.feeAmount).toInt256()); // increase calculated input amount
}
if (cache.communityFee > 0) {
uint256 delta = (step.feeAmount.mul(cache.communityFee)) / Constants.COMMUNITY_FEE_DENOMINATOR;
step.feeAmount -= delta;
communityFeeAmount += delta;
}
if (currentLiquidity > 0) cache.totalFeeGrowthInput += FullMath.mulDiv(step.feeAmount, Constants.Q128, currentLiquidity);
// min or max tick can not be crossed due to limitSqrtPrice check
if (currentPrice == step.nextTickPrice) {
// crossing tick
if (!cache.crossedAnyTick) {
cache.crossedAnyTick = true;
cache.totalFeeGrowthOutput = zeroToOne ? totalFeeGrowth1Token : totalFeeGrowth0Token;
}
int128 liquidityDelta;
if (zeroToOne) {
(liquidityDelta, cache.prevInitializedTick, ) = ticks.cross(nextTick, cache.totalFeeGrowthInput, cache.totalFeeGrowthOutput);
liquidityDelta = -liquidityDelta;
(currentTick, cache.nextInitializedTick) = (nextTick - 1, nextTick);
} else {
(liquidityDelta, , cache.nextInitializedTick) = ticks.cross(nextTick, cache.totalFeeGrowthOutput, cache.totalFeeGrowthInput);
(currentTick, cache.prevInitializedTick) = (nextTick, nextTick);
}
currentLiquidity = LiquidityMath.addDelta(currentLiquidity, liquidityDelta);
} else if (currentPrice != step.stepSqrtPrice) {
currentTick = TickMath.getTickAtSqrtRatio(currentPrice); // the price has changed but hasn't reached the target
break; // since the price hasn't reached the target, amountRequired should be 0
}
} while (amountRequired != 0 && currentPrice != limitSqrtPrice); // check stop condition
int256 amountSpent = cache.amountRequiredInitial - amountRequired; // spent amount could be less than initially specified (e.g. reached limit)
(amount0, amount1) = zeroToOne == cache.exactInput ? (amountSpent, cache.amountCalculated) : (cache.amountCalculated, amountSpent);
}
(globalState.price, globalState.tick) = (currentPrice, currentTick);
if (cache.crossedAnyTick) {
(liquidity, prevTickGlobal, nextTickGlobal) = (currentLiquidity, cache.prevInitializedTick, cache.nextInitializedTick);
}
if (zeroToOne) {
totalFeeGrowth0Token = cache.totalFeeGrowthInput;
} else {
totalFeeGrowth1Token = cache.totalFeeGrowthInput;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/TickManagement.sol';
import '../libraries/TickTree.sol';
import './AlgebraPoolBase.sol';
/// @title Algebra tick structure abstract contract
/// @notice Encapsulates the logic of interaction with the data structure with ticks
/// @dev Ticks are stored as a doubly linked list. A three-level bitmap tree is used to search through the list
abstract contract TickStructure is AlgebraPoolBase {
using TickManagement for mapping(int24 => TickManagement.Tick);
using TickTree for mapping(int16 => uint256);
/// @inheritdoc IAlgebraPoolState
uint32 public override tickTreeRoot; // The root bitmap of search tree
/// @inheritdoc IAlgebraPoolState
mapping(int16 => uint256) public override tickTreeSecondLayer; // The second layer of search tree
// the leaves of the tree are stored in `tickTable`
constructor() {
ticks.initTickState();
}
/// @notice Used to add or remove a tick from a doubly linked list and search tree
/// @param tick The tick being removed or added now
/// @param currentTick The current global tick in the pool
/// @param oldTickTreeRoot The current tick tree root
/// @param prevInitializedTick Previous active tick before `currentTick`
/// @param nextInitializedTick Next active tick after `currentTick`
/// @param remove Remove or add the tick
/// @return New previous active tick before `currentTick` if changed
/// @return New next active tick after `currentTick` if changed
/// @return New tick tree root if changed
function _addOrRemoveTick(
int24 tick,
int24 currentTick,
uint32 oldTickTreeRoot,
int24 prevInitializedTick,
int24 nextInitializedTick,
bool remove
) internal returns (int24, int24, uint32) {
if (remove) {
(int24 prevTick, int24 nextTick) = ticks.removeTick(tick);
if (prevInitializedTick == tick) prevInitializedTick = prevTick;
else if (nextInitializedTick == tick) nextInitializedTick = nextTick;
} else {
int24 prevTick;
int24 nextTick;
if (prevInitializedTick < tick && nextInitializedTick > tick) {
(prevTick, nextTick) = (prevInitializedTick, nextInitializedTick); // we know next and prev ticks
if (tick > currentTick) nextInitializedTick = tick;
else prevInitializedTick = tick;
} else {
nextTick = tickTable.getNextTick(tickTreeSecondLayer, oldTickTreeRoot, tick);
prevTick = ticks[nextTick].prevTick;
}
ticks.insertTick(tick, prevTick, nextTick);
}
uint32 newTickTreeRoot = tickTable.toggleTick(tickTreeSecondLayer, oldTickTreeRoot, tick);
return (prevInitializedTick, nextInitializedTick, newTickTreeRoot);
}
/// @notice Used to add or remove a pair of ticks from a doubly linked list and search tree
/// @param bottomTick The bottom tick being removed or added now
/// @param topTick The top tick being removed or added now
/// @param toggleBottom Should bottom tick be changed or not
/// @param toggleTop Should top tick be changed or not
/// @param currentTick The current global tick in the pool
/// @param remove Remove or add the ticks
function _addOrRemoveTicks(int24 bottomTick, int24 topTick, bool toggleBottom, bool toggleTop, int24 currentTick, bool remove) internal override {
(int24 prevInitializedTick, int24 nextInitializedTick, uint32 oldTickTreeRoot) = (prevTickGlobal, nextTickGlobal, tickTreeRoot);
(int24 newPrevTick, int24 newNextTick, uint32 newTreeRoot) = (prevInitializedTick, nextInitializedTick, oldTickTreeRoot);
if (toggleBottom) {
(newPrevTick, newNextTick, newTreeRoot) = _addOrRemoveTick(bottomTick, currentTick, newTreeRoot, newPrevTick, newNextTick, remove);
}
if (toggleTop) {
(newPrevTick, newNextTick, newTreeRoot) = _addOrRemoveTick(topTick, currentTick, newTreeRoot, newPrevTick, newNextTick, remove);
}
if (prevInitializedTick != newPrevTick || nextInitializedTick != newNextTick || newTreeRoot != oldTickTreeRoot) {
(prevTickGlobal, nextTickGlobal, tickTreeRoot) = (newPrevTick, newNextTick, newTreeRoot);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IAlgebraPoolActions#flash
/// @notice Any contract that calls IAlgebraPoolActions#flash must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraFlashCallback {
/// @notice Called to `msg.sender` after transferring to the recipient from IAlgebraPool#flash.
/// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
/// The caller of this method _must_ be checked to be a AlgebraPool deployed by the canonical AlgebraFactory.
/// @param fee0 The fee amount in token0 due to the pool by the end of the flash
/// @param fee1 The fee amount in token1 due to the pool by the end of the flash
/// @param data Any data passed through by the caller via the IAlgebraPoolActions#flash call
function algebraFlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IAlgebraPoolActions#mint
/// @notice Any contract that calls IAlgebraPoolActions#mint must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraMintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IAlgebraPool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method _must_ be checked to be a AlgebraPool deployed by the canonical AlgebraFactory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IAlgebraPoolActions#mint call
function algebraMintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata data) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IAlgebraPoolActions#swap
/// @notice Any contract that calls IAlgebraPoolActions#swap must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraSwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IAlgebraPool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method _must_ be checked to be a AlgebraPool deployed by the canonical AlgebraFactory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IAlgebraPoolActions#swap call
function algebraSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import './plugin/IAlgebraPluginFactory.sol';
import './vault/IAlgebraVaultFactory.sol';
/// @title The interface for the Algebra Factory
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraFactory {
/// @notice Emitted when a process of ownership renounce is started
/// @param timestamp The timestamp of event
/// @param finishTimestamp The timestamp when ownership renounce will be possible to finish
event RenounceOwnershipStart(uint256 timestamp, uint256 finishTimestamp);
/// @notice Emitted when a process of ownership renounce cancelled
/// @param timestamp The timestamp of event
event RenounceOwnershipStop(uint256 timestamp);
/// @notice Emitted when a process of ownership renounce finished
/// @param timestamp The timestamp of ownership renouncement
event RenounceOwnershipFinish(uint256 timestamp);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event Pool(address indexed token0, address indexed token1, address pool);
/// @notice Emitted when the default community fee is changed
/// @param newDefaultCommunityFee The new default community fee value
event DefaultCommunityFee(uint16 newDefaultCommunityFee);
/// @notice Emitted when the default tickspacing is changed
/// @param newDefaultTickspacing The new default tickspacing value
event DefaultTickspacing(int24 newDefaultTickspacing);
/// @notice Emitted when the default fee is changed
/// @param newDefaultFee The new default fee value
event DefaultFee(uint16 newDefaultFee);
/// @notice Emitted when the defaultPluginFactory address is changed
/// @param defaultPluginFactoryAddress The new defaultPluginFactory address
event DefaultPluginFactory(address defaultPluginFactoryAddress);
/// @notice Emitted when the vaultFactory address is changed
/// @param newVaultFactory The new vaultFactory address
event VaultFactory(address newVaultFactory);
/// @notice role that can change communityFee and tickspacing in pools
/// @return The hash corresponding to this role
function POOLS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice Returns `true` if `account` has been granted `role` or `account` is owner.
/// @param role The hash corresponding to the role
/// @param account The address for which the role is checked
/// @return bool Whether the address has this role or the owner role or not
function hasRoleOrOwner(bytes32 role, address account) external view returns (bool);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via transferOwnership(address newOwner)
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current poolDeployerAddress
/// @return The address of the poolDeployer
function poolDeployer() external view returns (address);
/// @notice Returns the default community fee
/// @return Fee which will be set at the creation of the pool
function defaultCommunityFee() external view returns (uint16);
/// @notice Returns the default fee
/// @return Fee which will be set at the creation of the pool
function defaultFee() external view returns (uint16);
/// @notice Returns the default tickspacing
/// @return Tickspacing which will be set at the creation of the pool
function defaultTickspacing() external view returns (int24);
/// @notice Return the current pluginFactory address
/// @dev This contract is used to automatically set a plugin address in new liquidity pools
/// @return Algebra plugin factory
function defaultPluginFactory() external view returns (IAlgebraPluginFactory);
/// @notice Return the current vaultFactory address
/// @dev This contract is used to automatically set a vault address in new liquidity pools
/// @return Algebra vault factory
function vaultFactory() external view returns (IAlgebraVaultFactory);
/// @notice Returns the default communityFee, tickspacing, fee and communityFeeVault for pool
/// @param pool the address of liquidity pool
/// @return communityFee which will be set at the creation of the pool
/// @return tickSpacing which will be set at the creation of the pool
/// @return fee which will be set at the creation of the pool
/// @return communityFeeVault the address of communityFeeVault
function defaultConfigurationForPool(
address pool
) external view returns (uint16 communityFee, int24 tickSpacing, uint16 fee, address communityFeeVault);
/// @notice Deterministically computes the pool address given the token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param token0 first token
/// @param token1 second token
/// @return pool The contract address of the Algebra pool
function computePoolAddress(address token0, address token1) external view returns (address pool);
/// @notice Returns the pool address for a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return pool The pool address
function poolByPair(address tokenA, address tokenB) external view returns (address pool);
/// @notice returns keccak256 of AlgebraPool init bytecode.
/// @dev the hash value changes with any change in the pool bytecode
/// @return Keccak256 hash of AlgebraPool contract init bytecode
function POOL_INIT_CODE_HASH() external view returns (bytes32);
/// @return timestamp The timestamp of the beginning of the renounceOwnership process
function renounceOwnershipStartTimestamp() external view returns (uint256 timestamp);
/// @notice Creates a pool for the given two tokens
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB) external returns (address pool);
/// @dev updates default community fee for new pools
/// @param newDefaultCommunityFee The new community fee, _must_ be <= MAX_COMMUNITY_FEE
function setDefaultCommunityFee(uint16 newDefaultCommunityFee) external;
/// @dev updates default fee for new pools
/// @param newDefaultFee The new fee, _must_ be <= MAX_DEFAULT_FEE
function setDefaultFee(uint16 newDefaultFee) external;
/// @dev updates default tickspacing for new pools
/// @param newDefaultTickspacing The new tickspacing, _must_ be <= MAX_TICK_SPACING and >= MIN_TICK_SPACING
function setDefaultTickspacing(int24 newDefaultTickspacing) external;
/// @dev updates pluginFactory address
/// @param newDefaultPluginFactory address of new plugin factory
function setDefaultPluginFactory(address newDefaultPluginFactory) external;
/// @dev updates vaultFactory address
/// @param newVaultFactory address of new vault factory
function setVaultFactory(address newVaultFactory) external;
/// @notice Starts process of renounceOwnership. After that, a certain period
/// of time must pass before the ownership renounce can be completed.
function startRenounceOwnership() external;
/// @notice Stops process of renounceOwnership and removes timer.
function stopRenounceOwnership() external;
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import './pool/IAlgebraPoolImmutables.sol';
import './pool/IAlgebraPoolState.sol';
import './pool/IAlgebraPoolActions.sol';
import './pool/IAlgebraPoolPermissionedActions.sol';
import './pool/IAlgebraPoolEvents.sol';
import './pool/IAlgebraPoolErrors.sol';
/// @title The interface for a Algebra Pool
/// @dev The pool interface is broken up into many smaller pieces.
/// This interface includes custom error definitions and cannot be used in older versions of Solidity.
/// For older versions of Solidity use #IAlgebraPoolLegacy
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPool is
IAlgebraPoolImmutables,
IAlgebraPoolState,
IAlgebraPoolActions,
IAlgebraPoolPermissionedActions,
IAlgebraPoolEvents,
IAlgebraPoolErrors
{
// used only for combining interfaces
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title An interface for a contract that is capable of deploying Algebra Pools
/// @notice A contract that constructs a pool must implement this to pass arguments to the pool
/// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash
/// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain.
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolDeployer {
/// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.
/// @dev Called by the pool constructor to fetch the parameters of the pool
/// @return plugin The pool associated plugin (if any)
/// @return factory The Algebra Factory address
/// @return token0 The first token of the pool by address sort order
/// @return token1 The second token of the pool by address sort order
function getDeployParameters() external view returns (address plugin, address factory, address token0, address token1);
/// @dev Deploys a pool with the given parameters by transiently setting the parameters in cache.
/// @param plugin The pool associated plugin (if any)
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @return pool The deployed pool's address
function deploy(address plugin, address token0, address token1) external returns (address pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Minimal ERC20 interface for Algebra
/// @notice Contains a subset of the full ERC20 interface that is used in Algebra
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IERC20Minimal {
/// @notice Returns the balance of a token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra plugin with dynamic fee logic
/// @dev A plugin with a dynamic fee must implement this interface so that the current fee can be known through the pool
/// If the dynamic fee logic does not allow the fee to be calculated without additional data, the method should revert with the appropriate message
interface IAlgebraDynamicFeePlugin {
/// @notice Returns fee from plugin
/// @return fee The pool fee value in hundredths of a bip, i.e. 1e-6
function getCurrentFee() external view returns (uint16 fee);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The Algebra plugin interface
/// @dev The plugin will be called by the pool using hook methods depending on the current pool settings
interface IAlgebraPlugin {
/// @notice Returns plugin config
/// @return config Each bit of the config is responsible for enabling/disabling the hooks.
/// The last bit indicates whether the plugin contains dynamic fees logic
function defaultPluginConfig() external view returns (uint8);
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, uint160 sqrtPriceX96, int24 tick) external returns (bytes4);
/// @notice The hook called before a position is modified
/// @param sender The initial msg.sender for the modify position call
/// @param recipient Address to which the liquidity will be assigned in case of a mint or
/// to which tokens will be sent in case of a burn
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param desiredLiquidityDelta The desired amount of liquidity to mint/burn
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function beforeModifyPosition(
address sender,
address recipient,
int24 bottomTick,
int24 topTick,
int128 desiredLiquidityDelta,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called after a position is modified
/// @param sender The initial msg.sender for the modify position call
/// @param recipient Address to which the liquidity will be assigned in case of a mint or
/// to which tokens will be sent in case of a burn
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param desiredLiquidityDelta The desired amount of liquidity to mint/burn
/// @param amount0 The amount of token0 sent to the recipient or was paid to mint
/// @param amount1 The amount of token0 sent to the recipient or was paid to mint
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterModifyPosition(
address sender,
address recipient,
int24 bottomTick,
int24 topTick,
int128 desiredLiquidityDelta,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param withPaymentInAdvance The flag indicating whether the `swapWithPaymentInAdvance` method was called
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function beforeSwap(
address sender,
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bool withPaymentInAdvance,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @param amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterSwap(
address sender,
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
int256 amount0,
int256 amount1,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called before flash
/// @param sender The initial msg.sender for the flash call
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 being requested for flash
/// @param amount1 The amount of token1 being requested for flash
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function beforeFlash(address sender, address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external returns (bytes4);
/// @notice The hook called after flash
/// @param sender The initial msg.sender for the flash call
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 being requested for flash
/// @param amount1 The amount of token1 being requested for flash
/// @param paid0 The amount of token0 being paid for flash
/// @param paid1 The amount of token1 being paid for flash
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterFlash(
address sender,
address recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title An interface for a contract that is capable of deploying Algebra plugins
/// @dev Such a factory is needed if the plugin should be automatically created and connected to each new pool
interface IAlgebraPluginFactory {
/// @notice Deploys new plugin contract for pool
/// @param pool The address of the pool for which the new plugin will be created
/// @param token0 First token of the pool
/// @param token1 Second token of the pool
/// @return New plugin address
function createPlugin(address pool, address token0, address token1) external returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @dev Initialization should be done in one transaction with pool creation to avoid front-running
/// @param initialPrice The initial sqrt price of the pool as a Q64.96
function initialize(uint160 initialPrice) external;
/// @notice Adds liquidity for the given recipient/bottomTick/topTick position
/// @dev The caller of this method receives a callback in the form of IAlgebraMintCallback#algebraMintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on bottomTick, topTick, the amount of liquidity, and the current price.
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address for which the liquidity will be created
/// @param bottomTick The lower tick of the position in which to add liquidity
/// @param topTick The upper tick of the position in which to add liquidity
/// @param liquidityDesired The desired amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return liquidityActual The actual minted amount of liquidity
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityActual);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param bottomTick The lower tick of the position for which to collect fees
/// @param topTick The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 bottomTick,
int24 topTick,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param bottomTick The lower tick of the position for which to burn liquidity
/// @param topTick The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @param data Any data that should be passed through to the plugin
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Swap token0 for token1, or token1 for token0 with prepayment
/// @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback#algebraSwapCallback
/// caller must send tokens in callback before swap calculation
/// the actually sent amount of tokens is used for further calculations
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountToSell The amount of the swap, only positive (exact input) amount allowed
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IAlgebraFlashCallback#algebraFlashCallback
/// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee.
/// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
/// @title Errors emitted by a pool
/// @notice Contains custom errors emitted by the pool
/// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity
interface IAlgebraPoolErrors {
// #### pool errors ####
/// @notice Emitted by the reentrancy guard
error locked();
/// @notice Emitted if arithmetic error occurred
error arithmeticError();
/// @notice Emitted if an attempt is made to initialize the pool twice
error alreadyInitialized();
/// @notice Emitted if an attempt is made to mint or swap in uninitialized pool
error notInitialized();
/// @notice Emitted if 0 is passed as amountRequired to swap function
error zeroAmountRequired();
/// @notice Emitted if invalid amount is passed as amountRequired to swap function
error invalidAmountRequired();
/// @notice Emitted if the pool received fewer tokens than it should have
error insufficientInputAmount();
/// @notice Emitted if there was an attempt to mint zero liquidity
error zeroLiquidityDesired();
/// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received)
error zeroLiquidityActual();
/// @notice Emitted if the pool received fewer tokens0 after flash than it should have
error flashInsufficientPaid0();
/// @notice Emitted if the pool received fewer tokens1 after flash than it should have
error flashInsufficientPaid1();
/// @notice Emitted if limitSqrtPrice param is incorrect
error invalidLimitSqrtPrice();
/// @notice Tick must be divisible by tickspacing
error tickIsNotSpaced();
/// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role
error notAllowed();
/// @notice Emitted if new tick spacing exceeds max allowed value
error invalidNewTickSpacing();
/// @notice Emitted if new community fee exceeds max allowed value
error invalidNewCommunityFee();
/// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled
error dynamicFeeActive();
/// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled
error dynamicFeeDisabled();
/// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected
error pluginIsNotConnected();
/// @notice Emitted if a plugin returns invalid selector after hook call
/// @param expectedSelector The expected selector
error invalidHookResponse(bytes4 expectedSelector);
// #### LiquidityMath errors ####
/// @notice Emitted if liquidity underflows
error liquiditySub();
/// @notice Emitted if liquidity overflows
error liquidityAdd();
// #### TickManagement errors ####
/// @notice Emitted if the topTick param not greater then the bottomTick param
error topTickLowerOrEqBottomTick();
/// @notice Emitted if the bottomTick param is lower than min allowed value
error bottomTickLowerThanMIN();
/// @notice Emitted if the topTick param is greater than max allowed value
error topTickAboveMAX();
/// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK
error liquidityOverflow();
/// @notice Emitted if an attempt is made to interact with an uninitialized tick
error tickIsNotInitialized();
/// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks
error tickInvalidLinks();
// #### SafeTransfer errors ####
/// @notice Emitted if token transfer failed internally
error transferFailed();
// #### TickMath errors ####
/// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value
error tickOutOfRange();
/// @notice Emitted if price is greater than the maximum or less than the minimum allowed value
error priceOutOfRange();
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize
/// @param price The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 price, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @param owner The owner of the position for which fees are collected
/// @param recipient The address that received fees
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(address indexed owner, address recipient, int24 indexed bottomTick, int24 indexed topTick, uint128 amount0, uint128 amount1);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(address indexed owner, int24 indexed bottomTick, int24 indexed topTick, uint128 liquidityAmount, uint256 amount0, uint256 amount1);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param price The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 price, uint128 liquidity, int24 tick);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);
/// @notice Emitted when the community fee is changed by the pool
/// @param communityFeeNew The updated value of the community fee in thousandths (1e-3)
event CommunityFee(uint16 communityFeeNew);
/// @notice Emitted when the tick spacing changes
/// @param newTickSpacing The updated value of the new tick spacing
event TickSpacing(int24 newTickSpacing);
/// @notice Emitted when the plugin address changes
/// @param newPluginAddress New plugin address
event Plugin(address newPluginAddress);
/// @notice Emitted when the plugin config changes
/// @param newPluginConfig New plugin config
event PluginConfig(uint8 newPluginConfig);
/// @notice Emitted when the fee changes inside the pool
/// @param fee The current fee in hundredths of a bip, i.e. 1e-6
event Fee(uint16 fee);
event CommunityVault(address newCommunityVault);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolImmutables {
/// @notice The Algebra factory contract, which must adhere to the IAlgebraFactory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by permissioned addresses
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolPermissionedActions {
/// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newCommunityFee The new community fee percent in thousandths (1e-3)
function setCommunityFee(uint16 newCommunityFee) external;
/// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newTickSpacing The new tick spacing value
function setTickSpacing(int24 newTickSpacing) external;
/// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newPluginAddress The new plugin address
function setPlugin(address newPluginAddress) external;
/// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newConfig In the new configuration of the plugin,
/// each bit of which is responsible for a particular hook.
function setPluginConfig(uint8 newConfig) external;
/// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @dev Community fee vault receives collected community fees.
/// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address**
/// @param newCommunityVault The address of new community fee vault
function setCommunityVault(address newCommunityVault) external;
/// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled.
/// Called by the plugin if dynamic fee is enabled
/// @param newFee The new fee value
function setFee(uint16 newFee) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility
/// of manipulation (including read-only reentrancy).
/// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IAlgebraPoolState {
/// @notice Safely get most important state values of Algebra Integral AMM
/// @dev Several values exposed as a single method to save gas when accessed externally.
/// **Important security note: this method checks reentrancy lock and should be preferred in most cases**.
/// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return activeLiquidity The currently in-range liquidity available to the pool
/// @return nextTick The next initialized tick after current global tick
/// @return previousTick The previous initialized tick before (or at) current global tick
function safelyGetStateOfAMM()
external
view
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick);
/// @notice Allows to easily get current reentrancy lock status
/// @dev can be used to prevent read-only reentrancy.
/// This method just returns `globalState.unlocked` value
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function isUnlocked() external view returns (bool unlocked);
// ! IMPORTANT security note: the pool state can be manipulated.
// ! The following methods do not check reentrancy lock themselves.
/// @notice The globalState structure in the pool stores many values but requires only one slot
/// and is exposed as a single method to save gas when accessed externally.
/// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy**
/// @return price The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked);
/// @notice Look up information about a specific tick in the pool
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param tick The tick to look up
/// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper
/// @return liquidityDelta How much liquidity changes when the pool price crosses the tick
/// @return prevTick The previous tick in tick list
/// @return nextTick The next tick in tick list
/// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0
/// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint256 liquidityTotal,
int128 liquidityDelta,
int24 prevTick,
int24 nextTick,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token
);
/// @notice The timestamp of the last sending of tokens to community vault
/// @return The timestamp truncated to 32 bits
function communityFeeLastTimestamp() external view returns (uint32);
/// @notice The amounts of token0 and token1 that will be sent to the vault
/// @dev Will be sent COMMUNITY_FEE_TRANSFER_FREQUENCY after communityFeeLastTimestamp
/// @return communityFeePending0 The amount of token0 that will be sent to the vault
/// @return communityFeePending1 The amount of token1 that will be sent to the vault
function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1);
/// @notice Returns the address of currently used plugin
/// @dev The plugin is subject to change
/// @return pluginAddress The address of currently used plugin
function plugin() external view returns (address pluginAddress);
/// @notice The contract to which community fees are transferred
/// @return communityVaultAddress The communityVault address
function communityVault() external view returns (address communityVaultAddress);
/// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information
/// @param wordPosition Index of 256-bits word with ticks
/// @return The 256-bits word with packed ticks info
function tickTable(int16 wordPosition) external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token0
function totalFeeGrowth0Token() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token1
function totalFeeGrowth1Token() external view returns (uint256);
/// @notice The current pool fee value
/// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee.
/// If the plugin implements complex fee logic, this method may return an incorrect value or revert.
/// In this case, see the plugin implementation and related documentation.
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6
function fee() external view returns (uint16 currentFee);
/// @notice The tracked token0 and token1 reserves of pool
/// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee.
/// If the balance exceeds uint128, the excess will be sent to the communityVault.
/// @return reserve0 The last known reserve of token0
/// @return reserve1 The last known reserve of token1
function getReserves() external view returns (uint128 reserve0, uint128 reserve1);
/// @notice Returns the information about a position by the position's key
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes
/// @return liquidity The amount of liquidity in the position
/// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke
/// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke
/// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke
/// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
) external view returns (uint256 liquidity, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token, uint128 fees0, uint128 fees1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks.
/// Returned value cannot exceed type(uint128).max
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The current in range liquidity
function liquidity() external view returns (uint128);
/// @notice The current tick spacing
/// @dev Ticks can only be initialized by new mints at multiples of this value
/// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ...
/// However, tickspacing can be changed after the ticks have been initialized.
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The current tick spacing
function tickSpacing() external view returns (int24);
/// @notice The previous initialized tick before (or at) current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The previous initialized tick
function prevTickGlobal() external view returns (int24);
/// @notice The next initialized tick after current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The next initialized tick
function nextTickGlobal() external view returns (int24);
/// @notice The root of tick search tree
/// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The root of tick search tree as bitmap
function tickTreeRoot() external view returns (uint32);
/// @notice The second layer of tick search tree
/// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The node of tick search tree second layer
function tickTreeSecondLayer(int16) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Algebra Vault Factory
/// @notice This contract can be used for automatic vaults creation
/// @dev Version: Algebra Integral
interface IAlgebraVaultFactory {
/// @notice returns address of the community fee vault for the pool
/// @param pool the address of Algebra Integral pool
/// @return communityFeeVault the address of community fee vault
function getVaultForPool(address pool) external view returns (address communityFeeVault);
/// @notice creates the community fee vault for the pool if needed
/// @param pool the address of Algebra Integral pool
/// @return communityFeeVault the address of community fee vault
function createVaultForPool(address pool) external returns (address communityFeeVault);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;
/// @title Contains common constants for Algebra contracts
/// @dev Constants moved to the library, not the base contract, to further emphasize their constant nature
library Constants {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 1 << 96;
uint256 internal constant Q128 = 1 << 128;
uint24 internal constant FEE_DENOMINATOR = 1e6;
uint16 internal constant FLASH_FEE = 0.01e4; // fee for flash loan in hundredths of a bip (0.01%)
uint16 internal constant INIT_DEFAULT_FEE = 0.05e4; // init default fee value in hundredths of a bip (0.05%)
uint16 internal constant MAX_DEFAULT_FEE = 5e4; // max default fee value in hundredths of a bip (5%)
int24 internal constant INIT_DEFAULT_TICK_SPACING = 60;
int24 internal constant MAX_TICK_SPACING = 500;
int24 internal constant MIN_TICK_SPACING = 1;
// the frequency with which the accumulated community fees are sent to the vault
uint32 internal constant COMMUNITY_FEE_TRANSFER_FREQUENCY = 8 hours;
// max(uint128) / (MAX_TICK - MIN_TICK)
uint128 internal constant MAX_LIQUIDITY_PER_TICK = 191757638537527648490752896198553;
uint16 internal constant MAX_COMMUNITY_FEE = 1e3; // 100%
uint256 internal constant COMMUNITY_FEE_DENOMINATOR = 1e3;
// role that can change settings in pools
bytes32 internal constant POOLS_ADMINISTRATOR_ROLE = keccak256('POOLS_ADMINISTRATOR');
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @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 {
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 {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
// Subtract 256 bit remainder from 512 bit number
assembly {
let remainder := mulmod(a, b, denominator)
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 {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
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 {
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 {
if (a == 0 || ((result = a * b) / a == b)) {
require(denominator > 0);
assembly {
result := add(div(result, denominator), gt(mod(result, denominator), 0))
}
} else {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
}
/// @notice Returns ceil(x / y)
/// @dev division by 0 has unspecified behavior, and must be checked externally
/// @param x The dividend
/// @param y The divisor
/// @return z The quotient, ceil(x / y)
function unsafeDivRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
import './TickMath.sol';
import './TokenDeltaMath.sol';
/// @title Math library for liquidity
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
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) {
unchecked {
if (y < 0) {
if ((z = x - uint128(-y)) >= x) revert IAlgebraPoolErrors.liquiditySub();
} else {
if ((z = x + uint128(y)) < x) revert IAlgebraPoolErrors.liquidityAdd();
}
}
}
function getAmountsForLiquidity(
int24 bottomTick,
int24 topTick,
int128 liquidityDelta,
int24 currentTick,
uint160 currentPrice
) internal pure returns (uint256 amount0, uint256 amount1, int128 globalLiquidityDelta) {
uint160 priceAtBottomTick = TickMath.getSqrtRatioAtTick(bottomTick);
uint160 priceAtTopTick = TickMath.getSqrtRatioAtTick(topTick);
int256 amount0Int;
int256 amount1Int;
if (currentTick < bottomTick) {
// If current tick is less than the provided bottom one then only the token0 has to be provided
amount0Int = TokenDeltaMath.getToken0Delta(priceAtBottomTick, priceAtTopTick, liquidityDelta);
} else if (currentTick < topTick) {
amount0Int = TokenDeltaMath.getToken0Delta(currentPrice, priceAtTopTick, liquidityDelta);
amount1Int = TokenDeltaMath.getToken1Delta(priceAtBottomTick, currentPrice, liquidityDelta);
globalLiquidityDelta = liquidityDelta;
} else {
// If current tick is greater than the provided top one then only the token1 has to be provided
amount1Int = TokenDeltaMath.getToken1Delta(priceAtBottomTick, priceAtTopTick, liquidityDelta);
}
unchecked {
(amount0, amount1) = liquidityDelta < 0 ? (uint256(-amount0Int), uint256(-amount1Int)) : (uint256(amount0Int), uint256(amount1Int));
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
require((z = x + y) >= x);
}
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
require((z = x - y) <= x);
}
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
require(x == 0 || (z = x * y) / x == y);
}
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
require((z = x + y) >= x == (y >= 0));
}
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
require((z = x - y) <= x == (y >= 0));
}
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add128(uint128 x, uint128 y) internal pure returns (uint128 z) {
unchecked {
require((z = x + y) >= x);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
/// @title Contains logic and constants for interacting with the plugin through hooks
/// @dev Allows pool to check which hooks are enabled, as well as control the return selector
library Plugins {
function hasFlag(uint8 pluginConfig, uint256 flag) internal pure returns (bool res) {
assembly {
res := gt(and(pluginConfig, flag), 0)
}
}
function shouldReturn(bytes4 selector, bytes4 expectedSelector) internal pure {
if (selector != expectedSelector) revert IAlgebraPoolErrors.invalidHookResponse(expectedSelector);
}
uint256 internal constant BEFORE_SWAP_FLAG = 1;
uint256 internal constant AFTER_SWAP_FLAG = 1 << 1;
uint256 internal constant BEFORE_POSITION_MODIFY_FLAG = 1 << 2;
uint256 internal constant AFTER_POSITION_MODIFY_FLAG = 1 << 3;
uint256 internal constant BEFORE_FLASH_FLAG = 1 << 4;
uint256 internal constant AFTER_FLASH_FLAG = 1 << 5;
uint256 internal constant AFTER_INIT_FLAG = 1 << 6;
uint256 internal constant DYNAMIC_FEE = 1 << 7;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
import './FullMath.sol';
import './LowGasSafeMath.sol';
import './TokenDeltaMath.sol';
import './Constants.sol';
/// @title Computes the result of price movement
/// @notice Contains methods for computing the result of price movement within a single tick price range.
library PriceMovementMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @notice Gets the next sqrt price given an input amount of token0 or token1
/// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
/// @param price The starting Q64.96 sqrt price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param input How much of token0, or token1, is being swapped in
/// @param zeroToOne Whether the amount in is token0 or token1
/// @return resultPrice The Q64.96 sqrt price after adding the input amount to token0 or token1
function getNewPriceAfterInput(uint160 price, uint128 liquidity, uint256 input, bool zeroToOne) internal pure returns (uint160 resultPrice) {
return getNewPrice(price, liquidity, input, zeroToOne, true);
}
/// @notice Gets the next sqrt price given an output amount of token0 or token1
/// @dev Throws if price or liquidity are 0 or the next price is out of bounds
/// @param price The starting Q64.96 sqrt price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param output How much of token0, or token1, is being swapped out
/// @param zeroToOne Whether the amount out is token0 or token1
/// @return resultPrice The Q64.96 sqrt price after removing the output amount of token0 or token1
function getNewPriceAfterOutput(uint160 price, uint128 liquidity, uint256 output, bool zeroToOne) internal pure returns (uint160 resultPrice) {
return getNewPrice(price, liquidity, output, zeroToOne, false);
}
function getNewPrice(uint160 price, uint128 liquidity, uint256 amount, bool zeroToOne, bool fromInput) internal pure returns (uint160 resultPrice) {
unchecked {
require(price != 0);
require(liquidity != 0);
if (amount == 0) return price;
if (zeroToOne == fromInput) {
// rounding up or down
uint256 liquidityShifted = uint256(liquidity) << Constants.RESOLUTION;
if (fromInput) {
uint256 product;
if ((product = amount * price) / amount == price) {
uint256 denominator = liquidityShifted + product;
if (denominator >= liquidityShifted) return uint160(FullMath.mulDivRoundingUp(liquidityShifted, price, denominator)); // always fits in 160 bits
}
return uint160(FullMath.unsafeDivRoundingUp(liquidityShifted, (liquidityShifted / price).add(amount))); // denominator always > 0
} else {
uint256 product;
require((product = amount * price) / amount == price); // if the product overflows, we know the denominator underflows
require(liquidityShifted > product); // in addition, we must check that the denominator does not underflow
return FullMath.mulDivRoundingUp(liquidityShifted, price, liquidityShifted - product).toUint160();
}
} else {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (fromInput) {
return
uint256(price)
.add(amount <= type(uint160).max ? (amount << Constants.RESOLUTION) / liquidity : FullMath.mulDiv(amount, Constants.Q96, liquidity))
.toUint160();
} else {
uint256 quotient = amount <= type(uint160).max
? FullMath.unsafeDivRoundingUp(amount << Constants.RESOLUTION, liquidity) // denominator always > 0
: FullMath.mulDivRoundingUp(amount, Constants.Q96, liquidity);
require(price > quotient);
return uint160(price - quotient); // always fits 160 bits
}
}
}
}
function getInputTokenDelta01(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken0Delta(to, from, liquidity, true);
}
function getInputTokenDelta10(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken1Delta(from, to, liquidity, true);
}
function getOutputTokenDelta01(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken1Delta(to, from, liquidity, false);
}
function getOutputTokenDelta10(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken0Delta(from, to, liquidity, false);
}
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
/// @param zeroToOne The direction of price movement
/// @param currentPrice The current Q64.96 sqrt price of the pool
/// @param targetPrice The Q64.96 sqrt price that cannot be exceeded, from which the direction of the swap is inferred
/// @param liquidity The usable liquidity
/// @param amountAvailable How much input or output amount is remaining to be swapped in/out
/// @param fee The fee taken from the input amount, expressed in hundredths of a bip
/// @return resultPrice The Q64.96 sqrt price after swapping the amount in/out, not to exceed the price target
/// @return input The amount to be swapped in, of either token0 or token1, based on the direction of the swap
/// @return output The amount to be received, of either token0 or token1, based on the direction of the swap
/// @return feeAmount The amount of input that will be taken as a fee
function movePriceTowardsTarget(
bool zeroToOne,
uint160 currentPrice,
uint160 targetPrice,
uint128 liquidity,
int256 amountAvailable,
uint16 fee
) internal pure returns (uint160 resultPrice, uint256 input, uint256 output, uint256 feeAmount) {
unchecked {
function(uint160, uint160, uint128) pure returns (uint256) getInputTokenAmount = zeroToOne ? getInputTokenDelta01 : getInputTokenDelta10;
if (amountAvailable >= 0) {
// exactIn or not
uint256 amountAvailableAfterFee = FullMath.mulDiv(uint256(amountAvailable), Constants.FEE_DENOMINATOR - fee, Constants.FEE_DENOMINATOR);
input = getInputTokenAmount(targetPrice, currentPrice, liquidity);
if (amountAvailableAfterFee >= input) {
resultPrice = targetPrice;
feeAmount = FullMath.mulDivRoundingUp(input, fee, Constants.FEE_DENOMINATOR - fee);
} else {
resultPrice = getNewPriceAfterInput(currentPrice, liquidity, amountAvailableAfterFee, zeroToOne);
assert(targetPrice != resultPrice); // should always be true
input = getInputTokenAmount(resultPrice, currentPrice, liquidity);
// we didn't reach the target, so take the remainder of the maximum input as fee
feeAmount = uint256(amountAvailable) - input; // input <= amountAvailable due to used formulas. This invariant is checked by fuzzy tests
}
output = (zeroToOne ? getOutputTokenDelta01 : getOutputTokenDelta10)(resultPrice, currentPrice, liquidity);
} else {
function(uint160, uint160, uint128) pure returns (uint256) getOutputTokenAmount = zeroToOne ? getOutputTokenDelta01 : getOutputTokenDelta10;
output = getOutputTokenAmount(targetPrice, currentPrice, liquidity);
amountAvailable = -amountAvailable;
if (amountAvailable < 0) revert IAlgebraPoolErrors.invalidAmountRequired(); // in case of type(int256).min
if (uint256(amountAvailable) >= output) resultPrice = targetPrice;
else {
resultPrice = getNewPriceAfterOutput(currentPrice, liquidity, uint256(amountAvailable), zeroToOne);
// should be always true if the price is in the allowed range
if (targetPrice != resultPrice) output = getOutputTokenAmount(resultPrice, currentPrice, liquidity);
// cap the output amount to not exceed the remaining output amount
if (output > uint256(amountAvailable)) output = uint256(amountAvailable);
}
input = getInputTokenAmount(resultPrice, currentPrice, liquidity);
feeAmount = FullMath.mulDivRoundingUp(input, fee, Constants.FEE_DENOMINATOR - fee);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint128 to a int128, revert on overflow
/// @param y The uint128 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(uint128 y) internal pure returns (int128 z) {
require((z = int128(y)) >= 0);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require((z = int256(y)) >= 0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
/// @title SafeTransfer
/// @notice Safe ERC20 transfer library that gracefully handles missing return values.
/// @dev Credit to Solmate under MIT license: https://github.com/transmissions11/solmate/blob/ed67feda67b24fdeff8ad1032360f0ee6047ba0a/src/utils/SafeTransferLib.sol
/// @dev Please note that this library does not check if the token has a code! That responsibility is delegated to the caller.
library SafeTransfer {
/// @notice Transfers tokens to a recipient
/// @dev Calls transfer on token contract, errors with transferFailed() if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param amount The amount of the token to transfer
function safeTransfer(address token, address to, uint256 amount) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40) // we will need to restore 0x40 slot
mstore(0x00, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // "transfer(address,uint256)" selector
mstore(0x04, and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // append cleaned "to" address
mstore(0x24, amount)
// now we use 0x00 - 0x44 bytes (68), freeMemoryPointer is dirty
success := call(gas(), token, 0, 0, 0x44, 0, 0x20)
success := and(
// set success to true if call isn't reverted and returned exactly 1 (can't just be non-zero data) or nothing
or(and(eq(mload(0), 1), eq(returndatasize(), 32)), iszero(returndatasize())),
success
)
mstore(0x40, freeMemoryPointer) // restore the freeMemoryPointer
}
if (!success) revert IAlgebraPoolErrors.transferFailed();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
import './TickMath.sol';
import './LiquidityMath.sol';
import './Constants.sol';
/// @title Library for managing and interacting with ticks
/// @notice Contains functions for managing tick processes and relevant calculations
/// @dev Ticks are organized as a doubly linked list
library TickManagement {
// info stored for each initialized individual tick
struct Tick {
uint256 liquidityTotal; // the total position liquidity that references this tick
int128 liquidityDelta; // amount of net liquidity added (subtracted) when tick is crossed left-right (right-left),
int24 prevTick;
int24 nextTick;
// fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
// only has relative meaning, not absolute — the value depends on when the tick is initialized
uint256 outerFeeGrowth0Token;
uint256 outerFeeGrowth1Token;
}
function checkTickRangeValidity(int24 bottomTick, int24 topTick) internal pure {
if (topTick > TickMath.MAX_TICK) revert IAlgebraPoolErrors.topTickAboveMAX();
if (topTick <= bottomTick) revert IAlgebraPoolErrors.topTickLowerOrEqBottomTick();
if (bottomTick < TickMath.MIN_TICK) revert IAlgebraPoolErrors.bottomTickLowerThanMIN();
}
/// @notice Retrieves fee growth data
/// @param self The mapping containing all tick information for initialized ticks
/// @param bottomTick The lower tick boundary of the position
/// @param topTick The upper tick boundary of the position
/// @param currentTick The current tick
/// @param totalFeeGrowth0Token The all-time global fee growth, per unit of liquidity, in token0
/// @param totalFeeGrowth1Token The all-time global fee growth, per unit of liquidity, in token1
/// @return innerFeeGrowth0Token The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
/// @return innerFeeGrowth1Token The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
function getInnerFeeGrowth(
mapping(int24 => Tick) storage self,
int24 bottomTick,
int24 topTick,
int24 currentTick,
uint256 totalFeeGrowth0Token,
uint256 totalFeeGrowth1Token
) internal view returns (uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token) {
Tick storage lower = self[bottomTick];
Tick storage upper = self[topTick];
unchecked {
if (currentTick < topTick) {
if (currentTick >= bottomTick) {
innerFeeGrowth0Token = totalFeeGrowth0Token - lower.outerFeeGrowth0Token;
innerFeeGrowth1Token = totalFeeGrowth1Token - lower.outerFeeGrowth1Token;
} else {
innerFeeGrowth0Token = lower.outerFeeGrowth0Token;
innerFeeGrowth1Token = lower.outerFeeGrowth1Token;
}
innerFeeGrowth0Token -= upper.outerFeeGrowth0Token;
innerFeeGrowth1Token -= upper.outerFeeGrowth1Token;
} else {
innerFeeGrowth0Token = upper.outerFeeGrowth0Token - lower.outerFeeGrowth0Token;
innerFeeGrowth1Token = upper.outerFeeGrowth1Token - lower.outerFeeGrowth1Token;
}
}
}
/// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The tick that will be updated
/// @param currentTick The current tick
/// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
/// @param totalFeeGrowth0Token The all-time global fee growth, per unit of liquidity, in token0
/// @param totalFeeGrowth1Token The all-time global fee growth, per unit of liquidity, in token1
/// @param upper True for updating a position's upper tick, or false for updating a position's lower tick
/// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
function update(
mapping(int24 => Tick) storage self,
int24 tick,
int24 currentTick,
int128 liquidityDelta,
uint256 totalFeeGrowth0Token,
uint256 totalFeeGrowth1Token,
bool upper
) internal returns (bool flipped) {
Tick storage data = self[tick];
uint256 liquidityTotalBefore = data.liquidityTotal;
uint256 liquidityTotalAfter = LiquidityMath.addDelta(uint128(liquidityTotalBefore), liquidityDelta);
if (liquidityTotalAfter > Constants.MAX_LIQUIDITY_PER_TICK) revert IAlgebraPoolErrors.liquidityOverflow();
int128 liquidityDeltaBefore = data.liquidityDelta;
// when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
data.liquidityDelta = upper ? int128(int256(liquidityDeltaBefore) - liquidityDelta) : int128(int256(liquidityDeltaBefore) + liquidityDelta);
data.liquidityTotal = liquidityTotalAfter;
flipped = (liquidityTotalAfter == 0);
if (liquidityTotalBefore == 0) {
flipped = !flipped;
// by convention, we assume that all growth before a tick was initialized happened _below_ the tick
if (tick <= currentTick) (data.outerFeeGrowth0Token, data.outerFeeGrowth1Token) = (totalFeeGrowth0Token, totalFeeGrowth1Token);
}
}
/// @notice Transitions to next tick as needed by price movement
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The destination tick of the transition
/// @param feeGrowth0 The all-time global fee growth, per unit of liquidity, in token0
/// @param feeGrowth1 The all-time global fee growth, per unit of liquidity, in token1
/// @return liquidityDelta The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
/// @return prevTick The previous active tick before _tick_
/// @return nextTick The next active tick after _tick_
function cross(
mapping(int24 => Tick) storage self,
int24 tick,
uint256 feeGrowth0,
uint256 feeGrowth1
) internal returns (int128 liquidityDelta, int24 prevTick, int24 nextTick) {
Tick storage data = self[tick];
unchecked {
(data.outerFeeGrowth1Token, data.outerFeeGrowth0Token) = (feeGrowth1 - data.outerFeeGrowth1Token, feeGrowth0 - data.outerFeeGrowth0Token);
}
return (data.liquidityDelta, data.prevTick, data.nextTick);
}
/// @notice Used for initial setup of ticks list
/// @param self The mapping containing all tick information for initialized ticks
function initTickState(mapping(int24 => Tick) storage self) internal {
(self[TickMath.MIN_TICK].prevTick, self[TickMath.MIN_TICK].nextTick) = (TickMath.MIN_TICK, TickMath.MAX_TICK);
(self[TickMath.MAX_TICK].prevTick, self[TickMath.MAX_TICK].nextTick) = (TickMath.MIN_TICK, TickMath.MAX_TICK);
}
/// @notice Removes tick from the linked list
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The tick that will be removed
/// @return prevTick The previous active tick before _tick_
/// @return nextTick The next active tick after _tick_
function removeTick(mapping(int24 => Tick) storage self, int24 tick) internal returns (int24 prevTick, int24 nextTick) {
(prevTick, nextTick) = (self[tick].prevTick, self[tick].nextTick);
delete self[tick];
if (tick == TickMath.MIN_TICK || tick == TickMath.MAX_TICK) {
// MIN_TICK and MAX_TICK cannot be removed from tick list
(self[tick].prevTick, self[tick].nextTick) = (prevTick, nextTick);
} else {
if (prevTick == nextTick) revert IAlgebraPoolErrors.tickIsNotInitialized();
self[prevTick].nextTick = nextTick;
self[nextTick].prevTick = prevTick;
}
return (prevTick, nextTick);
}
/// @notice Adds tick to the linked list
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The tick that will be inserted
/// @param prevTick The previous active tick before _tick_
/// @param nextTick The next active tick after _tick_
function insertTick(mapping(int24 => Tick) storage self, int24 tick, int24 prevTick, int24 nextTick) internal {
if (tick == TickMath.MIN_TICK || tick == TickMath.MAX_TICK) return;
if (!(prevTick < tick && nextTick > tick)) revert IAlgebraPoolErrors.tickInvalidLinks();
(self[tick].prevTick, self[tick].nextTick) = (prevTick, nextTick);
self[prevTick].nextTick = tick;
self[nextTick].prevTick = tick;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IAlgebraPoolErrors.sol';
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return price A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 price) {
unchecked {
// get abs value
int24 absTickMask = tick >> (24 - 1);
uint256 absTick = uint24((tick + absTickMask) ^ absTickMask);
if (absTick > uint24(MAX_TICK)) revert IAlgebraPoolErrors.tickOutOfRange();
uint256 ratio = 0x100000000000000000000000000000000;
if (absTick & 0x1 != 0) ratio = 0xfffcb933bd6fad37aa2d162d1a594001;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick >= 0x40000) {
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
}
if (tick > 0) {
assembly {
ratio := div(not(0), ratio)
}
}
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
price = uint160((ratio + 0xFFFFFFFF) >> 32);
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case price < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param price The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 price) internal pure returns (int24 tick) {
unchecked {
// second inequality must be >= because the price can never reach the price at the max tick
if (price < MIN_SQRT_RATIO || price >= MAX_SQRT_RATIO) revert IAlgebraPoolErrors.priceOutOfRange();
uint256 ratio = uint256(price) << 32;
uint256 r = ratio;
uint256 msb;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= price ? tickHi : tickLow;
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './TickMath.sol';
/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state and search tree
/// @dev The leafs mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickTree {
int16 internal constant SECOND_LAYER_OFFSET = 3466; // ceil(-MIN_TICK / 256)
/// @notice Toggles the initialized state for a given tick from false to true, or vice versa
/// @param leafs The mapping of words with ticks
/// @param secondLayer The mapping of words with leafs
/// @param treeRoot The word with info about active subtrees
/// @param tick The tick to toggle
function toggleTick(
mapping(int16 => uint256) storage leafs,
mapping(int16 => uint256) storage secondLayer,
uint32 treeRoot,
int24 tick
) internal returns (uint32 newTreeRoot) {
newTreeRoot = treeRoot;
(bool toggledNode, int16 nodeIndex) = _toggleBitInNode(leafs, tick); // toggle in leaf
if (toggledNode) {
unchecked {
(toggledNode, nodeIndex) = _toggleBitInNode(secondLayer, nodeIndex + SECOND_LAYER_OFFSET);
}
if (toggledNode) {
assembly {
newTreeRoot := xor(newTreeRoot, shl(nodeIndex, 1))
}
}
}
}
/// @notice Toggles a bit in a tree layer by its index
/// @param treeLevel The level of tree
/// @param bitIndex The end-to-end index of a bit in a layer of tree
/// @return toggledNode Toggled whole node or not
/// @return nodeIndex Number of corresponding node
function _toggleBitInNode(mapping(int16 => uint256) storage treeLevel, int24 bitIndex) private returns (bool toggledNode, int16 nodeIndex) {
assembly {
nodeIndex := sar(8, bitIndex)
}
uint256 node = treeLevel[nodeIndex];
assembly {
toggledNode := iszero(node)
node := xor(node, shl(and(bitIndex, 0xFF), 1))
toggledNode := xor(toggledNode, iszero(node))
}
treeLevel[nodeIndex] = node;
}
/// @notice Returns the next initialized tick in tree to the right (gte) of the given tick or `MAX_TICK`
/// @param leafs The words with ticks
/// @param secondLayer The words with info about active leafs
/// @param treeRoot The word with info about active subtrees
/// @param tick The starting tick
/// @return nextTick The next initialized tick or `MAX_TICK`
function getNextTick(
mapping(int16 => uint256) storage leafs,
mapping(int16 => uint256) storage secondLayer,
uint32 treeRoot,
int24 tick
) internal view returns (int24 nextTick) {
unchecked {
tick++; // start searching from the next tick
int16 nodeIndex;
assembly {
// index in treeRoot
nodeIndex := shr(8, add(sar(8, tick), SECOND_LAYER_OFFSET))
}
bool initialized;
// if subtree has active ticks
if (treeRoot & (1 << uint16(nodeIndex)) != 0) {
// try to find initialized tick in the corresponding leaf of the tree
(nodeIndex, nextTick, initialized) = _nextActiveBitInSameNode(leafs, tick);
if (initialized) return nextTick;
// try to find next initialized leaf in the tree
(nodeIndex, nextTick, initialized) = _nextActiveBitInSameNode(secondLayer, nodeIndex + SECOND_LAYER_OFFSET + 1);
}
if (!initialized) {
// try to find which subtree has an active leaf
// nodeIndex is now the index of the second level node
(nextTick, initialized) = _nextActiveBitInWord(treeRoot, ++nodeIndex);
if (!initialized) return TickMath.MAX_TICK;
nextTick = _firstActiveBitInNode(secondLayer, nextTick); // we found a second level node that has a leaf with an active tick
}
nextTick = _firstActiveBitInNode(leafs, nextTick - SECOND_LAYER_OFFSET);
}
}
/// @notice Returns the index of the next active bit in the same tree node
/// @param treeLevel The level of search tree
/// @param bitIndex The starting bit index
/// @return nodeIndex The index of corresponding node
/// @return nextBitIndex The index of next active bit or last bit in node
/// @return initialized Is nextBitIndex initialized or not
function _nextActiveBitInSameNode(
mapping(int16 => uint256) storage treeLevel,
int24 bitIndex
) internal view returns (int16 nodeIndex, int24 nextBitIndex, bool initialized) {
assembly {
nodeIndex := sar(8, bitIndex)
}
(nextBitIndex, initialized) = _nextActiveBitInWord(treeLevel[nodeIndex], bitIndex);
}
/// @notice Returns first active bit in given node
/// @param treeLevel The level of search tree
/// @param nodeIndex The index of corresponding node in the level of tree
/// @return bitIndex Number of next active bit or last bit in node
function _firstActiveBitInNode(mapping(int16 => uint256) storage treeLevel, int24 nodeIndex) internal view returns (int24 bitIndex) {
assembly {
bitIndex := shl(8, nodeIndex)
}
(bitIndex, ) = _nextActiveBitInWord(treeLevel[int16(nodeIndex)], bitIndex);
}
/// @notice Returns the next initialized bit contained in the word that is to the right or at (gte) of the given bit
/// @param word The word in which to compute the next initialized bit
/// @param bitIndex The end-to-end index of a bit in a layer of tree
/// @return nextBitIndex The next initialized or uninitialized bit up to 256 bits away from the current bit
/// @return initialized Whether the next bit is initialized, as the function only searches within up to 256 bits
function _nextActiveBitInWord(uint256 word, int24 bitIndex) internal pure returns (int24 nextBitIndex, bool initialized) {
uint256 bitIndexInWord;
assembly {
bitIndexInWord := and(bitIndex, 0xFF)
}
unchecked {
uint256 _row = word >> bitIndexInWord; // all the 1s at or to the left of the bitIndexInWord
if (_row == 0) {
nextBitIndex = bitIndex | 255;
} else {
nextBitIndex = bitIndex + int24(uint24(getSingleSignificantBit((0 - _row) & _row))); // least significant bit
initialized = true;
}
}
}
/// @notice get position of single 1-bit
/// @dev it is assumed that word contains exactly one 1-bit, otherwise the result will be incorrect
/// @param word The word containing only one 1-bit
function getSingleSignificantBit(uint256 word) internal pure returns (uint8 singleBitPos) {
assembly {
singleBitPos := iszero(and(word, 0x5555555555555555555555555555555555555555555555555555555555555555))
singleBitPos := or(singleBitPos, shl(7, iszero(and(word, 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))))
singleBitPos := or(singleBitPos, shl(6, iszero(and(word, 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF))))
singleBitPos := or(singleBitPos, shl(5, iszero(and(word, 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF))))
singleBitPos := or(singleBitPos, shl(4, iszero(and(word, 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF))))
singleBitPos := or(singleBitPos, shl(3, iszero(and(word, 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF))))
singleBitPos := or(singleBitPos, shl(2, iszero(and(word, 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F))))
singleBitPos := or(singleBitPos, shl(1, iszero(and(word, 0x3333333333333333333333333333333333333333333333333333333333333333))))
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './SafeCast.sol';
import './FullMath.sol';
import './Constants.sol';
/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library TokenDeltaMath {
using SafeCast for uint256;
/// @notice Gets the token0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper)
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return token0Delta Amount of token0 required to cover a position of size liquidity between the two passed prices
function getToken0Delta(uint160 priceLower, uint160 priceUpper, uint128 liquidity, bool roundUp) internal pure returns (uint256 token0Delta) {
unchecked {
uint256 priceDelta = priceUpper - priceLower;
require(priceDelta < priceUpper); // forbids underflow and 0 priceLower
uint256 liquidityShifted = uint256(liquidity) << Constants.RESOLUTION;
token0Delta = roundUp
? FullMath.unsafeDivRoundingUp(FullMath.mulDivRoundingUp(priceDelta, liquidityShifted, priceUpper), priceLower) // denominator always > 0
: FullMath.mulDiv(priceDelta, liquidityShifted, priceUpper) / priceLower;
}
}
/// @notice Gets the token1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return token1Delta Amount of token1 required to cover a position of size liquidity between the two passed prices
function getToken1Delta(uint160 priceLower, uint160 priceUpper, uint128 liquidity, bool roundUp) internal pure returns (uint256 token1Delta) {
unchecked {
require(priceUpper >= priceLower);
uint256 priceDelta = priceUpper - priceLower;
token1Delta = roundUp ? FullMath.mulDivRoundingUp(priceDelta, liquidity, Constants.Q96) : FullMath.mulDiv(priceDelta, liquidity, Constants.Q96);
}
}
/// @notice Helper that gets signed token0 delta
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The change in liquidity for which to compute the token0 delta
/// @return token0Delta Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getToken0Delta(uint160 priceLower, uint160 priceUpper, int128 liquidity) internal pure returns (int256 token0Delta) {
unchecked {
token0Delta = liquidity >= 0
? getToken0Delta(priceLower, priceUpper, uint128(liquidity), true).toInt256()
: -getToken0Delta(priceLower, priceUpper, uint128(-liquidity), false).toInt256();
}
}
/// @notice Helper that gets signed token1 delta
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The change in liquidity for which to compute the token1 delta
/// @return token1Delta Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getToken1Delta(uint160 priceLower, uint160 priceUpper, int128 liquidity) internal pure returns (int256 token1Delta) {
unchecked {
token1Delta = liquidity >= 0
? getToken1Delta(priceLower, priceUpper, uint128(liquidity), true).toInt256()
: -getToken1Delta(priceLower, priceUpper, uint128(-liquidity), false).toInt256();
}
}
}