Verified contractExactMIT
LiquidityGenHook
Address0x5725df570e0008997dacef46bc179bbfc4d125cc
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,206,890
- Creation transaction
- 0xb2f6bd834a…27868f23cf
20 files
- contracts/hooks/LiquidityGenHook.solmain28.93 KB
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol193 B
- @openzeppelin/contracts/interfaces/IERC20.sol182 B
- @openzeppelin/contracts/interfaces/draft-IERC6093.sol6.54 KB
- @openzeppelin/contracts/token/ERC20/ERC20.sol10.8 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol1.18 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- contracts/errors/Errors.sol608 B
- contracts/interfaces/IConfigurableHook.sol1.96 KB
- contracts/interfaces/ICurrency.sol939 B
- contracts/interfaces/IHooks.sol2.66 KB
- contracts/interfaces/IPoolManager.sol2.54 KB
- contracts/interfaces/IUnlockCallback.sol525 B
- contracts/interfaces/IWETH.sol523 B
- contracts/libraries/LiquidityMath.sol8.09 KB
contracts/hooks/LiquidityGenHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "../interfaces/IPoolManager.sol";
import "../interfaces/IHooks.sol";
import "../interfaces/ICurrency.sol";
import "../interfaces/IUnlockCallback.sol";
import "../interfaces/IConfigurableHook.sol";
import "../interfaces/IWETH.sol";
import "../libraries/LiquidityMath.sol";
import "../errors/Errors.sol";
contract LiquidityGenHook is IHooks, IConfigurableHook, IUnlockCallback {
using SafeERC20 for IERC20;
using CurrencyLibrary for Currency;
uint256 public constant FEE_DENOMINATOR = 10000;
uint256 public constant MAX_TAX_BPS = 1500;
uint256 public constant MIN_PLATFORM_FEE_BPS = 2000;
uint256 public constant MAX_PLATFORM_FEE_BPS = 5000;
uint256 public constant MIN_THRESHOLD = 0.01 ether;
uint256 public constant MAX_THRESHOLD = 1 ether;
int24 public constant FULL_RANGE_LOWER = -887220;
int24 public constant FULL_RANGE_UPPER = 887220;
uint256 public constant MIN_GAS_FOR_LIQUIDITY = 350000;
address public immutable poolManager;
address public immutable weth;
address public controller;
address public platformFeeCollector;
address public factory;
uint256 public defaultPlatformFeeBps;
struct LiquidityConfig {
uint16 buyTaxBps;
uint16 sellTaxBps;
uint16 platformFeeBps;
uint256 threshold;
uint256 accumulated;
address tokenAddress;
bool enabled;
}
mapping(bytes32 => LiquidityConfig) public liquidityConfigs;
uint256 public totalLiquidityAdded;
uint256 public totalLiquidityEvents;
uint256 public totalPlatformFees;
bool private _liquidityInProgress;
event TaxTaken(bytes32 indexed poolId, uint256 amount, bool isBuy);
event LiquidityAdded(bytes32 indexed poolId, uint256 wethAmount, uint256 tokenAmount, uint128 liquidity);
event PlatformFeeSent(bytes32 indexed poolId, uint256 wethAmount, address recipient);
event ThresholdReached(bytes32 indexed poolId, uint256 accumulated);
event PlatformFeeCollectorUpdated(address oldCollector, address newCollector);
event PlatformFeeBpsUpdated(uint256 oldBps, uint256 newBps);
event HookConfigured(bytes32 indexed poolId, address indexed token, uint16 buyTaxBps, uint16 sellTaxBps);
event EmergencyWithdraw(address indexed to, uint256 wethAmount, uint256 ethAmount);
event AutoLiquidityTriggered(bytes32 indexed poolId, uint256 gasRemaining);
event AutoLiquiditySkipped(bytes32 indexed poolId, string reason);
event ResidualsBurned(bytes32 indexed poolId, uint256 tokensBurned, uint256 wethRecycled);
constructor(address _poolManager, address _weth, address _controller, address _platformFeeCollector) {
poolManager = _poolManager;
weth = _weth;
controller = _controller;
platformFeeCollector = _platformFeeCollector;
defaultPlatformFeeBps = 2000;
}
function configureHook(
bytes32 poolId,
address tokenAddress,
bytes calldata config
) external override {
if (msg.sender != controller && msg.sender != factory) revert NotController();
if (liquidityConfigs[poolId].enabled) revert HookAlreadyConfigured();
(uint16 buyTaxBps, uint16 sellTaxBps, uint256 threshold) = abi.decode(config, (uint16, uint16, uint256));
if (buyTaxBps > MAX_TAX_BPS) revert InvalidTaxRate();
if (sellTaxBps > MAX_TAX_BPS) revert InvalidTaxRate();
if (threshold < MIN_THRESHOLD || threshold > MAX_THRESHOLD) revert InvalidThreshold();
liquidityConfigs[poolId] = LiquidityConfig({
buyTaxBps: buyTaxBps,
sellTaxBps: sellTaxBps,
platformFeeBps: uint16(defaultPlatformFeeBps),
threshold: threshold,
accumulated: 0,
tokenAddress: tokenAddress,
enabled: true
});
emit HookConfigured(poolId, tokenAddress, buyTaxBps, sellTaxBps);
}
function getPoolId(PoolKey calldata key) external pure override returns (bytes32) {
return _getPoolId(key);
}
function isConfigured(bytes32 poolId) external view override returns (bool) {
return liquidityConfigs[poolId].enabled;
}
function setController(address newController) external {
if (msg.sender != controller) revert NotController();
if (newController == address(0)) revert InvalidReceiver();
controller = newController;
}
function setFactory(address newFactory) external {
if (msg.sender != controller) revert NotController();
factory = newFactory;
}
function setPlatformFeeCollector(address newCollector) external {
if (msg.sender != controller) revert NotController();
if (newCollector == address(0)) revert InvalidReceiver();
address oldCollector = platformFeeCollector;
platformFeeCollector = newCollector;
emit PlatformFeeCollectorUpdated(oldCollector, newCollector);
}
function setDefaultPlatformFeeBps(uint256 newPlatformFeeBps) external {
if (msg.sender != controller) revert NotController();
if (newPlatformFeeBps < MIN_PLATFORM_FEE_BPS || newPlatformFeeBps > MAX_PLATFORM_FEE_BPS) {
revert InvalidConfig();
}
uint256 oldBps = defaultPlatformFeeBps;
defaultPlatformFeeBps = newPlatformFeeBps;
emit PlatformFeeBpsUpdated(oldBps, newPlatformFeeBps);
}
function emergencyWithdraw(bool withdrawETH) external {
if (msg.sender != controller) revert NotController();
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
uint256 ethBalance = address(this).balance;
if (wethBalance > 0) {
if (withdrawETH) {
IWETH(weth).withdraw(wethBalance);
ethBalance += wethBalance;
} else {
IERC20(weth).safeTransfer(controller, wethBalance);
}
}
if (ethBalance > 0) {
(bool success,) = payable(controller).call{value: ethBalance}("");
require(success, "ETH transfer failed");
}
emit EmergencyWithdraw(controller, wethBalance, ethBalance);
}
function getHookPermissions() external pure returns (Hooks.Permissions memory) {
return Hooks.Permissions({
beforeInitialize: false,
afterInitialize: false,
beforeAddLiquidity: false,
afterAddLiquidity: false,
beforeRemoveLiquidity: false,
afterRemoveLiquidity: false,
beforeSwap: true,
afterSwap: true,
beforeDonate: false,
afterDonate: false,
beforeSwapReturnDelta: true,
afterSwapReturnDelta: true,
afterAddLiquidityReturnDelta: false,
afterRemoveLiquidityReturnDelta: false
});
}
function beforeInitialize(address, PoolKey calldata, uint160) external pure returns (bytes4) {
return IHooks.beforeInitialize.selector;
}
function afterInitialize(address, PoolKey calldata, uint160, int24) external pure returns (bytes4) {
return IHooks.afterInitialize.selector;
}
function beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
external pure returns (bytes4)
{
return IHooks.beforeAddLiquidity.selector;
}
function afterAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external pure returns (bytes4, BalanceDelta)
{
return (IHooks.afterAddLiquidity.selector, BalanceDelta.wrap(0));
}
function beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
external pure returns (bytes4)
{
return IHooks.beforeRemoveLiquidity.selector;
}
function afterRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
external pure returns (bytes4, BalanceDelta)
{
return (IHooks.afterRemoveLiquidity.selector, BalanceDelta.wrap(0));
}
function beforeSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
bytes calldata
) external returns (bytes4, BeforeSwapDelta, uint24) {
if (msg.sender != poolManager) revert Unauthorized();
bytes32 poolId = _getPoolId(key);
LiquidityConfig storage config = liquidityConfigs[poolId];
if (!config.enabled || _liquidityInProgress) {
return (IHooks.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
}
address currency1Addr = Currency.unwrap(key.currency1);
bool wethIsCurrency1 = currency1Addr == weth;
bool isBuy;
if (wethIsCurrency1) {
isBuy = !params.zeroForOne;
} else {
isBuy = params.zeroForOne;
}
if (isBuy) {
uint16 taxBps = config.buyTaxBps;
if (taxBps == 0) {
return (IHooks.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
}
uint256 wethAmount;
if (params.amountSpecified < 0) {
wethAmount = uint256(uint128(-int128(params.amountSpecified)));
} else {
wethAmount = uint256(uint128(int128(params.amountSpecified)));
}
uint256 feeAmount = (wethAmount * taxBps) / FEE_DENOMINATOR;
if (feeAmount > 0) {
Currency wethCurrency = wethIsCurrency1 ? key.currency1 : key.currency0;
IPoolManager(poolManager).take(wethCurrency, address(this), feeAmount);
config.accumulated += feeAmount;
emit TaxTaken(poolId, feeAmount, true);
bool exactInput = params.amountSpecified < 0;
int128 specifiedDelta = exactInput ? int128(uint128(feeAmount)) : int128(0);
int128 unspecifiedDelta = exactInput ? int128(0) : int128(uint128(feeAmount));
BeforeSwapDelta hookDelta = BeforeSwapDelta.wrap(
int256(int128(specifiedDelta)) << 128 | int256(int128(unspecifiedDelta))
);
return (IHooks.beforeSwap.selector, hookDelta, 0);
}
}
return (IHooks.beforeSwap.selector, BeforeSwapDelta.wrap(0), 0);
}
function afterSwap(
address,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata
) external returns (bytes4, int128) {
if (msg.sender != poolManager) revert Unauthorized();
bytes32 poolId = _getPoolId(key);
LiquidityConfig storage config = liquidityConfigs[poolId];
if (!config.enabled || _liquidityInProgress) {
return (IHooks.afterSwap.selector, 0);
}
address currency1Addr = Currency.unwrap(key.currency1);
bool wethIsCurrency1 = currency1Addr == weth;
bool isSell;
if (wethIsCurrency1) {
isSell = params.zeroForOne;
} else {
isSell = !params.zeroForOne;
}
int128 hookDelta = 0;
if (isSell && config.sellTaxBps > 0) {
int128 amount0 = int128(int256(BalanceDelta.unwrap(delta)) >> 128);
int128 amount1 = int128(int256(BalanceDelta.unwrap(delta)));
int128 wethDelta = wethIsCurrency1 ? amount1 : amount0;
uint256 wethOutput;
if (wethDelta > 0) {
wethOutput = uint256(uint128(wethDelta));
} else if (wethDelta < 0) {
wethOutput = uint256(uint128(-wethDelta));
} else {
wethOutput = 0;
}
if (wethOutput > 0) {
uint256 feeAmount = (wethOutput * config.sellTaxBps) / FEE_DENOMINATOR;
if (feeAmount > 0) {
Currency wethCurrency = wethIsCurrency1 ? key.currency1 : key.currency0;
IPoolManager(poolManager).take(wethCurrency, address(this), feeAmount);
config.accumulated += feeAmount;
emit TaxTaken(poolId, feeAmount, false);
hookDelta = int128(uint128(feeAmount));
}
}
}
if (config.accumulated >= config.threshold) {
emit ThresholdReached(poolId, config.accumulated);
if (!_liquidityInProgress && gasleft() >= MIN_GAS_FOR_LIQUIDITY) {
emit AutoLiquidityTriggered(poolId, gasleft());
_executeAutoLiquidity(key, poolId, config);
} else if (_liquidityInProgress) {
emit AutoLiquiditySkipped(poolId, "reentrancy");
} else {
emit AutoLiquiditySkipped(poolId, "insufficient gas");
}
}
return (IHooks.afterSwap.selector, hookDelta);
}
function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
external pure returns (bytes4)
{
return IHooks.beforeDonate.selector;
}
function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
external pure returns (bytes4)
{
return IHooks.afterDonate.selector;
}
function _executeAutoLiquidity(
PoolKey calldata key,
bytes32 poolId,
LiquidityConfig storage config
) internal {
_liquidityInProgress = true;
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
if (wethBalance == 0) {
_liquidityInProgress = false;
return;
}
uint256 totalAmount = wethBalance < config.accumulated ? wethBalance : config.accumulated;
config.accumulated = config.accumulated > totalAmount ? config.accumulated - totalAmount : 0;
uint256 platformFee = (totalAmount * config.platformFeeBps) / FEE_DENOMINATOR;
uint256 liquidityBudget = totalAmount - platformFee;
if (platformFee > 0 && platformFeeCollector != address(0)) {
IWETH(weth).withdraw(platformFee);
(bool success, ) = payable(platformFeeCollector).call{value: platformFee}("");
require(success, "Platform fee transfer failed");
totalPlatformFees += platformFee;
emit PlatformFeeSent(poolId, platformFee, platformFeeCollector);
}
if (liquidityBudget > 0) {
address currency1Addr = Currency.unwrap(key.currency1);
bool wethIsCurrency1 = currency1Addr == weth;
Currency wethCurrency = wethIsCurrency1 ? key.currency1 : key.currency0;
Currency tokenCurrency = wethIsCurrency1 ? key.currency0 : key.currency1;
uint256 wethForTokenBuy = liquidityBudget / 2;
uint256 wethForLiquidity = liquidityBudget - wethForTokenBuy;
bool zeroForOne = !wethIsCurrency1;
SwapParams memory swapParams = SwapParams({
zeroForOne: zeroForOne,
amountSpecified: -int256(wethForTokenBuy),
sqrtPriceLimitX96: zeroForOne ? 4295128740 : 1461446703485210103287273052203988822378723970341
});
BalanceDelta swapDelta = IPoolManager(poolManager).swap(key, swapParams, "");
int128 swapAmount0 = int128(int256(BalanceDelta.unwrap(swapDelta)) >> 128);
int128 swapAmount1 = int128(int256(BalanceDelta.unwrap(swapDelta)));
int128 wethSwapDelta = wethIsCurrency1 ? swapAmount1 : swapAmount0;
int128 tokenSwapDelta = wethIsCurrency1 ? swapAmount0 : swapAmount1;
if (wethSwapDelta < 0) {
uint256 wethOwed = uint256(uint128(-wethSwapDelta));
IPoolManager(poolManager).sync(wethCurrency);
IERC20(weth).safeTransfer(poolManager, wethOwed);
IPoolManager(poolManager).settle();
}
uint256 tokensReceived = 0;
if (tokenSwapDelta > 0) {
tokensReceived = uint256(uint128(tokenSwapDelta));
IPoolManager(poolManager).take(tokenCurrency, address(this), tokensReceived);
}
if (wethForLiquidity > 0 && tokensReceived > 0) {
uint256 amount0Desired;
uint256 amount1Desired;
if (wethIsCurrency1) {
amount0Desired = tokensReceived;
amount1Desired = wethForLiquidity;
} else {
amount0Desired = wethForLiquidity;
amount1Desired = tokensReceived;
}
uint256 product = amount0Desired * amount1Desired;
uint128 liquidity = uint128((_sqrt(product) * 95) / 100);
if (liquidity > 0) {
bytes32 positionSalt = keccak256(abi.encodePacked(poolId, "LiquidityGenHook"));
ModifyLiquidityParams memory liqParams = ModifyLiquidityParams({
tickLower: FULL_RANGE_LOWER,
tickUpper: FULL_RANGE_UPPER,
liquidityDelta: int256(uint256(liquidity)),
salt: positionSalt
});
(BalanceDelta callerDelta,) = IPoolManager(poolManager).modifyLiquidity(key, liqParams, "");
int128 deltaAmount0 = BalanceDeltaLibrary.amount0(callerDelta);
int128 deltaAmount1 = BalanceDeltaLibrary.amount1(callerDelta);
uint256 actualAmount0 = 0;
uint256 actualAmount1 = 0;
if (deltaAmount0 < 0) {
actualAmount0 = uint256(-int256(deltaAmount0));
address token0 = Currency.unwrap(key.currency0);
IPoolManager(poolManager).sync(key.currency0);
IERC20(token0).safeTransfer(poolManager, actualAmount0);
IPoolManager(poolManager).settle();
}
if (deltaAmount1 < 0) {
actualAmount1 = uint256(-int256(deltaAmount1));
address token1 = Currency.unwrap(key.currency1);
IPoolManager(poolManager).sync(key.currency1);
IERC20(token1).safeTransfer(poolManager, actualAmount1);
IPoolManager(poolManager).settle();
}
uint256 wethUsed = wethIsCurrency1 ? actualAmount1 : actualAmount0;
uint256 tokensUsed = wethIsCurrency1 ? actualAmount0 : actualAmount1;
totalLiquidityAdded += wethUsed;
totalLiquidityEvents++;
emit LiquidityAdded(poolId, wethUsed, tokensUsed, liquidity);
uint256 residualWeth = wethForLiquidity > wethUsed ? wethForLiquidity - wethUsed : 0;
uint256 residualTokensAmt = tokensReceived > tokensUsed ? tokensReceived - tokensUsed : 0;
if (residualTokensAmt > 0) {
ERC20Burnable(config.tokenAddress).burn(residualTokensAmt);
}
if (residualWeth > 0) {
config.accumulated += residualWeth;
}
if (residualTokensAmt > 0 || residualWeth > 0) {
emit ResidualsBurned(poolId, residualTokensAmt, residualWeth);
}
}
}
}
_liquidityInProgress = false;
}
function executeLiquidityAdd(PoolKey calldata key) external {
require(!_liquidityInProgress, "Liquidity add in progress");
_liquidityInProgress = true;
bytes32 poolId = _getPoolId(key);
LiquidityConfig storage config = liquidityConfigs[poolId];
require(config.enabled, "Not enabled");
require(config.accumulated >= config.threshold, "Threshold not reached");
uint256 wethBalance = IERC20(weth).balanceOf(address(this));
require(wethBalance > 0, "No WETH for liquidity");
uint256 totalAmount = wethBalance < config.accumulated ? wethBalance : config.accumulated;
config.accumulated = config.accumulated > totalAmount ? config.accumulated - totalAmount : 0;
uint256 platformFee = (totalAmount * config.platformFeeBps) / FEE_DENOMINATOR;
uint256 liquidityBudget = totalAmount - platformFee;
if (platformFee > 0 && platformFeeCollector != address(0)) {
IWETH(weth).withdraw(platformFee);
(bool success, ) = payable(platformFeeCollector).call{value: platformFee}("");
require(success, "Platform fee transfer failed");
totalPlatformFees += platformFee;
emit PlatformFeeSent(poolId, platformFee, platformFeeCollector);
}
if (liquidityBudget > 0) {
IERC20(weth).approve(poolManager, liquidityBudget);
bytes memory data = abi.encode(key, liquidityBudget, config.tokenAddress, poolId);
IPoolManager(poolManager).unlock(data);
}
_liquidityInProgress = false;
}
function unlockCallback(bytes calldata data) external override returns (bytes memory) {
require(msg.sender == poolManager, "Not PoolManager");
(PoolKey memory key, uint256 liquidityBudget, address tokenAddress, bytes32 poolId) =
abi.decode(data, (PoolKey, uint256, address, bytes32));
uint256 wethForTokenBuy = liquidityBudget / 2;
uint256 wethForLiquidity = liquidityBudget - wethForTokenBuy;
address currency1Addr = Currency.unwrap(key.currency1);
bool wethIsCurrency1 = currency1Addr == weth;
bool zeroForOne = !wethIsCurrency1;
SwapParams memory swapParams = SwapParams({
zeroForOne: zeroForOne,
amountSpecified: -int256(wethForTokenBuy),
sqrtPriceLimitX96: zeroForOne ? 4295128740 : 1461446703485210103287273052203988822378723970341
});
BalanceDelta swapDelta = IPoolManager(poolManager).swap(key, swapParams, "");
int128 swapAmount0 = int128(int256(BalanceDelta.unwrap(swapDelta)) >> 128);
int128 swapAmount1 = int128(int256(BalanceDelta.unwrap(swapDelta)));
if (swapAmount0 < 0) {
uint256 amount0Owed = uint256(uint128(-swapAmount0));
address token0 = Currency.unwrap(key.currency0);
IPoolManager(poolManager).sync(key.currency0);
IERC20(token0).safeTransfer(poolManager, amount0Owed);
IPoolManager(poolManager).settle();
}
if (swapAmount1 < 0) {
uint256 amount1Owed = uint256(uint128(-swapAmount1));
address token1 = Currency.unwrap(key.currency1);
IPoolManager(poolManager).sync(key.currency1);
IERC20(token1).safeTransfer(poolManager, amount1Owed);
IPoolManager(poolManager).settle();
}
uint256 amount0Taken = 0;
if (swapAmount0 > 0) {
amount0Taken = uint256(uint128(swapAmount0));
IPoolManager(poolManager).take(key.currency0, address(this), amount0Taken);
}
uint256 amount1Taken = 0;
if (swapAmount1 > 0) {
amount1Taken = uint256(uint128(swapAmount1));
IPoolManager(poolManager).take(key.currency1, address(this), amount1Taken);
}
uint256 tokensReceived = wethIsCurrency1 ? amount0Taken : amount1Taken;
if (wethForLiquidity > 0 && tokensReceived > 0) {
uint160 sqrtPriceAX96 = LiquidityMath.getSqrtRatioAtTick(FULL_RANGE_LOWER);
uint160 sqrtPriceBX96 = LiquidityMath.getSqrtRatioAtTick(FULL_RANGE_UPPER);
uint256 amount0Desired;
uint256 amount1Desired;
if (wethIsCurrency1) {
amount0Desired = tokensReceived;
amount1Desired = wethForLiquidity;
} else {
amount0Desired = wethForLiquidity;
amount1Desired = tokensReceived;
}
uint128 liquidity0 = LiquidityMath.getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0Desired);
uint128 liquidity1 = LiquidityMath.getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1Desired);
uint128 liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
if (liquidity > 0) {
bytes32 positionSalt = keccak256(abi.encodePacked(poolId, "LiquidityGenHook"));
ModifyLiquidityParams memory liqParams = ModifyLiquidityParams({
tickLower: FULL_RANGE_LOWER,
tickUpper: FULL_RANGE_UPPER,
liquidityDelta: int256(uint256(liquidity)),
salt: positionSalt
});
(BalanceDelta callerDelta,) = IPoolManager(poolManager).modifyLiquidity(key, liqParams, "");
int128 deltaAmount0 = BalanceDeltaLibrary.amount0(callerDelta);
int128 deltaAmount1 = BalanceDeltaLibrary.amount1(callerDelta);
uint256 actualAmount0 = 0;
uint256 actualAmount1 = 0;
if (deltaAmount0 < 0) {
actualAmount0 = uint256(-int256(deltaAmount0));
address token0 = Currency.unwrap(key.currency0);
IPoolManager(poolManager).sync(key.currency0);
IERC20(token0).safeTransfer(poolManager, actualAmount0);
IPoolManager(poolManager).settle();
}
if (deltaAmount1 < 0) {
actualAmount1 = uint256(-int256(deltaAmount1));
address token1 = Currency.unwrap(key.currency1);
IPoolManager(poolManager).sync(key.currency1);
IERC20(token1).safeTransfer(poolManager, actualAmount1);
IPoolManager(poolManager).settle();
}
uint256 wethUsed = wethIsCurrency1 ? actualAmount1 : actualAmount0;
uint256 tokensUsed = wethIsCurrency1 ? actualAmount0 : actualAmount1;
totalLiquidityAdded += wethUsed;
totalLiquidityEvents++;
emit LiquidityAdded(poolId, wethUsed, tokensUsed, liquidity);
uint256 residualWeth = wethForLiquidity > wethUsed ? wethForLiquidity - wethUsed : 0;
uint256 residualTokensAmt = tokensReceived > tokensUsed ? tokensReceived - tokensUsed : 0;
if (residualTokensAmt > 0) {
ERC20Burnable(tokenAddress).burn(residualTokensAmt);
}
if (residualWeth > 0) {
liquidityConfigs[poolId].accumulated += residualWeth;
}
if (residualTokensAmt > 0 || residualWeth > 0) {
emit ResidualsBurned(poolId, residualTokensAmt, residualWeth);
}
}
}
return "";
}
function _sqrt(uint256 x) internal pure returns (uint256 y) {
if (x == 0) return 0;
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function _getPoolId(PoolKey calldata key) internal pure returns (bytes32) {
return keccak256(abi.encode(
Currency.unwrap(key.currency0),
Currency.unwrap(key.currency1),
key.fee,
key.tickSpacing,
address(key.hooks)
));
}
function getAccumulated(bytes32 poolId) external view returns (uint256) {
return liquidityConfigs[poolId].accumulated;
}
function isThresholdReached(bytes32 poolId) external view returns (bool) {
return liquidityConfigs[poolId].accumulated >= liquidityConfigs[poolId].threshold;
}
function getWethBalance() external view returns (uint256) {
return IERC20(weth).balanceOf(address(this));
}
function getLiquidityConfig(bytes32 poolId) external view returns (LiquidityConfig memory) {
return liquidityConfigs[poolId];
}
receive() external payable {}
}
library Hooks {
struct Permissions {
bool beforeInitialize;
bool afterInitialize;
bool beforeAddLiquidity;
bool afterAddLiquidity;
bool beforeRemoveLiquidity;
bool afterRemoveLiquidity;
bool beforeSwap;
bool afterSwap;
bool beforeDonate;
bool afterDonate;
bool beforeSwapReturnDelta;
bool afterSwapReturnDelta;
bool afterAddLiquidityReturnDelta;
bool afterRemoveLiquidityReturnDelta;
}
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
@openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.20;
import {ERC20} from "../ERC20.sol";
import {Context} from "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys a `value` amount of tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 value) public virtual {
_burn(_msgSender(), value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, deducting from
* the caller's allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `value`.
*/
function burnFrom(address account, uint256 value) public virtual {
_spendAllowance(account, _msgSender(), value);
_burn(account, value);
}
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/errors/Errors.sol
// SPDX-License-Identifier: MIT
// Qian Exchange - https://qian.ag
pragma solidity ^0.8.24;
// Factory Errors
error BadRouterConfig();
error DeployDisabled();
error InsufficientDeployFee();
error InvalidFeeVault();
error InvalidConfig();
error InvalidReceiver();
error InvalidTickRange();
error NotController();
error Unauthorized();
error TransferFailed();
error MintingDisabled();
error InsufficientTokenBalance(uint256 required, uint256 available);
// Hook Registry Errors
error HookNotApproved();
error HookAlreadyConfigured();
error InvalidTaxRate();
error InvalidThreshold();
error InvalidPoolFee();
contracts/interfaces/IConfigurableHook.sol
// SPDX-License-Identifier: MIT
// Qian Exchange - https://qian.ag
pragma solidity ^0.8.24;
import "./IPoolManager.sol";
/**
* @title IConfigurableHook
* @notice Generic interface for hooks that can be configured by the factory
* @dev All hooks that want to be auto-configured by QianDTMFactoryv4 must implement this interface
*
* This allows the factory to remain hook-agnostic - new hooks can be added
* without modifying the factory contract. Each hook:
* 1. Defines its own config format (decoded from bytes)
* 2. Validates its own constraints (tax limits, thresholds, etc.)
* 3. Stores per-pool configuration
*
* Example config encoding:
* - AutoBuyBurnHook: abi.encode(uint16 buyTaxBps, uint16 sellTaxBps, uint256 threshold)
* - TaxmanHook: abi.encode(uint16 buyTaxBps, uint16 sellTaxBps)
* - FutureHook: abi.encode(param1, param2, param3, ...)
*/
interface IConfigurableHook {
/**
* @notice Configure the hook for a newly deployed token's pool
* @param poolId The pool identifier (keccak256 of PoolKey)
* @param tokenAddress The token address being configured
* @param config Hook-specific configuration data (abi.encoded)
* @dev Called by factory during deployCoin(). Must validate and store config.
* Should revert if already configured (immutability) or invalid params.
*/
function configureHook(
bytes32 poolId,
address tokenAddress,
bytes calldata config
) external;
/**
* @notice Get the pool ID from a PoolKey
* @param key The pool key
* @return poolId The computed pool identifier
*/
function getPoolId(PoolKey calldata key) external pure returns (bytes32);
/**
* @notice Check if a pool has been configured for this hook
* @param poolId The pool identifier
* @return True if the pool is configured and enabled
*/
function isConfigured(bytes32 poolId) external view returns (bool);
}
contracts/interfaces/ICurrency.sol
// SPDX-License-Identifier: MIT
// Qian Exchange - https://qian.ag
pragma solidity ^0.8.24;
/// @notice Currency type for Uniswap V4
/// Wraps an address to represent a token or native ETH
type Currency is address;
/// @notice Currency library for V4
library CurrencyLibrary {
/// @notice Wrap an address as Currency
function wrap(address token) internal pure returns (Currency) {
return Currency.wrap(token);
}
/// @notice Unwrap Currency to address
function unwrap(Currency currency) internal pure returns (address) {
return Currency.unwrap(currency);
}
/// @notice Native ETH currency
function native() internal pure returns (Currency) {
return Currency.wrap(address(0));
}
/// @notice Check if currency is native ETH
function isNative(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == address(0);
}
}
contracts/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
// Qian Exchange - https://qian.ag
pragma solidity ^0.8.24;
import "./IPoolManager.sol";
/// @notice Swap parameters for hook callbacks
struct SwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
/// @notice Uniswap V4 Hooks interface
/// Hooks can implement various callbacks to customize pool behavior
interface IHooks {
/// @notice Called before a pool is initialized
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice Called after a pool is initialized
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick) external returns (bytes4);
/// @notice Called before a swap
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData) external returns (bytes4, BeforeSwapDelta, uint24);
/// @notice Called after a swap
function afterSwap(address sender, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata hookData) external returns (bytes4, int128);
/// @notice Called before liquidity is added
function beforeAddLiquidity(address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData) external returns (bytes4);
/// @notice Called after liquidity is added
function afterAddLiquidity(address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData) external returns (bytes4, BalanceDelta);
/// @notice Called before liquidity is removed
function beforeRemoveLiquidity(address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData) external returns (bytes4);
/// @notice Called after liquidity is removed
function afterRemoveLiquidity(address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData) external returns (bytes4, BalanceDelta);
/// @notice Called before a donate
function beforeDonate(address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (bytes4);
/// @notice Called after a donate
function afterDonate(address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (bytes4);
}
/// @notice Before swap delta type - encodes (specifiedDelta, unspecifiedDelta)
type BeforeSwapDelta is int256;
contracts/interfaces/IPoolManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "./ICurrency.sol";
import "./IHooks.sol";
// BalanceDelta is a packed int256 where:
// - Upper 128 bits = amount0 (int128)
// - Lower 128 bits = amount1 (int128)
type BalanceDelta is int256;
/// @notice Library for getting amount0/amount1 from BalanceDelta
library BalanceDeltaLibrary {
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
/// @notice PoolKey identifies a V4 pool
struct PoolKey {
Currency currency0;
Currency currency1;
uint24 fee;
int24 tickSpacing;
IHooks hooks;
}
/// @notice Parameters for modifyLiquidity
struct ModifyLiquidityParams {
int24 tickLower;
int24 tickUpper;
int256 liquidityDelta;
bytes32 salt;
}
/// @notice Interface for Uniswap V4 PoolManager
interface IPoolManager {
/// @notice Initialize the state for a given pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice All interactions on the contract that account deltas require unlocking
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Sync the currency to its current balance in the PoolManager
function sync(Currency currency) external;
/// @notice Settle the currency, paying what is owed
function settle() external payable returns (uint256 paid);
/// @notice Take currency from the PoolManager
/// @param currency The currency to take
/// @param to The address to receive the currency
/// @param amount The amount to take
function take(Currency currency, address to, uint256 amount) external;
/// @notice Execute a swap
/// @param key The pool key
/// @param params The swap parameters
/// @param hookData Any data to be passed to hooks
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
}
contracts/interfaces/IUnlockCallback.sol
// SPDX-License-Identifier: MIT
// Qian Exchange - https://qian.ag
pragma solidity ^0.8.24;
/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
/// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
/// @param data The data that was passed to the call to unlock
/// @return Any data that you want to be returned from the unlock call
function unlockCallback(bytes calldata data) external returns (bytes memory);
}
contracts/interfaces/IWETH.sol
// SPDX-License-Identifier: MIT
// Qian Exchange - https://qian.ag
pragma solidity ^0.8.24;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
contracts/libraries/LiquidityMath.sol
// SPDX-License-Identifier: MIT
// Qian Exchange - https://qian.ag
pragma solidity ^0.8.24;
/// @title LiquidityMath
/// @notice Math library for calculating liquidity from amounts and tick ranges
/// @dev Similar to Uniswap V3's LiquidityAmounts library
library LiquidityMath {
/// @notice Calculates the amount of liquidity for a given amount of token0
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return uint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Calculates the amount of liquidity for a given amount of token1
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return uint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Converts a tick to sqrt price
/// @param tick The tick to convert
/// @return sqrtPriceX96 The sqrt price
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(int256(887272)), "T");
uint256 ratio = absTick & 0x1 != 0
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
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 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @title FullMath
/// @notice Math library for full precision multiplication and division
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
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
require(denominator > prod1);
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
assembly {
denominator := div(denominator, twos)
}
assembly {
prod0 := div(prod0, twos)
}
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
uint256 inv = (3 * denominator) ^ 2;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
result = prod0 * inv;
return result;
}
}
}
/// @title FixedPoint96
/// @notice Math library for fixed point arithmetic with 96 bits of precision
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.