More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 25 from a total of 179 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Approve | 23613392 | 44 mins ago | IN | 0 ETH | 0.00003082 | ||||
Sell Target NFT | 23613170 | 1 hr ago | IN | 0.984 ETH | 0.0001429 | ||||
Approve | 23613167 | 1 hr ago | IN | 0 ETH | 0.0000418 | ||||
Process Token Tw... | 23613156 | 1 hr ago | IN | 0 ETH | 0.00003917 | ||||
Sell Target NFT | 23613143 | 1 hr ago | IN | 1.008 ETH | 0.00014347 | ||||
Approve | 23613037 | 1 hr ago | IN | 0 ETH | 0.00000745 | ||||
Sell Target NFT | 23612456 | 3 hrs ago | IN | 1.044 ETH | 0.00014391 | ||||
Buy Target NFT | 23612366 | 4 hrs ago | IN | 0 ETH | 0.00003163 | ||||
Sell Target NFT | 23612354 | 4 hrs ago | IN | 0.984 ETH | 0.00014517 | ||||
Sell Target NFT | 23612353 | 4 hrs ago | IN | 0.996 ETH | 0.00014484 | ||||
Sell Target NFT | 23612236 | 4 hrs ago | IN | 0.996 ETH | 0.00014081 | ||||
Sell Target NFT | 23612197 | 4 hrs ago | IN | 0.996 ETH | 0.0001396 | ||||
Transfer | 23612176 | 4 hrs ago | IN | 0 ETH | 0.00000616 | ||||
Sell Target NFT | 23612128 | 4 hrs ago | IN | 0.972 ETH | 0.00014612 | ||||
Transfer | 23611986 | 5 hrs ago | IN | 0 ETH | 0.00000837 | ||||
Transfer | 23611981 | 5 hrs ago | IN | 0 ETH | 0.00000839 | ||||
Transfer | 23611975 | 5 hrs ago | IN | 0 ETH | 0.00000847 | ||||
Sell Target NFT | 23610994 | 8 hrs ago | IN | 1.008 ETH | 0.00013773 | ||||
Sell Target NFT | 23610921 | 9 hrs ago | IN | 0.972 ETH | 0.00001868 | ||||
Sell Target NFT | 23610526 | 10 hrs ago | IN | 0.984 ETH | 0.0000937 | ||||
Sell Target NFT | 23609195 | 14 hrs ago | IN | 0.96 ETH | 0.00006078 | ||||
Sell Target NFT | 23608932 | 15 hrs ago | IN | 0.972 ETH | 0.0000597 | ||||
Sell Target NFT | 23608864 | 15 hrs ago | IN | 0.972 ETH | 0.00005996 | ||||
Sell Target NFT | 23608738 | 16 hrs ago | IN | 1.02 ETH | 0.00000894 | ||||
Sell Target NFT | 23608469 | 17 hrs ago | IN | 0.972 ETH | 0.00013662 |
Latest 25 internal transactions
Advanced mode:
Parent Transaction Hash | Method | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|---|
Transfer* | 23613585 | 6 mins ago | 0.88 ETH | ||||
Add Fees | 23613547 | 13 mins ago | 0.00204353 ETH | ||||
Transfer* | 23613498 | 23 mins ago | 0.88 ETH | ||||
Add Fees | 23613470 | 29 mins ago | 0.0320879 ETH | ||||
Add Fees | 23613468 | 29 mins ago | 0.04013781 ETH | ||||
Add Fees | 23613464 | 30 mins ago | 0.0164232 ETH | ||||
Add Fees | 23613420 | 39 mins ago | 0.02003456 ETH | ||||
Add Fees | 23613419 | 39 mins ago | 0.00062566 ETH | ||||
Add Fees | 23613413 | 40 mins ago | 0.0603126 ETH | ||||
Transfer* | 23613411 | 41 mins ago | 0.88 ETH | ||||
Add Fees | 23613405 | 42 mins ago | 0.00329454 ETH | ||||
Add Fees | 23613403 | 42 mins ago | 0.04013948 ETH | ||||
Add Fees | 23613403 | 42 mins ago | 0.08056164 ETH | ||||
Add Fees | 23613401 | 43 mins ago | 0.00144018 ETH | ||||
Add Fees | 23613394 | 44 mins ago | 0.03691929 ETH | ||||
Add Fees | 23613389 | 45 mins ago | 0.01602258 ETH | ||||
Add Fees | 23613387 | 45 mins ago | 0.01602261 ETH | ||||
Add Fees | 23613383 | 46 mins ago | 0.04014183 ETH | ||||
Add Fees | 23613381 | 47 mins ago | 0.00800567 ETH | ||||
Add Fees | 23613377 | 47 mins ago | 0.00038401 ETH | ||||
Add Fees | 23613372 | 48 mins ago | 0.00048002 ETH | ||||
Add Fees | 23613367 | 49 mins ago | 0.01682508 ETH | ||||
Add Fees | 23613357 | 51 mins ago | 0.00200035 ETH | ||||
Add Fees | 23613347 | 53 mins ago | 0.01201281 ETH | ||||
Add Fees | 23613345 | 54 mins ago | 0.0805732 ETH |
Cross-Chain Transactions
Loading...
Loading
Minimal Proxy Contract for 0x3e17172096fbe0a0bbae6931c2e4e6bd9c09bca1
Contract Name:
NFTStrategy
Compiler Version
v0.8.30+commit.73712a01
Optimization Enabled:
Yes with 200 runs
Other Settings:
prague EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {ERC20} from "solady/tokens/ERC20.sol"; import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol"; import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {Currency} from "@uniswap/v4-core/src/types/Currency.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {IUniswapV4Router04} from "v4-router/interfaces/IUniswapV4Router04.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import "./Interfaces.sol"; import {Initializable} from "solady/utils/Initializable.sol"; import {UUPSUpgradeable} from "solady/utils/UUPSUpgradeable.sol"; import {Ownable} from "solady/auth/Ownable.sol"; import {LibClone} from "solady/utils/LibClone.sol"; /// @title NFTStrategy - An ERC20 token that constantly churns NFTs from a collection /// @author TokenWorks (https://token.works/) /// @notice This contract implements an ERC20 token backed by NFTs from a specific collection. /// Users can trade the token on Uniswap V4, and the contract uses trading fees to buy and sell NFTs. /// @dev Uses ERC1967 proxy pattern with immutable args for gas-efficient upgrades contract NFTStrategy is Initializable, UUPSUpgradeable, Ownable, ReentrancyGuard, ERC20 { /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™ */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™ ™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ ™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™™™™ ™™™™™™™™™™™™™™ */ /* ™™™™™™™™™™™ ™™™™™™™™™™™™ ™™™™™™™™™™™™ */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* CONSTANTS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice The name of the ERC20 token string tokenName; /// @notice The symbol of the ERC20 token string tokenSymbol; /// @notice Address of the Uniswap V4 hook contract address public hookAddress; /// @notice The NFT collection this strategy is tied to IERC721 public collection; /// @notice Maximum token supply (1 billion tokens) uint256 public constant MAX_SUPPLY = 1_000_000_000 * 1e18; /// @notice Dead address for burning tokens address public constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD; /// @notice Contract version for upgrade tracking uint256 public constant VERSION = 2; /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* STATE VARIABLES */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Multiplier for NFT resale price (in basis points, e.g., 1200 = 1.2x) uint256 public priceMultiplier; /// @notice Mapping of NFT token IDs to their sale prices mapping(uint256 => uint256) public nftForSale; /// @notice Current accumulated fees available for NFT purchases uint256 public currentFees; /// @notice ETH accumulated from NFT sales, waiting to be used for token buyback uint256 public ethToTwap; /// @notice Amount of ETH to use per TWAP buyback operation uint256 public twapIncrement; /// @notice Number of blocks to wait between TWAP operations uint256 public twapDelayInBlocks; /// @notice Block number of the last TWAP operation uint256 public lastTwapBlock; /// @notice Block number when the last NFT was bought uint256 public lastBuyBlock; /// @notice ETH amount increment for maximum buy price calculation uint256 public buyIncrement; /// @notice Mapping of addresses that can distribute tokens freely (team wallets, airdrop contracts) mapping(address => bool) public isDistributor; /// @notice Storage gap for future upgrades (prevents storage collisions) uint256[49] private __gap; /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* CUSTOM EVENTS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Emitted when the protocol buys an NFT event NFTBoughtByProtocol(uint256 indexed tokenId, uint256 purchasePrice, uint256 listPrice); /// @notice Emitted when the protocol sells an NFT event NFTSoldByProtocol(uint256 indexed tokenId, uint256 price, address buyer); /// @notice Emitted when transfer allowance is increased by the hook event AllowanceIncreased(uint256 amount); /// @notice Emitted when transfer allowance is spent event AllowanceSpent(address indexed from, address indexed to, uint256 amount); /// @notice Emitted when the contract implementation is upgraded event ContractUpgraded(address indexed oldImplementation, address indexed newImplementation, uint256 version); /// @notice Emitted when a distributor's whitelist status is updated event DistributorUpdated(address indexed distributor, bool status); /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* CUSTOM ERRORS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice NFT is not currently for sale error NFTNotForSale(); /// @notice Sent ETH amount is less than the NFT sale price error NFTPriceTooLow(); /// @notice Contract doesn't have enough ETH balance error InsufficientContractBalance(); /// @notice Price multiplier is outside valid range error InvalidMultiplier(); /// @notice No ETH available for TWAP operations error NoETHToTwap(); /// @notice Not enough blocks have passed since last TWAP error TwapDelayNotMet(); /// @notice Not enough ETH in fees to make purchase error NotEnoughEth(); /// @notice Purchase price exceeds time-based maximum error PriceTooHigh(); /// @notice Caller is not the factory contract error NotFactory(); /// @notice Contract already owns this NFT error AlreadyNFTOwner(); /// @notice External call didn't result in NFT acquisition error NeedToBuyNFT(); /// @notice Contract doesn't own the specified NFT error NotNFTOwner(); /// @notice Caller is not the authorized hook contract error OnlyHook(); /// @notice Invalid NFT collection address error InvalidCollection(); /// @notice External call to marketplace failed error ExternalCallFailed(bytes reason); /// @notice Invalid target address for external call error InvalidTarget(); /// @notice Token transfer not authorized error InvalidTransfer(); /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* CONSTRUCTOR */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Constructor disables initializers to prevent implementation contract initialization /// @dev This is required for the proxy pattern to work correctly constructor() { _disableInitializers(); } /// @notice Initializes the contract with required addresses and permissions /// @param _collection Address of the NFT collection contract /// @param _hook Address of the NFTStrategyHook contract /// @param _tokenName Name of the token /// @param _tokenSymbol Symbol of the token /// @param _buyIncrement Buy increment for the token /// @param _owner Owner of the contract function initialize( address _collection, address _hook, string memory _tokenName, string memory _tokenSymbol, uint256 _buyIncrement, address _owner ) external initializer { require(_collection != address(0), "Invalid collection"); require(bytes(_tokenName).length > 0, "Empty name"); require(bytes(_tokenSymbol).length > 0, "Empty symbol"); collection = IERC721(_collection); hookAddress = _hook; tokenName = _tokenName; tokenSymbol = _tokenSymbol; lastBuyBlock = block.number; buyIncrement = _buyIncrement; // Initialize owner without validation in-case we want to disable upgradeability _initializeOwner(_owner); // Initialize state variables that have default values priceMultiplier = 1200; // 1.2x twapIncrement = 1 ether; twapDelayInBlocks = 1; _mint(factory(), MAX_SUPPLY); } /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* MODIFIERS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Restricts function access to the factory contract only modifier onlyFactory() { if (msg.sender != factory()) revert NotFactory(); _; } /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* ADMIN FUNCTIONS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Authorizes contract upgrades (UUPS pattern) /// @param newImplementation Address of the new implementation contract /// @dev Only callable by contract owner, validates implementation is a contract function _authorizeUpgrade(address newImplementation) internal override onlyOwner { require(newImplementation != address(0), "Invalid implementation"); require(newImplementation.code.length > 0, "Implementation must be contract"); emit ContractUpgraded(address(this), newImplementation, VERSION); } /// @notice Updates the hook address /// @dev Can only be called by the owner /// @param _hookAddress New hook address function updateHookAddress(address _hookAddress) external onlyOwner { hookAddress = _hookAddress; } /// @notice Returns the name of the token /// @return The token name as a string function name() public view override returns (string memory) { return tokenName; } /// @notice Returns the symbol of the token /// @return The token symbol as a string function symbol() public view override returns (string memory) { return tokenSymbol; } /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* FACTORY FUNCTIONS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Updates the name of the token /// @dev Can only be called by the factory /// @param _tokenName New name for the token function updateName(string memory _tokenName) external onlyFactory { tokenName = _tokenName; } /// @notice Updates the symbol of the token /// @dev Can only be called by the factory /// @param _tokenSymbol New symbol for the token function updateSymbol(string memory _tokenSymbol) external onlyFactory { tokenSymbol = _tokenSymbol; } /// @notice Updates the price multiplier for relisting punks /// @param _newMultiplier New multiplier in basis points (1100 = 1.1x, 10000 = 10.0x) /// @dev Only callable by factory. Must be between 1.1x (1100) and 10.0x (10000) function setPriceMultiplier(uint256 _newMultiplier) external onlyFactory { if (_newMultiplier < 1100 || _newMultiplier > 10000) revert InvalidMultiplier(); priceMultiplier = _newMultiplier; } /// @notice Allows owner to whitelist addresses that can distribute tokens freely /// @param distributor Address to whitelist /// @param status True to whitelist, false to remove from whitelist /// @dev Only callable by owner. Enables fee-free token distribution for whitelisted addresses function setDistributor(address distributor, bool status) external onlyOwner { isDistributor[distributor] = status; emit DistributorUpdated(distributor, status); } /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* MECHANISM FUNCTIONS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Returns the maximum price allowed for buying an NFT, increasing over time /// @return The maximum price in ETH (wei) that can be used for buying /// @dev Increases by buyIncrement per block from last buy function getMaxPriceForBuy() public view returns (uint256) { // Calculate blocks since last buy uint256 blocksSinceLastBuy = block.number - lastBuyBlock; // Return buyIncrement for each block, starting at 1 block minimum return (blocksSinceLastBuy + 1) * buyIncrement; } /// @notice Allows the hook to deposit trading fees into the contract /// @dev Only callable by the authorized hook contract, uses msg.value for fee amount function addFees() external payable { if (msg.sender != hookAddress) revert OnlyHook(); currentFees += msg.value; } /// @notice Increases the transient transfer allowance for pool operations /// @param amountAllowed Amount to add to the current allowance /// @dev Only callable by the hook contract, uses transient storage function increaseTransferAllowance(uint256 amountAllowed) external { if (msg.sender != hookAddress) revert OnlyHook(); uint256 currentAllowance = getTransferAllowance(); assembly { tstore(0, add(currentAllowance, amountAllowed)) } emit AllowanceIncreased(amountAllowed); } /// @notice Buys a specific NFT using accumulated fees /// @param value Amount of ETH to spend on the NFT purchase /// @param data Calldata for the external marketplace call /// @param expectedId The token ID expected to be acquired /// @param target The marketplace contract to call /// @dev Protected against reentrancy, validates NFT acquisition function buyTargetNFT(uint256 value, bytes calldata data, uint256 expectedId, address target) external nonReentrant { // Store both balance and nft amount before calling external uint256 ethBalanceBefore = address(this).balance; uint256 nftBalanceBefore = collection.balanceOf(address(this)); // Make sure we are not owner of the expected id if (collection.ownerOf(expectedId) == address(this)) { revert AlreadyNFTOwner(); } // Ensure value is not more than currentFees if (value > currentFees) { revert NotEnoughEth(); } // Ensure value doesn't exceed the time-based maximum price if (value > getMaxPriceForBuy()) { revert PriceTooHigh(); } // Ensure target is not the collection itself if (target == address(collection)) revert InvalidTarget(); // Call external (bool success, bytes memory reason) = target.call{value: value}(data); if (!success) { revert ExternalCallFailed(reason); } // Ensure we now have one more NFT uint256 nftBalanceAfter = collection.balanceOf(address(this)); if (nftBalanceAfter != nftBalanceBefore + 1) { revert NeedToBuyNFT(); } // Ensure we are now owner of expectedId if (collection.ownerOf(expectedId) != address(this)) { revert NotNFTOwner(); } // Calculate actual cost of the NFT to base new price on uint256 cost = ethBalanceBefore - address(this).balance; currentFees -= cost; // List NFT for sale at priceMultiplier times the cost uint256 salePrice = cost * priceMultiplier / 1000; nftForSale[expectedId] = salePrice; // Update last buy block to reset max price calculation lastBuyBlock = block.number; emit NFTBoughtByProtocol(expectedId, cost, salePrice); } /// @notice Sells an NFT owned by the contract for the listed price /// @param tokenId The ID of the NFT to sell function sellTargetNFT(uint256 tokenId) external payable nonReentrant { // Get sale price uint256 salePrice = nftForSale[tokenId]; // Verify NFT is for sale if (salePrice == 0) revert NFTNotForSale(); // Verify sent ETH matches sale price if (msg.value != salePrice) revert NFTPriceTooLow(); // Verify contract owns the NFT if (collection.ownerOf(tokenId) != address(this)) revert NotNFTOwner(); // Transfer NFT to buyer collection.transferFrom(address(this), msg.sender, tokenId); // Remove NFT from sale delete nftForSale[tokenId]; // Add sale price to fees ethToTwap += salePrice; emit NFTSoldByProtocol(tokenId, salePrice, msg.sender); } /// @notice Processes token buyback using TWAP mechanism /// @dev Can be called once every twapDelayInBlocks, uses ethToTwap for buyback /// @dev Caller receives 0.5% reward, remaining ETH is used to buy and burn tokens function processTokenTwap() external nonReentrant { if (ethToTwap == 0) revert NoETHToTwap(); // Check if enough blocks have passed since last TWAP if (block.number < lastTwapBlock + twapDelayInBlocks) revert TwapDelayNotMet(); // Calculate amount to burn - either twapIncrement or remaining ethToTwap uint256 burnAmount = twapIncrement; if (ethToTwap < twapIncrement) { burnAmount = ethToTwap; } // Set reward to 0.5% of burnAmount uint256 reward = (burnAmount * 5) / 1000; burnAmount -= reward; // Update state ethToTwap -= burnAmount + reward; lastTwapBlock = block.number; _buyAndBurnTokens(burnAmount); // Send reward to caller SafeTransferLib.forceSafeTransferETH(msg.sender, reward); } /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* INTERNAL FUNCTIONS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Buys tokens with ETH and burns them by sending to dead address /// @param amountIn The amount of ETH to spend on tokens that will be burned /// @dev Creates a pool key and swaps ETH for tokens, sending tokens to dead address function _buyAndBurnTokens(uint256 amountIn) internal { PoolKey memory key = PoolKey(Currency.wrap(address(0)), Currency.wrap(address(this)), 0, 60, IHooks(hookAddress)); router().swapExactTokensForTokens{value: amountIn}(amountIn, 0, true, key, "", DEAD_ADDRESS, block.timestamp); } /// @notice Validates token transfers using a transient allowance system /// @param from The address sending tokens /// @param to The address receiving tokens /// @param amount The amount of tokens being transferred /// @dev Reverts if transfer isn't through the hook function _afterTokenTransfer(address from, address to, uint256 amount) internal override { // On strategy launch, we need to allow for supply mint transfer if (from == address(0)) { return; } // Allow whitelisted distributors to send tokens freely if (isDistributor[from]) { return; } // Transfers to and from the poolManager require a transient allowance thats set by the hook if ((from == address(poolManager()) || to == address(poolManager()))) { uint256 transferAllowance = getTransferAllowance(); require(transferAllowance >= amount, InvalidTransfer()); assembly { let newAllowance := sub(transferAllowance, amount) tstore(0, newAllowance) } emit AllowanceSpent(from, to, amount); return; } revert InvalidTransfer(); } /// @notice Gets the current transient transfer allowance /// @return transferAllowance The current allowance amount /// @dev Reads from transient storage slot 0 function getTransferAllowance() public view returns (uint256 transferAllowance) { assembly { transferAllowance := tload(0) } } /// @notice Handles receipt of NFTs (ERC721 receiver) /// @dev Only accepts NFTs from the designated collection /// @return The function selector to confirm receipt function onERC721Received(address, address, uint256, bytes calldata) external view returns (bytes4) { if (msg.sender != address(collection)) { revert InvalidCollection(); } return this.onERC721Received.selector; } /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /* GETTER FUNCTIONS */ /* ™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™ */ /// @notice Returns the factory address from proxy bytecode /// @return The factory contract address /// @dev Reads from bytes 0-20 of the proxy's immutable args function factory() public view returns (address) { bytes memory args = LibClone.argsOnERC1967(address(this), 0, 20); return address(bytes20(args)); } /// @notice Returns the router address from proxy bytecode /// @return The Uniswap V4 router contract interface /// @dev Reads from bytes 20-40 of the proxy's immutable args function router() public view returns (IUniswapV4Router04) { bytes memory args = LibClone.argsOnERC1967(address(this), 20, 40); return IUniswapV4Router04(payable(address(bytes20(args)))); } /// @notice Returns the pool manager address from proxy bytecode /// @return The Uniswap V4 pool manager contract interface /// @dev Reads from bytes 40-60 of the proxy's immutable args function poolManager() public view returns (IPoolManager) { bytes memory args = LibClone.argsOnERC1967(address(this), 40, 60); return IPoolManager(address(bytes20(args))); } /// @notice Returns the current implementation address /// @return result The address of the current implementation contract /// @dev Reads from the ERC1967 implementation slot function getImplementation() external view returns (address result) { assembly { result := sload(_ERC1967_IMPLEMENTATION_SLOT) } } /// @notice Allows the contract to receive ETH receive() external payable {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Simple ERC20 + EIP-2612 implementation. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol) /// /// @dev Note: /// - The ERC20 standard allows minting and transferring to and from the zero address, /// minting and transferring zero tokens, as well as self-approvals. /// For performance, this implementation WILL NOT revert for such actions. /// Please add any checks with overrides if desired. /// - The `permit` function uses the ecrecover precompile (0x1). /// /// If you are overriding: /// - NEVER violate the ERC20 invariant: /// the total sum of all balances must be equal to `totalSupply()`. /// - Check that the overridden function is actually used in the function you want to /// change the behavior of. Much of the code has been manually inlined for performance. abstract contract ERC20 { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The total supply has overflowed. error TotalSupplyOverflow(); /// @dev The allowance has overflowed. error AllowanceOverflow(); /// @dev The allowance has underflowed. error AllowanceUnderflow(); /// @dev Insufficient balance. error InsufficientBalance(); /// @dev Insufficient allowance. error InsufficientAllowance(); /// @dev The permit is invalid. error InvalidPermit(); /// @dev The permit has expired. error PermitExpired(); /// @dev The allowance of Permit2 is fixed at infinity. error Permit2AllowanceIsFixedAtInfinity(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Emitted when `amount` tokens is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 amount); /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`. uint256 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`. uint256 private constant _APPROVAL_EVENT_SIGNATURE = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The storage slot for the total supply. uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c; /// @dev The balance slot of `owner` is given by: /// ``` /// mstore(0x0c, _BALANCE_SLOT_SEED) /// mstore(0x00, owner) /// let balanceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2; /// @dev The allowance slot of (`owner`, `spender`) is given by: /// ``` /// mstore(0x20, spender) /// mstore(0x0c, _ALLOWANCE_SLOT_SEED) /// mstore(0x00, owner) /// let allowanceSlot := keccak256(0x0c, 0x34) /// ``` uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20; /// @dev The nonce slot of `owner` is given by: /// ``` /// mstore(0x0c, _NONCES_SLOT_SEED) /// mstore(0x00, owner) /// let nonceSlot := keccak256(0x0c, 0x20) /// ``` uint256 private constant _NONCES_SLOT_SEED = 0x38377508; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`. uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901; /// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`. bytes32 private constant _DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev `keccak256("1")`. /// If you need to use a different version, override `_versionHash`. bytes32 private constant _DEFAULT_VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; /// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`. bytes32 private constant _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @dev The canonical Permit2 address. /// For signature-based allowance granting for single transaction ERC20 `transferFrom`. /// Enabled by default. To disable, override `_givePermit2InfiniteAllowance()`. /// [Github](https://github.com/Uniswap/permit2) /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3) address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 METADATA */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the name of the token. function name() public view virtual returns (string memory); /// @dev Returns the symbol of the token. function symbol() public view virtual returns (string memory); /// @dev Returns the decimals places of the token. function decimals() public view virtual returns (uint8) { return 18; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the amount of tokens in existence. function totalSupply() public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { result := sload(_TOTAL_SUPPLY_SLOT) } } /// @dev Returns the amount of tokens owned by `owner`. function balanceOf(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`. function allowance(address owner, address spender) public view virtual returns (uint256 result) { if (_givePermit2InfiniteAllowance()) { if (spender == _PERMIT2) return type(uint256).max; } /// @solidity memory-safe-assembly assembly { mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x34)) } } /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens. /// /// Emits a {Approval} event. function approve(address spender, uint256 amount) public virtual returns (bool) { if (_givePermit2InfiniteAllowance()) { /// @solidity memory-safe-assembly assembly { // If `spender == _PERMIT2 && amount != type(uint256).max`. if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) { mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`. revert(0x1c, 0x04) } } } /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c))) } return true; } /// @dev Transfer `amount` tokens from the caller to `to`. /// /// Requirements: /// - `from` must at least have `amount`. /// /// Emits a {Transfer} event. function transfer(address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(msg.sender, to, amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, caller()) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c))) } _afterTokenTransfer(msg.sender, to, amount); return true; } /// @dev Transfers `amount` tokens from `from` to `to`. /// /// Note: Does not update the allowance if it is the maximum uint256 value. /// /// Requirements: /// - `from` must at least have `amount`. /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`. /// /// Emits a {Transfer} event. function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) { _beforeTokenTransfer(from, to, amount); // Code duplication is for zero-cost abstraction if possible. if (_givePermit2InfiniteAllowance()) { /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) if iszero(eq(caller(), _PERMIT2)) { // Compute the allowance slot and load its value. mstore(0x20, caller()) mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED)) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if not(allowance_) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } } // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } } else { /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the allowance slot and load its value. mstore(0x20, caller()) mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED)) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if not(allowance_) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } } _afterTokenTransfer(from, to, amount); return true; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EIP-2612 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev For more performance, override to return the constant value /// of `keccak256(bytes(name()))` if `name()` will never change. function _constantNameHash() internal view virtual returns (bytes32 result) {} /// @dev If you need a different value, override this function. function _versionHash() internal view virtual returns (bytes32 result) { result = _DEFAULT_VERSION_HASH; } /// @dev For inheriting contracts to increment the nonce. function _incrementNonce(address owner) internal virtual { /// @solidity memory-safe-assembly assembly { mstore(0x0c, _NONCES_SLOT_SEED) mstore(0x00, owner) let nonceSlot := keccak256(0x0c, 0x20) sstore(nonceSlot, add(1, sload(nonceSlot))) } } /// @dev Returns the current nonce for `owner`. /// This value is used to compute the signature for EIP-2612 permit. function nonces(address owner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { // Compute the nonce slot and load its value. mstore(0x0c, _NONCES_SLOT_SEED) mstore(0x00, owner) result := sload(keccak256(0x0c, 0x20)) } } /// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`, /// authorized by a signed approval by `owner`. /// /// Emits a {Approval} event. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { if (_givePermit2InfiniteAllowance()) { /// @solidity memory-safe-assembly assembly { // If `spender == _PERMIT2 && value != type(uint256).max`. if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) { mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`. revert(0x1c, 0x04) } } } bytes32 nameHash = _constantNameHash(); // We simply calculate it on-the-fly to allow for cases where the `name` may change. if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name())); bytes32 versionHash = _versionHash(); /// @solidity memory-safe-assembly assembly { // Revert if the block timestamp is greater than `deadline`. if gt(timestamp(), deadline) { mstore(0x00, 0x1a15a3cc) // `PermitExpired()`. revert(0x1c, 0x04) } let m := mload(0x40) // Grab the free memory pointer. // Clean the upper 96 bits. owner := shr(96, shl(96, owner)) spender := shr(96, shl(96, spender)) // Compute the nonce slot and load its value. mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX) mstore(0x00, owner) let nonceSlot := keccak256(0x0c, 0x20) let nonceValue := sload(nonceSlot) // Prepare the domain separator. mstore(m, _DOMAIN_TYPEHASH) mstore(add(m, 0x20), nameHash) mstore(add(m, 0x40), versionHash) mstore(add(m, 0x60), chainid()) mstore(add(m, 0x80), address()) mstore(0x2e, keccak256(m, 0xa0)) // Prepare the struct hash. mstore(m, _PERMIT_TYPEHASH) mstore(add(m, 0x20), owner) mstore(add(m, 0x40), spender) mstore(add(m, 0x60), value) mstore(add(m, 0x80), nonceValue) mstore(add(m, 0xa0), deadline) mstore(0x4e, keccak256(m, 0xc0)) // Prepare the ecrecover calldata. mstore(0x00, keccak256(0x2c, 0x42)) mstore(0x20, and(0xff, v)) mstore(0x40, r) mstore(0x60, s) let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20) // If the ecrecover fails, the returndatasize will be 0x00, // `owner` will be checked if it equals the hash at 0x00, // which evaluates to false (i.e. 0), and we will revert. // If the ecrecover succeeds, the returndatasize will be 0x20, // `owner` will be compared against the returned address at 0x20. if iszero(eq(mload(returndatasize()), owner)) { mstore(0x00, 0xddafbaef) // `InvalidPermit()`. revert(0x1c, 0x04) } // Increment and store the updated nonce. sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds. // Compute the allowance slot and store the value. // The `owner` is already at slot 0x20. mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender)) sstore(keccak256(0x2c, 0x34), value) // Emit the {Approval} event. log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero pointer. } } /// @dev Returns the EIP-712 domain separator for the EIP-2612 permit. function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) { bytes32 nameHash = _constantNameHash(); // We simply calculate it on-the-fly to allow for cases where the `name` may change. if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name())); bytes32 versionHash = _versionHash(); /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Grab the free memory pointer. mstore(m, _DOMAIN_TYPEHASH) mstore(add(m, 0x20), nameHash) mstore(add(m, 0x40), versionHash) mstore(add(m, 0x60), chainid()) mstore(add(m, 0x80), address()) result := keccak256(m, 0xa0) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL MINT FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Mints `amount` tokens to `to`, increasing the total supply. /// /// Emits a {Transfer} event. function _mint(address to, uint256 amount) internal virtual { _beforeTokenTransfer(address(0), to, amount); /// @solidity memory-safe-assembly assembly { let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT) let totalSupplyAfter := add(totalSupplyBefore, amount) // Revert if the total supply overflows. if lt(totalSupplyAfter, totalSupplyBefore) { mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`. revert(0x1c, 0x04) } // Store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter) // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c))) } _afterTokenTransfer(address(0), to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL BURN FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Burns `amount` tokens from `from`, reducing the total supply. /// /// Emits a {Transfer} event. function _burn(address from, uint256 amount) internal virtual { _beforeTokenTransfer(from, address(0), amount); /// @solidity memory-safe-assembly assembly { // Compute the balance slot and load its value. mstore(0x0c, _BALANCE_SLOT_SEED) mstore(0x00, from) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Subtract and store the updated total supply. sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount)) // Emit the {Transfer} event. mstore(0x00, amount) log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0) } _afterTokenTransfer(from, address(0), amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL TRANSFER FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Moves `amount` of tokens from `from` to `to`. function _transfer(address from, address to, uint256 amount) internal virtual { _beforeTokenTransfer(from, to, amount); /// @solidity memory-safe-assembly assembly { let from_ := shl(96, from) // Compute the balance slot and load its value. mstore(0x0c, or(from_, _BALANCE_SLOT_SEED)) let fromBalanceSlot := keccak256(0x0c, 0x20) let fromBalance := sload(fromBalanceSlot) // Revert if insufficient balance. if gt(amount, fromBalance) { mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`. revert(0x1c, 0x04) } // Subtract and store the updated balance. sstore(fromBalanceSlot, sub(fromBalance, amount)) // Compute the balance slot of `to`. mstore(0x00, to) let toBalanceSlot := keccak256(0x0c, 0x20) // Add and store the updated balance of `to`. // Will not overflow because the sum of all user balances // cannot exceed the maximum uint256 value. sstore(toBalanceSlot, add(sload(toBalanceSlot), amount)) // Emit the {Transfer} event. mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c))) } _afterTokenTransfer(from, to, amount); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL ALLOWANCE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`. function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { if (_givePermit2InfiniteAllowance()) { if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite. } /// @solidity memory-safe-assembly assembly { // Compute the allowance slot and load its value. mstore(0x20, spender) mstore(0x0c, _ALLOWANCE_SLOT_SEED) mstore(0x00, owner) let allowanceSlot := keccak256(0x0c, 0x34) let allowance_ := sload(allowanceSlot) // If the allowance is not the maximum uint256 value. if not(allowance_) { // Revert if the amount to be transferred exceeds the allowance. if gt(amount, allowance_) { mstore(0x00, 0x13be252b) // `InsufficientAllowance()`. revert(0x1c, 0x04) } // Subtract and store the updated allowance. sstore(allowanceSlot, sub(allowance_, amount)) } } } /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`. /// /// Emits a {Approval} event. function _approve(address owner, address spender, uint256 amount) internal virtual { if (_givePermit2InfiniteAllowance()) { /// @solidity memory-safe-assembly assembly { // If `spender == _PERMIT2 && amount != type(uint256).max`. if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) { mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`. revert(0x1c, 0x04) } } } /// @solidity memory-safe-assembly assembly { let owner_ := shl(96, owner) // Compute the allowance slot and store the amount. mstore(0x20, spender) mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED)) sstore(keccak256(0x0c, 0x34), amount) // Emit the {Approval} event. mstore(0x00, amount) log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c))) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* HOOKS TO OVERRIDE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Hook that is called before any transfer of tokens. /// This includes minting and burning. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /// @dev Hook that is called after any transfer of tokens. /// This includes minting and burning. function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* PERMIT2 */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns whether to fix the Permit2 contract's allowance at infinity. /// /// This value should be kept constant after contract initialization, /// or else the actual allowance values may not match with the {Approval} events. /// For best performance, return a compile-time constant for zero-cost abstraction. function _givePermit2InfiniteAllowance() internal view virtual returns (bool) { return true; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Reentrancy guard mixin. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol) abstract contract ReentrancyGuard { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Unauthorized reentrant call. error Reentrancy(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`. /// 9 bytes is large enough to avoid collisions with lower slots, /// but not too large to result in excessive bytecode bloat. uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* REENTRANCY GUARD */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Guards a function from reentrancy. modifier nonReentrant() virtual { /// @solidity memory-safe-assembly assembly { if eq(sload(_REENTRANCY_GUARD_SLOT), address()) { mstore(0x00, 0xab143c06) // `Reentrancy()`. revert(0x1c, 0x04) } sstore(_REENTRANCY_GUARD_SLOT, address()) } _; /// @solidity memory-safe-assembly assembly { sstore(_REENTRANCY_GUARD_SLOT, codesize()) } } /// @dev Guards a view function from read-only reentrancy. modifier nonReadReentrant() virtual { /// @solidity memory-safe-assembly assembly { if eq(sload(_REENTRANCY_GUARD_SLOT), address()) { mstore(0x00, 0xab143c06) // `Reentrancy()`. revert(0x1c, 0x04) } } _; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol) /// /// @dev Note: /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection. library SafeTransferLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The ETH transfer has failed. error ETHTransferFailed(); /// @dev The ERC20 `transferFrom` has failed. error TransferFromFailed(); /// @dev The ERC20 `transfer` has failed. error TransferFailed(); /// @dev The ERC20 `approve` has failed. error ApproveFailed(); /// @dev The ERC20 `totalSupply` query has failed. error TotalSupplyQueryFailed(); /// @dev The Permit2 operation has failed. error Permit2Failed(); /// @dev The Permit2 amount must be less than `2**160 - 1`. error Permit2AmountOverflow(); /// @dev The Permit2 approve operation has failed. error Permit2ApproveFailed(); /// @dev The Permit2 lockdown operation has failed. error Permit2LockdownFailed(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes. uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300; /// @dev Suggested gas stipend for contract receiving ETH to perform a few /// storage reads and writes, but low enough to prevent griefing. uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000; /// @dev The unique EIP-712 domain separator for the DAI token contract. bytes32 internal constant DAI_DOMAIN_SEPARATOR = 0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7; /// @dev The address for the WETH9 contract on Ethereum mainnet. address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev The canonical Permit2 address. /// [Github](https://github.com/Uniswap/permit2) /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3) address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3; /// @dev The canonical address of the `SELFDESTRUCT` ETH mover. /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D) address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ETH OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants. // // The regular variants: // - Forwards all remaining gas to the target. // - Reverts if the target reverts. // - Reverts if the current contract has insufficient balance. // // The force variants: // - Forwards with an optional gas stipend // (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases). // - If the target reverts, or if the gas stipend is exhausted, // creates a temporary contract to force send the ETH via `SELFDESTRUCT`. // Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758. // - Reverts if the current contract has insufficient balance. // // The try variants: // - Forwards with a mandatory gas stipend. // - Instead of reverting, returns whether the transfer succeeded. /// @dev Sends `amount` (in wei) ETH to `to`. function safeTransferETH(address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } } } /// @dev Sends all the ETH in the current contract to `to`. function safeTransferAllETH(address to) internal { /// @solidity memory-safe-assembly assembly { // Transfer all the ETH and check if it succeeded or not. if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } } } /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`. function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { if lt(selfbalance(), amount) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`. function forceSafeTransferAllETH(address to, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`. function forceSafeTransferETH(address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { if lt(selfbalance(), amount) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`. function forceSafeTransferAllETH(address to) internal { /// @solidity memory-safe-assembly assembly { // forgefmt: disable-next-item if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`. function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00) } } /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`. function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00) } } /// @dev Force transfers ETH to `to`, without triggering the fallback (if any). /// This method attempts to use a separate contract to send via `SELFDESTRUCT`, /// and upon failure, deploys a minimal vault to accrue the ETH. function safeMoveETH(address to, uint256 amount) internal returns (address vault) { /// @solidity memory-safe-assembly assembly { to := shr(96, shl(96, to)) // Clean upper 96 bits. for { let mover := ETH_MOVER } iszero(eq(to, address())) {} { let selfBalanceBefore := selfbalance() if or(lt(selfBalanceBefore, amount), eq(to, mover)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } if extcodesize(mover) { let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked. mstore(0x00, to) pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00)) if iszero(lt(add(amount, balance(to)), balanceBefore)) { break } if lt(selfBalanceBefore, selfbalance()) { invalid() } // Just in case. } let m := mload(0x40) // If the mover is missing or bricked, deploy a minimal vault // that withdraws all ETH to `to` when being called only by `to`. // forgefmt: disable-next-item mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd) mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73))) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(m, 0x40)) mstore(0x01, shl(96, address())) // Deployer. mstore(0x15, 0) // Salt. vault := keccak256(0x00, 0x55) pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00)) // The vault returns a single word on success. Failure reverts with empty data. if iszero(returndatasize()) { if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation. } mstore(0x40, m) // Restore the free memory pointer. break } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// Reverts upon failure. /// /// The `from` account must have at least `amount` approved for /// the current contract to manage. function safeTransferFrom(address token, address from, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, amount) // Store the `amount` argument. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`. let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// /// The `from` account must have at least `amount` approved for the current contract to manage. function trySafeTransferFrom(address token, address from, address to, uint256 amount) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, amount) // Store the `amount` argument. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`. success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { success := lt(or(iszero(extcodesize(token)), returndatasize()), success) } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends all of ERC20 `token` from `from` to `to`. /// Reverts upon failure. /// /// The `from` account must have their entire balance approved for the current contract to manage. function safeTransferAllFrom(address token, address from, address to) internal returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`. // Read the balance, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20) ) ) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`. amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`. /// Reverts upon failure. function safeTransfer(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sends all of ERC20 `token` from the current contract to `to`. /// Reverts upon failure. function safeTransferAll(address token, address to) internal returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`. mstore(0x20, address()) // Store the address of the current contract. // Read the balance, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20) ) ) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } mstore(0x14, to) // Store the `to` argument. amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract. /// Reverts upon failure. function safeApprove(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract. /// If the initial attempt to approve fails, attempts to reset the approved amount to zero, /// then retries the approval again (some tokens, e.g. USDT, requires this). /// Reverts upon failure. function safeApproveWithRetry(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. // Perform the approval, retrying upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x34, 0) // Store 0 for the `amount`. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval. mstore(0x34, amount) // Store back the original `amount`. // Retry the approval, reverting upon failure. success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { // Check the `extcodesize` again just in case the token selfdestructs lol. if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`. revert(0x1c, 0x04) } } } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Returns the amount of ERC20 `token` owned by `account`. /// Returns zero if the `token` does not exist. function balanceOf(address token, address account) internal view returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { mstore(0x14, account) // Store the `account` argument. mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`. amount := mul( // The arguments of `mul` are evaluated from right to left. mload(0x20), and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20) ) ) } } /// @dev Performs a `token.balanceOf(account)` check. /// `implemented` denotes whether the `token` does not implement `balanceOf`. /// `amount` is zero if the `token` does not implement `balanceOf`. function checkBalanceOf(address token, address account) internal view returns (bool implemented, uint256 amount) { /// @solidity memory-safe-assembly assembly { mstore(0x14, account) // Store the `account` argument. mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`. implemented := and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20) ) amount := mul(mload(0x20), implemented) } } /// @dev Returns the total supply of the `token`. /// Reverts if the token does not exist or does not implement `totalSupply()`. function totalSupply(address token) internal view returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x18160ddd) // `totalSupply()`. if iszero( and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20)) ) { mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`. revert(0x1c, 0x04) } result := mload(0x00) } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// If the initial attempt fails, try to use Permit2 to transfer the token. /// Reverts upon failure. /// /// The `from` account must have at least `amount` approved for the current contract to manage. function safeTransferFrom2(address token, address from, address to, uint256 amount) internal { if (!trySafeTransferFrom(token, from, to, amount)) { permit2TransferFrom(token, from, to, amount); } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2. /// Reverts upon failure. function permit2TransferFrom(address token, address from, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(add(m, 0x74), shr(96, shl(96, token))) mstore(add(m, 0x54), amount) mstore(add(m, 0x34), to) mstore(add(m, 0x20), shl(96, from)) // `transferFrom(address,address,uint160,address)`. mstore(m, 0x36c78516000000000000000000000000) let p := PERMIT2 let exists := eq(chainid(), 1) if iszero(exists) { exists := iszero(iszero(extcodesize(p))) } if iszero( and( call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists. ) ) { mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`. revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04) } } } /// @dev Permit a user to spend a given amount of /// another user's tokens via native EIP-2612 permit if possible, falling /// back to Permit2 if native permit fails or is not implemented on the token. function permit2( address token, address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { bool success; /// @solidity memory-safe-assembly assembly { for {} shl(96, xor(token, WETH9)) {} { mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`. if iszero( and( // The arguments of `and` are evaluated from right to left. lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word. // Gas stipend to limit gas burn for tokens that don't refund gas when // an non-existing function is called. 5K should be enough for a SLOAD. staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20) ) ) { break } // After here, we can be sure that token is a contract. let m := mload(0x40) mstore(add(m, 0x34), spender) mstore(add(m, 0x20), shl(96, owner)) mstore(add(m, 0x74), deadline) if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) { mstore(0x14, owner) mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`. mstore( add(m, 0x94), lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20)) ) mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`. // `nonces` is already at `add(m, 0x54)`. // `amount != 0` is already stored at `add(m, 0x94)`. mstore(add(m, 0xb4), and(0xff, v)) mstore(add(m, 0xd4), r) mstore(add(m, 0xf4), s) success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00) break } mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`. mstore(add(m, 0x54), amount) mstore(add(m, 0x94), and(0xff, v)) mstore(add(m, 0xb4), r) mstore(add(m, 0xd4), s) success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00) break } } if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s); } /// @dev Simple permit on the Permit2 contract. function simplePermit2( address token, address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, 0x927da105) // `allowance(address,address,address)`. { let addressMask := shr(96, not(0)) mstore(add(m, 0x20), and(addressMask, owner)) mstore(add(m, 0x40), and(addressMask, token)) mstore(add(m, 0x60), and(addressMask, spender)) mstore(add(m, 0xc0), and(addressMask, spender)) } let p := mul(PERMIT2, iszero(shr(160, amount))) if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`. staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60) ) ) { mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`. revert(add(0x18, shl(2, iszero(p))), 0x04) } mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant). // `owner` is already `add(m, 0x20)`. // `token` is already at `add(m, 0x40)`. mstore(add(m, 0x60), amount) mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`. // `nonce` is already at `add(m, 0xa0)`. // `spender` is already at `add(m, 0xc0)`. mstore(add(m, 0xe0), deadline) mstore(add(m, 0x100), 0x100) // `signature` offset. mstore(add(m, 0x120), 0x41) // `signature` length. mstore(add(m, 0x140), r) mstore(add(m, 0x160), s) mstore(add(m, 0x180), shl(248, v)) if iszero( // Revert if token does not have code, or if the call fails. mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) { mstore(0x00, 0x6b836e6b) // `Permit2Failed()`. revert(0x1c, 0x04) } } } /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`. function permit2Approve(address token, address spender, uint160 amount, uint48 expiration) internal { /// @solidity memory-safe-assembly assembly { let addressMask := shr(96, not(0)) let m := mload(0x40) mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`. mstore(add(m, 0x20), and(addressMask, token)) mstore(add(m, 0x40), and(addressMask, spender)) mstore(add(m, 0x60), and(addressMask, amount)) mstore(add(m, 0x80), and(0xffffffffffff, expiration)) if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) { mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`. revert(0x1c, 0x04) } } } /// @dev Revokes an approval for `token` and `spender` for `address(this)`. function permit2Lockdown(address token, address spender) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, 0xcc53287f) // `Permit2.lockdown`. mstore(add(m, 0x20), 0x20) // Offset of the `approvals`. mstore(add(m, 0x40), 1) // `approvals.length`. mstore(add(m, 0x60), shr(96, shl(96, token))) mstore(add(m, 0x80), shr(96, shl(96, spender))) if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) { mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`. revert(0x1c, 0x04) } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits /// of the address that the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. /// See the Hooks library for the full spec. /// @dev Should only be callable by the v4 PoolManager. interface IHooks { /// @notice The hook called before the state of a pool is initialized /// @param sender The initial msg.sender for the initialize call /// @param key The key for the pool being initialized /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96 /// @return bytes4 The function selector for the hook function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4); /// @notice The hook called after the state of a pool is initialized /// @param sender The initial msg.sender for the initialize call /// @param key The key for the pool being initialized /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96 /// @param tick The current tick after the state of a pool is initialized /// @return bytes4 The function selector for the hook function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick) external returns (bytes4); /// @notice The hook called before liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook function beforeAddLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is added /// @param sender The initial msg.sender for the add liquidity call /// @param key The key for the pool /// @param params The parameters for adding liquidity /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta /// @param feesAccrued The fees accrued since the last time fees were collected from this position /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterAddLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeRemoveLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after liquidity is removed /// @param sender The initial msg.sender for the remove liquidity call /// @param key The key for the pool /// @param params The parameters for removing liquidity /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta /// @param feesAccrued The fees accrued since the last time fees were collected from this position /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterRemoveLiquidity( address sender, PoolKey calldata key, ModifyLiquidityParams calldata params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) external returns (bytes4, BalanceDelta); /// @notice The hook called before a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million) function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData) external returns (bytes4, BeforeSwapDelta, uint24); /// @notice The hook called after a swap /// @param sender The initial msg.sender for the swap call /// @param key The key for the pool /// @param params The parameters for the swap /// @param delta The amount owed to the caller (positive) or owed to the pool (negative) /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook /// @return bytes4 The function selector for the hook /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency function afterSwap( address sender, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata hookData ) external returns (bytes4, int128); /// @notice The hook called before donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function beforeDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); /// @notice The hook called after donate /// @param sender The initial msg.sender for the donate call /// @param key The key for the pool /// @param amount0 The amount of token0 being donated /// @param amount1 The amount of token1 being donated /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook /// @return bytes4 The function selector for the hook function afterDonate( address sender, PoolKey calldata key, uint256 amount0, uint256 amount1, bytes calldata hookData ) external returns (bytes4); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol"; import {CustomRevert} from "../libraries/CustomRevert.sol"; type Currency is address; using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global; using CurrencyLibrary for Currency global; function equals(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(other); } function greaterThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) > Currency.unwrap(other); } function lessThan(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) < Currency.unwrap(other); } function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) { return Currency.unwrap(currency) >= Currency.unwrap(other); } /// @title CurrencyLibrary /// @dev This library allows for transferring and holding native tokens and ERC20 tokens library CurrencyLibrary { /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails error NativeTransferFailed(); /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails error ERC20TransferFailed(); /// @notice A constant to represent the native currency Currency public constant ADDRESS_ZERO = Currency.wrap(address(0)); function transfer(Currency currency, address to, uint256 amount) internal { // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol // modified custom error selectors bool success; if (currency.isAddressZero()) { assembly ("memory-safe") { // Transfer the ETH and revert if it fails. success := call(gas(), to, amount, 0, 0, 0, 0) } // revert with NativeTransferFailed, containing the bubbled up error as an argument if (!success) { CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector); } } else { assembly ("memory-safe") { // Get a pointer to some free memory. let fmp := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument. mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type. success := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), currency, 0, fmp, 68, 0, 32) ) // Now clean the memory we used mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here } // revert with ERC20TransferFailed, containing the bubbled up error as an argument if (!success) { CustomRevert.bubbleUpAndRevertWith( Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector ); } } } function balanceOfSelf(Currency currency) internal view returns (uint256) { if (currency.isAddressZero()) { return address(this).balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this)); } } function balanceOf(Currency currency, address owner) internal view returns (uint256) { if (currency.isAddressZero()) { return owner.balance; } else { return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner); } } function isAddressZero(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO); } function toId(Currency currency) internal pure returns (uint256) { return uint160(Currency.unwrap(currency)); } // If the upper 12 bytes are non-zero, they will be zero-ed out // Therefore, fromId() and toId() are not inverses of each other function fromId(uint256 id) internal pure returns (Currency) { return Currency.wrap(address(uint160(id))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Currency} from "./Currency.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {PoolIdLibrary} from "./PoolId.sol"; using PoolIdLibrary for PoolKey global; /// @notice Returns the key for identifying a pool struct PoolKey { /// @notice The lower currency of the pool, sorted numerically Currency currency0; /// @notice The higher currency of the pool, sorted numerically Currency currency1; /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000 uint24 fee; /// @notice Ticks that involve positions must be a multiple of tick spacing int24 tickSpacing; /// @notice The hooks of the pool IHooks hooks; }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.26; import {PathKey} from "../libraries/PathKey.sol"; import {PoolKey} from "@v4/src/types/PoolKey.sol"; import {Currency} from "@v4/src/types/Currency.sol"; import {BalanceDelta} from "@v4/src/types/BalanceDelta.sol"; import {ISignatureTransfer} from "@permit2/interfaces/ISignatureTransfer.sol"; /// @title Uniswap V4 Swap Router /// @notice A simple, stateless router for execution of swaps against Uniswap v4 Pools /// @dev ABI inspired by UniswapV2Router02 interface IUniswapV4Router04 { /// ================ MULTI POOL SWAPS ================= /// /// @notice Exact Input Swap; swap the specified amount of input tokens for as many output tokens as possible, along the path /// @param amountIn the amount of input tokens to swap /// @param amountOutMin the minimum amount of output tokens that must be received for the transaction not to revert. reverts on equals to /// @param startCurrency the currency to start the swap from /// @param path the path of v4 Pools to swap through /// @param receiver the address to send the output tokens to /// @param deadline block.timestamp must be before this value, otherwise the transaction will revert /// @return Delta the balance changes from the swap function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, Currency startCurrency, PathKey[] calldata path, address receiver, uint256 deadline ) external payable returns (BalanceDelta); /// @notice Exact Output Swap; swap as few input tokens as possible for the specified amount of output tokens, along the path /// @param amountOut the amount of output tokens to receive /// @param amountInMax the maximum amount of input tokens that can be spent for the transaction not to revert. reverts on equal to /// @param startCurrency the currency to start the swap from /// @param path the path of v4 Pools to swap through /// @param receiver the address to send the output tokens to /// @param deadline block.timestamp must be before this value, otherwise the transaction will revert /// @return Delta the balance changes from the swap function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, Currency startCurrency, PathKey[] calldata path, address receiver, uint256 deadline ) external payable returns (BalanceDelta); /// @notice General-purpose swap interface for Uniswap v4 that handles all types of swaps /// @param amountSpecified the amount of tokens to be swapped, negative for exact input swaps and positive for exact output swaps /// @param amountLimit the minimum amount of output tokens for exact input swaps, the maximum amount of input tokens for exact output swaps /// @param startCurrency the currency to start the swap from /// @param path the path of v4 Pools to swap through /// @param receiver the address to send the output tokens to /// @param deadline block.timestamp must be before this value, otherwise the transaction will revert /// @return Delta the balance changes from the swap function swap( int256 amountSpecified, uint256 amountLimit, Currency startCurrency, PathKey[] calldata path, address receiver, uint256 deadline ) external payable returns (BalanceDelta); /// ================ SINGLE POOL SWAPS ================ /// /// @notice Single pool, exact input swap - swap the specified amount of input tokens for as many output tokens as possible, on a single pool /// @param amountIn the amount of input tokens to swap /// @param amountOutMin the minimum amount of output tokens that must be received for the transaction not to revert /// @param zeroForOne the direction of the swap, true if currency0 is being swapped for currency1 /// @param poolKey the pool to swap through /// @param hookData the data to be passed to the hook /// @param receiver the address to send the output tokens to /// @param deadline block.timestamp must be before this value, otherwise the transaction will revert /// @return Delta the balance changes from the swap function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, bool zeroForOne, PoolKey calldata poolKey, bytes calldata hookData, address receiver, uint256 deadline ) external payable returns (BalanceDelta); /// @notice Singe pool, exact output swap; swap as few input tokens as possible for the specified amount of output tokens, on a single pool /// @param amountOut the amount of output tokens to receive /// @param amountInMax the maximum amount of input tokens that can be spent for the transaction not to revert /// @param zeroForOne the direction of the swap, true if currency0 is being swapped for currency1 /// @param poolKey the pool to swap through /// @param hookData the data to be passed to the hook /// @param receiver the address to send the output tokens to /// @param deadline block.timestamp must be before this value, otherwise the transaction will revert /// @return Delta the balance changes from the swap function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, bool zeroForOne, PoolKey calldata poolKey, bytes calldata hookData, address receiver, uint256 deadline ) external payable returns (BalanceDelta); /// @notice General-purpose single-pool swap interface /// @param amountSpecified the amount of tokens to be swapped, negative for exact input swaps and positive for exact output swaps /// @param amountLimit the minimum amount of output tokens for exact input swaps, the maximum amount of input tokens for exact output swaps /// @param zeroForOne the direction of the swap, true if currency0 is being swapped for currency1 /// @param poolKey the pool to swap through /// @param hookData the data to be passed to the hook /// @param receiver the address to send the output tokens to /// @param deadline block.timestamp must be before this value, otherwise the transaction will revert /// @return Delta the balance changes from the swap function swap( int256 amountSpecified, uint256 amountLimit, bool zeroForOne, PoolKey calldata poolKey, bytes calldata hookData, address receiver, uint256 deadline ) external payable returns (BalanceDelta); /// ================ OPTIMIZED ================ /// /// @notice Generic multi-pool swap function that accepts pre-encoded calldata /// @dev Minor optimization to reduce the number of onchain abi.encode calls /// @param data Pre-encoded swap data in one of the following formats: /// 1. For single-pool swaps: abi.encode( /// BaseData baseData, // struct containing swap parameters /// bool zeroForOne, // direction of swap /// PoolKey poolKey, // key of the pool to swap through /// bytes hookData // data to pass to hooks /// ) /// 2. For multi-pool swaps: abi.encode( /// BaseData baseData, // struct containing swap parameters /// Currency startCurrency, // initial currency in the swap /// PathKey[] path // array of path keys defining the route /// ) /// /// PERMIT2 EXTENSION: /// 1. For single pool swaps: abi.encode( /// BaseData baseData, // struct containing swap parameters /// bool zeroForOne, // direction of swap /// PoolKey poolKey, // key of the pool to swap through /// bytes hookData, // data to pass to hooks /// PermitPayload permitPayload // permit2 signature payload /// ) /// 2. For multi-pool swaps: abi.encode( /// BaseData baseData, // struct containing swap parameters /// Currency startCurrency, // initial currency in the swap /// PathKey[] path, // array of path keys defining the route /// PermitPayload permitPayload // permit2 signature payload /// ) /// Where BaseData.flags contains permit2 flag, and PermitPayload contains: /// - permit: ISignatureTransfer.PermitTransferFrom /// - signature: bytes /// /// @param deadline block.timestamp must be before this value, otherwise the transaction will revert /// @return Delta the balance changes from the swap function swap(bytes calldata data, uint256 deadline) external payable returns (BalanceDelta); /// @notice Provides calldata compression fallback fallback() external payable; /// @notice Provides ETH receipts locked to Pool Manager receive() external payable; /// ================ GETTERS ================ /// /// @notice Public view function to be used instead of msg.sender, as the contract performs self-reentrancy and at /// times msg.sender == address(this). Instead msgSender() returns the initiator of the lock function msgSender() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Currency} from "../types/Currency.sol"; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "./IHooks.sol"; import {IERC6909Claims} from "./external/IERC6909Claims.sol"; import {IProtocolFees} from "./IProtocolFees.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; import {PoolId} from "../types/PoolId.sol"; import {IExtsload} from "./IExtsload.sol"; import {IExttload} from "./IExttload.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; /// @notice Interface for the PoolManager interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload { /// @notice Thrown when a currency is not netted out after the contract is unlocked error CurrencyNotSettled(); /// @notice Thrown when trying to interact with a non-initialized pool error PoolNotInitialized(); /// @notice Thrown when unlock is called, but the contract is already unlocked error AlreadyUnlocked(); /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not error ManagerLocked(); /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow error TickSpacingTooLarge(int24 tickSpacing); /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize error TickSpacingTooSmall(int24 tickSpacing); /// @notice PoolKey must have currencies where address(currency0) < address(currency1) error CurrenciesOutOfOrderOrEqual(address currency0, address currency1); /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook, /// or on a pool that does not have a dynamic swap fee. error UnauthorizedDynamicLPFeeUpdate(); /// @notice Thrown when trying to swap amount of 0 error SwapAmountCannotBeZero(); ///@notice Thrown when native currency is passed to a non native settlement error NonzeroNativeValue(); /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta. error MustClearExactPositiveDelta(); /// @notice Emitted when a new pool is initialized /// @param id The abi encoded hash of the pool key struct for the new pool /// @param currency0 The first currency of the pool by address sort order /// @param currency1 The second currency of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param hooks The hooks contract address for the pool, or address(0) if none /// @param sqrtPriceX96 The price of the pool on initialization /// @param tick The initial tick of the pool corresponding to the initialized price event Initialize( PoolId indexed id, Currency indexed currency0, Currency indexed currency1, uint24 fee, int24 tickSpacing, IHooks hooks, uint160 sqrtPriceX96, int24 tick ); /// @notice Emitted when a liquidity position is modified /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that modified the pool /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param liquidityDelta The amount of liquidity that was added or removed /// @param salt The extra data to make positions unique event ModifyLiquidity( PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt ); /// @notice Emitted for swaps between currency0 and currency1 /// @param id The abi encoded hash of the pool key struct for the pool that was modified /// @param sender The address that initiated the swap call, and that received the callback /// @param amount0 The delta of the currency0 balance of the pool /// @param amount1 The delta of the currency1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of the price of the pool after the swap /// @param fee The swap fee in hundredths of a bip event Swap( PoolId indexed id, address indexed sender, int128 amount0, int128 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick, uint24 fee ); /// @notice Emitted for donations /// @param id The abi encoded hash of the pool key struct for the pool that was donated to /// @param sender The address that initiated the donate call /// @param amount0 The amount donated in currency0 /// @param amount1 The amount donated in currency1 event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1); /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract. /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee` /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)` /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)` function unlock(bytes calldata data) external returns (bytes memory); /// @notice Initialize the state for a given pool ID /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee /// @param key The pool key for the pool to initialize /// @param sqrtPriceX96 The initial square root price /// @return tick The initial tick of the pool function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick); /// @notice Modify the liquidity for the given pool /// @dev Poke by calling with a zero liquidityDelta /// @param key The pool to modify liquidity in /// @param params The parameters for modifying the liquidity /// @param hookData The data to pass through to the add/removeLiquidity hooks /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued) /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData) external returns (BalanceDelta callerDelta, BalanceDelta feesAccrued); /// @notice Swap against the given pool /// @param key The pool to swap in /// @param params The parameters for swapping /// @param hookData The data to pass through to the swap hooks /// @return swapDelta The balance delta of the address swapping /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified. /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta. function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (BalanceDelta swapDelta); /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds. /// Donors should keep this in mind when designing donation mechanisms. /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)). /// Read the comments in `Pool.swap()` for more information about this. /// @param key The key of the pool to donate to /// @param amount0 The amount of currency0 to donate /// @param amount1 The amount of currency1 to donate /// @param hookData The data to pass through to the donate hooks /// @return BalanceDelta The delta of the caller after the donate function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) external returns (BalanceDelta); /// @notice Writes the current ERC20 balance of the specified currency to transient storage /// This is used to checkpoint balances for the manager and derive deltas for the caller. /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped /// for native tokens because the amount to settle is determined by the sent value. /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle /// native funds, this function can be called with the native currency to then be able to settle the native currency function sync(Currency currency) external; /// @notice Called by the user to net out some value owed to the user /// @dev Will revert if the requested amount is not available, consider using `mint` instead /// @dev Can also be used as a mechanism for free flash loans /// @param currency The currency to withdraw from the pool manager /// @param to The address to withdraw to /// @param amount The amount of currency to withdraw function take(Currency currency, address to, uint256 amount) external; /// @notice Called by the user to pay what is owed /// @return paid The amount of currency settled function settle() external payable returns (uint256 paid); /// @notice Called by the user to pay on behalf of another address /// @param recipient The address to credit for the payment /// @return paid The amount of currency settled function settleFor(address recipient) external payable returns (uint256 paid); /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently. /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer. /// @dev This could be used to clear a balance that is considered dust. /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared. function clear(Currency currency, uint256 amount) external; /// @notice Called by the user to move value into ERC6909 balance /// @param to The address to mint the tokens to /// @param id The currency address to mint to ERC6909s, as a uint256 /// @param amount The amount of currency to mint /// @dev The id is converted to a uint160 to correspond to a currency address /// If the upper 12 bytes are not 0, they will be 0-ed out function mint(address to, uint256 id, uint256 amount) external; /// @notice Called by the user to move value from ERC6909 balance /// @param from The address to burn the tokens from /// @param id The currency address to burn from ERC6909s, as a uint256 /// @param amount The amount of currency to burn /// @dev The id is converted to a uint160 to correspond to a currency address /// If the upper 12 bytes are not 0, they will be 0-ed out function burn(address from, uint256 id, uint256 amount) external; /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees. /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee /// @param key The key of the pool to update dynamic LP fees for /// @param newDynamicLPFee The new dynamic pool LP fee function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.7.5; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol"; import {IUniswapV4Router04} from "v4-router/interfaces/IUniswapV4Router04.sol"; /// @title Interfaces - Core interfaces for the strategy ecosystem /// @author TokenWorks (https://token.works/) /// @notice This file contains all the interfaces used by the strategy contracts /// @notice Interface for Universal Router (legacy, kept for compatibility) interface IUniversalRouter { /// @notice Thrown when a required command has failed error ExecutionFailed(uint256 commandIndex, bytes message); /// @notice Thrown when attempting to send ETH directly to the contract error ETHNotAccepted(); /// @notice Thrown when executing commands with an expired deadline error TransactionDeadlinePassed(); /// @notice Thrown when attempting to execute commands and an incorrect number of inputs are provided error LengthMismatch(); // @notice Thrown when an address that isn't WETH tries to send ETH to the router without calldata error InvalidEthSender(); /// @notice Executes encoded commands along with provided inputs. Reverts if deadline has expired. /// @param commands A set of concatenated commands, each 1 byte in length /// @param inputs An array of byte strings containing abi encoded inputs for each command /// @param deadline The deadline by which the transaction must be executed function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable; } /// @notice Parameters for exact input single swaps (legacy, kept for compatibility) struct ExactInputSingleParams { PoolKey poolKey; bool zeroForOne; uint128 amountIn; uint128 amountOutMinimum; bytes hookData; } /// @notice Interface for PunkStrategy contracts /// @dev Interface for the original PunkStrategy token contract interface IPunkStrategy { // View functions function loadingLiquidity() external view returns (bool); function owner() external view returns (address); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function hookAddress() external view returns (address); function currentFees() external view returns (uint256); function reward() external view returns (uint256); function lastPunkSalePrice() external view returns (uint256); function priceMultiplier() external view returns (uint256); function canProcessPunkSale() external view returns (bool); // Admin functions function loadLiquidity(address _hook) external payable; function transferEther(address _to, uint256 _amount) external payable; function setReward(uint256 _newReward) external; function setPriceMultiplier(uint256 _newMultiplier) external; function transferOwnership(address newOwner) external; // Mechanism functions function addFees() external payable; function buyPunkAndRelist(uint256 punkId) external returns (uint256); function processPunkSale() external returns (uint256); // Constants function MAX_SUPPLY() external pure returns (uint256); function DEADADDRESS() external pure returns (address); } /// @notice Interface for PunkStrategyHook contracts interface IPunkStrategyHook { // View functions function feeBips() external view returns (uint128); function prePunkSellBips() external view returns (uint128); function feeSplit() external view returns (IFeeSplit); function calculateFee(bool isBuying) external view returns (uint128); function getHookPermissions() external pure returns (Hooks.Permissions memory); // Admin functions function transferToken(address _token, address _to, uint256 _amount) external payable; function updateFeeBips(uint128 _feeBips) external; function updateManualFees(bool _manuallyProcessFees) external; function updateFeeSplit(IFeeSplit _feeSplit) external; // Mechanism functions function feeCooldown() external; function punksAreAccumulating() external; function processAccumulatedFees() external; } /// @notice Interface for fee splitting contracts interface IFeeSplit { function processDeposit() external payable; } /// @notice Offer struct for CryptoPunks marketplace struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; address onlySellTo; } /// @notice Interface for CryptoPunks contract /// @dev Interface for interacting with the original CryptoPunks contract interface IPunks { function buyPunk(uint256 punkIndex) external payable; function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) external; function punksOfferedForSale(uint256 punkId) external view returns (bool isForSale, uint256 punkIndex, address seller, uint256 minValue, address onlySellTo); function balanceOf(address owner) external view returns (uint256); function punkIndexToAddress(uint256 punkIndex) external view returns (address); function withdraw() external; function pendingWithdrawals(address owner) external view returns (uint256); function transferPunk(address to, uint256 punkIndex) external; } /// @notice Interface for ERC20 tokens (standard interface) interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 amount) external returns (bool); } /// @notice Interface for ERC721 NFT collections /// @dev Standard ERC721 interface with additional owner() function for collection ownership interface IERC721 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function setApprovalForAll(address operator, bool approved) external; function getApproved(uint256 tokenId) external view returns (address operator); function isApprovedForAll(address owner, address operator) external view returns (bool); function supportsInterface(bytes4 interfaceId) external view returns (bool); function owner() external view returns (address); } /// @notice Interface for NFTStrategy contracts /// @dev Core interface for NFT-backed ERC20 strategy tokens interface INFTStrategy { function initialize( address _collection, address _hook, string memory _tokenName, string memory _tokenSymbol, uint256 _buyIncrement, address _owner ) external; function factory() external view returns (address); function router() external view returns (address); function poolManager() external view returns (address); function owner() external view returns (address); function addFees() external payable; function setPriceMultiplier(uint256 _newMultiplier) external; function updateName(string memory _tokenName) external; function updateSymbol(string memory _tokenSymbol) external; function updateHookAddress(address _hookAddress) external; function nftForSale(uint256 tokenId) external view returns (uint256); function sellTargetNFT(uint256 tokenId) external payable; function increaseTransferAllowance(uint256 amountAllowed) external; function getTransferAllowance() external view returns (uint256); function getImplementation() external view returns (address); function upgradeToAndCall(address newImplementation, bytes memory data) external; } /// @notice Interface for NFTStrategyFactory contracts /// @dev Factory interface for deploying and managing NFTStrategy contracts interface INFTStrategyFactory { function loadingLiquidity() external view returns (bool); function owner() external view returns (address); function nftStrategyImplementation() external view returns (address); function collectionToNFTStrategy(address collection) external view returns (address); function nftStrategyToCollection(address collection) external view returns (address); function setNftStrategyImplementation(address _nftStrategyImplementation) external returns (address); function updateHookAddress(address _hookAddress) external returns (address); function ownerLaunchNFTStrategy( address collection, string memory tokenName, string memory tokenSymbol, address collectionOwner, uint256 buyIncrement ) external payable returns (address); function disableLaunchUpgradeable() external; } /// @notice Interface for NFTStrategyHook contracts /// @dev Hook interface for fee management and distribution interface INFTStrategyHook { function adminUpdateFeeAddress(address collection, address destination) external; } /// @notice Interface for NFTStrategyRange contracts interface INFTStrategyRange { function addFees() external payable; function setPriceMultiplier(uint256 _newMultiplier) external; function updateName(string memory _tokenName) external; function updateSymbol(string memory _tokenSymbol) external; function nftForSale(uint256 tokenId) external view returns (uint256); function midSwap() external view returns (bool); function setMidSwap(bool value) external; function sellTargetNFT(uint256 tokenId) external payable; function increaseTransferAllowance(uint256 amountAllowed) external; function getTransferAllowance() external view returns (uint256); } /// @notice Interface for NFTStrategyRangeFactory contracts interface INFTStrategyRangeFactory { function poolManager() external view returns (address); function loadingLiquidity() external view returns (bool); function deployerBuying() external view returns (bool); function owner() external view returns (address); function setRouter(address _router, bool status) external; function collectionToNFTStrategy(address collection) external view returns (address); function nftStrategyToCollection(address collection) external view returns (address); function routerRestrict() external view returns (bool); function setRouterRestrict(bool status) external; function validTransfer(address to, address from, address tokenAddress) external view returns (bool); } /// @notice Interface for NFTStrategyRangeHook contracts interface INFTStrategyRangeHook { function adminUpdateFeeAddress(address collection, address destination) external; } /// @notice Interface for router validation interface IValidRouter { function msgSender() external view returns (address); } /// @notice Interface for PunkStrategyPatch contracts /// @dev Interface for patch contracts that manage PunkStrategy operations interface IPunkStrategyPatch { function updateFeeBips(uint128 _feeBips) external; function setPriceMultiplier(uint256 _newMultiplier) external; function transferOwnership(address newOwner) external; function transferEther(address _to, uint256 _amount) external payable; function setReward(uint256 _newReward) external; function setTwapIncrement(uint256 _newIncrement) external; function setTwapDelayInBlocks(uint256 _newDelay) external; function buyPunkAndRelist(uint256 punkId) external returns (uint256); function processPunkSale() external returns (uint256); function processTokenTwap() external; function transferPunkStrategyOwnership(address newOwner) external; function addFees() external payable; function transferToken(address _token, address _to, uint256 _amount) external payable; function updateManualFees(bool _manuallyProcessFees) external; function updateFeeSplit(IFeeSplit _feeSplit) external; function owner() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Initializable mixin for the upgradeable contracts. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Initializable.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/proxy/utils/Initializable.sol) abstract contract Initializable { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The contract is already initialized. error InvalidInitialization(); /// @dev The contract is not initializing. error NotInitializing(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Triggered when the contract has been initialized. event Initialized(uint64 version); /// @dev `keccak256(bytes("Initialized(uint64)"))`. bytes32 private constant _INITIALIZED_EVENT_SIGNATURE = 0xc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The default initializable slot is given by: /// `bytes32(~uint256(uint32(bytes4(keccak256("_INITIALIZABLE_SLOT")))))`. /// /// Bits Layout: /// - [0] `initializing` /// - [1..64] `initializedVersion` bytes32 private constant _INITIALIZABLE_SLOT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffbf601132; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTRUCTOR */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ constructor() { // Construction time check to ensure that `_initializableSlot()` is not // overridden to zero. Will be optimized away if there is no revert. require(_initializableSlot() != bytes32(0)); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Override to return a non-zero custom storage slot if required. function _initializableSlot() internal pure virtual returns (bytes32) { return _INITIALIZABLE_SLOT; } /// @dev Guards an initializer function so that it can be invoked at most once. /// /// You can guard a function with `onlyInitializing` such that it can be called /// through a function guarded with `initializer`. /// /// This is similar to `reinitializer(1)`, except that in the context of a constructor, /// an `initializer` guarded function can be invoked multiple times. /// This can be useful during testing and is not expected to be used in production. /// /// Emits an {Initialized} event. modifier initializer() virtual { bytes32 s = _initializableSlot(); /// @solidity memory-safe-assembly assembly { let i := sload(s) // Set `initializing` to 1, `initializedVersion` to 1. sstore(s, 3) // If `!(initializing == 0 && initializedVersion == 0)`. if i { // If `!(address(this).code.length == 0 && initializedVersion == 1)`. if iszero(lt(extcodesize(address()), eq(shr(1, i), 1))) { mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`. revert(0x1c, 0x04) } s := shl(shl(255, i), s) // Skip initializing if `initializing == 1`. } } _; /// @solidity memory-safe-assembly assembly { if s { // Set `initializing` to 0, `initializedVersion` to 1. sstore(s, 2) // Emit the {Initialized} event. mstore(0x20, 1) log1(0x20, 0x20, _INITIALIZED_EVENT_SIGNATURE) } } } /// @dev Guards a reinitializer function so that it can be invoked at most once. /// /// You can guard a function with `onlyInitializing` such that it can be called /// through a function guarded with `reinitializer`. /// /// Emits an {Initialized} event. modifier reinitializer(uint64 version) virtual { bytes32 s = _initializableSlot(); /// @solidity memory-safe-assembly assembly { // Clean upper bits, and shift left by 1 to make space for the initializing bit. version := shl(1, and(version, 0xffffffffffffffff)) let i := sload(s) // If `initializing == 1 || initializedVersion >= version`. if iszero(lt(and(i, 1), lt(i, version))) { mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`. revert(0x1c, 0x04) } // Set `initializing` to 1, `initializedVersion` to `version`. sstore(s, or(1, version)) } _; /// @solidity memory-safe-assembly assembly { // Set `initializing` to 0, `initializedVersion` to `version`. sstore(s, version) // Emit the {Initialized} event. mstore(0x20, shr(1, version)) log1(0x20, 0x20, _INITIALIZED_EVENT_SIGNATURE) } } /// @dev Guards a function such that it can only be called in the scope /// of a function guarded with `initializer` or `reinitializer`. modifier onlyInitializing() virtual { _checkInitializing(); _; } /// @dev Reverts if the contract is not initializing. function _checkInitializing() internal view virtual { bytes32 s = _initializableSlot(); /// @solidity memory-safe-assembly assembly { if iszero(and(1, sload(s))) { mstore(0x00, 0xd7e6bcf8) // `NotInitializing()`. revert(0x1c, 0x04) } } } /// @dev Locks any future initializations by setting the initialized version to `2**64 - 1`. /// /// Calling this in the constructor will prevent the contract from being initialized /// or reinitialized. It is recommended to use this to lock implementation contracts /// that are designed to be called through proxies. /// /// Emits an {Initialized} event the first time it is successfully called. function _disableInitializers() internal virtual { bytes32 s = _initializableSlot(); /// @solidity memory-safe-assembly assembly { let i := sload(s) if and(i, 1) { mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`. revert(0x1c, 0x04) } let uint64max := 0xffffffffffffffff if iszero(eq(shr(1, i), uint64max)) { // Set `initializing` to 0, `initializedVersion` to `2**64 - 1`. sstore(s, shl(1, uint64max)) // Emit the {Initialized} event. mstore(0x20, uint64max) log1(0x20, 0x20, _INITIALIZED_EVENT_SIGNATURE) } } } /// @dev Returns the highest version that has been initialized. function _getInitializedVersion() internal view virtual returns (uint64 version) { bytes32 s = _initializableSlot(); /// @solidity memory-safe-assembly assembly { version := shr(1, sload(s)) } } /// @dev Returns whether the contract is currently initializing. function _isInitializing() internal view virtual returns (bool result) { bytes32 s = _initializableSlot(); /// @solidity memory-safe-assembly assembly { result := and(1, sload(s)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import {CallContextChecker} from "./CallContextChecker.sol"; /// @notice UUPS proxy mixin. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/UUPSUpgradeable.sol) /// @author Modified from OpenZeppelin /// (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/utils/UUPSUpgradeable.sol) /// /// @dev Note: /// - This implementation is intended to be used with ERC1967 proxies. /// See: `LibClone.deployERC1967` and related functions. /// - This implementation is NOT compatible with legacy OpenZeppelin proxies /// which do not store the implementation at `_ERC1967_IMPLEMENTATION_SLOT`. abstract contract UUPSUpgradeable is CallContextChecker { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The upgrade failed. error UpgradeFailed(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Emitted when the proxy's implementation is upgraded. event Upgraded(address indexed implementation); /// @dev `keccak256(bytes("Upgraded(address)"))`. uint256 private constant _UPGRADED_EVENT_SIGNATURE = 0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The ERC-1967 storage slot for the implementation in the proxy. /// `uint256(keccak256("eip1967.proxy.implementation")) - 1`. bytes32 internal constant _ERC1967_IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* UUPS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Please override this function to check if `msg.sender` is authorized /// to upgrade the proxy to `newImplementation`, reverting if not. /// ``` /// function _authorizeUpgrade(address) internal override onlyOwner {} /// ``` function _authorizeUpgrade(address newImplementation) internal virtual; /// @dev Returns the storage slot used by the implementation, /// as specified in [ERC1822](https://eips.ethereum.org/EIPS/eip-1822). /// /// Note: The `notDelegated` modifier prevents accidental upgrades to /// an implementation that is a proxy contract. function proxiableUUID() public view virtual notDelegated returns (bytes32) { // This function must always return `_ERC1967_IMPLEMENTATION_SLOT` to comply with ERC1967. return _ERC1967_IMPLEMENTATION_SLOT; } /// @dev Upgrades the proxy's implementation to `newImplementation`. /// Emits a {Upgraded} event. /// /// Note: Passing in empty `data` skips the delegatecall to `newImplementation`. function upgradeToAndCall(address newImplementation, bytes calldata data) public payable virtual onlyProxy { _authorizeUpgrade(newImplementation); /// @solidity memory-safe-assembly assembly { newImplementation := shr(96, shl(96, newImplementation)) // Clears upper 96 bits. mstore(0x00, returndatasize()) mstore(0x01, 0x52d1902d) // `proxiableUUID()`. let s := _ERC1967_IMPLEMENTATION_SLOT // Check if `newImplementation` implements `proxiableUUID` correctly. if iszero(eq(mload(staticcall(gas(), newImplementation, 0x1d, 0x04, 0x01, 0x20)), s)) { mstore(0x01, 0x55299b49) // `UpgradeFailed()`. revert(0x1d, 0x04) } // Emit the {Upgraded} event. log2(codesize(), 0x00, _UPGRADED_EVENT_SIGNATURE, newImplementation) sstore(s, newImplementation) // Updates the implementation. // Perform a delegatecall to `newImplementation` if `data` is non-empty. if data.length { // Forwards the `data` to `newImplementation` via delegatecall. let m := mload(0x40) calldatacopy(m, data.offset, data.length) if iszero(delegatecall(gas(), newImplementation, m, data.length, codesize(), 0x00)) { // Bubble up the revert if the call reverts. returndatacopy(m, 0x00, returndatasize()) revert(m, returndatasize()) } } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Simple single owner authorization mixin. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol) /// /// @dev Note: /// This implementation does NOT auto-initialize the owner to `msg.sender`. /// You MUST call the `_initializeOwner` in the constructor / initializer. /// /// While the ownable portion follows /// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility, /// the nomenclature for the 2-step ownership handover may be unique to this codebase. abstract contract Ownable { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The caller is not authorized to call the function. error Unauthorized(); /// @dev The `newOwner` cannot be the zero address. error NewOwnerIsZeroAddress(); /// @dev The `pendingOwner` does not have a valid handover request. error NoHandoverRequest(); /// @dev Cannot double-initialize. error AlreadyInitialized(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EVENTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The ownership is transferred from `oldOwner` to `newOwner`. /// This event is intentionally kept the same as OpenZeppelin's Ownable to be /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173), /// despite it not being as lightweight as a single argument event. event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); /// @dev An ownership handover to `pendingOwner` has been requested. event OwnershipHandoverRequested(address indexed pendingOwner); /// @dev The ownership handover to `pendingOwner` has been canceled. event OwnershipHandoverCanceled(address indexed pendingOwner); /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`. uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE = 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0; /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`. uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE = 0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d; /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`. uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE = 0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The owner slot is given by: /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`. /// It is intentionally chosen to be a high value /// to avoid collision with lower slots. /// The choice of manual storage layout is to enable compatibility /// with both regular and upgradeable contracts. bytes32 internal constant _OWNER_SLOT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927; /// The ownership handover slot of `newOwner` is given by: /// ``` /// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED)) /// let handoverSlot := keccak256(0x00, 0x20) /// ``` /// It stores the expiry timestamp of the two-step ownership handover. uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* INTERNAL FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Override to return true to make `_initializeOwner` prevent double-initialization. function _guardInitializeOwner() internal pure virtual returns (bool guard) {} /// @dev Initializes the owner directly without authorization guard. /// This function must be called upon initialization, /// regardless of whether the contract is upgradeable or not. /// This is to enable generalization to both regular and upgradeable contracts, /// and to save gas in case the initial owner is not the caller. /// For performance reasons, this function will not check if there /// is an existing owner. function _initializeOwner(address newOwner) internal virtual { if (_guardInitializeOwner()) { /// @solidity memory-safe-assembly assembly { let ownerSlot := _OWNER_SLOT if sload(ownerSlot) { mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`. revert(0x1c, 0x04) } // Clean the upper 96 bits. newOwner := shr(96, shl(96, newOwner)) // Store the new value. sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner)))) // Emit the {OwnershipTransferred} event. log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner) } } else { /// @solidity memory-safe-assembly assembly { // Clean the upper 96 bits. newOwner := shr(96, shl(96, newOwner)) // Store the new value. sstore(_OWNER_SLOT, newOwner) // Emit the {OwnershipTransferred} event. log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner) } } } /// @dev Sets the owner directly without authorization guard. function _setOwner(address newOwner) internal virtual { if (_guardInitializeOwner()) { /// @solidity memory-safe-assembly assembly { let ownerSlot := _OWNER_SLOT // Clean the upper 96 bits. newOwner := shr(96, shl(96, newOwner)) // Emit the {OwnershipTransferred} event. log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner) // Store the new value. sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner)))) } } else { /// @solidity memory-safe-assembly assembly { let ownerSlot := _OWNER_SLOT // Clean the upper 96 bits. newOwner := shr(96, shl(96, newOwner)) // Emit the {OwnershipTransferred} event. log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner) // Store the new value. sstore(ownerSlot, newOwner) } } } /// @dev Throws if the sender is not the owner. function _checkOwner() internal view virtual { /// @solidity memory-safe-assembly assembly { // If the caller is not the stored owner, revert. if iszero(eq(caller(), sload(_OWNER_SLOT))) { mstore(0x00, 0x82b42900) // `Unauthorized()`. revert(0x1c, 0x04) } } } /// @dev Returns how long a two-step ownership handover is valid for in seconds. /// Override to return a different value if needed. /// Made internal to conserve bytecode. Wrap it in a public function if needed. function _ownershipHandoverValidFor() internal view virtual returns (uint64) { return 48 * 3600; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* PUBLIC UPDATE FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Allows the owner to transfer the ownership to `newOwner`. function transferOwnership(address newOwner) public payable virtual onlyOwner { /// @solidity memory-safe-assembly assembly { if iszero(shl(96, newOwner)) { mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`. revert(0x1c, 0x04) } } _setOwner(newOwner); } /// @dev Allows the owner to renounce their ownership. function renounceOwnership() public payable virtual onlyOwner { _setOwner(address(0)); } /// @dev Request a two-step ownership handover to the caller. /// The request will automatically expire in 48 hours (172800 seconds) by default. function requestOwnershipHandover() public payable virtual { unchecked { uint256 expires = block.timestamp + _ownershipHandoverValidFor(); /// @solidity memory-safe-assembly assembly { // Compute and set the handover slot to `expires`. mstore(0x0c, _HANDOVER_SLOT_SEED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x20), expires) // Emit the {OwnershipHandoverRequested} event. log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller()) } } } /// @dev Cancels the two-step ownership handover to the caller, if any. function cancelOwnershipHandover() public payable virtual { /// @solidity memory-safe-assembly assembly { // Compute and set the handover slot to 0. mstore(0x0c, _HANDOVER_SLOT_SEED) mstore(0x00, caller()) sstore(keccak256(0x0c, 0x20), 0) // Emit the {OwnershipHandoverCanceled} event. log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller()) } } /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`. /// Reverts if there is no existing ownership handover requested by `pendingOwner`. function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner { /// @solidity memory-safe-assembly assembly { // Compute and set the handover slot to 0. mstore(0x0c, _HANDOVER_SLOT_SEED) mstore(0x00, pendingOwner) let handoverSlot := keccak256(0x0c, 0x20) // If the handover does not exist, or has expired. if gt(timestamp(), sload(handoverSlot)) { mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`. revert(0x1c, 0x04) } // Set the handover slot to 0. sstore(handoverSlot, 0) } _setOwner(pendingOwner); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* PUBLIC READ FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the owner of the contract. function owner() public view virtual returns (address result) { /// @solidity memory-safe-assembly assembly { result := sload(_OWNER_SLOT) } } /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`. function ownershipHandoverExpiresAt(address pendingOwner) public view virtual returns (uint256 result) { /// @solidity memory-safe-assembly assembly { // Compute the handover slot. mstore(0x0c, _HANDOVER_SLOT_SEED) mstore(0x00, pendingOwner) // Load the handover slot. result := sload(keccak256(0x0c, 0x20)) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MODIFIERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Marks a function as only callable by the owner. modifier onlyOwner() virtual { _checkOwner(); _; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Minimal proxy library. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibClone.sol) /// @author Minimal proxy by 0age (https://github.com/0age) /// @author Clones with immutable args by wighawag, zefram.eth, Saw-mon & Natalie /// (https://github.com/Saw-mon-and-Natalie/clones-with-immutable-args) /// @author Minimal ERC1967 proxy by jtriley-eth (https://github.com/jtriley-eth/minimum-viable-proxy) /// /// @dev Minimal proxy: /// Although the sw0nt pattern saves 5 gas over the ERC1167 pattern during runtime, /// it is not supported out-of-the-box on Etherscan. Hence, we choose to use the 0age pattern, /// which saves 4 gas over the ERC1167 pattern during runtime, and has the smallest bytecode. /// - Automatically verified on Etherscan. /// /// @dev Minimal proxy (PUSH0 variant): /// This is a new minimal proxy that uses the PUSH0 opcode introduced during Shanghai. /// It is optimized first for minimal runtime gas, then for minimal bytecode. /// The PUSH0 clone functions are intentionally postfixed with a jarring "_PUSH0" as /// many EVM chains may not support the PUSH0 opcode in the early months after Shanghai. /// Please use with caution. /// - Automatically verified on Etherscan. /// /// @dev Clones with immutable args (CWIA): /// The implementation of CWIA here does NOT append the immutable args into the calldata /// passed into delegatecall. It is simply an ERC1167 minimal proxy with the immutable arguments /// appended to the back of the runtime bytecode. /// - Uses the identity precompile (0x4) to copy args during deployment. /// /// @dev Minimal ERC1967 proxy: /// A minimal ERC1967 proxy, intended to be upgraded with UUPS. /// This is NOT the same as ERC1967Factory's transparent proxy, which includes admin logic. /// - Automatically verified on Etherscan. /// /// @dev Minimal ERC1967 proxy with immutable args: /// - Uses the identity precompile (0x4) to copy args during deployment. /// - Automatically verified on Etherscan. /// /// @dev ERC1967I proxy: /// A variant of the minimal ERC1967 proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// `implementation` address. The returned implementation is guaranteed to be valid if the /// keccak256 of the proxy's code is equal to `ERC1967I_CODE_HASH`. /// /// @dev ERC1967I proxy with immutable args: /// A variant of the minimal ERC1967 proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// - Uses the identity precompile (0x4) to copy args during deployment. /// /// @dev Minimal ERC1967 beacon proxy: /// A minimal beacon proxy, intended to be upgraded with an upgradable beacon. /// - Automatically verified on Etherscan. /// /// @dev Minimal ERC1967 beacon proxy with immutable args: /// - Uses the identity precompile (0x4) to copy args during deployment. /// - Automatically verified on Etherscan. /// /// @dev ERC1967I beacon proxy: /// A variant of the minimal ERC1967 beacon proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// `implementation` address. The returned implementation is guaranteed to be valid if the /// keccak256 of the proxy's code is equal to `ERC1967I_CODE_HASH`. /// /// @dev ERC1967I proxy with immutable args: /// A variant of the minimal ERC1967 beacon proxy, with a special code path that activates /// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the /// - Uses the identity precompile (0x4) to copy args during deployment. library LibClone { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The keccak256 of deployed code for the clone proxy, /// with the implementation set to `address(0)`. bytes32 internal constant CLONE_CODE_HASH = 0x48db2cfdb2853fce0b464f1f93a1996469459df3ab6c812106074c4106a1eb1f; /// @dev The keccak256 of deployed code for the PUSH0 proxy, /// with the implementation set to `address(0)`. bytes32 internal constant PUSH0_CLONE_CODE_HASH = 0x67bc6bde1b84d66e267c718ba44cf3928a615d29885537955cb43d44b3e789dc; /// @dev The keccak256 of deployed code for the ERC-1167 CWIA proxy, /// with the implementation set to `address(0)`. bytes32 internal constant CWIA_CODE_HASH = 0x3cf92464268225a4513da40a34d967354684c32cd0edd67b5f668dfe3550e940; /// @dev The keccak256 of the deployed code for the ERC1967 proxy. bytes32 internal constant ERC1967_CODE_HASH = 0xaaa52c8cc8a0e3fd27ce756cc6b4e70c51423e9b597b11f32d3e49f8b1fc890d; /// @dev The keccak256 of the deployed code for the ERC1967I proxy. bytes32 internal constant ERC1967I_CODE_HASH = 0xce700223c0d4cea4583409accfc45adac4a093b3519998a9cbbe1504dadba6f7; /// @dev The keccak256 of the deployed code for the ERC1967 beacon proxy. bytes32 internal constant ERC1967_BEACON_PROXY_CODE_HASH = 0x14044459af17bc4f0f5aa2f658cb692add77d1302c29fe2aebab005eea9d1162; /// @dev The keccak256 of the deployed code for the ERC1967 beacon proxy. bytes32 internal constant ERC1967I_BEACON_PROXY_CODE_HASH = 0xf8c46d2793d5aa984eb827aeaba4b63aedcab80119212fce827309788735519a; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Unable to deploy the clone. error DeploymentFailed(); /// @dev The salt must start with either the zero address or `by`. error SaltDoesNotStartWith(); /// @dev The ETH transfer has failed. error ETHTransferFailed(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a clone of `implementation`. function clone(address implementation) internal returns (address instance) { instance = clone(0, implementation); } /// @dev Deploys a clone of `implementation`. /// Deposits `value` ETH during deployment. function clone(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * --------------------------------------------------------------------------+ * CREATION (9 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * --------------------------------------------------------------------------| * RUNTIME (44 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * | * ::: keep some values in stack ::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 3d | RETURNDATASIZE | 0 0 0 | | * 3d | RETURNDATASIZE | 0 0 0 0 | | * | * ::: copy calldata to memory ::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 0 0 | | * 3d | RETURNDATASIZE | 0 cds 0 0 0 0 | | * 3d | RETURNDATASIZE | 0 0 cds 0 0 0 0 | | * 37 | CALLDATACOPY | 0 0 0 0 | [0..cds): calldata | * | * ::: delegate call to the implementation contract :::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 0 0 | [0..cds): calldata | * 73 addr | PUSH20 addr | addr 0 cds 0 0 0 0 | [0..cds): calldata | * 5a | GAS | gas addr 0 cds 0 0 0 0 | [0..cds): calldata | * f4 | DELEGATECALL | success 0 0 | [0..cds): calldata | * | * ::: copy return data to memory :::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds success 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | rds rds success 0 0 | [0..cds): calldata | * 93 | SWAP4 | 0 rds success 0 rds | [0..cds): calldata | * 80 | DUP1 | 0 0 rds success 0 rds | [0..cds): calldata | * 3e | RETURNDATACOPY | success 0 rds | [0..rds): returndata | * | * 60 0x2a | PUSH1 0x2a | 0x2a success 0 rds | [0..rds): returndata | * 57 | JUMPI | 0 rds | [0..rds): returndata | * | * ::: revert :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * fd | REVERT | | [0..rds): returndata | * | * ::: return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | 0 rds | [0..rds): returndata | * f3 | RETURN | | [0..rds): returndata | * --------------------------------------------------------------------------+ */ mstore(0x21, 0x5af43d3d93803e602a57fd5bf3) mstore(0x14, implementation) mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) instance := create(value, 0x0c, 0x35) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Deploys a deterministic clone of `implementation` with `salt`. function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { instance = cloneDeterministic(0, implementation, salt); } /// @dev Deploys a deterministic clone of `implementation` with `salt`. /// Deposits `value` ETH during deployment. function cloneDeterministic(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { mstore(0x21, 0x5af43d3d93803e602a57fd5bf3) mstore(0x14, implementation) mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) instance := create2(value, 0x0c, 0x35, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the clone of `implementation`. function initCode(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x40), 0x5af43d3d93803e602a57fd5bf30000000000000000000000) mstore(add(c, 0x28), implementation) mstore(add(c, 0x14), 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) mstore(c, 0x35) // Store the length. mstore(0x40, add(c, 0x60)) // Allocate memory. } } /// @dev Returns the initialization code hash of the clone of `implementation`. function initCodeHash(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { mstore(0x21, 0x5af43d3d93803e602a57fd5bf3) mstore(0x14, implementation) mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73) hash := keccak256(0x0c, 0x35) mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the address of the clone of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) { bytes32 hash = initCodeHash(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL PROXY OPERATIONS (PUSH0 VARIANT) */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a PUSH0 clone of `implementation`. function clone_PUSH0(address implementation) internal returns (address instance) { instance = clone_PUSH0(0, implementation); } /// @dev Deploys a PUSH0 clone of `implementation`. /// Deposits `value` ETH during deployment. function clone_PUSH0(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * --------------------------------------------------------------------------+ * CREATION (9 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 5f | PUSH0 | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 5f | PUSH0 | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * --------------------------------------------------------------------------| * RUNTIME (45 bytes) | * --------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * --------------------------------------------------------------------------| * | * ::: keep some values in stack ::::::::::::::::::::::::::::::::::::::::::: | * 5f | PUSH0 | 0 | | * 5f | PUSH0 | 0 0 | | * | * ::: copy calldata to memory ::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 | | * 5f | PUSH0 | 0 cds 0 0 | | * 5f | PUSH0 | 0 0 cds 0 0 | | * 37 | CALLDATACOPY | 0 0 | [0..cds): calldata | * | * ::: delegate call to the implementation contract :::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds 0 0 | [0..cds): calldata | * 5f | PUSH0 | 0 cds 0 0 | [0..cds): calldata | * 73 addr | PUSH20 addr | addr 0 cds 0 0 | [0..cds): calldata | * 5a | GAS | gas addr 0 cds 0 0 | [0..cds): calldata | * f4 | DELEGATECALL | success | [0..cds): calldata | * | * ::: copy return data to memory :::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds success | [0..cds): calldata | * 5f | PUSH0 | 0 rds success | [0..cds): calldata | * 5f | PUSH0 | 0 0 rds success | [0..cds): calldata | * 3e | RETURNDATACOPY | success | [0..rds): returndata | * | * 60 0x29 | PUSH1 0x29 | 0x29 success | [0..rds): returndata | * 57 | JUMPI | | [0..rds): returndata | * | * ::: revert :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..rds): returndata | * 5f | PUSH0 | 0 rds | [0..rds): returndata | * fd | REVERT | | [0..rds): returndata | * | * ::: return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..rds): returndata | * 3d | RETURNDATASIZE | rds | [0..rds): returndata | * 5f | PUSH0 | 0 rds | [0..rds): returndata | * f3 | RETURN | | [0..rds): returndata | * --------------------------------------------------------------------------+ */ mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16 mstore(0x14, implementation) // 20 mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 instance := create(value, 0x0e, 0x36) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x24, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Deploys a deterministic PUSH0 clone of `implementation` with `salt`. function cloneDeterministic_PUSH0(address implementation, bytes32 salt) internal returns (address instance) { instance = cloneDeterministic_PUSH0(0, implementation, salt); } /// @dev Deploys a deterministic PUSH0 clone of `implementation` with `salt`. /// Deposits `value` ETH during deployment. function cloneDeterministic_PUSH0(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16 mstore(0x14, implementation) // 20 mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 instance := create2(value, 0x0e, 0x36, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x24, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the PUSH0 clone of `implementation`. function initCode_PUSH0(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x40), 0x5af43d5f5f3e6029573d5ffd5b3d5ff300000000000000000000) // 16 mstore(add(c, 0x26), implementation) // 20 mstore(add(c, 0x12), 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 mstore(c, 0x36) // Store the length. mstore(0x40, add(c, 0x60)) // Allocate memory. } } /// @dev Returns the initialization code hash of the PUSH0 clone of `implementation`. function initCodeHash_PUSH0(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16 mstore(0x14, implementation) // 20 mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9 hash := keccak256(0x0e, 0x36) mstore(0x24, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the address of the PUSH0 clone of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress_PUSH0( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHash_PUSH0(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CLONES WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a clone of `implementation` with immutable arguments encoded in `args`. function clone(address implementation, bytes memory args) internal returns (address instance) { instance = clone(0, implementation, args); } /// @dev Deploys a clone of `implementation` with immutable arguments encoded in `args`. /// Deposits `value` ETH during deployment. function clone(uint256 value, address implementation, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------+ * CREATION (10 bytes) | * ---------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------| * 61 runSize | PUSH2 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------| * RUNTIME (45 bytes + extraLength) | * ---------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..cds): calldata | * | * ::: delegate call to the implementation contract ::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 0 0 | [0..cds): calldata | * 36 | CALLDATASIZE | cds 0 0 0 | [0..cds): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 0 0 | [0..cds): calldata | * 73 addr | PUSH20 addr | addr 0 cds 0 0 0 0 | [0..cds): calldata | * 5a | GAS | gas addr 0 cds 0 0 0 0 | [0..cds): calldata | * f4 | DELEGATECALL | success 0 0 | [0..cds): calldata | * | * ::: copy return data to memory ::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds success 0 | [0..cds): calldata | * 82 | DUP3 | 0 rds success 0 | [0..cds): calldata | * 80 | DUP1 | 0 0 rds success 0 | [0..cds): calldata | * 3e | RETURNDATACOPY | success 0 | [0..rds): returndata | * 90 | SWAP1 | 0 success | [0..rds): returndata | * 3d | RETURNDATASIZE | rds 0 success | [0..rds): returndata | * 91 | SWAP2 | success 0 rds | [0..rds): returndata | * | * 60 0x2b | PUSH1 0x2b | 0x2b success 0 rds | [0..rds): returndata | * 57 | JUMPI | 0 rds | [0..rds): returndata | * | * ::: revert ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * fd | REVERT | | [0..rds): returndata | * | * ::: return ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | 0 rds | [0..rds): returndata | * f3 | RETURN | | [0..rds): returndata | * ---------------------------------------------------------------------------+ */ let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n)) mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. instance := create(value, add(m, add(0x0b, lt(n, 0xffd3))), add(n, 0x37)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. function cloneDeterministic(address implementation, bytes memory args, bytes32 salt) internal returns (address instance) { instance = cloneDeterministic(0, implementation, args, salt); } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. function cloneDeterministic( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n)) mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. instance := create2(value, add(m, add(0x0b, lt(n, 0xffd3))), add(n, 0x37), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. /// This method does not revert if the clone has already been deployed. function createDeterministicClone(address implementation, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicClone(0, implementation, args, salt); } /// @dev Deploys a deterministic clone of `implementation` /// with immutable arguments encoded in `args` and `salt`. /// This method does not revert if the clone has already been deployed. function createDeterministicClone( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n)) mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. // forgefmt: disable-next-item mstore(add(m, gt(n, 0xffd2)), add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(add(m, 0x0c), add(n, 0x37))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, add(m, 0x0c), add(n, 0x37), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the clone of `implementation` /// using immutable arguments encoded in `args`. function initCode(address implementation, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffd2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x57), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x37), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(c, 0x28), implementation) mstore(add(c, 0x14), add(0x61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) mstore(c, add(0x37, n)) // Store the length. mstore(add(c, add(n, 0x57)), 0) // Zeroize the slot after the bytes. mstore(0x40, add(c, add(n, 0x77))) // Allocate memory. } } /// @dev Returns the initialization code hash of the clone of `implementation` /// using immutable arguments encoded in `args`. function initCodeHash(address implementation, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffd2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x43), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3) mstore(add(m, 0x14), implementation) mstore(m, add(0x61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n))) hash := keccak256(add(m, 0x0c), add(n, 0x37)) } } /// @dev Returns the address of the clone of /// `implementation` using immutable arguments encoded in `args`, with `salt`, by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress( address implementation, bytes memory data, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHash(implementation, data); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnClone(instance, 0, 2 ** 256 - 1)`. function argsOnClone(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x2d))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x2d, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnClone(instance, start, 2 ** 256 - 1)`. function argsOnClone(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x2d)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x0d), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the clone with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnClone(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x0d), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x2d) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL ERC1967 PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: The ERC1967 proxy here is intended to be upgraded with UUPS. // This is NOT the same as ERC1967Factory's transparent proxy, which includes admin logic. /// @dev Deploys a minimal ERC1967 proxy with `implementation`. function deployERC1967(address implementation) internal returns (address instance) { instance = deployERC1967(0, implementation); } /// @dev Deploys a minimal ERC1967 proxy with `implementation`. /// Deposits `value` ETH during deployment. function deployERC1967(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 impl | PUSH20 impl | impl 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos impl 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot impl 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (61 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * 7f slot | PUSH32 slot | s 0 cds 0 0 | [0..calldatasize): calldata | * 54 | SLOAD | i 0 cds 0 0 | [0..calldatasize): calldata | * 5a | GAS | g i 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 80 | DUP1 | 0 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [0..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x38 | PUSH1 0x38 | dest succ | [0..returndatasize): returndata | * 57 | JUMPI | | [0..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * fd | REVERT | | [0..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * f3 | RETURN | | [0..returndatasize): returndata | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) instance := create(value, 0x21, 0x5f) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation` and `salt`. function deployDeterministicERC1967(address implementation, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967(0, implementation, salt); } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) instance := create2(value, 0x21, 0x5f, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967(address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967(0, implementation, salt); } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967(uint256 value, address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x21, 0x5f)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x21, 0x5f, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the minimal ERC1967 proxy of `implementation`. function initCodeERC1967(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x60), 0x3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f300) mstore(add(c, 0x40), 0x55f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076cc) mstore(add(c, 0x20), or(shl(24, implementation), 0x600951)) mstore(add(c, 0x09), 0x603d3d8160223d3973) mstore(c, 0x5f) // Store the length. mstore(0x40, add(c, 0x80)) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 proxy of `implementation`. function initCodeHashERC1967(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x20, 0x6009) mstore(0x1e, implementation) mstore(0x0a, 0x603d3d8160223d3973) hash := keccak256(0x21, 0x5f) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967 proxy of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL ERC1967 PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a minimal ERC1967 proxy with `implementation` and `args`. function deployERC1967(address implementation, bytes memory args) internal returns (address instance) { instance = deployERC1967(0, implementation, args); } /// @dev Deploys a minimal ERC1967 proxy with `implementation` and `args`. /// Deposits `value` ETH during deployment. function deployERC1967(uint256 value, address implementation, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n)) mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) instance := create(value, m, add(n, 0x60)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. function deployDeterministicERC1967(address implementation, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967(0, implementation, args, salt); } /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n)) mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) instance := create2(value, m, add(n, 0x60), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967(address implementation, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967(0, implementation, args, salt); } /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n)) mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(m, add(n, 0x60))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, m, add(n, 0x60), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the minimal ERC1967 proxy of `implementation` and `args`. function initCodeERC1967(address implementation, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffc2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x80), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x60), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(c, 0x40), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(add(c, 0x20), 0x6009) mstore(add(c, 0x1e), implementation) mstore(add(c, 0x0a), add(0x61003d3d8160233d3973, shl(56, n))) mstore(c, add(n, 0x60)) // Store the length. mstore(add(c, add(n, 0x80)), 0) // Zeroize the slot after the bytes. mstore(0x40, add(c, add(n, 0xa0))) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 proxy of `implementation` and `args`. function initCodeHashERC1967(address implementation, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffc2)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x60), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3) mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076) mstore(0x16, 0x6009) mstore(0x14, implementation) mstore(0x00, add(0x61003d3d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) hash := keccak256(m, add(n, 0x60)) } } /// @dev Returns the address of the ERC1967 proxy of `implementation`, `args`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967( address implementation, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967(implementation, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967(instance, start, 2 ** 256 - 1)`. function argsOnERC1967(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x3d))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x3d, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967(instance, start, 2 ** 256 - 1)`. function argsOnERC1967(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x3d)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x1d), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967 with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x1d), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x3d) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: This proxy has a special code path that activates if `calldatasize() == 1`. // This code path skips the delegatecall and directly returns the `implementation` address. // The returned implementation is guaranteed to be valid if the keccak256 of the // proxy's code is equal to `ERC1967I_CODE_HASH`. /// @dev Deploys a ERC1967I proxy with `implementation`. function deployERC1967I(address implementation) internal returns (address instance) { instance = deployERC1967I(0, implementation); } /// @dev Deploys a ERC1967I proxy with `implementation`. /// Deposits `value` ETH during deployment. function deployERC1967I(uint256 value, address implementation) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 impl | PUSH20 impl | impl 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos impl 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot impl 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (82 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: check calldatasize ::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 58 | PC | 1 cds | | * 14 | EQ | eqs | | * 60 0x43 | PUSH1 0x43 | dest eqs | | * 57 | JUMPI | | | * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * 7f slot | PUSH32 slot | s 0 cds 0 0 | [0..calldatasize): calldata | * 54 | SLOAD | i 0 cds 0 0 | [0..calldatasize): calldata | * 5a | GAS | g i 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 80 | DUP1 | 0 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [0..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x3E | PUSH1 0x3E | dest succ | [0..returndatasize): returndata | * 57 | JUMPI | | [0..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * fd | REVERT | | [0..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * f3 | RETURN | | [0..returndatasize): returndata | * | * ::: implementation , return :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | | * 60 0x20 | PUSH1 0x20 | 32 | | * 60 0x0F | PUSH1 0x0F | o 32 | | * 3d | RETURNDATASIZE | 0 o 32 | | * 39 | CODECOPY | | [0..32): implementation slot | * 3d | RETURNDATASIZE | 0 | [0..32): implementation slot | * 51 | MLOAD | slot | [0..32): implementation slot | * 54 | SLOAD | impl | [0..32): implementation slot | * 3d | RETURNDATASIZE | 0 impl | [0..32): implementation slot | * 52 | MSTORE | | [0..32): implementation address | * 59 | MSIZE | 32 | [0..32): implementation address | * 3d | RETURNDATASIZE | 0 32 | [0..32): implementation address | * f3 | RETURN | | [0..32): implementation address | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) instance := create(value, 0x0c, 0x74) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic ERC1967I proxy with `implementation` and `salt`. function deployDeterministicERC1967I(address implementation, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967I(0, implementation, salt); } /// @dev Deploys a deterministic ERC1967I proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967I(uint256 value, address implementation, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic ERC1967I proxy with `implementation` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I(address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967I(0, implementation, salt); } /// @dev Creates a deterministic ERC1967I proxy with `implementation` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I(uint256 value, address implementation, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x0c, 0x74)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the ERC1967I proxy of `implementation`. function initCodeERC1967I(address implementation) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x74), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(c, 0x54), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(c, 0x34), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(c, 0x1d), implementation) mstore(add(c, 0x09), 0x60523d8160223d3973) mstore(add(c, 0x94), 0) mstore(c, 0x74) // Store the length. mstore(0x40, add(c, 0xa0)) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I proxy of `implementation`. function initCodeHashERC1967I(address implementation) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation)))) hash := keccak256(0x0c, 0x74) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967I proxy of `implementation`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967I( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967I(implementation); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a minimal ERC1967I proxy with `implementation` and `args`. function deployERC1967I(address implementation, bytes memory args) internal returns (address) { return deployERC1967I(0, implementation, args); } /// @dev Deploys a minimal ERC1967I proxy with `implementation` and `args`. /// Deposits `value` ETH during deployment. function deployERC1967I(uint256 value, address implementation, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x4b), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x2b), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe6100523d8160233d3973, shl(56, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. instance := create(value, add(m, add(0x15, lt(n, 0xffae))), add(0x75, n)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic ERC1967I proxy with `implementation`, `args`, and `salt`. function deployDeterministicERC1967I(address implementation, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967I(0, implementation, args, salt); } /// @dev Deploys a deterministic ERC1967I proxy with `implementation`, `args`, and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967I( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x4b), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x2b), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(m, 0x14), implementation) mstore(m, add(0xfe6100523d8160233d3973, shl(56, n))) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. instance := create2(value, add(m, add(0x15, lt(n, 0xffae))), add(0x75, n), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic ERC1967I proxy with `implementation`, `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I(address implementation, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967I(0, implementation, args, salt); } /// @dev Creates a deterministic ERC1967I proxy with `implementation`, `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967I( uint256 value, address implementation, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x75), n)) mstore(add(m, 0x55), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x35), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x15), 0x5155f3365814604357363d3d373d3d363d7f360894) mstore(0x16, 0x600f) mstore(0x14, implementation) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(gt(n, 0xffad), add(0xfe6100523d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(m, add(n, 0x75))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, m, add(0x75, n), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the ERC1967I proxy of `implementation` and `args`. function initCodeERC1967I(address implementation, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x95), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x75), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(c, 0x55), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(c, 0x35), 0x600f5155f3365814604357363d3d373d3d363d7f360894) mstore(add(c, 0x1e), implementation) mstore(add(c, 0x0a), add(0x6100523d8160233d3973, shl(56, n))) mstore(add(c, add(n, 0x95)), 0) mstore(c, add(0x75, n)) // Store the length. mstore(0x40, add(c, add(n, 0xb5))) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I proxy of `implementation` and `args. function initCodeHashERC1967I(address implementation, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x75), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x55), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3) mstore(add(m, 0x35), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4) mstore(add(m, 0x15), 0x5155f3365814604357363d3d373d3d363d7f360894) mstore(0x16, 0x600f) mstore(0x14, implementation) mstore(0x00, add(0x6100523d8160233d3973, shl(56, n))) mstore(m, mload(0x16)) hash := keccak256(m, add(0x75, n)) } } /// @dev Returns the address of the ERC1967I proxy of `implementation`, `args` with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967I( address implementation, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967I(implementation, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967I(instance, start, 2 ** 256 - 1)`. function argsOnERC1967I(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x52))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x52, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967I(instance, start, 2 ** 256 - 1)`. function argsOnERC1967I(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x52)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x32), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967 with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967I(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x32), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x52) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967 BOOTSTRAP OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // A bootstrap is a minimal UUPS implementation that allows an ERC1967 proxy // pointing to it to be upgraded. The ERC1967 proxy can then be deployed to a // deterministic address independent of the implementation: // ``` // address bootstrap = LibClone.erc1967Bootstrap(); // address instance = LibClone.deployDeterministicERC1967(0, bootstrap, salt); // LibClone.bootstrapERC1967(bootstrap, implementation); // ``` /// @dev Deploys the ERC1967 bootstrap if it has not been deployed. function erc1967Bootstrap() internal returns (address) { return erc1967Bootstrap(address(this)); } /// @dev Deploys the ERC1967 bootstrap if it has not been deployed. function erc1967Bootstrap(address authorizedUpgrader) internal returns (address bootstrap) { bytes memory c = initCodeERC1967Bootstrap(authorizedUpgrader); bootstrap = predictDeterministicAddress(keccak256(c), bytes32(0), address(this)); /// @solidity memory-safe-assembly assembly { if iszero(extcodesize(bootstrap)) { if iszero(create2(0, add(c, 0x20), mload(c), 0)) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } } /// @dev Replaces the implementation at `instance`. function bootstrapERC1967(address instance, address implementation) internal { /// @solidity memory-safe-assembly assembly { mstore(0x00, implementation) if iszero(call(gas(), instance, 0, 0x0c, 0x14, codesize(), 0x00)) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Replaces the implementation at `instance`, and then call it with `data`. function bootstrapERC1967AndCall(address instance, address implementation, bytes memory data) internal { /// @solidity memory-safe-assembly assembly { let n := mload(data) mstore(data, implementation) if iszero(call(gas(), instance, 0, add(data, 0x0c), add(n, 0x14), codesize(), 0x00)) { if iszero(returndatasize()) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } returndatacopy(mload(0x40), 0x00, returndatasize()) revert(mload(0x40), returndatasize()) } mstore(data, n) // Restore the length of `data`. } } /// @dev Returns the implementation address of the ERC1967 bootstrap for this contract. function predictDeterministicAddressERC1967Bootstrap() internal view returns (address) { return predictDeterministicAddressERC1967Bootstrap(address(this), address(this)); } /// @dev Returns the implementation address of the ERC1967 bootstrap for this contract. function predictDeterministicAddressERC1967Bootstrap( address authorizedUpgrader, address deployer ) internal pure returns (address) { bytes32 hash = initCodeHashERC1967Bootstrap(authorizedUpgrader); return predictDeterministicAddress(hash, bytes32(0), deployer); } /// @dev Returns the initialization code of the ERC1967 bootstrap. function initCodeERC1967Bootstrap(address authorizedUpgrader) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x80), 0x3d3560601c5af46047573d6000383e3d38fd0000000000000000000000000000) mstore(add(c, 0x60), 0xa920a3ca505d382bbc55601436116049575b005b363d3d373d3d601436036014) mstore(add(c, 0x40), 0x0338573d3560601c7f360894a13ba1a3210667c828492db98dca3e2076cc3735) mstore(add(c, 0x20), authorizedUpgrader) mstore(add(c, 0x0c), 0x606880600a3d393df3fe3373) mstore(c, 0x72) mstore(0x40, add(c, 0xa0)) } } /// @dev Returns the initialization code hash of the ERC1967 bootstrap. function initCodeHashERC1967Bootstrap(address authorizedUpgrader) internal pure returns (bytes32) { return keccak256(initCodeERC1967Bootstrap(authorizedUpgrader)); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MINIMAL ERC1967 BEACON PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: If you use this proxy, you MUST make sure that the beacon is a // valid ERC1967 beacon. This means that the beacon must always return a valid // address upon a staticcall to `implementation()`, given sufficient gas. // For performance, the deployment operations and the proxy assumes that the // beacon is always valid and will NOT validate it. /// @dev Deploys a minimal ERC1967 beacon proxy. function deployERC1967BeaconProxy(address beacon) internal returns (address instance) { instance = deployERC1967BeaconProxy(0, beacon); } /// @dev Deploys a minimal ERC1967 beacon proxy. /// Deposits `value` ETH during deployment. function deployERC1967BeaconProxy(uint256 value, address beacon) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 beac | PUSH20 beac | beac 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos beac 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot beac 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (82 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * | * ~~~~~~~ beacon staticcall sub procedure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 60 0x20 | PUSH1 0x20 | 32 | | * 36 | CALLDATASIZE | cds 32 | | * 60 0x04 | PUSH1 0x04 | 4 cds 32 | | * 36 | CALLDATASIZE | cds 4 cds 32 | | * 63 0x5c60da1b | PUSH4 0x5c60da1b | 0x5c60da1b cds 4 cds 32 | | * 60 0xe0 | PUSH1 0xe0 | 224 0x5c60da1b cds 4 cds 32 | | * 1b | SHL | sel cds 4 cds 32 | | * 36 | CALLDATASIZE | cds sel cds 4 cds 32 | | * 52 | MSTORE | cds 4 cds 32 | sel | * 7f slot | PUSH32 slot | s cds 4 cds 32 | sel | * 54 | SLOAD | beac cds 4 cds 32 | sel | * 5a | GAS | g beac cds 4 cds 32 | sel | * fa | STATICCALL | succ | impl | * 50 | POP | | impl | * 36 | CALLDATASIZE | cds | impl | * 51 | MLOAD | impl | impl | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 5a | GAS | g impl 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 80 | DUP1 | 0 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [0..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x4d | PUSH1 0x4d | dest succ | [0..returndatasize): returndata | * 57 | JUMPI | | [0..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * fd | REVERT | | [0..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [0..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [0..returndatasize): returndata | * 60 0x00 | PUSH1 0x00 | 0 rds | [0..returndatasize): returndata | * f3 | RETURN | | [0..returndatasize): returndata | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) instance := create(value, 0x0c, 0x74) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `salt`. function deployDeterministicERC1967BeaconProxy(address beacon, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967BeaconProxy(0, beacon, salt); } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967BeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy(address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967BeaconProxy(0, beacon, salt); } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x0c, 0x74)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x0c, 0x74, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the minimal ERC1967 beacon proxy. function initCodeERC1967BeaconProxy(address beacon) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x74), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(c, 0x54), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(c, 0x34), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(c, 0x1d), beacon) mstore(add(c, 0x09), 0x60523d8160223d3973) mstore(add(c, 0x94), 0) mstore(c, 0x74) // Store the length. mstore(0x40, add(c, 0xa0)) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 beacon proxy. function initCodeHashERC1967BeaconProxy(address beacon) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon)))) hash := keccak256(0x0c, 0x74) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967 beacon proxy, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967BeaconProxy( address beacon, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967BeaconProxy(beacon); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967 BEACON PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a minimal ERC1967 beacon proxy with `args`. function deployERC1967BeaconProxy(address beacon, bytes memory args) internal returns (address instance) { instance = deployERC1967BeaconProxy(0, beacon, args); } /// @dev Deploys a minimal ERC1967 beacon proxy with `args`. /// Deposits `value` ETH during deployment. function deployERC1967BeaconProxy(uint256 value, address beacon, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n))) instance := create(value, add(m, 0x16), add(n, 0x75)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. function deployDeterministicERC1967BeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967BeaconProxy(0, beacon, args, salt); } /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967BeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n))) instance := create2(value, add(m, 0x16), add(n, 0x75), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967BeaconProxy(0, beacon, args, salt); } /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967BeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n)) mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n))) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(add(m, 0x16), add(n, 0x75))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, add(m, 0x16), add(n, 0x75), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the minimal ERC1967 beacon proxy. function initCodeERC1967BeaconProxy(address beacon, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x95), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x75), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(c, 0x55), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(c, 0x35), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(c, 0x1e), beacon) mstore(add(c, 0x0a), add(0x6100523d8160233d3973, shl(56, n))) mstore(c, add(n, 0x75)) // Store the length. mstore(add(c, add(n, 0x95)), 0) // Zeroize the slot after the bytes. mstore(0x40, add(c, add(n, 0xb5))) // Allocate memory. } } /// @dev Returns the initialization code hash of the minimal ERC1967 beacon proxy with `args`. function initCodeHashERC1967BeaconProxy(address beacon, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(m, 0x8b), i), mload(add(add(args, 0x20), i))) } mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3) mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c) mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da) mstore(add(m, 0x14), beacon) mstore(m, add(0x6100523d8160233d3973, shl(56, n))) hash := keccak256(add(m, 0x16), add(n, 0x75)) } } /// @dev Returns the address of the ERC1967 beacon proxy with `args`, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967BeaconProxy( address beacon, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967BeaconProxy(beacon, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967BeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967BeaconProxy(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x52))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x52, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967BeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967BeaconProxy(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x52)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x32), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967 beacon proxy with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967BeaconProxy(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x32), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x52) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I BEACON PROXY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: This proxy has a special code path that activates if `calldatasize() == 1`. // This code path skips the delegatecall and directly returns the `implementation` address. // The returned implementation is guaranteed to be valid if the keccak256 of the // proxy's code is equal to `ERC1967_BEACON_PROXY_CODE_HASH`. // // If you use this proxy, you MUST make sure that the beacon is a // valid ERC1967 beacon. This means that the beacon must always return a valid // address upon a staticcall to `implementation()`, given sufficient gas. // For performance, the deployment operations and the proxy assumes that the // beacon is always valid and will NOT validate it. /// @dev Deploys a ERC1967I beacon proxy. function deployERC1967IBeaconProxy(address beacon) internal returns (address instance) { instance = deployERC1967IBeaconProxy(0, beacon); } /// @dev Deploys a ERC1967I beacon proxy. /// Deposits `value` ETH during deployment. function deployERC1967IBeaconProxy(uint256 value, address beacon) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { /** * ---------------------------------------------------------------------------------+ * CREATION (34 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * 60 runSize | PUSH1 runSize | r | | * 3d | RETURNDATASIZE | 0 r | | * 81 | DUP2 | r 0 r | | * 60 offset | PUSH1 offset | o r 0 r | | * 3d | RETURNDATASIZE | 0 o r 0 r | | * 39 | CODECOPY | 0 r | [0..runSize): runtime code | * 73 beac | PUSH20 beac | beac 0 r | [0..runSize): runtime code | * 60 slotPos | PUSH1 slotPos | slotPos beac 0 r | [0..runSize): runtime code | * 51 | MLOAD | slot beac 0 r | [0..runSize): runtime code | * 55 | SSTORE | 0 r | [0..runSize): runtime code | * f3 | RETURN | | [0..runSize): runtime code | * ---------------------------------------------------------------------------------| * RUNTIME (87 bytes) | * ---------------------------------------------------------------------------------| * Opcode | Mnemonic | Stack | Memory | * ---------------------------------------------------------------------------------| * | * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: | * 36 | CALLDATASIZE | cds | | * 3d | RETURNDATASIZE | 0 cds | | * 3d | RETURNDATASIZE | 0 0 cds | | * 37 | CALLDATACOPY | | [0..calldatasize): calldata | * | * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | 0 | | * 3d | RETURNDATASIZE | 0 0 | | * 36 | CALLDATASIZE | cds 0 0 | [0..calldatasize): calldata | * 3d | RETURNDATASIZE | 0 cds 0 0 | [0..calldatasize): calldata | * | * ~~~~~~~ beacon staticcall sub procedure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 60 0x20 | PUSH1 0x20 | 32 | | * 36 | CALLDATASIZE | cds 32 | | * 60 0x04 | PUSH1 0x04 | 4 cds 32 | | * 36 | CALLDATASIZE | cds 4 cds 32 | | * 63 0x5c60da1b | PUSH4 0x5c60da1b | 0x5c60da1b cds 4 cds 32 | | * 60 0xe0 | PUSH1 0xe0 | 224 0x5c60da1b cds 4 cds 32 | | * 1b | SHL | sel cds 4 cds 32 | | * 36 | CALLDATASIZE | cds sel cds 4 cds 32 | | * 52 | MSTORE | cds 4 cds 32 | sel | * 7f slot | PUSH32 slot | s cds 4 cds 32 | sel | * 54 | SLOAD | beac cds 4 cds 32 | sel | * 5a | GAS | g beac cds 4 cds 32 | sel | * fa | STATICCALL | succ | impl | * ~~~~~~ check calldatasize ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 36 | CALLDATASIZE | cds succ | | * 14 | EQ | | impl | * 60 0x52 | PUSH1 0x52 | | impl | * 57 | JUMPI | | impl | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 36 | CALLDATASIZE | cds | impl | * 51 | MLOAD | impl | impl | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | * 5a | GAS | g impl 0 cds 0 0 | [0..calldatasize): calldata | * f4 | DELEGATECALL | succ | [0..calldatasize): calldata | * | * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds succ | [0..calldatasize): calldata | * 60 0x00 | PUSH1 0x00 | 0 rds succ | [0..calldatasize): calldata | * 60 0x01 | PUSH1 0x01 | 1 0 rds succ | [0..calldatasize): calldata | * 3e | RETURNDATACOPY | succ | [1..returndatasize): returndata | * | * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: | * 60 0x52 | PUSH1 0x52 | dest succ | [1..returndatasize): returndata | * 57 | JUMPI | | [1..returndatasize): returndata | * | * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: | * 3d | RETURNDATASIZE | rds | [1..returndatasize): returndata | * 60 0x01 | PUSH1 0x01 | 1 rds | [1..returndatasize): returndata | * fd | REVERT | | [1..returndatasize): returndata | * | * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: | * 5b | JUMPDEST | | [1..returndatasize): returndata | * 3d | RETURNDATASIZE | rds | [1..returndatasize): returndata | * 60 0x01 | PUSH1 0x01 | 1 rds | [1..returndatasize): returndata | * f3 | RETURN | | [1..returndatasize): returndata | * ---------------------------------------------------------------------------------+ */ let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) instance := create(value, 0x07, 0x79) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Deploys a deterministic ERC1967I beacon proxy with `salt`. function deployDeterministicERC1967IBeaconProxy(address beacon, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967IBeaconProxy(0, beacon, salt); } /// @dev Deploys a deterministic ERC1967I beacon proxy with `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967IBeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) instance := create2(value, 0x07, 0x79, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Creates a deterministic ERC1967I beacon proxy with `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy(address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967IBeaconProxy(0, beacon, salt); } /// @dev Creates a deterministic ERC1967I beacon proxy with `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy(uint256 value, address beacon, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) // Compute and store the bytecode hash. mstore(add(m, 0x35), keccak256(0x07, 0x79)) mstore(m, shl(88, address())) mstore8(m, 0xff) // Write the prefix. mstore(add(m, 0x15), salt) instance := keccak256(m, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, 0x07, 0x79, salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the initialization code of the ERC1967I beacon proxy. function initCodeERC1967IBeaconProxy(address beacon) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) mstore(add(c, 0x79), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(c, 0x59), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(c, 0x39), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(c, 0x1d), beacon) mstore(add(c, 0x09), 0x60573d8160223d3973) mstore(add(c, 0x99), 0) mstore(c, 0x79) // Store the length. mstore(0x40, add(c, 0xa0)) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I beacon proxy. function initCodeHashERC1967IBeaconProxy(address beacon) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon)))) hash := keccak256(0x07, 0x79) mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero slot. } } /// @dev Returns the address of the ERC1967I beacon proxy, with `salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967IBeaconProxy( address beacon, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967IBeaconProxy(beacon); predicted = predictDeterministicAddress(hash, salt, deployer); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC1967I BEACON PROXY WITH IMMUTABLE ARGS OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Deploys a ERC1967I beacon proxy with `args. function deployERC1967IBeaconProxy(address beacon, bytes memory args) internal returns (address instance) { instance = deployERC1967IBeaconProxy(0, beacon, args); } /// @dev Deploys a ERC1967I beacon proxy with `args. /// Deposits `value` ETH during deployment. function deployERC1967IBeaconProxy(uint256 value, address beacon, bytes memory args) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n)) mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n))) instance := create(value, add(m, 0x16), add(n, 0x7a)) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Deploys a deterministic ERC1967I beacon proxy with `args` and `salt`. function deployDeterministicERC1967IBeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (address instance) { instance = deployDeterministicERC1967IBeaconProxy(0, beacon, args, salt); } /// @dev Deploys a deterministic ERC1967I beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. function deployDeterministicERC1967IBeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n)) mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n))) instance := create2(value, add(m, 0x16), add(n, 0x7a), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } } } /// @dev Creates a deterministic ERC1967I beacon proxy with `args` and `salt`. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy(address beacon, bytes memory args, bytes32 salt) internal returns (bool alreadyDeployed, address instance) { return createDeterministicERC1967IBeaconProxy(0, beacon, args, salt); } /// @dev Creates a deterministic ERC1967I beacon proxy with `args` and `salt`. /// Deposits `value` ETH during deployment. /// Note: This method is intended for use in ERC4337 factories, /// which are expected to NOT revert if the proxy is already deployed. function createDeterministicERC1967IBeaconProxy( uint256 value, address beacon, bytes memory args, bytes32 salt ) internal returns (bool alreadyDeployed, address instance) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let n := mload(args) pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n)) mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(m, 0x14), beacon) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n))) // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, keccak256(add(m, 0x16), add(n, 0x7a))) mstore(0x01, shl(96, address())) mstore(0x15, salt) instance := keccak256(0x00, 0x55) for {} 1 {} { if iszero(extcodesize(instance)) { instance := create2(value, add(m, 0x16), add(n, 0x7a), salt) if iszero(instance) { mstore(0x00, 0x30116425) // `DeploymentFailed()`. revert(0x1c, 0x04) } break } alreadyDeployed := 1 if iszero(value) { break } if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } break } mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the initialization code of the ERC1967I beacon proxy with `args`. function initCodeERC1967IBeaconProxy(address beacon, bytes memory args) internal pure returns (bytes memory c) { /// @solidity memory-safe-assembly assembly { c := mload(0x40) let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffa8)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x9a), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x7a), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(c, 0x5a), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(c, 0x3a), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(c, 0x1e), beacon) mstore(add(c, 0x0a), add(0x6100573d8160233d3973, shl(56, n))) mstore(add(c, add(n, 0x9a)), 0) mstore(c, add(n, 0x7a)) // Store the length. mstore(0x40, add(c, add(n, 0xba))) // Allocate memory. } } /// @dev Returns the initialization code hash of the ERC1967I beacon proxy with `args`. function initCodeHashERC1967IBeaconProxy(address beacon, bytes memory args) internal pure returns (bytes32 hash) { /// @solidity memory-safe-assembly assembly { let c := mload(0x40) // Cache the free memory pointer. let n := mload(args) // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`. returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffa8)) for { let i := 0 } lt(i, n) { i := add(i, 0x20) } { mstore(add(add(c, 0x90), i), mload(add(add(args, 0x20), i))) } mstore(add(c, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3) mstore(add(c, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513) mstore(add(c, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36) mstore(add(c, 0x14), beacon) mstore(c, add(0x6100573d8160233d3973, shl(56, n))) hash := keccak256(add(c, 0x16), add(n, 0x7a)) } } /// @dev Returns the address of the ERC1967I beacon proxy, with `args` and salt` by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddressERC1967IBeaconProxy( address beacon, bytes memory args, bytes32 salt, address deployer ) internal pure returns (address predicted) { bytes32 hash = initCodeHashERC1967IBeaconProxy(beacon, args); predicted = predictDeterministicAddress(hash, salt, deployer); } /// @dev Equivalent to `argsOnERC1967IBeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967IBeaconProxy(address instance) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x57))) // Store the length. extcodecopy(instance, add(args, 0x20), 0x57, add(mload(args), 0x20)) mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory. } } /// @dev Equivalent to `argsOnERC1967IBeaconProxy(instance, start, 2 ** 256 - 1)`. function argsOnERC1967IBeaconProxy(address instance, uint256 start) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) let n := and(0xffffffffff, sub(extcodesize(instance), 0x57)) let l := sub(n, and(0xffffff, mul(lt(start, n), start))) extcodecopy(instance, args, add(start, 0x37), add(l, 0x40)) mstore(args, mul(sub(n, start), lt(start, n))) // Store the length. mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory. } } /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`. /// `start` and `end` will be clamped to the range `[0, args.length]`. /// The `instance` MUST be deployed via the ERC1967I beacon proxy with immutable args functions. /// Otherwise, the behavior is undefined. /// Out-of-gas reverts if `instance` does not have any code. function argsOnERC1967IBeaconProxy(address instance, uint256 start, uint256 end) internal view returns (bytes memory args) { /// @solidity memory-safe-assembly assembly { args := mload(0x40) if iszero(lt(end, 0xffff)) { end := 0xffff } let d := mul(sub(end, start), lt(start, end)) extcodecopy(instance, args, add(start, 0x37), add(d, 0x20)) if iszero(and(0xff, mload(add(args, d)))) { let n := sub(extcodesize(instance), 0x57) returndatacopy(returndatasize(), returndatasize(), shr(40, n)) d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n)))) } mstore(args, d) // Store the length. mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes. mstore(0x40, add(add(args, 0x40), d)) // Allocate memory. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* OTHER OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `address(0)` if the implementation address cannot be determined. function implementationOf(address instance) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { for { extcodecopy(instance, 0x00, 0x00, 0x57) } 1 {} { if mload(0x2d) { // ERC1967I and ERC1967IBeaconProxy detection. if or( eq(keccak256(0x00, 0x52), ERC1967I_CODE_HASH), eq(keccak256(0x00, 0x57), ERC1967I_BEACON_PROXY_CODE_HASH) ) { pop(staticcall(gas(), instance, 0x00, 0x01, 0x00, 0x20)) result := mload(0x0c) break } } // 0age clone detection. result := mload(0x0b) codecopy(0x0b, codesize(), 0x14) // Zeroize the 20 bytes for the address. if iszero(xor(keccak256(0x00, 0x2c), CLONE_CODE_HASH)) { break } mstore(0x0b, result) // Restore the zeroized memory. // CWIA detection. result := mload(0x0a) codecopy(0x0a, codesize(), 0x14) // Zeroize the 20 bytes for the address. if iszero(xor(keccak256(0x00, 0x2d), CWIA_CODE_HASH)) { break } mstore(0x0a, result) // Restore the zeroized memory. // PUSH0 clone detection. result := mload(0x09) codecopy(0x09, codesize(), 0x14) // Zeroize the 20 bytes for the address. result := shr(xor(keccak256(0x00, 0x2d), PUSH0_CLONE_CODE_HASH), result) break } result := shr(96, result) mstore(0x37, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the address when a contract with initialization code hash, /// `hash`, is deployed with `salt`, by `deployer`. /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly. function predictDeterministicAddress(bytes32 hash, bytes32 salt, address deployer) internal pure returns (address predicted) { /// @solidity memory-safe-assembly assembly { // Compute and store the bytecode hash. mstore8(0x00, 0xff) // Write the prefix. mstore(0x35, hash) mstore(0x01, shl(96, deployer)) mstore(0x15, salt) predicted := keccak256(0x00, 0x55) mstore(0x35, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Requires that `salt` starts with either the zero address or `by`. function checkStartsWith(bytes32 salt, address by) internal pure { /// @solidity memory-safe-assembly assembly { // If the salt does not start with the zero address or `by`. if iszero(or(iszero(shr(96, salt)), eq(shr(96, shl(96, by)), shr(96, salt)))) { mstore(0x00, 0x0c4549ef) // `SaltDoesNotStartWith()`. revert(0x1c, 0x04) } } } /// @dev Returns the `bytes32` at `offset` in `args`, without any bounds checks. /// To load an address, you can use `address(bytes20(argLoad(args, offset)))`. function argLoad(bytes memory args, uint256 offset) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { result := mload(add(add(args, 0x20), offset)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeCast} from "../libraries/SafeCast.sol"; /// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0 /// and the lower 128 bits represent the amount1. type BalanceDelta is int256; using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global; using BalanceDeltaLibrary for BalanceDelta global; using SafeCast for int256; function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) { assembly ("memory-safe") { balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1)) } } function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly ("memory-safe") { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := add(a0, b0) res1 := add(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) { int256 res0; int256 res1; assembly ("memory-safe") { let a0 := sar(128, a) let a1 := signextend(15, a) let b0 := sar(128, b) let b1 := signextend(15, b) res0 := sub(a0, b0) res1 := sub(a1, b1) } return toBalanceDelta(res0.toInt128(), res1.toInt128()); } function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b); } function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) { return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b); } /// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type library BalanceDeltaLibrary { /// @notice A BalanceDelta of 0 BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0); function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) { assembly ("memory-safe") { _amount0 := sar(128, balanceDelta) } } function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) { assembly ("memory-safe") { _amount1 := signextend(15, balanceDelta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {PoolKey} from "../types/PoolKey.sol"; import {BalanceDelta} from "../types/BalanceDelta.sol"; /// @notice Parameter struct for `ModifyLiquidity` pool operations struct ModifyLiquidityParams { // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // how to modify the liquidity int256 liquidityDelta; // a value to set if you want unique liquidity positions at the same range bytes32 salt; } /// @notice Parameter struct for `Swap` pool operations struct SwapParams { /// Whether to swap token0 for token1 or vice versa bool zeroForOne; /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut) int256 amountSpecified; /// The sqrt price at which, if reached, the swap will stop executing uint160 sqrtPriceLimitX96; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Return type of the beforeSwap hook. // Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook) type BeforeSwapDelta is int256; // Creates a BeforeSwapDelta from specified and unspecified function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified) pure returns (BeforeSwapDelta beforeSwapDelta) { assembly ("memory-safe") { beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified)) } } /// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type library BeforeSwapDeltaLibrary { /// @notice A BeforeSwapDelta of 0 BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0); /// extracts int128 from the upper 128 bits of the BeforeSwapDelta /// returned by beforeSwap function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) { assembly ("memory-safe") { deltaSpecified := sar(128, delta) } } /// extracts int128 from the lower 128 bits of the BeforeSwapDelta /// returned by beforeSwap and afterSwap function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) { assembly ("memory-safe") { deltaUnspecified := signextend(15, delta) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Minimal ERC20 interface for Uniswap /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3 interface IERC20Minimal { /// @notice Returns an account's balance in the token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Library for reverting with custom errors efficiently /// @notice Contains functions for reverting with custom errors with different argument types efficiently /// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with /// `CustomError.selector.revertWith()` /// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately library CustomRevert { /// @dev ERC-7751 error for wrapping bubbled up reverts error WrappedError(address target, bytes4 selector, bytes reason, bytes details); /// @dev Reverts with the selector of a custom error in the scratch space function revertWith(bytes4 selector) internal pure { assembly ("memory-safe") { mstore(0, selector) revert(0, 0x04) } } /// @dev Reverts with a custom error with an address argument in the scratch space function revertWith(bytes4 selector, address addr) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0, 0x24) } } /// @dev Reverts with a custom error with an int24 argument in the scratch space function revertWith(bytes4 selector, int24 value) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, signextend(2, value)) revert(0, 0x24) } } /// @dev Reverts with a custom error with a uint160 argument in the scratch space function revertWith(bytes4 selector, uint160 value) internal pure { assembly ("memory-safe") { mstore(0, selector) mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0, 0x24) } } /// @dev Reverts with a custom error with two int24 arguments function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure { assembly ("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), signextend(2, value1)) mstore(add(fmp, 0x24), signextend(2, value2)) revert(fmp, 0x44) } } /// @dev Reverts with a custom error with two uint160 arguments function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure { assembly ("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff)) revert(fmp, 0x44) } } /// @dev Reverts with a custom error with two address arguments function revertWith(bytes4 selector, address value1, address value2) internal pure { assembly ("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff)) revert(fmp, 0x44) } } /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error /// @dev this method can be vulnerable to revert data bombs function bubbleUpAndRevertWith( address revertingContract, bytes4 revertingFunctionSelector, bytes4 additionalContext ) internal pure { bytes4 wrappedErrorSelector = WrappedError.selector; assembly ("memory-safe") { // Ensure the size of the revert data is a multiple of 32 bytes let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32) let fmp := mload(0x40) // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason mstore(fmp, wrappedErrorSelector) mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff)) mstore( add(fmp, 0x24), and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000) ) // offset revert reason mstore(add(fmp, 0x44), 0x80) // offset additional context mstore(add(fmp, 0x64), add(0xa0, encodedDataSize)) // size revert reason mstore(add(fmp, 0x84), returndatasize()) // revert reason returndatacopy(add(fmp, 0xa4), 0, returndatasize()) // size additional context mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04) // additional context mstore( add(fmp, add(0xc4, encodedDataSize)), and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000) ) revert(fmp, add(0xe4, encodedDataSize)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "./PoolKey.sol"; type PoolId is bytes32; /// @notice Library for computing the ID of a pool library PoolIdLibrary { /// @notice Returns value equal to keccak256(abi.encode(poolKey)) function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) { assembly ("memory-safe") { // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes) poolId := keccak256(poolKey, 0xa0) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import {PoolKey} from "@v4/src/types/PoolKey.sol"; import {IHooks} from "@v4/src/interfaces/IHooks.sol"; import {Currency, CurrencyLibrary} from "@v4/src/types/Currency.sol"; struct PathKey { Currency intermediateCurrency; uint24 fee; int24 tickSpacing; IHooks hooks; bytes hookData; } using PathKeyLibrary for PathKey global; /// @title PathKey Library /// @notice Memory-oriented version of v4-periphery/src/libraries/PathKeyLibrary.sol /// @dev Handles PathKey operations in memory rather than calldata for router operations library PathKeyLibrary { /// @notice Get the pool and swap direction for a given PathKey /// @param params the given PathKey /// @param currencyIn the input currency /// @return poolKey the pool key of the swap /// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1 function getPoolAndSwapDirection(PathKey memory params, Currency currencyIn) internal pure returns (PoolKey memory poolKey, bool zeroForOne) { Currency currencyOut = params.intermediateCurrency; (Currency currency0, Currency currency1) = currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn); zeroForOne = currencyIn == currency0; poolKey = PoolKey(currency0, currency1, params.fee, params.tickSpacing, params.hooks); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IEIP712} from "./IEIP712.sol"; /// @title SignatureTransfer /// @notice Handles ERC20 token transfers through signature based actions /// @dev Requires user's token approval on the Permit2 contract interface ISignatureTransfer is IEIP712 { /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount /// @param maxAmount The maximum amount a spender can request to transfer error InvalidAmount(uint256 maxAmount); /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred error LengthMismatch(); /// @notice Emits an event when the owner successfully invalidates an unordered nonce. event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask); /// @notice The token and amount details for a transfer signed in the permit transfer signature struct TokenPermissions { // ERC20 token address address token; // the maximum amount that can be spent uint256 amount; } /// @notice The signed permit message for a single token transfer struct PermitTransferFrom { TokenPermissions permitted; // a unique value for every token owner's signature to prevent signature replays uint256 nonce; // deadline on the permit signature uint256 deadline; } /// @notice Specifies the recipient address and amount for batched transfers. /// @dev Recipients and amounts correspond to the index of the signed token permissions array. /// @dev Reverts if the requested amount is greater than the permitted signed amount. struct SignatureTransferDetails { // recipient address address to; // spender requested amount uint256 requestedAmount; } /// @notice Used to reconstruct the signed permit message for multiple token transfers /// @dev Do not need to pass in spender address as it is required that it is msg.sender /// @dev Note that a user still signs over a spender address struct PermitBatchTransferFrom { // the tokens and corresponding amounts permitted for a transfer TokenPermissions[] permitted; // a unique value for every token owner's signature to prevent signature replays uint256 nonce; // deadline on the permit signature uint256 deadline; } /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce /// @dev It returns a uint256 bitmap /// @dev The index, or wordPosition is capped at type(uint248).max function nonceBitmap(address, uint256) external view returns (uint256); /// @notice Transfers a token using a signed permit message /// @dev Reverts if the requested amount is greater than the permitted signed amount /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails The spender's requested transfer details for the permitted token /// @param signature The signature to verify function permitTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes calldata signature ) external; /// @notice Transfers a token using a signed permit message /// @notice Includes extra data provided by the caller to verify signature over /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition /// @dev Reverts if the requested amount is greater than the permitted signed amount /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails The spender's requested transfer details for the permitted token /// @param witness Extra data to include when checking the user signature /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash /// @param signature The signature to verify function permitWitnessTransferFrom( PermitTransferFrom memory permit, SignatureTransferDetails calldata transferDetails, address owner, bytes32 witness, string calldata witnessTypeString, bytes calldata signature ) external; /// @notice Transfers multiple tokens using a signed permit message /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails Specifies the recipient and requested amount for the token transfer /// @param signature The signature to verify function permitTransferFrom( PermitBatchTransferFrom memory permit, SignatureTransferDetails[] calldata transferDetails, address owner, bytes calldata signature ) external; /// @notice Transfers multiple tokens using a signed permit message /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition /// @notice Includes extra data provided by the caller to verify signature over /// @param permit The permit data signed over by the owner /// @param owner The owner of the tokens to transfer /// @param transferDetails Specifies the recipient and requested amount for the token transfer /// @param witness Extra data to include when checking the user signature /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash /// @param signature The signature to verify function permitWitnessTransferFrom( PermitBatchTransferFrom memory permit, SignatureTransferDetails[] calldata transferDetails, address owner, bytes32 witness, string calldata witnessTypeString, bytes calldata signature ) external; /// @notice Invalidates the bits specified in mask for the bitmap at the word position /// @dev The wordPos is maxed at type(uint248).max /// @param wordPos A number to index the nonceBitmap at /// @param mask A bitmap masked against msg.sender's current bitmap at the word position function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Interface for claims over a contract balance, wrapped as a ERC6909 interface IERC6909Claims { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event OperatorSet(address indexed owner, address indexed operator, bool approved); event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount); event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount); /*////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Owner balance of an id. /// @param owner The address of the owner. /// @param id The id of the token. /// @return amount The balance of the token. function balanceOf(address owner, uint256 id) external view returns (uint256 amount); /// @notice Spender allowance of an id. /// @param owner The address of the owner. /// @param spender The address of the spender. /// @param id The id of the token. /// @return amount The allowance of the token. function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount); /// @notice Checks if a spender is approved by an owner as an operator /// @param owner The address of the owner. /// @param spender The address of the spender. /// @return approved The approval status. function isOperator(address owner, address spender) external view returns (bool approved); /// @notice Transfers an amount of an id from the caller to a receiver. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always, unless the function reverts function transfer(address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Transfers an amount of an id from a sender to a receiver. /// @param sender The address of the sender. /// @param receiver The address of the receiver. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always, unless the function reverts function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool); /// @notice Approves an amount of an id to a spender. /// @param spender The address of the spender. /// @param id The id of the token. /// @param amount The amount of the token. /// @return bool True, always function approve(address spender, uint256 id, uint256 amount) external returns (bool); /// @notice Sets or removes an operator for the caller. /// @param operator The address of the operator. /// @param approved The approval status. /// @return bool True, always function setOperator(address operator, bool approved) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Currency} from "../types/Currency.sol"; import {PoolId} from "../types/PoolId.sol"; import {PoolKey} from "../types/PoolKey.sol"; /// @notice Interface for all protocol-fee related functions in the pool manager interface IProtocolFees { /// @notice Thrown when protocol fee is set too high error ProtocolFeeTooLarge(uint24 fee); /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller. error InvalidCaller(); /// @notice Thrown when collectProtocolFees is attempted on a token that is synced. error ProtocolFeeCurrencySynced(); /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController. event ProtocolFeeControllerUpdated(address indexed protocolFeeController); /// @notice Emitted when the protocol fee is updated for a pool. event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee); /// @notice Given a currency address, returns the protocol fees accrued in that currency /// @param currency The currency to check /// @return amount The amount of protocol fees accrued in the currency function protocolFeesAccrued(Currency currency) external view returns (uint256 amount); /// @notice Sets the protocol fee for the given pool /// @param key The key of the pool to set a protocol fee for /// @param newProtocolFee The fee to set function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external; /// @notice Sets the protocol fee controller /// @param controller The new protocol fee controller function setProtocolFeeController(address controller) external; /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected /// @dev This will revert if the contract is unlocked /// @param recipient The address to receive the protocol fees /// @param currency The currency to withdraw /// @param amount The amount of currency to withdraw /// @return amountCollected The amount of currency successfully withdrawn function collectProtocolFees(address recipient, Currency currency, uint256 amount) external returns (uint256 amountCollected); /// @notice Returns the current protocol fee controller address /// @return address The current protocol fee controller address function protocolFeeController() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Interface for functions to access any storage slot in a contract interface IExtsload { /// @notice Called by external contracts to access granular pool state /// @param slot Key of slot to sload /// @return value The value of the slot as bytes32 function extsload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access granular pool state /// @param startSlot Key of slot to start sloading from /// @param nSlots Number of slots to load into return value /// @return values List of loaded values. function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values); /// @notice Called by external contracts to access sparse pool state /// @param slots List of slots to SLOAD from. /// @return values List of loaded values. function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; /// @notice Interface for functions to access any transient storage slot in a contract interface IExttload { /// @notice Called by external contracts to access transient storage of the contract /// @param slot Key of slot to tload /// @return value The value of the slot as bytes32 function exttload(bytes32 slot) external view returns (bytes32 value); /// @notice Called by external contracts to access sparse transient pool state /// @param slots List of slots to tload /// @return values List of loaded values function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {PoolKey} from "../types/PoolKey.sol"; import {IHooks} from "../interfaces/IHooks.sol"; import {SafeCast} from "./SafeCast.sol"; import {LPFeeLibrary} from "./LPFeeLibrary.sol"; import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol"; import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol"; import {IPoolManager} from "../interfaces/IPoolManager.sol"; import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol"; import {ParseBytes} from "./ParseBytes.sol"; import {CustomRevert} from "./CustomRevert.sol"; /// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits /// of the address that the hooks contract is deployed to. /// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400 /// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used. library Hooks { using LPFeeLibrary for uint24; using Hooks for IHooks; using SafeCast for int256; using BeforeSwapDeltaLibrary for BeforeSwapDelta; using ParseBytes for bytes; using CustomRevert for bytes4; uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1); uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13; uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12; uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11; uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10; uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9; uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8; uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7; uint160 internal constant AFTER_SWAP_FLAG = 1 << 6; uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5; uint160 internal constant AFTER_DONATE_FLAG = 1 << 4; uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3; uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2; uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1; uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0; struct Permissions { bool beforeInitialize; bool afterInitialize; bool beforeAddLiquidity; bool afterAddLiquidity; bool beforeRemoveLiquidity; bool afterRemoveLiquidity; bool beforeSwap; bool afterSwap; bool beforeDonate; bool afterDonate; bool beforeSwapReturnDelta; bool afterSwapReturnDelta; bool afterAddLiquidityReturnDelta; bool afterRemoveLiquidityReturnDelta; } /// @notice Thrown if the address will not lead to the specified hook calls being called /// @param hooks The address of the hooks contract error HookAddressNotValid(address hooks); /// @notice Hook did not return its selector error InvalidHookResponse(); /// @notice Additional context for ERC-7751 wrapped error when a hook call fails error HookCallFailed(); /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa error HookDeltaExceedsSwapAmount(); /// @notice Utility function intended to be used in hook constructors to ensure /// the deployed hooks address causes the intended hooks to be called /// @param permissions The hooks that are intended to be called /// @dev permissions param is memory as the function will be called from constructors function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure { if ( permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG) || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG) || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG) || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG) || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG) || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG) || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG) || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG) || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG) || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) || permissions.afterRemoveLiquidityReturnDelta != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) { HookAddressNotValid.selector.revertWith(address(self)); } } /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address /// @param self The hook to verify /// @param fee The fee of the pool the hook is used with /// @return bool True if the hook address is valid function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) { // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false; if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)) { return false; } if ( !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG) && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) return false; // If there is no hook contract set, then fee cannot be dynamic // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee return address(self) == address(0) ? !fee.isDynamicFee() : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee()); } /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta /// @return result The complete data returned by the hook function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) { bool success; assembly ("memory-safe") { success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0) } // Revert with FailedHookCall, containing any error message to bubble up if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector); // The call was successful, fetch the returned data assembly ("memory-safe") { // allocate result byte array from the free memory pointer result := mload(0x40) // store new free memory pointer at the end of the array padded to 32 bytes mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f)))) // store length in memory mstore(result, returndatasize()) // copy return data to result returndatacopy(add(result, 0x20), 0, returndatasize()) } // Length must be at least 32 to contain the selector. Check expected selector and returned selector match. if (result.length < 32 || result.parseSelector() != data.parseSelector()) { InvalidHookResponse.selector.revertWith(); } } /// @notice performs a hook call using the given calldata on the given hook /// @return int256 The delta returned by the hook function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) { bytes memory result = callHook(self, data); // If this hook wasn't meant to return something, default to 0 delta if (!parseReturn) return 0; // A length of 64 bytes is required to return a bytes4, and a 32 byte delta if (result.length != 64) InvalidHookResponse.selector.revertWith(); return result.parseReturnDelta(); } /// @notice modifier to prevent calling a hook if they initiated the action modifier noSelfCall(IHooks self) { if (msg.sender != address(self)) { _; } } /// @notice calls beforeInitialize hook if permissioned and validates return value function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) { if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96))); } } /// @notice calls afterInitialize hook if permissioned and validates return value function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick) internal noSelfCall(self) { if (self.hasPermission(AFTER_INITIALIZE_FLAG)) { self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick))); } } /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value function beforeModifyLiquidity( IHooks self, PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData ) internal noSelfCall(self) { if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData))); } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData))); } } /// @notice calls afterModifyLiquidity hook if permissioned and validates return value function afterModifyLiquidity( IHooks self, PoolKey memory key, ModifyLiquidityParams memory params, BalanceDelta delta, BalanceDelta feesAccrued, bytes calldata hookData ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) { if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA); callerDelta = delta; if (params.liquidityDelta > 0) { if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall( IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData) ), self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } else { if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) { hookDelta = BalanceDelta.wrap( self.callHookWithReturnDelta( abi.encodeCall( IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData) ), self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG) ) ); callerDelta = callerDelta - hookDelta; } } } /// @notice calls beforeSwap hook if permissioned and validates return value function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData) internal returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride) { amountToSwap = params.amountSpecified; if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride); if (self.hasPermission(BEFORE_SWAP_FLAG)) { bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData))); // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee if (result.length != 96) InvalidHookResponse.selector.revertWith(); // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee(); // skip this logic for the case where the hook return is 0 if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) { hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta()); // any return in unspecified is passed to the afterSwap hook for handling int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta(); // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output) if (hookDeltaSpecified != 0) { bool exactInput = amountToSwap < 0; amountToSwap += hookDeltaSpecified; if (exactInput ? amountToSwap > 0 : amountToSwap < 0) { HookDeltaExceedsSwapAmount.selector.revertWith(); } } } } } /// @notice calls afterSwap hook if permissioned and validates return value function afterSwap( IHooks self, PoolKey memory key, SwapParams memory params, BalanceDelta swapDelta, bytes calldata hookData, BeforeSwapDelta beforeSwapHookReturn ) internal returns (BalanceDelta, BalanceDelta) { if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA); int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta(); int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta(); if (self.hasPermission(AFTER_SWAP_FLAG)) { hookDeltaUnspecified += self.callHookWithReturnDelta( abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)), self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG) ).toInt128(); } BalanceDelta hookDelta; if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) { hookDelta = (params.amountSpecified < 0 == params.zeroForOne) ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified) : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified); // the caller has to pay for (or receive) the hook's delta swapDelta = swapDelta - hookDelta; } return (swapDelta, hookDelta); } /// @notice calls beforeDonate hook if permissioned and validates return value function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(BEFORE_DONATE_FLAG)) { self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData))); } } /// @notice calls afterDonate hook if permissioned and validates return value function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData) internal noSelfCall(self) { if (self.hasPermission(AFTER_DONATE_FLAG)) { self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData))); } } function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) { return uint160(address(self)) & flag != 0; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Call context checker mixin. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/CallContextChecker.sol) contract CallContextChecker { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The call is from an unauthorized call context. error UnauthorizedCallContext(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* IMMUTABLES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev For checking if the context is a delegate call. /// /// Note: To enable use cases with an immutable default implementation in the bytecode, /// (see: ERC6551Proxy), we don't require that the proxy address must match the /// value stored in the implementation slot, which may not be initialized. uint256 private immutable __self = uint256(uint160(address(this))); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CALL CONTEXT CHECKS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // A proxy call can be either via a `delegatecall` to an implementation, // or a 7702 call on an authority that points to a delegation. /// @dev Returns whether the current call context is on a EIP7702 authority /// (i.e. externally owned account). function _onEIP7702Authority() internal view virtual returns (bool result) { /// @solidity memory-safe-assembly assembly { extcodecopy(address(), 0x00, 0x00, 0x20) // Note: Checking that it starts with hex"ef01" is the most general and futureproof. // 7702 bytecode is `abi.encodePacked(hex"ef01", uint8(version), address(delegation))`. result := eq(0xef01, shr(240, mload(0x00))) } } /// @dev Returns the implementation of this contract. function _selfImplementation() internal view virtual returns (address) { return address(uint160(__self)); } /// @dev Returns whether the current call context is on the implementation itself. function _onImplementation() internal view virtual returns (bool) { return __self == uint160(address(this)); } /// @dev Requires that the current call context is performed via a EIP7702 authority. function _checkOnlyEIP7702Authority() internal view virtual { if (!_onEIP7702Authority()) _revertUnauthorizedCallContext(); } /// @dev Requires that the current call context is performed via a proxy. function _checkOnlyProxy() internal view virtual { if (_onImplementation()) _revertUnauthorizedCallContext(); } /// @dev Requires that the current call context is NOT performed via a proxy. /// This is the opposite of `checkOnlyProxy`. function _checkNotDelegated() internal view virtual { if (!_onImplementation()) _revertUnauthorizedCallContext(); } /// @dev Requires that the current call context is performed via a EIP7702 authority. modifier onlyEIP7702Authority() virtual { _checkOnlyEIP7702Authority(); _; } /// @dev Requires that the current call context is performed via a proxy. modifier onlyProxy() virtual { _checkOnlyProxy(); _; } /// @dev Requires that the current call context is NOT performed via a proxy. /// This is the opposite of `onlyProxy`. modifier notDelegated() virtual { _checkNotDelegated(); _; } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* PRIVATE HELPERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function _revertUnauthorizedCallContext() private pure { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x9f03a026) // `UnauthorizedCallContext()`. revert(0x1c, 0x04) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {CustomRevert} from "./CustomRevert.sol"; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { using CustomRevert for bytes4; error SafeCastOverflow(); /// @notice Cast a uint256 to a uint160, revert on overflow /// @param x The uint256 to be downcasted /// @return y The downcasted integer, now type uint160 function toUint160(uint256 x) internal pure returns (uint160 y) { y = uint160(x); if (y != x) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param x The uint256 to be downcasted /// @return y The downcasted integer, now type uint128 function toUint128(uint256 x) internal pure returns (uint128 y) { y = uint128(x); if (x != y) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a int128 to a uint128, revert on overflow or underflow /// @param x The int128 to be casted /// @return y The casted integer, now type uint128 function toUint128(int128 x) internal pure returns (uint128 y) { if (x < 0) SafeCastOverflow.selector.revertWith(); y = uint128(x); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param x The int256 to be downcasted /// @return y The downcasted integer, now type int128 function toInt128(int256 x) internal pure returns (int128 y) { y = int128(x); if (y != x) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param x The uint256 to be casted /// @return y The casted integer, now type int256 function toInt256(uint256 x) internal pure returns (int256 y) { y = int256(x); if (y < 0) SafeCastOverflow.selector.revertWith(); } /// @notice Cast a uint256 to a int128, revert on overflow /// @param x The uint256 to be downcasted /// @return The downcasted integer, now type int128 function toInt128(uint256 x) internal pure returns (int128) { if (x >= 1 << 127) SafeCastOverflow.selector.revertWith(); return int128(int256(x)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IEIP712 { function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {CustomRevert} from "./CustomRevert.sol"; /// @notice Library of helper functions for a pools LP fee library LPFeeLibrary { using LPFeeLibrary for uint24; using CustomRevert for bytes4; /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%. error LPFeeTooLarge(uint24 fee); /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE uint24 public constant DYNAMIC_FEE_FLAG = 0x800000; /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap // only dynamic-fee pools can return a fee via the beforeSwap hook uint24 public constant OVERRIDE_FEE_FLAG = 0x400000; /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF; /// @notice the lp fee is represented in hundredths of a bip, so the max is 100% uint24 public constant MAX_LP_FEE = 1000000; /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee /// @param self The fee to check /// @return bool True of the fee is dynamic function isDynamicFee(uint24 self) internal pure returns (bool) { return self == DYNAMIC_FEE_FLAG; } /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee /// @param self The fee to check /// @return bool True of the fee is valid function isValid(uint24 self) internal pure returns (bool) { return self <= MAX_LP_FEE; } /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid /// @param self The fee to validate function validate(uint24 self) internal pure { if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self); } /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0. /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook /// @param self The fee to get the initial LP from /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid) function getInitialLPFee(uint24 self) internal pure returns (uint24) { // the initial fee for a dynamic fee pool is 0 if (self.isDynamicFee()) return 0; self.validate(); return self; } /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24) /// @param self The fee to check /// @return bool True of the fee has the override flag set function isOverride(uint24 self) internal pure returns (bool) { return self & OVERRIDE_FEE_FLAG != 0; } /// @notice returns a fee with the override flag removed /// @param self The fee to remove the override flag from /// @return fee The fee without the override flag set function removeOverrideFlag(uint24 self) internal pure returns (uint24) { return self & REMOVE_OVERRIDE_MASK; } /// @notice Removes the override flag and validates the fee (reverts if the fee is too large) /// @param self The fee to remove the override flag from, and then validate /// @return fee The fee without the override flag set (if valid) function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) { fee = self.removeOverrideFlag(); fee.validate(); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks. /// @dev parseSelector also is used to parse the expected selector /// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24). library ParseBytes { function parseSelector(bytes memory result) internal pure returns (bytes4 selector) { // equivalent: (selector,) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { selector := mload(add(result, 0x20)) } } function parseFee(bytes memory result) internal pure returns (uint24 lpFee) { // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24)); assembly ("memory-safe") { lpFee := mload(add(result, 0x60)) } } function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) { // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256)); assembly ("memory-safe") { hookReturn := mload(add(result, 0x40)) } } }
{ "remappings": [ "solady/=lib/solady/src/", "@uniswap/v4-core/=lib/v4-core/", "@uniswap/v4-periphery/=lib/v4-periphery/", "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/", "v4-router/=lib/v4-router/src/", "@v4/=lib/v4-core/", "@ensdomains/=lib/v4-core/node_modules/@ensdomains/", "@forge/=lib/v4-router/lib/forge-std/src/", "@openzeppelin/uniswap-hooks/=lib/v4-router/lib/v4-template/lib/uniswap-hooks/", "@permit2/=lib/v4-router/lib/permit2/src/", "@solady/=lib/v4-router/lib/solady/", "@uniswap/v2-core/=lib/v4-router/lib/universal-router/node_modules/@uniswap/v2-core/", "@uniswap/v3-core/=lib/v4-router/lib/universal-router/node_modules/@uniswap/v3-core/", "@uniswap/v3-periphery/=lib/v4-router/lib/universal-router/lib/v3-periphery/", "@universal-router/=lib/v4-router/lib/universal-router/contracts/", "@v4-periphery/=lib/v4-router/lib/v4-periphery/", "@v4-template/=lib/v4-router/lib/v4-template/", "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/", "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/", "forge-gas-snapshot/=lib/v4-router/lib/forge-gas-snapshot/src/", "forge-std/=lib/forge-std/src/", "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/", "hardhat/=lib/v4-core/node_modules/hardhat/", "hookmate/=lib/v4-router/lib/v4-template/lib/hookmate/src/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "openzeppelin/=lib/v4-router/lib/v4-template/lib/uniswap-hooks/lib/v4-core/lib/openzeppelin-contracts/contracts/", "permit2/=lib/v4-periphery/lib/permit2/", "solmate/=lib/v4-core/lib/solmate/", "uniswap-hooks/=lib/v4-router/lib/v4-template/lib/uniswap-hooks/src/", "universal-router/=lib/v4-router/lib/universal-router/", "v3-periphery/=lib/v4-router/lib/universal-router/lib/v3-periphery/contracts/", "v4-core/=lib/v4-core/src/", "v4-periphery/=lib/v4-periphery/", "v4-template/=lib/v4-router/lib/v4-template/", "lib/permit2/test:openzeppelin-contracts/contracts/=lib/v4-router/lib/permit2/lib/openzeppelin-contracts/contracts/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "prague", "viaIR": true }
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AllowanceOverflow","type":"error"},{"inputs":[],"name":"AllowanceUnderflow","type":"error"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"AlreadyNFTOwner","type":"error"},{"inputs":[{"internalType":"bytes","name":"reason","type":"bytes"}],"name":"ExternalCallFailed","type":"error"},{"inputs":[],"name":"InsufficientAllowance","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InsufficientContractBalance","type":"error"},{"inputs":[],"name":"InvalidCollection","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidMultiplier","type":"error"},{"inputs":[],"name":"InvalidPermit","type":"error"},{"inputs":[],"name":"InvalidTarget","type":"error"},{"inputs":[],"name":"InvalidTransfer","type":"error"},{"inputs":[],"name":"NFTNotForSale","type":"error"},{"inputs":[],"name":"NFTPriceTooLow","type":"error"},{"inputs":[],"name":"NeedToBuyNFT","type":"error"},{"inputs":[],"name":"NewOwnerIsZeroAddress","type":"error"},{"inputs":[],"name":"NoETHToTwap","type":"error"},{"inputs":[],"name":"NoHandoverRequest","type":"error"},{"inputs":[],"name":"NotEnoughEth","type":"error"},{"inputs":[],"name":"NotFactory","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"NotNFTOwner","type":"error"},{"inputs":[],"name":"OnlyHook","type":"error"},{"inputs":[],"name":"Permit2AllowanceIsFixedAtInfinity","type":"error"},{"inputs":[],"name":"PermitExpired","type":"error"},{"inputs":[],"name":"PriceTooHigh","type":"error"},{"inputs":[],"name":"Reentrancy","type":"error"},{"inputs":[],"name":"TotalSupplyOverflow","type":"error"},{"inputs":[],"name":"TwapDelayNotMet","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"UnauthorizedCallContext","type":"error"},{"inputs":[],"name":"UpgradeFailed","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AllowanceIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"AllowanceSpent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldImplementation","type":"address"},{"indexed":true,"internalType":"address","name":"newImplementation","type":"address"},{"indexed":false,"internalType":"uint256","name":"version","type":"uint256"}],"name":"ContractUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"distributor","type":"address"},{"indexed":false,"internalType":"bool","name":"status","type":"bool"}],"name":"DistributorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"purchasePrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"listPrice","type":"uint256"}],"name":"NFTBoughtByProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"address","name":"buyer","type":"address"}],"name":"NFTSoldByProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pendingOwner","type":"address"}],"name":"OwnershipHandoverRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"DEAD_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"result","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_SUPPLY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"addFees","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"buyIncrement","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256","name":"expectedId","type":"uint256"},{"internalType":"address","name":"target","type":"address"}],"name":"buyTargetNFT","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"cancelOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"collection","outputs":[{"internalType":"contract IERC721","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"completeOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"currentFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ethToTwap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getImplementation","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMaxPriceForBuy","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTransferAllowance","outputs":[{"internalType":"uint256","name":"transferAllowance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hookAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountAllowed","type":"uint256"}],"name":"increaseTransferAllowance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_collection","type":"address"},{"internalType":"address","name":"_hook","type":"address"},{"internalType":"string","name":"_tokenName","type":"string"},{"internalType":"string","name":"_tokenSymbol","type":"string"},{"internalType":"uint256","name":"_buyIncrement","type":"uint256"},{"internalType":"address","name":"_owner","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isDistributor","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastBuyBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTwapBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"nftForSale","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"result","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pendingOwner","type":"address"}],"name":"ownershipHandoverExpiresAt","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"priceMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"processTokenTwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"requestOwnershipHandover","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"router","outputs":[{"internalType":"contract IUniswapV4Router04","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"sellTargetNFT","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"distributor","type":"address"},{"internalType":"bool","name":"status","type":"bool"}],"name":"setDistributor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newMultiplier","type":"uint256"}],"name":"setPriceMultiplier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"result","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"twapDelayInBlocks","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"twapIncrement","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_hookAddress","type":"address"}],"name":"updateHookAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_tokenName","type":"string"}],"name":"updateName","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_tokenSymbol","type":"string"}],"name":"updateSymbol","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]
Loading...
Loading
Loading...
Loading

Multichain Portfolio | 34 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|---|---|---|---|---|
ETH | 100.00% | $4,007.48 | 183.3029 | $734,583.04 |
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.