From 035a31815706371285359b1c09dc3a967338261d Mon Sep 17 00:00:00 2001 From: ross <92001561+z0r0z@users.noreply.github.com> Date: Tue, 4 Jun 2024 08:26:14 +0000 Subject: [PATCH] =?UTF-8?q?=E2=8C=98=20Deployment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gas-snapshot | 12 +-- README.md | 4 +- docs/src/README.md | 4 +- docs/src/src/IE.sol/contract.IE.md | 88 ++++++++++++++++++-- docs/src/src/IE.sol/interface.IExecutor.md | 2 +- docs/src/src/IE.sol/interface.INAMI.md | 2 +- docs/src/src/IE.sol/interface.ISwapRouter.md | 2 +- docs/src/src/IE.sol/interface.IToken.md | 11 ++- docs/src/src/NAMI.sol/contract.NAMI.md | 2 +- docs/src/src/NAMI.sol/interface.IToken.md | 2 +- etherscan.json | 2 +- lib/solady | 2 +- 12 files changed, 105 insertions(+), 28 deletions(-) diff --git a/.gas-snapshot b/.gas-snapshot index 13b29f8..7353e91 100644 --- a/.gas-snapshot +++ b/.gas-snapshot @@ -1,11 +1,11 @@ IETest:testCommandSendETH() (gas: 77576) IETest:testCommandSendETHRawAddr() (gas: 75355) -IETest:testCommandStakeETH() (gas: 147244) -IETest:testCommandSwapDAI() (gas: 130115) -IETest:testCommandSwapETH() (gas: 155507) -IETest:testCommandSwapForETH() (gas: 137252) -IETest:testCommandSwapUSDC() (gas: 171791) -IETest:testCommandSwapUSDCForWBTC() (gas: 196722) +IETest:testCommandStakeETH() (gas: 148128) +IETest:testCommandSwapDAI() (gas: 138821) +IETest:testCommandSwapETH() (gas: 185700) +IETest:testCommandSwapForETH() (gas: 145736) +IETest:testCommandSwapUSDC() (gas: 171759) +IETest:testCommandSwapUSDCForWBTC() (gas: 196702) IETest:testDeploy() (gas: 4059106) IETest:testENSNameOwnership() (gas: 50762) IETest:testPreviewBalanceChangeDAI() (gas: 130029) diff --git a/README.md b/README.md index 7910b4a..5d69eb9 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ The **Intents Engine** (`IE`): A Basic *Text-to-tx* Simulator Contract. ### Arbitrum -`V1.2:` [`0x1e00003a669bb466d6B49800000099E1abDD6600`](https://arbiscan.io/address/0x1e00003a669bb466d6b49800000099e1abdd6600#code) +`V1.3:` [`0x1e00002C59149d0057F12e031ecC0000d38A000C`](https://arbiscan.io/address/0x1e00002C59149d0057F12e031ecC0000d38A000C#code) `Note:` L2 will be used to rapidly prototype a stable and sufficient `IE` for common crypto commands. Many dev resources here will cater to the current L2 prototype until the release of `V2` on L1. @@ -72,7 +72,7 @@ aliases: *exchange* aliases: *exchange* -`Note:` In `V1.2` on Arbitrum, a `minOutputAmount` can be specified for swaps. It ensures that you receive a minimum output amount of `object` at the end of the swap, otherwise the transaction will revert. The default value is set to `0`. +`Note:` In `V1.3` on Arbitrum, a `minOutputAmount` can be specified for swaps. It ensures that you receive a minimum output amount of `object` at the end of the swap, otherwise the transaction will revert. The default value is set to `0`. ------------------------------------ diff --git a/docs/src/README.md b/docs/src/README.md index 7910b4a..5d69eb9 100644 --- a/docs/src/README.md +++ b/docs/src/README.md @@ -10,7 +10,7 @@ The **Intents Engine** (`IE`): A Basic *Text-to-tx* Simulator Contract. ### Arbitrum -`V1.2:` [`0x1e00003a669bb466d6B49800000099E1abDD6600`](https://arbiscan.io/address/0x1e00003a669bb466d6b49800000099e1abdd6600#code) +`V1.3:` [`0x1e00002C59149d0057F12e031ecC0000d38A000C`](https://arbiscan.io/address/0x1e00002C59149d0057F12e031ecC0000d38A000C#code) `Note:` L2 will be used to rapidly prototype a stable and sufficient `IE` for common crypto commands. Many dev resources here will cater to the current L2 prototype until the release of `V2` on L1. @@ -72,7 +72,7 @@ aliases: *exchange* aliases: *exchange* -`Note:` In `V1.2` on Arbitrum, a `minOutputAmount` can be specified for swaps. It ensures that you receive a minimum output amount of `object` at the end of the swap, otherwise the transaction will revert. The default value is set to `0`. +`Note:` In `V1.3` on Arbitrum, a `minOutputAmount` can be specified for swaps. It ensures that you receive a minimum output amount of `object` at the end of the swap, otherwise the transaction will revert. The default value is set to `0`. ------------------------------------ diff --git a/docs/src/src/IE.sol/contract.IE.md b/docs/src/src/IE.sol/contract.IE.md index f5eea24..d217300 100644 --- a/docs/src/src/IE.sol/contract.IE.md +++ b/docs/src/src/IE.sol/contract.IE.md @@ -1,5 +1,5 @@ # IE -[Git Source](https://github.com/NaniDAO/ie/blob/f14d7018eb9d8e0d134c41b44e0923f915c5a573/src/IE.sol) +[Git Source](https://github.com/NaniDAO/ie/blob/6ef68a2b1b107d6bd41812722498a697873f8c87/src/IE.sol) **Author:** nani.eth (https://github.com/NaniDAO/ie) @@ -22,6 +22,15 @@ address internal constant DAO = 0xDa000000000000d2885F108500803dfBAaB2f2aA; ``` +### AKA +*The onchain akashic library.* + + +```solidity +address internal constant AKA = 0x000000000000394793B2Fe854281CeE09a98bdBC; +``` + + ### NANI *The NANI token address.* @@ -271,7 +280,7 @@ function checkUserOp(string calldata intent, UserOperation calldata userOp) public view virtual - returns (bool); + returns (bool intentMatched); ``` ### checkPackedUserOp @@ -284,7 +293,7 @@ function checkPackedUserOp(string calldata intent, PackedUserOperation calldata public view virtual - returns (bool); + returns (bool intentMatched); ``` ### _returnTokenConstants @@ -438,16 +447,42 @@ Only canonical WETH can call.* receive() external payable virtual; ``` -### translate +### read ==================== COMMAND TRANSLATION ==================== /// -*Translates the `intent` for send action from the solution `callData` of a standard `execute()`. +*Returns the akashic library summary digest `about` a given `topic`.* + + +```solidity +function read(string calldata topic) public view virtual returns (string memory about); +``` + +### translateCommand + +*Translates an `intent` from raw `command()` calldata.* + + +```solidity +function translateCommand(bytes calldata callData) + public + pure + virtual + returns (string memory intent); +``` + +### translateExecute + +*Translates an `intent` for send action from the solution `callData` of standard `execute()`. note: The function selector technically doesn't need to be `execute()` but params should match.* ```solidity -function translate(bytes calldata callData) public view virtual returns (string memory intent); +function translateExecute(bytes calldata callData) + public + view + virtual + returns (string memory intent); ``` ### translateTokenTransfer @@ -466,7 +501,7 @@ function translateTokenTransfer(address token, bytes calldata tokenCalldata) ### translateUserOp -*Translate ERC4337 userOp `callData` into readable send `intent`.* +*Translate ERC4337 userOp `callData` into readable `intent`.* ```solidity @@ -479,7 +514,7 @@ function translateUserOp(UserOperation calldata userOp) ### translatePackedUserOp -*Translate packed ERC4337 userOp `callData` into readable send `intent`.* +*Translate packed ERC4337 userOp `callData` into readable `intent`.* ```solidity @@ -490,10 +525,23 @@ function translatePackedUserOp(PackedUserOperation calldata userOp) returns (string memory intent); ``` -### whatIsTheBalanceOf +### previewBalanceChange ================== BALANCE & SUPPLY HELPERS ================== /// +*Returns resulting percentage change of ETH or token balance.* + + +```solidity +function previewBalanceChange(address user, string calldata intent) + public + view + virtual + returns (uint256 percentage); +``` + +### whatIsTheBalanceOf + *Returns the balance of a named account in a named token.* @@ -699,6 +747,28 @@ function _toAsciiString(address x) internal pure virtual returns (string memory) function _char(bytes1 b) internal pure virtual returns (bytes1 c); ``` +### _convertWeiToString + +*Convert number to string and insert decimal point.* + + +```solidity +function _convertWeiToString(uint256 weiAmount, uint256 decimals) + internal + pure + virtual + returns (string memory); +``` + +### _removeTrailingZeros + +*Remove any trailing zeroes from string.* + + +```solidity +function _removeTrailingZeros(string memory str) internal pure virtual returns (string memory); +``` + ### _toString *Returns the base 10 decimal representation of `value`. diff --git a/docs/src/src/IE.sol/interface.IExecutor.md b/docs/src/src/IE.sol/interface.IExecutor.md index 437c8b7..e5408e0 100644 --- a/docs/src/src/IE.sol/interface.IExecutor.md +++ b/docs/src/src/IE.sol/interface.IExecutor.md @@ -1,5 +1,5 @@ # IExecutor -[Git Source](https://github.com/NaniDAO/ie/blob/f14d7018eb9d8e0d134c41b44e0923f915c5a573/src/IE.sol) +[Git Source](https://github.com/NaniDAO/ie/blob/6ef68a2b1b107d6bd41812722498a697873f8c87/src/IE.sol) Simple calldata executor interface. diff --git a/docs/src/src/IE.sol/interface.INAMI.md b/docs/src/src/IE.sol/interface.INAMI.md index 8d11399..f0246df 100644 --- a/docs/src/src/IE.sol/interface.INAMI.md +++ b/docs/src/src/IE.sol/interface.INAMI.md @@ -1,5 +1,5 @@ # INAMI -[Git Source](https://github.com/NaniDAO/ie/blob/f14d7018eb9d8e0d134c41b44e0923f915c5a573/src/IE.sol) +[Git Source](https://github.com/NaniDAO/ie/blob/6ef68a2b1b107d6bd41812722498a697873f8c87/src/IE.sol) *Simple NAMI names interface for resolving L2 ENS ownership.* diff --git a/docs/src/src/IE.sol/interface.ISwapRouter.md b/docs/src/src/IE.sol/interface.ISwapRouter.md index bef63dc..ed0dae3 100644 --- a/docs/src/src/IE.sol/interface.ISwapRouter.md +++ b/docs/src/src/IE.sol/interface.ISwapRouter.md @@ -1,5 +1,5 @@ # ISwapRouter -[Git Source](https://github.com/NaniDAO/ie/blob/f14d7018eb9d8e0d134c41b44e0923f915c5a573/src/IE.sol) +[Git Source](https://github.com/NaniDAO/ie/blob/6ef68a2b1b107d6bd41812722498a697873f8c87/src/IE.sol) *Simple Uniswap V3 swapping interface.* diff --git a/docs/src/src/IE.sol/interface.IToken.md b/docs/src/src/IE.sol/interface.IToken.md index 2130254..10d73c2 100644 --- a/docs/src/src/IE.sol/interface.IToken.md +++ b/docs/src/src/IE.sol/interface.IToken.md @@ -1,10 +1,17 @@ # IToken -[Git Source](https://github.com/NaniDAO/ie/blob/f14d7018eb9d8e0d134c41b44e0923f915c5a573/src/IE.sol) +[Git Source](https://github.com/NaniDAO/ie/blob/6ef68a2b1b107d6bd41812722498a697873f8c87/src/IE.sol) -*Simple token transfer interface.* +*Simple token handler interface.* ## Functions +### approve + + +```solidity +function approve(address, uint256) external returns (bool); +``` + ### transfer diff --git a/docs/src/src/NAMI.sol/contract.NAMI.md b/docs/src/src/NAMI.sol/contract.NAMI.md index 81a32ff..ad7ecfe 100644 --- a/docs/src/src/NAMI.sol/contract.NAMI.md +++ b/docs/src/src/NAMI.sol/contract.NAMI.md @@ -1,5 +1,5 @@ # NAMI -[Git Source](https://github.com/NaniDAO/ie/blob/f14d7018eb9d8e0d134c41b44e0923f915c5a573/src/NAMI.sol) +[Git Source](https://github.com/NaniDAO/ie/blob/6ef68a2b1b107d6bd41812722498a697873f8c87/src/NAMI.sol) **Author:** nani.eth (https://github.com/NaniDAO/ie) diff --git a/docs/src/src/NAMI.sol/interface.IToken.md b/docs/src/src/NAMI.sol/interface.IToken.md index ca8862d..ac4ec2d 100644 --- a/docs/src/src/NAMI.sol/interface.IToken.md +++ b/docs/src/src/NAMI.sol/interface.IToken.md @@ -1,5 +1,5 @@ # IToken -[Git Source](https://github.com/NaniDAO/ie/blob/f14d7018eb9d8e0d134c41b44e0923f915c5a573/src/NAMI.sol) +[Git Source](https://github.com/NaniDAO/ie/blob/6ef68a2b1b107d6bd41812722498a697873f8c87/src/NAMI.sol) *Simple token balance & supply interface.* diff --git a/etherscan.json b/etherscan.json index c34feb4..c455e55 100644 --- a/etherscan.json +++ b/etherscan.json @@ -1 +1 @@ -{"language":"Solidity","sources":{"src/IE.sol":{"content":"// ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.19;\n\nimport {SafeTransferLib} from \"../lib/solady/src/utils/SafeTransferLib.sol\";\nimport {MetadataReaderLib} from \"../lib/solady/src/utils/MetadataReaderLib.sol\";\n\n/// @title Intents Engine (IE)\n/// @notice Simple helper contract for turning transactional intents into executable code.\n/// @dev V1 simulates typical commands (sending and swapping tokens) and includes execution.\n/// IE also has a workflow to verify the intent of ERC4337 account userOps against calldata.\n/// @author nani.eth (https://github.com/NaniDAO/ie)\n/// @custom:version 1.2.0\ncontract IE {\n /// ======================= LIBRARY USAGE ======================= ///\n\n /// @dev Metadata reader library.\n using MetadataReaderLib for address;\n\n /// @dev Safe token transfer library.\n using SafeTransferLib for address;\n\n /// ======================= CUSTOM ERRORS ======================= ///\n\n /// @dev Bad math.\n error Overflow();\n\n /// @dev 0-liquidity.\n error InvalidSwap();\n\n /// @dev Invalid command.\n error InvalidSyntax();\n\n /// @dev Non-numeric character.\n error InvalidCharacter();\n\n /// @dev Insufficient swap output.\n error InsufficientSwap();\n\n /// =========================== EVENTS =========================== ///\n\n /// @dev Logs the registration of a token name.\n event NameSet(address indexed token, string name);\n\n /// @dev Logs the registration of a token swap pool pair route on Uniswap V3.\n event PairSet(address indexed token0, address indexed token1, address pair);\n\n /// ========================== STRUCTS ========================== ///\n\n /// @dev The ERC4337 user operation (userOp) struct.\n struct UserOperation {\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n uint256 callGasLimit;\n uint256 verificationGasLimit;\n uint256 preVerificationGas;\n uint256 maxFeePerGas;\n uint256 maxPriorityFeePerGas;\n bytes paymasterAndData;\n bytes signature;\n }\n\n /// @dev The packed ERC4337 userOp struct.\n struct PackedUserOperation {\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n bytes32 accountGasLimits;\n uint256 preVerificationGas;\n bytes32 gasFees;\n bytes paymasterAndData;\n bytes signature;\n }\n\n /// @dev The `swap` command information struct.\n struct SwapInfo {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n bool ETHIn;\n bool ETHOut;\n }\n\n /// @dev The `swap` pool liquidity struct.\n struct SwapLiq {\n address pool;\n uint256 liq;\n }\n\n /// ========================= CONSTANTS ========================= ///\n\n /// @dev The governing DAO address.\n address internal constant DAO = 0xDa000000000000d2885F108500803dfBAaB2f2aA;\n\n /// @dev The NANI token address.\n address internal constant NANI = 0x000000000000C6A645b0E51C9eCAA4CA580Ed8e8;\n\n /// @dev The conventional ERC7528 ETH address.\n address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n /// @dev The canonical wrapped ETH address.\n address internal constant WETH = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1;\n\n /// @dev The popular wrapped BTC address.\n address internal constant WBTC = 0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f;\n\n /// @dev The Circle USD stablecoin address.\n address internal constant USDC = 0xaf88d065e77c8cC2239327C5EDb3A432268e5831;\n\n /// @dev The Tether USD stablecoin address.\n address internal constant USDT = 0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9;\n\n /// @dev The Maker DAO USD stablecoin address.\n address internal constant DAI = 0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1;\n\n /// @dev The Arbitrum DAO governance token address.\n address internal constant ARB = 0x912CE59144191C1204E64559FE8253a0e49E6548;\n\n /// @dev The Lido Wrapped Staked ETH token address.\n address internal constant WSTETH = 0x5979D7b546E38E414F7E9822514be443A4800529;\n\n /// @dev The Rocket Pool Staked ETH token address.\n address internal constant RETH = 0xEC70Dcb4A1EFa46b8F2D97C310C9c4790ba5ffA8;\n\n /// @dev The address of the Uniswap V3 Factory.\n address internal constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;\n\n /// @dev The Uniswap V3 Pool `initcodehash`.\n bytes32 internal constant UNISWAP_V3_POOL_INIT_CODE_HASH =\n 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;\n\n /// @dev The minimum value that can be returned from `getSqrtRatioAtTick` (plus one).\n uint160 internal constant MIN_SQRT_RATIO_PLUS_ONE = 4295128740;\n\n /// @dev The maximum value that can be returned from `getSqrtRatioAtTick` (minus one).\n uint160 internal constant MAX_SQRT_RATIO_MINUS_ONE =\n 1461446703485210103287273052203988822378723970341;\n\n /// @dev The NAMI naming system on Arbitrum.\n INAMI internal constant NAMI = INAMI(0x000000006641B4C250AEA6B62A1e0067D300697a);\n\n /// ========================== STORAGE ========================== ///\n\n /// @dev DAO-governed token address naming.\n mapping(string name => address) public tokens;\n\n /// @dev DAO-governed token swap pool routing on Uniswap V3.\n mapping(address token0 => mapping(address token1 => address)) public pairs;\n\n /// ======================== CONSTRUCTOR ======================== ///\n\n /// @dev Constructs this IE on the Arbitrum L2 of Ethereum.\n constructor() payable {}\n\n /// ====================== COMMAND PREVIEW ====================== ///\n\n /// @dev Preview natural language smart contract command.\n /// The `send` syntax uses ENS naming: 'send vitalik 20 DAI'.\n /// `swap` syntax uses common format: 'swap 100 DAI for WETH'.\n function previewCommand(string calldata intent)\n public\n view\n virtual\n returns (\n address to, // Receiver address.\n uint256 amount, // Formatted amount.\n uint256 minAmountOut, // Formatted amount.\n address token, // Asset to send `to`.\n bytes memory callData, // Raw calldata for send transaction.\n bytes memory executeCallData // Anticipates common execute API.\n )\n {\n string memory normalized = _lowercase(intent);\n bytes32 action = _extraction(normalized);\n if (action == \"send\" || action == \"transfer\" || action == \"pay\" || action == \"grant\") {\n (string memory _to, string memory _amount, string memory _token) =\n _extractSend(normalized);\n (to, amount, token, callData, executeCallData) = previewSend(_to, _amount, _token);\n } else if (\n action == \"swap\" || action == \"exchange\" || action == \"stake\" || action == \"deposit\"\n || action == \"unstake\" || action == \"withdraw\"\n ) {\n (\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n ) = _extractSwap(normalized);\n (amount, minAmountOut, token, to) =\n previewSwap(amountIn, amountOutMinimum, tokenIn, tokenOut);\n } else {\n revert InvalidSyntax(); // Invalid command format.\n }\n }\n\n /// @dev Previews a `send` command from the parts of a matched intent string.\n function previewSend(string memory to, string memory amount, string memory token)\n public\n view\n virtual\n returns (\n address _to,\n uint256 _amount,\n address _token,\n bytes memory callData,\n bytes memory executeCallData\n )\n {\n uint256 decimals;\n (_token, decimals) = _returnTokenConstants(bytes32(bytes(token)));\n if (_token == address(0)) _token = tokens[token]; // Check storage.\n bool isETH = _token == ETH; // Memo whether the token is ETH or not.\n (, _to,) = whatIsTheAddressOf(to); // Fetch receiver address from ENS.\n _amount = _toUint(amount, decimals != 0 ? decimals : _token.readDecimals());\n if (!isETH) callData = abi.encodeCall(IToken.transfer, (_to, _amount));\n executeCallData =\n abi.encodeCall(IExecutor.execute, (isETH ? _to : _token, isETH ? _amount : 0, callData));\n }\n\n /// @dev Previews a `swap` command from the parts of a matched intent string.\n function previewSwap(\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n )\n public\n view\n virtual\n returns (uint256 _amountIn, uint256 _amountOut, address _tokenIn, address _tokenOut)\n {\n uint256 decimalsIn;\n uint256 decimalsOut;\n (_tokenIn, decimalsIn) = _returnTokenConstants(bytes32(bytes(tokenIn)));\n if (_tokenIn == address(0)) _tokenIn = tokens[tokenIn];\n (_tokenOut, decimalsOut) = _returnTokenConstants(bytes32(bytes(tokenOut)));\n if (_tokenOut == address(0)) _tokenOut = tokens[tokenOut];\n _amountIn = _toUint(amountIn, decimalsIn != 0 ? decimalsIn : _tokenIn.readDecimals());\n _amountOut =\n _toUint(amountOutMinimum, decimalsOut != 0 ? decimalsOut : _tokenOut.readDecimals());\n }\n\n /// @dev Checks ERC4337 userOp against the output of the command intent.\n function checkUserOp(string calldata intent, UserOperation calldata userOp)\n public\n view\n virtual\n returns (bool)\n {\n (,,,,, bytes memory executeCallData) = previewCommand(intent);\n if (executeCallData.length != userOp.callData.length) return false;\n return keccak256(executeCallData) == keccak256(userOp.callData);\n }\n\n /// @dev Checks packed ERC4337 userOp against the output of the command intent.\n function checkPackedUserOp(string calldata intent, PackedUserOperation calldata userOp)\n public\n view\n virtual\n returns (bool)\n {\n (,,,,, bytes memory executeCallData) = previewCommand(intent);\n if (executeCallData.length != userOp.callData.length) return false;\n return keccak256(executeCallData) == keccak256(userOp.callData);\n }\n\n /// @dev Checks and returns the canonical token address constant for a matched intent string.\n function _returnTokenConstants(bytes32 token)\n internal\n pure\n virtual\n returns (address _token, uint256 _decimals)\n {\n if (token == \"eth\" || token == \"ether\") return (ETH, 18);\n if (token == \"usdc\") return (USDC, 6);\n if (token == \"usdt\" || token == \"tether\") return (USDT, 6);\n if (token == \"dai\") return (DAI, 18);\n if (token == \"arb\" || token == \"arbitrum\") return (ARB, 18);\n if (token == \"weth\") return (WETH, 18);\n if (token == \"wbtc\" || token == \"btc\" || token == \"bitcoin\") return (WBTC, 8);\n if (token == \"steth\" || token == \"wsteth\" || token == \"lido\") return (WSTETH, 18);\n if (token == \"reth\") return (RETH, 18);\n if (token == \"nani\") return (NANI, 18);\n }\n\n /// @dev Checks and returns popular pool pairs for WETH swaps.\n function _returnPoolConstants(address token0, address token1)\n internal\n pure\n virtual\n returns (address pool)\n {\n if (token0 == WSTETH && token1 == WETH) return 0x35218a1cbaC5Bbc3E57fd9Bd38219D37571b3537;\n if (token0 == WETH && token1 == RETH) return 0x09ba302A3f5ad2bF8853266e271b005A5b3716fe;\n if (token0 == WETH && token1 == USDC) return 0xC6962004f452bE9203591991D15f6b388e09E8D0;\n if (token0 == WETH && token1 == USDT) return 0x641C00A822e8b671738d32a431a4Fb6074E5c79d;\n if (token0 == WETH && token1 == DAI) return 0xA961F0473dA4864C5eD28e00FcC53a3AAb056c1b;\n if (token0 == WETH && token1 == ARB) return 0xC6F780497A95e246EB9449f5e4770916DCd6396A;\n if (token0 == WBTC && token1 == WETH) return 0x2f5e87C9312fa29aed5c179E456625D79015299c;\n }\n\n /// ===================== COMMAND EXECUTION ===================== ///\n\n /// @dev Executes a text command from an intent string.\n function command(string calldata intent) public payable virtual {\n string memory normalized = _lowercase(intent);\n bytes32 action = _extraction(normalized);\n if (action == \"send\" || action == \"transfer\" || action == \"pay\" || action == \"grant\") {\n (string memory to, string memory amount, string memory token) = _extractSend(normalized);\n send(to, amount, token);\n } else if (\n action == \"swap\" || action == \"exchange\" || action == \"stake\" || action == \"deposit\"\n || action == \"unstake\" || action == \"withdraw\"\n ) {\n (\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n ) = _extractSwap(normalized);\n swap(amountIn, amountOutMinimum, tokenIn, tokenOut);\n } else {\n revert InvalidSyntax(); // Invalid command format.\n }\n }\n\n /// @dev Executes a `send` command from the parts of a matched intent string.\n function send(string memory to, string memory amount, string memory token)\n public\n payable\n virtual\n {\n (address _token, uint256 decimals) = _returnTokenConstants(bytes32(bytes(token)));\n if (_token == address(0)) _token = tokens[token];\n (, address _to,) = whatIsTheAddressOf(to);\n if (_token == ETH) {\n _to.safeTransferETH(_toUint(amount, decimals));\n } else {\n _token.safeTransferFrom(\n msg.sender, _to, _toUint(amount, decimals != 0 ? decimals : _token.readDecimals())\n );\n }\n }\n\n /// @dev Executes a `swap` command from the parts of a matched intent string.\n function swap(\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n ) public payable virtual {\n SwapInfo memory info;\n uint256 decimalsIn;\n uint256 decimalsOut;\n (info.tokenIn, decimalsIn) = _returnTokenConstants(bytes32(bytes(tokenIn)));\n if (info.tokenIn == address(0)) info.tokenIn = tokens[tokenIn];\n (info.tokenOut, decimalsOut) = _returnTokenConstants(bytes32(bytes(tokenOut)));\n if (info.tokenOut == address(0)) info.tokenOut = tokens[tokenOut];\n info.ETHIn = info.tokenIn == ETH;\n if (info.ETHIn) info.tokenIn = WETH;\n info.ETHOut = info.tokenOut == ETH;\n if (info.ETHOut) info.tokenOut = WETH;\n info.amountIn =\n _toUint(amountIn, decimalsIn != 0 ? decimalsIn : info.tokenIn.readDecimals());\n if (info.amountIn >= 1 << 255) revert Overflow();\n (address pool, bool zeroForOne) = _computePoolAddress(info.tokenIn, info.tokenOut);\n (int256 amount0, int256 amount1) = ISwapRouter(pool).swap(\n !info.ETHOut ? msg.sender : address(this),\n zeroForOne,\n int256(info.amountIn),\n zeroForOne ? MIN_SQRT_RATIO_PLUS_ONE : MAX_SQRT_RATIO_MINUS_ONE,\n abi.encodePacked(info.ETHIn, info.ETHOut, msg.sender, info.tokenIn, info.tokenOut)\n );\n if (\n uint256(-(zeroForOne ? amount1 : amount0))\n < _toUint(\n amountOutMinimum, decimalsOut != 0 ? decimalsOut : info.tokenOut.readDecimals()\n )\n ) revert InsufficientSwap();\n }\n\n /// @dev Fallback `uniswapV3SwapCallback`.\n /// If ETH is swapped, WETH is forwarded.\n fallback() external payable virtual {\n int256 amount0Delta;\n int256 amount1Delta;\n bool ETHIn;\n bool ETHOut;\n address payer;\n address tokenIn;\n address tokenOut;\n assembly (\"memory-safe\") {\n amount0Delta := calldataload(0x4)\n amount1Delta := calldataload(0x24)\n ETHIn := byte(0, calldataload(0x84))\n ETHOut := byte(0, calldataload(add(0x84, 1)))\n payer := shr(96, calldataload(add(0x84, 2)))\n tokenIn := shr(96, calldataload(add(0x84, 22)))\n tokenOut := shr(96, calldataload(add(0x84, 42)))\n }\n if (amount0Delta <= 0 && amount1Delta <= 0) revert InvalidSwap();\n (address pool, bool zeroForOne) = _computePoolAddress(tokenIn, tokenOut);\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), pool)) { revert(codesize(), 0x00) }\n }\n if (ETHIn) {\n _wrapETH(uint256(zeroForOne ? amount0Delta : amount1Delta));\n } else {\n tokenIn.safeTransferFrom(\n payer, msg.sender, uint256(zeroForOne ? amount0Delta : amount1Delta)\n );\n }\n if (ETHOut) {\n uint256 amount = uint256(-(zeroForOne ? amount1Delta : amount0Delta));\n _unwrapETH(amount);\n payer.safeTransferETH(amount);\n }\n }\n\n /// @dev Computes the create2 address for given token pair.\n /// note: This process checks all available pools for price.\n function _computePoolAddress(address tokenA, address tokenB)\n internal\n view\n virtual\n returns (address pool, bool zeroForOne)\n {\n if (tokenA < tokenB) zeroForOne = true;\n else (tokenA, tokenB) = (tokenB, tokenA);\n pool = _returnPoolConstants(tokenA, tokenB);\n if (pool == address(0)) {\n pool = pairs[tokenA][tokenB];\n if (pool == address(0)) {\n address pool100 = _computePairHash(tokenA, tokenB, 100); // Lowest fee.\n address pool500 = _computePairHash(tokenA, tokenB, 500); // Lower fee.\n address pool3000 = _computePairHash(tokenA, tokenB, 3000); // Mid fee.\n address pool10000 = _computePairHash(tokenA, tokenB, 10000); // Hi fee.\n // Initialize an array to hold the liquidity information for each pool.\n SwapLiq[5] memory pools = [\n SwapLiq(pool100, pool100.code.length != 0 ? _balanceOf(tokenA, pool100) : 0),\n SwapLiq(pool500, pool500.code.length != 0 ? _balanceOf(tokenA, pool500) : 0),\n SwapLiq(pool3000, pool3000.code.length != 0 ? _balanceOf(tokenA, pool3000) : 0),\n SwapLiq(pool10000, pool10000.code.length != 0 ? _balanceOf(tokenA, pool10000) : 0),\n SwapLiq(pool, 0) // Placeholder for top pool. This will hold outputs for comparison.\n ];\n // Iterate through the array to find the top pool with the highest liquidity in `tokenA`.\n for (uint256 i; i != 4; ++i) {\n if (pools[i].liq > pools[4].liq) {\n pools[4].liq = pools[i].liq;\n pools[4].pool = pools[i].pool;\n }\n }\n pool = pools[4].pool; // Return the top pool with likely best liquidity.\n }\n }\n }\n\n /// @dev Computes the create2 deployment hash for a given token pair.\n function _computePairHash(address token0, address token1, uint24 fee)\n internal\n pure\n virtual\n returns (address pool)\n {\n bytes32 salt = keccak256(abi.encode(token0, token1, fee));\n assembly (\"memory-safe\") {\n mstore8(0x00, 0xff) // Write the prefix.\n mstore(0x35, UNISWAP_V3_POOL_INIT_CODE_HASH)\n mstore(0x01, shl(96, UNISWAP_V3_FACTORY))\n mstore(0x15, salt)\n pool := keccak256(0x00, 0x55)\n mstore(0x35, 0) // Restore overwritten.\n }\n }\n\n /// @dev Wraps an `amount` of ETH to WETH and funds pool caller for swap.\n function _wrapETH(uint256 amount) internal virtual {\n assembly (\"memory-safe\") {\n pop(call(gas(), WETH, amount, codesize(), 0x00, codesize(), 0x00))\n mstore(0x14, caller()) // Store the `pool` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n pop(call(gas(), WETH, 0, 0x10, 0x44, codesize(), 0x00))\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Unwraps an `amount` of ETH from WETH for return.\n function _unwrapETH(uint256 amount) internal virtual {\n assembly (\"memory-safe\") {\n mstore(0x00, 0x2e1a7d4d) // `withdraw(uint256)`.\n mstore(0x20, amount) // Store the `amount` argument.\n pop(call(gas(), WETH, 0, 0x1c, 0x24, codesize(), 0x00))\n }\n }\n\n /// @dev Returns the amount of ERC20 `token` owned by `account`.\n function _balanceOf(address token, address account)\n internal\n view\n virtual\n returns (uint256 amount)\n {\n assembly (\"memory-safe\") {\n mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.\n mstore(0x14, account) // Store the `account` argument.\n pop(staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20))\n amount := mload(0x20)\n }\n }\n\n /// @dev ETH receiver fallback.\n /// Only canonical WETH can call.\n receive() external payable virtual {\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), WETH)) { revert(codesize(), 0x00) }\n }\n }\n\n /// ================== BALANCE & SUPPLY HELPERS ================== ///\n\n /// @dev Returns the balance of a named account in a named token.\n function whatIsTheBalanceOf(string calldata name, /*(bob)*/ /*in*/ string calldata token)\n public\n view\n virtual\n returns (uint256 balance, uint256 balanceAdjusted)\n {\n (, address _name,) = whatIsTheAddressOf(name);\n (address _token, uint256 decimals) =\n _returnTokenConstants(bytes32(bytes(_lowercase(token))));\n if (_token == address(0)) _token = tokens[token];\n balance = _token == ETH ? _name.balance : _token.balanceOf(_name);\n balanceAdjusted = balance / 10 ** (decimals != 0 ? decimals : _token.readDecimals());\n }\n\n /// @dev Returns the total supply of a named token.\n function whatIsTheTotalSupplyOf(string calldata token)\n public\n view\n virtual\n returns (uint256 supply, uint256 supplyAdjusted)\n {\n (address _token, uint256 decimals) =\n _returnTokenConstants(bytes32(bytes(_lowercase(token))));\n if (_token == address(0)) _token = tokens[token];\n assembly (\"memory-safe\") {\n mstore(0x00, 0x18160ddd) // `totalSupply()`.\n if iszero(staticcall(gas(), _token, 0x1c, 0x04, 0x20, 0x20)) {\n revert(codesize(), 0x00)\n }\n supply := mload(0x20)\n }\n supplyAdjusted = supply / 10 ** (decimals != 0 ? decimals : _token.readDecimals());\n }\n\n /// ====================== ENS VERIFICATION ====================== ///\n\n /// @dev Returns ENS name ownership details.\n function whatIsTheAddressOf(string memory name)\n public\n view\n virtual\n returns (address owner, address receiver, bytes32 node)\n {\n // If address length, convert.\n if (bytes(name).length == 42) {\n receiver = _toAddress(name);\n } else {\n (owner, receiver, node) = NAMI.whatIsTheAddressOf(name);\n }\n }\n\n /// ========================= GOVERNANCE ========================= ///\n\n /// @dev Sets a public `name` tag for a given `token` address. Governed by DAO.\n function setName(address token, string calldata name) public payable virtual {\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), DAO)) { revert(codesize(), 0x00) } // Optimized for repeat.\n }\n string memory normalized = _lowercase(name);\n emit NameSet(tokens[normalized] = token, normalized);\n }\n\n /// @dev Sets a public name and ticker for a given `token` address.\n function setNameAndTicker(address token) public payable virtual {\n string memory normalizedName = _lowercase(token.readName());\n string memory normalizedSymbol = _lowercase(token.readSymbol());\n emit NameSet(tokens[normalizedName] = token, normalizedName);\n emit NameSet(tokens[normalizedSymbol] = token, normalizedSymbol);\n }\n\n /// @dev Sets a public pool `pair` for swapping. Governed by DAO.\n function setPair(address tokenA, address tokenB, address pair) public payable virtual {\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), DAO)) { revert(codesize(), 0x00) } // Optimized for repeat.\n }\n if (tokenB < tokenA) (tokenA, tokenB) = (tokenB, tokenA);\n emit PairSet(tokenA, tokenB, pairs[tokenA][tokenB] = pair);\n }\n\n /// ===================== STRING OPERATIONS ===================== ///\n\n /// @dev Returns copy of string in lowercase.\n /// Modified from Solady LibString `toCase`.\n function _lowercase(string memory subject)\n internal\n pure\n virtual\n returns (string memory result)\n {\n assembly (\"memory-safe\") {\n let length := mload(subject)\n if length {\n result := add(mload(0x40), 0x20)\n subject := add(subject, 1)\n let flags := shl(add(70, shl(5, 0)), 0x3ffffff)\n let w := not(0)\n for { let o := length } 1 {} {\n o := add(o, w)\n let b := and(0xff, mload(add(subject, o)))\n mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))\n if iszero(o) { break }\n }\n result := mload(0x40)\n mstore(result, length) // Store the length.\n let last := add(add(result, 0x20), length)\n mstore(last, 0) // Zeroize the slot after the string.\n mstore(0x40, add(last, 0x20)) // Allocate the memory.\n }\n }\n }\n\n /// @dev Extracts the first word (action) as bytes32.\n function _extraction(string memory normalizedIntent)\n internal\n pure\n virtual\n returns (bytes32 result)\n {\n assembly (\"memory-safe\") {\n let str := add(normalizedIntent, 0x20)\n for { let i } lt(i, 0x20) { i := add(i, 1) } {\n let char := byte(0, mload(add(str, i)))\n if eq(char, 0x20) { break }\n result := or(result, shl(sub(248, mul(i, 8)), char))\n }\n }\n }\n\n /// @dev Extract the key words of normalized `send` intent.\n function _extractSend(string memory normalizedIntent)\n internal\n pure\n virtual\n returns (string memory to, string memory amount, string memory token)\n {\n string[] memory parts = _split(normalizedIntent, \" \");\n if (parts.length == 4) return (parts[1], parts[2], parts[3]);\n if (parts.length == 5) return (parts[4], parts[1], parts[2]);\n else revert InvalidSyntax(); // Command is not formatted.\n }\n\n /// @dev Extract the key words of normalized `swap` intent.\n function _extractSwap(string memory normalizedIntent)\n internal\n pure\n virtual\n returns (\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n )\n {\n string[] memory parts = _split(normalizedIntent, \" \");\n if (parts.length == 5) return (parts[1], \"\", parts[2], parts[4]);\n if (parts.length == 6) return (parts[1], parts[4], parts[2], parts[5]);\n else revert InvalidSyntax(); // Command is not formatted.\n }\n\n /// @dev Split the intent into an array of words.\n function _split(string memory base, bytes1 delimiter)\n internal\n pure\n virtual\n returns (string[] memory parts)\n {\n unchecked {\n bytes memory baseBytes = bytes(base);\n uint256 count = 1;\n for (uint256 i; i != baseBytes.length; ++i) {\n if (baseBytes[i] == delimiter) {\n ++count;\n }\n }\n parts = new string[](count);\n uint256 partIndex;\n uint256 start;\n for (uint256 i; i <= baseBytes.length; ++i) {\n if (i == baseBytes.length || baseBytes[i] == delimiter) {\n bytes memory part = new bytes(i - start);\n for (uint256 j = start; j != i; ++j) {\n part[j - start] = baseBytes[j];\n }\n parts[partIndex] = string(part);\n ++partIndex;\n start = i + 1;\n }\n }\n }\n }\n\n /// @dev Convert string to decimalized numerical value.\n function _toUint(string memory s, uint256 decimals)\n internal\n pure\n virtual\n returns (uint256 result)\n {\n unchecked {\n bool hasDecimal;\n uint256 decimalPlaces;\n bytes memory b = bytes(s);\n for (uint256 i; i != b.length; ++i) {\n if (b[i] >= \"0\" && b[i] <= \"9\") {\n result = result * 10 + uint8(b[i]) - 48;\n if (hasDecimal) {\n ++decimalPlaces;\n if (decimalPlaces > decimals) break;\n }\n } else if (b[i] == \".\" && !hasDecimal) {\n hasDecimal = true;\n } else {\n revert InvalidCharacter();\n }\n }\n if (decimalPlaces < decimals) {\n result *= 10 ** (decimals - decimalPlaces);\n }\n }\n }\n\n /// @dev Converts a hexadecimal string to its `address` representation.\n /// Modified from Stack (https://ethereum.stackexchange.com/a/156916).\n function _toAddress(string memory s) internal pure virtual returns (address addr) {\n bytes memory _bytes = _hexStringToAddress(s);\n if (_bytes.length < 21) revert InvalidSyntax();\n assembly (\"memory-safe\") {\n addr := div(mload(add(add(_bytes, 0x20), 1)), 0x1000000000000000000000000)\n }\n }\n\n /// @dev Converts a hexadecimal string into its bytes representation.\n function _hexStringToAddress(string memory s) internal pure virtual returns (bytes memory r) {\n unchecked {\n bytes memory ss = bytes(s);\n if (ss.length % 2 != 0) revert InvalidSyntax(); // Length must be even.\n r = new bytes(ss.length / 2);\n for (uint256 i; i != ss.length / 2; ++i) {\n r[i] =\n bytes1(_fromHexChar(uint8(ss[2 * i])) * 16 + _fromHexChar(uint8(ss[2 * i + 1])));\n }\n }\n }\n\n /// @dev Converts a single hexadecimal character into its numerical value.\n function _fromHexChar(uint8 c) internal pure virtual returns (uint8 result) {\n unchecked {\n if (bytes1(c) >= bytes1(\"0\") && bytes1(c) <= bytes1(\"9\")) return c - uint8(bytes1(\"0\"));\n if (bytes1(c) >= bytes1(\"a\") && bytes1(c) <= bytes1(\"f\")) {\n return 10 + c - uint8(bytes1(\"a\"));\n }\n if (bytes1(c) >= bytes1(\"A\") && bytes1(c) <= bytes1(\"F\")) {\n return 10 + c - uint8(bytes1(\"A\"));\n }\n }\n }\n}\n\n/// @dev Simple token transfer interface.\ninterface IToken {\n function transfer(address, uint256) external returns (bool);\n}\n\n/// @notice Simple calldata executor interface.\ninterface IExecutor {\n function execute(address, uint256, bytes calldata) external payable returns (bytes memory);\n}\n\n/// @dev Simple NAMI names interface for resolving L2 ENS ownership.\ninterface INAMI {\n function whatIsTheAddressOf(string calldata)\n external\n view\n returns (address, address, bytes32);\n}\n\n/// @dev Simple Uniswap V3 swapping interface.\ninterface ISwapRouter {\n function swap(address, bool, int256, uint160, bytes calldata)\n external\n returns (int256, int256);\n}\n"},"lib/solady/src/utils/SafeTransferLib.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)\n///\n/// @dev Note:\n/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.\n/// - For ERC20s, this implementation won't check that a token has code,\n/// responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CUSTOM ERRORS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The ETH transfer has failed.\n error ETHTransferFailed();\n\n /// @dev The ERC20 `transferFrom` has failed.\n error TransferFromFailed();\n\n /// @dev The ERC20 `transfer` has failed.\n error TransferFailed();\n\n /// @dev The ERC20 `approve` has failed.\n error ApproveFailed();\n\n /// @dev The Permit2 operation has failed.\n error Permit2Failed();\n\n /// @dev The Permit2 amount must be less than `2**160 - 1`.\n error Permit2AmountOverflow();\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CONSTANTS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.\n uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;\n\n /// @dev Suggested gas stipend for contract receiving ETH to perform a few\n /// storage reads and writes, but low enough to prevent griefing.\n uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;\n\n /// @dev The unique EIP-712 domain domain separator for the DAI token contract.\n bytes32 internal constant DAI_DOMAIN_SEPARATOR =\n 0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;\n\n /// @dev The address for the WETH9 contract on Ethereum mainnet.\n address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n\n /// @dev The canonical Permit2 address.\n /// [Github](https://github.com/Uniswap/permit2)\n /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)\n address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* ETH OPERATIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.\n //\n // The regular variants:\n // - Forwards all remaining gas to the target.\n // - Reverts if the target reverts.\n // - Reverts if the current contract has insufficient balance.\n //\n // The force variants:\n // - Forwards with an optional gas stipend\n // (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).\n // - If the target reverts, or if the gas stipend is exhausted,\n // creates a temporary contract to force send the ETH via `SELFDESTRUCT`.\n // Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.\n // - Reverts if the current contract has insufficient balance.\n //\n // The try variants:\n // - Forwards with a mandatory gas stipend.\n // - Instead of reverting, returns whether the transfer succeeded.\n\n /// @dev Sends `amount` (in wei) ETH to `to`.\n function safeTransferETH(address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n }\n }\n\n /// @dev Sends all the ETH in the current contract to `to`.\n function safeTransferAllETH(address to) internal {\n /// @solidity memory-safe-assembly\n assembly {\n // Transfer all the ETH and check if it succeeded or not.\n if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n }\n }\n\n /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.\n function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if lt(selfbalance(), amount) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.\n function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.\n function forceSafeTransferETH(address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if lt(selfbalance(), amount) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.\n function forceSafeTransferAllETH(address to) internal {\n /// @solidity memory-safe-assembly\n assembly {\n // forgefmt: disable-next-item\n if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.\n function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)\n internal\n returns (bool success)\n {\n /// @solidity memory-safe-assembly\n assembly {\n success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)\n }\n }\n\n /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.\n function trySafeTransferAllETH(address to, uint256 gasStipend)\n internal\n returns (bool success)\n {\n /// @solidity memory-safe-assembly\n assembly {\n success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)\n }\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* ERC20 OPERATIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.\n /// Reverts upon failure.\n ///\n /// The `from` account must have at least `amount` approved for\n /// the current contract to manage.\n function safeTransferFrom(address token, address from, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40) // Cache the free memory pointer.\n mstore(0x60, amount) // Store the `amount` argument.\n mstore(0x40, to) // Store the `to` argument.\n mstore(0x2c, shl(96, from)) // Store the `from` argument.\n mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x7939f424) // `TransferFromFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x60, 0) // Restore the zero slot to zero.\n mstore(0x40, m) // Restore the free memory pointer.\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.\n ///\n /// The `from` account must have at least `amount` approved for the current contract to manage.\n function trySafeTransferFrom(address token, address from, address to, uint256 amount)\n internal\n returns (bool success)\n {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40) // Cache the free memory pointer.\n mstore(0x60, amount) // Store the `amount` argument.\n mstore(0x40, to) // Store the `to` argument.\n mstore(0x2c, shl(96, from)) // Store the `from` argument.\n mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.\n success :=\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)\n )\n mstore(0x60, 0) // Restore the zero slot to zero.\n mstore(0x40, m) // Restore the free memory pointer.\n }\n }\n\n /// @dev Sends all of ERC20 `token` from `from` to `to`.\n /// Reverts upon failure.\n ///\n /// The `from` account must have their entire balance approved for the current contract to manage.\n function safeTransferAllFrom(address token, address from, address to)\n internal\n returns (uint256 amount)\n {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40) // Cache the free memory pointer.\n mstore(0x40, to) // Store the `to` argument.\n mstore(0x2c, shl(96, from)) // Store the `from` argument.\n mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.\n // Read the balance, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)\n )\n ) {\n mstore(0x00, 0x7939f424) // `TransferFromFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.\n amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x7939f424) // `TransferFromFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x60, 0) // Restore the zero slot to zero.\n mstore(0x40, m) // Restore the free memory pointer.\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.\n /// Reverts upon failure.\n function safeTransfer(address token, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, to) // Store the `to` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Sends all of ERC20 `token` from the current contract to `to`.\n /// Reverts upon failure.\n function safeTransferAll(address token, address to) internal returns (uint256 amount) {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.\n mstore(0x20, address()) // Store the address of the current contract.\n // Read the balance, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)\n )\n ) {\n mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x14, to) // Store the `to` argument.\n amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.\n mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.\n /// Reverts upon failure.\n function safeApprove(address token, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, to) // Store the `to` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.\n // Perform the approval, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.\n /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,\n /// then retries the approval again (some tokens, e.g. USDT, requires this).\n /// Reverts upon failure.\n function safeApproveWithRetry(address token, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, to) // Store the `to` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.\n // Perform the approval, retrying upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x34, 0) // Store 0 for the `amount`.\n mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.\n pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.\n mstore(0x34, amount) // Store back the original `amount`.\n // Retry the approval, reverting upon failure.\n if iszero(\n and(\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.\n revert(0x1c, 0x04)\n }\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Returns the amount of ERC20 `token` owned by `account`.\n /// Returns zero if the `token` does not exist.\n function balanceOf(address token, address account) internal view returns (uint256 amount) {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, account) // Store the `account` argument.\n mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.\n amount :=\n mul( // The arguments of `mul` are evaluated from right to left.\n mload(0x20),\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)\n )\n )\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.\n /// If the initial attempt fails, try to use Permit2 to transfer the token.\n /// Reverts upon failure.\n ///\n /// The `from` account must have at least `amount` approved for the current contract to manage.\n function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {\n if (!trySafeTransferFrom(token, from, to, amount)) {\n permit2TransferFrom(token, from, to, amount);\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.\n /// Reverts upon failure.\n function permit2TransferFrom(address token, address from, address to, uint256 amount)\n internal\n {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40)\n mstore(add(m, 0x74), shr(96, shl(96, token)))\n mstore(add(m, 0x54), amount)\n mstore(add(m, 0x34), to)\n mstore(add(m, 0x20), shl(96, from))\n // `transferFrom(address,address,uint160,address)`.\n mstore(m, 0x36c78516000000000000000000000000)\n let p := PERMIT2\n let exists := eq(chainid(), 1)\n if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }\n if iszero(and(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), exists)) {\n mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.\n revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)\n }\n }\n }\n\n /// @dev Permit a user to spend a given amount of\n /// another user's tokens via native EIP-2612 permit if possible, falling\n /// back to Permit2 if native permit fails or is not implemented on the token.\n function permit2(\n address token,\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n bool success;\n /// @solidity memory-safe-assembly\n assembly {\n for {} shl(96, xor(token, WETH9)) {} {\n mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.\n // Gas stipend to limit gas burn for tokens that don't refund gas when\n // an non-existing function is called. 5K should be enough for a SLOAD.\n staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)\n )\n ) { break }\n // After here, we can be sure that token is a contract.\n let m := mload(0x40)\n mstore(add(m, 0x34), spender)\n mstore(add(m, 0x20), shl(96, owner))\n mstore(add(m, 0x74), deadline)\n if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {\n mstore(0x14, owner)\n mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.\n mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))\n mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.\n // `nonces` is already at `add(m, 0x54)`.\n // `1` is already stored at `add(m, 0x94)`.\n mstore(add(m, 0xb4), and(0xff, v))\n mstore(add(m, 0xd4), r)\n mstore(add(m, 0xf4), s)\n success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)\n break\n }\n mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.\n mstore(add(m, 0x54), amount)\n mstore(add(m, 0x94), and(0xff, v))\n mstore(add(m, 0xb4), r)\n mstore(add(m, 0xd4), s)\n success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)\n break\n }\n }\n if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);\n }\n\n /// @dev Simple permit on the Permit2 contract.\n function simplePermit2(\n address token,\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40)\n mstore(m, 0x927da105) // `allowance(address,address,address)`.\n {\n let addressMask := shr(96, not(0))\n mstore(add(m, 0x20), and(addressMask, owner))\n mstore(add(m, 0x40), and(addressMask, token))\n mstore(add(m, 0x60), and(addressMask, spender))\n mstore(add(m, 0xc0), and(addressMask, spender))\n }\n let p := mul(PERMIT2, iszero(shr(160, amount)))\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.\n staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)\n )\n ) {\n mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.\n revert(add(0x18, shl(2, iszero(p))), 0x04)\n }\n mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).\n // `owner` is already `add(m, 0x20)`.\n // `token` is already at `add(m, 0x40)`.\n mstore(add(m, 0x60), amount)\n mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.\n // `nonce` is already at `add(m, 0xa0)`.\n // `spender` is already at `add(m, 0xc0)`.\n mstore(add(m, 0xe0), deadline)\n mstore(add(m, 0x100), 0x100) // `signature` offset.\n mstore(add(m, 0x120), 0x41) // `signature` length.\n mstore(add(m, 0x140), r)\n mstore(add(m, 0x160), s)\n mstore(add(m, 0x180), shl(248, v))\n if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {\n mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.\n revert(0x1c, 0x04)\n }\n }\n }\n}\n"},"lib/solady/src/utils/MetadataReaderLib.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Library for reading contract metadata robustly.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MetadataReaderLib.sol)\nlibrary MetadataReaderLib {\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CONSTANTS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Default gas stipend for contract reads. High enough for most practical use cases\n /// (able to SLOAD about 1000 bytes of data), but low enough to prevent griefing.\n uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;\n\n /// @dev Default string byte length limit.\n uint256 internal constant STRING_LIMIT_DEFAULT = 1000;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* METADATA READING OPERATIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n // Best-effort string reading operations.\n // Should NOT revert as long as sufficient gas is provided.\n //\n // Performs the following in order:\n // 1. Returns the empty string for the following cases:\n // - Reverts.\n // - No returndata (e.g. function returns nothing, EOA).\n // - Returns empty string.\n // 2. Attempts to `abi.decode` the returndata into a string.\n // 3. With any remaining gas, scans the returndata from start to end for the\n // null byte '\\0', to interpret the returndata as a null-terminated string.\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"name()\"))`.\n function readName(address target) internal view returns (string memory) {\n return _string(target, _ptr(0x06fdde03), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"name()\"), limit)`.\n function readName(address target, uint256 limit) internal view returns (string memory) {\n return _string(target, _ptr(0x06fdde03), limit, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"name()\"), limit, gasStipend)`.\n function readName(address target, uint256 limit, uint256 gasStipend)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(0x06fdde03), limit, gasStipend);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"symbol()\"))`.\n function readSymbol(address target) internal view returns (string memory) {\n return _string(target, _ptr(0x95d89b41), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"symbol()\"), limit)`.\n function readSymbol(address target, uint256 limit) internal view returns (string memory) {\n return _string(target, _ptr(0x95d89b41), limit, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"symbol()\"), limit, gasStipend)`.\n function readSymbol(address target, uint256 limit, uint256 gasStipend)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(0x95d89b41), limit, gasStipend);\n }\n\n /// @dev Performs a best-effort string query on `target` with `data` as the calldata.\n /// The string will be truncated to `STRING_LIMIT_DEFAULT` (1000) bytes.\n function readString(address target, bytes memory data) internal view returns (string memory) {\n return _string(target, _ptr(data), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Performs a best-effort string query on `target` with `data` as the calldata.\n /// The string will be truncated to `limit` bytes.\n function readString(address target, bytes memory data, uint256 limit)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(data), limit, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Performs a best-effort string query on `target` with `data` as the calldata.\n /// The string will be truncated to `limit` bytes.\n function readString(address target, bytes memory data, uint256 limit, uint256 gasStipend)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(data), limit, gasStipend);\n }\n\n // Best-effort unsigned integer reading operations.\n // Should NOT revert as long as sufficient gas is provided.\n //\n // Performs the following in order:\n // 1. Attempts to `abi.decode` the result into a uint256\n // (equivalent across all Solidity uint types, downcast as needed).\n // 2. Returns zero for the following cases:\n // - Reverts.\n // - No returndata (e.g. function returns nothing, EOA).\n // - Returns zero.\n // - `abi.decode` failure.\n\n /// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature(\"decimal()\")))`.\n function readDecimals(address target) internal view returns (uint8) {\n return uint8(_uint(target, _ptr(0x313ce567), GAS_STIPEND_NO_GRIEF));\n }\n\n /// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature(\"decimal()\"), gasStipend))`.\n function readDecimals(address target, uint256 gasStipend) internal view returns (uint8) {\n return uint8(_uint(target, _ptr(0x313ce567), gasStipend));\n }\n\n /// @dev Performs a best-effort uint query on `target` with `data` as the calldata.\n function readUint(address target, bytes memory data) internal view returns (uint256) {\n return _uint(target, _ptr(data), GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Performs a best-effort uint query on `target` with `data` as the calldata.\n function readUint(address target, bytes memory data, uint256 gasStipend)\n internal\n view\n returns (uint256)\n {\n return _uint(target, _ptr(data), gasStipend);\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* PRIVATE HELPERS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Attempts to read and return a string at `target`.\n function _string(address target, bytes32 ptr, uint256 limit, uint256 gasStipend)\n private\n view\n returns (string memory result)\n {\n /// @solidity memory-safe-assembly\n assembly {\n function min(x_, y_) -> _z {\n _z := xor(x_, mul(xor(x_, y_), lt(y_, x_)))\n }\n for {} staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x00, 0x20) {} {\n let m := mload(0x40) // Grab the free memory pointer.\n let s := add(0x20, m) // Start of the string's bytes in memory.\n // Attempt to `abi.decode` if the returndatasize is greater or equal to 64.\n if iszero(lt(returndatasize(), 0x40)) {\n let o := mload(0x00) // Load the string's offset in the returndata.\n // If the string's offset is within bounds.\n if iszero(gt(o, sub(returndatasize(), 0x20))) {\n returndatacopy(m, o, 0x20) // Copy the string's length.\n // If the full string's end is within bounds.\n // Note: If the full string doesn't fit, the `abi.decode` must be aborted\n // for compliance purposes, regardless if the truncated string can fit.\n if iszero(gt(mload(m), sub(returndatasize(), add(o, 0x20)))) {\n let n := min(mload(m), limit) // Truncate if needed.\n mstore(m, n) // Overwrite the length.\n returndatacopy(s, add(o, 0x20), n) // Copy the string's bytes.\n mstore(add(s, n), 0) // Zeroize the slot after the string.\n mstore(0x40, add(0x20, add(s, n))) // Allocate memory for the string.\n result := m\n break\n }\n }\n }\n // Try interpreting as a null-terminated string.\n let n := min(returndatasize(), limit) // Truncate if needed.\n returndatacopy(s, 0, n) // Copy the string's bytes.\n mstore8(add(s, n), 0) // Place a '\\0' at the end.\n let i := s // Pointer to the next byte to scan.\n for {} byte(0, mload(i)) { i := add(i, 1) } {} // Scan for '\\0'.\n mstore(m, sub(i, s)) // Store the string's length.\n mstore(i, 0) // Zeroize the slot after the string.\n mstore(0x40, add(0x20, i)) // Allocate memory for the string.\n result := m\n break\n }\n }\n }\n\n /// @dev Attempts to read and return a uint at `target`.\n function _uint(address target, bytes32 ptr, uint256 gasStipend)\n private\n view\n returns (uint256 result)\n {\n /// @solidity memory-safe-assembly\n assembly {\n result :=\n mul(\n mload(0x20),\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x20, 0x20)\n )\n )\n }\n }\n\n /// @dev Casts the function selector `s` into a pointer.\n function _ptr(uint256 s) private pure returns (bytes32 result) {\n /// @solidity memory-safe-assembly\n assembly {\n // Layout the calldata in the scratch space for temporary usage.\n mstore(0x04, s) // Store the function selector.\n mstore(result, 4) // Store the length.\n }\n }\n\n /// @dev Casts the `data` into a pointer.\n function _ptr(bytes memory data) private pure returns (bytes32 result) {\n /// @solidity memory-safe-assembly\n assembly {\n result := data\n }\n }\n}\n"}},"settings":{"remappings":["ds-test/=lib/forge-std/lib/ds-test/src/","forge-std/=lib/forge-std/src/","solady/=lib/solady/src/"],"optimizer":{"enabled":true,"runs":9999999},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"cancun","viaIR":true,"libraries":{}}} +{"language":"Solidity","sources":{"src/IE.sol":{"content":"// ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘ ⌘\n// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.19;\n\nimport {SafeTransferLib} from \"../lib/solady/src/utils/SafeTransferLib.sol\";\nimport {MetadataReaderLib} from \"../lib/solady/src/utils/MetadataReaderLib.sol\";\n\n/// @title Intents Engine (IE)\n/// @notice Simple helper contract for turning transactional intents into executable code.\n/// @dev V1 simulates typical commands (sending and swapping tokens) and includes execution.\n/// IE also has a workflow to verify the intent of ERC4337 account userOps against calldata.\n/// @author nani.eth (https://github.com/NaniDAO/ie)\n/// @custom:version 1.3.0\ncontract IE {\n /// ======================= LIBRARY USAGE ======================= ///\n\n /// @dev Token transfer library.\n using SafeTransferLib for address;\n\n /// @dev Token metadata reader library.\n using MetadataReaderLib for address;\n\n /// ======================= CUSTOM ERRORS ======================= ///\n\n /// @dev Bad math.\n error Overflow();\n\n /// @dev 0-liquidity.\n error InvalidSwap();\n\n /// @dev Invalid command.\n error InvalidSyntax();\n\n /// @dev Non-numeric character.\n error InvalidCharacter();\n\n /// @dev Insufficient swap output.\n error InsufficientSwap();\n\n /// @dev Invalid selector for the given asset spend.\n error InvalidSelector();\n\n /// =========================== EVENTS =========================== ///\n\n /// @dev Logs the registration of a token name alias.\n event AliasSet(address indexed token, string name);\n\n /// @dev Logs the registration of a token swap pool pair route on Uniswap V3.\n event PairSet(address indexed token0, address indexed token1, address pair);\n\n /// ========================== STRUCTS ========================== ///\n\n /// @dev The ERC4337 user operation (userOp) struct.\n struct UserOperation {\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n uint256 callGasLimit;\n uint256 verificationGasLimit;\n uint256 preVerificationGas;\n uint256 maxFeePerGas;\n uint256 maxPriorityFeePerGas;\n bytes paymasterAndData;\n bytes signature;\n }\n\n /// @dev The packed ERC4337 userOp struct.\n struct PackedUserOperation {\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n bytes32 accountGasLimits;\n uint256 preVerificationGas;\n bytes32 gasFees;\n bytes paymasterAndData;\n bytes signature;\n }\n\n /// @dev The `swap` command information struct.\n struct SwapInfo {\n address tokenIn;\n address tokenOut;\n uint256 amountIn;\n bool ETHIn;\n bool ETHOut;\n }\n\n /// @dev The `swap` pool liquidity struct.\n struct SwapLiq {\n address pool;\n uint256 liq;\n }\n\n /// ========================= CONSTANTS ========================= ///\n\n /// @dev The governing DAO address.\n address internal constant DAO = 0xDa000000000000d2885F108500803dfBAaB2f2aA;\n\n /// @dev The onchain akashic library.\n address internal constant AKA = 0x000000000000394793B2Fe854281CeE09a98bdBC;\n\n /// @dev The NANI token address.\n address internal constant NANI = 0x000000000000C6A645b0E51C9eCAA4CA580Ed8e8;\n\n /// @dev The conventional ERC7528 ETH address.\n address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n /// @dev The canonical wrapped ETH address.\n address internal constant WETH = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1;\n\n /// @dev The popular wrapped BTC address.\n address internal constant WBTC = 0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f;\n\n /// @dev The Circle USD stablecoin address.\n address internal constant USDC = 0xaf88d065e77c8cC2239327C5EDb3A432268e5831;\n\n /// @dev The Tether USD stablecoin address.\n address internal constant USDT = 0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9;\n\n /// @dev The Maker DAO USD stablecoin address.\n address internal constant DAI = 0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1;\n\n /// @dev The Arbitrum DAO governance token address.\n address internal constant ARB = 0x912CE59144191C1204E64559FE8253a0e49E6548;\n\n /// @dev The Lido Wrapped Staked ETH token address.\n address internal constant WSTETH = 0x5979D7b546E38E414F7E9822514be443A4800529;\n\n /// @dev The Rocket Pool Staked ETH token address.\n address internal constant RETH = 0xEC70Dcb4A1EFa46b8F2D97C310C9c4790ba5ffA8;\n\n /// @dev The address of the Uniswap V3 Factory.\n address internal constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;\n\n /// @dev The Uniswap V3 Pool `initcodehash`.\n bytes32 internal constant UNISWAP_V3_POOL_INIT_CODE_HASH =\n 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;\n\n /// @dev The minimum value that can be returned from `getSqrtRatioAtTick` (plus one).\n uint160 internal constant MIN_SQRT_RATIO_PLUS_ONE = 4295128740;\n\n /// @dev The maximum value that can be returned from `getSqrtRatioAtTick` (minus one).\n uint160 internal constant MAX_SQRT_RATIO_MINUS_ONE =\n 1461446703485210103287273052203988822378723970341;\n\n /// ========================== STORAGE ========================== ///\n\n /// @dev DAO-governed NAMI naming system on Arbitrum.\n INAMI internal nami = INAMI(0x000000006641B4C250AEA6B62A1e0067D300697a);\n\n /// @dev DAO-governed token name aliasing.\n mapping(string name => address) public tokens;\n\n /// @dev DAO-governed token address name aliasing.\n mapping(address token => string name) public aliases;\n\n /// @dev DAO-governed token swap pool routing on Uniswap V3.\n mapping(address token0 => mapping(address token1 => address)) public pairs;\n\n /// ======================== CONSTRUCTOR ======================== ///\n\n /// @dev Constructs this IE on the Arbitrum L2 of Ethereum.\n constructor() payable {}\n\n /// ====================== COMMAND PREVIEW ====================== ///\n\n /// @dev Preview natural language smart contract command.\n /// The `send` syntax uses ENS naming: 'send vitalik 20 DAI'.\n /// `swap` syntax uses common format: 'swap 100 DAI for WETH'.\n function previewCommand(string calldata intent)\n public\n view\n virtual\n returns (\n address to, // Receiver address.\n uint256 amount, // Formatted amount.\n uint256 minAmountOut, // Formatted amount.\n address token, // Asset to send `to`.\n bytes memory callData, // Raw calldata for send transaction.\n bytes memory executeCallData // Anticipates common execute API.\n )\n {\n string memory normalized = _lowercase(intent);\n bytes32 action = _extraction(normalized);\n if (action == \"send\" || action == \"transfer\" || action == \"pay\" || action == \"grant\") {\n (string memory _to, string memory _amount, string memory _token) =\n _extractSend(normalized);\n (to, amount, token, callData, executeCallData) = previewSend(_to, _amount, _token);\n } else if (\n action == \"swap\" || action == \"sell\" || action == \"exchange\" || action == \"stake\"\n ) {\n (\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n ) = _extractSwap(normalized);\n (amount, minAmountOut, token, to) =\n previewSwap(amountIn, amountOutMinimum, tokenIn, tokenOut);\n } else {\n revert InvalidSyntax(); // Invalid command format.\n }\n }\n\n /// @dev Previews a `send` command from the parts of a matched intent string.\n function previewSend(string memory to, string memory amount, string memory token)\n public\n view\n virtual\n returns (\n address _to,\n uint256 _amount,\n address _token,\n bytes memory callData,\n bytes memory executeCallData\n )\n {\n uint256 decimals;\n (_token, decimals) = _returnTokenConstants(bytes32(bytes(token)));\n if (_token == address(0)) _token = tokens[token]; // Check storage.\n bool isETH = _token == ETH; // Memo whether the token is ETH or not.\n (, _to,) = whatIsTheAddressOf(to); // Fetch receiver address from ENS.\n _amount = _toUint(amount, decimals != 0 ? decimals : _token.readDecimals());\n if (!isETH) callData = abi.encodeCall(IToken.transfer, (_to, _amount));\n executeCallData =\n abi.encodeCall(IExecutor.execute, (isETH ? _to : _token, isETH ? _amount : 0, callData));\n }\n\n /// @dev Previews a `swap` command from the parts of a matched intent string.\n function previewSwap(\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n )\n public\n view\n virtual\n returns (uint256 _amountIn, uint256 _amountOut, address _tokenIn, address _tokenOut)\n {\n uint256 decimalsIn;\n uint256 decimalsOut;\n (_tokenIn, decimalsIn) = _returnTokenConstants(bytes32(bytes(tokenIn)));\n if (_tokenIn == address(0)) _tokenIn = tokens[tokenIn];\n (_tokenOut, decimalsOut) = _returnTokenConstants(bytes32(bytes(tokenOut)));\n if (_tokenOut == address(0)) _tokenOut = tokens[tokenOut];\n _amountIn = _toUint(amountIn, decimalsIn != 0 ? decimalsIn : _tokenIn.readDecimals());\n _amountOut =\n _toUint(amountOutMinimum, decimalsOut != 0 ? decimalsOut : _tokenOut.readDecimals());\n }\n\n /// @dev Checks ERC4337 userOp against the output of the command intent.\n function checkUserOp(string calldata intent, UserOperation calldata userOp)\n public\n view\n virtual\n returns (bool intentMatched)\n {\n (,,,,, bytes memory executeCallData) = previewCommand(intent);\n if (executeCallData.length != userOp.callData.length) return false;\n return keccak256(executeCallData) == keccak256(userOp.callData);\n }\n\n /// @dev Checks packed ERC4337 userOp against the output of the command intent.\n function checkPackedUserOp(string calldata intent, PackedUserOperation calldata userOp)\n public\n view\n virtual\n returns (bool intentMatched)\n {\n (,,,,, bytes memory executeCallData) = previewCommand(intent);\n if (executeCallData.length != userOp.callData.length) return false;\n return keccak256(executeCallData) == keccak256(userOp.callData);\n }\n\n /// @dev Checks and returns the canonical token address constant for a matched intent string.\n function _returnTokenConstants(bytes32 token)\n internal\n pure\n virtual\n returns (address _token, uint256 _decimals)\n {\n if (token == \"eth\" || token == \"ether\") return (ETH, 18);\n if (token == \"usdc\") return (USDC, 6);\n if (token == \"usdt\" || token == \"tether\") return (USDT, 6);\n if (token == \"dai\") return (DAI, 18);\n if (token == \"arb\" || token == \"arbitrum\") return (ARB, 18);\n if (token == \"weth\") return (WETH, 18);\n if (token == \"wbtc\" || token == \"btc\" || token == \"bitcoin\") return (WBTC, 8);\n if (token == \"steth\" || token == \"wsteth\" || token == \"lido\") return (WSTETH, 18);\n if (token == \"reth\") return (RETH, 18);\n if (token == \"nani\") return (NANI, 18);\n }\n\n /// @dev Checks and returns the canonical token string constant for a matched address.\n function _returnTokenAliasConstants(address token)\n internal\n pure\n virtual\n returns (string memory _token, uint256 _decimals)\n {\n if (token == USDC) return (\"USDC\", 6);\n if (token == USDT) return (\"USDT\", 6);\n if (token == DAI) return (\"DAI\", 18);\n if (token == ARB) return (\"ARB\", 18);\n if (token == WETH) return (\"WETH\", 18);\n if (token == WBTC) return (\"WBTC\", 8);\n if (token == WSTETH) return (\"WSTETH\", 18);\n if (token == RETH) return (\"RETH\", 18);\n if (token == NANI) return (\"NANI\", 18);\n }\n\n /// @dev Checks and returns popular pool pairs for WETH swaps.\n function _returnPoolConstants(address token0, address token1)\n internal\n pure\n virtual\n returns (address pool)\n {\n if (token0 == WSTETH && token1 == WETH) return 0x35218a1cbaC5Bbc3E57fd9Bd38219D37571b3537;\n if (token0 == WETH && token1 == RETH) return 0x09ba302A3f5ad2bF8853266e271b005A5b3716fe;\n if (token0 == WETH && token1 == USDC) return 0xC6962004f452bE9203591991D15f6b388e09E8D0;\n if (token0 == WETH && token1 == USDT) return 0x641C00A822e8b671738d32a431a4Fb6074E5c79d;\n if (token0 == WETH && token1 == DAI) return 0xA961F0473dA4864C5eD28e00FcC53a3AAb056c1b;\n if (token0 == WETH && token1 == ARB) return 0xC6F780497A95e246EB9449f5e4770916DCd6396A;\n if (token0 == WBTC && token1 == WETH) return 0x2f5e87C9312fa29aed5c179E456625D79015299c;\n }\n\n /// ===================== COMMAND EXECUTION ===================== ///\n\n /// @dev Executes a text command from an intent string.\n function command(string calldata intent) public payable virtual {\n string memory normalized = _lowercase(intent);\n bytes32 action = _extraction(normalized);\n if (action == \"send\" || action == \"transfer\" || action == \"pay\" || action == \"grant\") {\n (string memory to, string memory amount, string memory token) = _extractSend(normalized);\n send(to, amount, token);\n } else if (\n action == \"swap\" || action == \"sell\" || action == \"exchange\" || action == \"stake\"\n ) {\n (\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n ) = _extractSwap(normalized);\n swap(amountIn, amountOutMinimum, tokenIn, tokenOut);\n } else {\n revert InvalidSyntax(); // Invalid command format.\n }\n }\n\n /// @dev Executes a `send` command from the parts of a matched intent string.\n function send(string memory to, string memory amount, string memory token)\n public\n payable\n virtual\n {\n (address _token, uint256 decimals) = _returnTokenConstants(bytes32(bytes(token)));\n if (_token == address(0)) _token = tokens[token];\n (, address _to,) = whatIsTheAddressOf(to);\n if (_token == ETH) {\n _to.safeTransferETH(_toUint(amount, decimals));\n } else {\n _token.safeTransferFrom(\n msg.sender, _to, _toUint(amount, decimals != 0 ? decimals : _token.readDecimals())\n );\n }\n }\n\n /// @dev Executes a `swap` command from the parts of a matched intent string.\n function swap(\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n ) public payable virtual {\n SwapInfo memory info;\n uint256 decimalsIn;\n uint256 decimalsOut;\n (info.tokenIn, decimalsIn) = _returnTokenConstants(bytes32(bytes(tokenIn)));\n if (info.tokenIn == address(0)) info.tokenIn = tokens[tokenIn];\n (info.tokenOut, decimalsOut) = _returnTokenConstants(bytes32(bytes(tokenOut)));\n if (info.tokenOut == address(0)) info.tokenOut = tokens[tokenOut];\n info.ETHIn = info.tokenIn == ETH;\n if (info.ETHIn) info.tokenIn = WETH;\n info.ETHOut = info.tokenOut == ETH;\n if (info.ETHOut) info.tokenOut = WETH;\n info.amountIn =\n _toUint(amountIn, decimalsIn != 0 ? decimalsIn : info.tokenIn.readDecimals());\n if (info.amountIn >= 1 << 255) revert Overflow();\n (address pool, bool zeroForOne) = _computePoolAddress(info.tokenIn, info.tokenOut);\n (int256 amount0, int256 amount1) = ISwapRouter(pool).swap(\n !info.ETHOut ? msg.sender : address(this),\n zeroForOne,\n int256(info.amountIn),\n zeroForOne ? MIN_SQRT_RATIO_PLUS_ONE : MAX_SQRT_RATIO_MINUS_ONE,\n abi.encodePacked(info.ETHIn, info.ETHOut, msg.sender, info.tokenIn, info.tokenOut)\n );\n if (\n uint256(-(zeroForOne ? amount1 : amount0))\n < _toUint(\n amountOutMinimum, decimalsOut != 0 ? decimalsOut : info.tokenOut.readDecimals()\n )\n ) revert InsufficientSwap();\n }\n\n /// @dev Fallback `uniswapV3SwapCallback`.\n /// If ETH is swapped, WETH is forwarded.\n fallback() external payable virtual {\n int256 amount0Delta;\n int256 amount1Delta;\n bool ETHIn;\n bool ETHOut;\n address payer;\n address tokenIn;\n address tokenOut;\n assembly (\"memory-safe\") {\n amount0Delta := calldataload(0x4)\n amount1Delta := calldataload(0x24)\n ETHIn := byte(0, calldataload(0x84))\n ETHOut := byte(0, calldataload(add(0x84, 1)))\n payer := shr(96, calldataload(add(0x84, 2)))\n tokenIn := shr(96, calldataload(add(0x84, 22)))\n tokenOut := shr(96, calldataload(add(0x84, 42)))\n }\n if (amount0Delta <= 0 && amount1Delta <= 0) revert InvalidSwap();\n (address pool, bool zeroForOne) = _computePoolAddress(tokenIn, tokenOut);\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), pool)) { revert(codesize(), 0x00) }\n }\n if (ETHIn) {\n _wrapETH(uint256(zeroForOne ? amount0Delta : amount1Delta));\n } else {\n tokenIn.safeTransferFrom(\n payer, msg.sender, uint256(zeroForOne ? amount0Delta : amount1Delta)\n );\n }\n if (ETHOut) {\n uint256 amount = uint256(-(zeroForOne ? amount1Delta : amount0Delta));\n _unwrapETH(amount);\n payer.safeTransferETH(amount);\n }\n }\n\n /// @dev Computes the create2 address for given token pair.\n /// note: This process checks all available pools for price.\n function _computePoolAddress(address tokenA, address tokenB)\n internal\n view\n virtual\n returns (address pool, bool zeroForOne)\n {\n if (tokenA < tokenB) zeroForOne = true;\n else (tokenA, tokenB) = (tokenB, tokenA);\n pool = _returnPoolConstants(tokenA, tokenB);\n if (pool == address(0)) {\n pool = pairs[tokenA][tokenB];\n if (pool == address(0)) {\n address pool100 = _computePairHash(tokenA, tokenB, 100); // Lowest fee.\n address pool500 = _computePairHash(tokenA, tokenB, 500); // Lower fee.\n address pool3000 = _computePairHash(tokenA, tokenB, 3000); // Mid fee.\n address pool10000 = _computePairHash(tokenA, tokenB, 10000); // Hi fee.\n // Initialize an array to hold the liquidity information for each pool.\n SwapLiq[5] memory pools = [\n SwapLiq(pool100, pool100.code.length != 0 ? _balanceOf(tokenA, pool100) : 0),\n SwapLiq(pool500, pool500.code.length != 0 ? _balanceOf(tokenA, pool500) : 0),\n SwapLiq(pool3000, pool3000.code.length != 0 ? _balanceOf(tokenA, pool3000) : 0),\n SwapLiq(pool10000, pool10000.code.length != 0 ? _balanceOf(tokenA, pool10000) : 0),\n SwapLiq(pool, 0) // Placeholder for top pool. This will hold outputs for comparison.\n ];\n // Iterate through the array to find the top pool with the highest liquidity in `tokenA`.\n for (uint256 i; i != 4; ++i) {\n if (pools[i].liq > pools[4].liq) {\n pools[4].liq = pools[i].liq;\n pools[4].pool = pools[i].pool;\n }\n }\n pool = pools[4].pool; // Return the top pool with likely best liquidity.\n }\n }\n }\n\n /// @dev Computes the create2 deployment hash for a given token pair.\n function _computePairHash(address token0, address token1, uint24 fee)\n internal\n pure\n virtual\n returns (address pool)\n {\n bytes32 salt = keccak256(abi.encode(token0, token1, fee));\n assembly (\"memory-safe\") {\n mstore8(0x00, 0xff) // Write the prefix.\n mstore(0x35, UNISWAP_V3_POOL_INIT_CODE_HASH)\n mstore(0x01, shl(96, UNISWAP_V3_FACTORY))\n mstore(0x15, salt)\n pool := keccak256(0x00, 0x55)\n mstore(0x35, 0) // Restore overwritten.\n }\n }\n\n /// @dev Wraps an `amount` of ETH to WETH and funds pool caller for swap.\n function _wrapETH(uint256 amount) internal virtual {\n assembly (\"memory-safe\") {\n pop(call(gas(), WETH, amount, codesize(), 0x00, codesize(), 0x00))\n mstore(0x14, caller()) // Store the `pool` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n pop(call(gas(), WETH, 0, 0x10, 0x44, codesize(), 0x00))\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Unwraps an `amount` of ETH from WETH for return.\n function _unwrapETH(uint256 amount) internal virtual {\n assembly (\"memory-safe\") {\n mstore(0x00, 0x2e1a7d4d) // `withdraw(uint256)`.\n mstore(0x20, amount) // Store the `amount` argument.\n pop(call(gas(), WETH, 0, 0x1c, 0x24, codesize(), 0x00))\n }\n }\n\n /// @dev Returns the amount of ERC20 `token` owned by `account`.\n function _balanceOf(address token, address account)\n internal\n view\n virtual\n returns (uint256 amount)\n {\n assembly (\"memory-safe\") {\n mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.\n mstore(0x14, account) // Store the `account` argument.\n pop(staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20))\n amount := mload(0x20)\n }\n }\n\n /// @dev ETH receiver fallback.\n /// Only canonical WETH can call.\n receive() external payable virtual {\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), WETH)) { revert(codesize(), 0x00) }\n }\n }\n\n /// ==================== COMMAND TRANSLATION ==================== ///\n\n /// @dev Returns the akashic library summary digest `about` a given `topic`.\n function read(string calldata topic) public view virtual returns (string memory about) {\n return IE(payable(AKA)).read(topic);\n }\n\n /// @dev Translates an `intent` from raw `command()` calldata.\n function translateCommand(bytes calldata callData)\n public\n pure\n virtual\n returns (string memory intent)\n {\n return string(callData[4:]);\n }\n\n /// @dev Translates an `intent` for send action from the solution `callData` of standard `execute()`.\n /// note: The function selector technically doesn't need to be `execute()` but params should match.\n function translateExecute(bytes calldata callData)\n public\n view\n virtual\n returns (string memory intent)\n {\n unchecked {\n (address target, uint256 value) = abi.decode(callData[4:68], (address, uint256));\n\n if (value != 0) {\n return string(\n abi.encodePacked(\n \"send \",\n _convertWeiToString(value, 18),\n \" ETH to 0x\",\n _toAsciiString(target)\n )\n );\n }\n\n if (\n bytes4(callData[132:136]) != IToken.transfer.selector\n && bytes4(callData[132:136]) != IToken.approve.selector\n ) revert InvalidSelector();\n bool transfer = bytes4(callData[132:136]) == IToken.transfer.selector;\n\n (string memory token, uint256 decimals) = _returnTokenAliasConstants(target);\n if (bytes(token).length == 0) token = aliases[target];\n if (decimals == 0) decimals = target.readDecimals(); // Sanity check.\n (target, value) = abi.decode(callData[136:], (address, uint256));\n\n return string(\n abi.encodePacked(\n transfer ? \"send \" : \"approve \",\n _convertWeiToString(value, decimals),\n \" \",\n token,\n \" to 0x\",\n _toAsciiString(target)\n )\n );\n }\n }\n\n /// @dev Translates the `intent` for `token` send action from the solution `tokenCalldata`.\n /// note: Designed for EOAs and raw verification. Token alias is checked against storage.\n function translateTokenTransfer(address token, bytes calldata tokenCalldata)\n public\n view\n virtual\n returns (string memory intent)\n {\n unchecked {\n if (\n bytes4(tokenCalldata) != IToken.transfer.selector\n && bytes4(tokenCalldata) != IToken.approve.selector\n ) revert InvalidSelector();\n bool transfer = bytes4(tokenCalldata) == IToken.transfer.selector;\n (string memory tokenAlias, uint256 decimals) = _returnTokenAliasConstants(token);\n if (bytes(tokenAlias).length == 0) tokenAlias = aliases[token];\n if (decimals == 0) decimals = token.readDecimals(); // Sanity check.\n (address target, uint256 value) = abi.decode(tokenCalldata[4:], (address, uint256));\n\n return string(\n abi.encodePacked(\n transfer ? \"send \" : \"approve \",\n _convertWeiToString(value, decimals),\n \" \",\n tokenAlias,\n \" to 0x\",\n _toAsciiString(target)\n )\n );\n }\n }\n\n /// @dev Translate ERC4337 userOp `callData` into readable `intent`.\n function translateUserOp(UserOperation calldata userOp)\n public\n view\n virtual\n returns (string memory intent)\n {\n return bytes4(userOp.callData) == IExecutor.execute.selector\n ? translateExecute(userOp.callData)\n : translateCommand(userOp.callData);\n }\n\n /// @dev Translate packed ERC4337 userOp `callData` into readable `intent`.\n function translatePackedUserOp(PackedUserOperation calldata userOp)\n public\n view\n virtual\n returns (string memory intent)\n {\n return bytes4(userOp.callData) == IExecutor.execute.selector\n ? translateExecute(userOp.callData)\n : translateCommand(userOp.callData);\n }\n\n /// ================== BALANCE & SUPPLY HELPERS ================== ///\n\n /// @dev Returns resulting percentage change of ETH or token balance.\n function previewBalanceChange(address user, string calldata intent)\n public\n view\n virtual\n returns (uint256 percentage)\n {\n (, uint256 amount,, address token,,) = previewCommand(intent);\n return (amount * 100) / (token == ETH ? user.balance : _balanceOf(token, user));\n }\n\n /// @dev Returns the balance of a named account in a named token.\n function whatIsTheBalanceOf(string calldata name, /*(bob)*/ /*in*/ string calldata token)\n public\n view\n virtual\n returns (uint256 balance, uint256 balanceAdjusted)\n {\n (, address _name,) = whatIsTheAddressOf(name);\n (address _token, uint256 decimals) =\n _returnTokenConstants(bytes32(bytes(_lowercase(token))));\n if (_token == address(0)) _token = tokens[token];\n balance = _token == ETH ? _name.balance : _token.balanceOf(_name);\n balanceAdjusted = balance / 10 ** (decimals != 0 ? decimals : _token.readDecimals());\n }\n\n /// @dev Returns the total supply of a named token.\n function whatIsTheTotalSupplyOf(string calldata token)\n public\n view\n virtual\n returns (uint256 supply, uint256 supplyAdjusted)\n {\n (address _token, uint256 decimals) =\n _returnTokenConstants(bytes32(bytes(_lowercase(token))));\n if (_token == address(0)) _token = tokens[token];\n assembly (\"memory-safe\") {\n mstore(0x00, 0x18160ddd) // `totalSupply()`.\n if iszero(staticcall(gas(), _token, 0x1c, 0x04, 0x20, 0x20)) {\n revert(codesize(), 0x00)\n }\n supply := mload(0x20)\n }\n supplyAdjusted = supply / 10 ** (decimals != 0 ? decimals : _token.readDecimals());\n }\n\n /// ====================== ENS VERIFICATION ====================== ///\n\n /// @dev Returns ENS name ownership details.\n function whatIsTheAddressOf(string memory name)\n public\n view\n virtual\n returns (address owner, address receiver, bytes32 node)\n {\n // If address length, convert.\n if (bytes(name).length == 42) {\n receiver = _toAddress(name);\n } else {\n (owner, receiver, node) = nami.whatIsTheAddressOf(name);\n }\n }\n\n /// ========================= GOVERNANCE ========================= ///\n\n /// @dev Sets a public alias tag for a given `token` address. Governed by DAO.\n function setAlias(address token, string calldata _alias) public payable virtual {\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), DAO)) { revert(codesize(), 0x00) } // Optimized for repeat.\n }\n string memory normalized = _lowercase(_alias);\n aliases[token] = _alias;\n emit AliasSet(tokens[normalized] = token, normalized);\n }\n\n /// @dev Sets a public alias and ticker for a given `token` address.\n function setAliasAndTicker(address token) public payable virtual {\n string memory normalizedName = _lowercase(token.readName());\n string memory normalizedSymbol = _lowercase(token.readSymbol());\n aliases[token] = normalizedSymbol;\n emit AliasSet(tokens[normalizedName] = token, normalizedName);\n emit AliasSet(tokens[normalizedSymbol] = token, normalizedSymbol);\n }\n\n /// @dev Sets a public pool `pair` for swapping. Governed by DAO.\n function setPair(address tokenA, address tokenB, address pair) public payable virtual {\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), DAO)) { revert(codesize(), 0x00) } // Optimized for repeat.\n }\n if (tokenB < tokenA) (tokenA, tokenB) = (tokenB, tokenA);\n emit PairSet(tokenA, tokenB, pairs[tokenA][tokenB] = pair);\n }\n\n /// @dev Sets the Arbitrum naming singleton (NAMI). Governed by DAO.\n function setNAMI(INAMI NAMI) public payable virtual {\n assembly (\"memory-safe\") {\n if iszero(eq(caller(), DAO)) { revert(codesize(), 0x00) } // Optimized for repeat.\n }\n nami = NAMI; // No event emitted since very infrequent if ever.\n }\n\n /// ===================== STRING OPERATIONS ===================== ///\n\n /// @dev Returns copy of string in lowercase.\n /// Modified from Solady LibString `toCase`.\n function _lowercase(string memory subject)\n internal\n pure\n virtual\n returns (string memory result)\n {\n assembly (\"memory-safe\") {\n let length := mload(subject)\n if length {\n result := add(mload(0x40), 0x20)\n subject := add(subject, 1)\n let flags := shl(add(70, shl(5, 0)), 0x3ffffff)\n let w := not(0)\n for { let o := length } 1 {} {\n o := add(o, w)\n let b := and(0xff, mload(add(subject, o)))\n mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))\n if iszero(o) { break }\n }\n result := mload(0x40)\n mstore(result, length) // Store the length.\n let last := add(add(result, 0x20), length)\n mstore(last, 0) // Zeroize the slot after the string.\n mstore(0x40, add(last, 0x20)) // Allocate the memory.\n }\n }\n }\n\n /// @dev Extracts the first word (action) as bytes32.\n function _extraction(string memory normalizedIntent)\n internal\n pure\n virtual\n returns (bytes32 result)\n {\n assembly (\"memory-safe\") {\n let str := add(normalizedIntent, 0x20)\n for { let i } lt(i, 0x20) { i := add(i, 1) } {\n let char := byte(0, mload(add(str, i)))\n if eq(char, 0x20) { break }\n result := or(result, shl(sub(248, mul(i, 8)), char))\n }\n }\n }\n\n /// @dev Extract the key words of normalized `send` intent.\n function _extractSend(string memory normalizedIntent)\n internal\n pure\n virtual\n returns (string memory to, string memory amount, string memory token)\n {\n string[] memory parts = _split(normalizedIntent, \" \");\n if (parts.length == 4) return (parts[1], parts[2], parts[3]);\n if (parts.length == 5) return (parts[4], parts[1], parts[2]);\n else revert InvalidSyntax(); // Command is not formatted.\n }\n\n /// @dev Extract the key words of normalized `swap` intent.\n function _extractSwap(string memory normalizedIntent)\n internal\n pure\n virtual\n returns (\n string memory amountIn,\n string memory amountOutMinimum,\n string memory tokenIn,\n string memory tokenOut\n )\n {\n string[] memory parts = _split(normalizedIntent, \" \");\n if (parts.length == 5) return (parts[1], \"\", parts[2], parts[4]);\n if (parts.length == 6) return (parts[1], parts[4], parts[2], parts[5]);\n else revert InvalidSyntax(); // Command is not formatted.\n }\n\n /// @dev Split the intent into an array of words.\n function _split(string memory base, bytes1 delimiter)\n internal\n pure\n virtual\n returns (string[] memory parts)\n {\n unchecked {\n bytes memory baseBytes = bytes(base);\n uint256 count = 1;\n for (uint256 i; i != baseBytes.length; ++i) {\n if (baseBytes[i] == delimiter) {\n ++count;\n }\n }\n parts = new string[](count);\n uint256 partIndex;\n uint256 start;\n for (uint256 i; i <= baseBytes.length; ++i) {\n if (i == baseBytes.length || baseBytes[i] == delimiter) {\n bytes memory part = new bytes(i - start);\n for (uint256 j = start; j != i; ++j) {\n part[j - start] = baseBytes[j];\n }\n parts[partIndex] = string(part);\n ++partIndex;\n start = i + 1;\n }\n }\n }\n }\n\n /// @dev Convert string to decimalized numerical value.\n function _toUint(string memory s, uint256 decimals)\n internal\n pure\n virtual\n returns (uint256 result)\n {\n unchecked {\n bool hasDecimal;\n uint256 decimalPlaces;\n bytes memory b = bytes(s);\n for (uint256 i; i != b.length; ++i) {\n if (b[i] >= \"0\" && b[i] <= \"9\") {\n result = result * 10 + uint8(b[i]) - 48;\n if (hasDecimal) {\n ++decimalPlaces;\n if (decimalPlaces > decimals) break;\n }\n } else if (b[i] == \".\" && !hasDecimal) {\n hasDecimal = true;\n } else {\n revert InvalidCharacter();\n }\n }\n if (decimalPlaces < decimals) {\n result *= 10 ** (decimals - decimalPlaces);\n }\n }\n }\n\n /// @dev Converts a hexadecimal string to its `address` representation.\n /// Modified from Stack (https://ethereum.stackexchange.com/a/156916).\n function _toAddress(string memory s) internal pure virtual returns (address addr) {\n bytes memory _bytes = _hexStringToAddress(s);\n if (_bytes.length < 21) revert InvalidSyntax();\n assembly (\"memory-safe\") {\n addr := div(mload(add(add(_bytes, 0x20), 1)), 0x1000000000000000000000000)\n }\n }\n\n /// @dev Converts a hexadecimal string into its bytes representation.\n function _hexStringToAddress(string memory s) internal pure virtual returns (bytes memory r) {\n unchecked {\n bytes memory ss = bytes(s);\n if (ss.length % 2 != 0) revert InvalidSyntax(); // Length must be even.\n r = new bytes(ss.length / 2);\n for (uint256 i; i != ss.length / 2; ++i) {\n r[i] =\n bytes1(_fromHexChar(uint8(ss[2 * i])) * 16 + _fromHexChar(uint8(ss[2 * i + 1])));\n }\n }\n }\n\n /// @dev Converts a single hexadecimal character into its numerical value.\n function _fromHexChar(uint8 c) internal pure virtual returns (uint8 result) {\n unchecked {\n if (bytes1(c) >= bytes1(\"0\") && bytes1(c) <= bytes1(\"9\")) return c - uint8(bytes1(\"0\"));\n if (bytes1(c) >= bytes1(\"a\") && bytes1(c) <= bytes1(\"f\")) {\n return 10 + c - uint8(bytes1(\"a\"));\n }\n if (bytes1(c) >= bytes1(\"A\") && bytes1(c) <= bytes1(\"F\")) {\n return 10 + c - uint8(bytes1(\"A\"));\n }\n }\n }\n\n /// @dev Convert an address to an ASCII string representation.\n function _toAsciiString(address x) internal pure virtual returns (string memory) {\n unchecked {\n bytes memory s = new bytes(40);\n for (uint256 i; i < 20; ++i) {\n bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2 ** (8 * (19 - i)))));\n bytes1 hi = bytes1(uint8(b) / 16);\n bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));\n s[2 * i] = _char(hi);\n s[2 * i + 1] = _char(lo);\n }\n return string(s);\n }\n }\n\n /// @dev Convert a single byte to a character in the ASCII string.\n function _char(bytes1 b) internal pure virtual returns (bytes1 c) {\n unchecked {\n if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);\n else return bytes1(uint8(b) + 0x57);\n }\n }\n\n /// @dev Convert number to string and insert decimal point.\n function _convertWeiToString(uint256 weiAmount, uint256 decimals)\n internal\n pure\n virtual\n returns (string memory)\n {\n unchecked {\n uint256 scalingFactor = 10 ** decimals;\n\n string memory wholeNumberStr = _toString(weiAmount / scalingFactor);\n string memory decimalPartStr = _toString(weiAmount % scalingFactor);\n\n while (bytes(decimalPartStr).length != decimals) {\n decimalPartStr = string(abi.encodePacked(\"0\", decimalPartStr));\n }\n\n decimalPartStr = _removeTrailingZeros(decimalPartStr);\n\n if (bytes(decimalPartStr).length == 0) {\n return wholeNumberStr;\n }\n\n return string(abi.encodePacked(wholeNumberStr, \".\", decimalPartStr));\n }\n }\n\n /// @dev Remove any trailing zeroes from string.\n function _removeTrailingZeros(string memory str)\n internal\n pure\n virtual\n returns (string memory)\n {\n unchecked {\n bytes memory strBytes = bytes(str);\n uint256 end = strBytes.length;\n\n while (end != 0 && strBytes[end - 1] == \"0\") {\n --end;\n }\n\n bytes memory trimmedBytes = new bytes(end);\n for (uint256 i; i != end; ++i) {\n trimmedBytes[i] = strBytes[i];\n }\n\n return string(trimmedBytes);\n }\n }\n\n /// @dev Returns the base 10 decimal representation of `value`.\n /// Modified from (https://github.com/Vectorized/solady/blob/main/src/utils/LibString.sol)\n function _toString(uint256 value) internal pure virtual returns (string memory str) {\n assembly (\"memory-safe\") {\n str := add(mload(0x40), 0x80)\n mstore(0x40, add(str, 0x20))\n mstore(str, 0)\n let end := str\n let w := not(0)\n for { let temp := value } 1 {} {\n str := add(str, w)\n mstore8(str, add(48, mod(temp, 10)))\n temp := div(temp, 10)\n if iszero(temp) { break }\n }\n let length := sub(end, str)\n str := sub(str, 0x20)\n mstore(str, length)\n }\n }\n}\n\n/// @dev Simple token handler interface.\ninterface IToken {\n function approve(address, uint256) external returns (bool);\n function transfer(address, uint256) external returns (bool);\n}\n\n/// @notice Simple calldata executor interface.\ninterface IExecutor {\n function execute(address, uint256, bytes calldata) external payable returns (bytes memory);\n}\n\n/// @dev Simple NAMI names interface for resolving L2 ENS ownership.\ninterface INAMI {\n function whatIsTheAddressOf(string calldata)\n external\n view\n returns (address, address, bytes32);\n}\n\n/// @dev Simple Uniswap V3 swapping interface.\ninterface ISwapRouter {\n function swap(address, bool, int256, uint160, bytes calldata)\n external\n returns (int256, int256);\n}\n"},"lib/solady/src/utils/SafeTransferLib.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)\n///\n/// @dev Note:\n/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.\n/// - For ERC20s, this implementation won't check that a token has code,\n/// responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CUSTOM ERRORS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The ETH transfer has failed.\n error ETHTransferFailed();\n\n /// @dev The ERC20 `transferFrom` has failed.\n error TransferFromFailed();\n\n /// @dev The ERC20 `transfer` has failed.\n error TransferFailed();\n\n /// @dev The ERC20 `approve` has failed.\n error ApproveFailed();\n\n /// @dev The Permit2 operation has failed.\n error Permit2Failed();\n\n /// @dev The Permit2 amount must be less than `2**160 - 1`.\n error Permit2AmountOverflow();\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CONSTANTS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.\n uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;\n\n /// @dev Suggested gas stipend for contract receiving ETH to perform a few\n /// storage reads and writes, but low enough to prevent griefing.\n uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;\n\n /// @dev The unique EIP-712 domain domain separator for the DAI token contract.\n bytes32 internal constant DAI_DOMAIN_SEPARATOR =\n 0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;\n\n /// @dev The address for the WETH9 contract on Ethereum mainnet.\n address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n\n /// @dev The canonical Permit2 address.\n /// [Github](https://github.com/Uniswap/permit2)\n /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)\n address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* ETH OPERATIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.\n //\n // The regular variants:\n // - Forwards all remaining gas to the target.\n // - Reverts if the target reverts.\n // - Reverts if the current contract has insufficient balance.\n //\n // The force variants:\n // - Forwards with an optional gas stipend\n // (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).\n // - If the target reverts, or if the gas stipend is exhausted,\n // creates a temporary contract to force send the ETH via `SELFDESTRUCT`.\n // Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.\n // - Reverts if the current contract has insufficient balance.\n //\n // The try variants:\n // - Forwards with a mandatory gas stipend.\n // - Instead of reverting, returns whether the transfer succeeded.\n\n /// @dev Sends `amount` (in wei) ETH to `to`.\n function safeTransferETH(address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n }\n }\n\n /// @dev Sends all the ETH in the current contract to `to`.\n function safeTransferAllETH(address to) internal {\n /// @solidity memory-safe-assembly\n assembly {\n // Transfer all the ETH and check if it succeeded or not.\n if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n }\n }\n\n /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.\n function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if lt(selfbalance(), amount) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.\n function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.\n function forceSafeTransferETH(address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n if lt(selfbalance(), amount) {\n mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.\n revert(0x1c, 0x04)\n }\n if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.\n function forceSafeTransferAllETH(address to) internal {\n /// @solidity memory-safe-assembly\n assembly {\n // forgefmt: disable-next-item\n if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {\n mstore(0x00, to) // Store the address in scratch space.\n mstore8(0x0b, 0x73) // Opcode `PUSH20`.\n mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.\n if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.\n }\n }\n }\n\n /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.\n function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)\n internal\n returns (bool success)\n {\n /// @solidity memory-safe-assembly\n assembly {\n success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)\n }\n }\n\n /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.\n function trySafeTransferAllETH(address to, uint256 gasStipend)\n internal\n returns (bool success)\n {\n /// @solidity memory-safe-assembly\n assembly {\n success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)\n }\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* ERC20 OPERATIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.\n /// Reverts upon failure.\n ///\n /// The `from` account must have at least `amount` approved for\n /// the current contract to manage.\n function safeTransferFrom(address token, address from, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40) // Cache the free memory pointer.\n mstore(0x60, amount) // Store the `amount` argument.\n mstore(0x40, to) // Store the `to` argument.\n mstore(0x2c, shl(96, from)) // Store the `from` argument.\n mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x7939f424) // `TransferFromFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x60, 0) // Restore the zero slot to zero.\n mstore(0x40, m) // Restore the free memory pointer.\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.\n ///\n /// The `from` account must have at least `amount` approved for the current contract to manage.\n function trySafeTransferFrom(address token, address from, address to, uint256 amount)\n internal\n returns (bool success)\n {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40) // Cache the free memory pointer.\n mstore(0x60, amount) // Store the `amount` argument.\n mstore(0x40, to) // Store the `to` argument.\n mstore(0x2c, shl(96, from)) // Store the `from` argument.\n mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.\n success :=\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)\n )\n mstore(0x60, 0) // Restore the zero slot to zero.\n mstore(0x40, m) // Restore the free memory pointer.\n }\n }\n\n /// @dev Sends all of ERC20 `token` from `from` to `to`.\n /// Reverts upon failure.\n ///\n /// The `from` account must have their entire balance approved for the current contract to manage.\n function safeTransferAllFrom(address token, address from, address to)\n internal\n returns (uint256 amount)\n {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40) // Cache the free memory pointer.\n mstore(0x40, to) // Store the `to` argument.\n mstore(0x2c, shl(96, from)) // Store the `from` argument.\n mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.\n // Read the balance, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)\n )\n ) {\n mstore(0x00, 0x7939f424) // `TransferFromFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.\n amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x7939f424) // `TransferFromFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x60, 0) // Restore the zero slot to zero.\n mstore(0x40, m) // Restore the free memory pointer.\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.\n /// Reverts upon failure.\n function safeTransfer(address token, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, to) // Store the `to` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Sends all of ERC20 `token` from the current contract to `to`.\n /// Reverts upon failure.\n function safeTransferAll(address token, address to) internal returns (uint256 amount) {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.\n mstore(0x20, address()) // Store the address of the current contract.\n // Read the balance, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)\n )\n ) {\n mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x14, to) // Store the `to` argument.\n amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.\n mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n // Perform the transfer, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.\n /// Reverts upon failure.\n function safeApprove(address token, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, to) // Store the `to` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.\n // Perform the approval, reverting upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.\n revert(0x1c, 0x04)\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.\n /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,\n /// then retries the approval again (some tokens, e.g. USDT, requires this).\n /// Reverts upon failure.\n function safeApproveWithRetry(address token, address to, uint256 amount) internal {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, to) // Store the `to` argument.\n mstore(0x34, amount) // Store the `amount` argument.\n mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.\n // Perform the approval, retrying upon failure.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x34, 0) // Store 0 for the `amount`.\n mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.\n pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.\n mstore(0x34, amount) // Store back the original `amount`.\n // Retry the approval, reverting upon failure.\n if iszero(\n and(\n or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n )\n ) {\n mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.\n revert(0x1c, 0x04)\n }\n }\n mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n }\n }\n\n /// @dev Returns the amount of ERC20 `token` owned by `account`.\n /// Returns zero if the `token` does not exist.\n function balanceOf(address token, address account) internal view returns (uint256 amount) {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x14, account) // Store the `account` argument.\n mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.\n amount :=\n mul( // The arguments of `mul` are evaluated from right to left.\n mload(0x20),\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)\n )\n )\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.\n /// If the initial attempt fails, try to use Permit2 to transfer the token.\n /// Reverts upon failure.\n ///\n /// The `from` account must have at least `amount` approved for the current contract to manage.\n function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {\n if (!trySafeTransferFrom(token, from, to, amount)) {\n permit2TransferFrom(token, from, to, amount);\n }\n }\n\n /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.\n /// Reverts upon failure.\n function permit2TransferFrom(address token, address from, address to, uint256 amount)\n internal\n {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40)\n mstore(add(m, 0x74), shr(96, shl(96, token)))\n mstore(add(m, 0x54), amount)\n mstore(add(m, 0x34), to)\n mstore(add(m, 0x20), shl(96, from))\n // `transferFrom(address,address,uint160,address)`.\n mstore(m, 0x36c78516000000000000000000000000)\n let p := PERMIT2\n let exists := eq(chainid(), 1)\n if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }\n if iszero(and(call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), exists)) {\n mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.\n revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)\n }\n }\n }\n\n /// @dev Permit a user to spend a given amount of\n /// another user's tokens via native EIP-2612 permit if possible, falling\n /// back to Permit2 if native permit fails or is not implemented on the token.\n function permit2(\n address token,\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n bool success;\n /// @solidity memory-safe-assembly\n assembly {\n for {} shl(96, xor(token, WETH9)) {} {\n mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.\n // Gas stipend to limit gas burn for tokens that don't refund gas when\n // an non-existing function is called. 5K should be enough for a SLOAD.\n staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)\n )\n ) { break }\n // After here, we can be sure that token is a contract.\n let m := mload(0x40)\n mstore(add(m, 0x34), spender)\n mstore(add(m, 0x20), shl(96, owner))\n mstore(add(m, 0x74), deadline)\n if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {\n mstore(0x14, owner)\n mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.\n mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))\n mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.\n // `nonces` is already at `add(m, 0x54)`.\n // `1` is already stored at `add(m, 0x94)`.\n mstore(add(m, 0xb4), and(0xff, v))\n mstore(add(m, 0xd4), r)\n mstore(add(m, 0xf4), s)\n success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)\n break\n }\n mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.\n mstore(add(m, 0x54), amount)\n mstore(add(m, 0x94), and(0xff, v))\n mstore(add(m, 0xb4), r)\n mstore(add(m, 0xd4), s)\n success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)\n break\n }\n }\n if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);\n }\n\n /// @dev Simple permit on the Permit2 contract.\n function simplePermit2(\n address token,\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n /// @solidity memory-safe-assembly\n assembly {\n let m := mload(0x40)\n mstore(m, 0x927da105) // `allowance(address,address,address)`.\n {\n let addressMask := shr(96, not(0))\n mstore(add(m, 0x20), and(addressMask, owner))\n mstore(add(m, 0x40), and(addressMask, token))\n mstore(add(m, 0x60), and(addressMask, spender))\n mstore(add(m, 0xc0), and(addressMask, spender))\n }\n let p := mul(PERMIT2, iszero(shr(160, amount)))\n if iszero(\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.\n staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)\n )\n ) {\n mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.\n revert(add(0x18, shl(2, iszero(p))), 0x04)\n }\n mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).\n // `owner` is already `add(m, 0x20)`.\n // `token` is already at `add(m, 0x40)`.\n mstore(add(m, 0x60), amount)\n mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.\n // `nonce` is already at `add(m, 0xa0)`.\n // `spender` is already at `add(m, 0xc0)`.\n mstore(add(m, 0xe0), deadline)\n mstore(add(m, 0x100), 0x100) // `signature` offset.\n mstore(add(m, 0x120), 0x41) // `signature` length.\n mstore(add(m, 0x140), r)\n mstore(add(m, 0x160), s)\n mstore(add(m, 0x180), shl(248, v))\n if iszero(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {\n mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.\n revert(0x1c, 0x04)\n }\n }\n }\n}\n"},"lib/solady/src/utils/MetadataReaderLib.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Library for reading contract metadata robustly.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MetadataReaderLib.sol)\nlibrary MetadataReaderLib {\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CONSTANTS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Default gas stipend for contract reads. High enough for most practical use cases\n /// (able to SLOAD about 1000 bytes of data), but low enough to prevent griefing.\n uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;\n\n /// @dev Default string byte length limit.\n uint256 internal constant STRING_LIMIT_DEFAULT = 1000;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* METADATA READING OPERATIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n // Best-effort string reading operations.\n // Should NOT revert as long as sufficient gas is provided.\n //\n // Performs the following in order:\n // 1. Returns the empty string for the following cases:\n // - Reverts.\n // - No returndata (e.g. function returns nothing, EOA).\n // - Returns empty string.\n // 2. Attempts to `abi.decode` the returndata into a string.\n // 3. With any remaining gas, scans the returndata from start to end for the\n // null byte '\\0', to interpret the returndata as a null-terminated string.\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"name()\"))`.\n function readName(address target) internal view returns (string memory) {\n return _string(target, _ptr(0x06fdde03), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"name()\"), limit)`.\n function readName(address target, uint256 limit) internal view returns (string memory) {\n return _string(target, _ptr(0x06fdde03), limit, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"name()\"), limit, gasStipend)`.\n function readName(address target, uint256 limit, uint256 gasStipend)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(0x06fdde03), limit, gasStipend);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"symbol()\"))`.\n function readSymbol(address target) internal view returns (string memory) {\n return _string(target, _ptr(0x95d89b41), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"symbol()\"), limit)`.\n function readSymbol(address target, uint256 limit) internal view returns (string memory) {\n return _string(target, _ptr(0x95d89b41), limit, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Equivalent to `readString(abi.encodeWithSignature(\"symbol()\"), limit, gasStipend)`.\n function readSymbol(address target, uint256 limit, uint256 gasStipend)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(0x95d89b41), limit, gasStipend);\n }\n\n /// @dev Performs a best-effort string query on `target` with `data` as the calldata.\n /// The string will be truncated to `STRING_LIMIT_DEFAULT` (1000) bytes.\n function readString(address target, bytes memory data) internal view returns (string memory) {\n return _string(target, _ptr(data), STRING_LIMIT_DEFAULT, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Performs a best-effort string query on `target` with `data` as the calldata.\n /// The string will be truncated to `limit` bytes.\n function readString(address target, bytes memory data, uint256 limit)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(data), limit, GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Performs a best-effort string query on `target` with `data` as the calldata.\n /// The string will be truncated to `limit` bytes.\n function readString(address target, bytes memory data, uint256 limit, uint256 gasStipend)\n internal\n view\n returns (string memory)\n {\n return _string(target, _ptr(data), limit, gasStipend);\n }\n\n // Best-effort unsigned integer reading operations.\n // Should NOT revert as long as sufficient gas is provided.\n //\n // Performs the following in order:\n // 1. Attempts to `abi.decode` the result into a uint256\n // (equivalent across all Solidity uint types, downcast as needed).\n // 2. Returns zero for the following cases:\n // - Reverts.\n // - No returndata (e.g. function returns nothing, EOA).\n // - Returns zero.\n // - `abi.decode` failure.\n\n /// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature(\"decimal()\")))`.\n function readDecimals(address target) internal view returns (uint8) {\n return uint8(_uint(target, _ptr(0x313ce567), GAS_STIPEND_NO_GRIEF));\n }\n\n /// @dev Equivalent to `uint8(readUint(abi.encodeWithSignature(\"decimal()\"), gasStipend))`.\n function readDecimals(address target, uint256 gasStipend) internal view returns (uint8) {\n return uint8(_uint(target, _ptr(0x313ce567), gasStipend));\n }\n\n /// @dev Performs a best-effort uint query on `target` with `data` as the calldata.\n function readUint(address target, bytes memory data) internal view returns (uint256) {\n return _uint(target, _ptr(data), GAS_STIPEND_NO_GRIEF);\n }\n\n /// @dev Performs a best-effort uint query on `target` with `data` as the calldata.\n function readUint(address target, bytes memory data, uint256 gasStipend)\n internal\n view\n returns (uint256)\n {\n return _uint(target, _ptr(data), gasStipend);\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* PRIVATE HELPERS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Attempts to read and return a string at `target`.\n function _string(address target, bytes32 ptr, uint256 limit, uint256 gasStipend)\n private\n view\n returns (string memory result)\n {\n /// @solidity memory-safe-assembly\n assembly {\n function min(x_, y_) -> _z {\n _z := xor(x_, mul(xor(x_, y_), lt(y_, x_)))\n }\n for {} staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x00, 0x20) {} {\n let m := mload(0x40) // Grab the free memory pointer.\n let s := add(0x20, m) // Start of the string's bytes in memory.\n // Attempt to `abi.decode` if the returndatasize is greater or equal to 64.\n if iszero(lt(returndatasize(), 0x40)) {\n let o := mload(0x00) // Load the string's offset in the returndata.\n // If the string's offset is within bounds.\n if iszero(gt(o, sub(returndatasize(), 0x20))) {\n returndatacopy(m, o, 0x20) // Copy the string's length.\n // If the full string's end is within bounds.\n // Note: If the full string doesn't fit, the `abi.decode` must be aborted\n // for compliance purposes, regardless if the truncated string can fit.\n if iszero(gt(mload(m), sub(returndatasize(), add(o, 0x20)))) {\n let n := min(mload(m), limit) // Truncate if needed.\n mstore(m, n) // Overwrite the length.\n returndatacopy(s, add(o, 0x20), n) // Copy the string's bytes.\n mstore(add(s, n), 0) // Zeroize the slot after the string.\n mstore(0x40, add(0x20, add(s, n))) // Allocate memory for the string.\n result := m\n break\n }\n }\n }\n // Try interpreting as a null-terminated string.\n let n := min(returndatasize(), limit) // Truncate if needed.\n returndatacopy(s, 0, n) // Copy the string's bytes.\n mstore8(add(s, n), 0) // Place a '\\0' at the end.\n let i := s // Pointer to the next byte to scan.\n for {} byte(0, mload(i)) { i := add(i, 1) } {} // Scan for '\\0'.\n mstore(m, sub(i, s)) // Store the string's length.\n mstore(i, 0) // Zeroize the slot after the string.\n mstore(0x40, add(0x20, i)) // Allocate memory for the string.\n result := m\n break\n }\n }\n }\n\n /// @dev Attempts to read and return a uint at `target`.\n function _uint(address target, bytes32 ptr, uint256 gasStipend)\n private\n view\n returns (uint256 result)\n {\n /// @solidity memory-safe-assembly\n assembly {\n result :=\n mul(\n mload(0x20),\n and( // The arguments of `and` are evaluated from right to left.\n gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n staticcall(gasStipend, target, add(ptr, 0x20), mload(ptr), 0x20, 0x20)\n )\n )\n }\n }\n\n /// @dev Casts the function selector `s` into a pointer.\n function _ptr(uint256 s) private pure returns (bytes32 result) {\n /// @solidity memory-safe-assembly\n assembly {\n // Layout the calldata in the scratch space for temporary usage.\n mstore(0x04, s) // Store the function selector.\n mstore(result, 4) // Store the length.\n }\n }\n\n /// @dev Casts the `data` into a pointer.\n function _ptr(bytes memory data) private pure returns (bytes32 result) {\n /// @solidity memory-safe-assembly\n assembly {\n result := data\n }\n }\n}\n"}},"settings":{"remappings":["forge-std/=lib/forge-std/src/","solady/=lib/solady/src/"],"optimizer":{"enabled":true,"runs":99999999},"metadata":{"useLiteralContent":false,"bytecodeHash":"ipfs","appendCBOR":true},"outputSelection":{"*":{"*":["abi","evm.bytecode","evm.deployedBytecode","evm.methodIdentifiers","metadata"]}},"evmVersion":"cancun","viaIR":true,"libraries":{}}} diff --git a/lib/solady b/lib/solady index c55500d..ab266e9 160000 --- a/lib/solady +++ b/lib/solady @@ -1 +1 @@ -Subproject commit c55500db941600053d149cc2a1d1696aa37c4294 +Subproject commit ab266e9340671c56fbd102629036f8afc5f9c9de