Source Code
More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 25 from a total of 123 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Approve | 23599041 | 3 days ago | IN | 0 ETH | 0.00002861 | ||||
Approve | 23599040 | 3 days ago | IN | 0 ETH | 0.00002855 | ||||
Approve | 23543130 | 10 days ago | IN | 0 ETH | 0.00004344 | ||||
Approve | 23520459 | 13 days ago | IN | 0 ETH | 0.00043321 | ||||
Sell Strategy | 23520375 | 14 days ago | IN | 0 ETH | 0.0010122 | ||||
Set Minimum Bala... | 23520367 | 14 days ago | IN | 0 ETH | 0.00006936 | ||||
Sell Strategy | 23520352 | 14 days ago | IN | 0 ETH | 0.00292428 | ||||
Approve | 23520321 | 14 days ago | IN | 0 ETH | 0.04592614 | ||||
Approve | 23520311 | 14 days ago | IN | 0 ETH | 0.00024308 | ||||
Approve | 23520303 | 14 days ago | IN | 0 ETH | 0.000333 | ||||
Set Profit Thres... | 23520274 | 14 days ago | IN | 0 ETH | 0.00005349 | ||||
Approve | 23520236 | 14 days ago | IN | 0 ETH | 0.00033995 | ||||
Approve | 23520218 | 14 days ago | IN | 0 ETH | 0.00033806 | ||||
Approve | 23520206 | 14 days ago | IN | 0 ETH | 0.00023379 | ||||
Approve | 23520203 | 14 days ago | IN | 0 ETH | 0.00264954 | ||||
Approve | 23520193 | 14 days ago | IN | 0 ETH | 0.00023599 | ||||
Approve | 23520191 | 14 days ago | IN | 0 ETH | 0.00023814 | ||||
Approve | 23520191 | 14 days ago | IN | 0 ETH | 0.00014578 | ||||
Approve | 23520190 | 14 days ago | IN | 0 ETH | 0.00023785 | ||||
Approve | 23520190 | 14 days ago | IN | 0 ETH | 0.00033074 | ||||
Approve | 23520189 | 14 days ago | IN | 0 ETH | 0.00032378 | ||||
Approve | 23520189 | 14 days ago | IN | 0 ETH | 0.0014803 | ||||
Approve | 23520188 | 14 days ago | IN | 0 ETH | 0.00032748 | ||||
Approve | 23520187 | 14 days ago | IN | 0 ETH | 0.00023561 | ||||
Approve | 23520187 | 14 days ago | IN | 0 ETH | 0.00023561 |
Latest 25 internal transactions
Advanced mode:
Parent Transaction Hash | Method | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|---|
Deposit Taxes | 23565425 | 7 days ago | 0.00050086 ETH | ||||
Deposit Taxes | 23534579 | 12 days ago | 0.00288507 ETH | ||||
Deposit Taxes | 23521880 | 13 days ago | 0.00049806 ETH | ||||
Exact Input Sing... | 23521537 | 13 days ago | 0.01555341 ETH | ||||
Transfer | 23521537 | 13 days ago | 0.0001571 ETH | ||||
Deposit Taxes | 23521245 | 13 days ago | 0.0009029 ETH | ||||
Deposit Taxes | 23520526 | 13 days ago | 0.00770853 ETH | ||||
Deposit Taxes | 23520513 | 13 days ago | 0.00211681 ETH | ||||
Deposit Taxes | 23520451 | 13 days ago | 0.00062302 ETH | ||||
Deposit Taxes | 23520451 | 13 days ago | 0.00107746 ETH | ||||
Deposit Taxes | 23520424 | 13 days ago | 0.00002228 ETH | ||||
Deposit Taxes | 23520392 | 14 days ago | 0.00119446 ETH | ||||
Deposit Taxes | 23520380 | 14 days ago | 0.00114421 ETH | ||||
Deposit Taxes | 23520375 | 14 days ago | 0.00092082 ETH | ||||
Transfer | 23520375 | 14 days ago | 0.31828118 ETH | ||||
Transfer | 23520375 | 14 days ago | 0.31828118 ETH | ||||
Exact Input Sing... | 23520368 | 14 days ago | 0.32669362 ETH | ||||
Transfer | 23520368 | 14 days ago | 0.00329993 ETH | ||||
Deposit Taxes | 23520361 | 14 days ago | 0.00877041 ETH | ||||
Deposit Taxes | 23520361 | 14 days ago | 0.00954485 ETH | ||||
Deposit Taxes | 23520355 | 14 days ago | 0.02780278 ETH | ||||
Transfer | 23520352 | 14 days ago | 10.25789379 ETH | ||||
Transfer | 23520352 | 14 days ago | 10.25789379 ETH | ||||
Deposit Taxes | 23520324 | 14 days ago | 0.0042978 ETH | ||||
Deposit Taxes | 23520319 | 14 days ago | 0.00157004 ETH |
Cross-Chain Transactions
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
Token
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
/// SPDX-License-Identifier: MIT /// @title PunkStrategy - The Perpetual Punk Machine /// @author TokenWorks (https://token.works/) pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol"; import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol"; import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol"; import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol"; import {IPositionManager} from "@uniswap/v4-periphery/src/interfaces/IPositionManager.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Actions} from "@uniswap/v4-periphery/src/libraries/Actions.sol"; import {LiquidityAmounts} from "@uniswap/v4-periphery/src/libraries/LiquidityAmounts.sol"; import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; interface IStateView { function getSlot0(PoolId poolId) external view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee); } import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol"; import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol"; import {IUniversalRouter} from "@uniswap/universal-router/contracts/interfaces/IUniversalRouter.sol"; import {IV4Router} from "@uniswap/v4-periphery/src/interfaces/IV4Router.sol"; import { IPermit2 } from "permit2/src/interfaces/IPermit2.sol"; import { Commands } from "@uniswap/universal-router/contracts/libraries/Commands.sol"; interface IUniswapV3Pool { function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); } interface ISwapRouter02 { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); } interface INonfungiblePositionManager { struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } function factory() external view returns (address); function WETH9() external view returns (address); function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external returns (address pool); function mint(MintParams calldata params) external returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } function collect(CollectParams calldata params) external payable returns ( uint256 amount0, uint256 amount1 ); function getApproved(uint256 tokenId) external view returns (address); function isApprovedForAll(address owner, address operator) external view returns (bool); function ownerOf(uint256 tokenId) external view returns (address); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IToken { function creator() external view returns (address); } interface IWETH { function withdraw(uint256 amount) external; function deposit() external payable; } contract Token is ERC20, ERC20Burnable { address public immutable automation; address public hookAddress; uint256 public minimumBalance = 1 ether; // Configurable minimum balance uint256 public profitThreshold = 10; // Configurable profit threshold (default 10%) uint256 public slippageTolerance = 99; // Configurable slippage (default 90% = 10% slippage) bool public midSwap = false; uint256 totalTokens = 1000000000 * 10 ** decimals(); uint256 public constant MAX_SUPPLY = 1_000_000_000 * 1e18; // 1 billion tokens event ERC20TokenCreated(address tokenAddress); struct Strategy { address tokenAddress; string name; uint256 ethBought; // Total ETH spent buying this strategy uint256 ethSold; // Total ETH received from selling this strategy uint256 currentValueInETH; // Current ETH value of tokens held uint256 lastBuyAmount; // ETH amount from the last buy uint256 lastBuyTokenAmount; // Token amount from the last buy uint256 canSell; // 1 if profit threshold met, 0 if not } Strategy[] public strategies; IAllowanceTransfer constant PERMIT2 = IAllowanceTransfer(address(0x000000000022D473030F116dDEE9F6B43aC78BA3)); address public constant POSITION_MANAGER = 0xbD216513d74C8cf14cf4747E6AaA6420FF64ee9e; IPositionManager positionManager = IPositionManager(POSITION_MANAGER); address public constant POOL_MANAGER = 0x000000000004444c5dc75cB358380D2e3dE08A90; IPoolManager poolManager = IPoolManager(POOL_MANAGER); address public constant UNIVERSAL_ROUTER = 0x66a9893cC07D91D95644AEDD05D03f95e1dBA8Af; IUniversalRouter router = IUniversalRouter(UNIVERSAL_ROUTER); address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IWETH weth = IWETH(WETH); IUniswapV2Router02 public immutable uniswapRouter; address public constant SWAP_ROUTER = 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45; // SwapRouter02 uint24 private constant FEE_TIER = 0; modifier onlyAutomation() { require(msg.sender == automation, "Only automation can call this function"); _; } modifier onlyEOA() { require(msg.sender == tx.origin, "Only EOA allowed"); _; } constructor() ERC20("Gold Strategy", "XAUSTR") { automation = msg.sender; _mint(address(this), totalTokens); IUniswapV2Router02 _uniswapRouter = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapRouter = _uniswapRouter; // Add default XAU strategy strategies.push(Strategy({ tokenAddress: 0x68749665FF8D2d112Fa859AA293F07A622782F38, name: "XAU", ethBought: 0, ethSold: 0, currentValueInETH: 0, lastBuyAmount: 0, lastBuyTokenAmount: 0, canSell: 0 })); } receive() external payable {} function loadLiquidity(address _hook) external onlyAutomation returns (uint256 tokenId) { hookAddress = _hook; address tokenA = address(this); // hardcoded values specific to a single sided liquidity of 1.5 ether and 100% token supply uint160 sqrtPriceX96 = 2505411999795360582221170761428213; int24 tickLower = -887200; int24 tickUpper = 207200; IERC20 token = IERC20(tokenA); token.approve(address(PERMIT2), type(uint256).max); PERMIT2.approve(tokenA, address(POSITION_MANAGER), type(uint160).max, type(uint48).max); PERMIT2.approve(tokenA, address(POOL_MANAGER), type(uint160).max, type(uint48).max); PoolKey memory pool = PoolKey({ currency0: Currency.wrap(address(0)), currency1: Currency.wrap(address(tokenA)), fee: FEE_TIER, tickSpacing: 200, hooks: IHooks(hookAddress) }); poolManager.initialize(pool, sqrtPriceX96); uint128 liquidity = _calculateLiquidity( sqrtPriceX96, tickLower, tickUpper, 0, 1000000000000000000000000000 ); // Get the nextTokenId before minting uint256 nextId = positionManager.nextTokenId(); bytes memory actions = abi.encodePacked(uint8(Actions.MINT_POSITION), uint8(Actions.SETTLE_PAIR)); bytes memory hookData = new bytes(0); bytes[] memory params = new bytes[](2); params[0] = abi.encode( pool, tickLower, tickUpper, liquidity, 0, 1000000000000000000000000000, address(this), hookData ); params[1] = abi.encode(pool.currency0, pool.currency1); try positionManager.modifyLiquidities( abi.encode(actions, params), block.timestamp + 120 ) { tokenId = nextId; return tokenId; } catch (bytes memory reason) { assembly { revert(add(reason, 0x20), mload(reason)) } } } function setMidSwap(bool value) external { require(msg.sender == hookAddress, "Only hook"); midSwap = value; } error OnlyHook(); function depositTaxes() external payable { if (msg.sender != hookAddress && msg.sender != automation) revert OnlyHook(); uint256 amount = msg.value; } function _calculateLiquidity( uint160 sqrtPriceX96, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired ) private pure returns (uint128) { return LiquidityAmounts.getLiquidityForAmounts( sqrtPriceX96, TickMath.getSqrtPriceAtTick(tickLower), TickMath.getSqrtPriceAtTick(tickUpper), amount0Desired, amount1Desired ); } // Strategy Management Functions (Only automation) function addStrategy(address _tokenAddress, string memory _name) external onlyAutomation { strategies.push(Strategy({ tokenAddress: _tokenAddress, name: _name, ethBought: 0, ethSold: 0, currentValueInETH: 0, lastBuyAmount: 0, lastBuyTokenAmount: 0, canSell: 0 })); } function getStrategiesCount() external view returns (uint256) { return strategies.length; } function getStrategy(uint256 _id) external view returns (Strategy memory) { require(_id < strategies.length, "Strategy ID does not exist"); Strategy memory strategy = strategies[_id]; // Update current value with real-time calculation strategy.currentValueInETH = getCurrentValueInETH(_id); // Update canSell with real-time calculation strategy.canSell = _calculateCanSell(_id); return strategy; } function setMinimumBalance(uint256 _minimumBalance) external onlyAutomation { minimumBalance = _minimumBalance; } function setProfitThreshold(uint256 _profitThreshold) external onlyAutomation { profitThreshold = _profitThreshold; } function setSlippageTolerance(uint256 _slippageTolerance) external onlyAutomation { require(_slippageTolerance > 0 && _slippageTolerance <= 100, "Slippage must be between 1-100"); slippageTolerance = _slippageTolerance; } function _calculateCanSell(uint256 _strategyId) internal view returns (uint256) { if (profitThreshold == 0) { return 1; // Can always sell if threshold is 0 } uint256 lastBuy = strategies[_strategyId].lastBuyAmount; uint256 lastBuyTokens = strategies[_strategyId].lastBuyTokenAmount; if (lastBuy == 0 || lastBuyTokens == 0) { return 0; // Never bought, can't sell } // Calculate current value of only the tokens from last buy uint256 currentValueOfLastBuyTokens = simulateSell(lastBuyTokens, _strategyId); uint256 requiredValue = lastBuy * (100 + profitThreshold) / 100; return currentValueOfLastBuyTokens >= requiredValue ? 1 : 0; } function buyStrategy() public onlyEOA { require(address(this).balance >= minimumBalance, "Insufficient ETH balance"); require(strategies.length > 0, "No strategies available"); uint256 availableEth = address(this).balance; // Use ALL ETH, don't reserve any // Calculate and send 1% caller reward uint256 callerReward = availableEth * 1 / 100; if (callerReward > 0) { payable(msg.sender).transfer(callerReward); } // Use remaining 99% for strategies uint256 ethForStrategies = availableEth - callerReward; uint256 ethPerStrategy = ethForStrategies / strategies.length; require(ethPerStrategy > 0, "Insufficient ETH to split among strategies"); // Loop through all strategies and buy them for (uint256 i = 0; i < strategies.length; i++) { // Get token balance before swap to calculate tokens received uint256 tokensBefore = IERC20(strategies[i].tokenAddress).balanceOf(address(this)); ISwapRouter02(SWAP_ROUTER).exactInputSingle{ value: ethPerStrategy }( ISwapRouter02.ExactInputSingleParams({ tokenIn: WETH, tokenOut: 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, fee: 10000, recipient: address(this), // Factory receives tokens first amountIn: ethPerStrategy, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }) ); IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599).approve(address(SWAP_ROUTER), IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599).balanceOf(address(this))); ISwapRouter02(SWAP_ROUTER).exactInputSingle( ISwapRouter02.ExactInputSingleParams({ tokenIn: 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, tokenOut: strategies[i].tokenAddress, fee: 3000, recipient: address(this), // Factory receives tokens first amountIn: IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599).balanceOf(address(this)), amountOutMinimum: 0, sqrtPriceLimitX96: 0 }) ); // Calculate tokens received from this specific purchase uint256 tokensAfter = IERC20(strategies[i].tokenAddress).balanceOf(address(this)); uint256 tokensReceived = tokensAfter - tokensBefore; // Always track total ETH spent strategies[i].ethBought += ethPerStrategy; // Always accumulate - never reset on buy strategies[i].lastBuyAmount += ethPerStrategy; strategies[i].lastBuyTokenAmount += tokensReceived; } } function sellStrategy(uint256 _strategyId, uint256 manualStrategy) public onlyAutomation { //Uniswap V3 does not have a view function to determine output amounts //StrategySelling will be automated with an off chain script require(_strategyId < strategies.length, "Strategy ID does not exist"); // Check if strategy can be sold based on profit threshold require(_calculateCanSell(_strategyId) == 1, "Strategy cannot be sold - profit threshold not met"); address strategyToken = strategies[_strategyId].tokenAddress; uint256 strategyBalance = IERC20(strategyToken).balanceOf(address(this)); require(strategyBalance > 0, "No strategy tokens to sell"); // Capture ETH balance before swap uint256 ethBefore = address(this).balance; IERC20(strategyToken).approve(address(SWAP_ROUTER), strategyBalance); ISwapRouter02(SWAP_ROUTER).exactInputSingle( ISwapRouter02.ExactInputSingleParams({ tokenIn: strategyToken, tokenOut: 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, fee: 3000, recipient: address(this), // Factory receives tokens first amountIn: strategyBalance, amountOutMinimum: 0, sqrtPriceLimitX96: 0 }) ); IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599).approve(address(SWAP_ROUTER), IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599).balanceOf(address(this))); ISwapRouter02(SWAP_ROUTER).exactInputSingle( ISwapRouter02.ExactInputSingleParams({ tokenIn: 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599, tokenOut: WETH, fee: 10000, recipient: address(this), // Factory receives tokens first amountIn: IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599).balanceOf(address(this)), amountOutMinimum: 0, sqrtPriceLimitX96: 0 }) ); // Unwrap WETH to native ETH using the internal function _unwrapAllWETH(); // Calculate ETH received from this specific swap uint256 ethReceived = address(this).balance - ethBefore; // Track ETH received from selling this strategy strategies[_strategyId].ethSold += ethReceived; manualStrategy == 1 ? payable(automation).transfer(ethReceived) : _buyBack(ethReceived); // Reset lastBuyAmount and lastBuyTokenAmount since we sold all tokens strategies[_strategyId].lastBuyAmount = 0; strategies[_strategyId].lastBuyTokenAmount = 0; } function simulateSell(uint256 amountIn, uint256 _strategyId) public view returns (uint256 ethExpected) { require(_strategyId < strategies.length, "Strategy ID does not exist"); address strategyToken = strategies[_strategyId].tokenAddress; address[] memory path = new address[](2); path[0] = strategyToken; path[1] = uniswapRouter.WETH(); uint[] memory amounts = uniswapRouter.getAmountsOut(amountIn, path); ethExpected = amounts[1]; } function getCurrentValueInETH(uint256 _strategyId) public view returns (uint256 currentValue) { require(_strategyId < strategies.length, "Strategy ID does not exist"); address strategyToken = strategies[_strategyId].tokenAddress; uint256 balance = IERC20(strategyToken).balanceOf(address(this)); if (balance == 0) { return 0; } // Use simulateSell to get current ETH value of our holdings currentValue = simulateSell(balance, _strategyId); } function _executeCollect(uint256 tokenId, address tokenAddress) internal { bytes[] memory params = new bytes[](2); params[0] = abi.encode(tokenId, uint256(0), uint128(0), uint128(0), bytes("")); params[1] = abi.encode( Currency.wrap(address(0)), // ETH Currency.wrap(tokenAddress), // Token address(this) ); positionManager.modifyLiquidities{value: 0}( abi.encode( abi.encodePacked(uint8(Actions.DECREASE_LIQUIDITY), uint8(Actions.TAKE_PAIR)), params ), block.timestamp + 60 ); } function _getTokenFromPosition(uint256 tokenId) internal view returns (address tokenAddress) { (bool success, bytes memory returnData) = address(positionManager).staticcall( abi.encodeWithSelector(bytes4(keccak256("getPoolAndPositionInfo(uint256)")), tokenId) ); require(success, "Failed to get position info"); assembly { tokenAddress := mload(add(returnData, 0x40)) // Extract currency1 at offset 0x40 } require(tokenAddress != address(0), "Invalid token address"); } function _buyBack(uint256 ethAmount) internal { address tokenAddress = address(this); // Create PoolKey for ETH -> Token swap PoolKey memory pool = PoolKey({ currency0: Currency.wrap(address(0)), // ETH currency1: Currency.wrap(tokenAddress), // New token fee: FEE_TIER, tickSpacing: 200, hooks: IHooks(hookAddress) }); // Encode the Universal Router command bytes memory commands = abi.encodePacked(uint8(Commands.V4_SWAP)); bytes[] memory inputs = new bytes[](1); // Encode V4Router actions bytes memory actions = abi.encodePacked( uint8(Actions.SWAP_EXACT_IN_SINGLE), uint8(Actions.SETTLE_ALL), uint8(Actions.TAKE_ALL) ); // Prepare parameters for each action bytes[] memory params = new bytes[](3); params[0] = abi.encode( pool, // PoolKey true, // zeroForOne: ETH (currency0) -> Token (currency1) uint128(ethAmount), // amountIn uint128(0), // amountOutMinimum: 0 = no minimum requirement bytes("") // hookData ); params[1] = abi.encode(pool.currency0, ethAmount); // SETTLE_ALL params params[2] = abi.encode(pool.currency1, uint128(0)); // TAKE_ALL params // Combine actions and params into inputs inputs[0] = abi.encode(actions, params); // Execute the swap uint256 deadline = block.timestamp + 120; router.execute{value: ethAmount}(commands, inputs, deadline); // burn all the tokens IERC20 token = IERC20(tokenAddress); uint256 tokensReceived = token.balanceOf(address(this)); token.transfer(0x000000000000000000000000000000000000dEaD, tokensReceived); } // Internal function to unwrap all WETH to ETH function _unwrapAllWETH() internal { uint256 wethBalance = IERC20(WETH).balanceOf(address(this)); if (wethBalance > 0) { weth.withdraw(wethBalance); } } }
// 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); } }
// 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 sets 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); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; /// @notice Parameter struct for `ModifyLiquidity` pool operations struct ModifyLiquidityParams { // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // how to modify the liquidity int256 liquidityDelta; // a value to set if you want unique liquidity positions at the same range bytes32 salt; } /// @notice Parameter struct for `Swap` pool operations struct SwapParams { /// Whether to swap token0 for token1 or vice versa bool zeroForOne; /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut) int256 amountSpecified; /// The sqrt price at which, if reached, the swap will stop executing uint160 sqrtPriceLimitX96; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Currency} from "../types/Currency.sol"; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "./IHooks.sol"; import {IERC6909Claims} from "./external/IERC6909Claims.sol"; import {IProtocolFees} from "./IProtocolFees.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {PoolId} from "../types/PoolId.sol"; import {IExtsload} from "./IExtsload.sol"; import {IExttload} from "./IExttload.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; /// @notice Interface for the PoolManager interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload { /// @notice Thrown when a currency is not netted out after the contract is unlocked error CurrencyNotSettled(); /// @notice Thrown when trying to interact with a non-initialized pool error PoolNotInitialized(); /// @notice Thrown when unlock is called, but the contract is already unlocked error AlreadyUnlocked(); /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not error ManagerLocked(); /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow error TickSpacingTooLarge(int24 tickSpacing); /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize error TickSpacingTooSmall(int24 tickSpacing); /// @notice PoolKey must have currencies where address(currency0) < address(currency1) error CurrenciesOutOfOrderOrEqual(address currency0, address currency1); /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook, /// or on a pool that does not have a dynamic swap fee. error UnauthorizedDynamicLPFeeUpdate(); /// @notice Thrown when trying to swap amount of 0 error SwapAmountCannotBeZero(); ///@notice Thrown when native currency is passed to a non native settlement error NonzeroNativeValue(); /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta. error MustClearExactPositiveDelta(); /// @notice Emitted when a new pool is initialized /// @param id The abi encoded hash of the pool key struct for the new pool /// @param currency0 The first currency of the pool by address sort order /// @param currency1 The second currency of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param hooks The hooks contract address for the pool, or address(0) if none /// @param sqrtPriceX96 The price of the pool on initialization /// @param tick The initial tick of the pool corresponding to the initialized price event Initialize( PoolId indexed id, Currency indexed currency0, Currency indexed currency1, uint24 fee, int24 tickSpacing, IHooks hooks, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted when a liquidity position is modified /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that modified the pool /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param liquidityDelta The amount of liquidity that was added or removed /// @param salt The extra data to make positions unique event ModifyLiquidity( PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt ); /// @notice Emitted for swaps between currency0 and currency1 /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that initiated the swap call, and that received the callback /// @param amount0 The delta of the currency0 balance of the pool /// @param amount1 The delta of the currency1 balance of the pool /// @param sqrtPriceX96 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 the price of the pool after the swap /// @param fee The swap fee in hundredths of a bip event Swap( PoolId indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee ); /// @notice Emitted for donations /// @param id The abi encoded hash of the pool key struct for the pool that was donated to /// @param sender The address that initiated the donate call /// @param amount0 The amount donated in currency0 /// @param amount1 The amount donated in currency1 event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1); /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract. /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee` /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)` function unlock(bytes calldata data) external returns (bytes memory); /// @notice Initialize the state for a given pool ID /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee /// @param key The pool key for the pool to initialize /// @param sqrtPriceX96 The initial square root price /// @return tick The initial tick of the pool function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick); /// @notice Modify the liquidity for the given pool /// @dev Poke by calling with a zero liquidityDelta /// @param key The pool to modify liquidity in /// @param params The parameters for modifying the liquidity /// @param hookData The data to pass through to the add/removeLiquidity hooks /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued) /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData) external returns (BalanceDelta callerDelta, BalanceDelta feesAccrued); /// @notice Swap against the given pool /// @param key The pool to swap in /// @param params The parameters for swapping /// @param hookData The data to pass through to the swap hooks /// @return swapDelta The balance delta of the address swapping /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified. /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta. function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (BalanceDelta swapDelta); /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds. /// Donors should keep this in mind when designing donation mechanisms. /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)). /// Read the comments in `Pool.swap()` for more information about this. /// @param key The key of the pool to donate to /// @param amount0 The amount of currency0 to donate /// @param amount1 The amount of currency1 to donate /// @param hookData The data to pass through to the donate hooks /// @return BalanceDelta The delta of the caller after the donate function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (BalanceDelta); /// @notice Writes the current ERC20 balance of the specified currency to transient storage /// This is used to checkpoint balances for the manager and derive deltas for the caller. /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped /// for native tokens because the amount to settle is determined by the sent value. /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle /// native funds, this function can be called with the native currency to then be able to settle the native currency function sync(Currency currency) external; /// @notice Called by the user to net out some value owed to the user /// @dev Will revert if the requested amount is not available, consider using `mint` instead /// @dev Can also be used as a mechanism for free flash loans /// @param currency The currency to withdraw from the pool manager /// @param to The address to withdraw to /// @param amount The amount of currency to withdraw function take(Currency currency, address to, uint256 amount) external; /// @notice Called by the user to pay what is owed /// @return paid The amount of currency settled function settle() external payable returns (uint256 paid); /// @notice Called by the user to pay on behalf of another address /// @param recipient The address to credit for the payment /// @return paid The amount of currency settled function settleFor(address recipient) external payable returns (uint256 paid); /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently. /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer. /// @dev This could be used to clear a balance that is considered dust. /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared. function clear(Currency currency, uint256 amount) external; /// @notice Called by the user to move value into ERC6909 balance /// @param to The address to mint the tokens to /// @param id The currency address to mint to ERC6909s, as a uint256 /// @param amount The amount of currency to mint /// @dev The id is converted to a uint160 to correspond to a currency address /// If the upper 12 bytes are not 0, they will be 0-ed out function mint(address to, uint256 id, uint256 amount) external; /// @notice Called by the user to move value from ERC6909 balance /// @param from The address to burn the tokens from /// @param id The currency address to burn from ERC6909s, as a uint256 /// @param amount The amount of currency to burn /// @dev The id is converted to a uint160 to correspond to a currency address /// If the upper 12 bytes are not 0, they will be 0-ed out function burn(address from, uint256 id, uint256 amount) external; /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees. /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee /// @param key The key of the pool to update dynamic LP fees for /// @param newDynamicLPFee The new dynamic pool LP fee function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Currency} from "./Currency.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {PoolIdLibrary} from "./PoolId.sol"; using PoolIdLibrary for PoolKey global; /// @notice Returns the key for identifying a pool struct PoolKey { /// @notice The lower currency of the pool, sorted numerically Currency currency0; /// @notice The higher currency of the pool, sorted numerically Currency currency1; /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000 uint24 fee; /// @notice Ticks that involve positions must be a multiple of tick spacing int24 tickSpacing; /// @notice The hooks of the pool IHooks hooks; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "./PoolKey.sol"; type PoolId is bytes32; /// @notice Library for computing the ID of a pool library PoolIdLibrary { /// @notice Returns value equal to keccak256(abi.encode(poolKey)) function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) { assembly ("memory-safe") { // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes) poolId := keccak256(poolKey, 0xa0) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol"; import {CustomRevert} from "../libraries/CustomRevert.sol"; type Currency is address; using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global; using CurrencyLibrary for Currency global; function equals(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(other); } function greaterThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) > Currency.unwrap(other); } function lessThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) < Currency.unwrap(other); } function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) >= Currency.unwrap(other); } /// @title CurrencyLibrary /// @dev This library allows for transferring and holding native tokens and ERC20 tokens library CurrencyLibrary { /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails error NativeTransferFailed(); /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails error ERC20TransferFailed(); /// @notice A constant to represent the native currency Currency public constant ADDRESS_ZERO = Currency.wrap(address(0)); function transfer(Currency currency, address to, uint256 amount) internal { // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol // modified custom error selectors bool success; if (currency.isAddressZero()) { assembly ("memory-safe") { // Transfer the ETH and revert if it fails. success := call(gas(), to, amount, 0, 0, 0, 0) } // revert with NativeTransferFailed, containing the bubbled up error as an argument if (!success) { CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector); } } else { assembly ("memory-safe") { // Get a pointer to some free memory. let fmp := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument. mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type. success := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), currency, 0, fmp, 68, 0, 32) ) // Now clean the memory we used mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here } // revert with ERC20TransferFailed, containing the bubbled up error as an argument if (!success) { CustomRevert.bubbleUpAndRevertWith( Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector ); } } } function balanceOfSelf(Currency currency) internal view returns (uint256) { if (currency.isAddressZero()) { return address(this).balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this)); } } function balanceOf(Currency currency, address owner) internal view returns (uint256) { if (currency.isAddressZero()) { return owner.balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner); } } function isAddressZero(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO); } function toId(Currency currency) internal pure returns (uint256) { return uint160(Currency.unwrap(currency)); } // If the upper 12 bytes are non-zero, they will be zero-ed out // Therefore, fromId() and toId() are not inverses of each other function fromId(uint256 id) internal pure returns (Currency) { return Currency.wrap(address(uint160(id))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits /// of the address that the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. /// See the Hooks library for the full spec. /// @dev Should only be callable by the v4 PoolManager. interface IHooks { /// @notice The hook called before the state of a pool is initialized /// @param sender The initial msg.sender for the initialize call /// @param key The key for the pool being initialized /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96 /// @return bytes4 The function selector for the hook function beforeInitialize(address sender, PoolKey calldata key, 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 key The key for the pool being initialized /// @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, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick) external returns (bytes4); /// @notice The hook called before liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook function beforeAddLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta /// @param feesAccrued The fees accrued since the last time fees were collected from this position /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterAddLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeRemoveLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta /// @param feesAccrued The fees accrued since the last time fees were collected from this position /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterRemoveLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million) function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData) external returns (bytes4, BeforeSwapDelta, uint24); /// @notice The hook called after a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param delta The amount owed to the caller (positive) or owed to the pool (negative) /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterSwap( address sender, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, int128); /// @notice The hook called before donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {SafeCast} from "./SafeCast.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; import {ParseBytes} from "./ParseBytes.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits /// of the address that the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. library Hooks { using LPFeeLibrary for uint24; using Hooks for IHooks; using SafeCast for int256; using BeforeSwapDeltaLibrary for BeforeSwapDelta; using ParseBytes for bytes; using CustomRevert for bytes4; uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1); uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13; uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12; uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11; uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10; uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9; uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8; uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7; uint160 internal constant AFTER_SWAP_FLAG = 1 << 6; uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5; uint160 internal constant AFTER_DONATE_FLAG = 1 << 4; uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3; uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2; uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1; uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0; 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; } /// @notice Thrown if the address will not lead to the specified hook calls being called /// @param hooks The address of the hooks contract error HookAddressNotValid(address hooks); /// @notice Hook did not return its selector error InvalidHookResponse(); /// @notice Additional context for ERC-7751 wrapped error when a hook call fails error HookCallFailed(); /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa error HookDeltaExceedsSwapAmount(); /// @notice Utility function intended to be used in hook constructors to ensure /// the deployed hooks address causes the intended hooks to be called /// @param permissions The hooks that are intended to be called /// @dev permissions param is memory as the function will be called from constructors function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure { if ( permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG) || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG) || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG) || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG) || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG) || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG) || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG) || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG) || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG) || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) || permissions.afterRemoveLiquidityReturnDelta != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) { HookAddressNotValid.selector.revertWith(address(self)); } } /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address /// @param self The hook to verify /// @param fee The fee of the pool the hook is used with /// @return bool True if the hook address is valid function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) { // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)) { return false; } if ( !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) return false; // If there is no hook contract set, then fee cannot be dynamic // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee return address(self) == address(0) ? !fee.isDynamicFee() : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee()); } /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta /// @return result The complete data returned by the hook function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) { bool success; assembly ("memory-safe") { success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0) } // Revert with FailedHookCall, containing any error message to bubble up if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector); // The call was successful, fetch the returned data assembly ("memory-safe") { // allocate result byte array from the free memory pointer result := mload(0x40) // store new free memory pointer at the end of the array padded to 32 bytes mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f)))) // store length in memory mstore(result, returndatasize()) // copy return data to result returndatacopy(add(result, 0x20), 0, returndatasize()) } // Length must be at least 32 to contain the selector. Check expected selector and returned selector match. if (result.length < 32 || result.parseSelector() != data.parseSelector()) { InvalidHookResponse.selector.revertWith(); } } /// @notice performs a hook call using the given calldata on the given hook /// @return int256 The delta returned by the hook function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) { bytes memory result = callHook(self, data); // If this hook wasn't meant to return something, default to 0 delta if (!parseReturn) return 0; // A length of 64 bytes is required to return a bytes4, and a 32 byte delta if (result.length != 64) InvalidHookResponse.selector.revertWith(); return result.parseReturnDelta(); } /// @notice modifier to prevent calling a hook if they initiated the action modifier noSelfCall(IHooks self) { if (msg.sender != address(self)) { _; } } /// @notice calls beforeInitialize hook if permissioned and validates return value function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) { if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96))); } } /// @notice calls afterInitialize hook if permissioned and validates return value function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick) internal noSelfCall(self) { if (self.hasPermission(AFTER_INITIALIZE_FLAG)) { self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick))); } } /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value function beforeModifyLiquidity( IHooks self, PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData ) internal noSelfCall(self) { if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData))); } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData))); } } /// @notice calls afterModifyLiquidity hook if permissioned and validates return value function afterModifyLiquidity( IHooks self, PoolKey memory key, ModifyLiquidityParams memory params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) { if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA); callerDelta = delta; if (params.liquidityDelta > 0) { if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall( IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData) ), self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } else { if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall( IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData) ), self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } } /// @notice calls beforeSwap hook if permissioned and validates return value function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData) internal returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride) { amountToSwap = params.amountSpecified; if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride); if (self.hasPermission(BEFORE_SWAP_FLAG)) { bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData))); // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee if (result.length != 96) InvalidHookResponse.selector.revertWith(); // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee(); // skip this logic for the case where the hook return is 0 if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) { hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta()); // any return in unspecified is passed to the afterSwap hook for handling int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta(); // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output) if (hookDeltaSpecified != 0) { bool exactInput = amountToSwap < 0; amountToSwap += hookDeltaSpecified; if (exactInput ? amountToSwap > 0 : amountToSwap < 0) { HookDeltaExceedsSwapAmount.selector.revertWith(); } } } } } /// @notice calls afterSwap hook if permissioned and validates return value function afterSwap( IHooks self, PoolKey memory key, SwapParams memory params, BalanceDelta swapDelta, bytes calldata hookData, BeforeSwapDelta beforeSwapHookReturn ) internal returns (BalanceDelta, BalanceDelta) { if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA); int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta(); int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta(); if (self.hasPermission(AFTER_SWAP_FLAG)) { hookDeltaUnspecified += self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)), self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) ).toInt128(); } BalanceDelta hookDelta; if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) { hookDelta = (params.amountSpecified < 0 == params.zeroForOne) ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified) : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified); // the caller has to pay for (or receive) the hook's delta swapDelta = swapDelta - hookDelta; } return (swapDelta, hookDelta); } /// @notice calls beforeDonate hook if permissioned and validates return value function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_DONATE_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData))); } } /// @notice calls afterDonate hook if permissioned and validates return value function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_DONATE_FLAG)) { self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData))); } } function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) { return uint160(address(self)) & flag != 0; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeCast} from "../libraries/SafeCast.sol"; /// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0 /// and the lower 128 bits represent the amount1. type BalanceDelta is int256; using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global; using BalanceDeltaLibrary for BalanceDelta global; using SafeCast for int256; function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) { assembly ("memory-safe") { balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1)) } } function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly ("memory-safe") { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := add(a0, b0) res1 := add(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly ("memory-safe") { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := sub(a0, b0) res1 := sub(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b); } function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b); } /// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type library BalanceDeltaLibrary { /// @notice A BalanceDelta of 0 BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0); function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) { assembly ("memory-safe") { _amount0 := sar(128, balanceDelta) } } function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) { assembly ("memory-safe") { _amount1 := signextend(15, balanceDelta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {BitMath} from "./BitMath.sol"; import {CustomRevert} from "./CustomRevert.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 library TickMath { using CustomRevert for bytes4; /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK error InvalidTick(int24 tick); /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK error InvalidSqrtPrice(uint160 sqrtPriceX96); /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128 /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128 /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used int24 internal constant MAX_TICK = 887272; /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767] int24 internal constant MIN_TICK_SPACING = 1; /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767] int24 internal constant MAX_TICK_SPACING = type(int16).max; /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_PRICE = 4295128739; /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342; /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1` uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE = 1461446703485210103287273052203988822378723970342 - 4295128739 - 1; /// @notice Given a tickSpacing, compute the maximum usable tick function maxUsableTick(int24 tickSpacing) internal pure returns (int24) { unchecked { return (MAX_TICK / tickSpacing) * tickSpacing; } } /// @notice Given a tickSpacing, compute the minimum usable tick function minUsableTick(int24 tickSpacing) internal pure returns (int24) { unchecked { return (MIN_TICK / tickSpacing) * tickSpacing; } } /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0) /// at the given tick function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { unchecked { uint256 absTick; assembly ("memory-safe") { tick := signextend(2, tick) // mask = 0 if tick >= 0 else -1 (all 1s) let mask := sar(255, tick) // if tick >= 0, |tick| = tick = 0 ^ tick // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1) // either way, |tick| = mask ^ (tick + mask) absTick := xor(mask, add(mask, tick)) } if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick); // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i)) // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer // Equivalent to: // price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; // or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128 uint256 price; assembly ("memory-safe") { price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1))) } if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128; assembly ("memory-safe") { // if (tick > 0) price = type(uint256).max / price; if sgt(tick, 0) { price := div(not(0), price) } // 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 getTickAtSqrtPrice of the output price is always consistent // `sub(shl(32, 1), 1)` is `type(uint32).max` // `price + type(uint32).max` will not overflow because `price` fits in 192 bits sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1))) } } } /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96 /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96 function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) { unchecked { // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice(); // second inequality must be >= because the price can never reach the price at the max tick // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1 if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) { InvalidSqrtPrice.selector.revertWith(sqrtPriceX96); } uint256 price = uint256(sqrtPriceX96) << 32; uint256 r = price; uint256 msb = BitMath.mostSignificantBit(r); if (msb >= 128) r = price >> (msb - 127); else r = price << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly ("memory-safe") { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly ("memory-safe") { 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; // Q22.128 number // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x) int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE // is changed, this may need to be changed too int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {PositionInfo} from "../libraries/PositionInfoLibrary.sol"; import {INotifier} from "./INotifier.sol"; import {IImmutableState} from "./IImmutableState.sol"; import {IERC721Permit_v4} from "./IERC721Permit_v4.sol"; import {IEIP712_v4} from "./IEIP712_v4.sol"; import {IMulticall_v4} from "./IMulticall_v4.sol"; import {IPoolInitializer_v4} from "./IPoolInitializer_v4.sol"; import {IUnorderedNonce} from "./IUnorderedNonce.sol"; import {IPermit2Forwarder} from "./IPermit2Forwarder.sol"; /// @title IPositionManager /// @notice Interface for the PositionManager contract interface IPositionManager is INotifier, IImmutableState, IERC721Permit_v4, IEIP712_v4, IMulticall_v4, IPoolInitializer_v4, IUnorderedNonce, IPermit2Forwarder { /// @notice Thrown when the caller is not approved to modify a position error NotApproved(address caller); /// @notice Thrown when the block.timestamp exceeds the user-provided deadline error DeadlinePassed(uint256 deadline); /// @notice Thrown when calling transfer, subscribe, or unsubscribe when the PoolManager is unlocked. /// @dev This is to prevent hooks from being able to trigger notifications at the same time the position is being modified. error PoolManagerMustBeLocked(); /// @notice Unlocks Uniswap v4 PoolManager and batches actions for modifying liquidity /// @dev This is the standard entrypoint for the PositionManager /// @param unlockData is an encoding of actions, and parameters for those actions /// @param deadline is the deadline for the batched actions to be executed function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable; /// @notice Batches actions for modifying liquidity without unlocking v4 PoolManager /// @dev This must be called by a contract that has already unlocked the v4 PoolManager /// @param actions the actions to perform /// @param params the parameters to provide for the actions function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable; /// @notice Used to get the ID that will be used for the next minted liquidity position /// @return uint256 The next token ID function nextTokenId() external view returns (uint256); /// @notice Returns the liquidity of a position /// @param tokenId the ERC721 tokenId /// @return liquidity the position's liquidity, as a liquidityAmount /// @dev this value can be processed as an amount0 and amount1 by using the LiquidityAmounts library function getPositionLiquidity(uint256 tokenId) external view returns (uint128 liquidity); /// @notice Returns the pool key and position info of a position /// @param tokenId the ERC721 tokenId /// @return poolKey the pool key of the position /// @return PositionInfo a uint256 packed value holding information about the position including the range (tickLower, tickUpper) function getPoolAndPositionInfo(uint256 tokenId) external view returns (PoolKey memory, PositionInfo); /// @notice Returns the position info of a position /// @param tokenId the ERC721 tokenId /// @return a uint256 packed value holding information about the position including the range (tickLower, tickUpper) function positionInfo(uint256 tokenId) external view returns (PositionInfo); }
// 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); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Library to define different pool actions. /// @dev These are suggested common commands, however additional commands should be defined as required /// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts. library Actions { // pool actions // liquidity actions uint256 internal constant INCREASE_LIQUIDITY = 0x00; uint256 internal constant DECREASE_LIQUIDITY = 0x01; uint256 internal constant MINT_POSITION = 0x02; uint256 internal constant BURN_POSITION = 0x03; uint256 internal constant INCREASE_LIQUIDITY_FROM_DELTAS = 0x04; uint256 internal constant MINT_POSITION_FROM_DELTAS = 0x05; // swapping uint256 internal constant SWAP_EXACT_IN_SINGLE = 0x06; uint256 internal constant SWAP_EXACT_IN = 0x07; uint256 internal constant SWAP_EXACT_OUT_SINGLE = 0x08; uint256 internal constant SWAP_EXACT_OUT = 0x09; // donate // note this is not supported in the position manager or router uint256 internal constant DONATE = 0x0a; // closing deltas on the pool manager // settling uint256 internal constant SETTLE = 0x0b; uint256 internal constant SETTLE_ALL = 0x0c; uint256 internal constant SETTLE_PAIR = 0x0d; // taking uint256 internal constant TAKE = 0x0e; uint256 internal constant TAKE_ALL = 0x0f; uint256 internal constant TAKE_PORTION = 0x10; uint256 internal constant TAKE_PAIR = 0x11; uint256 internal constant CLOSE_CURRENCY = 0x12; uint256 internal constant CLEAR_OR_TAKE = 0x13; uint256 internal constant SWEEP = 0x14; uint256 internal constant WRAP = 0x15; uint256 internal constant UNWRAP = 0x16; // minting/burning 6909s to close deltas // note this is not supported in the position manager or router uint256 internal constant MINT_6909 = 0x17; uint256 internal constant BURN_6909 = 0x18; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol"; import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol"; import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol"; /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { using SafeCast for uint256; /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary /// @param sqrtPriceBX96 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 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0) internal pure returns (uint128 liquidity) { unchecked { if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96); uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96); return FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96).toUint128(); } } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary /// @param sqrtPriceBX96 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 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1) internal pure returns (uint128 liquidity) { unchecked { if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96); return FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96).toUint128(); } } /// @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 sqrtPriceX96 A sqrt price representing the current pool prices /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary /// @param sqrtPriceBX96 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 sqrtPriceX96, uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96); if (sqrtPriceX96 <= sqrtPriceAX96) { liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0); } else if (sqrtPriceX96 < sqrtPriceBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1); } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolId} from "../types/PoolId.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {Position} from "./Position.sol"; /// @notice A helper library to provide state getters that use extsload library StateLibrary { /// @notice index of pools mapping in the PoolManager bytes32 public constant POOLS_SLOT = bytes32(uint256(6)); /// @notice index of feeGrowthGlobal0X128 in Pool.State uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1; // feeGrowthGlobal1X128 offset in Pool.State = 2 /// @notice index of liquidity in Pool.State uint256 public constant LIQUIDITY_OFFSET = 3; /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks; uint256 public constant TICKS_OFFSET = 4; /// @notice index of tickBitmap mapping in Pool.State uint256 public constant TICK_BITMAP_OFFSET = 5; /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions; uint256 public constant POSITIONS_OFFSET = 6; /** * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee * @dev Corresponds to pools[poolId].slot0 * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision. * @return tick The current tick of the pool. * @return protocolFee The protocol fee of the pool. * @return lpFee The swap fee of the pool. */ function getSlot0(IPoolManager manager, PoolId poolId) internal view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); bytes32 data = manager.extsload(stateSlot); // 24 bits |24bits|24bits |24 bits|160 bits // 0x000000 |000bb8|000000 |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7 // ---------- | fee |protocolfee | tick | sqrtPriceX96 assembly ("memory-safe") { // bottom 160 bits of data sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) // next 24 bits of data tick := signextend(2, shr(160, data)) // next 24 bits of data protocolFee := and(shr(184, data), 0xFFFFFF) // last 24 bits of data lpFee := and(shr(208, data), 0xFFFFFF) } } /** * @notice Retrieves the tick information of a pool at a specific tick. * @dev Corresponds to pools[poolId].ticks[tick] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve information for. * @return liquidityGross The total position liquidity that references this tick * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) */ function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick) internal view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128 ) { bytes32 slot = _getTickInfoSlot(poolId, tick); // read all 3 words of the TickInfo struct bytes32[] memory data = manager.extsload(slot, 3); assembly ("memory-safe") { let firstWord := mload(add(data, 32)) liquidityNet := sar(128, firstWord) liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) feeGrowthOutside0X128 := mload(add(data, 64)) feeGrowthOutside1X128 := mload(add(data, 96)) } } /** * @notice Retrieves the liquidity information of a pool at a specific tick. * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve liquidity for. * @return liquidityGross The total position liquidity that references this tick * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left) */ function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick) internal view returns (uint128 liquidityGross, int128 liquidityNet) { bytes32 slot = _getTickInfoSlot(poolId, tick); bytes32 value = manager.extsload(slot); assembly ("memory-safe") { liquidityNet := sar(128, value) liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /** * @notice Retrieves the fee growth outside a tick range of a pool * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve fee growth for. * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) */ function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick) internal view returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128) { bytes32 slot = _getTickInfoSlot(poolId, tick); // offset by 1 word, since the first word is liquidityGross + liquidityNet bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2); assembly ("memory-safe") { feeGrowthOutside0X128 := mload(add(data, 32)) feeGrowthOutside1X128 := mload(add(data, 64)) } } /** * @notice Retrieves the global fee growth of a pool. * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128 * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return feeGrowthGlobal0 The global fee growth for token0. * @return feeGrowthGlobal1 The global fee growth for token1. * @dev Note that feeGrowthGlobal can be artificially inflated * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme */ function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId) internal view returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State, `uint256 feeGrowthGlobal0X128` bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET); // read the 2 words of feeGrowthGlobal bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2); assembly ("memory-safe") { feeGrowthGlobal0 := mload(add(data, 32)) feeGrowthGlobal1 := mload(add(data, 64)) } } /** * @notice Retrieves total the liquidity of a pool. * @dev Corresponds to pools[poolId].liquidity * @param manager The pool manager contract. * @param poolId The ID of the pool. * @return liquidity The liquidity of the pool. */ function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `uint128 liquidity` bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET); liquidity = uint128(uint256(manager.extsload(slot))); } /** * @notice Retrieves the tick bitmap of a pool at a specific tick. * @dev Corresponds to pools[poolId].tickBitmap[tick] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tick The tick to retrieve the bitmap for. * @return tickBitmap The bitmap of the tick. */ function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick) internal view returns (uint256 tickBitmap) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(int16 => uint256) tickBitmap;` bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET); // slot id of the mapping key: `pools[poolId].tickBitmap[tick] bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping)); tickBitmap = uint256(manager.extsload(slot)); } /** * @notice Retrieves the position information of a pool without needing to calculate the `positionId`. * @dev Corresponds to pools[poolId].positions[positionId] * @param poolId The ID of the pool. * @param owner The owner of the liquidity position. * @param tickLower The lower tick of the liquidity range. * @param tickUpper The upper tick of the liquidity range. * @param salt The bytes32 randomness to further distinguish position state. * @return liquidity The liquidity of the position. * @return feeGrowthInside0LastX128 The fee growth inside the position for token0. * @return feeGrowthInside1LastX128 The fee growth inside the position for token1. */ function getPositionInfo( IPoolManager manager, PoolId poolId, address owner, int24 tickLower, int24 tickUpper, bytes32 salt ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt); (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey); } /** * @notice Retrieves the position information of a pool at a specific position ID. * @dev Corresponds to pools[poolId].positions[positionId] * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param positionId The ID of the position. * @return liquidity The liquidity of the position. * @return feeGrowthInside0LastX128 The fee growth inside the position for token0. * @return feeGrowthInside1LastX128 The fee growth inside the position for token1. */ function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) { bytes32 slot = _getPositionInfoSlot(poolId, positionId); // read all 3 words of the Position.State struct bytes32[] memory data = manager.extsload(slot, 3); assembly ("memory-safe") { liquidity := mload(add(data, 32)) feeGrowthInside0LastX128 := mload(add(data, 64)) feeGrowthInside1LastX128 := mload(add(data, 96)) } } /** * @notice Retrieves the liquidity of a position. * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param positionId The ID of the position. * @return liquidity The liquidity of the position. */ function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId) internal view returns (uint128 liquidity) { bytes32 slot = _getPositionInfoSlot(poolId, positionId); liquidity = uint128(uint256(manager.extsload(slot))); } /** * @notice Calculate the fee growth inside a tick range of a pool * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside * @param manager The pool manager contract. * @param poolId The ID of the pool. * @param tickLower The lower tick of the range. * @param tickUpper The upper tick of the range. * @return feeGrowthInside0X128 The fee growth inside the tick range for token0. * @return feeGrowthInside1X128 The fee growth inside the tick range for token1. */ function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId); (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) = getTickFeeGrowthOutside(manager, poolId, tickLower); (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) = getTickFeeGrowthOutside(manager, poolId, tickUpper); (, int24 tickCurrent,,) = getSlot0(manager, poolId); unchecked { if (tickCurrent < tickLower) { feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } else if (tickCurrent >= tickUpper) { feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128; feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128; } else { feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128; } } } function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT)); } function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(int24 => TickInfo) ticks` bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET); // slot key of the tick key: `pools[poolId].ticks[tick] return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot)); } function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) { // slot key of Pool.State value: `pools[poolId]` bytes32 stateSlot = _getPoolStateSlot(poolId); // Pool.State: `mapping(bytes32 => Position.State) positions;` bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET); // slot of the mapping key: `pools[poolId].positions[positionId] return keccak256(abi.encodePacked(positionId, positionMapping)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IEIP712} from "./IEIP712.sol"; /// @title AllowanceTransfer /// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts /// @dev Requires user's token approval on the Permit2 contract interface IAllowanceTransfer is IEIP712 { /// @notice Thrown when an allowance on a token has expired. /// @param deadline The timestamp at which the allowed amount is no longer valid error AllowanceExpired(uint256 deadline); /// @notice Thrown when an allowance on a token has been depleted. /// @param amount The maximum amount allowed error InsufficientAllowance(uint256 amount); /// @notice Thrown when too many nonces are invalidated. error ExcessiveInvalidation(); /// @notice Emits an event when the owner successfully invalidates an ordered nonce. event NonceInvalidation( address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce ); /// @notice Emits an event when the owner successfully sets permissions on a token for the spender. event Approval( address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration ); /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender. event Permit( address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration, uint48 nonce ); /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function. event Lockdown(address indexed owner, address token, address spender); /// @notice The permit data for a token struct PermitDetails { // ERC20 token address address token; // the maximum amount allowed to spend uint160 amount; // timestamp at which a spender's token allowances become invalid uint48 expiration; // an incrementing value indexed per owner,token,and spender for each signature uint48 nonce; } /// @notice The permit message signed for a single token allowance struct PermitSingle { // the permit data for a single token alownce PermitDetails details; // address permissioned on the allowed tokens address spender; // deadline on the permit signature uint256 sigDeadline; } /// @notice The permit message signed for multiple token allowances struct PermitBatch { // the permit data for multiple token allowances PermitDetails[] details; // address permissioned on the allowed tokens address spender; // deadline on the permit signature uint256 sigDeadline; } /// @notice The saved permissions /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message /// @dev Setting amount to type(uint160).max sets an unlimited approval struct PackedAllowance { // amount allowed uint160 amount; // permission expiry uint48 expiration; // an incrementing value indexed per owner,token,and spender for each signature uint48 nonce; } /// @notice A token spender pair. struct TokenSpenderPair { // the token the spender is approved address token; // the spender address address spender; } /// @notice Details for a token transfer. struct AllowanceTransferDetails { // the owner of the token address from; // the recipient of the token address to; // the amount of the token uint160 amount; // the token to be transferred address token; } /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval. /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress] /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals. function allowance(address user, address token, address spender) external view returns (uint160 amount, uint48 expiration, uint48 nonce); /// @notice Approves the spender to use up to amount of the specified token up until the expiration /// @param token The token to approve /// @param spender The spender address to approve /// @param amount The approved amount of the token /// @param expiration The timestamp at which the approval is no longer valid /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve /// @dev Setting amount to type(uint160).max sets an unlimited approval function approve(address token, address spender, uint160 amount, uint48 expiration) external; /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce /// @param owner The owner of the tokens being approved /// @param permitSingle Data signed over by the owner specifying the terms of approval /// @param signature The owner's signature over the permit data function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external; /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce /// @param owner The owner of the tokens being approved /// @param permitBatch Data signed over by the owner specifying the terms of approval /// @param signature The owner's signature over the permit data function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external; /// @notice Transfer approved tokens from one address to another /// @param from The address to transfer from /// @param to The address of the recipient /// @param amount The amount of the token to transfer /// @param token The token address to transfer /// @dev Requires the from address to have approved at least the desired amount /// of tokens to msg.sender. function transferFrom(address from, address to, uint160 amount, address token) external; /// @notice Transfer approved tokens in a batch /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers /// @dev Requires the from addresses to have approved at least the desired amount /// of tokens to msg.sender. function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external; /// @notice Enables performing a "lockdown" of the sender's Permit2 identity /// by batch revoking approvals /// @param approvals Array of approvals to revoke. function lockdown(TokenSpenderPair[] calldata approvals) external; /// @notice Invalidate nonces for a given (token, spender) pair /// @param token The token to invalidate nonces for /// @param spender The spender to invalidate nonces for /// @param newNonce The new nonce to set. Invalidates all nonces less than it. /// @dev Can't invalidate more than 2**16 nonces per transaction. function invalidateNonces(address token, address spender, uint48 newNonce) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {CustomRevert} from "./CustomRevert.sol"; /// @notice Library of helper functions for a pools LP fee library LPFeeLibrary { using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%. error LPFeeTooLarge(uint24 fee); /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE uint24 public constant DYNAMIC_FEE_FLAG = 0x800000; /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap // only dynamic-fee pools can return a fee via the beforeSwap hook uint24 public constant OVERRIDE_FEE_FLAG = 0x400000; /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF; /// @notice the lp fee is represented in hundredths of a bip, so the max is 100% uint24 public constant MAX_LP_FEE = 1000000; /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee /// @param self The fee to check /// @return bool True of the fee is dynamic function isDynamicFee(uint24 self) internal pure returns (bool) { return self == DYNAMIC_FEE_FLAG; } /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee /// @param self The fee to check /// @return bool True of the fee is valid function isValid(uint24 self) internal pure returns (bool) { return self <= MAX_LP_FEE; } /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid /// @param self The fee to validate function validate(uint24 self) internal pure { if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self); } /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0. /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook /// @param self The fee to get the initial LP from /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid) function getInitialLPFee(uint24 self) internal pure returns (uint24) { // the initial fee for a dynamic fee pool is 0 if (self.isDynamicFee()) return 0; self.validate(); return self; } /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24) /// @param self The fee to check /// @return bool True of the fee has the override flag set function isOverride(uint24 self) internal pure returns (bool) { return self & OVERRIDE_FEE_FLAG != 0; } /// @notice returns a fee with the override flag removed /// @param self The fee to remove the override flag from /// @return fee The fee without the override flag set function removeOverrideFlag(uint24 self) internal pure returns (uint24) { return self & REMOVE_OVERRIDE_MASK; } /// @notice Removes the override flag and validates the fee (reverts if the fee is too large) /// @param self The fee to remove the override flag from, and then validate /// @return fee The fee without the override flag set (if valid) function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) { fee = self.removeOverrideFlag(); fee.validate(); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.24; interface IUniversalRouter { /// @notice Thrown when a required command has failed error ExecutionFailed(uint256 commandIndex, bytes message); /// @notice Thrown when attempting to send ETH directly to the contract error ETHNotAccepted(); /// @notice Thrown when executing commands with an expired deadline error TransactionDeadlinePassed(); /// @notice Thrown when attempting to execute commands and an incorrect number of inputs are provided error LengthMismatch(); // @notice Thrown when an address that isn't WETH tries to send ETH to the router without calldata error InvalidEthSender(); /// @notice Executes encoded commands along with provided inputs. Reverts if deadline has expired. /// @param commands A set of concatenated commands, each 1 byte in length /// @param inputs An array of byte strings containing abi encoded inputs for each command /// @param deadline The deadline by which the transaction must be executed function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; import {PathKey} from "../libraries/PathKey.sol"; import {IImmutableState} from "./IImmutableState.sol"; /// @title IV4Router /// @notice Interface for the V4Router contract interface IV4Router is IImmutableState { /// @notice Emitted when an exactInput swap does not receive its minAmountOut error V4TooLittleReceived(uint256 minAmountOutReceived, uint256 amountReceived); /// @notice Emitted when an exactOutput is asked for more than its maxAmountIn error V4TooMuchRequested(uint256 maxAmountInRequested, uint256 amountRequested); /// @notice Parameters for a single-hop exact-input swap struct ExactInputSingleParams { PoolKey poolKey; bool zeroForOne; uint128 amountIn; uint128 amountOutMinimum; bytes hookData; } /// @notice Parameters for a multi-hop exact-input swap struct ExactInputParams { Currency currencyIn; PathKey[] path; uint128 amountIn; uint128 amountOutMinimum; } /// @notice Parameters for a single-hop exact-output swap struct ExactOutputSingleParams { PoolKey poolKey; bool zeroForOne; uint128 amountOut; uint128 amountInMaximum; bytes hookData; } /// @notice Parameters for a multi-hop exact-output swap struct ExactOutputParams { Currency currencyOut; PathKey[] path; uint128 amountOut; uint128 amountInMaximum; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ISignatureTransfer} from "./ISignatureTransfer.sol"; import {IAllowanceTransfer} from "./IAllowanceTransfer.sol"; /// @notice Permit2 handles signature-based transfers in SignatureTransfer and allowance-based transfers in AllowanceTransfer. /// @dev Users must approve Permit2 before calling any of the transfer functions. interface IPermit2 is ISignatureTransfer, IAllowanceTransfer { // IPermit2 unifies the two interfaces so users have maximal flexibility with their approval. }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.24; /// @title Commands /// @notice Command Flags used to decode commands library Commands { // Masks to extract certain bits of commands bytes1 internal constant FLAG_ALLOW_REVERT = 0x80; bytes1 internal constant COMMAND_TYPE_MASK = 0x3f; // Command Types. Maximum supported command at this moment is 0x3f. // The commands are executed in nested if blocks to minimise gas consumption // Command Types where value<=0x07, executed in the first nested-if block uint256 constant V3_SWAP_EXACT_IN = 0x00; uint256 constant V3_SWAP_EXACT_OUT = 0x01; uint256 constant PERMIT2_TRANSFER_FROM = 0x02; uint256 constant PERMIT2_PERMIT_BATCH = 0x03; uint256 constant SWEEP = 0x04; uint256 constant TRANSFER = 0x05; uint256 constant PAY_PORTION = 0x06; // COMMAND_PLACEHOLDER = 0x07; // Command Types where 0x08<=value<=0x0f, executed in the second nested-if block uint256 constant V2_SWAP_EXACT_IN = 0x08; uint256 constant V2_SWAP_EXACT_OUT = 0x09; uint256 constant PERMIT2_PERMIT = 0x0a; uint256 constant WRAP_ETH = 0x0b; uint256 constant UNWRAP_WETH = 0x0c; uint256 constant PERMIT2_TRANSFER_FROM_BATCH = 0x0d; uint256 constant BALANCE_CHECK_ERC20 = 0x0e; // COMMAND_PLACEHOLDER = 0x0f; // Command Types where 0x10<=value<=0x20, executed in the third nested-if block uint256 constant V4_SWAP = 0x10; uint256 constant V3_POSITION_MANAGER_PERMIT = 0x11; uint256 constant V3_POSITION_MANAGER_CALL = 0x12; uint256 constant V4_INITIALIZE_POOL = 0x13; uint256 constant V4_POSITION_MANAGER_CALL = 0x14; // COMMAND_PLACEHOLDER = 0x15 -> 0x20 // Command Types where 0x21<=value<=0x3f uint256 constant EXECUTE_SUB_PLAN = 0x21; // COMMAND_PLACEHOLDER for 0x22 to 0x3f }
// 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; } }
// 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); }
// 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-721. * 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); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Interface for claims over a contract balance, wrapped as a ERC6909 interface IERC6909Claims { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event OperatorSet(address indexed owner, address indexed operator, bool approved); event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount); event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount); /*////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Owner balance of an id. /// @param owner The address of the owner. /// @param id The id of the token. /// @return amount The balance of the token. function balanceOf(address owner, uint256 id) external view returns (uint256 amount); /// @notice Spender allowance of an id. /// @param owner The address of the owner. /// @param spender The address of the spender. /// @param id The id of the token. /// @return amount The allowance of the token. function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount); /// @notice Checks if a spender is approved by an owner as an operator /// @param owner The address of the owner. /// @param spender The address of the spender. /// @return approved The approval status. function isOperator(address owner, address spender) external view returns (bool approved); /// @notice Transfers an amount of an id from the caller to a receiver. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always, unless the function reverts function transfer(address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Transfers an amount of an id from a sender to a receiver. /// @param sender The address of the sender. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always, unless the function reverts function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Approves an amount of an id to a spender. /// @param spender The address of the spender. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always function approve(address spender, uint256 id, uint256 amount) external returns (bool); /// @notice Sets or removes an operator for the caller. /// @param operator The address of the operator. /// @param approved The approval status. /// @return bool True, always function setOperator(address operator, bool approved) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Currency} from "../types/Currency.sol"; import {PoolId} from "../types/PoolId.sol"; import {PoolKey} from "../types/PoolKey.sol"; /// @notice Interface for all protocol-fee related functions in the pool manager interface IProtocolFees { /// @notice Thrown when protocol fee is set too high error ProtocolFeeTooLarge(uint24 fee); /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller. error InvalidCaller(); /// @notice Thrown when collectProtocolFees is attempted on a token that is synced. error ProtocolFeeCurrencySynced(); /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController. event ProtocolFeeControllerUpdated(address indexed protocolFeeController); /// @notice Emitted when the protocol fee is updated for a pool. event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee); /// @notice Given a currency address, returns the protocol fees accrued in that currency /// @param currency The currency to check /// @return amount The amount of protocol fees accrued in the currency function protocolFeesAccrued(Currency currency) external view returns (uint256 amount); /// @notice Sets the protocol fee for the given pool /// @param key The key of the pool to set a protocol fee for /// @param newProtocolFee The fee to set function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external; /// @notice Sets the protocol fee controller /// @param controller The new protocol fee controller function setProtocolFeeController(address controller) external; /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected /// @dev This will revert if the contract is unlocked /// @param recipient The address to receive the protocol fees /// @param currency The currency to withdraw /// @param amount The amount of currency to withdraw /// @return amountCollected The amount of currency successfully withdrawn function collectProtocolFees(address recipient, Currency currency, uint256 amount) external returns (uint256 amountCollected); /// @notice Returns the current protocol fee controller address /// @return address The current protocol fee controller address function protocolFeeController() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Interface for functions to access any storage slot in a contract interface IExtsload { /// @notice Called by external contracts to access granular pool state /// @param slot Key of slot to sload /// @return value The value of the slot as bytes32 function extsload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access granular pool state /// @param startSlot Key of slot to start sloading from /// @param nSlots Number of slots to load into return value /// @return values List of loaded values. function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values); /// @notice Called by external contracts to access sparse pool state /// @param slots List of slots to SLOAD from. /// @return values List of loaded values. function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; /// @notice Interface for functions to access any transient storage slot in a contract interface IExttload { /// @notice Called by external contracts to access transient storage of the contract /// @param slot Key of slot to tload /// @return value The value of the slot as bytes32 function exttload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access sparse transient pool state /// @param slots List of slots to tload /// @return values List of loaded values function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Minimal ERC20 interface for Uniswap /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3 interface IERC20Minimal { /// @notice Returns an account's balance in the 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: MIT pragma solidity ^0.8.0; /// @title Library for reverting with custom errors efficiently /// @notice Contains functions for reverting with custom errors with different argument types efficiently /// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with /// `CustomError.selector.revertWith()` /// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately library CustomRevert { /// @dev ERC-7751 error for wrapping bubbled up reverts error WrappedError(address target, bytes4 selector, bytes reason, bytes details); /// @dev Reverts with the selector of a custom error in the scratch space function revertWith(bytes4 selector) internal pure { assembly ("memory-safe") { mstore(0, selector) revert(0, 0x04) } } /// @dev Reverts with a custom error with an address argument in the scratch space function revertWith(bytes4 selector, address addr) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0, 0x24) } } /// @dev Reverts with a custom error with an int24 argument in the scratch space function revertWith(bytes4 selector, int24 value) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, signextend(2, value)) revert(0, 0x24) } } /// @dev Reverts with a custom error with a uint160 argument in the scratch space function revertWith(bytes4 selector, uint160 value) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0, 0x24) } } /// @dev Reverts with a custom error with two int24 arguments function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure { assembly ("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), signextend(2, value1)) mstore(add(fmp, 0x24), signextend(2, value2)) revert(fmp, 0x44) } } /// @dev Reverts with a custom error with two uint160 arguments function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure { assembly ("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff)) revert(fmp, 0x44) } } /// @dev Reverts with a custom error with two address arguments function revertWith(bytes4 selector, address value1, address value2) internal pure { assembly ("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff)) revert(fmp, 0x44) } } /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error /// @dev this method can be vulnerable to revert data bombs function bubbleUpAndRevertWith( address revertingContract, bytes4 revertingFunctionSelector, bytes4 additionalContext ) internal pure { bytes4 wrappedErrorSelector = WrappedError.selector; assembly ("memory-safe") { // Ensure the size of the revert data is a multiple of 32 bytes let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32) let fmp := mload(0x40) // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason mstore(fmp, wrappedErrorSelector) mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff)) mstore( add(fmp, 0x24), and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000) ) // offset revert reason mstore(add(fmp, 0x44), 0x80) // offset additional context mstore(add(fmp, 0x64), add(0xa0, encodedDataSize)) // size revert reason mstore(add(fmp, 0x84), returndatasize()) // revert reason returndatacopy(add(fmp, 0xa4), 0, returndatasize()) // size additional context mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04) // additional context mstore( add(fmp, add(0xc4, encodedDataSize)), and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000) ) revert(fmp, add(0xe4, encodedDataSize)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Return type of the beforeSwap hook. // Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook) type BeforeSwapDelta is int256; // Creates a BeforeSwapDelta from specified and unspecified function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified) pure returns (BeforeSwapDelta beforeSwapDelta) { assembly ("memory-safe") { beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified)) } } /// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type library BeforeSwapDeltaLibrary { /// @notice A BeforeSwapDelta of 0 BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0); /// extracts int128 from the upper 128 bits of the BeforeSwapDelta /// returned by beforeSwap function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) { assembly ("memory-safe") { deltaSpecified := sar(128, delta) } } /// extracts int128 from the lower 128 bits of the BeforeSwapDelta /// returned by beforeSwap and afterSwap function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) { assembly ("memory-safe") { deltaUnspecified := signextend(15, delta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {CustomRevert} from "./CustomRevert.sol"; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { using CustomRevert for bytes4; error SafeCastOverflow(); /// @notice Cast a uint256 to a uint160, revert on overflow /// @param x The uint256 to be downcasted /// @return y The downcasted integer, now type uint160 function toUint160(uint256 x) internal pure returns (uint160 y) { y = uint160(x); if (y != x) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param x The uint256 to be downcasted /// @return y The downcasted integer, now type uint128 function toUint128(uint256 x) internal pure returns (uint128 y) { y = uint128(x); if (x != y) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a int128 to a uint128, revert on overflow or underflow /// @param x The int128 to be casted /// @return y The casted integer, now type uint128 function toUint128(int128 x) internal pure returns (uint128 y) { if (x < 0) SafeCastOverflow.selector.revertWith(); y = uint128(x); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param x The int256 to be downcasted /// @return y The downcasted integer, now type int128 function toInt128(int256 x) internal pure returns (int128 y) { y = int128(x); if (y != x) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param x The uint256 to be casted /// @return y The casted integer, now type int256 function toInt256(uint256 x) internal pure returns (int256 y) { y = int256(x); if (y < 0) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a int128, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type int128 function toInt128(uint256 x) internal pure returns (int128) { if (x >= 1 << 127) SafeCastOverflow.selector.revertWith(); return int128(int256(x)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks. /// @dev parseSelector also is used to parse the expected selector /// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24). library ParseBytes { function parseSelector(bytes memory result) internal pure returns (bytes4 selector) { // equivalent: (selector,) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { selector := mload(add(result, 0x20)) } } function parseFee(bytes memory result) internal pure returns (uint24 lpFee) { // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24)); assembly ("memory-safe") { lpFee := mload(add(result, 0x60)) } } function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) { // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { hookReturn := mload(add(result, 0x40)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer /// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol) library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); assembly ("memory-safe") { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // forgefmt: disable-next-item r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020500060203020504000106050205030304010505030400000000)) } } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); assembly ("memory-safe") { // Isolate the least significant bit. x := and(x, sub(0, x)) // For the upper 3 bits of the result, use a De Bruijn-like lookup. // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/ // forgefmt: disable-next-item r := shl(5, shr(252, shl(shl(2, shr(250, mul(x, 0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))), 0x8040405543005266443200005020610674053026020000107506200176117077))) // For the lower 5 bits of the result, use a De Bruijn lookup. // forgefmt: disable-next-item r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f), 0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol"; /** * @dev PositionInfo is a packed version of solidity structure. * Using the packaged version saves gas and memory by not storing the structure fields in memory slots. * * Layout: * 200 bits poolId | 24 bits tickUpper | 24 bits tickLower | 8 bits hasSubscriber * * Fields in the direction from the least significant bit: * * A flag to know if the tokenId is subscribed to an address * uint8 hasSubscriber; * * The tickUpper of the position * int24 tickUpper; * * The tickLower of the position * int24 tickLower; * * The truncated poolId. Truncates a bytes32 value so the most signifcant (highest) 200 bits are used. * bytes25 poolId; * * Note: If more bits are needed, hasSubscriber can be a single bit. * */ type PositionInfo is uint256; using PositionInfoLibrary for PositionInfo global; library PositionInfoLibrary { PositionInfo internal constant EMPTY_POSITION_INFO = PositionInfo.wrap(0); uint256 internal constant MASK_UPPER_200_BITS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000; uint256 internal constant MASK_8_BITS = 0xFF; uint24 internal constant MASK_24_BITS = 0xFFFFFF; uint256 internal constant SET_UNSUBSCRIBE = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00; uint256 internal constant SET_SUBSCRIBE = 0x01; uint8 internal constant TICK_LOWER_OFFSET = 8; uint8 internal constant TICK_UPPER_OFFSET = 32; /// @dev This poolId is NOT compatible with the poolId used in UniswapV4 core. It is truncated to 25 bytes, and just used to lookup PoolKey in the poolKeys mapping. function poolId(PositionInfo info) internal pure returns (bytes25 _poolId) { assembly ("memory-safe") { _poolId := and(MASK_UPPER_200_BITS, info) } } function tickLower(PositionInfo info) internal pure returns (int24 _tickLower) { assembly ("memory-safe") { _tickLower := signextend(2, shr(TICK_LOWER_OFFSET, info)) } } function tickUpper(PositionInfo info) internal pure returns (int24 _tickUpper) { assembly ("memory-safe") { _tickUpper := signextend(2, shr(TICK_UPPER_OFFSET, info)) } } function hasSubscriber(PositionInfo info) internal pure returns (bool _hasSubscriber) { assembly ("memory-safe") { _hasSubscriber := and(MASK_8_BITS, info) } } /// @dev this does not actually set any storage function setSubscribe(PositionInfo info) internal pure returns (PositionInfo _info) { assembly ("memory-safe") { _info := or(info, SET_SUBSCRIBE) } } /// @dev this does not actually set any storage function setUnsubscribe(PositionInfo info) internal pure returns (PositionInfo _info) { assembly ("memory-safe") { _info := and(info, SET_UNSUBSCRIBE) } } /// @notice Creates the default PositionInfo struct /// @dev Called when minting a new position /// @param _poolKey the pool key of the position /// @param _tickLower the lower tick of the position /// @param _tickUpper the upper tick of the position /// @return info packed position info, with the truncated poolId and the hasSubscriber flag set to false function initialize(PoolKey memory _poolKey, int24 _tickLower, int24 _tickUpper) internal pure returns (PositionInfo info) { bytes25 _poolId = bytes25(PoolId.unwrap(_poolKey.toId())); assembly { info := or( or(and(MASK_UPPER_200_BITS, _poolId), shl(TICK_UPPER_OFFSET, and(MASK_24_BITS, _tickUpper))), shl(TICK_LOWER_OFFSET, and(MASK_24_BITS, _tickLower)) ) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ISubscriber} from "./ISubscriber.sol"; /// @title INotifier /// @notice Interface for the Notifier contract interface INotifier { /// @notice Thrown when unsubscribing without a subscriber error NotSubscribed(); /// @notice Thrown when a subscriber does not have code error NoCodeSubscriber(); /// @notice Thrown when a user specifies a gas limit too low to avoid valid unsubscribe notifications error GasLimitTooLow(); /// @notice Wraps the revert message of the subscriber contract on a reverting subscription error SubscriptionReverted(address subscriber, bytes reason); /// @notice Wraps the revert message of the subscriber contract on a reverting modify liquidity notification error ModifyLiquidityNotificationReverted(address subscriber, bytes reason); /// @notice Wraps the revert message of the subscriber contract on a reverting burn notification error BurnNotificationReverted(address subscriber, bytes reason); /// @notice Thrown when a tokenId already has a subscriber error AlreadySubscribed(uint256 tokenId, address subscriber); /// @notice Emitted on a successful call to subscribe event Subscription(uint256 indexed tokenId, address indexed subscriber); /// @notice Emitted on a successful call to unsubscribe event Unsubscription(uint256 indexed tokenId, address indexed subscriber); /// @notice Returns the subscriber for a respective position /// @param tokenId the ERC721 tokenId /// @return subscriber the subscriber contract function subscriber(uint256 tokenId) external view returns (ISubscriber subscriber); /// @notice Enables the subscriber to receive notifications for a respective position /// @param tokenId the ERC721 tokenId /// @param newSubscriber the address of the subscriber contract /// @param data caller-provided data that's forwarded to the subscriber contract /// @dev Calling subscribe when a position is already subscribed will revert /// @dev payable so it can be multicalled with NATIVE related actions /// @dev will revert if pool manager is locked function subscribe(uint256 tokenId, address newSubscriber, bytes calldata data) external payable; /// @notice Removes the subscriber from receiving notifications for a respective position /// @param tokenId the ERC721 tokenId /// @dev Callers must specify a high gas limit (remaining gas should be higher than unsubscriberGasLimit) such that the subscriber can be notified /// @dev payable so it can be multicalled with NATIVE related actions /// @dev Must always allow a user to unsubscribe. In the case of a malicious subscriber, a user can always unsubscribe safely, ensuring liquidity is always modifiable. /// @dev will revert if pool manager is locked function unsubscribe(uint256 tokenId) external payable; /// @notice Returns and determines the maximum allowable gas-used for notifying unsubscribe /// @return uint256 the maximum gas limit when notifying a subscriber's `notifyUnsubscribe` function function unsubscribeGasLimit() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; /// @title IImmutableState /// @notice Interface for the ImmutableState contract interface IImmutableState { /// @notice The Uniswap v4 PoolManager contract function poolManager() external view returns (IPoolManager); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IERC721Permit_v4 /// @notice Interface for the ERC721Permit_v4 contract interface IERC721Permit_v4 { error SignatureDeadlineExpired(); error NoSelfPermit(); error Unauthorized(); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word /// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v) /// @dev payable so it can be multicalled with NATIVE related actions function permit(address spender, uint256 tokenId, uint256 deadline, uint256 nonce, bytes calldata signature) external payable; /// @notice Set an operator with full permission to an owner's tokens via signature /// @param owner The address that is setting the operator /// @param operator The address that will be set as an operator for the owner /// @param approved The permission to set on the operator /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param nonce a unique value, for an owner, to prevent replay attacks; an unordered nonce where the top 248 bits correspond to a word and the bottom 8 bits calculate the bit position of the word /// @param signature Concatenated data from a valid secp256k1 signature from the holder, i.e. abi.encodePacked(r, s, v) /// @dev payable so it can be multicalled with NATIVE related actions function permitForAll( address owner, address operator, bool approved, uint256 deadline, uint256 nonce, bytes calldata signature ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IEIP712_v4 /// @notice Interface for the EIP712 contract interface IEIP712_v4 { /// @notice Returns the domain separator for the current chain. /// @return bytes32 The domain separator function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IMulticall_v4 /// @notice Interface for the Multicall_v4 contract interface IMulticall_v4 { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether. /// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}. /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; /// @title IPoolInitializer_v4 /// @notice Interface for the PoolInitializer_v4 contract interface IPoolInitializer_v4 { /// @notice Initialize a Uniswap v4 Pool /// @dev If the pool is already initialized, this function will not revert and just return type(int24).max /// @param key The PoolKey of the pool to initialize /// @param sqrtPriceX96 The initial starting price of the pool, expressed as a sqrtPriceX96 /// @return The current tick of the pool, or type(int24).max if the pool creation failed, or the pool already existed function initializePool(PoolKey calldata key, uint160 sqrtPriceX96) external payable returns (int24); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IUnorderedNonce /// @notice Interface for the UnorderedNonce contract interface IUnorderedNonce { error NonceAlreadyUsed(); /// @notice mapping of nonces consumed by each address, where a nonce is a single bit on the 256-bit bitmap /// @dev word is at most type(uint248).max function nonces(address owner, uint256 word) external view returns (uint256); /// @notice Revoke a nonce by spending it, preventing it from being used again /// @dev Used in cases where a valid nonce has not been broadcasted onchain, and the owner wants to revoke the validity of the nonce /// @dev payable so it can be multicalled with native-token related actions function revokeNonce(uint256 nonce) external payable; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol"; /// @title IPermit2Forwarder /// @notice Interface for the Permit2Forwarder contract interface IPermit2Forwarder { /// @notice allows forwarding a single permit to permit2 /// @dev this function is payable to allow multicall with NATIVE based actions /// @param owner the owner of the tokens /// @param permitSingle the permit data /// @param signature the signature of the permit; abi.encodePacked(r, s, v) /// @return err the error returned by a reverting permit call, empty if successful function permit(address owner, IAllowanceTransfer.PermitSingle calldata permitSingle, bytes calldata signature) external payable returns (bytes memory err); /// @notice allows forwarding batch permits to permit2 /// @dev this function is payable to allow multicall with NATIVE based actions /// @param owner the owner of the tokens /// @param _permitBatch a batch of approvals /// @param signature the signature of the permit; abi.encodePacked(r, s, v) /// @return err the error returned by a reverting permit call, empty if successful function permitBatch(address owner, IAllowanceTransfer.PermitBatch calldata _permitBatch, bytes calldata signature) external payable returns (bytes memory err); }
// 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 ("memory-safe") { let mm := mulmod(a, b, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { assembly ("memory-safe") { result := div(prod0, denominator) } return result; } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly ("memory-safe") { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly ("memory-safe") { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (0 - denominator) & denominator; // Divide denominator by power of two assembly ("memory-safe") { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly ("memory-safe") { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly ("memory-safe") { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the preconditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) != 0) { require(++result > 0); } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import {FullMath} from "./FullMath.sol"; import {FixedPoint128} from "./FixedPoint128.sol"; import {LiquidityMath} from "./LiquidityMath.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @title Position /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary /// @dev Positions store additional state for tracking fees owed to the position library Position { using CustomRevert for bytes4; /// @notice Cannot update a position with no liquidity error CannotUpdateEmptyPosition(); // info stored for each user's position struct State { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; } /// @notice Returns the State struct of a position, given an owner and position boundaries /// @param self The mapping containing all user positions /// @param owner The address of the position owner /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param salt A unique value to differentiate between multiple positions in the same range /// @return position The position info struct of the given owners' position function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt) internal view returns (State storage position) { bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt); position = self[positionKey]; } /// @notice A helper function to calculate the position key /// @param owner The address of the position owner /// @param tickLower the lower tick boundary of the position /// @param tickUpper the upper tick boundary of the position /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller. function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt) internal pure returns (bytes32 positionKey) { // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt)) assembly ("memory-safe") { let fmp := mload(0x40) mstore(add(fmp, 0x26), salt) // [0x26, 0x46) mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26) mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23) mstore(fmp, owner) // [0x0c, 0x20) positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes // now clean the memory we used mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt mstore(fmp, 0) // fmp held owner } } /// @notice Credits accumulated fees to a user's position /// @param self The individual position to update /// @param liquidityDelta The change in pool liquidity as a result of the position update /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries /// @return feesOwed0 The amount of currency0 owed to the position owner /// @return feesOwed1 The amount of currency1 owed to the position owner function update( State storage self, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128 ) internal returns (uint256 feesOwed0, uint256 feesOwed1) { uint128 liquidity = self.liquidity; if (liquidityDelta == 0) { // disallow pokes for 0 liquidity positions if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith(); } else { self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta); } // calculate accumulated fees. overflow in the subtraction of fee growth is expected unchecked { feesOwed0 = FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128); feesOwed1 = FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128); } // update the position self.feeGrowthInside0LastX128 = feeGrowthInside0X128; self.feeGrowthInside1LastX128 = feeGrowthInside1X128; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IEIP712 { function DOMAIN_SEPARATOR() external view returns (bytes32); }
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; struct PathKey { Currency intermediateCurrency; uint24 fee; int24 tickSpacing; IHooks hooks; bytes hookData; } using PathKeyLibrary for PathKey global; /// @title PathKey Library /// @notice Functions for working with PathKeys library PathKeyLibrary { /// @notice Get the pool and swap direction for a given PathKey /// @param params the given PathKey /// @param currencyIn the input currency /// @return poolKey the pool key of the swap /// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1 function getPoolAndSwapDirection(PathKey calldata params, Currency currencyIn) internal pure returns (PoolKey memory poolKey, bool zeroForOne) { Currency currencyOut = params.intermediateCurrency; (Currency currency0, Currency currency1) = currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn); zeroForOne = currencyIn == currency0; poolKey = PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IEIP712} from "./IEIP712.sol"; /// @title SignatureTransfer /// @notice Handles ERC20 token transfers through signature based actions /// @dev Requires user's token approval on the Permit2 contract interface ISignatureTransfer is IEIP712 { /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount /// @param maxAmount The maximum amount a spender can request to transfer error InvalidAmount(uint256 maxAmount); /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred error LengthMismatch(); /// @notice Emits an event when the owner successfully invalidates an unordered nonce. event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask); /// @notice The token and amount details for a transfer signed in the permit transfer signature struct TokenPermissions { // ERC20 token address address token; // the maximum amount that can be spent uint256 amount; } /// @notice The signed permit message for a single token transfer struct PermitTransferFrom { TokenPermissions permitted; // a unique value for every token owner's signature to prevent signature replays uint256 nonce; // deadline on the permit signature uint256 deadline; } /// @notice Specifies the recipient address and amount for batched transfers. /// @dev Recipients and amounts correspond to the index of the signed token permissions array. /// @dev Reverts if the requested amount is greater than the permitted signed amount. struct SignatureTransferDetails { // recipient address address to; // spender requested amount uint256 requestedAmount; } /// @notice Used to reconstruct the signed permit message for multiple token transfers /// @dev Do not need to pass in spender address as it is required that it is msg.sender /// @dev Note that a user still signs over a spender address struct PermitBatchTransferFrom { // the tokens and corresponding amounts permitted for a transfer TokenPermissions[] permitted; // a unique value for every token owner's signature to prevent signature replays uint256 nonce; // deadline on the permit signature uint256 deadline; } /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce /// @dev It returns a uint256 bitmap /// @dev The index, or wordPosition is capped at type(uint248).max function nonceBitmap(address, uint256) external view returns (uint256); /// @notice Transfers a token using a signed permit message /// @dev Reverts if the requested amount is greater than the permitted signed amount /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails The spender's requested transfer details for the permitted token /// @param signature The signature to verify function permitTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes calldata signature ) external; /// @notice Transfers a token using a signed permit message /// @notice Includes extra data provided by the caller to verify signature over /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition /// @dev Reverts if the requested amount is greater than the permitted signed amount /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails The spender's requested transfer details for the permitted token /// @param witness Extra data to include when checking the user signature /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash /// @param signature The signature to verify function permitWitnessTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes32 witness, string calldata witnessTypeString, bytes calldata signature ) external; /// @notice Transfers multiple tokens using a signed permit message /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails Specifies the recipient and requested amount for the token transfer /// @param signature The signature to verify function permitTransferFrom( PermitBatchTransferFrom memory permit, SignatureTransferDetails[] calldata transferDetails, address owner, bytes calldata signature ) external; /// @notice Transfers multiple tokens using a signed permit message /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition /// @notice Includes extra data provided by the caller to verify signature over /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails Specifies the recipient and requested amount for the token transfer /// @param witness Extra data to include when checking the user signature /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash /// @param signature The signature to verify function permitWitnessTransferFrom( PermitBatchTransferFrom memory permit, SignatureTransferDetails[] calldata transferDetails, address owner, bytes32 witness, string calldata witnessTypeString, bytes calldata signature ) external; /// @notice Invalidates the bits specified in mask for the bitmap at the word position /// @dev The wordPos is maxed at type(uint248).max /// @param wordPos A number to index the nonceBitmap at /// @param mask A bitmap masked against msg.sender's current bitmap at the word position function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol"; import {PositionInfo} from "../libraries/PositionInfoLibrary.sol"; /// @title ISubscriber /// @notice Interface that a Subscriber contract should implement to receive updates from the v4 position manager interface ISubscriber { /// @notice Called when a position subscribes to this subscriber contract /// @param tokenId the token ID of the position /// @param data additional data passed in by the caller function notifySubscribe(uint256 tokenId, bytes memory data) external; /// @notice Called when a position unsubscribes from the subscriber /// @dev This call's gas is capped at `unsubscribeGasLimit` (set at deployment) /// @dev Because of EIP-150, solidity may only allocate 63/64 of gasleft() /// @param tokenId the token ID of the position function notifyUnsubscribe(uint256 tokenId) external; /// @notice Called when a position is burned /// @param tokenId the token ID of the position /// @param owner the current owner of the tokenId /// @param info information about the position /// @param liquidity the amount of liquidity decreased in the position, may be 0 /// @param feesAccrued the fees accrued by the position if liquidity was decreased function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued) external; /// @notice Called when a position modifies its liquidity or collects fees /// @param tokenId the token ID of the position /// @param liquidityChange the change in liquidity on the underlying position /// @param feesAccrued the fees to be collected from the position as a result of the modifyLiquidity call /// @dev Note that feesAccrued can be artificially inflated by a malicious user /// Pools with a single liquidity position can inflate feeGrowthGlobal (and consequently feesAccrued) by donating to themselves; /// atomically donating and collecting fees within the same unlockCallback may further inflate feeGrowthGlobal/feesAccrued function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { assembly ("memory-safe") { z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y)) if shr(128, z) { // revert SafeCastOverflow() mstore(0, 0x93dafdf1) revert(0x1c, 0x04) } } } }
{ "remappings": [ "@uniswap/v4-periphery/=lib/v4-periphery/", "@uniswap/v4-core/=lib/v4-core/", "permit2/=lib/permit2/", "solady/=lib/solady/", "forge-std/=lib/forge-std/src/", "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/", "@uniswap/universal-router/=lib/universal-router/", "@uniswap/=node_modules/@uniswap/", "@ensdomains/=lib/v4-core/node_modules/@ensdomains/", "@pythnetwork/=node_modules/@pythnetwork/", "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/", "hardhat/=lib/v4-core/node_modules/hardhat/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "solmate/=lib/permit2/lib/solmate/", "universal-router/=lib/universal-router/", "v4-core/=lib/v4-core/src/", "v4-periphery/=lib/v4-periphery/src/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "cancun", "viaIR": true }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"OnlyHook","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"tokenAddress","type":"address"}],"name":"ERC20TokenCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"MAX_SUPPLY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POOL_MANAGER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"POSITION_MANAGER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SWAP_ROUTER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNIVERSAL_ROUTER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenAddress","type":"address"},{"internalType":"string","name":"_name","type":"string"}],"name":"addStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"automation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"buyStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"depositTaxes","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_strategyId","type":"uint256"}],"name":"getCurrentValueInETH","outputs":[{"internalType":"uint256","name":"currentValue","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getStrategiesCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_id","type":"uint256"}],"name":"getStrategy","outputs":[{"components":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"ethBought","type":"uint256"},{"internalType":"uint256","name":"ethSold","type":"uint256"},{"internalType":"uint256","name":"currentValueInETH","type":"uint256"},{"internalType":"uint256","name":"lastBuyAmount","type":"uint256"},{"internalType":"uint256","name":"lastBuyTokenAmount","type":"uint256"},{"internalType":"uint256","name":"canSell","type":"uint256"}],"internalType":"struct Token.Strategy","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hookAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_hook","type":"address"}],"name":"loadLiquidity","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"midSwap","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minimumBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"profitThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_strategyId","type":"uint256"},{"internalType":"uint256","name":"manualStrategy","type":"uint256"}],"name":"sellStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"value","type":"bool"}],"name":"setMidSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_minimumBalance","type":"uint256"}],"name":"setMinimumBalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_profitThreshold","type":"uint256"}],"name":"setProfitThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_slippageTolerance","type":"uint256"}],"name":"setSlippageTolerance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"_strategyId","type":"uint256"}],"name":"simulateSell","outputs":[{"internalType":"uint256","name":"ethExpected","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"slippageTolerance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"strategies","outputs":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"ethBought","type":"uint256"},{"internalType":"uint256","name":"ethSold","type":"uint256"},{"internalType":"uint256","name":"currentValueInETH","type":"uint256"},{"internalType":"uint256","name":"lastBuyAmount","type":"uint256"},{"internalType":"uint256","name":"lastBuyTokenAmount","type":"uint256"},{"internalType":"uint256","name":"canSell","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"uniswapRouter","outputs":[{"internalType":"contract IUniswapV2Router02","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
60c06040523461071a57610013604061071e565b600d81526c476f6c6420537472617465677960981b6020820152610037604061071e565b60068152652c20aaa9aa2960d11b602082015281516001600160401b03811161051a57600354600181811c91168015610710575b60208210146104fc57601f81116106ad575b50602092601f821160011461064c57928192935f92610641575b50508160011b915f199060031b1c1916176003555b80516001600160401b03811161051a57600454600181811c91168015610637575b60208210146104fc57601f81116105d4575b50602091601f8211600114610574579181925f92610569575b50508160011b915f199060031b1c1916176004555b670de0b6b3a7640000600655600a600781905560636008556009805460ff191690556b033b2e3c9fd0803ce80000009055600c80546001600160a01b031990811673bd216513d74c8cf14cf4747e6aaa6420ff64ee9e17909155600d805482166e04444c5dc75cb358380d2e3de08a90179055600e805482167366a9893cc07d91d95644aedd05d03f95e1dba8af179055600f805490911673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2179055336080523015610556576002546b033b2e3c9fd0803ce8000000810180911161054257600255305f525f60205260405f206b033b2e3c9fd0803ce800000081540190556040516b033b2e3c9fd0803ce800000081525f7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60203093a3737a250d5630b4cf539739df2c5dacb4c659f2488d60a05260405161010081016001600160401b0381118282101761051a576040527368749665ff8d2d112fa859aa293f07a622782f38815261028f604061071e565b90600382526258415560e81b602083015260208101918252604081015f8152606082015f8152608083015f815260a08401905f825260c08501925f845260e08601945f8652600b546801000000000000000081101561051a576001810180600b5581101561052e57600b5f52965160039790971b7f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db9810180546001600160a01b0319166001600160a01b03999099169890981788559751805190987f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01dba01906001600160401b03811161051a578154600181811c91168015610510575b60208210146104fc57601f81116104b7575b506020601f821160011461045257819060079a9b5f92610447575b50508160011b915f199060031b1c19161790555b5160028801555160038701555160048601555160058501555160068401555191015560405161352e908161074482396080518181816104a8015281816105e90152818161069f015281816107040152818161074c0152818161149d015281816114f40152611c84015260a051818181610c5801526127680152f35b015190505f806103b8565b601f1982169a835f52815f209b5f5b81811061049f57509160079b9c91846001959410610487575b505050811b0190556103cc565b01515f1960f88460031b161c191690555f808061047a565b838301518e556001909d019c60209384019301610461565b825f5260205f20601f830160051c810191602084106104f2575b601f0160051c01905b8181106104e7575061039d565b5f81556001016104da565b90915081906104d1565b634e487b7160e01b5f52602260045260245ffd5b90607f169061038b565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b63ec442f0560e01b5f525f60045260245ffd5b015190505f806100f8565b601f1982169260045f52805f20915f5b8581106105bc575083600195106105a4575b505050811b0160045561010d565b01515f1960f88460031b161c191690555f8080610596565b91926020600181928685015181550194019201610584565b60045f527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b601f830160051c8101916020841061062d575b601f0160051c01905b81811061062257506100df565b5f8155600101610615565b909150819061060c565b90607f16906100cd565b015190505f80610097565b601f1982169360035f52805f20915f5b868110610695575083600195961061067d575b505050811b016003556100ac565b01515f1960f88460031b161c191690555f808061066f565b9192602060018192868501518155019401920161065c565b60035f527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b601f830160051c81019160208410610706575b601f0160051c01905b8181106106fb575061007d565b5f81556001016106ee565b90915081906106e5565b90607f169061006b565b5f80fd5b6040519190601f01601f191682016001600160401b0381118382101761051a5760405256fe6080604052600436101561001a575b3615610018575f80fd5b005b5f3560e01c806306fdde03146102795780630716cd1114610274578063095ea7b31461026f578063117da1ee1461026a57806318160ddd146102655780631bea83fe1461026057806323b872dd1461025b5780632882118214610256578063313ce5671461025157806332a3cf961461024c57806332cb6b0c146102475780633446e4b41461024257806342966c681461023d57806349f961d6146102385780634d4cb4a61461023357806362308e851461022e57806370a0823114610229578063735de9f71461022457806379a687401461021f57806379cc67901461021a5780637cb9b544146102155780638f6a49a11461021057806390524c591461020b57806395d89b4114610206578063a6ee3a8414610201578063a9059cbb146101fc578063ad5c4648146101f7578063b9d1d49b146101f2578063c6005893146101ed578063ca5200a7146101e8578063cc8c4fa7146101e3578063cfc0cc34146101de578063d03153aa146101d9578063d574ea3d146101d4578063db33e291146101cf578063dd62ed3e146101ca578063e8dd7fc3146101c55763f974821a0361000e57611912565b6118e4565b611885565b611864565b6117f4565b611682565b611592565b6114cc565b611464565b611436565b611419565b6113eb565b6113c1565b61134d565b61129e565b611278565b61125b565b6111db565b611103565b610c87565b610c43565b610c09565b610be0565b610733565b6106ef565b6106d2565b610685565b61065f565b610637565b61061c565b6105cf565b610584565b610556565b610539565b61048e565b6103d1565b61039e565b6102c4565b5f91031261028857565b5f80fd5b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9060206102c192818152019061028c565b90565b34610288575f366003190112610288576040515f6003546102e4816116d4565b808452906001811690811561037a575060011461031c575b6103188361030c8185038261116d565b604051918291826102b0565b0390f35b60035f9081527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b939250905b8082106103605750909150810160200161030c6102fc565b919260018160209254838588010152019101909291610348565b60ff191660208086019190915291151560051b8401909101915061030c90506102fc565b34610288575f36600319011261028857602060ff600954166040519015158152f35b6001600160a01b0381160361028857565b34610288576040366003190112610288576004356103ee816103c0565b602435331561047b576001600160a01b0382169182156104685761042e8291335f52600160205260405f209060018060a01b03165f5260205260405f2090565b5560405190815233907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a3602060405160018152f35b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b34610288576020366003190112610288576004356104d6337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161461192f565b8015158061052e575b156104e957600855005b60405162461bcd60e51b815260206004820152601e60248201527f536c697070616765206d757374206265206265747765656e20312d31303000006044820152606490fd5b5060648111156104df565b34610288575f366003190112610288576020600254604051908152f35b34610288575f36600319011261028857602060405173bd216513d74c8cf14cf4747e6aaa6420ff64ee9e8152f35b34610288576060366003190112610288576105c46004356105a4816103c0565b6024356105b0816103c0565b604435916105bf833383612846565b6128ee565b602060405160018152f35b3461028857602036600319011261028857600435610617337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161461192f565b600755005b34610288575f36600319011261028857602060405160128152f35b34610288575f366003190112610288576005546040516001600160a01b039091168152602090f35b34610288575f3660031901126102885760206040516b033b2e3c9fd0803ce80000008152f35b34610288576020366003190112610288576004356106cd337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161461192f565b600655005b3461028857602036600319011261028857610018600435336129ea565b34610288575f366003190112610288576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610288576040366003190112610288576004356024357f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031661077f33821461192f565b61078c600b54841061198a565b6107a0600161079a85612a95565b146119d6565b6107ba6107ac846116b3565b50546001600160a01b031690565b6040516370a0823160e01b81523060048201526001600160a01b03821690602081602481855afa908115610ad1575f91610bc1575b506107fb811515611a57565b60405163095ea7b360e01b81527368b3465833fb72a70ecdf485e0e4c7bd8665fc4560048201526024810182905247939092602090849060449082905f905af1918215610ad1576108bc93602093610ba6575b5061086961085a61118f565b6001600160a01b039093168352565b732260fac5e5542a773aa44fbcfedf7c193bc2c599828401525b610bb8604083015230606083015260808201525f60a08201525f60c0820152604051809381926304e45aaf60e01b835260048301611ab8565b03815f7368b3465833fb72a70ecdf485e0e4c7bd8665fc455af18015610ad157610b89575b506040516370a0823160e01b8152306004820152602081602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa908115610ad157610961916020915f91610b6c575b506040518093819263095ea7b360e01b8352600483019190602060408401937368b3465833fb72a70ecdf485e0e4c7bd8665fc4581520152565b03815f732260fac5e5542a773aa44fbcfedf7c193bc2c5995af18015610ad157610b3f575b506040516370a0823160e01b815230600482015290602082602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa918215610ad157610a40926020915f91610b22575b506109d661118f565b732260fac5e5542a773aa44fbcfedf7c193bc2c59981529073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc282840152612710604083015230606083015260808201525f60a08201525f60c0820152604051809481926304e45aaf60e01b835260048301611ab8565b03815f7368b3465833fb72a70ecdf485e0e4c7bd8665fc455af1908115610ad157600192610a7c92610af5575b50610a76612b19565b47611b2a565b926003610a88866116b3565b5001610a95858254611b4a565b905503610adf575f8080938193828215610ad6575bf115610ad1576006610acc5f925b836005610ac4836116b3565b5001556116b3565b500155005b611a4c565b506108fc610aaa565b50610acc5f92610af0600693612c3d565b610ab8565b610b169060203d602011610b1b575b610b0e818361116d565b810190611a3d565b610a6d565b503d610b04565b610b399150823d8411610b1b57610b0e818361116d565b5f6109cd565b610b609060203d602011610b65575b610b58818361116d565b810190611aa3565b610986565b503d610b4e565b610b839150823d8411610b1b57610b0e818361116d565b5f610927565b610ba19060203d602011610b1b57610b0e818361116d565b6108e1565b610bbc90843d8611610b6557610b58818361116d565b61084e565b610bda915060203d602011610b1b57610b0e818361116d565b5f6107ef565b34610288575f3660031901126102885760206040516e04444c5dc75cb358380d2e3de08a908152f35b3461028857602036600319011261028857600435610c26816103c0565b60018060a01b03165f525f602052602060405f2054604051908152f35b34610288575f366003190112610288576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610288575f366003190112610288573233036110cb57610cac476006541115611b57565b610cb9600b541515611ba3565b47610ccd610cc682611bef565b6064900490565b90811580156110a5575b50610cee91610ce591611b2a565b600b5490611c00565b610cf9811515611c1e565b5f5b600b5481101561001857610d23610d17610d176107ac846116b3565b6001600160a01b031690565b6040516370a0823160e01b81523060048201529190602090839060249082905afa918215610ad1575f92611085575b50610dca6020610d6061118f565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28152732260fac5e5542a773aa44fbcfedf7c193bc2c5998183015261271060408201523060608201528560808201525f60a08201525f60c0820152604051809381926304e45aaf60e01b835260048301611ab8565b0381877368b3465833fb72a70ecdf485e0e4c7bd8665fc455af18015610ad157611069575b506040516370a0823160e01b8152306004820152602081602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa908115610ad157610e6e916020915f9161105257506040518093819263095ea7b360e01b8352600483019190602060408401937368b3465833fb72a70ecdf485e0e4c7bd8665fc4581520152565b03815f732260fac5e5542a773aa44fbcfedf7c193bc2c5995af18015610ad157611036575b50610ea06107ac826116b3565b6040516370a0823160e01b8152306004820152602081602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa918215610ad157610f18926020925f91611019575b50610883610ef161118f565b732260fac5e5542a773aa44fbcfedf7c193bc2c5998152926001600160a01b031683850152565b03815f7368b3465833fb72a70ecdf485e0e4c7bd8665fc455af18015610ad157610ffd575b50610f50610d17610d176107ac846116b3565b6040516370a0823160e01b815230600482015290602090829060249082905afa928315610ad157600193610f8b925f91610fdf575b50611b2a565b6002610f96836116b3565b5001610fa3858254611b4a565b90556005610fb0836116b3565b5001610fbd858254611b4a565b9055610fd76006610fcd846116b3565b5001918254611b4a565b905501610cfb565b610ff7915060203d8111610b1b57610b0e818361116d565b5f610f85565b6110149060203d8111610b1b57610b0e818361116d565b610f3d565b6110309150833d8111610b1b57610b0e818361116d565b5f610ee5565b61104d9060203d8111610b6557610b58818361116d565b610e93565b610b839150823d8111610b1b57610b0e818361116d565b6110809060203d8111610b1b57610b0e818361116d565b610def565b61109e91925060203d8111610b1b57610b0e818361116d565b905f610d52565b82905f906110c2575b5f80809381933390f115610ad1575f610cd7565b506108fc6110ae565b60405162461bcd60e51b815260206004820152601060248201526f13db9b1e481153d048185b1b1bddd95960821b6044820152606490fd5b3461028857604036600319011261028857610018600435611123816103c0565b60243590611132823383612846565b6129ea565b634e487b7160e01b5f52604160045260245ffd5b610100810190811067ffffffffffffffff82111761116857604052565b611137565b90601f8019910116810190811067ffffffffffffffff82111761116857604052565b6040519061119e60e08361116d565b565b6040519061119e6101008361116d565b6040519061119e60a08361116d565b67ffffffffffffffff811161116857601f01601f191660200190565b34610288576040366003190112610288576004356111f8816103c0565b6024359067ffffffffffffffff8211610288573660238301121561028857816004013590611225826111bf565b91611233604051938461116d565b8083523660248286010111610288576020815f92602461001897018387013784010152611c7d565b34610288575f366003190112610288576020600b54604051908152f35b34610288576020366003190112610288576020611296600435611ea7565b604051908152f35b34610288575f366003190112610288576040515f6004546112be816116d4565b808452906001811690811561037a57506001146112e5576103188361030c8185038261116d565b60045f9081527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b939250905b8082106113295750909150810160200161030c6102fc565b919260018160209254838588010152019101909291611311565b8015150361028857565b346102885760203660031901126102885760043561136a81611343565b6005546001600160a01b031633036113905760ff80196009541691151516176009555f80f35b60405162461bcd60e51b81526020600482015260096024820152684f6e6c7920686f6f6b60b81b6044820152606490fd5b34610288576040366003190112610288576105c46004356113e1816103c0565b60243590336128ee565b34610288575f36600319011261028857602060405173c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28152f35b34610288575f366003190112610288576020600654604051908152f35b34610288575f3660031901126102885760206040517368b3465833fb72a70ecdf485e0e4c7bd8665fc458152f35b5f366003190112610288576005546001600160a01b031633141580611499575b61148a57005b635a91834f60e01b5f5260045ffd5b50337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161415611484565b346102885760203660031901126102885760206112966004356114ee816103c0565b611522337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161461192f565b612200565b6020815260018060a01b03825116602082015261010060e0611558602085015183604086015261012085019061028c565b936040810151606085015260608101516080850152608081015160a085015260a081015160c085015260c081015182850152015191015290565b34610288576020366003190112610288576103186004355f60e06040516115b88161114b565b828152606060208201528260408201528260608201528260808201528260a08201528260c082015201526115ef600b54821061198a565b6115f8816116b3565b506116746116046111a0565b82546001600160a01b031681529261161e6001840161170c565b60208501526002830154604085015260038301546060850152600760048401549360808601948552600581015460a0870152600681015460c087015201549260e0850193845261166d82611ea7565b9052612a95565b905260405191829182611527565b34610288575f366003190112610288576020600854604051908152f35b634e487b7160e01b5f52603260045260245ffd5b600b548110156116cf57600b5f5260205f209060031b01905f90565b61169f565b90600182811c92168015611702575b60208310146116ee57565b634e487b7160e01b5f52602260045260245ffd5b91607f16916116e3565b9060405191825f82549261171f846116d4565b80845293600181169081156117885750600114611744575b5061119e9250038361116d565b90505f9291925260205f20905f915b81831061176c57505090602061119e928201015f611737565b6020919350806001915483858901015201910190918492611753565b90506020925061119e94915060ff191682840152151560051b8201015f611737565b94916117d69060e097949a9998959260018060a01b03168752610100602088015261010087019061028c565b9860408601526060850152608084015260a083015260c08201520152565b3461028857602036600319011261028857600435600b548110156102885761181b906116b3565b5080546001600160a01b03166103186118366001840161170c565b92600281015490600381015460048201546005830154916007600685015494015494604051988998896117aa565b34610288576040366003190112610288576020611296602435600435612719565b346102885760403660031901126102885760206118db6004356118a7816103c0565b602435906118b4826103c0565b60018060a01b03165f526001835260405f209060018060a01b03165f5260205260405f2090565b54604051908152f35b34610288575f3660031901126102885760206040517366a9893cc07d91d95644aedd05d03f95e1dba8af8152f35b34610288575f366003190112610288576020600754604051908152f35b1561193657565b60405162461bcd60e51b815260206004820152602660248201527f4f6e6c79206175746f6d6174696f6e2063616e2063616c6c20746869732066756044820152653731ba34b7b760d11b6064820152608490fd5b1561199157565b60405162461bcd60e51b815260206004820152601a60248201527f537472617465677920494420646f6573206e6f742065786973740000000000006044820152606490fd5b156119dd57565b60405162461bcd60e51b815260206004820152603260248201527f53747261746567792063616e6e6f7420626520736f6c64202d2070726f666974604482015271081d1a1c995cda1bdb19081b9bdd081b595d60721b6064820152608490fd5b90816020910312610288575190565b6040513d5f823e3d90fd5b15611a5e57565b60405162461bcd60e51b815260206004820152601a60248201527f4e6f20737472617465677920746f6b656e7320746f2073656c6c0000000000006044820152606490fd5b9081602091031261028857516102c181611343565b81516001600160a01b03908116825260208084015182169083015260408084015162ffffff16908301526060808401518216908301526080808401519083015260a0808401519083015260c092830151169181019190915260e00190565b634e487b7160e01b5f52601160045260245ffd5b91908203918211611b3757565b611b16565b9060788201809211611b3757565b91908201809211611b3757565b15611b5e57565b60405162461bcd60e51b815260206004820152601860248201527f496e73756666696369656e74204554482062616c616e636500000000000000006044820152606490fd5b15611baa57565b60405162461bcd60e51b815260206004820152601760248201527f4e6f207374726174656769657320617661696c61626c650000000000000000006044820152606490fd5b9081156001838004141715611b3757565b8115611c0a570490565b634e487b7160e01b5f52601260045260245ffd5b15611c2557565b60405162461bcd60e51b815260206004820152602a60248201527f496e73756666696369656e742045544820746f2073706c697420616d6f6e67206044820152697374726174656769657360b01b6064820152608490fd5b90611cb2337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161461192f565b60405191611cbf8361114b565b60018060a01b0316825260208201908152604082015f8152606083015f8152608084015f815260a08501905f825260c08601925f845260e08701945f8652600b546801000000000000000081101561116857806001611d219201600b556116b3565b989098611d79575188546001600160a01b0319166001600160a01b0391909116178855600796611d55905160018a01611ddb565b51600288015551600387015551600486015551600585015551600684015551910155565b634e487b7160e01b5f525f60045260245ffd5b601f8211611d9957505050565b5f5260205f20906020601f840160051c83019310611dd1575b601f0160051c01905b818110611dc6575050565b5f8155600101611dbb565b9091508190611db2565b919091825167ffffffffffffffff811161116857611e0381611dfd84546116d4565b84611d8c565b6020601f8211600114611e42578190611e339394955f92611e37575b50508160011b915f199060031b1c19161790565b9055565b015190505f80611e1f565b601f19821690611e55845f5260205f2090565b915f5b818110611e8f57509583600195969710611e77575b505050811b019055565b01515f1960f88460031b161c191690555f8080611e6d565b9192602060018192868b015181550194019201611e58565b611eb4600b54821061198a565b611ec06107ac826116b3565b6040516370a0823160e01b81523060048201529190602090839060249082905afa918215610ad1575f92611f05575b508115611eff576102c191612719565b50505f90565b611f1f91925060203d602011610b1b57610b0e818361116d565b905f611eef565b9081602091031261028857518060020b81036102885790565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b60a06d7b86bec8b03d1b4fa773ae726cf591939293611fa58160c0810196611f3f565b0152565b60405190611fb860208361116d565b5f8252565b60405190611fcc60208361116d565b5f808352366020840137565b67ffffffffffffffff81116111685760051b60200190565b60405160609190612001838261116d565b6002815291601f1901825f5b82811061201957505050565b80606060208093850101520161200d565b6040805190919061203b838261116d565b6001815291601f1901825f5b82811061205357505050565b806060602080938501015201612047565b60405160809190612075838261116d565b6003815291601f1901825f5b82811061208d57505050565b806060602080938501015201612081565b90926001600160801b03610180936120ba846102c19897611f3f565b620d899f1960a08501526203296060c08501521660e08301525f6101008301526b033b2e3c9fd0803ce80000006101208301526001600160a01b03166101408201526101608101829052019061028c565b8051156116cf5760200190565b8051600110156116cf5760400190565b8051600210156116cf5760600190565b9080602083519182815201916020808360051b8301019401925f915b83831061216357505050505090565b9091929394602080612181600193601f19868203018752895161028c565b97019301930191939290612154565b90916121a76102c19360408452604084019061028c565b916020818403910152612138565b9291906121cc60209160408652604086019061028c565b930152565b3d156121fb573d906121e2826111bf565b916121f0604051938461116d565b82523d5f602084013e565b606090565b600580546001600160a01b0319166001600160a01b039290921691909117905560405163095ea7b360e01b81526e22d473030f116ddee9f6b43ac78ba360048201525f1960248201526020816044815f305af18015610ad157612602575b506e22d473030f116ddee9f6b43ac78ba33b15610288576040516387517c4560e01b815230600482015273bd216513d74c8cf14cf4747e6aaa6420ff64ee9e60248201526001600160a01b03604482015265ffffffffffff60648201525f81608481836e22d473030f116ddee9f6b43ac78ba35af18015610ad1576125ee575b506e22d473030f116ddee9f6b43ac78ba33b15610288576040516387517c4560e01b81523060048201526e04444c5dc75cb358380d2e3de08a9060248201526001600160a01b03604482015265ffffffffffff60648201525f81608481836e22d473030f116ddee9f6b43ac78ba35af18015610ad1576125da575b5060055461236f906001600160a01b0316610d17565b6123776111b0565b5f81523060208201908152916123a4905f604084015260c860608401526001600160a01b03166080830152565b600d546123b9906001600160a01b0316610d17565b6020604051809263313b65df60e11b8252815f816123da8860048301611f82565b03925af18015610ad1576125ad575b506123f2612ecf565b600c54612407906001600160a01b0316610d17565b9160405193631d5e528f60e21b8552602085600481875afa948515610ad1575f95612586575b50604051600160f91b6020820152600d60f81b602182015260028152612519929091906124f3906124cd906124bf9061246760228761116d565b61246f611fbd565b61249e61247a611ff0565b996124906040519384923090876020860161209e565b03601f19810183528261116d565b6124a78961210b565b526124b18861210b565b50516001600160a01b031690565b92516001600160a01b031690565b604080516001600160a01b03948516602082015293909116908301528160608101612490565b6124fc84612118565b5261250683612118565b5061249060405193849260208401612190565b61252242611b3c565b823b156102885761254c925f928360405180968195829463dd46508f60e01b8452600484016121b5565b03925af1908161256c575b506102c1576125646121d1565b602081519101fd5b8061257a5f6125809361116d565b8061027e565b5f612557565b612519929195506125a59060203d602011610b1b57610b0e818361116d565b94909161242d565b6125ce9060203d6020116125d3575b6125c6818361116d565b810190611f26565b6123e9565b503d6125bc565b8061257a5f6125e89361116d565b5f612359565b8061257a5f6125fc9361116d565b5f6122de565b61261a9060203d602011610b6557610b58818361116d565b61225e565b60405160609190612630838261116d565b6002815291601f1901366020840137565b9081602091031261028857516102c1816103c0565b6020818303126102885780519067ffffffffffffffff821161028857019080601f8301121561028857815161268a81611fd8565b92612698604051948561116d565b81845260208085019260051b82010192831161028857602001905b8282106126c05750505090565b81518152602091820191016126b3565b6060602091604081019381526040838201528451809452019201905f5b8181106126fa5750505090565b82516001600160a01b03168452602093840193909201916001016126ed565b906107ac6127339161272e600b54821061198a565b6116b3565b9061275861273f61261f565b926127498461210b565b6001600160a01b039091169052565b6040516315ab88c960e31b8152917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316602084600481845afa928315610ad1576127ba5f946127d6968691612817575b5061274985612118565b60405180958194829363d06ca61f60e01b8452600484016126d0565b03915afa8015610ad1576127f1915f916127f5575b50612118565b5190565b61281191503d805f833e612809818361116d565b810190612656565b5f6127eb565b612839915060203d60201161283f575b612831818361116d565b810190612641565b5f6127b0565b503d612827565b6001600160a01b039081165f81815260016020908152604080832094861683529390529190912091929091545f198110612881575b50505050565b8181106128cd57821561047b576001600160a01b03841615610468576128c3925f526001602052039160405f209060018060a01b03165f5260205260405f2090565b555f80808061287b565b83637dc7a0d960e11b5f5260018060a01b031660045260245260445260645ffd5b916001600160a01b0383169182156129d7576001600160a01b0381169384156129c4576001600160a01b0381165f9081526020819052604090205483811061299f579161298d91612973857fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9695039160018060a01b03165f525f60205260405f2090565b556001600160a01b03165f90815260208190526040902090565b805482019055604051908152602090a3565b63391434e360e21b5f526001600160a01b03909116600452602452604482905260645ffd5b63ec442f0560e01b5f525f60045260245ffd5b634b637e8f60e11b5f525f60045260245ffd5b6001600160a01b038116919082156129d7576001600160a01b0381165f90815260208190526040902054828110612a7257917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91612a5c825f9695039160018060a01b03165f525f60205260405f2090565b55600280548290039055604051908152602090a3565b63391434e360e21b5f526001600160a01b0390911660045260245260445260645ffd5b600754908115612b12576005612aaa826116b3565b500154906006612ab9826116b3565b5001549082158015612b0a575b612b0257612ad391612719565b916064019081606411611b3757818102918183041490151715611b37576064900411612afe57600190565b5f90565b505050505f90565b508115612ac6565b5050600190565b6040516370a0823160e01b815230600482015260208160248173c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25afa908115610ad1575f91612bba575b5080612b61575b50565b600f54612b76906001600160a01b0316610d17565b803b1561028857604051632e1a7d4d60e01b815260048101929092525f908290602490829084905af18015610ad157612bac5750565b8061257a5f61119e9361116d565b612bd3915060203d602011610b1b57610b0e818361116d565b5f612b57565b6001600160801b036102c19493612bf38361012095611f3f565b600160a08401521660c08201525f60e082015281610100820152019061028c565b9392916121cc90612c2f60409360608852606088019061028c565b908682036020880152612138565b600554612c52906001600160a01b0316610d17565b612c5a6111b0565b5f815230602082019081529091612c88905f604085015260c860608501526001600160a01b03166080840152565b604051600160fc1b60208201526001815291612ca560218461116d565b612da6612cb061202a565b604051600360f91b6020820152600360fa1b6021820152600f60f81b602282015260038152909361249090612d9390612d7090612cee60238661116d565b89612d5d612d39612cfd612064565b99612490612d26612d0c611fa9565b6040519283916001600160801b0389168660208501612bd9565b612d2f8c61210b565b526124b18b61210b565b604080516001600160a01b0390921660208301528101929092528160608101612490565b612d6688612118565b526124b187612118565b604080516001600160a01b0390921660208301525f908201529182906060820190565b612d9c84612128565b5261250683612128565b612daf8261210b565b52612db98161210b565b50612dc342611b3c565b600e54909190612ddb906001600160a01b0316610d17565b90813b1561028857612e06945f9460405196879586948593630d64d59360e21b855260048501612c14565b03925af18015610ad157612ebb575b506040516370a0823160e01b815230600482015260208180602481010381305afa908115610ad157612e73916020915f91612e9e575b506040518093819263a9059cbb60e01b83526004830191906020604084019361dead81520152565b03815f305af18015610ad157612e865750565b612b5e9060203d602011610b6557610b58818361116d565b612eb59150823d8411610b1b57610b0e818361116d565b5f612e4b565b8061257a5f612ec99361116d565b5f612e15565b612edc620d899f19612fbe565b612ee862032960612fbe565b80826001600160a01b0380831690821611612fb3575b50506001600160a01b0382166d7b86bec8b03d1b4fa773ae726cf511612f29575f906102c192613328565b6001600160a01b0381166d7b86bec8b03d1b4fa773ae726cf51015612f9c576b033b2e3c9fd0803ce80000006d7b86bec8b03d1b4fa773ae726cf5612f725f612f789483613328565b936132ee565b6001600160801b0381166001600160801b038316105f14612f97575090565b905090565b6b033b2e3c9fd0803ce8000000906102c1926132ee565b915091505f80612efe565b60020b908160ff1d82810118620d89e881116132d85763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b1891600281166132bc575b600481166132a0575b60088116613284575b60108116613268575b6020811661324c575b60408116613230575b60808116613214575b61010081166131f8575b61020081166131dc575b61040081166131c0575b61080081166131a4575b6110008116613188575b612000811661316c575b6140008116613150575b6180008116613134575b620100008116613118575b6202000081166130fd575b6204000081166130e2575b62080000166130c9575b5f126130c1575b0160201c90565b5f19046130ba565b6b048a170391f7dc42444e8fa290910260801c906130b3565b6d2216e584f5fa1ea926041bedfe9890920260801c916130a9565b916e5d6af8dedb81196699c329225ee6040260801c9161309e565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c91613093565b916f31be135f97d08fd981231505542fcfa60260801c91613088565b916f70d869a156d2a1b890bb3df62baf32f70260801c9161307e565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91613074565b916fd097f3bdfd2022b8845ad8f792aa58250260801c9161306a565b916fe7159475a2c29b7443b29c7fa6e889d90260801c91613060565b916ff3392b0822b70005940c7a398e4b70f30260801c91613056565b916ff987a7253ac413176f2b074cf7815e540260801c9161304c565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91613042565b916ffe5dee046a99a2a811c461f1969c30530260801c91613038565b916fff2ea16466c96a3843ec78b326b528610260801c9161302f565b916fff973b41fa98c081472e6896dfb254c00260801c91613026565b916fffcb9843d60f6159c9db58835c9266440260801c9161301d565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613014565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c9161300b565b916ffff97272373d413259a46990580e213a0260801c91613002565b826345c3193d60e11b5f5260020b60045260245ffd5b6102c19261331d9290916001600160a01b0380831690821611613322575b90036001600160a01b03169061337c565b6134d5565b9061330c565b6102c19261331d929091906001600160a01b038082169083161161336f575b61335d6001600160a01b03828116908416613409565b9190036001600160a01b031691613452565b90613347565b1561028857565b90606082901b905f19600160601b84099282808510940393808503946133a3868511613375565b14613402578190600160601b900981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b81810291905f1982820991838084109303928084039384600160601b1115610288571461344957600160601b910990828211900360a01b910360601c1790565b50505060601c90565b91818302915f19818509938380861095039480860395613473878611613375565b146134cd579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b906001600160801b0382168092036134e957565b6393dafdf160e01b5f5260045ffdfea26469706673582212204af00d265fe97d5f4332453c78690384fa502ee224f66e6d7eb29c4d4b99141e64736f6c634300081a0033
Deployed Bytecode
0x6080604052600436101561001a575b3615610018575f80fd5b005b5f3560e01c806306fdde03146102795780630716cd1114610274578063095ea7b31461026f578063117da1ee1461026a57806318160ddd146102655780631bea83fe1461026057806323b872dd1461025b5780632882118214610256578063313ce5671461025157806332a3cf961461024c57806332cb6b0c146102475780633446e4b41461024257806342966c681461023d57806349f961d6146102385780634d4cb4a61461023357806362308e851461022e57806370a0823114610229578063735de9f71461022457806379a687401461021f57806379cc67901461021a5780637cb9b544146102155780638f6a49a11461021057806390524c591461020b57806395d89b4114610206578063a6ee3a8414610201578063a9059cbb146101fc578063ad5c4648146101f7578063b9d1d49b146101f2578063c6005893146101ed578063ca5200a7146101e8578063cc8c4fa7146101e3578063cfc0cc34146101de578063d03153aa146101d9578063d574ea3d146101d4578063db33e291146101cf578063dd62ed3e146101ca578063e8dd7fc3146101c55763f974821a0361000e57611912565b6118e4565b611885565b611864565b6117f4565b611682565b611592565b6114cc565b611464565b611436565b611419565b6113eb565b6113c1565b61134d565b61129e565b611278565b61125b565b6111db565b611103565b610c87565b610c43565b610c09565b610be0565b610733565b6106ef565b6106d2565b610685565b61065f565b610637565b61061c565b6105cf565b610584565b610556565b610539565b61048e565b6103d1565b61039e565b6102c4565b5f91031261028857565b5f80fd5b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9060206102c192818152019061028c565b90565b34610288575f366003190112610288576040515f6003546102e4816116d4565b808452906001811690811561037a575060011461031c575b6103188361030c8185038261116d565b604051918291826102b0565b0390f35b60035f9081527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b939250905b8082106103605750909150810160200161030c6102fc565b919260018160209254838588010152019101909291610348565b60ff191660208086019190915291151560051b8401909101915061030c90506102fc565b34610288575f36600319011261028857602060ff600954166040519015158152f35b6001600160a01b0381160361028857565b34610288576040366003190112610288576004356103ee816103c0565b602435331561047b576001600160a01b0382169182156104685761042e8291335f52600160205260405f209060018060a01b03165f5260205260405f2090565b5560405190815233907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a3602060405160018152f35b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b34610288576020366003190112610288576004356104d6337f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b03161461192f565b8015158061052e575b156104e957600855005b60405162461bcd60e51b815260206004820152601e60248201527f536c697070616765206d757374206265206265747765656e20312d31303000006044820152606490fd5b5060648111156104df565b34610288575f366003190112610288576020600254604051908152f35b34610288575f36600319011261028857602060405173bd216513d74c8cf14cf4747e6aaa6420ff64ee9e8152f35b34610288576060366003190112610288576105c46004356105a4816103c0565b6024356105b0816103c0565b604435916105bf833383612846565b6128ee565b602060405160018152f35b3461028857602036600319011261028857600435610617337f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b03161461192f565b600755005b34610288575f36600319011261028857602060405160128152f35b34610288575f366003190112610288576005546040516001600160a01b039091168152602090f35b34610288575f3660031901126102885760206040516b033b2e3c9fd0803ce80000008152f35b34610288576020366003190112610288576004356106cd337f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b03161461192f565b600655005b3461028857602036600319011261028857610018600435336129ea565b34610288575f366003190112610288576040517f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b03168152602090f35b34610288576040366003190112610288576004356024357f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b031661077f33821461192f565b61078c600b54841061198a565b6107a0600161079a85612a95565b146119d6565b6107ba6107ac846116b3565b50546001600160a01b031690565b6040516370a0823160e01b81523060048201526001600160a01b03821690602081602481855afa908115610ad1575f91610bc1575b506107fb811515611a57565b60405163095ea7b360e01b81527368b3465833fb72a70ecdf485e0e4c7bd8665fc4560048201526024810182905247939092602090849060449082905f905af1918215610ad1576108bc93602093610ba6575b5061086961085a61118f565b6001600160a01b039093168352565b732260fac5e5542a773aa44fbcfedf7c193bc2c599828401525b610bb8604083015230606083015260808201525f60a08201525f60c0820152604051809381926304e45aaf60e01b835260048301611ab8565b03815f7368b3465833fb72a70ecdf485e0e4c7bd8665fc455af18015610ad157610b89575b506040516370a0823160e01b8152306004820152602081602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa908115610ad157610961916020915f91610b6c575b506040518093819263095ea7b360e01b8352600483019190602060408401937368b3465833fb72a70ecdf485e0e4c7bd8665fc4581520152565b03815f732260fac5e5542a773aa44fbcfedf7c193bc2c5995af18015610ad157610b3f575b506040516370a0823160e01b815230600482015290602082602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa918215610ad157610a40926020915f91610b22575b506109d661118f565b732260fac5e5542a773aa44fbcfedf7c193bc2c59981529073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc282840152612710604083015230606083015260808201525f60a08201525f60c0820152604051809481926304e45aaf60e01b835260048301611ab8565b03815f7368b3465833fb72a70ecdf485e0e4c7bd8665fc455af1908115610ad157600192610a7c92610af5575b50610a76612b19565b47611b2a565b926003610a88866116b3565b5001610a95858254611b4a565b905503610adf575f8080938193828215610ad6575bf115610ad1576006610acc5f925b836005610ac4836116b3565b5001556116b3565b500155005b611a4c565b506108fc610aaa565b50610acc5f92610af0600693612c3d565b610ab8565b610b169060203d602011610b1b575b610b0e818361116d565b810190611a3d565b610a6d565b503d610b04565b610b399150823d8411610b1b57610b0e818361116d565b5f6109cd565b610b609060203d602011610b65575b610b58818361116d565b810190611aa3565b610986565b503d610b4e565b610b839150823d8411610b1b57610b0e818361116d565b5f610927565b610ba19060203d602011610b1b57610b0e818361116d565b6108e1565b610bbc90843d8611610b6557610b58818361116d565b61084e565b610bda915060203d602011610b1b57610b0e818361116d565b5f6107ef565b34610288575f3660031901126102885760206040516e04444c5dc75cb358380d2e3de08a908152f35b3461028857602036600319011261028857600435610c26816103c0565b60018060a01b03165f525f602052602060405f2054604051908152f35b34610288575f366003190112610288576040517f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b03168152602090f35b34610288575f366003190112610288573233036110cb57610cac476006541115611b57565b610cb9600b541515611ba3565b47610ccd610cc682611bef565b6064900490565b90811580156110a5575b50610cee91610ce591611b2a565b600b5490611c00565b610cf9811515611c1e565b5f5b600b5481101561001857610d23610d17610d176107ac846116b3565b6001600160a01b031690565b6040516370a0823160e01b81523060048201529190602090839060249082905afa918215610ad1575f92611085575b50610dca6020610d6061118f565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28152732260fac5e5542a773aa44fbcfedf7c193bc2c5998183015261271060408201523060608201528560808201525f60a08201525f60c0820152604051809381926304e45aaf60e01b835260048301611ab8565b0381877368b3465833fb72a70ecdf485e0e4c7bd8665fc455af18015610ad157611069575b506040516370a0823160e01b8152306004820152602081602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa908115610ad157610e6e916020915f9161105257506040518093819263095ea7b360e01b8352600483019190602060408401937368b3465833fb72a70ecdf485e0e4c7bd8665fc4581520152565b03815f732260fac5e5542a773aa44fbcfedf7c193bc2c5995af18015610ad157611036575b50610ea06107ac826116b3565b6040516370a0823160e01b8152306004820152602081602481732260fac5e5542a773aa44fbcfedf7c193bc2c5995afa918215610ad157610f18926020925f91611019575b50610883610ef161118f565b732260fac5e5542a773aa44fbcfedf7c193bc2c5998152926001600160a01b031683850152565b03815f7368b3465833fb72a70ecdf485e0e4c7bd8665fc455af18015610ad157610ffd575b50610f50610d17610d176107ac846116b3565b6040516370a0823160e01b815230600482015290602090829060249082905afa928315610ad157600193610f8b925f91610fdf575b50611b2a565b6002610f96836116b3565b5001610fa3858254611b4a565b90556005610fb0836116b3565b5001610fbd858254611b4a565b9055610fd76006610fcd846116b3565b5001918254611b4a565b905501610cfb565b610ff7915060203d8111610b1b57610b0e818361116d565b5f610f85565b6110149060203d8111610b1b57610b0e818361116d565b610f3d565b6110309150833d8111610b1b57610b0e818361116d565b5f610ee5565b61104d9060203d8111610b6557610b58818361116d565b610e93565b610b839150823d8111610b1b57610b0e818361116d565b6110809060203d8111610b1b57610b0e818361116d565b610def565b61109e91925060203d8111610b1b57610b0e818361116d565b905f610d52565b82905f906110c2575b5f80809381933390f115610ad1575f610cd7565b506108fc6110ae565b60405162461bcd60e51b815260206004820152601060248201526f13db9b1e481153d048185b1b1bddd95960821b6044820152606490fd5b3461028857604036600319011261028857610018600435611123816103c0565b60243590611132823383612846565b6129ea565b634e487b7160e01b5f52604160045260245ffd5b610100810190811067ffffffffffffffff82111761116857604052565b611137565b90601f8019910116810190811067ffffffffffffffff82111761116857604052565b6040519061119e60e08361116d565b565b6040519061119e6101008361116d565b6040519061119e60a08361116d565b67ffffffffffffffff811161116857601f01601f191660200190565b34610288576040366003190112610288576004356111f8816103c0565b6024359067ffffffffffffffff8211610288573660238301121561028857816004013590611225826111bf565b91611233604051938461116d565b8083523660248286010111610288576020815f92602461001897018387013784010152611c7d565b34610288575f366003190112610288576020600b54604051908152f35b34610288576020366003190112610288576020611296600435611ea7565b604051908152f35b34610288575f366003190112610288576040515f6004546112be816116d4565b808452906001811690811561037a57506001146112e5576103188361030c8185038261116d565b60045f9081527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b939250905b8082106113295750909150810160200161030c6102fc565b919260018160209254838588010152019101909291611311565b8015150361028857565b346102885760203660031901126102885760043561136a81611343565b6005546001600160a01b031633036113905760ff80196009541691151516176009555f80f35b60405162461bcd60e51b81526020600482015260096024820152684f6e6c7920686f6f6b60b81b6044820152606490fd5b34610288576040366003190112610288576105c46004356113e1816103c0565b60243590336128ee565b34610288575f36600319011261028857602060405173c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28152f35b34610288575f366003190112610288576020600654604051908152f35b34610288575f3660031901126102885760206040517368b3465833fb72a70ecdf485e0e4c7bd8665fc458152f35b5f366003190112610288576005546001600160a01b031633141580611499575b61148a57005b635a91834f60e01b5f5260045ffd5b50337f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b03161415611484565b346102885760203660031901126102885760206112966004356114ee816103c0565b611522337f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b03161461192f565b612200565b6020815260018060a01b03825116602082015261010060e0611558602085015183604086015261012085019061028c565b936040810151606085015260608101516080850152608081015160a085015260a081015160c085015260c081015182850152015191015290565b34610288576020366003190112610288576103186004355f60e06040516115b88161114b565b828152606060208201528260408201528260608201528260808201528260a08201528260c082015201526115ef600b54821061198a565b6115f8816116b3565b506116746116046111a0565b82546001600160a01b031681529261161e6001840161170c565b60208501526002830154604085015260038301546060850152600760048401549360808601948552600581015460a0870152600681015460c087015201549260e0850193845261166d82611ea7565b9052612a95565b905260405191829182611527565b34610288575f366003190112610288576020600854604051908152f35b634e487b7160e01b5f52603260045260245ffd5b600b548110156116cf57600b5f5260205f209060031b01905f90565b61169f565b90600182811c92168015611702575b60208310146116ee57565b634e487b7160e01b5f52602260045260245ffd5b91607f16916116e3565b9060405191825f82549261171f846116d4565b80845293600181169081156117885750600114611744575b5061119e9250038361116d565b90505f9291925260205f20905f915b81831061176c57505090602061119e928201015f611737565b6020919350806001915483858901015201910190918492611753565b90506020925061119e94915060ff191682840152151560051b8201015f611737565b94916117d69060e097949a9998959260018060a01b03168752610100602088015261010087019061028c565b9860408601526060850152608084015260a083015260c08201520152565b3461028857602036600319011261028857600435600b548110156102885761181b906116b3565b5080546001600160a01b03166103186118366001840161170c565b92600281015490600381015460048201546005830154916007600685015494015494604051988998896117aa565b34610288576040366003190112610288576020611296602435600435612719565b346102885760403660031901126102885760206118db6004356118a7816103c0565b602435906118b4826103c0565b60018060a01b03165f526001835260405f209060018060a01b03165f5260205260405f2090565b54604051908152f35b34610288575f3660031901126102885760206040517366a9893cc07d91d95644aedd05d03f95e1dba8af8152f35b34610288575f366003190112610288576020600754604051908152f35b1561193657565b60405162461bcd60e51b815260206004820152602660248201527f4f6e6c79206175746f6d6174696f6e2063616e2063616c6c20746869732066756044820152653731ba34b7b760d11b6064820152608490fd5b1561199157565b60405162461bcd60e51b815260206004820152601a60248201527f537472617465677920494420646f6573206e6f742065786973740000000000006044820152606490fd5b156119dd57565b60405162461bcd60e51b815260206004820152603260248201527f53747261746567792063616e6e6f7420626520736f6c64202d2070726f666974604482015271081d1a1c995cda1bdb19081b9bdd081b595d60721b6064820152608490fd5b90816020910312610288575190565b6040513d5f823e3d90fd5b15611a5e57565b60405162461bcd60e51b815260206004820152601a60248201527f4e6f20737472617465677920746f6b656e7320746f2073656c6c0000000000006044820152606490fd5b9081602091031261028857516102c181611343565b81516001600160a01b03908116825260208084015182169083015260408084015162ffffff16908301526060808401518216908301526080808401519083015260a0808401519083015260c092830151169181019190915260e00190565b634e487b7160e01b5f52601160045260245ffd5b91908203918211611b3757565b611b16565b9060788201809211611b3757565b91908201809211611b3757565b15611b5e57565b60405162461bcd60e51b815260206004820152601860248201527f496e73756666696369656e74204554482062616c616e636500000000000000006044820152606490fd5b15611baa57565b60405162461bcd60e51b815260206004820152601760248201527f4e6f207374726174656769657320617661696c61626c650000000000000000006044820152606490fd5b9081156001838004141715611b3757565b8115611c0a570490565b634e487b7160e01b5f52601260045260245ffd5b15611c2557565b60405162461bcd60e51b815260206004820152602a60248201527f496e73756666696369656e742045544820746f2073706c697420616d6f6e67206044820152697374726174656769657360b01b6064820152608490fd5b90611cb2337f0000000000000000000000001560e5709526fe8f6c942accb36a1619f6cb3b5b6001600160a01b03161461192f565b60405191611cbf8361114b565b60018060a01b0316825260208201908152604082015f8152606083015f8152608084015f815260a08501905f825260c08601925f845260e08701945f8652600b546801000000000000000081101561116857806001611d219201600b556116b3565b989098611d79575188546001600160a01b0319166001600160a01b0391909116178855600796611d55905160018a01611ddb565b51600288015551600387015551600486015551600585015551600684015551910155565b634e487b7160e01b5f525f60045260245ffd5b601f8211611d9957505050565b5f5260205f20906020601f840160051c83019310611dd1575b601f0160051c01905b818110611dc6575050565b5f8155600101611dbb565b9091508190611db2565b919091825167ffffffffffffffff811161116857611e0381611dfd84546116d4565b84611d8c565b6020601f8211600114611e42578190611e339394955f92611e37575b50508160011b915f199060031b1c19161790565b9055565b015190505f80611e1f565b601f19821690611e55845f5260205f2090565b915f5b818110611e8f57509583600195969710611e77575b505050811b019055565b01515f1960f88460031b161c191690555f8080611e6d565b9192602060018192868b015181550194019201611e58565b611eb4600b54821061198a565b611ec06107ac826116b3565b6040516370a0823160e01b81523060048201529190602090839060249082905afa918215610ad1575f92611f05575b508115611eff576102c191612719565b50505f90565b611f1f91925060203d602011610b1b57610b0e818361116d565b905f611eef565b9081602091031261028857518060020b81036102885790565b80516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116910152565b60a06d7b86bec8b03d1b4fa773ae726cf591939293611fa58160c0810196611f3f565b0152565b60405190611fb860208361116d565b5f8252565b60405190611fcc60208361116d565b5f808352366020840137565b67ffffffffffffffff81116111685760051b60200190565b60405160609190612001838261116d565b6002815291601f1901825f5b82811061201957505050565b80606060208093850101520161200d565b6040805190919061203b838261116d565b6001815291601f1901825f5b82811061205357505050565b806060602080938501015201612047565b60405160809190612075838261116d565b6003815291601f1901825f5b82811061208d57505050565b806060602080938501015201612081565b90926001600160801b03610180936120ba846102c19897611f3f565b620d899f1960a08501526203296060c08501521660e08301525f6101008301526b033b2e3c9fd0803ce80000006101208301526001600160a01b03166101408201526101608101829052019061028c565b8051156116cf5760200190565b8051600110156116cf5760400190565b8051600210156116cf5760600190565b9080602083519182815201916020808360051b8301019401925f915b83831061216357505050505090565b9091929394602080612181600193601f19868203018752895161028c565b97019301930191939290612154565b90916121a76102c19360408452604084019061028c565b916020818403910152612138565b9291906121cc60209160408652604086019061028c565b930152565b3d156121fb573d906121e2826111bf565b916121f0604051938461116d565b82523d5f602084013e565b606090565b600580546001600160a01b0319166001600160a01b039290921691909117905560405163095ea7b360e01b81526e22d473030f116ddee9f6b43ac78ba360048201525f1960248201526020816044815f305af18015610ad157612602575b506e22d473030f116ddee9f6b43ac78ba33b15610288576040516387517c4560e01b815230600482015273bd216513d74c8cf14cf4747e6aaa6420ff64ee9e60248201526001600160a01b03604482015265ffffffffffff60648201525f81608481836e22d473030f116ddee9f6b43ac78ba35af18015610ad1576125ee575b506e22d473030f116ddee9f6b43ac78ba33b15610288576040516387517c4560e01b81523060048201526e04444c5dc75cb358380d2e3de08a9060248201526001600160a01b03604482015265ffffffffffff60648201525f81608481836e22d473030f116ddee9f6b43ac78ba35af18015610ad1576125da575b5060055461236f906001600160a01b0316610d17565b6123776111b0565b5f81523060208201908152916123a4905f604084015260c860608401526001600160a01b03166080830152565b600d546123b9906001600160a01b0316610d17565b6020604051809263313b65df60e11b8252815f816123da8860048301611f82565b03925af18015610ad1576125ad575b506123f2612ecf565b600c54612407906001600160a01b0316610d17565b9160405193631d5e528f60e21b8552602085600481875afa948515610ad1575f95612586575b50604051600160f91b6020820152600d60f81b602182015260028152612519929091906124f3906124cd906124bf9061246760228761116d565b61246f611fbd565b61249e61247a611ff0565b996124906040519384923090876020860161209e565b03601f19810183528261116d565b6124a78961210b565b526124b18861210b565b50516001600160a01b031690565b92516001600160a01b031690565b604080516001600160a01b03948516602082015293909116908301528160608101612490565b6124fc84612118565b5261250683612118565b5061249060405193849260208401612190565b61252242611b3c565b823b156102885761254c925f928360405180968195829463dd46508f60e01b8452600484016121b5565b03925af1908161256c575b506102c1576125646121d1565b602081519101fd5b8061257a5f6125809361116d565b8061027e565b5f612557565b612519929195506125a59060203d602011610b1b57610b0e818361116d565b94909161242d565b6125ce9060203d6020116125d3575b6125c6818361116d565b810190611f26565b6123e9565b503d6125bc565b8061257a5f6125e89361116d565b5f612359565b8061257a5f6125fc9361116d565b5f6122de565b61261a9060203d602011610b6557610b58818361116d565b61225e565b60405160609190612630838261116d565b6002815291601f1901366020840137565b9081602091031261028857516102c1816103c0565b6020818303126102885780519067ffffffffffffffff821161028857019080601f8301121561028857815161268a81611fd8565b92612698604051948561116d565b81845260208085019260051b82010192831161028857602001905b8282106126c05750505090565b81518152602091820191016126b3565b6060602091604081019381526040838201528451809452019201905f5b8181106126fa5750505090565b82516001600160a01b03168452602093840193909201916001016126ed565b906107ac6127339161272e600b54821061198a565b6116b3565b9061275861273f61261f565b926127498461210b565b6001600160a01b039091169052565b6040516315ab88c960e31b8152917f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b0316602084600481845afa928315610ad1576127ba5f946127d6968691612817575b5061274985612118565b60405180958194829363d06ca61f60e01b8452600484016126d0565b03915afa8015610ad1576127f1915f916127f5575b50612118565b5190565b61281191503d805f833e612809818361116d565b810190612656565b5f6127eb565b612839915060203d60201161283f575b612831818361116d565b810190612641565b5f6127b0565b503d612827565b6001600160a01b039081165f81815260016020908152604080832094861683529390529190912091929091545f198110612881575b50505050565b8181106128cd57821561047b576001600160a01b03841615610468576128c3925f526001602052039160405f209060018060a01b03165f5260205260405f2090565b555f80808061287b565b83637dc7a0d960e11b5f5260018060a01b031660045260245260445260645ffd5b916001600160a01b0383169182156129d7576001600160a01b0381169384156129c4576001600160a01b0381165f9081526020819052604090205483811061299f579161298d91612973857fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9695039160018060a01b03165f525f60205260405f2090565b556001600160a01b03165f90815260208190526040902090565b805482019055604051908152602090a3565b63391434e360e21b5f526001600160a01b03909116600452602452604482905260645ffd5b63ec442f0560e01b5f525f60045260245ffd5b634b637e8f60e11b5f525f60045260245ffd5b6001600160a01b038116919082156129d7576001600160a01b0381165f90815260208190526040902054828110612a7257917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91612a5c825f9695039160018060a01b03165f525f60205260405f2090565b55600280548290039055604051908152602090a3565b63391434e360e21b5f526001600160a01b0390911660045260245260445260645ffd5b600754908115612b12576005612aaa826116b3565b500154906006612ab9826116b3565b5001549082158015612b0a575b612b0257612ad391612719565b916064019081606411611b3757818102918183041490151715611b37576064900411612afe57600190565b5f90565b505050505f90565b508115612ac6565b5050600190565b6040516370a0823160e01b815230600482015260208160248173c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25afa908115610ad1575f91612bba575b5080612b61575b50565b600f54612b76906001600160a01b0316610d17565b803b1561028857604051632e1a7d4d60e01b815260048101929092525f908290602490829084905af18015610ad157612bac5750565b8061257a5f61119e9361116d565b612bd3915060203d602011610b1b57610b0e818361116d565b5f612b57565b6001600160801b036102c19493612bf38361012095611f3f565b600160a08401521660c08201525f60e082015281610100820152019061028c565b9392916121cc90612c2f60409360608852606088019061028c565b908682036020880152612138565b600554612c52906001600160a01b0316610d17565b612c5a6111b0565b5f815230602082019081529091612c88905f604085015260c860608501526001600160a01b03166080840152565b604051600160fc1b60208201526001815291612ca560218461116d565b612da6612cb061202a565b604051600360f91b6020820152600360fa1b6021820152600f60f81b602282015260038152909361249090612d9390612d7090612cee60238661116d565b89612d5d612d39612cfd612064565b99612490612d26612d0c611fa9565b6040519283916001600160801b0389168660208501612bd9565b612d2f8c61210b565b526124b18b61210b565b604080516001600160a01b0390921660208301528101929092528160608101612490565b612d6688612118565b526124b187612118565b604080516001600160a01b0390921660208301525f908201529182906060820190565b612d9c84612128565b5261250683612128565b612daf8261210b565b52612db98161210b565b50612dc342611b3c565b600e54909190612ddb906001600160a01b0316610d17565b90813b1561028857612e06945f9460405196879586948593630d64d59360e21b855260048501612c14565b03925af18015610ad157612ebb575b506040516370a0823160e01b815230600482015260208180602481010381305afa908115610ad157612e73916020915f91612e9e575b506040518093819263a9059cbb60e01b83526004830191906020604084019361dead81520152565b03815f305af18015610ad157612e865750565b612b5e9060203d602011610b6557610b58818361116d565b612eb59150823d8411610b1b57610b0e818361116d565b5f612e4b565b8061257a5f612ec99361116d565b5f612e15565b612edc620d899f19612fbe565b612ee862032960612fbe565b80826001600160a01b0380831690821611612fb3575b50506001600160a01b0382166d7b86bec8b03d1b4fa773ae726cf511612f29575f906102c192613328565b6001600160a01b0381166d7b86bec8b03d1b4fa773ae726cf51015612f9c576b033b2e3c9fd0803ce80000006d7b86bec8b03d1b4fa773ae726cf5612f725f612f789483613328565b936132ee565b6001600160801b0381166001600160801b038316105f14612f97575090565b905090565b6b033b2e3c9fd0803ce8000000906102c1926132ee565b915091505f80612efe565b60020b908160ff1d82810118620d89e881116132d85763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102600160801b1891600281166132bc575b600481166132a0575b60088116613284575b60108116613268575b6020811661324c575b60408116613230575b60808116613214575b61010081166131f8575b61020081166131dc575b61040081166131c0575b61080081166131a4575b6110008116613188575b612000811661316c575b6140008116613150575b6180008116613134575b620100008116613118575b6202000081166130fd575b6204000081166130e2575b62080000166130c9575b5f126130c1575b0160201c90565b5f19046130ba565b6b048a170391f7dc42444e8fa290910260801c906130b3565b6d2216e584f5fa1ea926041bedfe9890920260801c916130a9565b916e5d6af8dedb81196699c329225ee6040260801c9161309e565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c91613093565b916f31be135f97d08fd981231505542fcfa60260801c91613088565b916f70d869a156d2a1b890bb3df62baf32f70260801c9161307e565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91613074565b916fd097f3bdfd2022b8845ad8f792aa58250260801c9161306a565b916fe7159475a2c29b7443b29c7fa6e889d90260801c91613060565b916ff3392b0822b70005940c7a398e4b70f30260801c91613056565b916ff987a7253ac413176f2b074cf7815e540260801c9161304c565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91613042565b916ffe5dee046a99a2a811c461f1969c30530260801c91613038565b916fff2ea16466c96a3843ec78b326b528610260801c9161302f565b916fff973b41fa98c081472e6896dfb254c00260801c91613026565b916fffcb9843d60f6159c9db58835c9266440260801c9161301d565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91613014565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c9161300b565b916ffff97272373d413259a46990580e213a0260801c91613002565b826345c3193d60e11b5f5260020b60045260245ffd5b6102c19261331d9290916001600160a01b0380831690821611613322575b90036001600160a01b03169061337c565b6134d5565b9061330c565b6102c19261331d929091906001600160a01b038082169083161161336f575b61335d6001600160a01b03828116908416613409565b9190036001600160a01b031691613452565b90613347565b1561028857565b90606082901b905f19600160601b84099282808510940393808503946133a3868511613375565b14613402578190600160601b900981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b81810291905f1982820991838084109303928084039384600160601b1115610288571461344957600160601b910990828211900360a01b910360601c1790565b50505060601c90565b91818302915f19818509938380861095039480860395613473878611613375565b146134cd579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b906001600160801b0382168092036134e957565b6393dafdf160e01b5f5260045ffdfea26469706673582212204af00d265fe97d5f4332453c78690384fa502ee224f66e6d7eb29c4d4b99141e64736f6c634300081a0033
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.