{"language":"Solidity","sources":{"contracts/PebbleCreatorVault.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\n/// @notice Non-upgradeable custody for earned creator ETH. No owner, admin,\n/// recipient setter, arbitrary call, allowance, or hook withdrawal authority.\n/// Anyone may pay claim gas; all ETH can only reach the immutable recipient.\ncontract PebbleCreatorVault {\n    address public immutable recipient;\n    uint256 public totalClaimed;\n    bool private entered;\n    error InvalidRecipient();\n    error ReentrantClaim();\n    error TransferFailed();\n    event RevenueReceived(address indexed sender,uint256 amount);\n    event RevenueClaimed(address indexed recipient,uint256 amount);\n\n    constructor(address recipient_) {\n        if(recipient_==address(0) || recipient_==address(this))revert InvalidRecipient();\n        recipient=recipient_;\n    }\n    receive() external payable {emit RevenueReceived(msg.sender,msg.value);}\n    function available() external view returns(uint256){return address(this).balance;}\n    // Includes ordinary donations and forced ETH; no depositor gets withdrawal rights.\n    function totalReceived() external view returns(uint256){return address(this).balance+totalClaimed;}\n    function claim() external returns(uint256 amount) {\n        if(entered)revert ReentrantClaim();\n        entered=true;amount=address(this).balance;\n        if(amount!=0) {\n            totalClaimed+=amount;\n            (bool ok,)=recipient.call{value:amount}(\"\");\n            if(!ok)revert TransferFailed();\n            emit RevenueClaimed(recipient,amount);\n        }\n        entered=false;\n    }\n}\n"},"contracts/PebbleNftRewardChannel.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\n/// @notice Minimal future rewards boundary, NOT the NFT collection or final rewards product.\n/// Deployed only after a collection and eligibility policy are reviewed. This fixed\n/// runtime can receive only its separately accrued future-fee bucket from the hook.\n/// There is no admin withdrawal, recipient override, delegatecall or upgrade.\n/// Equal ETH entitlement for 500 consecutive ERC721 IDs; unclaimed entitlement\n/// follows the ID to its current owner. Optional eligibility code can only deny a\n/// claim, never increase its amount or change its recipient. Those are fixed limits.\ncontract PebbleNftRewardChannel {\n    uint256 public constant COLLECTION_SIZE=500;\n    address public hook;\n    address public collection;\n    bytes32 public collectionCodeHash;\n    uint256 public firstTokenId;\n    address public eligibility;\n    bytes32 public eligibilityCodeHash;\n    uint256 public rewardPerToken;\n    uint256 public remainder;\n    uint256 public totalFunded;\n    uint256 public totalClaimed;\n    mapping(uint256=>uint256) public claimed;\n    bool private entered;\n    event Funded(uint256 amount,uint256 rewardPerToken);\n    event Claimed(uint256 indexed tokenId,address indexed owner,uint256 amount);\n    error InvalidReward();\n    constructor(address hook_,address collection_,uint256 firstId,address eligibility_) {\n        if(hook_==address(0) || collection_.code.length==0 || firstId>type(uint256).max-499\n            || (eligibility_!=address(0) && eligibility_.code.length==0))revert InvalidReward();\n        hook=hook_;collection=collection_;collectionCodeHash=collection_.codehash;\n        firstTokenId=firstId;eligibility=eligibility_;eligibilityCodeHash=eligibility_.codehash;\n    }\n    receive() external payable {\n        if(msg.sender!=hook)revert InvalidReward();\n        uint256 amount=msg.value+remainder;\n        rewardPerToken+=amount/COLLECTION_SIZE;remainder=amount%COLLECTION_SIZE;totalFunded+=msg.value;\n        emit Funded(msg.value,rewardPerToken);\n    }\n    function _read(address target,bytes memory data) private view returns(uint256 word) {\n        bool ok;uint256 size;uint256[1] memory result;\n        assembly {ok:=staticcall(50000,target,add(data,32),mload(data),result,32) size:=returndatasize()}\n        if(!ok || size!=32)revert InvalidReward();return result[0];\n    }\n    function claim(uint256 tokenId) external {\n        if(entered || tokenId<firstTokenId || tokenId-firstTokenId>=COLLECTION_SIZE\n            || collection.codehash!=collectionCodeHash)revert InvalidReward();\n        entered=true;\n        if(_read(collection,abi.encodeWithSignature(\"ownerOf(uint256)\",tokenId))!=uint256(uint160(msg.sender)))revert InvalidReward();\n        if(eligibility!=address(0) && (eligibility.codehash!=eligibilityCodeHash\n            || _read(eligibility,abi.encodeWithSignature(\"eligible(address,uint256)\",msg.sender,tokenId))!=1))revert InvalidReward();\n        uint256 amount=rewardPerToken-claimed[tokenId];if(amount==0)revert InvalidReward();\n        claimed[tokenId]=rewardPerToken;totalClaimed+=amount;\n        (bool ok,)=msg.sender.call{value:amount}(\"\");if(!ok)revert InvalidReward();\n        entered=false;emit Claimed(tokenId,msg.sender,amount);\n    }\n}\n"},"contracts/PebblePeripheryInterfaces.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n// ABI-compatible subset of the pinned, real Uniswap PositionManager and Permit2.\ninterface IPositionManager {\n    function poolManager() external view returns (address);\n    function permit2() external view returns (address);\n    function nextTokenId() external view returns (uint256);\n    function getPoolAndPositionInfo(uint256 id) external view returns (PoolKey memory, uint256);\n    function getPositionLiquidity(uint256 id) external view returns (uint128);\n    function ownerOf(uint256 id) external view returns (address);\n    function getApproved(uint256 id) external view returns (address);\n    function approve(address to, uint256 id) external;\n    function transferFrom(address from, address to, uint256 id) external;\n    function modifyLiquidities(bytes calldata data, uint256 deadline) external payable;\n    function modifyLiquiditiesWithoutUnlock(bytes calldata actions, bytes[] calldata params) external payable;\n}\ninterface IAllowanceTransfer {\n    function approve(address token, address spender, uint160 amount, uint48 expiry) external;\n    function allowance(address user, address token, address spender) external view returns (uint160,uint48,uint48);\n}\n\n"},"contracts/PebblePermanentLiquidity.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IPositionManager,IAllowanceTransfer} from \"./PebblePeripheryInterfaces.sol\";\n\n/// @notice Irrevocable custody of the launch LP NFT and every fee-funded addition.\n/// No owner, NFT approval/transfer, unlock, principal withdrawal, rescue, delegatecall\n/// or upgrade route. Only increase liquidity or collect fees with zero principal delta.\ncontract PebblePermanentLiquidity {\n    address public immutable coordinator;\n    bool public initialized;\n    IPoolManager public immutable poolManager;\n    IPositionManager public immutable positionManager;\n    IAllowanceTransfer public immutable permit2;\n    address public hook;\n    address public token;\n    function positionOwner() external view returns(address){return address(this);}\n    uint256 public tokenId;\n    int24 public tickLower;\n    int24 public tickUpper;\n    error Unauthorized(); error InvalidPosition(); error TransferFailed();\n\n    constructor(IPoolManager manager,IPositionManager posm,IAllowanceTransfer permits,address coordinator_) {\n        if(coordinator_==address(0) || posm.poolManager()!=address(manager) || posm.permit2()!=address(permits))revert InvalidPosition();\n        poolManager=manager;positionManager=posm;permit2=permits;coordinator=coordinator_;\n    }\n\n    function initialize(address hook_,address token_,uint256 id) external {\n        if(msg.sender!=coordinator || initialized)revert Unauthorized();\n        (PoolKey memory key,uint256 info)=positionManager.getPoolAndPositionInfo(id);\n        if(address(key.hooks)!=hook_ || hook_==address(0)\n            || Currency.unwrap(key.currency0)!=address(0) || Currency.unwrap(key.currency1)!=token_\n            || key.fee!=0x800000 || key.tickSpacing!=1 || positionManager.ownerOf(id)!=address(this))revert InvalidPosition();\n        initialized=true;hook=hook_;token=token_;tokenId=id;\n        tickLower=int24(uint24(info>>8));tickUpper=int24(uint24(info>>32));\n        poolManager.setOperator(hook_,true);\n        if(!IERC20(token_).approve(address(permit2),type(uint256).max))revert TransferFailed();\n    }\n\n    receive() external payable {\n        if (msg.sender!=address(positionManager) && msg.sender!=address(poolManager)) revert Unauthorized();\n    }\n\n    function increase(uint128 liquidity, uint128 amount0, uint128 amount1) external payable {\n        if (msg.sender!=hook || msg.value!=amount0) revert Unauthorized();\n        if (positionManager.ownerOf(tokenId)!=address(this)) revert InvalidPosition();\n        uint128 beforeLiquidity=positionManager.getPositionLiquidity(tokenId);\n        if(liquidity==0)revert InvalidPosition();\n        permit2.approve(token,address(positionManager),amount1,uint48(block.timestamp));\n        bytes[] memory args=new bytes[](4);\n        args[0]=abi.encode(tokenId,uint256(liquidity),amount0,amount1,bytes(\"\"));\n        args[1]=abi.encode(Currency.wrap(address(0)));\n        args[2]=abi.encode(Currency.wrap(token));\n        args[3]=abi.encode(Currency.wrap(address(0)),address(this));\n        // INCREASE_LIQUIDITY, CLOSE_CURRENCY x2, SWEEP (pinned Uniswap Actions).\n        positionManager.modifyLiquiditiesWithoutUnlock{value:amount0}(hex\"00121214\",args);\n        permit2.approve(token,address(positionManager),0,0);\n        if(positionManager.getPositionLiquidity(tokenId)!=beforeLiquidity+liquidity)revert InvalidPosition();\n        _storeDust();\n    }\n\n    function _storeDust() private {\n        uint256 tokens=IERC20(token).balanceOf(address(this));\n        if (tokens!=0) {\n            poolManager.sync(Currency.wrap(token));\n            if (!IERC20(token).transfer(address(poolManager),tokens)) revert TransferFailed();\n            poolManager.settle();\n            poolManager.mint(address(this),uint256(uint160(token)),tokens);\n        }\n        uint256 balance=address(this).balance;\n        if (balance!=0) {\n            poolManager.sync(Currency.wrap(address(0)));\n            poolManager.settle{value:balance}();\n            poolManager.mint(address(this),0,balance);\n        }\n    }\n\n    function collectFees() external {\n        if(!initialized)revert InvalidPosition();\n        poolManager.unlock(\"\");\n    }\n    function unlockCallback(bytes calldata) external returns(bytes memory) {\n        if(msg.sender!=address(poolManager) || !initialized)revert Unauthorized();\n        uint128 beforeLiquidity=positionManager.getPositionLiquidity(tokenId);\n        bytes[] memory args=new bytes[](2);\n        args[0]=abi.encode(tokenId,uint256(0),uint128(0),uint128(0),bytes(\"\"));\n        args[1]=abi.encode(Currency.wrap(address(0)),Currency.wrap(token),address(this));\n        // DECREASE_LIQUIDITY with a hardcoded ZERO principal delta, TAKE_PAIR.\n        positionManager.modifyLiquiditiesWithoutUnlock(hex\"0111\",args);\n        if(positionManager.getPositionLiquidity(tokenId)!=beforeLiquidity\n            || positionManager.ownerOf(tokenId)!=address(this))revert InvalidPosition();\n        _storeDust();\n        return \"\";\n    }\n}\n"},"contracts/PebbleQuoteController.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\nimport {PebbleNftRewardChannel} from \"./PebbleNftRewardChannel.sol\";\n\ninterface IPebbleQuoteStrategyCore {\n    function owner() external view returns(address);\n    function rewardsChannel() external view returns(address);\n    function bindRewardsChannel(address) external;\n    function pblReserve() external view returns(uint256);\n    function clausReserve() external view returns(uint256);\n    function liquidityReserve() external view returns(uint256);\n    function clausAllocationPpm() external view returns(uint16);\n    function liquidityAllocationPpm() external view returns(uint16);\n    function applyStrategyAllocation(uint16,uint16) external;\n    function processBuyback(bool,uint256,uint256,uint160,uint256) external returns(uint256);\n    function processLiquidity(uint256,uint256,uint256,uint128,uint160,uint256) external returns(uint128,uint256,uint256,uint256);\n}\ninterface IPebbleQuoteStrategy {\n    struct Context {address hook;uint256 timestamp;uint256 pbl;uint256 claus;uint256 liquidity;uint256 clausPpm;uint256 liquidityPpm;}\n    // 0 wait; 1 PBL burn; 2 CLAUS purchase; 3 locked liquidity; 4 future allocation.\n    struct Plan {uint256 action;uint256 clausPpm;uint256 liquidityPpm;uint256 amount;uint256 swapEth;uint256 validAfter;uint256 deadline;uint256 minimumTokens;}\n    function plan(Context calldata) external view returns(Plan memory);\n}\n\n/// @notice Replaceable policy CODE, never delegatecalled and never given custody.\n/// No strategy is invoked during a swap. Hostile code can only fail its own preview\n/// or maintenance call; the owner can replace it or execute protected actions directly.\ncontract PebbleQuoteController {\n    address public immutable coordinator;\n    address public hook;\n    address public strategy;\n    bytes32 public strategyCodeHash;\n    address public pendingStrategy;\n    bytes32 public pendingCodeHash;\n    uint256 public upgradeAt;\n    uint256 public constant UPGRADE_DELAY=1 days;\n    bytes32 public immutable REWARDS_CHANNEL_CODEHASH;\n    address public pendingRewardsChannel;\n    uint256 public rewardsActivateAt;\n    event RewardsChannelScheduled(address indexed channel,uint256 activateAt);\n\n    event StrategyScheduled(address indexed strategy,bytes32 codeHash,uint256 activateAt);\n    event StrategyUpgraded(address indexed strategy,bytes32 codeHash);\n    event StrategyExecuted(address indexed strategy,uint256 action,uint256 amount);\n    error InvalidStrategy();error Unauthorized();\n    constructor(address c,address initial) {require(c!=address(0) && initial.code.length!=0);coordinator=c;strategy=initial;strategyCodeHash=initial.codehash;REWARDS_CHANNEL_CODEHASH=keccak256(type(PebbleNftRewardChannel).runtimeCode);}\n    function bind(address h) external {if(msg.sender!=coordinator || hook!=address(0) || h.code.length==0)revert Unauthorized();hook=h;}\n    modifier onlyOwner(){if(hook==address(0) || msg.sender!=IPebbleQuoteStrategyCore(hook).owner())revert Unauthorized();_;}\n    /// @notice A post-launch channel is accepted only if its entire runtime matches\n    /// the fixed, non-upgradeable recipient/claim boundary compiled into this controller.\n    function scheduleRewardsChannel(address next) external onlyOwner {\n        if(IPebbleQuoteStrategyCore(hook).rewardsChannel()!=address(0) || next.codehash!=REWARDS_CHANNEL_CODEHASH\n            || PebbleNftRewardChannel(payable(next)).hook()!=hook)revert InvalidStrategy();\n        pendingRewardsChannel=next;rewardsActivateAt=block.timestamp+UPGRADE_DELAY;\n        emit RewardsChannelScheduled(next,rewardsActivateAt);\n    }\n    function activateRewardsChannel() external onlyOwner {\n        address next=pendingRewardsChannel;\n        if(next==address(0) || block.timestamp<rewardsActivateAt || next.codehash!=REWARDS_CHANNEL_CODEHASH)revert InvalidStrategy();\n        delete pendingRewardsChannel;delete rewardsActivateAt;\n        IPebbleQuoteStrategyCore(hook).bindRewardsChannel(next);\n    }\n    function scheduleStrategy(address next) external onlyOwner {\n        _schedule(next);\n    }\n    function scheduleReviewedStrategy(address next,bytes32 reviewedHash) external onlyOwner {\n        if(next.codehash!=reviewedHash)revert InvalidStrategy();_schedule(next);\n    }\n    function _schedule(address next) private {\n        if(next.code.length==0 || next==address(this) || next==hook)revert InvalidStrategy();\n        pendingStrategy=next;pendingCodeHash=next.codehash;upgradeAt=block.timestamp+UPGRADE_DELAY;\n        emit StrategyScheduled(next,pendingCodeHash,upgradeAt);\n    }\n    function activateStrategy() external onlyOwner {\n        if(pendingStrategy==address(0) || block.timestamp<upgradeAt || pendingStrategy.codehash!=pendingCodeHash)revert InvalidStrategy();\n        strategy=pendingStrategy;strategyCodeHash=pendingCodeHash;delete pendingStrategy;delete pendingCodeHash;delete upgradeAt;\n        emit StrategyUpgraded(strategy,strategyCodeHash);\n    }\n    function preview() public view returns(IPebbleQuoteStrategy.Plan memory p) {\n        if(hook==address(0) || strategy.codehash!=strategyCodeHash)revert InvalidStrategy();\n        IPebbleQuoteStrategyCore core=IPebbleQuoteStrategyCore(hook);\n        IPebbleQuoteStrategy.Context memory context=IPebbleQuoteStrategy.Context(hook,block.timestamp,core.pblReserve(),core.clausReserve(),core.liquidityReserve(),core.clausAllocationPpm(),core.liquidityAllocationPpm());\n        bytes memory data=abi.encodeCall(IPebbleQuoteStrategy.plan,(context));\n        address target=strategy;bool ok;uint256 size;uint256[8] memory words;\n        assembly {ok := staticcall(150000,target,add(data,32),mload(data),words,256) size := returndatasize()}\n        if(!ok || size!=256)revert InvalidStrategy();\n        p=IPebbleQuoteStrategy.Plan(words[0],words[1],words[2],words[3],words[4],words[5],words[6],words[7]);\n        if(p.action>4 || p.clausPpm>17000 || p.liquidityPpm>17000-p.clausPpm\n            || p.amount>0.005 ether || p.swapEth>p.amount || p.validAfter>block.timestamp\n            || p.deadline<block.timestamp || p.deadline>block.timestamp+300)revert InvalidStrategy();\n    }\n    function executeStrategy() external onlyOwner {\n        _execute(preview());\n    }\n    function executeReviewedStrategy(bytes32 expectedIntent,uint256 deadline) external onlyOwner {\n        IPebbleQuoteStrategy.Plan memory p=preview();\n        if(block.timestamp>deadline || deadline>block.timestamp+120 ||\n            keccak256(abi.encode(p.action,p.clausPpm,p.liquidityPpm,p.amount,p.swapEth,p.minimumTokens))!=expectedIntent)revert InvalidStrategy();\n        _execute(p);\n    }\n    /// @notice Exact owner-reviewed order terms. The immutable core still applies\n    /// its spending caps and spot sanity floor. This is not a fair-value oracle.\n    function executeQuotedStrategy(bytes32 expectedIntent,uint256 minimumTokens,uint128 minimumLiquidity,uint160 priceLimit,uint256 deadline)\n        external onlyOwner returns(uint256 tokens,uint128 liquidity)\n    {\n        IPebbleQuoteStrategy.Plan memory p=preview();\n        if(block.timestamp>deadline || deadline>block.timestamp+120 ||\n            keccak256(abi.encode(p.action,p.clausPpm,p.liquidityPpm,p.amount,p.swapEth,p.minimumTokens))!=expectedIntent)revert InvalidStrategy();\n        if(p.deadline>deadline)p.deadline=deadline;\n        IPebbleQuoteStrategyCore core=IPebbleQuoteStrategyCore(hook);\n        if(p.action==4){\n            if(minimumTokens!=0 || minimumLiquidity!=0 || priceLimit!=0)revert InvalidStrategy();\n            core.applyStrategyAllocation(uint16(p.clausPpm),uint16(p.liquidityPpm));\n        }else{\n            if(minimumTokens==0 || priceLimit<=4295128739)revert InvalidStrategy();\n            if(minimumTokens<p.minimumTokens)minimumTokens=p.minimumTokens;\n            if(p.action==1 || p.action==2){\n                if(minimumLiquidity!=0)revert InvalidStrategy();\n                tokens=core.processBuyback(p.action==2,p.amount,minimumTokens,priceLimit,p.deadline);\n            }else if(p.action==3){\n                if(minimumLiquidity==0)revert InvalidStrategy();\n                (liquidity,,tokens,)=core.processLiquidity(p.amount,p.swapEth,minimumTokens,minimumLiquidity,priceLimit,p.deadline);\n            }else revert InvalidStrategy();\n        }\n        emit StrategyExecuted(strategy,p.action,p.amount);\n    }\n    function _execute(IPebbleQuoteStrategy.Plan memory p) private {\n        IPebbleQuoteStrategyCore core=IPebbleQuoteStrategyCore(hook);\n        if(p.action==4)core.applyStrategyAllocation(uint16(p.clausPpm),uint16(p.liquidityPpm));\n        else if(p.action==1 || p.action==2)core.processBuyback(p.action==2,p.amount,p.minimumTokens==0?1:p.minimumTokens,4295128740,p.deadline);\n        else if(p.action==3)core.processLiquidity(p.amount,p.swapEth,p.minimumTokens==0?1:p.minimumTokens,1,4295128740,p.deadline);\n        emit StrategyExecuted(strategy,p.action,p.amount);\n    }\n}\n\n/// @notice First launch policy: process the larger funded buyback bucket.\ncontract PebbleQuoteSteadyStrategy is IPebbleQuoteStrategy {\n    function plan(Context calldata c) external pure returns(Plan memory p){\n        p.deadline=c.timestamp+120;p.clausPpm=c.clausPpm;p.liquidityPpm=c.liquidityPpm;\n        bool cl=c.claus>c.pbl;p.amount=(cl?c.claus:c.pbl)/20;\n        if(p.amount>0.001 ether)p.amount=0.001 ether;\n        if(p.amount>=(cl?0.0001 ether:0.001 ether))p.action=cl?2:1;\n    }\n}\n\n/// @notice A replacement policy adds alternating execution windows and a different\n/// future allocation regime without changing trading, custody or reserve rules.\ncontract PebbleQuotePacedStrategy is IPebbleQuoteStrategy {\n    function plan(Context calldata c) external pure returns(Plan memory p){\n        p.deadline=c.timestamp+120;p.clausPpm=5000;p.liquidityPpm=2000;\n        if(c.clausPpm!=5000 || c.liquidityPpm!=2000){p.action=4;return p;}\n        bool cl=(c.timestamp/180)%2==1;p.amount=(cl?c.claus:c.pbl)/20;\n        if(p.amount>0.001 ether)p.amount=0.001 ether;\n        if(p.amount>=(cl?0.0001 ether:0.001 ether))p.action=cl?2:1;\n    }\n}\n"},"contracts/PebbleQuoteHook.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {IHooks} from \"@uniswap/v4-core/src/interfaces/IHooks.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId, PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {BalanceDelta} from \"@uniswap/v4-core/src/types/BalanceDelta.sol\";\nimport {BeforeSwapDelta, toBeforeSwapDelta} from \"@uniswap/v4-core/src/types/BeforeSwapDelta.sol\";\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\nimport {TickMath} from \"@uniswap/v4-core/src/libraries/TickMath.sol\";\nimport {FullMath} from \"@uniswap/v4-core/src/libraries/FullMath.sol\";\nimport {SqrtPriceMath} from \"@uniswap/v4-core/src/libraries/SqrtPriceMath.sol\";\nimport {PebblePermanentLiquidity} from \"./PebblePermanentLiquidity.sol\";\nimport {PebbleCreatorVault} from \"./PebbleCreatorVault.sol\";\nimport {PebbleSwapRouter} from \"./PebbleSwapRouter.sol\";\nimport {PebbleQuotePolicy} from \"./PebbleQuotePolicy.sol\";\nimport {PebbleQuoteController} from \"./PebbleQuoteController.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IBurnable { function burn(uint256 amount) external; }\n\n/// @notice Fixed trading/accounting and custody boundary with separately replaceable\n/// strategy code. Strategies are never called from trading callbacks and cannot\n/// replace this contract, weaken its execution policy or receive reserve authority.\ncontract PebbleQuoteHook {\n    using PoolIdLibrary for PoolKey;\n    using StateLibrary for IPoolManager;\n\n    IPoolManager public immutable poolManager;\n    uint24 public constant CREATOR_PPM = 10_000;\n    uint24 public constant BUYBACK_PPM = 17_000;\n    uint24 public constant TOTAL_PPM = 27_000;\n    uint24 public constant MAX_PROJECT_FEE_PPM = 50_000;\n    // All callbacks are fixed at deployment; unused callbacks are neutral.\n    uint160 public constant HOOK_FLAGS = 0x3fff;\n\n    PebbleQuotePolicy public immutable executionPolicy;\n    PebbleQuoteController public immutable strategyController;\n    PebbleCreatorVault public immutable creatorVault;\n    address public immutable taxRouter;\n    address public immutable clausTreasuryWallet;\n    address public immutable exemptKeeperWallet;\n    bool public graphBootstrapComplete;\n    bool public constant feeMigrationComplete = true;\n    mapping(address=>bool) public projectTaxExempt;\n    struct Config {\n        address owner; address creator; address token; address claus;\n        address coordinator; address treasury; PebbleCreatorVault vault;\n        address exemptKeeper; PebblePermanentLiquidity locker; PebbleSwapRouter router;\n        PebbleQuotePolicy policy; PebbleQuoteController strategies;\n    }\n    bool public poolBound;\n    bool public clausPoolBound;\n    bool public buybacksPaused;\n    bool private entered;\n    bool private processing;\n    address public owner;\n    address public pendingOwner;\n    address public keeper;\n    address public creatorWallet;\n    address public token;\n    address public clausToken;\n    address public launchCoordinator;\n    PoolKey private primaryKey;\n    PoolKey private companionKey;\n    uint16 public clausAllocationPpm; // Same slot/type as legacy clausShareBps; V3 migrates its units atomically.\n    uint32 public cooldownSeconds;\n    uint256 public pblThreshold;\n    uint256 public clausThreshold;\n    uint256 public maxBatch;\n    uint256 internal _creatorAccrued; // Original slot; getter remains ABI-compatible.\n    uint256 public pblReserve;\n    uint256 public clausReserve;\n    uint256 public totalCreatorEarned;\n    uint256 internal _totalCreatorClaimed; // Original slot; no storage reordering.\n    uint256 public totalPblBurned;\n    uint256 internal _legacyClausBurned; // Unused legacy accounting slot.\n    uint256 public totalPblBuybackEth;\n    uint256 public totalClausBuybackEth;\n    uint256 public lastPblBatch;\n    uint256 public lastClausBatch;\n    uint256 public totalGrossEthVolume;\n    uint256 public tradeCount;\n    address public deployerWallet;\n    uint256 public totalClausBought;\n    uint16 public liquidityAllocationPpm; // Same slot/type as legacy liquidityShareBps.\n    uint256 public liquidityReserve;\n    uint256 public liquidityThreshold;\n    uint256 public lastLiquidityBatch;\n    uint256 public totalLiquidityEthSpent;\n    uint256 public liquidityBatchCount;\n    PebblePermanentLiquidity public immutable lpReserve;\n    bool private processingLiquidity;\n    uint256 public totalAutoEthDeposited;\n    uint256 public totalAutoPblDeposited;\n    uint256 public totalAutoEthSwapped;\n    address public rewardsChannel;\n    uint16 public rewardsAllocationPpm;\n    uint256 public rewardsReserve;\n    uint256 public totalRewardsFunded;\n\n    event FeesAccrued(uint256 grossEth, uint256 creator, uint256 pbl, uint256 claus);\n    event BuybackBurned(address indexed asset, uint256 ethSpent, uint256 tokensBurned);\n    event ClausPurchased(address indexed recipient, uint256 ethSpent, uint256 tokensSent);\n    event FeesClaimed(address indexed recipient, uint256 amount);\n    event ModuleRatesChanged(uint16 clausPpm, uint16 liquidityPpm);\n    event LiquidityFeesAccrued(uint256 amount);\n    event LiquidityAdded(uint256 ethSpent, uint256 ethDeposited, uint256 pblDeposited, uint128 liquidity);\n    event BuybackControlsChanged(bool paused, uint256 pblMinimum, uint256 clausMinimum, uint256 maximum, uint32 cooldown);\n    event KeeperChanged(address indexed keeper);\n    event ClausPoolConfigured(bytes32 indexed poolId);\n    event OwnerProposed(address indexed owner);\n    event OwnerChanged(address indexed owner);\n    event RewardsChannelActivated(address indexed channel);\n    event RewardsAllocationChanged(uint16 rewardsPpm);\n    event RewardsFeesAccrued(uint256 amount);\n    event RewardsFunded(uint256 amount);\n\n    error Unauthorized();\n    error InvalidConfiguration();\n    error UnsupportedSwap();\n    error WrongPool();\n    error BatchNotReady();\n    error Slippage();\n    error TransferFailed();\n\n    constructor(IPoolManager manager, Config memory c) {\n        if (address(manager)==address(0) || c.owner==address(0) || c.creator==address(0)\n            || c.token==address(0) || c.claus==address(0) || c.token==c.claus\n            || c.coordinator==address(0) || c.treasury==address(0) || c.exemptKeeper==address(0)\n            || address(c.vault).code.length==0 || c.vault.recipient()!=c.creator\n            || address(c.locker.poolManager())!=address(manager) || c.locker.coordinator()!=c.coordinator\n            || address(c.router.manager())!=address(manager)\n            || c.policy.coordinator()!=c.coordinator || c.strategies.coordinator()!=c.coordinator\n            || address(c.policy.manager())!=address(manager) || c.policy.token()!=c.token || c.policy.claus()!=c.claus\n            || TOTAL_PPM>MAX_PROJECT_FEE_PPM || CREATOR_PPM+BUYBACK_PPM!=TOTAL_PPM)\n            revert InvalidConfiguration();\n        if ((uint160(address(this)) & 0x3fff)!=HOOK_FLAGS) revert InvalidConfiguration();\n        executionPolicy=c.policy; strategyController=c.strategies;\n        poolManager=manager; owner=c.owner; keeper=c.owner; creatorWallet=c.creator;\n        token=c.token; clausToken=c.claus; launchCoordinator=c.coordinator;\n        deployerWallet=c.owner; clausTreasuryWallet=c.treasury; creatorVault=c.vault;\n        exemptKeeperWallet=c.exemptKeeper; taxRouter=address(c.router); lpReserve=c.locker;\n        projectTaxExempt[c.owner]=true;projectTaxExempt[c.creator]=true;\n        projectTaxExempt[c.treasury]=true;projectTaxExempt[c.exemptKeeper]=true;\n        clausAllocationPpm=7000;\n        pblThreshold=0.001 ether;clausThreshold=0.0001 ether;maxBatch=0.05 ether;\n        cooldownSeconds=60;liquidityThreshold=0.002 ether;\n    }\n\n    modifier onlyOwner() { if (msg.sender != owner) revert Unauthorized(); _; }\n    modifier onlyManager() { if (msg.sender != address(poolManager)) revert Unauthorized(); _; }\n    modifier nonReentrant() { if (entered) revert Unauthorized(); entered = true; _; entered = false; }\n\n    function version() external pure returns(uint256){return 8;}\n    function clausRecipient() public view returns(address){return clausTreasuryWallet;}\n\n    /// @notice Called only by the immutable one-shot launch coordinator.\n    /// Neither the CLAUS route nor custody can be changed after initialization.\n    function completeGraphLaunch(PoolKey calldata clausKey) external {\n        if(msg.sender!=launchCoordinator || graphBootstrapComplete || !poolBound\n            || !lpReserve.initialized() || lpReserve.hook()!=address(this) || lpReserve.token()!=token\n            || lpReserve.positionOwner()!=address(lpReserve)) revert InvalidConfiguration();\n        graphBootstrapComplete=true;\n        _setClausPool(clausKey);\n    }\n\n    function poolKey() external view returns (PoolKey memory) { return primaryKey; }\n    function clausPoolKey() external view returns (PoolKey memory) { return companionKey; }\n    function creatorAccrued() public view returns(uint256){return address(creatorVault).balance;}\n    function totalCreatorClaimed() public view returns(uint256){return creatorVault.totalClaimed();}\n    function reservedEth() public view returns (uint256) { return _creatorAccrued + pblReserve + clausReserve + liquidityReserve + rewardsReserve; }\n\n    function beforeInitialize(address sender, PoolKey calldata key, uint160) external onlyManager returns (bytes4) {\n        if (poolBound || sender != launchCoordinator || Currency.unwrap(key.currency0) != address(0)\n            || Currency.unwrap(key.currency1) != token || address(key.hooks) != address(this)\n            || key.fee != 0x800000 || key.tickSpacing != 1) revert WrongPool();\n        primaryKey = key; poolBound = true;\n        return this.beforeInitialize.selector;\n    }\n\n    function afterInitialize(address, PoolKey calldata key, uint160, int24)\n        external onlyManager returns (bytes4)\n    {\n        _checkPool(key);\n        poolManager.updateDynamicLPFee(key,0);\n        return this.afterInitialize.selector;\n    }\n\n    function beforeAddLiquidity(address, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)\n        external onlyManager returns (bytes4)\n    {\n        _checkPool(key);\n        return this.beforeAddLiquidity.selector;\n    }\n\n    function afterAddLiquidity(address, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)\n        external onlyManager returns (bytes4, BalanceDelta)\n    {\n        _checkPool(key);\n        return (this.afterAddLiquidity.selector, BalanceDelta.wrap(0));\n    }\n\n    function beforeRemoveLiquidity(address, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata, bytes calldata)\n        external onlyManager returns (bytes4)\n    {\n        _checkPool(key);\n        return this.beforeRemoveLiquidity.selector;\n    }\n\n    function afterRemoveLiquidity(address, PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)\n        external onlyManager returns (bytes4, BalanceDelta)\n    {\n        _checkPool(key);\n        return (this.afterRemoveLiquidity.selector, BalanceDelta.wrap(0));\n    }\n\n    function beforeDonate(address, PoolKey calldata key, uint256, uint256, bytes calldata)\n        external onlyManager returns (bytes4)\n    {\n        _checkPool(key);\n        return this.beforeDonate.selector;\n    }\n\n    function afterDonate(address, PoolKey calldata key, uint256, uint256, bytes calldata)\n        external onlyManager returns (bytes4)\n    {\n        _checkPool(key);\n        return this.afterDonate.selector;\n    }\n\n    function beforeSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params, bytes calldata)\n        external onlyManager returns(bytes4,BeforeSwapDelta,uint24)\n    {\n        _checkPool(key);\n        if(params.amountSpecified==0 || params.amountSpecified==type(int256).min)revert UnsupportedSwap();\n        uint256 specified=uint256(params.amountSpecified<0 ? -params.amountSpecified : params.amountSpecified);\n        if(specified>uint256(uint128(type(int128).max)))revert UnsupportedSwap();\n        uint256 fee;\n        if(!_projectTaxExempt(sender,key)) {\n            if(params.zeroForOne && params.amountSpecified<0)fee=_accrue(specified);\n            else if(!params.zeroForOne && params.amountSpecified>0) {\n                uint256 gross=specified+Math.mulDiv(specified,TOTAL_PPM,1_000_000-TOTAL_PPM);\n                if(gross>uint256(uint128(type(int128).max)))revert UnsupportedSwap();\n                fee=_accrue(gross);\n            }\n            if(fee>0)_takeSwapFee(key.currency0,fee);\n        }\n        return(this.beforeSwap.selector,toBeforeSwapDelta(int128(uint128(fee)),0),0);\n    }\n\n    function afterSwap(address sender, PoolKey calldata key, IPoolManager.SwapParams calldata params, BalanceDelta delta, bytes calldata)\n        external onlyManager returns(bytes4,int128)\n    {\n        _checkPool(key);\n        bool exempt=_projectTaxExempt(sender,key);\n        uint256 fee;\n        if(params.amountSpecified<0) {\n            if(params.zeroForOne) {\n                uint256 gross=uint256(-params.amountSpecified);\n                uint256 expectedFee=exempt ? 0 : Math.mulDiv(gross,TOTAL_PPM,1_000_000);\n                if(delta.amount0()!=-int256(gross-expectedFee) || delta.amount1()<=0)revert UnsupportedSwap();\n            } else {\n                if(delta.amount1()!=params.amountSpecified || delta.amount0()<=0)revert UnsupportedSwap();\n                if(!exempt)fee=_accrue(uint256(uint128(delta.amount0())));\n            }\n        } else if(params.zeroForOne) {\n            if(delta.amount1()!=params.amountSpecified || delta.amount0()>=0)revert UnsupportedSwap();\n            if(!exempt) {\n                uint256 net=uint256(-int256(delta.amount0()));\n                fee=_accrue(net+Math.mulDiv(net,TOTAL_PPM,1_000_000-TOTAL_PPM));\n            }\n        } else {\n            uint256 net=uint256(params.amountSpecified);\n            uint256 charged=exempt ? 0 : Math.mulDiv(net,TOTAL_PPM,1_000_000-TOTAL_PPM);\n            if(delta.amount0()!=int256(net+charged) || delta.amount1()>=0)revert UnsupportedSwap();\n        }\n        if(fee>0)_takeSwapFee(key.currency0,fee);\n        return(this.afterSwap.selector,int128(uint128(fee)));\n    }\n\n    /// @dev Project fee only; 30 bps Programmable routing is separate.\n    /// All project charges use this one fixed 2.7% calculation, below the immutable 5% ceiling.\n    /// Floor component shares; rounding dust stays in the PBL reserve.\n    function previewAllFees(uint256 gross) public view returns (uint256 creator, uint256 pbl, uint256 claus, uint256 liquidity) {\n        uint256 total = Math.mulDiv(gross, TOTAL_PPM, 1_000_000);\n        creator = Math.mulDiv(gross, CREATOR_PPM, 1_000_000);\n        // Allocate exact trade percentages. A budget-share basis-point ratio cannot\n        // represent 0.7 / 1.7 exactly. At most two rounding wei remain in PBL.\n        claus = Math.mulDiv(gross, clausAllocationPpm, 1_000_000);\n        liquidity = Math.mulDiv(gross, liquidityAllocationPpm, 1_000_000);\n        pbl = total - creator - claus - liquidity - Math.mulDiv(gross,rewardsAllocationPpm,1_000_000);\n    }\n    function previewExtendedFees(uint256 gross) external view returns(uint256 creator,uint256 pbl,uint256 claus,uint256 liquidity,uint256 rewards){\n        (creator,pbl,claus,liquidity)=previewAllFees(gross);rewards=Math.mulDiv(gross,rewardsAllocationPpm,1_000_000);\n    }\n\n    function _accrue(uint256 gross) internal returns (uint256 total) {\n        (uint256 c, uint256 b, uint256 cl, uint256 liq) = previewAllFees(gross);\n        uint256 rewards=Math.mulDiv(gross,rewardsAllocationPpm,1_000_000);\n        _creatorAccrued += c; pblReserve += b; clausReserve += cl; liquidityReserve += liq; rewardsReserve+=rewards;\n        totalCreatorEarned += c; totalGrossEthVolume += gross; tradeCount++;\n        emit FeesAccrued(gross, c, b, cl);\n        if (liq > 0) emit LiquidityFeesAccrued(liq);\n        if(rewards>0)emit RewardsFeesAccrued(rewards);\n        total=c+b+cl+liq+rewards;\n        assert(total<=Math.mulDiv(gross,MAX_PROJECT_FEE_PPM,1_000_000));\n        return total;\n    }\n\n    function _takeSwapFee(Currency currency,uint256 fee) internal {\n        poolManager.take(currency,address(this),fee);\n        _flushCreatorAccrual();\n    }\n    function _flushCreatorAccrual() internal {\n        uint256 amount=_creatorAccrued;\n        if(amount==0)return;\n        _creatorAccrued=0;\n        (bool ok,)=address(creatorVault).call{value:amount}(\"\");\n        if(!ok)revert TransferFailed();\n    }\n    function _maintenanceBuybackFee(uint256) internal pure returns(uint256){return 0;}\n    function _projectTaxExempt(address sender,PoolKey calldata key) internal view returns(bool) {\n        if(sender!=taxRouter && sender!=launchCoordinator)return false;\n        IBoundedPayer route=IBoundedPayer(sender);\n        return route.activePoolId()==PoolId.unwrap(key.toId()) && projectTaxExempt[route.activePayer()];\n    }\n\n    function _setClausPool(PoolKey calldata key) internal {\n        if (Currency.unwrap(key.currency0) != address(0) || Currency.unwrap(key.currency1) != clausToken\n            || address(key.hooks) == address(this)) revert WrongPool();\n        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(key.toId());\n        if (sqrtPriceX96 == 0) revert WrongPool();\n        companionKey = key; clausPoolBound = true;\n        emit ClausPoolConfigured(PoolId.unwrap(key.toId()));\n    }\n\n    function pblAllocationPpm() external view returns(uint256) {\n        return BUYBACK_PPM-clausAllocationPpm-liquidityAllocationPpm-rewardsAllocationPpm;\n    }\n\n    function setModuleAllocation(uint16 clausPpm, uint16 liquidityPpm) external onlyOwner {\n        _setModuleAllocation(clausPpm, liquidityPpm);\n    }\n\n    function applyStrategyAllocation(uint16 clausPpm,uint16 liquidityPpm) external {\n        if(msg.sender!=address(strategyController))revert Unauthorized();\n        _setModuleAllocation(clausPpm,liquidityPpm);\n    }\n\n    function _setModuleAllocation(uint16 clausPpm, uint16 liquidityPpm) internal {\n        if (uint256(clausPpm) + liquidityPpm + rewardsAllocationPpm > BUYBACK_PPM || (clausPpm > 0 && !clausPoolBound)\n            || (liquidityPpm > 0 && (!poolBound || liquidityThreshold == 0 || address(lpReserve)==address(0)))) revert InvalidConfiguration();\n        clausAllocationPpm = clausPpm;\n        liquidityAllocationPpm = liquidityPpm;\n        emit ModuleRatesChanged(clausPpm, liquidityPpm);\n    }\n\n    /// @notice Only the fixed controller can bind its reviewed, fixed-runtime channel.\n    function bindRewardsChannel(address next) external {\n        if(msg.sender!=address(strategyController) || rewardsChannel!=address(0) || next==address(0))revert Unauthorized();\n        rewardsChannel=next;emit RewardsChannelActivated(next);\n    }\n    /// @notice All four module shares fit inside the EXISTING 1.7%, including LP.\n    /// Only future accrual changes. Enabling rewards needs a separate explicit owner action.\n    function setExtendedAllocation(uint16 clausPpm,uint16 liquidityPpm,uint16 rewardsPpm) external onlyOwner {\n        if(rewardsPpm>0 && rewardsChannel==address(0))revert InvalidConfiguration();\n        rewardsAllocationPpm=rewardsPpm;_setModuleAllocation(clausPpm,liquidityPpm);\n        emit RewardsAllocationChanged(rewardsPpm);\n    }\n    function fundRewards(uint256 amount) external nonReentrant {\n        if(msg.sender!=owner || rewardsChannel==address(0) || amount==0 || amount>rewardsReserve\n            || rewardsChannel.codehash!=strategyController.REWARDS_CHANNEL_CODEHASH())revert Unauthorized();\n        rewardsReserve-=amount;totalRewardsFunded+=amount;\n        (bool ok,)=rewardsChannel.call{value:amount}(\"\");if(!ok)revert TransferFailed();\n        assert(address(this).balance>=reservedEth());emit RewardsFunded(amount);\n    }\n\n    function setLiquidityThreshold(uint256 minimum) external onlyOwner {\n        if (minimum == 0 || minimum > maxBatch) revert InvalidConfiguration();\n        liquidityThreshold = minimum;\n    }\n\n    function setKeeper(address next) external onlyOwner {\n        if (next == address(0)) revert InvalidConfiguration(); keeper = next; emit KeeperChanged(next);\n    }\n\n    function setBuybackControls(bool paused, uint256 pblMin, uint256 clausMin, uint256 maximum, uint32 cooldown) external onlyOwner {\n        if (pblMin == 0 || clausMin == 0 || maximum < pblMin || maximum < clausMin || maximum < liquidityThreshold || maximum > 10 ether\n            || cooldown < 10 || cooldown > 7 days) revert InvalidConfiguration();\n        buybacksPaused = paused; pblThreshold = pblMin; clausThreshold = clausMin; maxBatch = maximum; cooldownSeconds = cooldown;\n        emit BuybackControlsChanged(paused, pblMin, clausMin, maximum, cooldown);\n    }\n\n    /// @notice Keeper pays gas. Only the chosen buyback bucket funds the purchase.\n    /// PBL is burned; CLAUS is delivered to the fixed separate treasury.\n    /// A failed quote, trade, PBL burn or CLAUS delivery reverts the complete batch.\n    function processBuyback(bool isClaus, uint256 amount, uint256 minTokensOut, uint160 priceLimit, uint256 deadline)\n        external nonReentrant returns (uint256 bought)\n    {\n        if (msg.sender != keeper && msg.sender != owner && msg.sender!=address(strategyController)) revert Unauthorized();\n        if (buybacksPaused || !poolBound || deadline < block.timestamp || deadline > block.timestamp + 5 minutes\n            || minTokensOut == 0 || amount > maxBatch || amount < (isClaus ? clausThreshold : pblThreshold)\n            || block.timestamp < (isClaus ? lastClausBatch : lastPblBatch) + cooldownSeconds\n            || priceLimit <= TickMath.MIN_SQRT_PRICE) revert BatchNotReady();\n        uint160 startingPrice; uint256 protectedMinimum;\n        (protectedMinimum,startingPrice)=executionPolicy.authorize(isClaus?1:0,amount,amount,isClaus?clausReserve:pblReserve);\n        if(minTokensOut<protectedMinimum)minTokensOut=protectedMinimum;\n        uint256 net = amount;\n        if (isClaus) {\n            if (!clausPoolBound || amount > clausReserve) revert BatchNotReady();\n            clausReserve -= amount; lastClausBatch = block.timestamp;\n        } else {\n            if (amount > pblReserve) revert BatchNotReady();\n            pblReserve -= amount; lastPblBatch = block.timestamp;\n            // Maintenance never re-taxes the project budget.\n            net -= _maintenanceBuybackFee(amount);\n        }\n        processing = true;\n        bought = abi.decode(poolManager.unlock(abi.encode(isClaus, net, minTokensOut, priceLimit)), (uint256));\n        processing = false;\n        executionPolicy.verifyPrice(isClaus?1:0,startingPrice);\n        if (isClaus) {\n            totalClausBought += bought; totalClausBuybackEth += amount;\n            emit ClausPurchased(clausRecipient(), amount, bought);\n        } else {\n            totalPblBurned += bought; totalPblBuybackEth += amount;\n            emit BuybackBurned(token, amount, bought);\n        }\n        assert(address(this).balance >= reservedEth());\n    }\n\n    function unlockCallback(bytes calldata data) external onlyManager returns (bytes memory) {\n        if (processingLiquidity) return _liquidityCallback(data);\n        if (!processing) revert Unauthorized();\n        (bool isClaus, uint256 amount, uint256 minOut, uint160 limit) = abi.decode(data, (bool,uint256,uint256,uint160));\n        PoolKey memory key = isClaus ? companionKey : primaryKey;\n        poolManager.settle{value: amount}();\n        BalanceDelta delta = poolManager.swap(key, IPoolManager.SwapParams(true, -int256(amount), limit), \"\");\n        // Exact input must be fully consumed; a price-limit partial fill is not silently accepted.\n        if (delta.amount0() != -int256(amount) || delta.amount1() <= 0) revert Slippage();\n        uint256 output = uint256(uint128(delta.amount1()));\n        if (output < minOut) revert Slippage();\n        address asset = Currency.unwrap(key.currency1);\n        if (isClaus) {\n            address recipient = clausRecipient();\n            if (recipient == address(0)) revert InvalidConfiguration();\n            uint256 beforeDelivery = IERC20(asset).balanceOf(recipient);\n            poolManager.take(key.currency1, recipient, output);\n            if (IERC20(asset).balanceOf(recipient) != beforeDelivery + output) revert Slippage();\n        } else {\n            poolManager.take(key.currency1, address(this), output);\n            uint256 supplyBefore = IERC20(asset).totalSupply();\n            uint256 balanceBefore = IERC20(asset).balanceOf(address(this));\n            IBurnable(asset).burn(output);\n            if (IERC20(asset).totalSupply() != supplyBefore - output || IERC20(asset).balanceOf(address(this)) != balanceBefore - output) revert Slippage();\n        }\n        return abi.encode(output);\n    }\n\n    function claimCreator() external nonReentrant {creatorVault.claim();}\n\n    /// @notice Fee-funded additions remain permanently locked in the same NFT.\n    function processLiquidity(uint256 amount,uint256 swapEth,uint256 minTokens,uint128 minLiquidity,uint160 limit,uint256 deadline)\n        external nonReentrant returns(uint128 liquidity,uint256 ethAdded,uint256 tokensAdded,uint256 pendingEth)\n    {\n        if (msg.sender!=keeper && msg.sender!=owner && msg.sender!=address(strategyController)) revert Unauthorized();\n        if (buybacksPaused || !poolBound || address(lpReserve)==address(0) || liquidityThreshold==0 || amount<liquidityThreshold\n            || amount>maxBatch || amount>liquidityReserve || block.timestamp<lastLiquidityBatch+cooldownSeconds\n            || deadline<block.timestamp || deadline>block.timestamp+5 minutes || swapEth==0 || swapEth>=amount\n            || minTokens==0 || minLiquidity==0 || limit<=TickMath.MIN_SQRT_PRICE) revert BatchNotReady();\n        if(swapEth>amount/2)revert InvalidConfiguration();\n        (uint256 protectedMinimum,uint160 startingPrice)=executionPolicy.authorize(2,amount,swapEth,liquidityReserve);\n        if(minTokens<protectedMinimum)minTokens=protectedMinimum;\n        liquidityReserve-=amount;lastLiquidityBatch=block.timestamp;\n        processingLiquidity=true;\n        (liquidity,ethAdded,tokensAdded,pendingEth)=abi.decode(poolManager.unlock(\n            abi.encode(amount,swapEth,minTokens,minLiquidity,limit)),(uint128,uint256,uint256,uint256));\n        processingLiquidity=false;\n        executionPolicy.verifyPrice(2,startingPrice);\n        totalLiquidityEthSpent+=amount;liquidityBatchCount++;\n        totalAutoEthDeposited+=ethAdded;totalAutoPblDeposited+=tokensAdded;totalAutoEthSwapped+=swapEth;\n        assert(address(this).balance>=reservedEth());\n        emit LiquidityAdded(amount,ethAdded,tokensAdded,liquidity);\n    }\n\n    function _liquidityCallback(bytes calldata data) internal returns(bytes memory) {\n        (uint256 budget,uint256 swapEth,uint256 minTokens,uint128 minLiquidity,uint160 limit)=\n            abi.decode(data,(uint256,uint256,uint256,uint128,uint160));\n        PebblePermanentLiquidity reserve=lpReserve;\n        uint256 pending0=poolManager.balanceOf(address(reserve),0);\n        uint256 tokenId=uint256(uint160(token));\n        uint256 pending1=poolManager.balanceOf(address(reserve),tokenId);\n        if(pending0!=0)poolManager.burn(address(reserve),0,pending0);\n        if(pending1!=0)poolManager.burn(address(reserve),tokenId,pending1);\n        // Maintenance does not tax its own budget again.\n        uint256 fee=0;\n        _flushCreatorAccrual();\n        poolManager.settle{value:budget-fee}();\n        BalanceDelta bought=poolManager.swap(primaryKey,IPoolManager.SwapParams(true,-int256(swapEth-fee),limit),\"\");\n        if(bought.amount0()!=-int256(swapEth-fee) || bought.amount1()<=0\n            || uint256(uint128(bought.amount1()))<minTokens)revert Slippage();\n        uint256 available0=budget-swapEth+pending0;\n        uint256 available1=uint256(uint128(bought.amount1()))+pending1;\n        return _depositLiquidity(available0,available1,minLiquidity);\n    }\n\n    /// @dev Keep the swap and deposit calculation in separate stack frames.\n    /// This preserves accounting while avoiding the Solidity 0.8.26 optimizer\n    /// failure in the combined callback. No storage layout is changed.\n    function _depositLiquidity(uint256 available0,uint256 available1,uint128 minLiquidity) internal returns(bytes memory) {\n        PebblePermanentLiquidity reserve=lpReserve;\n        (uint128 liquidity,uint256 ethAdded,uint256 tokensAdded)=_quoteLiquidity(available0,available1,minLiquidity);\n        poolManager.take(primaryKey.currency0,address(this),available0);\n        poolManager.take(primaryKey.currency1,address(reserve),available1);\n        reserve.increase{value:available0}(liquidity,uint128(available0),uint128(available1));\n        uint256 remaining0=poolManager.balanceOf(address(reserve),0);\n        // Report principal added, not net spending: collected LP fees may make\n        // the ending reserve claims larger than the inputs supplied to the NFT.\n        return abi.encode(liquidity,ethAdded,tokensAdded,remaining0);\n    }\n\n    function _quoteLiquidity(uint256 available0,uint256 available1,uint128 minLiquidity)\n        internal view returns(uint128 liquidity,uint256 ethAdded,uint256 tokensAdded)\n    {\n        (uint160 price,,,)=poolManager.getSlot0(primaryKey.toId());\n        uint160 lo=TickMath.getSqrtPriceAtTick(lpReserve.tickLower());\n        uint160 hi=TickMath.getSqrtPriceAtTick(lpReserve.tickUpper());\n        if(price<=lo || price>=hi)revert Slippage();\n        uint256 l0=FullMath.mulDiv(available0,FullMath.mulDiv(price,hi,1<<96),uint256(hi)-price);\n        uint256 l1=FullMath.mulDiv(available1,1<<96,uint256(price)-lo);\n        uint256 value=l0<l1?l0:l1;\n        if(value<minLiquidity || value>uint256(uint128(type(int128).max))\n            || available0>type(uint128).max || available1>type(uint128).max)revert Slippage();\n        liquidity=uint128(value);\n        ethAdded=SqrtPriceMath.getAmount0Delta(price,hi,liquidity,true);\n        tokensAdded=SqrtPriceMath.getAmount1Delta(lo,price,liquidity,true);\n    }\n\n    function proposeOwner(address next) external onlyOwner { if(next==address(0)) revert InvalidConfiguration(); pendingOwner=next; emit OwnerProposed(next); }\n    function acceptOwner() external { if(msg.sender!=pendingOwner) revert Unauthorized(); owner=msg.sender; pendingOwner=address(0); emit OwnerChanged(msg.sender); }\n    function _checkPool(PoolKey calldata key) internal view { if (!poolBound || PoolId.unwrap(key.toId())!=PoolId.unwrap(primaryKey.toId())) revert WrongPool(); }\n    receive() external payable { if(msg.sender!=address(poolManager)) revert Unauthorized(); }\n}\n\n\ninterface IBoundedPayer {\n    function activePayer() external view returns(address);\n    function activePoolId() external view returns(bytes32);\n}\n"},"contracts/PebbleQuoteLaunchCoordinator.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {IHooks} from \"@uniswap/v4-core/src/interfaces/IHooks.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId,PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {BalanceDelta} from \"@uniswap/v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"@uniswap/v4-core/src/libraries/TickMath.sol\";\nimport {FullMath} from \"@uniswap/v4-core/src/libraries/FullMath.sol\";\nimport {PebbleToken} from \"./PebbleToken.sol\";\nimport {PebbleSwapRouter} from \"./PebbleSwapRouter.sol\";\nimport {PebbleQuoteHook} from \"./PebbleQuoteHook.sol\";\nimport {PebblePermanentLiquidity} from \"./PebblePermanentLiquidity.sol\";\nimport {IPositionManager,IAllowanceTransfer} from \"./PebblePeripheryInterfaces.sol\";\n\n/// @notice A one-shot initializer target for the canonical CustomGraph factory.\n/// Supply is minted here; the first buy goes to the wallet and the LP goes directly\n/// to permanent custody. The wallet never owns or approves the launch NFT.\n/// No authority signature or platform-fee waiver is created by this contract.\ncontract PebbleQuoteLaunchCoordinator {\n    using PoolIdLibrary for PoolKey;\n    IPoolManager public immutable manager;\n    IPositionManager public immutable positionManager;\n    IAllowanceTransfer public immutable permit2;\n    address public immutable graphFactory;\n    address public immutable launchWallet;\n    address public immutable creatorWallet;\n    address public immutable clausTreasury;\n    address public immutable clausToken;\n    uint256 public constant DEV_BUY=0.15 ether;\n    bool public launched;\n    bool private launching;\n    bytes32 public activePoolId;\n    uint256 public tokenId;\n    uint256 public developerTokens;\n    uint256 public tokensDeposited;\n    int24 public lowerTick;\n    int24 public upperTick;\n\n    struct LaunchConfig {\n        address token;\n        address hook;\n        address reserve;\n        address router;\n        int24 lower;\n        int24 upper;\n        uint256 minDeveloperTokens;\n        PoolKey clausKey;\n    }\n    event GraphLaunchCompleted(address indexed token,address indexed hook,address indexed wallet,uint256 positionId,uint256 devTokens);\n\n    constructor(IPoolManager manager_,IPositionManager posm,IAllowanceTransfer permits,address factory_,\n        address wallet_,address creator_,address treasury_,address claus_) {\n        require(factory_!=address(0) && wallet_!=address(0) && creator_!=address(0)\n            && treasury_!=address(0) && claus_!=address(0),\"Zero configuration\");\n        require(posm.poolManager()==address(manager_) && posm.permit2()==address(permits),\"Periphery\");\n        manager=manager_;positionManager=posm;permit2=permits;graphFactory=factory_;\n        launchWallet=wallet_;creatorWallet=creator_;clausTreasury=treasury_;clausToken=claus_;\n    }\n\n    function positionLiquidity() external view returns(uint128){return positionManager.getPositionLiquidity(tokenId);}\n    function activePayer() external view returns(address){return launching ? launchWallet : address(0);}\n\n    function launch(LaunchConfig calldata config) external payable {\n        require(msg.sender==graphFactory && !launched && msg.value==DEV_BUY,\"Unauthorized launch\");\n        uint256 preexistingBalance=address(this).balance-msg.value;\n        require(config.lower>=TickMath.MIN_TICK && config.upper<=TickMath.MAX_TICK\n            && config.lower<config.upper && config.minDeveloperTokens>0,\"Launch limits\");\n        _validateComponents(config);\n        launched=true;launching=true;lowerTick=config.lower;upperTick=config.upper;\n        PoolKey memory key=PoolKey(Currency.wrap(address(0)),Currency.wrap(config.token),0x800000,1,IHooks(config.hook));\n        activePoolId=PoolId.unwrap(key.toId());\n        _mintPosition(key,config.lower,config.upper,config.reserve);\n        manager.unlock(abi.encode(key,config.minDeveloperTokens));\n        launching=false;\n        delete activePoolId;\n        PebblePermanentLiquidity(payable(config.reserve)).initialize(config.hook,config.token,tokenId);\n        PebbleQuoteHook safeHook=PebbleQuoteHook(payable(config.hook));\n        safeHook.executionPolicy().bind(config.hook,config.clausKey);\n        safeHook.strategyController().bind(config.hook);\n        safeHook.completeGraphLaunch(config.clausKey);\n        uint256 dust=PebbleToken(config.token).balanceOf(address(this));\n        if(dust!=0)require(PebbleToken(config.token).transfer(launchWallet,dust),\"Dust transfer\");\n        require(address(this).balance==preexistingBalance,\"Residual launch ETH\");\n        emit GraphLaunchCompleted(config.token,config.hook,launchWallet,tokenId,developerTokens);\n    }\n\n    function _validateComponents(LaunchConfig calldata config) private view {\n        PebbleQuoteHook hook=PebbleQuoteHook(payable(config.hook));\n        require(PebbleToken(config.token).owner()==launchWallet && config.token!=clausToken,\"Token\");\n        require(address(hook.poolManager())==address(manager) && hook.launchCoordinator()==address(this)\n            && hook.owner()==launchWallet && hook.deployerWallet()==launchWallet\n            && hook.creatorWallet()==creatorWallet && hook.clausRecipient()==clausTreasury\n            && hook.token()==config.token && hook.clausToken()==clausToken\n            && hook.feeMigrationComplete() && !hook.graphBootstrapComplete()\n            && address(hook.lpReserve())==config.reserve && hook.taxRouter()==config.router,\"Hook binding\");\n        require(address(hook.creatorVault()).code.length!=0 && hook.creatorVault().recipient()==creatorWallet,\"Creator vault\");\n        require(hook.projectTaxExempt(launchWallet) && hook.projectTaxExempt(creatorWallet)\n            && hook.projectTaxExempt(clausTreasury),\"Wallet exemptions\");\n        PebblePermanentLiquidity reserve=PebblePermanentLiquidity(payable(config.reserve));\n        require(reserve.coordinator()==address(this) && address(reserve.poolManager())==address(manager)\n            && address(reserve.positionManager())==address(positionManager)\n            && address(reserve.permit2())==address(permit2) && !reserve.initialized(),\"Reserve binding\");\n    }\n\n    function _mintPosition(PoolKey memory key,int24 lower,int24 upper,address custody) private {\n        PebbleToken asset=PebbleToken(Currency.unwrap(key.currency1));\n        uint256 supply=asset.totalSupply();\n        require(supply>0 && supply<=type(uint128).max && asset.balanceOf(address(this))==supply,\"Inventory\");\n        uint160 lo=TickMath.getSqrtPriceAtTick(lower);uint160 hi=TickMath.getSqrtPriceAtTick(upper);\n        uint256 liquidity=FullMath.mulDiv(supply,1<<96,uint256(hi)-lo);\n        require(liquidity>0 && liquidity<=uint256(uint128(type(int128).max)),\"Liquidity\");\n        manager.initialize(key,hi);tokenId=positionManager.nextTokenId();\n        require(asset.approve(address(permit2),supply),\"Approval\");\n        permit2.approve(address(asset),address(positionManager),uint160(supply),uint48(block.timestamp));\n        bytes[] memory args=new bytes[](2);\n        args[0]=abi.encode(key,lower,upper,liquidity,uint128(0),uint128(supply),custody,bytes(\"\"));\n        args[1]=abi.encode(key.currency0,key.currency1);\n        positionManager.modifyLiquidities(abi.encode(hex\"020d\",args),block.timestamp);\n        permit2.approve(address(asset),address(positionManager),0,0);\n        require(asset.approve(address(permit2),0),\"Revoke\");\n        tokensDeposited=supply-asset.balanceOf(address(this));\n        require(positionManager.ownerOf(tokenId)==custody\n            && positionManager.getPositionLiquidity(tokenId)==liquidity,\"Position\");\n    }\n\n    function unlockCallback(bytes calldata data) external returns(bytes memory) {\n        require(msg.sender==address(manager) && launching,\"Unauthorized callback\");\n        (PoolKey memory key,uint256 minimum)=abi.decode(data,(PoolKey,uint256));\n        manager.settle{value:DEV_BUY}();\n        BalanceDelta d=manager.swap(key,IPoolManager.SwapParams(true,-int256(DEV_BUY),TickMath.MIN_SQRT_PRICE+1),\"\");\n        require(d.amount0()==-int256(DEV_BUY) && d.amount1()>0,\"Partial first buy\");\n        developerTokens=uint256(uint128(d.amount1()));require(developerTokens>=minimum,\"Dev buy slippage\");\n        manager.take(key.currency1,launchWallet,developerTokens);\n        return \"\";\n    }\n}\n"},"contracts/PebbleQuotePolicy.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {StateLibrary} from \"@uniswap/v4-core/src/libraries/StateLibrary.sol\";\nimport {FullMath} from \"@uniswap/v4-core/src/libraries/FullMath.sol\";\n\ninterface IPolicyHook {function poolKey() external view returns(PoolKey memory);function token() external view returns(address);function clausToken() external view returns(address);}\n\n/// @notice Immutable execution envelope, including for owner-initiated maintenance.\n/// No custody or approvals. Never called from ordinary trading callbacks.\ncontract PebbleQuotePolicy {\n    using StateLibrary for IPoolManager;\n    using PoolIdLibrary for PoolKey;\n    uint256 public constant MAX_BATCH=0.005 ether;\n    uint256 public constant MAX_ROLLING_DAY=0.05 ether;\n    uint256 public constant MIN_INTERVAL=180;\n    uint256 public constant MAX_SQRT_PRICE_MOVE_BPS=50; // about 1% price movement\n    address public immutable coordinator;\n    IPoolManager public immutable manager;\n    address public immutable token;\n    address public immutable claus;\n    address public hook;\n    PoolKey private pblKey;\n    PoolKey private clausKey;\n    // 25 rolling hourly bins: conservative overcount at the oldest boundary;\n    // never the double-spend possible at a UTC daily reset.\n    uint64[25] private hourBins;\n    uint192[25] private spent;\n    uint256 public lastExecution;\n    error UnsafeExecution();\n    constructor(IPoolManager m,address coordinator_,address token_,address claus_) {\n        require(address(m)!=address(0) && coordinator_!=address(0) && token_!=address(0) && claus_!=address(0));\n        manager=m;coordinator=coordinator_;token=token_;claus=claus_;\n    }\n    function bind(address h,PoolKey calldata cl) external {\n        if(msg.sender!=coordinator || hook!=address(0) || h.code.length==0)revert UnsafeExecution();\n        PoolKey memory key=IPolicyHook(h).poolKey();\n        if(IPolicyHook(h).token()!=token || IPolicyHook(h).clausToken()!=claus || address(key.hooks)!=h\n            || Currency.unwrap(key.currency0)!=address(0) || Currency.unwrap(key.currency1)!=token\n            || Currency.unwrap(cl.currency0)!=address(0) || Currency.unwrap(cl.currency1)!=claus)revert UnsafeExecution();\n        hook=h;pblKey=key;clausKey=cl;\n    }\n    function rollingSpent() public view returns(uint256 total) {\n        uint256 hour=block.timestamp/1 hours;\n        for(uint256 i;i<25;i++)if(hourBins[i]<=hour && hour-hourBins[i]<=24)total+=spent[i];\n    }\n    function _price(PoolKey memory key) private view returns(uint160 sqrt,uint256 spot,uint256 virtualEth) {\n        (sqrt,,,)=manager.getSlot0(key.toId());\n        if(sqrt==0)revert UnsafeExecution();\n        // The intermediate remains within uint256 across valid V4 prices.\n        spot=FullMath.mulDiv(FullMath.mulDiv(sqrt,sqrt,1<<96),1 ether,1<<96);\n        virtualEth=FullMath.mulDiv(manager.getLiquidity(key.toId()),1<<96,sqrt);\n    }\n    function bounds(uint8 kind,uint256 budget,uint256 swapAmount,uint256 reserve)\n        public view returns(uint256 minimum,uint160 sqrt)\n    {\n        if(hook==address(0) || kind>2 || budget==0 || budget>MAX_BATCH || budget>reserve/10\n            || swapAmount==0 || swapAmount>budget || (kind==2 && swapAmount>budget/2))revert UnsafeExecution();\n        PoolKey memory key=kind==1?clausKey:pblKey;\n        uint256 spot;uint256 virtualEth;(sqrt,spot,virtualEth)=_price(key);\n        if(swapAmount>virtualEth/1000)revert UnsafeExecution();\n        // Same-pool spot sanity floor, not independent fair value. A manipulated\n        // starting price can pass. Callers should sign fresh, stricter quote minima.\n        minimum=FullMath.mulDiv(FullMath.mulDiv(swapAmount,spot,1 ether),kind==1?9500:9800,10000);\n        if(minimum==0)revert UnsafeExecution();\n    }\n    function authorize(uint8 kind,uint256 budget,uint256 swapAmount,uint256 reserve) external returns(uint256 minimum,uint160 sqrt) {\n        if(msg.sender!=hook || block.timestamp<lastExecution+MIN_INTERVAL || rollingSpent()+budget>MAX_ROLLING_DAY)revert UnsafeExecution();\n        (minimum,sqrt)=bounds(kind,budget,swapAmount,reserve);\n        uint256 hour=block.timestamp/1 hours;uint256 slot=hour%25;\n        if(hourBins[slot]!=hour){hourBins[slot]=uint64(hour);spent[slot]=0;}\n        spent[slot]+=uint192(budget);lastExecution=block.timestamp;\n    }\n    function verifyPrice(uint8 kind,uint160 beforeSqrt) external view {\n        if(msg.sender!=hook || kind>2)revert UnsafeExecution();\n        (uint160 afterSqrt,,)=_price(kind==1?clausKey:pblKey);\n        if(uint256(afterSqrt)*10000<uint256(beforeSqrt)*(10000-MAX_SQRT_PRICE_MOVE_BPS))revert UnsafeExecution();\n    }\n}\n"},"contracts/PebbleSwapRouter.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\nimport {IPoolManager} from \"@uniswap/v4-core/src/interfaces/IPoolManager.sol\";\nimport {PoolKey} from \"@uniswap/v4-core/src/types/PoolKey.sol\";\nimport {PoolId,PoolIdLibrary} from \"@uniswap/v4-core/src/types/PoolId.sol\";\nimport {Currency} from \"@uniswap/v4-core/src/types/Currency.sol\";\nimport {BalanceDelta} from \"@uniswap/v4-core/src/types/BalanceDelta.sol\";\nimport {TickMath} from \"@uniswap/v4-core/src/libraries/TickMath.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\ncontract PebbleSwapRouter {\n    using SafeERC20 for IERC20;\n    using PoolIdLibrary for PoolKey;\n    IPoolManager public immutable manager; bool private swapping;\n    // Set exclusively from the external caller, for the duration of one funded\n    // swap. Never accept a claimed payer, recipient or exemption in calldata.\n    address public activePayer;\n    bytes32 public activePoolId;\n    constructor(IPoolManager manager_) { manager=manager_; }\n    function swap(PoolKey calldata key, bool buy, uint256 input, uint256 minOutput, uint256 deadline) external payable returns(uint256 output) {\n        require(!swapping && block.timestamp<=deadline && deadline<=block.timestamp+5 minutes,\"Swap unavailable\");\n        require(input>0 && input<=uint256(uint128(type(int128).max)) && minOutput>0,\"Amounts\");\n        require(Currency.unwrap(key.currency0)==address(0) && msg.value==(buy?input:0),\"Funding\");\n        swapping=true;\n        activePayer=msg.sender;activePoolId=PoolId.unwrap(key.toId());\n        output=abi.decode(manager.unlock(abi.encode(msg.sender,key,buy,input,minOutput)),(uint256));\n        delete activePayer;delete activePoolId;\n        swapping=false;\n    }\n    function unlockCallback(bytes calldata data) external returns(bytes memory) {\n        require(msg.sender==address(manager) && swapping,\"Unauthorized callback\");\n        (address payer,PoolKey memory key,bool buy,uint256 input,uint256 minOut)=abi.decode(data,(address,PoolKey,bool,uint256,uint256));\n        if(buy) manager.settle{value:input}();\n        BalanceDelta delta=manager.swap(key,IPoolManager.SwapParams(buy,-int256(input),buy?TickMath.MIN_SQRT_PRICE+1:TickMath.MAX_SQRT_PRICE-1),\"\");\n        require((buy?delta.amount0():delta.amount1())==-int256(input),\"Partial fill\");\n        int128 received=buy?delta.amount1():delta.amount0(); require(received>0 && uint256(uint128(received))>=minOut,\"Slippage\");\n        // V4 permits settlement after the swap. Restricted tokens such as CLAUS\n        // grant the transfer allowance in afterSwap, so token input must settle\n        // only after that callback. A failed payment reverts the whole unlock.\n        if(!buy) { manager.sync(key.currency1); IERC20(Currency.unwrap(key.currency1)).safeTransferFrom(payer,address(manager),input); manager.settle(); }\n        manager.take(buy?key.currency1:key.currency0,payer,uint256(uint128(received)));\n        return abi.encode(uint256(uint128(received)));\n    }\n}\n"},"contracts/PebbleToken.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.26;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {ERC20Burnable} from \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol\";\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {Ownable2Step} from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\n\n/// @notice Fixed supply, standard transfers, optional owner-controlled display identity.\ncontract PebbleToken is ERC20Burnable, Ownable2Step {\n    string private displayName;\n    string private displaySymbol;\n    event IdentityChanged(string name, string symbol);\n\n    constructor(address owner_, address inventory, uint256 supply)\n        ERC20(\"Pebble\", \"PBL\") Ownable(owner_)\n    {\n        require(inventory != address(0) && supply > 0, \"Bad inventory\");\n        displayName = \"Pebble\"; displaySymbol = \"PBL\";\n        _mint(inventory, supply);\n    }\n\n    function name() public view override returns (string memory) { return displayName; }\n    function symbol() public view override returns (string memory) { return displaySymbol; }\n\n    function setIdentity(string calldata name_, string calldata symbol_) external onlyOwner {\n        require(bytes(name_).length > 0 && bytes(name_).length <= 64, \"Bad name\");\n        require(bytes(symbol_).length > 0 && bytes(symbol_).length <= 12, \"Bad symbol\");\n        displayName = name_; displaySymbol = symbol_;\n        emit IdentityChanged(name_, symbol_);\n    }\n}\n"},"vendor/openzeppelin/contracts/access/Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"},"vendor/openzeppelin/contracts/access/Ownable2Step.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.20;\n\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * This extension of the {Ownable} contract includes a two-step mechanism to transfer\n * ownership, where the new owner must call {acceptOwnership} in order to replace the\n * old one. This can help prevent common mistakes, such as transfers of ownership to\n * incorrect accounts, or to contracts that are unable to interact with the\n * permission system.\n *\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2Step is Ownable {\n    address private _pendingOwner;\n\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Returns the address of the pending owner.\n     */\n    function pendingOwner() public view virtual returns (address) {\n        return _pendingOwner;\n    }\n\n    /**\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n     * Can only be called by the current owner.\n     *\n     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.\n     */\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\n        _pendingOwner = newOwner;\n        emit OwnershipTransferStarted(owner(), newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual override {\n        delete _pendingOwner;\n        super._transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev The new owner accepts the ownership transfer.\n     */\n    function acceptOwnership() public virtual {\n        address sender = _msgSender();\n        if (pendingOwner() != sender) {\n            revert OwnableUnauthorizedAccount(sender);\n        }\n        _transferOwnership(sender);\n    }\n}\n"},"vendor/openzeppelin/contracts/interfaces/IERC1363.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n    /*\n     * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n     * 0xb0202a11 ===\n     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n     */\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @param data Additional data with no specified format, sent in call to `spender`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"},"vendor/openzeppelin/contracts/interfaces/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},"vendor/openzeppelin/contracts/interfaces/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},"vendor/openzeppelin/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)\npragma solidity >=0.8.4;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`\u2019s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`\u2019s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`\u2019s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"vendor/openzeppelin/contracts/token/ERC20/ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC20Metadata} from \"./extensions/IERC20Metadata.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {IERC20Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n    mapping(address account => uint256) private _balances;\n\n    mapping(address account => mapping(address spender => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * Both values are immutable: they can only be set once during construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /// @inheritdoc IERC20\n    function totalSupply() public view virtual returns (uint256) {\n        return _totalSupply;\n    }\n\n    /// @inheritdoc IERC20\n    function balanceOf(address account) public view virtual returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /// @inheritdoc IERC20\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            _totalSupply += value;\n        } else {\n            uint256 fromBalance = _balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                _balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                _totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                _balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n     * true using the following override:\n     *\n     * ```solidity\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        _allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance < type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},"vendor/openzeppelin/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},"vendor/openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC20} from \"../ERC20.sol\";\nimport {Context} from \"../../../utils/Context.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20Burnable is Context, ERC20 {\n    /**\n     * @dev Destroys a `value` amount of tokens from the caller.\n     *\n     * See {ERC20-_burn}.\n     */\n    function burn(uint256 value) public virtual {\n        _burn(_msgSender(), value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, deducting from\n     * the caller's allowance.\n     *\n     * See {ERC20-_burn} and {ERC20-allowance}.\n     *\n     * Requirements:\n     *\n     * - the caller must have allowance for ``accounts``'s tokens of at least\n     * `value`.\n     */\n    function burnFrom(address account, uint256 value) public virtual {\n        _spendAllowance(account, _msgSender(), value);\n        _burn(account, value);\n    }\n}\n"},"vendor/openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"vendor/openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    /**\n     * @dev An operation with an ERC-20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {\n        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {\n        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     *\n     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n     * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n     * set here.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            safeTransfer(token, to, value);\n        } else if (!token.transferAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferFromAndCallRelaxed(\n        IERC1363 token,\n        address from,\n        address to,\n        uint256 value,\n        bytes memory data\n    ) internal {\n        if (to.code.length == 0) {\n            safeTransferFrom(token, from, to, value);\n        } else if (!token.transferFromAndCall(from, to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n     * once without retrying, and relies on the returned value to be true.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            forceApprove(token, to, value);\n        } else if (!token.approveAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            // bubble errors\n            if iszero(success) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n\n        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        bool success;\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n    }\n}\n"},"vendor/openzeppelin/contracts/utils/Context.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"vendor/openzeppelin/contracts/utils/Panic.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},"vendor/openzeppelin/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"vendor/openzeppelin/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Return the 512-bit addition of two uint256.\n     *\n     * The result is stored in two 256 variables such that sum = high * 2\u00b2\u2075\u2076 + low.\n     */\n    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        assembly (\"memory-safe\") {\n            low := add(a, b)\n            high := lt(low, a)\n        }\n    }\n\n    /**\n     * @dev Return the 512-bit multiplication of two uint256.\n     *\n     * The result is stored in two 256 variables such that product = high * 2\u00b2\u2075\u2076 + low.\n     */\n    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        // 512-bit multiply [high low] = x * y. Compute the product mod 2\u00b2\u2075\u2076 and mod 2\u00b2\u2075\u2076 - 1, then use\n        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = high * 2\u00b2\u2075\u2076 + low.\n        assembly (\"memory-safe\") {\n            let mm := mulmod(a, b, not(0))\n            low := mul(a, b)\n            high := sub(sub(mm, low), lt(mm, low))\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            success = c >= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a - b;\n            success = c <= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a * b;\n            assembly (\"memory-safe\") {\n                // Only true when the multiplication doesn't overflow\n                // (c / a == b) || (a == 0)\n                success := or(eq(div(c, a), b), iszero(a))\n            }\n            // equivalent to: success ? c : 0\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `DIV` opcode returns zero when the denominator is 0.\n                result := div(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `MOD` opcode returns zero when the denominator is 0.\n                result := mod(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Unsigned saturating addition, bounds to `2\u00b2\u2075\u2076 - 1` instead of overflowing.\n     */\n    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryAdd(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.\n     */\n    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {\n        (, uint256 result) = trySub(a, b);\n        return result;\n    }\n\n    /**\n     * @dev Unsigned saturating multiplication, bounds to `2\u00b2\u2075\u2076 - 1` instead of overflowing.\n     */\n    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryMul(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (high == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return low / denominator;\n            }\n\n            // Make sure the result is less than 2\u00b2\u2075\u2076. Also prevents denominator == 0.\n            if (denominator <= high) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [high low].\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                high := sub(high, gt(remainder, low))\n                low := sub(low, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly (\"memory-safe\") {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [high low] by twos.\n                low := div(low, twos)\n\n                // Flip twos such that it is 2\u00b2\u2075\u2076 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from high into low.\n            low |= high * twos;\n\n            // Invert denominator mod 2\u00b2\u2075\u2076. Now that denominator is an odd number, it has an inverse modulo 2\u00b2\u2075\u2076 such\n            // that denominator * inv \u2261 1 mod 2\u00b2\u2075\u2076. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv \u2261 1 mod 2\u2074.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2\u2078\n            inverse *= 2 - denominator * inverse; // inverse mod 2\u00b9\u2076\n            inverse *= 2 - denominator * inverse; // inverse mod 2\u00b3\u00b2\n            inverse *= 2 - denominator * inverse; // inverse mod 2\u2076\u2074\n            inverse *= 2 - denominator * inverse; // inverse mod 2\u00b9\u00b2\u2078\n            inverse *= 2 - denominator * inverse; // inverse mod 2\u00b2\u2075\u2076\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2\u00b2\u2075\u2076. Since the preconditions guarantee that the outcome is\n            // less than 2\u00b2\u2075\u2076, this is the final result. We don't need to compute the high bits of the result and high\n            // is no longer required.\n            result = low * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n            if (high >= 1 << n) {\n                Panic.panic(Panic.UNDER_OVERFLOW);\n            }\n            return (high << (256 - n)) | (low >> n);\n        }\n    }\n\n    /**\n     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {\n        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax \u2261 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) \u2261 1 mod p`. As a consequence, we have `a * a**(p-2) \u2261 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {\n        for (uint256 i = 0; i < byteArray.length; ++i) {\n            if (byteArray[i] != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x\u00b2 - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `\u03b5_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) \u2264 sqrt(a) < 2**e`). We know that `e \u2264 128` because `(2\u00b9\u00b2\u2078)\u00b2 = 2\u00b2\u2075\u2076` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) \u2264 sqrt(a) < 2**e \u2192 (2**(e-1))\u00b2 \u2264 a < (2**e)\u00b2 \u2192 2**(2*e-2) \u2264 a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // We now have x_n such that `x_n = 2**(e-1) \u2264 sqrt(a) < 2**e = 2 * x_n`. This implies \u03b5_n \u2264 2**(e-1).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to \u03b5_n \u2264 2**(e-2).\n            // This is going to be our x_0 (and \u03b5_0)\n            xn = (3 * xn) >> 1; // \u03b5_0 := | x_0 - sqrt(a) | \u2264 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}\u00b2 - a = ((x_n + a / x_n) / 2)\u00b2 - a\n            //              = ((x_n\u00b2 + a) / (2 * x_n))\u00b2 - a\n            //              = (x_n\u2074 + 2 * a * x_n\u00b2 + a\u00b2) / (4 * x_n\u00b2) - a\n            //              = (x_n\u2074 + 2 * a * x_n\u00b2 + a\u00b2 - 4 * a * x_n\u00b2) / (4 * x_n\u00b2)\n            //              = (x_n\u2074 - 2 * a * x_n\u00b2 + a\u00b2) / (4 * x_n\u00b2)\n            //              = (x_n\u00b2 - a)\u00b2 / (2 * x_n)\u00b2\n            //              = ((x_n\u00b2 - a) / (2 * x_n))\u00b2\n            //              \u2265 0\n            // Which proves that for all n \u2265 1, sqrt(a) \u2264 x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // \u03b5_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n\u00b2 + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))\u00b2 / (2 * x_n) |\n            //         = | \u03b5_n\u00b2 / (2 * x_n) |\n            //         = \u03b5_n\u00b2 / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // \u03b5_1 = \u03b5_0\u00b2 / | (2 * x_0) |\n            //     \u2264 (2**(e-2))\u00b2 / (2 * (2**(e-1) + 2**(e-2)))\n            //     \u2264 2**(2*e-4) / (3 * 2**(e-1))\n            //     \u2264 2**(e-3) / 3\n            //     \u2264 2**(e-3-log2(3))\n            //     \u2264 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) \u2264 sqrt(a) \u2264 x_n:\n            // \u03b5_{n+1} = \u03b5_n\u00b2 / | (2 * x_n) |\n            //         \u2264 (2**(e-k))\u00b2 / (2 * 2**(e-1))\n            //         \u2264 2**(2*e-2*k) / 2**e\n            //         \u2264 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // \u03b5_1 := | x_1 - sqrt(a) | \u2264 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // \u03b5_2 := | x_2 - sqrt(a) | \u2264 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // \u03b5_3 := | x_3 - sqrt(a) | \u2264 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // \u03b5_4 := | x_4 - sqrt(a) | \u2264 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // \u03b5_5 := | x_5 - sqrt(a) | \u2264 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // \u03b5_6 := | x_6 - sqrt(a) | \u2264 2**(e-144)  -- general case with k = 72\n\n            // Because e \u2264 128 (as discussed during the first estimation phase), we know have reached a precision\n            // \u03b5_6 \u2264 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // If upper 8 bits of 16-bit half set, add 8 to result\n        r |= SafeCast.toUint((x >> r) > 0xff) << 3;\n        // If upper 4 bits of 8-bit half set, add 4 to result\n        r |= SafeCast.toUint((x >> r) > 0xf) << 2;\n\n        // Shifts value right by the current result and use it as an index into this lookup table:\n        //\n        // | x (4 bits) |  index  | table[index] = MSB position |\n        // |------------|---------|-----------------------------|\n        // |    0000    |    0    |        table[0] = 0         |\n        // |    0001    |    1    |        table[1] = 0         |\n        // |    0010    |    2    |        table[2] = 1         |\n        // |    0011    |    3    |        table[3] = 1         |\n        // |    0100    |    4    |        table[4] = 2         |\n        // |    0101    |    5    |        table[5] = 2         |\n        // |    0110    |    6    |        table[6] = 2         |\n        // |    0111    |    7    |        table[7] = 2         |\n        // |    1000    |    8    |        table[8] = 3         |\n        // |    1001    |    9    |        table[9] = 3         |\n        // |    1010    |   10    |        table[10] = 3        |\n        // |    1011    |   11    |        table[11] = 3        |\n        // |    1100    |   12    |        table[12] = 3        |\n        // |    1101    |   13    |        table[13] = 3        |\n        // |    1110    |   14    |        table[14] = 3        |\n        // |    1111    |   15    |        table[15] = 3        |\n        //\n        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.\n        assembly (\"memory-safe\") {\n            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8\n        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},"vendor/openzeppelin/contracts/utils/math/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev An uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},"vendor/v4-core/src/interfaces/IExtsload.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for functions to access any storage slot in a contract\ninterface IExtsload {\n    /// @notice Called by external contracts to access granular pool state\n    /// @param slot Key of slot to sload\n    /// @return value The value of the slot as bytes32\n    function extsload(bytes32 slot) external view returns (bytes32 value);\n\n    /// @notice Called by external contracts to access granular pool state\n    /// @param startSlot Key of slot to start sloading from\n    /// @param nSlots Number of slots to load into return value\n    /// @return values List of loaded values.\n    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);\n\n    /// @notice Called by external contracts to access sparse pool state\n    /// @param slots List of slots to SLOAD from.\n    /// @return values List of loaded values.\n    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n"},"vendor/v4-core/src/interfaces/IExttload.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\n/// @notice Interface for functions to access any transient storage slot in a contract\ninterface IExttload {\n    /// @notice Called by external contracts to access transient storage of the contract\n    /// @param slot Key of slot to tload\n    /// @return value The value of the slot as bytes32\n    function exttload(bytes32 slot) external view returns (bytes32 value);\n\n    /// @notice Called by external contracts to access sparse transient pool state\n    /// @param slots List of slots to tload\n    /// @return values List of loaded values\n    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);\n}\n"},"vendor/v4-core/src/interfaces/IHooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {IPoolManager} from \"./IPoolManager.sol\";\nimport {BeforeSwapDelta} from \"../types/BeforeSwapDelta.sol\";\n\n/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits\n/// of the address that the hooks contract is deployed to.\n/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400\n/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.\n/// See the Hooks library for the full spec.\n/// @dev Should only be callable by the v4 PoolManager.\ninterface IHooks {\n    /// @notice The hook called before the state of a pool is initialized\n    /// @param sender The initial msg.sender for the initialize call\n    /// @param key The key for the pool being initialized\n    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n    /// @return bytes4 The function selector for the hook\n    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);\n\n    /// @notice The hook called after the state of a pool is initialized\n    /// @param sender The initial msg.sender for the initialize call\n    /// @param key The key for the pool being initialized\n    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96\n    /// @param tick The current tick after the state of a pool is initialized\n    /// @return bytes4 The function selector for the hook\n    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)\n        external\n        returns (bytes4);\n\n    /// @notice The hook called before liquidity is added\n    /// @param sender The initial msg.sender for the add liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for adding liquidity\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        IPoolManager.ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after liquidity is added\n    /// @param sender The initial msg.sender for the add liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for adding liquidity\n    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta\n    /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterAddLiquidity(\n        address sender,\n        PoolKey calldata key,\n        IPoolManager.ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external returns (bytes4, BalanceDelta);\n\n    /// @notice The hook called before liquidity is removed\n    /// @param sender The initial msg.sender for the remove liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for removing liquidity\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        IPoolManager.ModifyLiquidityParams calldata params,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after liquidity is removed\n    /// @param sender The initial msg.sender for the remove liquidity call\n    /// @param key The key for the pool\n    /// @param params The parameters for removing liquidity\n    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta\n    /// @param feesAccrued The fees accrued since the last time fees were collected from this position\n    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterRemoveLiquidity(\n        address sender,\n        PoolKey calldata key,\n        IPoolManager.ModifyLiquidityParams calldata params,\n        BalanceDelta delta,\n        BalanceDelta feesAccrued,\n        bytes calldata hookData\n    ) external returns (bytes4, BalanceDelta);\n\n    /// @notice The hook called before a swap\n    /// @param sender The initial msg.sender for the swap call\n    /// @param key The key for the pool\n    /// @param params The parameters for the swap\n    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    /// @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)\n    function beforeSwap(\n        address sender,\n        PoolKey calldata key,\n        IPoolManager.SwapParams calldata params,\n        bytes calldata hookData\n    ) external returns (bytes4, BeforeSwapDelta, uint24);\n\n    /// @notice The hook called after a swap\n    /// @param sender The initial msg.sender for the swap call\n    /// @param key The key for the pool\n    /// @param params The parameters for the swap\n    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)\n    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency\n    function afterSwap(\n        address sender,\n        PoolKey calldata key,\n        IPoolManager.SwapParams calldata params,\n        BalanceDelta delta,\n        bytes calldata hookData\n    ) external returns (bytes4, int128);\n\n    /// @notice The hook called before donate\n    /// @param sender The initial msg.sender for the donate call\n    /// @param key The key for the pool\n    /// @param amount0 The amount of token0 being donated\n    /// @param amount1 The amount of token1 being donated\n    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function beforeDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external returns (bytes4);\n\n    /// @notice The hook called after donate\n    /// @param sender The initial msg.sender for the donate call\n    /// @param key The key for the pool\n    /// @param amount0 The amount of token0 being donated\n    /// @param amount1 The amount of token1 being donated\n    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook\n    /// @return bytes4 The function selector for the hook\n    function afterDonate(\n        address sender,\n        PoolKey calldata key,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata hookData\n    ) external returns (bytes4);\n}\n"},"vendor/v4-core/src/interfaces/IPoolManager.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\nimport {IHooks} from \"./IHooks.sol\";\nimport {IERC6909Claims} from \"./external/IERC6909Claims.sol\";\nimport {IProtocolFees} from \"./IProtocolFees.sol\";\nimport {BalanceDelta} from \"../types/BalanceDelta.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IExtsload} from \"./IExtsload.sol\";\nimport {IExttload} from \"./IExttload.sol\";\n\n/// @notice Interface for the PoolManager\ninterface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {\n    /// @notice Thrown when a currency is not netted out after the contract is unlocked\n    error CurrencyNotSettled();\n\n    /// @notice Thrown when trying to interact with a non-initialized pool\n    error PoolNotInitialized();\n\n    /// @notice Thrown when unlock is called, but the contract is already unlocked\n    error AlreadyUnlocked();\n\n    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not\n    error ManagerLocked();\n\n    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow\n    error TickSpacingTooLarge(int24 tickSpacing);\n\n    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize\n    error TickSpacingTooSmall(int24 tickSpacing);\n\n    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)\n    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);\n\n    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,\n    /// or on a pool that does not have a dynamic swap fee.\n    error UnauthorizedDynamicLPFeeUpdate();\n\n    /// @notice Thrown when trying to swap amount of 0\n    error SwapAmountCannotBeZero();\n\n    ///@notice Thrown when native currency is passed to a non native settlement\n    error NonzeroNativeValue();\n\n    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.\n    error MustClearExactPositiveDelta();\n\n    /// @notice Emitted when a new pool is initialized\n    /// @param id The abi encoded hash of the pool key struct for the new pool\n    /// @param currency0 The first currency of the pool by address sort order\n    /// @param currency1 The second currency of the pool by address sort order\n    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// @param tickSpacing The minimum number of ticks between initialized ticks\n    /// @param hooks The hooks contract address for the pool, or address(0) if none\n    /// @param sqrtPriceX96 The price of the pool on initialization\n    /// @param tick The initial tick of the pool corresponding to the initialized price\n    event Initialize(\n        PoolId indexed id,\n        Currency indexed currency0,\n        Currency indexed currency1,\n        uint24 fee,\n        int24 tickSpacing,\n        IHooks hooks,\n        uint160 sqrtPriceX96,\n        int24 tick\n    );\n\n    /// @notice Emitted when a liquidity position is modified\n    /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n    /// @param sender The address that modified the pool\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param liquidityDelta The amount of liquidity that was added or removed\n    /// @param salt The extra data to make positions unique\n    event ModifyLiquidity(\n        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt\n    );\n\n    /// @notice Emitted for swaps between currency0 and currency1\n    /// @param id The abi encoded hash of the pool key struct for the pool that was modified\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param amount0 The delta of the currency0 balance of the pool\n    /// @param amount1 The delta of the currency1 balance of the pool\n    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n    /// @param liquidity The liquidity of the pool after the swap\n    /// @param tick The log base 1.0001 of the price of the pool after the swap\n    /// @param fee The swap fee in hundredths of a bip\n    event Swap(\n        PoolId indexed id,\n        address indexed sender,\n        int128 amount0,\n        int128 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick,\n        uint24 fee\n    );\n\n    /// @notice Emitted for donations\n    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to\n    /// @param sender The address that initiated the donate call\n    /// @param amount0 The amount donated in currency0\n    /// @param amount1 The amount donated in currency1\n    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);\n\n    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement\n    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.\n    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`\n    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`\n    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`\n    function unlock(bytes calldata data) external returns (bytes memory);\n\n    /// @notice Initialize the state for a given pool ID\n    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n    /// @param key The pool key for the pool to initialize\n    /// @param sqrtPriceX96 The initial square root price\n    /// @return tick The initial tick of the pool\n    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);\n\n    struct ModifyLiquidityParams {\n        // the lower and upper tick of the position\n        int24 tickLower;\n        int24 tickUpper;\n        // how to modify the liquidity\n        int256 liquidityDelta;\n        // a value to set if you want unique liquidity positions at the same range\n        bytes32 salt;\n    }\n\n    /// @notice Modify the liquidity for the given pool\n    /// @dev Poke by calling with a zero liquidityDelta\n    /// @param key The pool to modify liquidity in\n    /// @param params The parameters for modifying the liquidity\n    /// @param hookData The data to pass through to the add/removeLiquidity hooks\n    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable\n    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes\n    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value\n    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)\n    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)\n        external\n        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);\n\n    struct SwapParams {\n        /// Whether to swap token0 for token1 or vice versa\n        bool zeroForOne;\n        /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)\n        int256 amountSpecified;\n        /// The sqrt price at which, if reached, the swap will stop executing\n        uint160 sqrtPriceLimitX96;\n    }\n\n    /// @notice Swap against the given pool\n    /// @param key The pool to swap in\n    /// @param params The parameters for swapping\n    /// @param hookData The data to pass through to the swap hooks\n    /// @return swapDelta The balance delta of the address swapping\n    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.\n    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG\n    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.\n    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)\n        external\n        returns (BalanceDelta swapDelta);\n\n    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool\n    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.\n    /// Donors should keep this in mind when designing donation mechanisms.\n    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of\n    /// 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\n    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).\n    /// Read the comments in `Pool.swap()` for more information about this.\n    /// @param key The key of the pool to donate to\n    /// @param amount0 The amount of currency0 to donate\n    /// @param amount1 The amount of currency1 to donate\n    /// @param hookData The data to pass through to the donate hooks\n    /// @return BalanceDelta The delta of the caller after the donate\n    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)\n        external\n        returns (BalanceDelta);\n\n    /// @notice Writes the current ERC20 balance of the specified currency to transient storage\n    /// This is used to checkpoint balances for the manager and derive deltas for the caller.\n    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped\n    /// for native tokens because the amount to settle is determined by the sent value.\n    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle\n    /// native funds, this function can be called with the native currency to then be able to settle the native currency\n    function sync(Currency currency) external;\n\n    /// @notice Called by the user to net out some value owed to the user\n    /// @dev Will revert if the requested amount is not available, consider using `mint` instead\n    /// @dev Can also be used as a mechanism for free flash loans\n    /// @param currency The currency to withdraw from the pool manager\n    /// @param to The address to withdraw to\n    /// @param amount The amount of currency to withdraw\n    function take(Currency currency, address to, uint256 amount) external;\n\n    /// @notice Called by the user to pay what is owed\n    /// @return paid The amount of currency settled\n    function settle() external payable returns (uint256 paid);\n\n    /// @notice Called by the user to pay on behalf of another address\n    /// @param recipient The address to credit for the payment\n    /// @return paid The amount of currency settled\n    function settleFor(address recipient) external payable returns (uint256 paid);\n\n    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.\n    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.\n    /// @dev This could be used to clear a balance that is considered dust.\n    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.\n    function clear(Currency currency, uint256 amount) external;\n\n    /// @notice Called by the user to move value into ERC6909 balance\n    /// @param to The address to mint the tokens to\n    /// @param id The currency address to mint to ERC6909s, as a uint256\n    /// @param amount The amount of currency to mint\n    /// @dev The id is converted to a uint160 to correspond to a currency address\n    /// If the upper 12 bytes are not 0, they will be 0-ed out\n    function mint(address to, uint256 id, uint256 amount) external;\n\n    /// @notice Called by the user to move value from ERC6909 balance\n    /// @param from The address to burn the tokens from\n    /// @param id The currency address to burn from ERC6909s, as a uint256\n    /// @param amount The amount of currency to burn\n    /// @dev The id is converted to a uint160 to correspond to a currency address\n    /// If the upper 12 bytes are not 0, they will be 0-ed out\n    function burn(address from, uint256 id, uint256 amount) external;\n\n    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.\n    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee\n    /// @param key The key of the pool to update dynamic LP fees for\n    /// @param newDynamicLPFee The new dynamic pool LP fee\n    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;\n}\n"},"vendor/v4-core/src/interfaces/IProtocolFees.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"../types/Currency.sol\";\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {PoolKey} from \"../types/PoolKey.sol\";\n\n/// @notice Interface for all protocol-fee related functions in the pool manager\ninterface IProtocolFees {\n    /// @notice Thrown when protocol fee is set too high\n    error ProtocolFeeTooLarge(uint24 fee);\n\n    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.\n    error InvalidCaller();\n\n    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.\n    error ProtocolFeeCurrencySynced();\n\n    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.\n    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);\n\n    /// @notice Emitted when the protocol fee is updated for a pool.\n    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);\n\n    /// @notice Given a currency address, returns the protocol fees accrued in that currency\n    /// @param currency The currency to check\n    /// @return amount The amount of protocol fees accrued in the currency\n    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);\n\n    /// @notice Sets the protocol fee for the given pool\n    /// @param key The key of the pool to set a protocol fee for\n    /// @param newProtocolFee The fee to set\n    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;\n\n    /// @notice Sets the protocol fee controller\n    /// @param controller The new protocol fee controller\n    function setProtocolFeeController(address controller) external;\n\n    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected\n    /// @dev This will revert if the contract is unlocked\n    /// @param recipient The address to receive the protocol fees\n    /// @param currency The currency to withdraw\n    /// @param amount The amount of currency to withdraw\n    /// @return amountCollected The amount of currency successfully withdrawn\n    function collectProtocolFees(address recipient, Currency currency, uint256 amount)\n        external\n        returns (uint256 amountCollected);\n\n    /// @notice Returns the current protocol fee controller address\n    /// @return address The current protocol fee controller address\n    function protocolFeeController() external view returns (address);\n}\n"},"vendor/v4-core/src/interfaces/external/IERC20Minimal.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n    /// @notice Returns an account's balance in the token\n    /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n    /// @return The number of tokens held by the account\n    function balanceOf(address account) external view returns (uint256);\n\n    /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n    /// @param recipient The account that will receive the amount transferred\n    /// @param amount The number of tokens to send from the sender to the recipient\n    /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /// @notice Returns the current allowance given to a spender by an owner\n    /// @param owner The account of the token owner\n    /// @param spender The account of the token spender\n    /// @return The current allowance granted by `owner` to `spender`\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n    /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n    /// @param amount The amount of tokens allowed to be used by `spender`\n    /// @return Returns true for a successful approval, false for unsuccessful\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n    /// @param sender The account from which the transfer will be initiated\n    /// @param recipient The recipient of the transfer\n    /// @param amount The amount of the transfer\n    /// @return Returns true for a successful transfer, false for unsuccessful\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n    /// @param from The account from which the tokens were sent, i.e. the balance decreased\n    /// @param to The account to which the tokens were sent, i.e. the balance increased\n    /// @param value The amount of tokens that were transferred\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n    /// @param owner The account that approved spending of its tokens\n    /// @param spender The account for which the spending allowance was modified\n    /// @param value The new allowance from the owner to the spender\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"},"vendor/v4-core/src/interfaces/external/IERC6909Claims.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @notice Interface for claims over a contract balance, wrapped as a ERC6909\ninterface IERC6909Claims {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event OperatorSet(address indexed owner, address indexed operator, bool approved);\n\n    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);\n\n    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);\n\n    /*//////////////////////////////////////////////////////////////\n                                 FUNCTIONS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Owner balance of an id.\n    /// @param owner The address of the owner.\n    /// @param id The id of the token.\n    /// @return amount The balance of the token.\n    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);\n\n    /// @notice Spender allowance of an id.\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @param id The id of the token.\n    /// @return amount The allowance of the token.\n    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);\n\n    /// @notice Checks if a spender is approved by an owner as an operator\n    /// @param owner The address of the owner.\n    /// @param spender The address of the spender.\n    /// @return approved The approval status.\n    function isOperator(address owner, address spender) external view returns (bool approved);\n\n    /// @notice Transfers an amount of an id from the caller to a receiver.\n    /// @param receiver The address of the receiver.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always, unless the function reverts\n    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Transfers an amount of an id from a sender to a receiver.\n    /// @param sender The address of the sender.\n    /// @param receiver The address of the receiver.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always, unless the function reverts\n    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Approves an amount of an id to a spender.\n    /// @param spender The address of the spender.\n    /// @param id The id of the token.\n    /// @param amount The amount of the token.\n    /// @return bool True, always\n    function approve(address spender, uint256 id, uint256 amount) external returns (bool);\n\n    /// @notice Sets or removes an operator for the caller.\n    /// @param operator The address of the operator.\n    /// @param approved The approval status.\n    /// @return bool True, always\n    function setOperator(address operator, bool approved) external returns (bool);\n}\n"},"vendor/v4-core/src/libraries/BitMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\n/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)\nlibrary BitMath {\n    /// @notice Returns the index of the most significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @param x the value for which to compute the most significant bit, must be greater than 0\n    /// @return r the index of the most significant bit\n    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        assembly (\"memory-safe\") {\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n            // forgefmt: disable-next-item\n            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),\n                0x0706060506020500060203020504000106050205030304010505030400000000))\n        }\n    }\n\n    /// @notice Returns the index of the least significant bit of the number,\n    ///     where the least significant bit is at index 0 and the most significant bit is at index 255\n    /// @param x the value for which to compute the least significant bit, must be greater than 0\n    /// @return r the index of the least significant bit\n    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n        require(x > 0);\n\n        assembly (\"memory-safe\") {\n            // Isolate the least significant bit.\n            x := and(x, sub(0, x))\n            // For the upper 3 bits of the result, use a De Bruijn-like lookup.\n            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/\n            // forgefmt: disable-next-item\n            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,\n                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),\n                0x8040405543005266443200005020610674053026020000107506200176117077)))\n            // For the lower 5 bits of the result, use a De Bruijn lookup.\n            // forgefmt: disable-next-item\n            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),\n                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))\n        }\n    }\n}\n"},"vendor/v4-core/src/libraries/CustomRevert.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Library for reverting with custom errors efficiently\n/// @notice Contains functions for reverting with custom errors with different argument types efficiently\n/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with\n/// `CustomError.selector.revertWith()`\n/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately\nlibrary CustomRevert {\n    /// @dev ERC-7751 error for wrapping bubbled up reverts\n    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);\n\n    /// @dev Reverts with the selector of a custom error in the scratch space\n    function revertWith(bytes4 selector) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            revert(0, 0x04)\n        }\n    }\n\n    /// @dev Reverts with a custom error with an address argument in the scratch space\n    function revertWith(bytes4 selector, address addr) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with an int24 argument in the scratch space\n    function revertWith(bytes4 selector, int24 value) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, signextend(2, value))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with a uint160 argument in the scratch space\n    function revertWith(bytes4 selector, uint160 value) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0, selector)\n            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(0, 0x24)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two int24 arguments\n    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), signextend(2, value1))\n            mstore(add(fmp, 0x24), signextend(2, value2))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two uint160 arguments\n    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @dev Reverts with a custom error with two address arguments\n    function revertWith(bytes4 selector, address value1, address value2) internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(fmp, selector)\n            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))\n            revert(fmp, 0x44)\n        }\n    }\n\n    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error\n    /// @dev this method can be vulnerable to revert data bombs\n    function bubbleUpAndRevertWith(\n        address revertingContract,\n        bytes4 revertingFunctionSelector,\n        bytes4 additionalContext\n    ) internal pure {\n        bytes4 wrappedErrorSelector = WrappedError.selector;\n        assembly (\"memory-safe\") {\n            // Ensure the size of the revert data is a multiple of 32 bytes\n            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)\n\n            let fmp := mload(0x40)\n\n            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason\n            mstore(fmp, wrappedErrorSelector)\n            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))\n            mstore(\n                add(fmp, 0x24),\n                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n            )\n            // offset revert reason\n            mstore(add(fmp, 0x44), 0x80)\n            // offset additional context\n            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))\n            // size revert reason\n            mstore(add(fmp, 0x84), returndatasize())\n            // revert reason\n            returndatacopy(add(fmp, 0xa4), 0, returndatasize())\n            // size additional context\n            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)\n            // additional context\n            mstore(\n                add(fmp, add(0xc4, encodedDataSize)),\n                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)\n            )\n            revert(fmp, add(0xe4, encodedDataSize))\n        }\n    }\n}\n"},"vendor/v4-core/src/libraries/FixedPoint128.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n    uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n"},"vendor/v4-core/src/libraries/FixedPoint96.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n    uint8 internal constant RESOLUTION = 96;\n    uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n"},"vendor/v4-core/src/libraries/FullMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n    /// @notice Calculates floor(a\u00d7b\u00f7denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = a * b\n            // Compute the product mod 2**256 and mod 2**256 - 1\n            // then use the Chinese Remainder Theorem to reconstruct\n            // the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2**256 + prod0\n            uint256 prod0 = a * b; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly (\"memory-safe\") {\n                let mm := mulmod(a, b, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Make sure the result is less than 2**256.\n            // Also prevents denominator == 0\n            require(denominator > prod1);\n\n            // Handle non-overflow cases, 256 by 256 division\n            if (prod1 == 0) {\n                assembly (\"memory-safe\") {\n                    result := div(prod0, denominator)\n                }\n                return result;\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0]\n            // Compute remainder using mulmod\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                remainder := mulmod(a, b, denominator)\n            }\n            // Subtract 256 bit number from 512 bit number\n            assembly (\"memory-safe\") {\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator\n            // Compute largest power of two divisor of denominator.\n            // Always >= 1.\n            uint256 twos = (0 - denominator) & denominator;\n            // Divide denominator by power of two\n            assembly (\"memory-safe\") {\n                denominator := div(denominator, twos)\n            }\n\n            // Divide [prod1 prod0] by the factors of two\n            assembly (\"memory-safe\") {\n                prod0 := div(prod0, twos)\n            }\n            // Shift in bits from prod1 into prod0. For this we need\n            // to flip `twos` such that it is 2**256 / twos.\n            // If twos is zero, then it becomes one\n            assembly (\"memory-safe\") {\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2**256\n            // Now that denominator is an odd number, it has an inverse\n            // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n            // Compute the inverse by starting with a seed that is correct\n            // correct for four bits. That is, denominator * inv = 1 mod 2**4\n            uint256 inv = (3 * denominator) ^ 2;\n            // Now use Newton-Raphson iteration to improve the precision.\n            // Thanks to Hensel's lifting lemma, this also works in modular\n            // arithmetic, doubling the correct bits in each step.\n            inv *= 2 - denominator * inv; // inverse mod 2**8\n            inv *= 2 - denominator * inv; // inverse mod 2**16\n            inv *= 2 - denominator * inv; // inverse mod 2**32\n            inv *= 2 - denominator * inv; // inverse mod 2**64\n            inv *= 2 - denominator * inv; // inverse mod 2**128\n            inv *= 2 - denominator * inv; // inverse mod 2**256\n\n            // Because the division is now exact we can divide by multiplying\n            // with the modular inverse of denominator. This will give us the\n            // correct result modulo 2**256. Since the preconditions guarantee\n            // that the outcome is less than 2**256, this is the final result.\n            // We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inv;\n            return result;\n        }\n    }\n\n    /// @notice Calculates ceil(a\u00d7b\u00f7denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result\n    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            result = mulDiv(a, b, denominator);\n            if (mulmod(a, b, denominator) != 0) {\n                require(++result > 0);\n            }\n        }\n    }\n}\n"},"vendor/v4-core/src/libraries/LiquidityMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n    /// @param x The liquidity before change\n    /// @param y The delta by which liquidity should be changed\n    /// @return z The liquidity delta\n    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n        assembly (\"memory-safe\") {\n            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))\n            if shr(128, z) {\n                // revert SafeCastOverflow()\n                mstore(0, 0x93dafdf1)\n                revert(0x1c, 0x04)\n            }\n        }\n    }\n}\n"},"vendor/v4-core/src/libraries/Position.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.0;\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {FixedPoint128} from \"./FixedPoint128.sol\";\nimport {LiquidityMath} from \"./LiquidityMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n    using CustomRevert for bytes4;\n\n    /// @notice Cannot update a position with no liquidity\n    error CannotUpdateEmptyPosition();\n\n    // info stored for each user's position\n    struct State {\n        // the amount of liquidity owned by this position\n        uint128 liquidity;\n        // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n        uint256 feeGrowthInside0LastX128;\n        uint256 feeGrowthInside1LastX128;\n    }\n\n    /// @notice Returns the State struct of a position, given an owner and position boundaries\n    /// @param self The mapping containing all user positions\n    /// @param owner The address of the position owner\n    /// @param tickLower The lower tick boundary of the position\n    /// @param tickUpper The upper tick boundary of the position\n    /// @param salt A unique value to differentiate between multiple positions in the same range\n    /// @return position The position info struct of the given owners' position\n    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n        internal\n        view\n        returns (State storage position)\n    {\n        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);\n        position = self[positionKey];\n    }\n\n    /// @notice A helper function to calculate the position key\n    /// @param owner The address of the position owner\n    /// @param tickLower the lower tick boundary of the position\n    /// @param tickUpper the upper tick boundary of the position\n    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.\n    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)\n        internal\n        pure\n        returns (bytes32 positionKey)\n    {\n        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)\n            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)\n            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)\n            mstore(fmp, owner) // [0x0c, 0x20)\n            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes\n\n            // now clean the memory we used\n            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt\n            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt\n            mstore(fmp, 0) // fmp held owner\n        }\n    }\n\n    /// @notice Credits accumulated fees to a user's position\n    /// @param self The individual position to update\n    /// @param liquidityDelta The change in pool liquidity as a result of the position update\n    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries\n    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries\n    /// @return feesOwed0 The amount of currency0 owed to the position owner\n    /// @return feesOwed1 The amount of currency1 owed to the position owner\n    function update(\n        State storage self,\n        int128 liquidityDelta,\n        uint256 feeGrowthInside0X128,\n        uint256 feeGrowthInside1X128\n    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {\n        uint128 liquidity = self.liquidity;\n\n        if (liquidityDelta == 0) {\n            // disallow pokes for 0 liquidity positions\n            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();\n        } else {\n            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);\n        }\n\n        // calculate accumulated fees. overflow in the subtraction of fee growth is expected\n        unchecked {\n            feesOwed0 =\n                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);\n            feesOwed1 =\n                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);\n        }\n\n        // update the position\n        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n    }\n}\n"},"vendor/v4-core/src/libraries/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n    using CustomRevert for bytes4;\n\n    error SafeCastOverflow();\n\n    /// @notice Cast a uint256 to a uint160, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return y The downcasted integer, now type uint160\n    function toUint160(uint256 x) internal pure returns (uint160 y) {\n        y = uint160(x);\n        if (y != x) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a uint128, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return y The downcasted integer, now type uint128\n    function toUint128(uint256 x) internal pure returns (uint128 y) {\n        y = uint128(x);\n        if (x != y) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a int128 to a uint128, revert on overflow or underflow\n    /// @param x The int128 to be casted\n    /// @return y The casted integer, now type uint128\n    function toUint128(int128 x) internal pure returns (uint128 y) {\n        if (x < 0) SafeCastOverflow.selector.revertWith();\n        y = uint128(x);\n    }\n\n    /// @notice Cast a int256 to a int128, revert on overflow or underflow\n    /// @param x The int256 to be downcasted\n    /// @return y The downcasted integer, now type int128\n    function toInt128(int256 x) internal pure returns (int128 y) {\n        y = int128(x);\n        if (y != x) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a int256, revert on overflow\n    /// @param x The uint256 to be casted\n    /// @return y The casted integer, now type int256\n    function toInt256(uint256 x) internal pure returns (int256 y) {\n        y = int256(x);\n        if (y < 0) SafeCastOverflow.selector.revertWith();\n    }\n\n    /// @notice Cast a uint256 to a int128, revert on overflow\n    /// @param x The uint256 to be downcasted\n    /// @return The downcasted integer, now type int128\n    function toInt128(uint256 x) internal pure returns (int128) {\n        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();\n        return int128(int256(x));\n    }\n}\n"},"vendor/v4-core/src/libraries/SqrtPriceMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\nimport {FullMath} from \"./FullMath.sol\";\nimport {UnsafeMath} from \"./UnsafeMath.sol\";\nimport {FixedPoint96} from \"./FixedPoint96.sol\";\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n    using SafeCast for uint256;\n\n    error InvalidPriceOrLiquidity();\n    error InvalidPrice();\n    error NotEnoughLiquidity();\n    error PriceOverflow();\n\n    /// @notice Gets the next sqrt price given a delta of currency0\n    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n    /// price less in order to not send too much output.\n    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n    /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta\n    /// @param liquidity The amount of usable liquidity\n    /// @param amount How much of currency0 to add or remove from virtual reserves\n    /// @param add Whether to add or remove the amount of currency0\n    /// @return The price after adding or removing amount, depending on add\n    function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)\n        internal\n        pure\n        returns (uint160)\n    {\n        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n        if (amount == 0) return sqrtPX96;\n        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n        if (add) {\n            unchecked {\n                uint256 product = amount * sqrtPX96;\n                if (product / amount == sqrtPX96) {\n                    uint256 denominator = numerator1 + product;\n                    if (denominator >= numerator1) {\n                        // always fits in 160 bits\n                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n                    }\n                }\n            }\n            // denominator is checked for overflow\n            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));\n        } else {\n            unchecked {\n                uint256 product = amount * sqrtPX96;\n                // if the product overflows, we know the denominator underflows\n                // in addition, we must check that the denominator does not underflow\n                // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();\n                assembly (\"memory-safe\") {\n                    if iszero(\n                        and(\n                            eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),\n                            gt(numerator1, product)\n                        )\n                    ) {\n                        mstore(0, 0xf5c787f1) // selector for PriceOverflow()\n                        revert(0x1c, 0x04)\n                    }\n                }\n                uint256 denominator = numerator1 - product;\n                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n            }\n        }\n    }\n\n    /// @notice Gets the next sqrt price given a delta of currency1\n    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n    /// price less in order to not send too much output.\n    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n    /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta\n    /// @param liquidity The amount of usable liquidity\n    /// @param amount How much of currency1 to add, or remove, from virtual reserves\n    /// @param add Whether to add, or remove, the amount of currency1\n    /// @return The price after adding or removing `amount`\n    function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)\n        internal\n        pure\n        returns (uint160)\n    {\n        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n        // in both cases, avoid a mulDiv for most inputs\n        if (add) {\n            uint256 quotient = (\n                amount <= type(uint160).max\n                    ? (amount << FixedPoint96.RESOLUTION) / liquidity\n                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n            );\n\n            return (uint256(sqrtPX96) + quotient).toUint160();\n        } else {\n            uint256 quotient = (\n                amount <= type(uint160).max\n                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n            );\n\n            // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();\n            assembly (\"memory-safe\") {\n                if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {\n                    mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()\n                    revert(0x1c, 0x04)\n                }\n            }\n            // always fits 160 bits\n            unchecked {\n                return uint160(sqrtPX96 - quotient);\n            }\n        }\n    }\n\n    /// @notice Gets the next sqrt price given an input amount of currency0 or currency1\n    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n    /// @param liquidity The amount of usable liquidity\n    /// @param amountIn How much of currency0, or currency1, is being swapped in\n    /// @param zeroForOne Whether the amount in is currency0 or currency1\n    /// @return uint160 The price after adding the input amount to currency0 or currency1\n    function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)\n        internal\n        pure\n        returns (uint160)\n    {\n        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();\n        assembly (\"memory-safe\") {\n            if or(\n                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),\n                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))\n            ) {\n                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()\n                revert(0x1c, 0x04)\n            }\n        }\n\n        // round to make sure that we don't pass the target price\n        return zeroForOne\n            ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n            : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n    }\n\n    /// @notice Gets the next sqrt price given an output amount of currency0 or currency1\n    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n    /// @param sqrtPX96 The starting price before accounting for the output amount\n    /// @param liquidity The amount of usable liquidity\n    /// @param amountOut How much of currency0, or currency1, is being swapped out\n    /// @param zeroForOne Whether the amount out is currency1 or currency0\n    /// @return uint160 The price after removing the output amount of currency0 or currency1\n    function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)\n        internal\n        pure\n        returns (uint160)\n    {\n        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();\n        assembly (\"memory-safe\") {\n            if or(\n                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),\n                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))\n            ) {\n                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()\n                revert(0x1c, 0x04)\n            }\n        }\n\n        // round to make sure that we pass the target price\n        return zeroForOne\n            ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n            : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n    }\n\n    /// @notice Gets the amount0 delta between two prices\n    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The amount of usable liquidity\n    /// @param roundUp Whether to round the amount up or down\n    /// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices\n    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)\n        internal\n        pure\n        returns (uint256)\n    {\n        unchecked {\n            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);\n\n            // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();\n            assembly (\"memory-safe\") {\n                if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {\n                    mstore(0, 0x00bfc921) // selector for InvalidPrice()\n                    revert(0x1c, 0x04)\n                }\n            }\n\n            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n            uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;\n\n            return roundUp\n                ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)\n                : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;\n        }\n    }\n\n    /// @notice Equivalent to: `a >= b ? a - b : b - a`\n    function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {\n        assembly (\"memory-safe\") {\n            let diff :=\n                sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))\n            // mask = 0 if a >= b else -1 (all 1s)\n            let mask := sar(255, diff)\n            // if a >= b, res = a - b = 0 ^ (a - b)\n            // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)\n            // either way, res = mask ^ (a - b + mask)\n            res := xor(mask, add(mask, diff))\n        }\n    }\n\n    /// @notice Gets the amount1 delta between two prices\n    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The amount of usable liquidity\n    /// @param roundUp Whether to round the amount up, or down\n    /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices\n    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)\n        internal\n        pure\n        returns (uint256 amount1)\n    {\n        uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);\n        uint256 denominator = FixedPoint96.Q96;\n        uint256 _liquidity = uint256(liquidity);\n\n        /**\n         * Equivalent to:\n         *   amount1 = roundUp\n         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)\n         *       : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);\n         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.\n         */\n        amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);\n        assembly (\"memory-safe\") {\n            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))\n        }\n    }\n\n    /// @notice Helper that gets signed currency0 delta\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The change in liquidity for which to compute the amount0 delta\n    /// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices\n    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)\n        internal\n        pure\n        returns (int256)\n    {\n        unchecked {\n            return liquidity < 0\n                ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()\n                : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();\n        }\n    }\n\n    /// @notice Helper that gets signed currency1 delta\n    /// @param sqrtPriceAX96 A sqrt price\n    /// @param sqrtPriceBX96 Another sqrt price\n    /// @param liquidity The change in liquidity for which to compute the amount1 delta\n    /// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices\n    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)\n        internal\n        pure\n        returns (int256)\n    {\n        unchecked {\n            return liquidity < 0\n                ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()\n                : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();\n        }\n    }\n}\n"},"vendor/v4-core/src/libraries/StateLibrary.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolId} from \"../types/PoolId.sol\";\nimport {IPoolManager} from \"../interfaces/IPoolManager.sol\";\nimport {Position} from \"./Position.sol\";\n\n/// @notice A helper library to provide state getters that use extsload\nlibrary StateLibrary {\n    /// @notice index of pools mapping in the PoolManager\n    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));\n\n    /// @notice index of feeGrowthGlobal0X128 in Pool.State\n    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;\n\n    // feeGrowthGlobal1X128 offset in Pool.State = 2\n\n    /// @notice index of liquidity in Pool.State\n    uint256 public constant LIQUIDITY_OFFSET = 3;\n\n    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;\n    uint256 public constant TICKS_OFFSET = 4;\n\n    /// @notice index of tickBitmap mapping in Pool.State\n    uint256 public constant TICK_BITMAP_OFFSET = 5;\n\n    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;\n    uint256 public constant POSITIONS_OFFSET = 6;\n\n    /**\n     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee\n     * @dev Corresponds to pools[poolId].slot0\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.\n     * @return tick The current tick of the pool.\n     * @return protocolFee The protocol fee of the pool.\n     * @return lpFee The swap fee of the pool.\n     */\n    function getSlot0(IPoolManager manager, PoolId poolId)\n        internal\n        view\n        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)\n    {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        bytes32 data = manager.extsload(stateSlot);\n\n        //   24 bits  |24bits|24bits      |24 bits|160 bits\n        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7\n        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96\n        assembly (\"memory-safe\") {\n            // bottom 160 bits of data\n            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n            // next 24 bits of data\n            tick := signextend(2, shr(160, data))\n            // next 24 bits of data\n            protocolFee := and(shr(184, data), 0xFFFFFF)\n            // last 24 bits of data\n            lpFee := and(shr(208, data), 0xFFFFFF)\n        }\n    }\n\n    /**\n     * @notice Retrieves the tick information of a pool at a specific tick.\n     * @dev Corresponds to pools[poolId].ticks[tick]\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve information for.\n     * @return liquidityGross The total position liquidity that references this tick\n     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     */\n    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)\n        internal\n        view\n        returns (\n            uint128 liquidityGross,\n            int128 liquidityNet,\n            uint256 feeGrowthOutside0X128,\n            uint256 feeGrowthOutside1X128\n        )\n    {\n        bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n        // read all 3 words of the TickInfo struct\n        bytes32[] memory data = manager.extsload(slot, 3);\n        assembly (\"memory-safe\") {\n            let firstWord := mload(add(data, 32))\n            liquidityNet := sar(128, firstWord)\n            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n            feeGrowthOutside0X128 := mload(add(data, 64))\n            feeGrowthOutside1X128 := mload(add(data, 96))\n        }\n    }\n\n    /**\n     * @notice Retrieves the liquidity information of a pool at a specific tick.\n     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve liquidity for.\n     * @return liquidityGross The total position liquidity that references this tick\n     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)\n     */\n    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)\n        internal\n        view\n        returns (uint128 liquidityGross, int128 liquidityNet)\n    {\n        bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n        bytes32 value = manager.extsload(slot);\n        assembly (\"memory-safe\") {\n            liquidityNet := sar(128, value)\n            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n        }\n    }\n\n    /**\n     * @notice Retrieves the fee growth outside a tick range of a pool\n     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve fee growth for.\n     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n     */\n    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)\n        internal\n        view\n        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)\n    {\n        bytes32 slot = _getTickInfoSlot(poolId, tick);\n\n        // offset by 1 word, since the first word is liquidityGross + liquidityNet\n        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);\n        assembly (\"memory-safe\") {\n            feeGrowthOutside0X128 := mload(add(data, 32))\n            feeGrowthOutside1X128 := mload(add(data, 64))\n        }\n    }\n\n    /**\n     * @notice Retrieves the global fee growth of a pool.\n     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @return feeGrowthGlobal0 The global fee growth for token0.\n     * @return feeGrowthGlobal1 The global fee growth for token1.\n     * @dev Note that feeGrowthGlobal can be artificially inflated\n     * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal\n     * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme\n     */\n    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)\n        internal\n        view\n        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)\n    {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State, `uint256 feeGrowthGlobal0X128`\n        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);\n\n        // read the 2 words of feeGrowthGlobal\n        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);\n        assembly (\"memory-safe\") {\n            feeGrowthGlobal0 := mload(add(data, 32))\n            feeGrowthGlobal1 := mload(add(data, 64))\n        }\n    }\n\n    /**\n     * @notice Retrieves total the liquidity of a pool.\n     * @dev Corresponds to pools[poolId].liquidity\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @return liquidity The liquidity of the pool.\n     */\n    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `uint128 liquidity`\n        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);\n\n        liquidity = uint128(uint256(manager.extsload(slot)));\n    }\n\n    /**\n     * @notice Retrieves the tick bitmap of a pool at a specific tick.\n     * @dev Corresponds to pools[poolId].tickBitmap[tick]\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tick The tick to retrieve the bitmap for.\n     * @return tickBitmap The bitmap of the tick.\n     */\n    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)\n        internal\n        view\n        returns (uint256 tickBitmap)\n    {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `mapping(int16 => uint256) tickBitmap;`\n        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);\n\n        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]\n        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));\n\n        tickBitmap = uint256(manager.extsload(slot));\n    }\n\n    /**\n     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.\n     * @dev Corresponds to pools[poolId].positions[positionId]\n     * @param poolId The ID of the pool.\n     * @param owner The owner of the liquidity position.\n     * @param tickLower The lower tick of the liquidity range.\n     * @param tickUpper The upper tick of the liquidity range.\n     * @param salt The bytes32 randomness to further distinguish position state.\n     * @return liquidity The liquidity of the position.\n     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n     */\n    function getPositionInfo(\n        IPoolManager manager,\n        PoolId poolId,\n        address owner,\n        int24 tickLower,\n        int24 tickUpper,\n        bytes32 salt\n    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {\n        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))\n        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);\n\n        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);\n    }\n\n    /**\n     * @notice Retrieves the position information of a pool at a specific position ID.\n     * @dev Corresponds to pools[poolId].positions[positionId]\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param positionId The ID of the position.\n     * @return liquidity The liquidity of the position.\n     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.\n     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.\n     */\n    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)\n        internal\n        view\n        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)\n    {\n        bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n\n        // read all 3 words of the Position.State struct\n        bytes32[] memory data = manager.extsload(slot, 3);\n\n        assembly (\"memory-safe\") {\n            liquidity := mload(add(data, 32))\n            feeGrowthInside0LastX128 := mload(add(data, 64))\n            feeGrowthInside1LastX128 := mload(add(data, 96))\n        }\n    }\n\n    /**\n     * @notice Retrieves the liquidity of a position.\n     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param positionId The ID of the position.\n     * @return liquidity The liquidity of the position.\n     */\n    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)\n        internal\n        view\n        returns (uint128 liquidity)\n    {\n        bytes32 slot = _getPositionInfoSlot(poolId, positionId);\n        liquidity = uint128(uint256(manager.extsload(slot)));\n    }\n\n    /**\n     * @notice Calculate the fee growth inside a tick range of a pool\n     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside\n     * @param manager The pool manager contract.\n     * @param poolId The ID of the pool.\n     * @param tickLower The lower tick of the range.\n     * @param tickUpper The upper tick of the range.\n     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.\n     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.\n     */\n    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)\n        internal\n        view\n        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)\n    {\n        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);\n\n        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =\n            getTickFeeGrowthOutside(manager, poolId, tickLower);\n        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =\n            getTickFeeGrowthOutside(manager, poolId, tickUpper);\n        (, int24 tickCurrent,,) = getSlot0(manager, poolId);\n        unchecked {\n            if (tickCurrent < tickLower) {\n                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n            } else if (tickCurrent >= tickUpper) {\n                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;\n            } else {\n                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;\n                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;\n            }\n        }\n    }\n\n    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));\n    }\n\n    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `mapping(int24 => TickInfo) ticks`\n        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);\n\n        // slot key of the tick key: `pools[poolId].ticks[tick]\n        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));\n    }\n\n    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {\n        // slot key of Pool.State value: `pools[poolId]`\n        bytes32 stateSlot = _getPoolStateSlot(poolId);\n\n        // Pool.State: `mapping(bytes32 => Position.State) positions;`\n        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);\n\n        // slot of the mapping key: `pools[poolId].positions[positionId]\n        return keccak256(abi.encodePacked(positionId, positionMapping));\n    }\n}\n"},"vendor/v4-core/src/libraries/TickMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {BitMath} from \"./BitMath.sol\";\nimport {CustomRevert} from \"./CustomRevert.sol\";\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n    using CustomRevert for bytes4;\n\n    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK\n    error InvalidTick(int24 tick);\n    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK\n    error InvalidSqrtPrice(uint160 sqrtPriceX96);\n\n    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128\n    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used\n    int24 internal constant MIN_TICK = -887272;\n    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128\n    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used\n    int24 internal constant MAX_TICK = 887272;\n\n    /// @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]\n    int24 internal constant MIN_TICK_SPACING = 1;\n    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]\n    int24 internal constant MAX_TICK_SPACING = type(int16).max;\n\n    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)\n    uint160 internal constant MIN_SQRT_PRICE = 4295128739;\n    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)\n    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;\n    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`\n    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =\n        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;\n\n    /// @notice Given a tickSpacing, compute the maximum usable tick\n    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {\n        unchecked {\n            return (MAX_TICK / tickSpacing) * tickSpacing;\n        }\n    }\n\n    /// @notice Given a tickSpacing, compute the minimum usable tick\n    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {\n        unchecked {\n            return (MIN_TICK / tickSpacing) * tickSpacing;\n        }\n    }\n\n    /// @notice Calculates sqrt(1.0001^tick) * 2^96\n    /// @dev Throws if |tick| > max tick\n    /// @param tick The input tick for the above formula\n    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)\n    /// at the given tick\n    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n        unchecked {\n            uint256 absTick;\n            assembly (\"memory-safe\") {\n                tick := signextend(2, tick)\n                // mask = 0 if tick >= 0 else -1 (all 1s)\n                let mask := sar(255, tick)\n                // if tick >= 0, |tick| = tick = 0 ^ tick\n                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)\n                // either way, |tick| = mask ^ (tick + mask)\n                absTick := xor(mask, add(mask, tick))\n            }\n\n            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);\n\n            // 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))\n            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer\n\n            // Equivalent to:\n            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128\n            uint256 price;\n            assembly (\"memory-safe\") {\n                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))\n            }\n            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;\n            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;\n            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;\n\n            assembly (\"memory-safe\") {\n                // if (tick > 0) price = type(uint256).max / price;\n                if sgt(tick, 0) { price := div(not(0), price) }\n\n                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent\n                // `sub(shl(32, 1), 1)` is `type(uint32).max`\n                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits\n                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))\n            }\n        }\n    }\n\n    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96\n    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may\n    /// ever return.\n    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96\n    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96\n    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n        unchecked {\n            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();\n            // second inequality must be >= because the price can never reach the price at the max tick\n            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true\n            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1\n            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {\n                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);\n            }\n\n            uint256 price = uint256(sqrtPriceX96) << 32;\n\n            uint256 r = price;\n            uint256 msb = BitMath.mostSignificantBit(r);\n\n            if (msb >= 128) r = price >> (msb - 127);\n            else r = price << (127 - msb);\n\n            int256 log_2 = (int256(msb) - 128) << 64;\n\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(63, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(62, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(61, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(60, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(59, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(58, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(57, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(56, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(55, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(54, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(53, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(52, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(51, f))\n                r := shr(f, r)\n            }\n            assembly (\"memory-safe\") {\n                r := shr(127, mul(r, r))\n                let f := shr(128, r)\n                log_2 := or(log_2, shl(50, f))\n            }\n\n            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number\n\n            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)\n            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n\n            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when\n            // 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\n            // is changed, this may need to be changed too\n            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n        }\n    }\n}\n"},"vendor/v4-core/src/libraries/UnsafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n    /// @notice Returns ceil(x / y)\n    /// @dev division by 0 will return 0, and should be checked externally\n    /// @param x The dividend\n    /// @param y The divisor\n    /// @return z The quotient, ceil(x / y)\n    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        assembly (\"memory-safe\") {\n            z := add(div(x, y), gt(mod(x, y), 0))\n        }\n    }\n\n    /// @notice Calculates floor(a\u00d7b\u00f7denominator)\n    /// @dev division by 0 will return 0, and should be checked externally\n    /// @param a The multiplicand\n    /// @param b The multiplier\n    /// @param denominator The divisor\n    /// @return result The 256-bit result, floor(a\u00d7b\u00f7denominator)\n    function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {\n        assembly (\"memory-safe\") {\n            result := div(mul(a, b), denominator)\n        }\n    }\n}\n"},"vendor/v4-core/src/types/BalanceDelta.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {SafeCast} from \"../libraries/SafeCast.sol\";\n\n/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0\n/// and the lower 128 bits represent the amount1.\ntype BalanceDelta is int256;\n\nusing {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;\nusing BalanceDeltaLibrary for BalanceDelta global;\nusing SafeCast for int256;\n\nfunction toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {\n    assembly (\"memory-safe\") {\n        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))\n    }\n}\n\nfunction add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n    int256 res0;\n    int256 res1;\n    assembly (\"memory-safe\") {\n        let a0 := sar(128, a)\n        let a1 := signextend(15, a)\n        let b0 := sar(128, b)\n        let b1 := signextend(15, b)\n        res0 := add(a0, b0)\n        res1 := add(a1, b1)\n    }\n    return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {\n    int256 res0;\n    int256 res1;\n    assembly (\"memory-safe\") {\n        let a0 := sar(128, a)\n        let a1 := signextend(15, a)\n        let b0 := sar(128, b)\n        let b1 := signextend(15, b)\n        res0 := sub(a0, b0)\n        res1 := sub(a1, b1)\n    }\n    return toBalanceDelta(res0.toInt128(), res1.toInt128());\n}\n\nfunction eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);\n}\n\nfunction neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {\n    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);\n}\n\n/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type\nlibrary BalanceDeltaLibrary {\n    /// @notice A BalanceDelta of 0\n    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);\n\n    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {\n        assembly (\"memory-safe\") {\n            _amount0 := sar(128, balanceDelta)\n        }\n    }\n\n    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {\n        assembly (\"memory-safe\") {\n            _amount1 := signextend(15, balanceDelta)\n        }\n    }\n}\n"},"vendor/v4-core/src/types/BeforeSwapDelta.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Return type of the beforeSwap hook.\n// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)\ntype BeforeSwapDelta is int256;\n\n// Creates a BeforeSwapDelta from specified and unspecified\nfunction toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)\n    pure\n    returns (BeforeSwapDelta beforeSwapDelta)\n{\n    assembly (\"memory-safe\") {\n        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))\n    }\n}\n\n/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type\nlibrary BeforeSwapDeltaLibrary {\n    /// @notice A BeforeSwapDelta of 0\n    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);\n\n    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta\n    /// returned by beforeSwap\n    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {\n        assembly (\"memory-safe\") {\n            deltaSpecified := sar(128, delta)\n        }\n    }\n\n    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta\n    /// returned by beforeSwap and afterSwap\n    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {\n        assembly (\"memory-safe\") {\n            deltaUnspecified := signextend(15, delta)\n        }\n    }\n}\n"},"vendor/v4-core/src/types/Currency.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20Minimal} from \"../interfaces/external/IERC20Minimal.sol\";\nimport {CustomRevert} from \"../libraries/CustomRevert.sol\";\n\ntype Currency is address;\n\nusing {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;\nusing CurrencyLibrary for Currency global;\n\nfunction equals(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) == Currency.unwrap(other);\n}\n\nfunction greaterThan(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) > Currency.unwrap(other);\n}\n\nfunction lessThan(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) < Currency.unwrap(other);\n}\n\nfunction greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {\n    return Currency.unwrap(currency) >= Currency.unwrap(other);\n}\n\n/// @title CurrencyLibrary\n/// @dev This library allows for transferring and holding native tokens and ERC20 tokens\nlibrary CurrencyLibrary {\n    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails\n    error NativeTransferFailed();\n\n    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails\n    error ERC20TransferFailed();\n\n    /// @notice A constant to represent the native currency\n    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));\n\n    function transfer(Currency currency, address to, uint256 amount) internal {\n        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol\n        // modified custom error selectors\n\n        bool success;\n        if (currency.isAddressZero()) {\n            assembly (\"memory-safe\") {\n                // Transfer the ETH and revert if it fails.\n                success := call(gas(), to, amount, 0, 0, 0, 0)\n            }\n            // revert with NativeTransferFailed, containing the bubbled up error as an argument\n            if (!success) {\n                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);\n            }\n        } else {\n            assembly (\"memory-safe\") {\n                // Get a pointer to some free memory.\n                let fmp := mload(0x40)\n\n                // Write the abi-encoded calldata into memory, beginning with the function selector.\n                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the \"to\" argument.\n                mstore(add(fmp, 36), amount) // Append the \"amount\" argument. Masking not required as it's a full 32 byte type.\n\n                success :=\n                    and(\n                        // Set success to whether the call reverted, if not we check it either\n                        // returned exactly 1 (can't just be non-zero data), or had no return data.\n                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                        // Counterintuitively, this call must be positioned second to the or() call in the\n                        // surrounding and() call or else returndatasize() will be zero during the computation.\n                        call(gas(), currency, 0, fmp, 68, 0, 32)\n                    )\n\n                // Now clean the memory we used\n                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here\n                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here\n                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here\n            }\n            // revert with ERC20TransferFailed, containing the bubbled up error as an argument\n            if (!success) {\n                CustomRevert.bubbleUpAndRevertWith(\n                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector\n                );\n            }\n        }\n    }\n\n    function balanceOfSelf(Currency currency) internal view returns (uint256) {\n        if (currency.isAddressZero()) {\n            return address(this).balance;\n        } else {\n            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));\n        }\n    }\n\n    function balanceOf(Currency currency, address owner) internal view returns (uint256) {\n        if (currency.isAddressZero()) {\n            return owner.balance;\n        } else {\n            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);\n        }\n    }\n\n    function isAddressZero(Currency currency) internal pure returns (bool) {\n        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);\n    }\n\n    function toId(Currency currency) internal pure returns (uint256) {\n        return uint160(Currency.unwrap(currency));\n    }\n\n    // If the upper 12 bytes are non-zero, they will be zero-ed out\n    // Therefore, fromId() and toId() are not inverses of each other\n    function fromId(uint256 id) internal pure returns (Currency) {\n        return Currency.wrap(address(uint160(id)));\n    }\n}\n"},"vendor/v4-core/src/types/PoolId.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {PoolKey} from \"./PoolKey.sol\";\n\ntype PoolId is bytes32;\n\n/// @notice Library for computing the ID of a pool\nlibrary PoolIdLibrary {\n    /// @notice Returns value equal to keccak256(abi.encode(poolKey))\n    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {\n        assembly (\"memory-safe\") {\n            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)\n            poolId := keccak256(poolKey, 0xa0)\n        }\n    }\n}\n"},"vendor/v4-core/src/types/PoolKey.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Currency} from \"./Currency.sol\";\nimport {IHooks} from \"../interfaces/IHooks.sol\";\nimport {PoolIdLibrary} from \"./PoolId.sol\";\n\nusing PoolIdLibrary for PoolKey global;\n\n/// @notice Returns the key for identifying a pool\nstruct PoolKey {\n    /// @notice The lower currency of the pool, sorted numerically\n    Currency currency0;\n    /// @notice The higher currency of the pool, sorted numerically\n    Currency currency1;\n    /// @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\n    uint24 fee;\n    /// @notice Ticks that involve positions must be a multiple of tick spacing\n    int24 tickSpacing;\n    /// @notice The hooks of the pool\n    IHooks hooks;\n}\n"}},"settings":{"remappings":["@openzeppelin/contracts/=vendor/openzeppelin/contracts/","@uniswap/v4-core/=vendor/v4-core/","claus-proxy/=vendor/claus-proxy/src/","forge-std/=vendor/forge-std/src/","openzeppelin-contracts/=vendor/claus-proxy/lib/openzeppelin-contracts/contracts/","openzeppelin/=vendor/openzeppelin/contracts/","solmate/=vendor/solmate/","v4-core/=vendor/v4-core/src/","vendor/claus-proxy/:@openzeppelin/contracts/=vendor/claus-proxy/lib/openzeppelin-contracts/contracts/","vendor/claus-proxy/:@uniswap/v4-core/=vendor/claus-proxy/lib/v4-periphery/lib/v4-core/"],"optimizer":{"enabled":true,"runs":1},"metadata":{"bytecodeHash":"none"},"evmVersion":"cancun","libraries":{},"outputSelection":{"contracts/PebbleQuoteLaunchCoordinator.sol":{"PebbleQuoteLaunchCoordinator":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebbleToken.sol":{"PebbleToken":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebbleCreatorVault.sol":{"PebbleCreatorVault":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebblePermanentLiquidity.sol":{"PebblePermanentLiquidity":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebbleSwapRouter.sol":{"PebbleSwapRouter":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebbleQuotePolicy.sol":{"PebbleQuotePolicy":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebbleQuoteController.sol":{"PebbleQuoteSteadyStrategy":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"],"PebbleQuoteController":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"],"PebbleQuotePacedStrategy":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebbleQuoteHook.sol":{"PebbleQuoteHook":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]},"contracts/PebbleNftRewardChannel.sol":{"PebbleNftRewardChannel":["abi","evm.bytecode.object","evm.deployedBytecode.object","evm.deployedBytecode.immutableReferences","metadata"]}},"viaIR":true}}
