From a3098257690e141fa860850aa11a646f03efb79d Mon Sep 17 00:00:00 2001 From: royvardhan Date: Thu, 13 Feb 2025 20:31:21 +0530 Subject: [PATCH 01/15] refactor: rm usv3 callback from router and add generic callback to executor --- foundry/interfaces/IExecutor.sol | 4 ++ foundry/src/TychoRouter.sol | 52 ++------------------- foundry/src/executors/UniswapV3Executor.sol | 43 +++++++++++++++++ 3 files changed, 51 insertions(+), 48 deletions(-) diff --git a/foundry/interfaces/IExecutor.sol b/foundry/interfaces/IExecutor.sol index 0a60022..0316e08 100644 --- a/foundry/interfaces/IExecutor.sol +++ b/foundry/interfaces/IExecutor.sol @@ -24,6 +24,10 @@ interface IExecutor { uint256 givenAmount, bytes calldata data ) external payable returns (uint256 calculatedAmount); + + function handleCallback( + bytes calldata callbackData + ) external returns (address tokenOwed, uint256 amountOwed); } interface IExecutorErrors { diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 9d77dec..374a427 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -11,7 +11,6 @@ import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@permit2/src/interfaces/IAllowanceTransfer.sol"; -import "@uniswap/v3-updated/CallbackValidationV2.sol"; import "./ExecutionDispatcher.sol"; import "./CallbackVerificationDispatcher.sol"; import {LibSwap} from "../lib/LibSwap.sol"; @@ -66,24 +65,15 @@ contract TychoRouter is ); event FeeSet(uint256 indexed oldFee, uint256 indexed newFee); - address private immutable _usv3Factory; - - constructor( - IPoolManager _poolManager, - address _permit2, - address weth, - address usv3Factory - ) SafeCallback(_poolManager) { - if ( - _permit2 == address(0) || weth == address(0) - || usv3Factory == address(0) - ) { + constructor(IPoolManager _poolManager, address _permit2, address weth) + SafeCallback(_poolManager) + { + if (_permit2 == address(0) || weth == address(0)) { revert TychoRouter__AddressZero(); } permit2 = IAllowanceTransfer(_permit2); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _weth = IWETH(weth); - _usv3Factory = usv3Factory; } /** @@ -409,40 +399,6 @@ contract TychoRouter is */ receive() external payable {} - /** - * @dev Called by UniswapV3 pool when swapping on it. - * See in IUniswapV3SwapCallback for documentation. - */ - function uniswapV3SwapCallback( - int256 amount0Delta, - int256 amount1Delta, - bytes calldata msgData - ) external { - (uint256 amountOwed, address tokenOwed) = - _verifyUSV3Callback(amount0Delta, amount1Delta, msgData); - IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); - } - - function _verifyUSV3Callback( - int256 amount0Delta, - int256 amount1Delta, - bytes calldata data - ) internal view returns (uint256 amountIn, address tokenIn) { - tokenIn = address(bytes20(data[0:20])); - address tokenOut = address(bytes20(data[20:40])); - uint24 poolFee = uint24(bytes3(data[40:43])); - - // slither-disable-next-line unused-return - CallbackValidationV2.verifyCallback( - _usv3Factory, tokenIn, tokenOut, poolFee - ); - - amountIn = - amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); - - return (amountIn, tokenIn); - } - function _unlockCallback(bytes calldata data) internal override diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index ac986c5..cc1058e 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -4,14 +4,23 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; +import "@uniswap/v3-updated/CallbackValidationV2.sol"; error UniswapV3Executor__InvalidDataLength(); contract UniswapV3Executor is IExecutor { + using SafeERC20 for IERC20; + uint160 private constant MIN_SQRT_RATIO = 4295128739; uint160 private constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; + address public immutable factory; + + constructor(address factory_) { + factory = factory_; + } + // slither-disable-next-line locked-ether function swap(uint256 amountIn, bytes calldata data) external @@ -50,6 +59,40 @@ contract UniswapV3Executor is IExecutor { } } + function handleCallback(bytes calldata msgData) + external + returns (address tokenOwed, uint256 amountOwed) + { + int256 amount0Delta; + int256 amount1Delta; + + (amount0Delta, amount1Delta) = + abi.decode(msgData[:64], (int256, int256)); + + bytes calldata remainingData = msgData[64:]; + (amountOwed, tokenOwed) = + _verifyUSV3Callback(amount0Delta, amount1Delta, remainingData); + IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); + } + + function _verifyUSV3Callback( + int256 amount0Delta, + int256 amount1Delta, + bytes calldata data + ) internal view returns (uint256 amountIn, address tokenIn) { + tokenIn = address(bytes20(data[0:20])); + address tokenOut = address(bytes20(data[20:40])); + uint24 poolFee = uint24(bytes3(data[40:43])); + + // slither-disable-next-line unused-return + CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); + + amountIn = + amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); + + return (amountIn, tokenIn); + } + function _decodeData(bytes calldata data) internal pure From bd1971334e61a128f8454d96df48889374749203 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Thu, 13 Feb 2025 20:54:54 +0530 Subject: [PATCH 02/15] feat: update new interface in codebase --- foundry/interfaces/IExecutor.sol | 2 +- foundry/src/ExecutionDispatcher.sol | 20 +++ foundry/src/TychoRouter.sol | 110 ++++++-------- foundry/src/executors/BalancerV2Executor.sol | 30 ++-- foundry/src/executors/UniswapV2Executor.sol | 31 ++-- foundry/src/executors/UniswapV3Executor.sol | 60 +++++--- foundry/src/executors/UniswapV4Executor.sol | 81 ++++++---- foundry/test/TychoRouter.t.sol | 143 ++++++++++++------ foundry/test/TychoRouterTestSetup.sol | 85 ++++++----- .../test/executors/UniswapV3Executor.t.sol | 26 +++- 10 files changed, 357 insertions(+), 231 deletions(-) diff --git a/foundry/interfaces/IExecutor.sol b/foundry/interfaces/IExecutor.sol index 0316e08..5e595a3 100644 --- a/foundry/interfaces/IExecutor.sol +++ b/foundry/interfaces/IExecutor.sol @@ -27,7 +27,7 @@ interface IExecutor { function handleCallback( bytes calldata callbackData - ) external returns (address tokenOwed, uint256 amountOwed); + ) external returns (bytes memory result); } interface IExecutorErrors { diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/ExecutionDispatcher.sol index 73bd554..4b87dbd 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/ExecutionDispatcher.sol @@ -79,4 +79,24 @@ contract ExecutionDispatcher { calculatedAmount = abi.decode(result, (uint256)); } + + function _handleCallback(address executor, bytes calldata data) internal { + if (!executors[executor]) { + revert ExecutionDispatcher__UnapprovedExecutor(); + } + + (bool success, bytes memory result) = executor.delegatecall( + abi.encodeWithSelector(IExecutor.handleCallback.selector, data) + ); + + if (!success) { + revert( + string( + result.length > 0 + ? result + : abi.encodePacked("Callback failed") + ) + ); + } + } } diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 374a427..9f83c8e 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -12,7 +12,6 @@ import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@permit2/src/interfaces/IAllowanceTransfer.sol"; import "./ExecutionDispatcher.sol"; -import "./CallbackVerificationDispatcher.sol"; import {LibSwap} from "../lib/LibSwap.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {SafeCallback} from "@uniswap/v4-periphery/src/base/SafeCallback.sol"; @@ -58,16 +57,21 @@ contract TychoRouter is uint256 public fee; event Withdrawal( - address indexed token, uint256 amount, address indexed receiver + address indexed token, + uint256 amount, + address indexed receiver ); event FeeReceiverSet( - address indexed oldFeeReceiver, address indexed newFeeReceiver + address indexed oldFeeReceiver, + address indexed newFeeReceiver ); event FeeSet(uint256 indexed oldFee, uint256 indexed newFee); - constructor(IPoolManager _poolManager, address _permit2, address weth) - SafeCallback(_poolManager) - { + constructor( + IPoolManager _poolManager, + address _permit2, + address weth + ) SafeCallback(_poolManager) { if (_permit2 == address(0) || weth == address(0)) { revert TychoRouter__AddressZero(); } @@ -181,10 +185,11 @@ contract TychoRouter is * * @return The total amount of the buy token obtained after all swaps have been executed. */ - function _swap(uint256 amountIn, uint256 nTokens, bytes calldata swaps_) - internal - returns (uint256) - { + function _swap( + uint256 amountIn, + uint256 nTokens, + bytes calldata swaps_ + ) internal returns (uint256) { if (swaps_.length == 0) { revert TychoRouter__EmptySwaps(); } @@ -230,17 +235,7 @@ contract TychoRouter is * caller is not a pool. */ fallback() external { - _executeGenericCallback(msg.data); - } - - /** - * @dev Check if the sender is correct and executes callback actions. - * @param msgData encoded data. It must includes data for the verification. - */ - function _executeGenericCallback(bytes calldata msgData) internal { - (uint256 amountOwed, address tokenOwed) = _callVerifyCallback(msgData); - - IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); + _handleCallback(msg.sender, msg.data); } /** @@ -260,10 +255,10 @@ contract TychoRouter is /** * @dev Allows granting roles to multiple accounts in a single call. */ - function batchGrantRole(bytes32 role, address[] memory accounts) - external - onlyRole(DEFAULT_ADMIN_ROLE) - { + function batchGrantRole( + bytes32 role, + address[] memory accounts + ) external onlyRole(DEFAULT_ADMIN_ROLE) { for (uint256 i = 0; i < accounts.length; i++) { _grantRole(role, accounts[i]); } @@ -273,10 +268,9 @@ contract TychoRouter is * @dev Entrypoint to add or replace an approved executor contract address * @param targets address of the executor contract */ - function setExecutors(address[] memory targets) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { + function setExecutors( + address[] memory targets + ) external onlyRole(EXECUTOR_SETTER_ROLE) { for (uint256 i = 0; i < targets.length; i++) { _setExecutor(targets[i]); } @@ -286,10 +280,9 @@ contract TychoRouter is * @dev Entrypoint to remove an approved executor contract address * @param target address of the executor contract */ - function removeExecutor(address target) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { + function removeExecutor( + address target + ) external onlyRole(EXECUTOR_SETTER_ROLE) { _removeExecutor(target); } @@ -297,10 +290,9 @@ contract TychoRouter is * @dev Entrypoint to add or replace an approved callback verifier contract address * @param target address of the callback verifier contract */ - function setCallbackVerifier(address target) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { + function setCallbackVerifier( + address target + ) external onlyRole(EXECUTOR_SETTER_ROLE) { _setCallbackVerifier(target); } @@ -308,20 +300,18 @@ contract TychoRouter is * @dev Entrypoint to remove an approved callback verifier contract address * @param target address of the callback verifier contract */ - function removeCallbackVerifier(address target) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { + function removeCallbackVerifier( + address target + ) external onlyRole(EXECUTOR_SETTER_ROLE) { _removeCallbackVerifier(target); } /** * @dev Allows setting the fee receiver. */ - function setFeeReceiver(address newfeeReceiver) - external - onlyRole(FEE_SETTER_ROLE) - { + function setFeeReceiver( + address newfeeReceiver + ) external onlyRole(FEE_SETTER_ROLE) { if (newfeeReceiver == address(0)) revert TychoRouter__AddressZero(); emit FeeReceiverSet(feeReceiver, newfeeReceiver); feeReceiver = newfeeReceiver; @@ -338,10 +328,10 @@ contract TychoRouter is /** * @dev Allows withdrawing any ERC20 funds if funds get stuck in case of a bug. */ - function withdraw(IERC20[] memory tokens, address receiver) - external - onlyRole(FUND_RESCUER_ROLE) - { + function withdraw( + IERC20[] memory tokens, + address receiver + ) external onlyRole(FUND_RESCUER_ROLE) { if (receiver == address(0)) revert TychoRouter__AddressZero(); for (uint256 i = 0; i < tokens.length; i++) { @@ -358,10 +348,9 @@ contract TychoRouter is * @dev Allows withdrawing any NATIVE funds if funds get stuck in case of a bug. * The contract should never hold any NATIVE tokens for security reasons. */ - function withdrawNative(address receiver) - external - onlyRole(FUND_RESCUER_ROLE) - { + function withdrawNative( + address receiver + ) external onlyRole(FUND_RESCUER_ROLE) { if (receiver == address(0)) revert TychoRouter__AddressZero(); uint256 amount = address(this).balance; @@ -389,8 +378,9 @@ contract TychoRouter is * @param amount of WETH to unwrap. */ function _unwrapETH(uint256 amount) internal { - uint256 unwrapAmount = - amount == 0 ? _weth.balanceOf(address(this)) : amount; + uint256 unwrapAmount = amount == 0 + ? _weth.balanceOf(address(this)) + : amount; _weth.withdraw(unwrapAmount); } @@ -399,11 +389,9 @@ contract TychoRouter is */ receive() external payable {} - function _unlockCallback(bytes calldata data) - internal - override - returns (bytes memory) - { + function _unlockCallback( + bytes calldata data + ) internal override returns (bytes memory) { require(data.length >= 20, "Invalid data length"); bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); address executor = address(uint160(bytes20(data[data.length - 20:]))); @@ -414,7 +402,7 @@ contract TychoRouter is } // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success,) = executor.delegatecall( + (bool success, ) = executor.delegatecall( abi.encodeWithSelector(selector, protocolData) ); require(success, "delegatecall to uniswap v4 callback failed"); diff --git a/foundry/src/executors/BalancerV2Executor.sol b/foundry/src/executors/BalancerV2Executor.sol index 14340cf..f769d2e 100644 --- a/foundry/src/executors/BalancerV2Executor.sol +++ b/foundry/src/executors/BalancerV2Executor.sol @@ -2,10 +2,7 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import { - IERC20, - SafeERC20 -} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // slither-disable-next-line solc-version import {IAsset} from "@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol"; // slither-disable-next-line solc-version @@ -19,11 +16,10 @@ contract BalancerV2Executor is IExecutor { address private constant VAULT = 0xBA12222222228d8Ba445958a75a0704d566BF2C8; // slither-disable-next-line locked-ether - function swap(uint256 givenAmount, bytes calldata data) - external - payable - returns (uint256 calculatedAmount) - { + function swap( + uint256 givenAmount, + bytes calldata data + ) external payable returns (uint256 calculatedAmount) { ( IERC20 tokenIn, IERC20 tokenOut, @@ -55,11 +51,21 @@ contract BalancerV2Executor is IExecutor { uint256 limit = 0; - calculatedAmount = - IVault(VAULT).swap(singleSwap, funds, limit, block.timestamp); + calculatedAmount = IVault(VAULT).swap( + singleSwap, + funds, + limit, + block.timestamp + ); } - function _decodeData(bytes calldata data) + function handleCallback( + bytes calldata data + ) external returns (bytes memory result) {} + + function _decodeData( + bytes calldata data + ) internal pure returns ( diff --git a/foundry/src/executors/UniswapV2Executor.sol b/foundry/src/executors/UniswapV2Executor.sol index 7239a8a..f8cf820 100644 --- a/foundry/src/executors/UniswapV2Executor.sol +++ b/foundry/src/executors/UniswapV2Executor.sol @@ -11,11 +11,10 @@ contract UniswapV2Executor is IExecutor { using SafeERC20 for IERC20; // slither-disable-next-line locked-ether - function swap(uint256 givenAmount, bytes calldata data) - external - payable - returns (uint256 calculatedAmount) - { + function swap( + uint256 givenAmount, + bytes calldata data + ) external payable returns (uint256 calculatedAmount) { address target; address receiver; bool zeroForOne; @@ -33,7 +32,13 @@ contract UniswapV2Executor is IExecutor { } } - function _decodeData(bytes calldata data) + function handleCallback( + bytes calldata data + ) external returns (bytes memory result) {} + + function _decodeData( + bytes calldata data + ) internal pure returns ( @@ -52,20 +57,20 @@ contract UniswapV2Executor is IExecutor { zeroForOne = uint8(data[60]) > 0; } - function _getAmountOut(address target, uint256 amountIn, bool zeroForOne) - internal - view - returns (uint256 amount) - { + function _getAmountOut( + address target, + uint256 amountIn, + bool zeroForOne + ) internal view returns (uint256 amount) { IUniswapV2Pair pair = IUniswapV2Pair(target); uint112 reserveIn; uint112 reserveOut; if (zeroForOne) { // slither-disable-next-line unused-return - (reserveIn, reserveOut,) = pair.getReserves(); + (reserveIn, reserveOut, ) = pair.getReserves(); } else { // slither-disable-next-line unused-return - (reserveOut, reserveIn,) = pair.getReserves(); + (reserveOut, reserveIn, ) = pair.getReserves(); } require(reserveIn > 0 && reserveOut > 0, "L"); diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index cc1058e..060f27f 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -17,16 +17,15 @@ contract UniswapV3Executor is IExecutor { address public immutable factory; - constructor(address factory_) { - factory = factory_; + constructor(address _factory) { + factory = _factory; } // slither-disable-next-line locked-ether - function swap(uint256 amountIn, bytes calldata data) - external - payable - returns (uint256 amountOut) - { + function swap( + uint256 amountIn, + bytes calldata data + ) external payable returns (uint256 amountOut) { ( address tokenIn, address tokenOut, @@ -59,20 +58,25 @@ contract UniswapV3Executor is IExecutor { } } - function handleCallback(bytes calldata msgData) - external - returns (address tokenOwed, uint256 amountOwed) - { + function handleCallback( + bytes calldata msgData + ) external returns (bytes memory result) { int256 amount0Delta; int256 amount1Delta; - (amount0Delta, amount1Delta) = - abi.decode(msgData[:64], (int256, int256)); + (amount0Delta, amount1Delta) = abi.decode( + msgData[:64], + (int256, int256) + ); bytes calldata remainingData = msgData[64:]; - (amountOwed, tokenOwed) = - _verifyUSV3Callback(amount0Delta, amount1Delta, remainingData); + (uint256 amountOwed, address tokenOwed) = _verifyUSV3Callback( + amount0Delta, + amount1Delta, + remainingData + ); IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); + return abi.encode(amountOwed, tokenOwed); } function _verifyUSV3Callback( @@ -85,15 +89,23 @@ contract UniswapV3Executor is IExecutor { uint24 poolFee = uint24(bytes3(data[40:43])); // slither-disable-next-line unused-return - CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); + CallbackValidationV2.verifyCallback( + factory, + tokenIn, + tokenOut, + poolFee + ); - amountIn = - amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); + amountIn = amount0Delta > 0 + ? uint256(amount0Delta) + : uint256(amount1Delta); return (amountIn, tokenIn); } - function _decodeData(bytes calldata data) + function _decodeData( + bytes calldata data + ) internal pure returns ( @@ -116,11 +128,11 @@ contract UniswapV3Executor is IExecutor { zeroForOne = uint8(data[83]) > 0; } - function _makeV3CallbackData(address tokenIn, address tokenOut, uint24 fee) - internal - pure - returns (bytes memory) - { + function _makeV3CallbackData( + address tokenIn, + address tokenOut, + uint24 fee + ) internal pure returns (bytes memory) { return abi.encodePacked(tokenIn, tokenOut, fee); } } diff --git a/foundry/src/executors/UniswapV4Executor.sol b/foundry/src/executors/UniswapV4Executor.sol index 4a67727..bda2e11 100644 --- a/foundry/src/executors/UniswapV4Executor.sol +++ b/foundry/src/executors/UniswapV4Executor.sol @@ -2,14 +2,9 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import { - IERC20, - SafeERC20 -} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; -import { - Currency, CurrencyLibrary -} from "@uniswap/v4-core/src/types/Currency.sol"; +import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {V4Router} from "@uniswap/v4-periphery/src/V4Router.sol"; @@ -26,13 +21,16 @@ contract UniswapV4Executor is IExecutor, V4Router { constructor(IPoolManager _poolManager) V4Router(_poolManager) {} - function swap(uint256, bytes calldata data) - external - payable - returns (uint256 calculatedAmount) - { - (address tokenIn, address tokenOut, bool isExactInput, uint256 amount) = - _decodeData(data); + function swap( + uint256, + bytes calldata data + ) external payable returns (uint256 calculatedAmount) { + ( + address tokenIn, + address tokenOut, + bool isExactInput, + uint256 amount + ) = _decodeData(data); uint256 tokenOutBalanceBefore; uint256 tokenInBalanceBefore; @@ -67,7 +65,9 @@ contract UniswapV4Executor is IExecutor, V4Router { return calculatedAmount; } - function _decodeData(bytes calldata data) + function _decodeData( + bytes calldata data + ) internal pure returns ( @@ -77,15 +77,19 @@ contract UniswapV4Executor is IExecutor, V4Router { uint256 amount ) { - (bytes memory actions, bytes[] memory params) = - abi.decode(data, (bytes, bytes[])); + (bytes memory actions, bytes[] memory params) = abi.decode( + data, + (bytes, bytes[]) + ); // First byte of actions determines the swap type uint8 action = uint8(bytes1(actions[0])); if (action == uint8(Actions.SWAP_EXACT_IN_SINGLE)) { - IV4Router.ExactInputSingleParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactInputSingleParams)); + IV4Router.ExactInputSingleParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactInputSingleParams) + ); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -96,8 +100,10 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT_SINGLE)) { - IV4Router.ExactOutputSingleParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactOutputSingleParams)); + IV4Router.ExactOutputSingleParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactOutputSingleParams) + ); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -108,18 +114,23 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = false; amount = swapParams.amountOut; } else if (action == uint8(Actions.SWAP_EXACT_IN)) { - IV4Router.ExactInputParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactInputParams)); + IV4Router.ExactInputParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactInputParams) + ); tokenIn = address(uint160(swapParams.currencyIn.toId())); - PathKey memory lastPath = - swapParams.path[swapParams.path.length - 1]; + PathKey memory lastPath = swapParams.path[ + swapParams.path.length - 1 + ]; tokenOut = address(uint160(lastPath.intermediateCurrency.toId())); isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT)) { - IV4Router.ExactOutputParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactOutputParams)); + IV4Router.ExactOutputParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactOutputParams) + ); PathKey memory firstPath = swapParams.path[0]; tokenIn = address(uint160(firstPath.intermediateCurrency.toId())); @@ -129,16 +140,22 @@ contract UniswapV4Executor is IExecutor, V4Router { } } - function _pay(Currency token, address payer, uint256 amount) - internal - override - { + function _pay( + Currency token, + address payer, + uint256 amount + ) internal override { IERC20(Currency.unwrap(token)).safeTransfer( - address(poolManager), amount + address(poolManager), + amount ); } function msgSender() public view override returns (address) { return address(this); } + + function handleCallback( + bytes calldata data + ) external returns (bytes memory result) {} } diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index 960e7b9..b7bbc9c 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -18,7 +18,9 @@ contract TychoRouterTest is TychoRouterTestSetup { event CallbackVerifierSet(address indexed callbackVerifier); event Withdrawal( - address indexed token, uint256 amount, address indexed receiver + address indexed token, + uint256 amount, + address indexed receiver ); function testSetExecutorsValidRole() public { @@ -239,7 +241,10 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(WETH_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -276,7 +281,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ) ); @@ -315,7 +323,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, WETH_WBTC_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_WBTC_POOL, + tychoRouterAddr, + false ) ); // WBTC -> USDC @@ -326,7 +337,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WBTC_ADDR, USDC_WBTC_POOL, tychoRouterAddr, true + WBTC_ADDR, + USDC_WBTC_POOL, + tychoRouterAddr, + true ) ); // WETH -> DAI @@ -337,7 +351,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ) ); @@ -373,7 +390,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -426,7 +446,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -485,7 +508,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -517,7 +543,10 @@ contract TychoRouterTest is TychoRouterTestSetup { assertEq(amountOut, expectedAmount); uint256 daiBalance = IERC20(DAI_ADDR).balanceOf(ALICE); assertEq(daiBalance, expectedAmount); - assertEq(IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), 26598819248184436997); + assertEq( + IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), + 26598819248184436997 + ); vm.stopPrank(); } @@ -530,19 +559,22 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.startPrank(ALICE); - IAllowanceTransfer.PermitSingle memory emptyPermitSingle = - IAllowanceTransfer.PermitSingle({ - details: IAllowanceTransfer.PermitDetails({ - token: address(0), - amount: 0, - expiration: 0, - nonce: 0 - }), - spender: address(0), - sigDeadline: 0 - }); + IAllowanceTransfer.PermitSingle + memory emptyPermitSingle = IAllowanceTransfer.PermitSingle({ + details: IAllowanceTransfer.PermitDetails({ + token: address(0), + amount: 0, + expiration: 0, + nonce: 0 + }), + spender: address(0), + sigDeadline: 0 + }); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -591,8 +623,12 @@ contract TychoRouterTest is TychoRouterTestSetup { bytes memory signature ) = handlePermit2Approval(DAI_ADDR, amountIn); - bytes memory protocolData = - encodeUniswapV2Swap(DAI_ADDR, WETH_DAI_POOL, tychoRouterAddr, true); + bytes memory protocolData = encodeUniswapV2Swap( + DAI_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + true + ); bytes memory swap = encodeSwap( uint8(0), @@ -626,23 +662,23 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.stopPrank(); } - function testUSV3Callback() public { - uint24 poolFee = 3000; - uint256 amountOwed = 1000000000000000000; - deal(WETH_ADDR, tychoRouterAddr, amountOwed); - uint256 initialPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); + // function testUSV3Callback() public { + // uint24 poolFee = 3000; + // uint256 amountOwed = 1000000000000000000; + // deal(WETH_ADDR, tychoRouterAddr, amountOwed); + // uint256 initialPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); - vm.startPrank(DAI_WETH_USV3); - tychoRouter.uniswapV3SwapCallback( - -2631245338449998525223, - int256(amountOwed), - abi.encodePacked(WETH_ADDR, DAI_ADDR, poolFee) - ); - vm.stopPrank(); + // vm.startPrank(DAI_WETH_USV3); + // tychoRouter.uniswapV3SwapCallback( + // -2631245338449998525223, + // int256(amountOwed), + // abi.encodePacked(WETH_ADDR, DAI_ADDR, poolFee) + // ); + // vm.stopPrank(); - uint256 finalPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); - assertEq(finalPoolReserve - initialPoolReserve, amountOwed); - } + // uint256 finalPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); + // assertEq(finalPoolReserve - initialPoolReserve, amountOwed); + // } function testSwapSingleUSV3() public { // Trade 1 WETH for DAI with 1 swap on Uniswap V3 @@ -654,7 +690,11 @@ contract TychoRouterTest is TychoRouterTestSetup { uint256 expAmountOut = 1205_128428842122129186; //Swap 1 WETH for 1205.12 DAI bool zeroForOne = false; bytes memory protocolData = encodeUniswapV3Swap( - WETH_ADDR, DAI_ADDR, tychoRouterAddr, DAI_WETH_USV3, zeroForOne + WETH_ADDR, + DAI_ADDR, + tychoRouterAddr, + DAI_WETH_USV3, + zeroForOne ); bytes memory swap = encodeSwap( uint8(0), @@ -696,7 +736,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call( + (bool success, ) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d481bb00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfbc3000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041f2740fde9662d8bc1f8fe8e8fc29447c1832d625f06f4a56ee5103ad555c12323af5d50eb840f73d17873383ae3b7573956d5df7b2bf76bddba768c2837894a51b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -725,7 +765,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call{value: 1 ether}( + (bool success, ) = tychoRouterAddr.call{value: 1 ether}( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4806b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfa73000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041c36406a750c499ac7f79f7666650f0d4f20fc27bb49ab68121c0be6554cb5cab6caf90dc3aab2e21083a8fa46976521a1e9df41ce74be59abf03e0d3691541e91c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00020000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -754,7 +794,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call( + (bool success, ) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000000000000000000000000000000000000067d4809800000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfaa000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000004146411c70ec7fee0d5d260803cb220f5365792426c5d94f7a0a4d37abb05205752c5418b1fadd059570a71f0911814e546728e1f21876f2a1c6d38d34bd235fd61c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fa478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950100000000" ); @@ -785,7 +825,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call( + (bool success, ) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4810d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfb15000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041ecaab75f0791c9683b001ea2f0e01a0a6aaf03e6e49c83e9c8a8e588a38e3be9230d962926628ffbf6a5370cda559ff0e7876a63ed38eebe33dbef5b5e2e46ef1b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000170005a00028000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d0139500005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2bb2b8038a1640196fbe3e38816f3e67cba72d9403ede3eca2a72b3aecc820e955b36f38437d0139500005a02030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fae461ca67b15dc8dc81ce7615e0320da1a9ab8d53ede3eca2a72b3aecc820e955b36f38437d0139501005a01030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab2260fac5e5542a773aa44fbcfedf7c193bc2c599004375dff511095cc5a197a54140a24efef3a4163ede3eca2a72b3aecc820e955b36f38437d013950100000000000000000000000000000000" ); @@ -815,7 +855,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -832,7 +875,8 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.expectRevert( abi.encodeWithSelector( - TychoRouter__AmountInNotFullySpent.selector, 400000000000000000 + TychoRouter__AmountInNotFullySpent.selector, + 400000000000000000 ) ); @@ -858,7 +902,12 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(USDE_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = UniswapV4Utils.encodeExactInputSingle( - USDE_ADDR, USDT_ADDR, 100, true, 1, uint128(amountIn) + USDE_ADDR, + USDT_ADDR, + 100, + true, + 1, + uint128(amountIn) ); // add executor and selector for callback diff --git a/foundry/test/TychoRouterTestSetup.sol b/foundry/test/TychoRouterTestSetup.sol index b0bbf2e..42cf7ba 100644 --- a/foundry/test/TychoRouterTestSetup.sol +++ b/foundry/test/TychoRouterTestSetup.sol @@ -15,9 +15,8 @@ contract TychoRouterExposed is TychoRouter { constructor( IPoolManager _poolManager, address _permit2, - address weth, - address usv3Factory - ) TychoRouter(_poolManager, _permit2, weth, usv3Factory) {} + address weth + ) TychoRouter(_poolManager, _permit2, weth) {} function wrapETH(uint256 amount) external payable { return _wrapETH(amount); @@ -39,7 +38,8 @@ contract TychoRouterExposed is TychoRouter { contract TychoRouterTestSetup is Test, Constants { TychoRouterExposed tychoRouter; address tychoRouterAddr; - address permit2Address = address(0x000000000022D473030F116dDEE9F6B43aC78BA3); + address permit2Address = + address(0x000000000022D473030F116dDEE9F6B43aC78BA3); UniswapV2Executor public usv2Executor; UniswapV3Executor public usv3Executor; UniswapV4Executor public usv4Executor; @@ -54,7 +54,9 @@ contract TychoRouterTestSetup is Test, Constants { address poolManagerAddress = 0x000000000004444c5dc75cB358380D2e3dE08A90; IPoolManager poolManager = IPoolManager(poolManagerAddress); tychoRouter = new TychoRouterExposed( - poolManager, permit2Address, WETH_ADDR, factoryV3 + poolManager, + permit2Address, + WETH_ADDR ); tychoRouterAddr = address(tychoRouter); tychoRouter.grantRole(keccak256("FUND_RESCUER_ROLE"), FUND_RESCUER); @@ -62,13 +64,14 @@ contract TychoRouterTestSetup is Test, Constants { tychoRouter.grantRole(keccak256("PAUSER_ROLE"), PAUSER); tychoRouter.grantRole(keccak256("UNPAUSER_ROLE"), UNPAUSER); tychoRouter.grantRole( - keccak256("EXECUTOR_SETTER_ROLE"), EXECUTOR_SETTER + keccak256("EXECUTOR_SETTER_ROLE"), + EXECUTOR_SETTER ); deployDummyContract(); vm.stopPrank(); usv2Executor = new UniswapV2Executor(); - usv3Executor = new UniswapV3Executor(); + usv3Executor = new UniswapV3Executor(factoryV3); usv4Executor = new UniswapV4Executor(poolManager); vm.startPrank(EXECUTOR_SETTER); address[] memory executors = new address[](3); @@ -110,22 +113,22 @@ contract TychoRouterTestSetup is Test, Constants { * @return permitSingle The `PermitSingle` struct containing the approval details. * @return signature The EIP-712 signature for the approval. */ - function handlePermit2Approval(address tokenIn, uint256 amount_in) - internal - returns (IAllowanceTransfer.PermitSingle memory, bytes memory) - { + function handlePermit2Approval( + address tokenIn, + uint256 amount_in + ) internal returns (IAllowanceTransfer.PermitSingle memory, bytes memory) { IERC20(tokenIn).approve(permit2Address, amount_in); IAllowanceTransfer.PermitSingle memory permitSingle = IAllowanceTransfer .PermitSingle({ - details: IAllowanceTransfer.PermitDetails({ - token: tokenIn, - amount: uint160(amount_in), - expiration: uint48(block.timestamp + 1 days), - nonce: 0 - }), - spender: tychoRouterAddr, - sigDeadline: block.timestamp + 1 days - }); + details: IAllowanceTransfer.PermitDetails({ + token: tokenIn, + amount: uint160(amount_in), + expiration: uint48(block.timestamp + 1 days), + nonce: 0 + }), + spender: tychoRouterAddr, + sigDeadline: block.timestamp + 1 days + }); bytes memory signature = signPermit2(permitSingle, ALICE_PK); return (permitSingle, signature); @@ -157,8 +160,9 @@ contract TychoRouterTestSetup is Test, Constants { permit2Address ) ); - bytes32 detailsHash = - keccak256(abi.encode(_PERMIT_DETAILS_TYPEHASH, permit.details)); + bytes32 detailsHash = keccak256( + abi.encode(_PERMIT_DETAILS_TYPEHASH, permit.details) + ); bytes32 permitHash = keccak256( abi.encode( _PERMIT_SINGLE_TYPEHASH, @@ -168,18 +172,17 @@ contract TychoRouterTestSetup is Test, Constants { ) ); - bytes32 digest = - keccak256(abi.encodePacked("\x19\x01", domainSeparator, permitHash)); + bytes32 digest = keccak256( + abi.encodePacked("\x19\x01", domainSeparator, permitHash) + ); (uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, digest); return abi.encodePacked(r, s, v); } - function pleEncode(bytes[] memory data) - public - pure - returns (bytes memory encoded) - { + function pleEncode( + bytes[] memory data + ) public pure returns (bytes memory encoded) { for (uint256 i = 0; i < data.length; i++) { encoded = bytes.concat( encoded, @@ -196,9 +199,15 @@ contract TychoRouterTestSetup is Test, Constants { bytes4 selector, bytes memory protocolData ) internal pure returns (bytes memory) { - return abi.encodePacked( - tokenInIndex, tokenOutIndex, split, executor, selector, protocolData - ); + return + abi.encodePacked( + tokenInIndex, + tokenOutIndex, + split, + executor, + selector, + protocolData + ); } function encodeUniswapV2Swap( @@ -218,8 +227,14 @@ contract TychoRouterTestSetup is Test, Constants { bool zero2one ) internal view returns (bytes memory) { IUniswapV3Pool pool = IUniswapV3Pool(target); - return abi.encodePacked( - tokenIn, tokenOut, pool.fee(), receiver, target, zero2one - ); + return + abi.encodePacked( + tokenIn, + tokenOut, + pool.fee(), + receiver, + target, + zero2one + ); } } diff --git a/foundry/test/executors/UniswapV3Executor.t.sol b/foundry/test/executors/UniswapV3Executor.t.sol index 4c9c1e9..36bd8e5 100644 --- a/foundry/test/executors/UniswapV3Executor.t.sol +++ b/foundry/test/executors/UniswapV3Executor.t.sol @@ -6,7 +6,11 @@ import {Test} from "../../lib/forge-std/src/Test.sol"; import {Constants} from "../Constants.sol"; contract UniswapV3ExecutorExposed is UniswapV3Executor { - function decodeData(bytes calldata data) + constructor(address _factory) UniswapV3Executor(_factory) {} + + function decodeData( + bytes calldata data + ) external pure returns ( @@ -22,23 +26,30 @@ contract UniswapV3ExecutorExposed is UniswapV3Executor { } } -contract UniswapV3ExecutorTest is UniswapV3ExecutorExposed, Test, Constants { +contract UniswapV3ExecutorTest is Test, Constants { using SafeERC20 for IERC20; UniswapV3ExecutorExposed uniswapV3Exposed; IERC20 WETH = IERC20(WETH_ADDR); IERC20 DAI = IERC20(DAI_ADDR); + address factory = 0x1F98431c8aD98523631AE4a59f267346ea31F984; function setUp() public { uint256 forkBlock = 17323404; vm.createSelectFork(vm.rpcUrl("mainnet"), forkBlock); - uniswapV3Exposed = new UniswapV3ExecutorExposed(); + + uniswapV3Exposed = new UniswapV3ExecutorExposed(factory); } function testDecodeParams() public view { uint24 expectedPoolFee = 500; bytes memory data = abi.encodePacked( - WETH_ADDR, DAI_ADDR, expectedPoolFee, address(2), address(3), false + WETH_ADDR, + DAI_ADDR, + expectedPoolFee, + address(2), + address(3), + false ); ( @@ -59,8 +70,11 @@ contract UniswapV3ExecutorTest is UniswapV3ExecutorExposed, Test, Constants { } function testDecodeParamsInvalidDataLength() public { - bytes memory invalidParams = - abi.encodePacked(WETH_ADDR, address(2), address(3)); + bytes memory invalidParams = abi.encodePacked( + WETH_ADDR, + address(2), + address(3) + ); vm.expectRevert(UniswapV3Executor__InvalidDataLength.selector); uniswapV3Exposed.decodeData(invalidParams); From 80500e615eedbd3a2b075104787e817b1a1ec42f Mon Sep 17 00:00:00 2001 From: royvardhan Date: Fri, 14 Feb 2025 00:53:43 +0530 Subject: [PATCH 03/15] feat: fix input decoding in usv3 executor and execution dispatcher --- .../lib/v3-updated/CallbackValidationV2.sol | 8 +- foundry/src/ExecutionDispatcher.sol | 8 +- foundry/src/TychoRouter.sol | 99 +++++++-------- foundry/src/executors/BalancerV2Executor.sol | 33 +++-- foundry/src/executors/UniswapV2Executor.sol | 34 +++--- foundry/src/executors/UniswapV3Executor.sol | 72 ++++++----- foundry/src/executors/UniswapV4Executor.sol | 84 ++++++------- foundry/test/TychoRouter.t.sol | 113 +++++------------- foundry/test/TychoRouterTestSetup.sol | 89 ++++++-------- .../test/executors/UniswapV3Executor.t.sol | 18 +-- 10 files changed, 237 insertions(+), 321 deletions(-) diff --git a/foundry/lib/v3-updated/CallbackValidationV2.sol b/foundry/lib/v3-updated/CallbackValidationV2.sol index b673dd2..a3c7a7f 100644 --- a/foundry/lib/v3-updated/CallbackValidationV2.sol +++ b/foundry/lib/v3-updated/CallbackValidationV2.sol @@ -20,9 +20,11 @@ library CallbackValidationV2 { address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { - return verifyCallback( - factory, PoolAddressV2.getPoolKey(tokenA, tokenB, fee) - ); + return + verifyCallback( + factory, + PoolAddressV2.getPoolKey(tokenA, tokenB, fee) + ); } /// @notice Returns the address of a valid Uniswap V3 Pool diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/ExecutionDispatcher.sol index 4b87dbd..973f6f0 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/ExecutionDispatcher.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; +import "forge-std/console.sol"; error ExecutionDispatcher__UnapprovedExecutor(); error ExecutionDispatcher__NonContractExecutor(); @@ -80,11 +81,16 @@ contract ExecutionDispatcher { calculatedAmount = abi.decode(result, (uint256)); } - function _handleCallback(address executor, bytes calldata data) internal { + function _handleCallback(bytes calldata data) internal { + // Take last 20 bytes (excluding the final byte) + address executor = + address(bytes20(data[data.length - 21:data.length - 1])); + if (!executors[executor]) { revert ExecutionDispatcher__UnapprovedExecutor(); } + // slither-disable-next-line controlled-delegatecall,low-level-calls (bool success, bytes memory result) = executor.delegatecall( abi.encodeWithSelector(IExecutor.handleCallback.selector, data) ); diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 9f83c8e..15e45c3 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -57,21 +57,16 @@ contract TychoRouter is uint256 public fee; event Withdrawal( - address indexed token, - uint256 amount, - address indexed receiver + address indexed token, uint256 amount, address indexed receiver ); event FeeReceiverSet( - address indexed oldFeeReceiver, - address indexed newFeeReceiver + address indexed oldFeeReceiver, address indexed newFeeReceiver ); event FeeSet(uint256 indexed oldFee, uint256 indexed newFee); - constructor( - IPoolManager _poolManager, - address _permit2, - address weth - ) SafeCallback(_poolManager) { + constructor(IPoolManager _poolManager, address _permit2, address weth) + SafeCallback(_poolManager) + { if (_permit2 == address(0) || weth == address(0)) { revert TychoRouter__AddressZero(); } @@ -185,11 +180,10 @@ contract TychoRouter is * * @return The total amount of the buy token obtained after all swaps have been executed. */ - function _swap( - uint256 amountIn, - uint256 nTokens, - bytes calldata swaps_ - ) internal returns (uint256) { + function _swap(uint256 amountIn, uint256 nTokens, bytes calldata swaps_) + internal + returns (uint256) + { if (swaps_.length == 0) { revert TychoRouter__EmptySwaps(); } @@ -235,7 +229,7 @@ contract TychoRouter is * caller is not a pool. */ fallback() external { - _handleCallback(msg.sender, msg.data); + _handleCallback(msg.data); } /** @@ -255,10 +249,10 @@ contract TychoRouter is /** * @dev Allows granting roles to multiple accounts in a single call. */ - function batchGrantRole( - bytes32 role, - address[] memory accounts - ) external onlyRole(DEFAULT_ADMIN_ROLE) { + function batchGrantRole(bytes32 role, address[] memory accounts) + external + onlyRole(DEFAULT_ADMIN_ROLE) + { for (uint256 i = 0; i < accounts.length; i++) { _grantRole(role, accounts[i]); } @@ -268,9 +262,10 @@ contract TychoRouter is * @dev Entrypoint to add or replace an approved executor contract address * @param targets address of the executor contract */ - function setExecutors( - address[] memory targets - ) external onlyRole(EXECUTOR_SETTER_ROLE) { + function setExecutors(address[] memory targets) + external + onlyRole(EXECUTOR_SETTER_ROLE) + { for (uint256 i = 0; i < targets.length; i++) { _setExecutor(targets[i]); } @@ -280,9 +275,10 @@ contract TychoRouter is * @dev Entrypoint to remove an approved executor contract address * @param target address of the executor contract */ - function removeExecutor( - address target - ) external onlyRole(EXECUTOR_SETTER_ROLE) { + function removeExecutor(address target) + external + onlyRole(EXECUTOR_SETTER_ROLE) + { _removeExecutor(target); } @@ -290,9 +286,10 @@ contract TychoRouter is * @dev Entrypoint to add or replace an approved callback verifier contract address * @param target address of the callback verifier contract */ - function setCallbackVerifier( - address target - ) external onlyRole(EXECUTOR_SETTER_ROLE) { + function setCallbackVerifier(address target) + external + onlyRole(EXECUTOR_SETTER_ROLE) + { _setCallbackVerifier(target); } @@ -300,18 +297,20 @@ contract TychoRouter is * @dev Entrypoint to remove an approved callback verifier contract address * @param target address of the callback verifier contract */ - function removeCallbackVerifier( - address target - ) external onlyRole(EXECUTOR_SETTER_ROLE) { + function removeCallbackVerifier(address target) + external + onlyRole(EXECUTOR_SETTER_ROLE) + { _removeCallbackVerifier(target); } /** * @dev Allows setting the fee receiver. */ - function setFeeReceiver( - address newfeeReceiver - ) external onlyRole(FEE_SETTER_ROLE) { + function setFeeReceiver(address newfeeReceiver) + external + onlyRole(FEE_SETTER_ROLE) + { if (newfeeReceiver == address(0)) revert TychoRouter__AddressZero(); emit FeeReceiverSet(feeReceiver, newfeeReceiver); feeReceiver = newfeeReceiver; @@ -328,10 +327,10 @@ contract TychoRouter is /** * @dev Allows withdrawing any ERC20 funds if funds get stuck in case of a bug. */ - function withdraw( - IERC20[] memory tokens, - address receiver - ) external onlyRole(FUND_RESCUER_ROLE) { + function withdraw(IERC20[] memory tokens, address receiver) + external + onlyRole(FUND_RESCUER_ROLE) + { if (receiver == address(0)) revert TychoRouter__AddressZero(); for (uint256 i = 0; i < tokens.length; i++) { @@ -348,9 +347,10 @@ contract TychoRouter is * @dev Allows withdrawing any NATIVE funds if funds get stuck in case of a bug. * The contract should never hold any NATIVE tokens for security reasons. */ - function withdrawNative( - address receiver - ) external onlyRole(FUND_RESCUER_ROLE) { + function withdrawNative(address receiver) + external + onlyRole(FUND_RESCUER_ROLE) + { if (receiver == address(0)) revert TychoRouter__AddressZero(); uint256 amount = address(this).balance; @@ -378,9 +378,8 @@ contract TychoRouter is * @param amount of WETH to unwrap. */ function _unwrapETH(uint256 amount) internal { - uint256 unwrapAmount = amount == 0 - ? _weth.balanceOf(address(this)) - : amount; + uint256 unwrapAmount = + amount == 0 ? _weth.balanceOf(address(this)) : amount; _weth.withdraw(unwrapAmount); } @@ -389,9 +388,11 @@ contract TychoRouter is */ receive() external payable {} - function _unlockCallback( - bytes calldata data - ) internal override returns (bytes memory) { + function _unlockCallback(bytes calldata data) + internal + override + returns (bytes memory) + { require(data.length >= 20, "Invalid data length"); bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); address executor = address(uint160(bytes20(data[data.length - 20:]))); @@ -402,7 +403,7 @@ contract TychoRouter is } // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success, ) = executor.delegatecall( + (bool success,) = executor.delegatecall( abi.encodeWithSelector(selector, protocolData) ); require(success, "delegatecall to uniswap v4 callback failed"); diff --git a/foundry/src/executors/BalancerV2Executor.sol b/foundry/src/executors/BalancerV2Executor.sol index f769d2e..a328715 100644 --- a/foundry/src/executors/BalancerV2Executor.sol +++ b/foundry/src/executors/BalancerV2Executor.sol @@ -2,7 +2,10 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import { + IERC20, + SafeERC20 +} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // slither-disable-next-line solc-version import {IAsset} from "@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol"; // slither-disable-next-line solc-version @@ -16,10 +19,11 @@ contract BalancerV2Executor is IExecutor { address private constant VAULT = 0xBA12222222228d8Ba445958a75a0704d566BF2C8; // slither-disable-next-line locked-ether - function swap( - uint256 givenAmount, - bytes calldata data - ) external payable returns (uint256 calculatedAmount) { + function swap(uint256 givenAmount, bytes calldata data) + external + payable + returns (uint256 calculatedAmount) + { ( IERC20 tokenIn, IERC20 tokenOut, @@ -51,21 +55,16 @@ contract BalancerV2Executor is IExecutor { uint256 limit = 0; - calculatedAmount = IVault(VAULT).swap( - singleSwap, - funds, - limit, - block.timestamp - ); + calculatedAmount = + IVault(VAULT).swap(singleSwap, funds, limit, block.timestamp); } - function handleCallback( - bytes calldata data - ) external returns (bytes memory result) {} + function handleCallback(bytes calldata data) + external + returns (bytes memory result) + {} - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( diff --git a/foundry/src/executors/UniswapV2Executor.sol b/foundry/src/executors/UniswapV2Executor.sol index f8cf820..870ef74 100644 --- a/foundry/src/executors/UniswapV2Executor.sol +++ b/foundry/src/executors/UniswapV2Executor.sol @@ -11,10 +11,11 @@ contract UniswapV2Executor is IExecutor { using SafeERC20 for IERC20; // slither-disable-next-line locked-ether - function swap( - uint256 givenAmount, - bytes calldata data - ) external payable returns (uint256 calculatedAmount) { + function swap(uint256 givenAmount, bytes calldata data) + external + payable + returns (uint256 calculatedAmount) + { address target; address receiver; bool zeroForOne; @@ -32,13 +33,12 @@ contract UniswapV2Executor is IExecutor { } } - function handleCallback( - bytes calldata data - ) external returns (bytes memory result) {} + function handleCallback(bytes calldata data) + external + returns (bytes memory result) + {} - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( @@ -57,20 +57,20 @@ contract UniswapV2Executor is IExecutor { zeroForOne = uint8(data[60]) > 0; } - function _getAmountOut( - address target, - uint256 amountIn, - bool zeroForOne - ) internal view returns (uint256 amount) { + function _getAmountOut(address target, uint256 amountIn, bool zeroForOne) + internal + view + returns (uint256 amount) + { IUniswapV2Pair pair = IUniswapV2Pair(target); uint112 reserveIn; uint112 reserveOut; if (zeroForOne) { // slither-disable-next-line unused-return - (reserveIn, reserveOut, ) = pair.getReserves(); + (reserveIn, reserveOut,) = pair.getReserves(); } else { // slither-disable-next-line unused-return - (reserveOut, reserveIn, ) = pair.getReserves(); + (reserveOut, reserveIn,) = pair.getReserves(); } require(reserveIn > 0 && reserveOut > 0, "L"); diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index 060f27f..f5b6c06 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -7,6 +7,7 @@ import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-updated/CallbackValidationV2.sol"; error UniswapV3Executor__InvalidDataLength(); +error UniswapV3Executor__InvalidFactory(); contract UniswapV3Executor is IExecutor { using SafeERC20 for IERC20; @@ -16,16 +17,22 @@ contract UniswapV3Executor is IExecutor { 1461446703485210103287273052203988822378723970342; address public immutable factory; + address private immutable self; constructor(address _factory) { + if (_factory == address(0)) { + revert UniswapV3Executor__InvalidFactory(); + } factory = _factory; + self = address(this); } // slither-disable-next-line locked-ether - function swap( - uint256 amountIn, - bytes calldata data - ) external payable returns (uint256 amountOut) { + function swap(uint256 amountIn, bytes calldata data) + external + payable + returns (uint256 amountOut) + { ( address tokenIn, address tokenOut, @@ -58,23 +65,19 @@ contract UniswapV3Executor is IExecutor { } } - function handleCallback( - bytes calldata msgData - ) external returns (bytes memory result) { - int256 amount0Delta; - int256 amount1Delta; + function handleCallback(bytes calldata msgData) + external + returns (bytes memory result) + { + // Skip first 4 bytes of function selector and decode the two int256 values + (int256 amount0Delta, int256 amount1Delta) = + abi.decode(msgData[4:68], (int256, int256)); - (amount0Delta, amount1Delta) = abi.decode( - msgData[:64], - (int256, int256) - ); + bytes calldata remainingData = msgData[68:]; + + (uint256 amountOwed, address tokenOwed) = + _verifyUSV3Callback(amount0Delta, amount1Delta, remainingData); - bytes calldata remainingData = msgData[64:]; - (uint256 amountOwed, address tokenOwed) = _verifyUSV3Callback( - amount0Delta, - amount1Delta, - remainingData - ); IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); return abi.encode(amountOwed, tokenOwed); } @@ -84,28 +87,23 @@ contract UniswapV3Executor is IExecutor { int256 amount1Delta, bytes calldata data ) internal view returns (uint256 amountIn, address tokenIn) { + // Skip the first 64 bytes (32 bytes offset + 32 bytes length) + data = data[64:]; + tokenIn = address(bytes20(data[0:20])); address tokenOut = address(bytes20(data[20:40])); uint24 poolFee = uint24(bytes3(data[40:43])); // slither-disable-next-line unused-return - CallbackValidationV2.verifyCallback( - factory, - tokenIn, - tokenOut, - poolFee - ); + CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); - amountIn = amount0Delta > 0 - ? uint256(amount0Delta) - : uint256(amount1Delta); + amountIn = + amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); return (amountIn, tokenIn); } - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( @@ -128,11 +126,11 @@ contract UniswapV3Executor is IExecutor { zeroForOne = uint8(data[83]) > 0; } - function _makeV3CallbackData( - address tokenIn, - address tokenOut, - uint24 fee - ) internal pure returns (bytes memory) { - return abi.encodePacked(tokenIn, tokenOut, fee); + function _makeV3CallbackData(address tokenIn, address tokenOut, uint24 fee) + internal + view + returns (bytes memory) + { + return abi.encodePacked(tokenIn, tokenOut, fee, self); } } diff --git a/foundry/src/executors/UniswapV4Executor.sol b/foundry/src/executors/UniswapV4Executor.sol index bda2e11..c365a89 100644 --- a/foundry/src/executors/UniswapV4Executor.sol +++ b/foundry/src/executors/UniswapV4Executor.sol @@ -2,9 +2,14 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import { + IERC20, + SafeERC20 +} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; -import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol"; +import { + Currency, CurrencyLibrary +} from "@uniswap/v4-core/src/types/Currency.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {V4Router} from "@uniswap/v4-periphery/src/V4Router.sol"; @@ -21,16 +26,13 @@ contract UniswapV4Executor is IExecutor, V4Router { constructor(IPoolManager _poolManager) V4Router(_poolManager) {} - function swap( - uint256, - bytes calldata data - ) external payable returns (uint256 calculatedAmount) { - ( - address tokenIn, - address tokenOut, - bool isExactInput, - uint256 amount - ) = _decodeData(data); + function swap(uint256, bytes calldata data) + external + payable + returns (uint256 calculatedAmount) + { + (address tokenIn, address tokenOut, bool isExactInput, uint256 amount) = + _decodeData(data); uint256 tokenOutBalanceBefore; uint256 tokenInBalanceBefore; @@ -65,9 +67,7 @@ contract UniswapV4Executor is IExecutor, V4Router { return calculatedAmount; } - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( @@ -77,19 +77,15 @@ contract UniswapV4Executor is IExecutor, V4Router { uint256 amount ) { - (bytes memory actions, bytes[] memory params) = abi.decode( - data, - (bytes, bytes[]) - ); + (bytes memory actions, bytes[] memory params) = + abi.decode(data, (bytes, bytes[])); // First byte of actions determines the swap type uint8 action = uint8(bytes1(actions[0])); if (action == uint8(Actions.SWAP_EXACT_IN_SINGLE)) { - IV4Router.ExactInputSingleParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactInputSingleParams) - ); + IV4Router.ExactInputSingleParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactInputSingleParams)); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -100,10 +96,8 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT_SINGLE)) { - IV4Router.ExactOutputSingleParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactOutputSingleParams) - ); + IV4Router.ExactOutputSingleParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactOutputSingleParams)); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -114,23 +108,18 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = false; amount = swapParams.amountOut; } else if (action == uint8(Actions.SWAP_EXACT_IN)) { - IV4Router.ExactInputParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactInputParams) - ); + IV4Router.ExactInputParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactInputParams)); tokenIn = address(uint160(swapParams.currencyIn.toId())); - PathKey memory lastPath = swapParams.path[ - swapParams.path.length - 1 - ]; + PathKey memory lastPath = + swapParams.path[swapParams.path.length - 1]; tokenOut = address(uint160(lastPath.intermediateCurrency.toId())); isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT)) { - IV4Router.ExactOutputParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactOutputParams) - ); + IV4Router.ExactOutputParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactOutputParams)); PathKey memory firstPath = swapParams.path[0]; tokenIn = address(uint160(firstPath.intermediateCurrency.toId())); @@ -140,14 +129,12 @@ contract UniswapV4Executor is IExecutor, V4Router { } } - function _pay( - Currency token, - address payer, - uint256 amount - ) internal override { + function _pay(Currency token, address payer, uint256 amount) + internal + override + { IERC20(Currency.unwrap(token)).safeTransfer( - address(poolManager), - amount + address(poolManager), amount ); } @@ -155,7 +142,8 @@ contract UniswapV4Executor is IExecutor, V4Router { return address(this); } - function handleCallback( - bytes calldata data - ) external returns (bytes memory result) {} + function handleCallback(bytes calldata data) + external + returns (bytes memory result) + {} } diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index b7bbc9c..095af50 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -18,9 +18,7 @@ contract TychoRouterTest is TychoRouterTestSetup { event CallbackVerifierSet(address indexed callbackVerifier); event Withdrawal( - address indexed token, - uint256 amount, - address indexed receiver + address indexed token, uint256 amount, address indexed receiver ); function testSetExecutorsValidRole() public { @@ -241,10 +239,7 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(WETH_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -281,10 +276,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ) ); @@ -323,10 +315,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, - WETH_WBTC_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_WBTC_POOL, tychoRouterAddr, false ) ); // WBTC -> USDC @@ -337,10 +326,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WBTC_ADDR, - USDC_WBTC_POOL, - tychoRouterAddr, - true + WBTC_ADDR, USDC_WBTC_POOL, tychoRouterAddr, true ) ); // WETH -> DAI @@ -351,10 +337,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ) ); @@ -390,10 +373,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -446,10 +426,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -508,10 +485,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -543,10 +517,7 @@ contract TychoRouterTest is TychoRouterTestSetup { assertEq(amountOut, expectedAmount); uint256 daiBalance = IERC20(DAI_ADDR).balanceOf(ALICE); assertEq(daiBalance, expectedAmount); - assertEq( - IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), - 26598819248184436997 - ); + assertEq(IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), 26598819248184436997); vm.stopPrank(); } @@ -559,22 +530,19 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.startPrank(ALICE); - IAllowanceTransfer.PermitSingle - memory emptyPermitSingle = IAllowanceTransfer.PermitSingle({ - details: IAllowanceTransfer.PermitDetails({ - token: address(0), - amount: 0, - expiration: 0, - nonce: 0 - }), - spender: address(0), - sigDeadline: 0 - }); + IAllowanceTransfer.PermitSingle memory emptyPermitSingle = + IAllowanceTransfer.PermitSingle({ + details: IAllowanceTransfer.PermitDetails({ + token: address(0), + amount: 0, + expiration: 0, + nonce: 0 + }), + spender: address(0), + sigDeadline: 0 + }); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -623,12 +591,8 @@ contract TychoRouterTest is TychoRouterTestSetup { bytes memory signature ) = handlePermit2Approval(DAI_ADDR, amountIn); - bytes memory protocolData = encodeUniswapV2Swap( - DAI_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - true - ); + bytes memory protocolData = + encodeUniswapV2Swap(DAI_ADDR, WETH_DAI_POOL, tychoRouterAddr, true); bytes memory swap = encodeSwap( uint8(0), @@ -690,11 +654,7 @@ contract TychoRouterTest is TychoRouterTestSetup { uint256 expAmountOut = 1205_128428842122129186; //Swap 1 WETH for 1205.12 DAI bool zeroForOne = false; bytes memory protocolData = encodeUniswapV3Swap( - WETH_ADDR, - DAI_ADDR, - tychoRouterAddr, - DAI_WETH_USV3, - zeroForOne + WETH_ADDR, DAI_ADDR, tychoRouterAddr, DAI_WETH_USV3, zeroForOne ); bytes memory swap = encodeSwap( uint8(0), @@ -736,7 +696,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call( + (bool success,) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d481bb00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfbc3000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041f2740fde9662d8bc1f8fe8e8fc29447c1832d625f06f4a56ee5103ad555c12323af5d50eb840f73d17873383ae3b7573956d5df7b2bf76bddba768c2837894a51b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -765,7 +725,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call{value: 1 ether}( + (bool success,) = tychoRouterAddr.call{value: 1 ether}( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4806b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfa73000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041c36406a750c499ac7f79f7666650f0d4f20fc27bb49ab68121c0be6554cb5cab6caf90dc3aab2e21083a8fa46976521a1e9df41ce74be59abf03e0d3691541e91c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00020000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -794,7 +754,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call( + (bool success,) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000000000000000000000000000000000000067d4809800000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfaa000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000004146411c70ec7fee0d5d260803cb220f5365792426c5d94f7a0a4d37abb05205752c5418b1fadd059570a71f0911814e546728e1f21876f2a1c6d38d34bd235fd61c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fa478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950100000000" ); @@ -825,7 +785,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call( + (bool success,) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4810d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfb15000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041ecaab75f0791c9683b001ea2f0e01a0a6aaf03e6e49c83e9c8a8e588a38e3be9230d962926628ffbf6a5370cda559ff0e7876a63ed38eebe33dbef5b5e2e46ef1b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000170005a00028000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d0139500005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2bb2b8038a1640196fbe3e38816f3e67cba72d9403ede3eca2a72b3aecc820e955b36f38437d0139500005a02030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fae461ca67b15dc8dc81ce7615e0320da1a9ab8d53ede3eca2a72b3aecc820e955b36f38437d0139501005a01030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab2260fac5e5542a773aa44fbcfedf7c193bc2c599004375dff511095cc5a197a54140a24efef3a4163ede3eca2a72b3aecc820e955b36f38437d013950100000000000000000000000000000000" ); @@ -855,10 +815,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -875,8 +832,7 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.expectRevert( abi.encodeWithSelector( - TychoRouter__AmountInNotFullySpent.selector, - 400000000000000000 + TychoRouter__AmountInNotFullySpent.selector, 400000000000000000 ) ); @@ -902,12 +858,7 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(USDE_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = UniswapV4Utils.encodeExactInputSingle( - USDE_ADDR, - USDT_ADDR, - 100, - true, - 1, - uint128(amountIn) + USDE_ADDR, USDT_ADDR, 100, true, 1, uint128(amountIn) ); // add executor and selector for callback diff --git a/foundry/test/TychoRouterTestSetup.sol b/foundry/test/TychoRouterTestSetup.sol index 42cf7ba..ef913fd 100644 --- a/foundry/test/TychoRouterTestSetup.sol +++ b/foundry/test/TychoRouterTestSetup.sol @@ -12,11 +12,9 @@ import {WETH} from "../lib/permit2/lib/solmate/src/tokens/WETH.sol"; import {PoolManager} from "@uniswap/v4-core/src/PoolManager.sol"; contract TychoRouterExposed is TychoRouter { - constructor( - IPoolManager _poolManager, - address _permit2, - address weth - ) TychoRouter(_poolManager, _permit2, weth) {} + constructor(IPoolManager _poolManager, address _permit2, address weth) + TychoRouter(_poolManager, _permit2, weth) + {} function wrapETH(uint256 amount) external payable { return _wrapETH(amount); @@ -38,8 +36,7 @@ contract TychoRouterExposed is TychoRouter { contract TychoRouterTestSetup is Test, Constants { TychoRouterExposed tychoRouter; address tychoRouterAddr; - address permit2Address = - address(0x000000000022D473030F116dDEE9F6B43aC78BA3); + address permit2Address = address(0x000000000022D473030F116dDEE9F6B43aC78BA3); UniswapV2Executor public usv2Executor; UniswapV3Executor public usv3Executor; UniswapV4Executor public usv4Executor; @@ -53,19 +50,15 @@ contract TychoRouterTestSetup is Test, Constants { address factoryV3 = address(0x1F98431c8aD98523631AE4a59f267346ea31F984); address poolManagerAddress = 0x000000000004444c5dc75cB358380D2e3dE08A90; IPoolManager poolManager = IPoolManager(poolManagerAddress); - tychoRouter = new TychoRouterExposed( - poolManager, - permit2Address, - WETH_ADDR - ); + tychoRouter = + new TychoRouterExposed(poolManager, permit2Address, WETH_ADDR); tychoRouterAddr = address(tychoRouter); tychoRouter.grantRole(keccak256("FUND_RESCUER_ROLE"), FUND_RESCUER); tychoRouter.grantRole(keccak256("FEE_SETTER_ROLE"), FEE_SETTER); tychoRouter.grantRole(keccak256("PAUSER_ROLE"), PAUSER); tychoRouter.grantRole(keccak256("UNPAUSER_ROLE"), UNPAUSER); tychoRouter.grantRole( - keccak256("EXECUTOR_SETTER_ROLE"), - EXECUTOR_SETTER + keccak256("EXECUTOR_SETTER_ROLE"), EXECUTOR_SETTER ); deployDummyContract(); vm.stopPrank(); @@ -113,22 +106,22 @@ contract TychoRouterTestSetup is Test, Constants { * @return permitSingle The `PermitSingle` struct containing the approval details. * @return signature The EIP-712 signature for the approval. */ - function handlePermit2Approval( - address tokenIn, - uint256 amount_in - ) internal returns (IAllowanceTransfer.PermitSingle memory, bytes memory) { + function handlePermit2Approval(address tokenIn, uint256 amount_in) + internal + returns (IAllowanceTransfer.PermitSingle memory, bytes memory) + { IERC20(tokenIn).approve(permit2Address, amount_in); IAllowanceTransfer.PermitSingle memory permitSingle = IAllowanceTransfer .PermitSingle({ - details: IAllowanceTransfer.PermitDetails({ - token: tokenIn, - amount: uint160(amount_in), - expiration: uint48(block.timestamp + 1 days), - nonce: 0 - }), - spender: tychoRouterAddr, - sigDeadline: block.timestamp + 1 days - }); + details: IAllowanceTransfer.PermitDetails({ + token: tokenIn, + amount: uint160(amount_in), + expiration: uint48(block.timestamp + 1 days), + nonce: 0 + }), + spender: tychoRouterAddr, + sigDeadline: block.timestamp + 1 days + }); bytes memory signature = signPermit2(permitSingle, ALICE_PK); return (permitSingle, signature); @@ -160,9 +153,8 @@ contract TychoRouterTestSetup is Test, Constants { permit2Address ) ); - bytes32 detailsHash = keccak256( - abi.encode(_PERMIT_DETAILS_TYPEHASH, permit.details) - ); + bytes32 detailsHash = + keccak256(abi.encode(_PERMIT_DETAILS_TYPEHASH, permit.details)); bytes32 permitHash = keccak256( abi.encode( _PERMIT_SINGLE_TYPEHASH, @@ -172,17 +164,18 @@ contract TychoRouterTestSetup is Test, Constants { ) ); - bytes32 digest = keccak256( - abi.encodePacked("\x19\x01", domainSeparator, permitHash) - ); + bytes32 digest = + keccak256(abi.encodePacked("\x19\x01", domainSeparator, permitHash)); (uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, digest); return abi.encodePacked(r, s, v); } - function pleEncode( - bytes[] memory data - ) public pure returns (bytes memory encoded) { + function pleEncode(bytes[] memory data) + public + pure + returns (bytes memory encoded) + { for (uint256 i = 0; i < data.length; i++) { encoded = bytes.concat( encoded, @@ -199,15 +192,9 @@ contract TychoRouterTestSetup is Test, Constants { bytes4 selector, bytes memory protocolData ) internal pure returns (bytes memory) { - return - abi.encodePacked( - tokenInIndex, - tokenOutIndex, - split, - executor, - selector, - protocolData - ); + return abi.encodePacked( + tokenInIndex, tokenOutIndex, split, executor, selector, protocolData + ); } function encodeUniswapV2Swap( @@ -227,14 +214,8 @@ contract TychoRouterTestSetup is Test, Constants { bool zero2one ) internal view returns (bytes memory) { IUniswapV3Pool pool = IUniswapV3Pool(target); - return - abi.encodePacked( - tokenIn, - tokenOut, - pool.fee(), - receiver, - target, - zero2one - ); + return abi.encodePacked( + tokenIn, tokenOut, pool.fee(), receiver, target, zero2one + ); } } diff --git a/foundry/test/executors/UniswapV3Executor.t.sol b/foundry/test/executors/UniswapV3Executor.t.sol index 36bd8e5..2116cb1 100644 --- a/foundry/test/executors/UniswapV3Executor.t.sol +++ b/foundry/test/executors/UniswapV3Executor.t.sol @@ -8,9 +8,7 @@ import {Constants} from "../Constants.sol"; contract UniswapV3ExecutorExposed is UniswapV3Executor { constructor(address _factory) UniswapV3Executor(_factory) {} - function decodeData( - bytes calldata data - ) + function decodeData(bytes calldata data) external pure returns ( @@ -44,12 +42,7 @@ contract UniswapV3ExecutorTest is Test, Constants { function testDecodeParams() public view { uint24 expectedPoolFee = 500; bytes memory data = abi.encodePacked( - WETH_ADDR, - DAI_ADDR, - expectedPoolFee, - address(2), - address(3), - false + WETH_ADDR, DAI_ADDR, expectedPoolFee, address(2), address(3), false ); ( @@ -70,11 +63,8 @@ contract UniswapV3ExecutorTest is Test, Constants { } function testDecodeParamsInvalidDataLength() public { - bytes memory invalidParams = abi.encodePacked( - WETH_ADDR, - address(2), - address(3) - ); + bytes memory invalidParams = + abi.encodePacked(WETH_ADDR, address(2), address(3)); vm.expectRevert(UniswapV3Executor__InvalidDataLength.selector); uniswapV3Exposed.decodeData(invalidParams); From 5853de679ad0182ce75467245054d28b916d518f Mon Sep 17 00:00:00 2001 From: royvardhan Date: Fri, 14 Feb 2025 01:29:30 +0530 Subject: [PATCH 04/15] feat: move callback testing to usv3 executor --- foundry/src/ExecutionDispatcher.sol | 1 - foundry/src/executors/UniswapV4Executor.sol | 3 -- foundry/test/TychoRouter.t.sol | 18 -------- .../test/executors/UniswapV3Executor.t.sol | 44 +++++++++++++++++++ 4 files changed, 44 insertions(+), 22 deletions(-) diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/ExecutionDispatcher.sol index 973f6f0..eae85dc 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/ExecutionDispatcher.sol @@ -2,7 +2,6 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import "forge-std/console.sol"; error ExecutionDispatcher__UnapprovedExecutor(); error ExecutionDispatcher__NonContractExecutor(); diff --git a/foundry/src/executors/UniswapV4Executor.sol b/foundry/src/executors/UniswapV4Executor.sol index c365a89..2a2e40b 100644 --- a/foundry/src/executors/UniswapV4Executor.sol +++ b/foundry/src/executors/UniswapV4Executor.sol @@ -17,9 +17,6 @@ import {Actions} from "@uniswap/v4-periphery/src/libraries/Actions.sol"; import {IV4Router} from "@uniswap/v4-periphery/src/interfaces/IV4Router.sol"; import {PathKey} from "@uniswap/v4-periphery/src/libraries/PathKey.sol"; -error UniswapV4Executor__InvalidDataLength(); -error UniswapV4Executor__SwapFailed(); - contract UniswapV4Executor is IExecutor, V4Router { using SafeERC20 for IERC20; using CurrencyLibrary for Currency; diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index 095af50..bfbca0b 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -626,24 +626,6 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.stopPrank(); } - // function testUSV3Callback() public { - // uint24 poolFee = 3000; - // uint256 amountOwed = 1000000000000000000; - // deal(WETH_ADDR, tychoRouterAddr, amountOwed); - // uint256 initialPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); - - // vm.startPrank(DAI_WETH_USV3); - // tychoRouter.uniswapV3SwapCallback( - // -2631245338449998525223, - // int256(amountOwed), - // abi.encodePacked(WETH_ADDR, DAI_ADDR, poolFee) - // ); - // vm.stopPrank(); - - // uint256 finalPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); - // assertEq(finalPoolReserve - initialPoolReserve, amountOwed); - // } - function testSwapSingleUSV3() public { // Trade 1 WETH for DAI with 1 swap on Uniswap V3 // 1 WETH -> DAI diff --git a/foundry/test/executors/UniswapV3Executor.t.sol b/foundry/test/executors/UniswapV3Executor.t.sol index 2116cb1..e0d1638 100644 --- a/foundry/test/executors/UniswapV3Executor.t.sol +++ b/foundry/test/executors/UniswapV3Executor.t.sol @@ -69,4 +69,48 @@ contract UniswapV3ExecutorTest is Test, Constants { vm.expectRevert(UniswapV3Executor__InvalidDataLength.selector); uniswapV3Exposed.decodeData(invalidParams); } + + function testUSV3Callback() public { + uint24 poolFee = 3000; + uint256 amountOwed = 1000000000000000000; + deal(WETH_ADDR, address(uniswapV3Exposed), amountOwed); + uint256 initialPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); + + vm.startPrank(DAI_WETH_USV3); + bytes memory callbackData = _encodeUSV3CallbackData( + int256(amountOwed), // amount0Delta + int256(0), // amount1Delta + WETH_ADDR, + DAI_ADDR, + poolFee + ); + uniswapV3Exposed.handleCallback(callbackData); + vm.stopPrank(); + + uint256 finalPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); + assertEq(finalPoolReserve - initialPoolReserve, amountOwed); + } + + function _encodeUSV3CallbackData( + int256 amount0Delta, + int256 amount1Delta, + address tokenIn, + address tokenOut, + uint24 fee + ) internal pure returns (bytes memory) { + // Dummy selector for handleCallback + bytes4 selector = + bytes4(keccak256("handleCallback(int256,int256,bytes)")); + + bytes memory tokenData = abi.encodePacked(tokenIn, tokenOut, fee); + + // [0:4] - function selector + // [4:68] - abi.encode(amount0Delta, amount1Delta) + // [68:end] - abi.encode(tokenData) where tokenData is the packed bytes + return abi.encodePacked( + selector, + abi.encode(amount0Delta, amount1Delta), + abi.encode(tokenData) + ); + } } From 260f9d866f9cd58d0739e24e6abcd08cb3ad4a45 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Fri, 14 Feb 2025 23:00:23 +0530 Subject: [PATCH 05/15] feat: add back uniswapV3SwapCallback in router --- foundry/src/ExecutionDispatcher.sol | 21 +++++++++++++------- foundry/src/TychoRouter.sol | 22 ++++++++++++++++++--- foundry/src/executors/UniswapV3Executor.sol | 9 +++------ 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/ExecutionDispatcher.sol index eae85dc..1283b41 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/ExecutionDispatcher.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; +import "forge-std/console.sol"; error ExecutionDispatcher__UnapprovedExecutor(); error ExecutionDispatcher__NonContractExecutor(); @@ -80,19 +81,25 @@ contract ExecutionDispatcher { calculatedAmount = abi.decode(result, (uint256)); } - function _handleCallback(bytes calldata data) internal { - // Take last 20 bytes (excluding the final byte) - address executor = - address(bytes20(data[data.length - 21:data.length - 1])); + function _handleCallback(bytes4 selector, bytes memory data) internal { + // Access the last 20 bytes of the bytes memory data using assembly + address executor; + // slither-disable-next-line assembly + assembly { + let pos := sub(add(add(data, 0x20), mload(data)), 20) + executor := mload(pos) + executor := shr(96, executor) + } if (!executors[executor]) { revert ExecutionDispatcher__UnapprovedExecutor(); } + selector = + selector == bytes4(0) ? IExecutor.handleCallback.selector : selector; // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success, bytes memory result) = executor.delegatecall( - abi.encodeWithSelector(IExecutor.handleCallback.selector, data) - ); + (bool success, bytes memory result) = + executor.delegatecall(abi.encodeWithSelector(selector, data)); if (!success) { revert( diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 15e45c3..8084afc 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -15,6 +15,7 @@ import "./ExecutionDispatcher.sol"; import {LibSwap} from "../lib/LibSwap.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {SafeCallback} from "@uniswap/v4-periphery/src/base/SafeCallback.sol"; +import "forge-std/console.sol"; error TychoRouter__WithdrawalFailed(); error TychoRouter__AddressZero(); @@ -228,9 +229,10 @@ contract TychoRouter is * This function will static call a verifier contract and should revert if the * caller is not a pool. */ - fallback() external { - _handleCallback(msg.data); - } + // fallback() external { + // bytes4 selector = bytes4(msg.data[:4]); + // _handleCallback(selector, msg.data[4:]); + // } /** * @dev Pauses the contract @@ -388,6 +390,20 @@ contract TychoRouter is */ receive() external payable {} + /** + * @dev Called by UniswapV3 pool when swapping on it. + * See in IUniswapV3SwapCallback for documentation. + */ + function uniswapV3SwapCallback( + int256 amount0Delta, + int256 amount1Delta, + bytes calldata msgData + ) external { + _handleCallback( + bytes4(0), abi.encodePacked(amount0Delta, amount1Delta, msgData) + ); + } + function _unlockCallback(bytes calldata data) internal override diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index f5b6c06..906c771 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -5,6 +5,7 @@ import "@interfaces/IExecutor.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-updated/CallbackValidationV2.sol"; +import "forge-std/console.sol"; error UniswapV3Executor__InvalidDataLength(); error UniswapV3Executor__InvalidFactory(); @@ -69,11 +70,10 @@ contract UniswapV3Executor is IExecutor { external returns (bytes memory result) { - // Skip first 4 bytes of function selector and decode the two int256 values (int256 amount0Delta, int256 amount1Delta) = - abi.decode(msgData[4:68], (int256, int256)); + abi.decode(msgData[:64], (int256, int256)); - bytes calldata remainingData = msgData[68:]; + bytes calldata remainingData = msgData[64:]; (uint256 amountOwed, address tokenOwed) = _verifyUSV3Callback(amount0Delta, amount1Delta, remainingData); @@ -87,9 +87,6 @@ contract UniswapV3Executor is IExecutor { int256 amount1Delta, bytes calldata data ) internal view returns (uint256 amountIn, address tokenIn) { - // Skip the first 64 bytes (32 bytes offset + 32 bytes length) - data = data[64:]; - tokenIn = address(bytes20(data[0:20])); address tokenOut = address(bytes20(data[20:40])); uint24 poolFee = uint24(bytes3(data[40:43])); From d0027e6cf2da5b4f5fb743f1aa994f94b34a22f4 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Fri, 14 Feb 2025 23:11:01 +0530 Subject: [PATCH 06/15] refactor: rm callback verifier dispatcher --- foundry/interfaces/ICallback.sol | 10 + foundry/interfaces/ICallbackVerifier.sol | 14 -- foundry/interfaces/IExecutor.sol | 4 - .../src/CallbackVerificationDispatcher.sol | 99 ---------- foundry/src/ExecutionDispatcher.sol | 11 +- foundry/src/TychoRouter.sol | 111 +++++------ foundry/src/executors/BalancerV2Executor.sol | 31 ++- foundry/src/executors/UniswapV2Executor.sol | 32 ++-- foundry/src/executors/UniswapV4Executor.sol | 82 ++++---- .../test/CallbackVerificationDispatcher.t.sol | 180 ------------------ foundry/test/TychoRouter.t.sol | 138 ++++++++------ 11 files changed, 216 insertions(+), 496 deletions(-) create mode 100644 foundry/interfaces/ICallback.sol delete mode 100644 foundry/interfaces/ICallbackVerifier.sol delete mode 100644 foundry/src/CallbackVerificationDispatcher.sol delete mode 100644 foundry/test/CallbackVerificationDispatcher.t.sol diff --git a/foundry/interfaces/ICallback.sol b/foundry/interfaces/ICallback.sol new file mode 100644 index 0000000..38decfa --- /dev/null +++ b/foundry/interfaces/ICallback.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.26; + +interface ICallback { + error UnauthorizedCaller(string exchange, address sender); + + function handleCallback( + bytes calldata data + ) external returns (bytes memory result); +} diff --git a/foundry/interfaces/ICallbackVerifier.sol b/foundry/interfaces/ICallbackVerifier.sol deleted file mode 100644 index 612279c..0000000 --- a/foundry/interfaces/ICallbackVerifier.sol +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity ^0.8.26; - -interface ICallbackVerifier { - error UnauthorizedCaller(string exchange, address sender); - - /** - * @dev This method should revert if the sender is not a verified sender of the exchange. - */ - function verifyCallback( - address sender, - bytes calldata data - ) external returns (uint256 amountOwed, address tokenOwed); -} diff --git a/foundry/interfaces/IExecutor.sol b/foundry/interfaces/IExecutor.sol index 5e595a3..0a60022 100644 --- a/foundry/interfaces/IExecutor.sol +++ b/foundry/interfaces/IExecutor.sol @@ -24,10 +24,6 @@ interface IExecutor { uint256 givenAmount, bytes calldata data ) external payable returns (uint256 calculatedAmount); - - function handleCallback( - bytes calldata callbackData - ) external returns (bytes memory result); } interface IExecutorErrors { diff --git a/foundry/src/CallbackVerificationDispatcher.sol b/foundry/src/CallbackVerificationDispatcher.sol deleted file mode 100644 index 8df5848..0000000 --- a/foundry/src/CallbackVerificationDispatcher.sol +++ /dev/null @@ -1,99 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity ^0.8.26; - -import "@interfaces/ICallbackVerifier.sol"; - -error CallbackVerificationDispatcher__UnapprovedVerifier(); -error CallbackVerificationDispatcher__NonContractVerifier(); - -/** - * @title Dispatch callback verification to external contracts - * @author PropellerHeads Devs - * @dev Provides the ability call external contracts to perform callback - * verification. This allows dynamically adding new supported protocols - * without needing to upgrade any contracts. - * - * Note: Verifier contracts need to implement the ICallbackVerifier interface - */ -contract CallbackVerificationDispatcher { - mapping(address => bool) public callbackVerifiers; - - event CallbackVerifierSet(address indexed callbackVerifier); - event CallbackVerifierRemoved(address indexed callbackVerifier); - - /** - * @dev Adds or replaces an approved callback verifier contract address if it is a - * contract. - * @param target address of the callback verifier contract - */ - function _setCallbackVerifier(address target) internal { - if (target.code.length == 0) { - revert CallbackVerificationDispatcher__NonContractVerifier(); - } - callbackVerifiers[target] = true; - emit CallbackVerifierSet(target); - } - - /** - * @dev Removes an approved callback verifier contract address - * @param target address of the callback verifier contract - */ - function _removeCallbackVerifier(address target) internal { - delete callbackVerifiers[target]; - emit CallbackVerifierRemoved(target); - } - - /** - * @dev Calls a callback verifier. This should revert if the callback verification fails. - */ - // slither-disable-next-line dead-code - function _callVerifyCallback(bytes calldata data) - internal - view - returns (uint256 amountOwed, address tokenOwed) - { - address verifier; - bytes4 decodedSelector; - bytes memory verifierData; - - (verifier, decodedSelector, verifierData) = - _decodeVerifierAndSelector(data); - - if (!callbackVerifiers[verifier]) { - revert CallbackVerificationDispatcher__UnapprovedVerifier(); - } - - bytes4 selector = decodedSelector == bytes4(0) - ? ICallbackVerifier.verifyCallback.selector - : decodedSelector; - - address sender = msg.sender; - - // slither-disable-next-line low-level-calls - (bool success, bytes memory result) = verifier.staticcall( - abi.encodeWithSelector(selector, sender, verifierData) - ); - - if (!success) { - if (result.length > 0) { - revert(string(result)); - } else { - revert("Callback verification failed"); - } - } - - (amountOwed, tokenOwed) = abi.decode(result, (uint256, address)); - } - - // slither-disable-next-line dead-code - function _decodeVerifierAndSelector(bytes calldata data) - internal - pure - returns (address verifier, bytes4 selector, bytes memory verifierData) - { - require(data.length >= 20, "Invalid data length"); - verifier = address(uint160(bytes20(data[:20]))); - selector = bytes4(data[20:24]); - verifierData = data[24:]; - } -} diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/ExecutionDispatcher.sol index 1283b41..c48caca 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/ExecutionDispatcher.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; +import "@interfaces/ICallback.sol"; import "forge-std/console.sol"; error ExecutionDispatcher__UnapprovedExecutor(); @@ -95,11 +96,13 @@ contract ExecutionDispatcher { revert ExecutionDispatcher__UnapprovedExecutor(); } - selector = - selector == bytes4(0) ? IExecutor.handleCallback.selector : selector; + selector = selector == bytes4(0) + ? ICallback.handleCallback.selector + : selector; // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success, bytes memory result) = - executor.delegatecall(abi.encodeWithSelector(selector, data)); + (bool success, bytes memory result) = executor.delegatecall( + abi.encodeWithSelector(selector, data) + ); if (!success) { revert( diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 8084afc..41e8ac3 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -3,7 +3,7 @@ pragma solidity ^0.8.26; import "../lib/IWETH.sol"; import "../lib/bytes/LibPrefixLengthEncodedByteArray.sol"; -import "./CallbackVerificationDispatcher.sol"; + import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; @@ -27,7 +27,6 @@ error TychoRouter__MessageValueMismatch(uint256 value, uint256 amount); contract TychoRouter is AccessControl, ExecutionDispatcher, - CallbackVerificationDispatcher, Pausable, ReentrancyGuard, SafeCallback @@ -58,16 +57,21 @@ contract TychoRouter is uint256 public fee; event Withdrawal( - address indexed token, uint256 amount, address indexed receiver + address indexed token, + uint256 amount, + address indexed receiver ); event FeeReceiverSet( - address indexed oldFeeReceiver, address indexed newFeeReceiver + address indexed oldFeeReceiver, + address indexed newFeeReceiver ); event FeeSet(uint256 indexed oldFee, uint256 indexed newFee); - constructor(IPoolManager _poolManager, address _permit2, address weth) - SafeCallback(_poolManager) - { + constructor( + IPoolManager _poolManager, + address _permit2, + address weth + ) SafeCallback(_poolManager) { if (_permit2 == address(0) || weth == address(0)) { revert TychoRouter__AddressZero(); } @@ -181,10 +185,11 @@ contract TychoRouter is * * @return The total amount of the buy token obtained after all swaps have been executed. */ - function _swap(uint256 amountIn, uint256 nTokens, bytes calldata swaps_) - internal - returns (uint256) - { + function _swap( + uint256 amountIn, + uint256 nTokens, + bytes calldata swaps_ + ) internal returns (uint256) { if (swaps_.length == 0) { revert TychoRouter__EmptySwaps(); } @@ -251,10 +256,10 @@ contract TychoRouter is /** * @dev Allows granting roles to multiple accounts in a single call. */ - function batchGrantRole(bytes32 role, address[] memory accounts) - external - onlyRole(DEFAULT_ADMIN_ROLE) - { + function batchGrantRole( + bytes32 role, + address[] memory accounts + ) external onlyRole(DEFAULT_ADMIN_ROLE) { for (uint256 i = 0; i < accounts.length; i++) { _grantRole(role, accounts[i]); } @@ -264,10 +269,9 @@ contract TychoRouter is * @dev Entrypoint to add or replace an approved executor contract address * @param targets address of the executor contract */ - function setExecutors(address[] memory targets) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { + function setExecutors( + address[] memory targets + ) external onlyRole(EXECUTOR_SETTER_ROLE) { for (uint256 i = 0; i < targets.length; i++) { _setExecutor(targets[i]); } @@ -277,42 +281,18 @@ contract TychoRouter is * @dev Entrypoint to remove an approved executor contract address * @param target address of the executor contract */ - function removeExecutor(address target) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { + function removeExecutor( + address target + ) external onlyRole(EXECUTOR_SETTER_ROLE) { _removeExecutor(target); } - /** - * @dev Entrypoint to add or replace an approved callback verifier contract address - * @param target address of the callback verifier contract - */ - function setCallbackVerifier(address target) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { - _setCallbackVerifier(target); - } - - /** - * @dev Entrypoint to remove an approved callback verifier contract address - * @param target address of the callback verifier contract - */ - function removeCallbackVerifier(address target) - external - onlyRole(EXECUTOR_SETTER_ROLE) - { - _removeCallbackVerifier(target); - } - /** * @dev Allows setting the fee receiver. */ - function setFeeReceiver(address newfeeReceiver) - external - onlyRole(FEE_SETTER_ROLE) - { + function setFeeReceiver( + address newfeeReceiver + ) external onlyRole(FEE_SETTER_ROLE) { if (newfeeReceiver == address(0)) revert TychoRouter__AddressZero(); emit FeeReceiverSet(feeReceiver, newfeeReceiver); feeReceiver = newfeeReceiver; @@ -329,10 +309,10 @@ contract TychoRouter is /** * @dev Allows withdrawing any ERC20 funds if funds get stuck in case of a bug. */ - function withdraw(IERC20[] memory tokens, address receiver) - external - onlyRole(FUND_RESCUER_ROLE) - { + function withdraw( + IERC20[] memory tokens, + address receiver + ) external onlyRole(FUND_RESCUER_ROLE) { if (receiver == address(0)) revert TychoRouter__AddressZero(); for (uint256 i = 0; i < tokens.length; i++) { @@ -349,10 +329,9 @@ contract TychoRouter is * @dev Allows withdrawing any NATIVE funds if funds get stuck in case of a bug. * The contract should never hold any NATIVE tokens for security reasons. */ - function withdrawNative(address receiver) - external - onlyRole(FUND_RESCUER_ROLE) - { + function withdrawNative( + address receiver + ) external onlyRole(FUND_RESCUER_ROLE) { if (receiver == address(0)) revert TychoRouter__AddressZero(); uint256 amount = address(this).balance; @@ -380,8 +359,9 @@ contract TychoRouter is * @param amount of WETH to unwrap. */ function _unwrapETH(uint256 amount) internal { - uint256 unwrapAmount = - amount == 0 ? _weth.balanceOf(address(this)) : amount; + uint256 unwrapAmount = amount == 0 + ? _weth.balanceOf(address(this)) + : amount; _weth.withdraw(unwrapAmount); } @@ -400,15 +380,14 @@ contract TychoRouter is bytes calldata msgData ) external { _handleCallback( - bytes4(0), abi.encodePacked(amount0Delta, amount1Delta, msgData) + bytes4(0), + abi.encodePacked(amount0Delta, amount1Delta, msgData) ); } - function _unlockCallback(bytes calldata data) - internal - override - returns (bytes memory) - { + function _unlockCallback( + bytes calldata data + ) internal override returns (bytes memory) { require(data.length >= 20, "Invalid data length"); bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); address executor = address(uint160(bytes20(data[data.length - 20:]))); @@ -419,7 +398,7 @@ contract TychoRouter is } // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success,) = executor.delegatecall( + (bool success, ) = executor.delegatecall( abi.encodeWithSelector(selector, protocolData) ); require(success, "delegatecall to uniswap v4 callback failed"); diff --git a/foundry/src/executors/BalancerV2Executor.sol b/foundry/src/executors/BalancerV2Executor.sol index a328715..d738e92 100644 --- a/foundry/src/executors/BalancerV2Executor.sol +++ b/foundry/src/executors/BalancerV2Executor.sol @@ -2,10 +2,7 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import { - IERC20, - SafeERC20 -} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // slither-disable-next-line solc-version import {IAsset} from "@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol"; // slither-disable-next-line solc-version @@ -19,11 +16,10 @@ contract BalancerV2Executor is IExecutor { address private constant VAULT = 0xBA12222222228d8Ba445958a75a0704d566BF2C8; // slither-disable-next-line locked-ether - function swap(uint256 givenAmount, bytes calldata data) - external - payable - returns (uint256 calculatedAmount) - { + function swap( + uint256 givenAmount, + bytes calldata data + ) external payable returns (uint256 calculatedAmount) { ( IERC20 tokenIn, IERC20 tokenOut, @@ -55,16 +51,17 @@ contract BalancerV2Executor is IExecutor { uint256 limit = 0; - calculatedAmount = - IVault(VAULT).swap(singleSwap, funds, limit, block.timestamp); + calculatedAmount = IVault(VAULT).swap( + singleSwap, + funds, + limit, + block.timestamp + ); } - function handleCallback(bytes calldata data) - external - returns (bytes memory result) - {} - - function _decodeData(bytes calldata data) + function _decodeData( + bytes calldata data + ) internal pure returns ( diff --git a/foundry/src/executors/UniswapV2Executor.sol b/foundry/src/executors/UniswapV2Executor.sol index 870ef74..15522b1 100644 --- a/foundry/src/executors/UniswapV2Executor.sol +++ b/foundry/src/executors/UniswapV2Executor.sol @@ -11,11 +11,10 @@ contract UniswapV2Executor is IExecutor { using SafeERC20 for IERC20; // slither-disable-next-line locked-ether - function swap(uint256 givenAmount, bytes calldata data) - external - payable - returns (uint256 calculatedAmount) - { + function swap( + uint256 givenAmount, + bytes calldata data + ) external payable returns (uint256 calculatedAmount) { address target; address receiver; bool zeroForOne; @@ -33,12 +32,9 @@ contract UniswapV2Executor is IExecutor { } } - function handleCallback(bytes calldata data) - external - returns (bytes memory result) - {} - - function _decodeData(bytes calldata data) + function _decodeData( + bytes calldata data + ) internal pure returns ( @@ -57,20 +53,20 @@ contract UniswapV2Executor is IExecutor { zeroForOne = uint8(data[60]) > 0; } - function _getAmountOut(address target, uint256 amountIn, bool zeroForOne) - internal - view - returns (uint256 amount) - { + function _getAmountOut( + address target, + uint256 amountIn, + bool zeroForOne + ) internal view returns (uint256 amount) { IUniswapV2Pair pair = IUniswapV2Pair(target); uint112 reserveIn; uint112 reserveOut; if (zeroForOne) { // slither-disable-next-line unused-return - (reserveIn, reserveOut,) = pair.getReserves(); + (reserveIn, reserveOut, ) = pair.getReserves(); } else { // slither-disable-next-line unused-return - (reserveOut, reserveIn,) = pair.getReserves(); + (reserveOut, reserveIn, ) = pair.getReserves(); } require(reserveIn > 0 && reserveOut > 0, "L"); diff --git a/foundry/src/executors/UniswapV4Executor.sol b/foundry/src/executors/UniswapV4Executor.sol index 2a2e40b..9077b1a 100644 --- a/foundry/src/executors/UniswapV4Executor.sol +++ b/foundry/src/executors/UniswapV4Executor.sol @@ -2,14 +2,9 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import { - IERC20, - SafeERC20 -} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; -import { - Currency, CurrencyLibrary -} from "@uniswap/v4-core/src/types/Currency.sol"; +import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {V4Router} from "@uniswap/v4-periphery/src/V4Router.sol"; @@ -23,13 +18,16 @@ contract UniswapV4Executor is IExecutor, V4Router { constructor(IPoolManager _poolManager) V4Router(_poolManager) {} - function swap(uint256, bytes calldata data) - external - payable - returns (uint256 calculatedAmount) - { - (address tokenIn, address tokenOut, bool isExactInput, uint256 amount) = - _decodeData(data); + function swap( + uint256, + bytes calldata data + ) external payable returns (uint256 calculatedAmount) { + ( + address tokenIn, + address tokenOut, + bool isExactInput, + uint256 amount + ) = _decodeData(data); uint256 tokenOutBalanceBefore; uint256 tokenInBalanceBefore; @@ -64,7 +62,9 @@ contract UniswapV4Executor is IExecutor, V4Router { return calculatedAmount; } - function _decodeData(bytes calldata data) + function _decodeData( + bytes calldata data + ) internal pure returns ( @@ -74,15 +74,19 @@ contract UniswapV4Executor is IExecutor, V4Router { uint256 amount ) { - (bytes memory actions, bytes[] memory params) = - abi.decode(data, (bytes, bytes[])); + (bytes memory actions, bytes[] memory params) = abi.decode( + data, + (bytes, bytes[]) + ); // First byte of actions determines the swap type uint8 action = uint8(bytes1(actions[0])); if (action == uint8(Actions.SWAP_EXACT_IN_SINGLE)) { - IV4Router.ExactInputSingleParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactInputSingleParams)); + IV4Router.ExactInputSingleParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactInputSingleParams) + ); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -93,8 +97,10 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT_SINGLE)) { - IV4Router.ExactOutputSingleParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactOutputSingleParams)); + IV4Router.ExactOutputSingleParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactOutputSingleParams) + ); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -105,18 +111,23 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = false; amount = swapParams.amountOut; } else if (action == uint8(Actions.SWAP_EXACT_IN)) { - IV4Router.ExactInputParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactInputParams)); + IV4Router.ExactInputParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactInputParams) + ); tokenIn = address(uint160(swapParams.currencyIn.toId())); - PathKey memory lastPath = - swapParams.path[swapParams.path.length - 1]; + PathKey memory lastPath = swapParams.path[ + swapParams.path.length - 1 + ]; tokenOut = address(uint160(lastPath.intermediateCurrency.toId())); isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT)) { - IV4Router.ExactOutputParams memory swapParams = - abi.decode(params[0], (IV4Router.ExactOutputParams)); + IV4Router.ExactOutputParams memory swapParams = abi.decode( + params[0], + (IV4Router.ExactOutputParams) + ); PathKey memory firstPath = swapParams.path[0]; tokenIn = address(uint160(firstPath.intermediateCurrency.toId())); @@ -126,21 +137,18 @@ contract UniswapV4Executor is IExecutor, V4Router { } } - function _pay(Currency token, address payer, uint256 amount) - internal - override - { + function _pay( + Currency token, + address payer, + uint256 amount + ) internal override { IERC20(Currency.unwrap(token)).safeTransfer( - address(poolManager), amount + address(poolManager), + amount ); } function msgSender() public view override returns (address) { return address(this); } - - function handleCallback(bytes calldata data) - external - returns (bytes memory result) - {} } diff --git a/foundry/test/CallbackVerificationDispatcher.t.sol b/foundry/test/CallbackVerificationDispatcher.t.sol deleted file mode 100644 index fd2577e..0000000 --- a/foundry/test/CallbackVerificationDispatcher.t.sol +++ /dev/null @@ -1,180 +0,0 @@ -// SPDX-License-Identifier: UNLICENSED -pragma solidity ^0.8.26; - -import "@src/CallbackVerificationDispatcher.sol"; -import "./TychoRouterTestSetup.sol"; - -contract CallbackVerificationDispatcherExposed is - CallbackVerificationDispatcher -{ - function exposedCallVerifier(bytes calldata data) - external - view - returns (uint256 amountOwed, address tokenOwed) - { - return _callVerifyCallback(data); - } - - function exposedDecodeVerifierAndSelector(bytes calldata data) - external - pure - returns (address executor, bytes4 selector, bytes memory protocolData) - { - return _decodeVerifierAndSelector(data); - } - - function exposedSetCallbackVerifier(address target) external { - _setCallbackVerifier(target); - } - - function exposedRemoveCallbackVerifier(address target) external { - _removeCallbackVerifier(target); - } -} - -contract CallbackVerificationDispatcherTest is Constants { - CallbackVerificationDispatcherExposed dispatcherExposed; - - event CallbackVerifierSet(address indexed callbackVerifier); - event CallbackVerifierRemoved(address indexed callbackVerifier); - - function setUp() public { - uint256 forkBlock = 20673900; - vm.createSelectFork(vm.rpcUrl("mainnet"), forkBlock); - dispatcherExposed = new CallbackVerificationDispatcherExposed(); - deal(WETH_ADDR, address(dispatcherExposed), 15 ether); - deployDummyContract(); - } - - function testSetValidVerifier() public { - vm.expectEmit(); - // Define the event we expect to be emitted at the next step - emit CallbackVerifierSet(DUMMY); - dispatcherExposed.exposedSetCallbackVerifier(DUMMY); - assert(dispatcherExposed.callbackVerifiers(DUMMY) == true); - } - - function testRemoveVerifier() public { - dispatcherExposed.exposedSetCallbackVerifier(DUMMY); - vm.expectEmit(); - // Define the event we expect to be emitted at the next step - emit CallbackVerifierRemoved(DUMMY); - dispatcherExposed.exposedRemoveCallbackVerifier(DUMMY); - assert(dispatcherExposed.callbackVerifiers(DUMMY) == false); - } - - function testRemoveUnSetVerifier() public { - dispatcherExposed.exposedRemoveCallbackVerifier(BOB); - assert(dispatcherExposed.callbackVerifiers(BOB) == false); - } - - function testSetVerifierNonContract() public { - vm.expectRevert( - abi.encodeWithSelector( - CallbackVerificationDispatcher__NonContractVerifier.selector - ) - ); - dispatcherExposed.exposedSetCallbackVerifier(BOB); - } - - function testCallVerifierSuccess() public { - // For this test, we can use any callback verifier and any calldata that we - // know works for this verifier. We don't care about which calldata/executor, - // since we are only testing the functionality of the staticcall and not - // the inner verifier. - // Thus, this test case designed from scratch using previously-deployed - // Maverick callback verifier. Looking at the code, we can easily design - // passing calldata. - dispatcherExposed.exposedSetCallbackVerifier( - address(0x2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8) - ); - bytes memory data = - hex"2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e876b20f8a0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; - vm.startPrank(address(0xD0b2F5018B5D22759724af6d4281AC0B13266360)); - (uint256 amountOwed, address tokenOwed) = - dispatcherExposed.exposedCallVerifier(data); - vm.stopPrank(); - - // The specific values returned are not important for this test. - // The goal is to ensure correct calling of the Maverick verifier's. - // Since the verifier's output format has changed, the asserted values may not be meaningful. - // Full validation of the functionality will be covered in the integration tests. - assert(amountOwed == 1); - assert(tokenOwed == address(0x0000000000000000000000000000000000000001)); - } - - function testCallVerifierNoSelector() public { - // This test is exactly the same as testCallVerifierSuccess, except that the - // fn selector is not explicitly passed. The test should still pass using the - // default selector. - dispatcherExposed.exposedSetCallbackVerifier( - address(0x2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8) - ); - - // Pass all-zero selector. This should default to the verifyCallback selector - bytes memory data = - hex"2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; - vm.startPrank(address(0xD0b2F5018B5D22759724af6d4281AC0B13266360)); - (uint256 amountOwed, address tokenOwed) = - dispatcherExposed.exposedCallVerifier(data); - vm.stopPrank(); - - // The specific values returned are not important for this test. - // The goal is to ensure correct calling of the Maverick verifier's. - // Since the verifier's output format has changed, the asserted values may not be meaningful. - // Full validation of the functionality will be covered in the integration tests. - assert(amountOwed == 1); - assert(tokenOwed == address(0x0000000000000000000000000000000000000001)); - } - - function testCallVerifierBadSelector() public { - // A bad selector is provided to an approved executor - causing the call - // itself to fail. Make sure this actually reverts. - dispatcherExposed.exposedSetCallbackVerifier( - address(0x2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8) - ); - vm.startPrank(address(0xD0b2F5018B5D22759724af6d4281AC0B13266360)); - bytes memory data = - hex"2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8aa0000000000"; - vm.expectRevert(bytes("Callback verification failed")); - dispatcherExposed.exposedCallVerifier(data); - vm.stopPrank(); - } - - function testCallVerifierParseRevertMessage() public { - // Verification should fail because caller is not a Maverick pool - // Check that we correctly parse the revert message - dispatcherExposed.exposedSetCallbackVerifier( - address(0x2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8) - ); - bytes memory data = - hex"2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; - vm.expectRevert( - abi.encodeWithSignature( - "Error(string)", "Must call from a Maverick Factory Pool" - ) - ); - dispatcherExposed.exposedCallVerifier(data); - } - - function testCallVerifierUnapprovedVerifier() public { - bytes memory data = - hex"5d622C9053b8FFB1B3465495C8a42E603632bA70aabbccdd1111111111111111"; - vm.expectRevert(); - dispatcherExposed.exposedCallVerifier(data); - } - - function testDecodeVerifierAndSelector() public view { - bytes memory data = - hex"2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e876b20f8aA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; - (address executor, bytes4 selector, bytes memory verifierData) = - dispatcherExposed.exposedDecodeVerifierAndSelector(data); - assert(executor == address(0x2C960bD1CFE09A26105ad3C351bEa0a3fAD0F8e8)); - assert(selector == bytes4(0x76b20f8a)); - // Direct bytes comparison not supported - must use keccak - assert( - keccak256(verifierData) - == keccak256(hex"A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48") - ); - } -} diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index bfbca0b..ef3b69b 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -18,7 +18,9 @@ contract TychoRouterTest is TychoRouterTestSetup { event CallbackVerifierSet(address indexed callbackVerifier); event Withdrawal( - address indexed token, uint256 amount, address indexed receiver + address indexed token, + uint256 amount, + address indexed receiver ); function testSetExecutorsValidRole() public { @@ -63,31 +65,6 @@ contract TychoRouterTest is TychoRouterTestSetup { tychoRouter.setExecutors(executors); } - function testSetVerifierValidRole() public { - vm.startPrank(EXECUTOR_SETTER); - tychoRouter.setCallbackVerifier(DUMMY); - vm.stopPrank(); - assert(tychoRouter.callbackVerifiers(DUMMY) == true); - } - - function testRemoveVerifierValidRole() public { - vm.startPrank(EXECUTOR_SETTER); - tychoRouter.setCallbackVerifier(DUMMY); - tychoRouter.removeCallbackVerifier(DUMMY); - vm.stopPrank(); - assert(tychoRouter.callbackVerifiers(DUMMY) == false); - } - - function testRemoveVerifierMissingSetterRole() public { - vm.expectRevert(); - tychoRouter.removeCallbackVerifier(BOB); - } - - function testSetVerifierMissingSetterRole() public { - vm.expectRevert(); - tychoRouter.setCallbackVerifier(DUMMY); - } - function testWithdrawNative() public { vm.startPrank(FUND_RESCUER); // Send 100 ether to tychoRouter @@ -239,7 +216,10 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(WETH_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -276,7 +256,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ) ); @@ -315,7 +298,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, WETH_WBTC_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_WBTC_POOL, + tychoRouterAddr, + false ) ); // WBTC -> USDC @@ -326,7 +312,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WBTC_ADDR, USDC_WBTC_POOL, tychoRouterAddr, true + WBTC_ADDR, + USDC_WBTC_POOL, + tychoRouterAddr, + true ) ); // WETH -> DAI @@ -337,7 +326,10 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ) ); @@ -373,7 +365,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -426,7 +421,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -485,7 +483,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -517,7 +518,10 @@ contract TychoRouterTest is TychoRouterTestSetup { assertEq(amountOut, expectedAmount); uint256 daiBalance = IERC20(DAI_ADDR).balanceOf(ALICE); assertEq(daiBalance, expectedAmount); - assertEq(IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), 26598819248184436997); + assertEq( + IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), + 26598819248184436997 + ); vm.stopPrank(); } @@ -530,19 +534,22 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.startPrank(ALICE); - IAllowanceTransfer.PermitSingle memory emptyPermitSingle = - IAllowanceTransfer.PermitSingle({ - details: IAllowanceTransfer.PermitDetails({ - token: address(0), - amount: 0, - expiration: 0, - nonce: 0 - }), - spender: address(0), - sigDeadline: 0 - }); + IAllowanceTransfer.PermitSingle + memory emptyPermitSingle = IAllowanceTransfer.PermitSingle({ + details: IAllowanceTransfer.PermitDetails({ + token: address(0), + amount: 0, + expiration: 0, + nonce: 0 + }), + spender: address(0), + sigDeadline: 0 + }); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -591,8 +598,12 @@ contract TychoRouterTest is TychoRouterTestSetup { bytes memory signature ) = handlePermit2Approval(DAI_ADDR, amountIn); - bytes memory protocolData = - encodeUniswapV2Swap(DAI_ADDR, WETH_DAI_POOL, tychoRouterAddr, true); + bytes memory protocolData = encodeUniswapV2Swap( + DAI_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + true + ); bytes memory swap = encodeSwap( uint8(0), @@ -636,7 +647,11 @@ contract TychoRouterTest is TychoRouterTestSetup { uint256 expAmountOut = 1205_128428842122129186; //Swap 1 WETH for 1205.12 DAI bool zeroForOne = false; bytes memory protocolData = encodeUniswapV3Swap( - WETH_ADDR, DAI_ADDR, tychoRouterAddr, DAI_WETH_USV3, zeroForOne + WETH_ADDR, + DAI_ADDR, + tychoRouterAddr, + DAI_WETH_USV3, + zeroForOne ); bytes memory swap = encodeSwap( uint8(0), @@ -678,7 +693,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call( + (bool success, ) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d481bb00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfbc3000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041f2740fde9662d8bc1f8fe8e8fc29447c1832d625f06f4a56ee5103ad555c12323af5d50eb840f73d17873383ae3b7573956d5df7b2bf76bddba768c2837894a51b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -707,7 +722,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call{value: 1 ether}( + (bool success, ) = tychoRouterAddr.call{value: 1 ether}( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4806b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfa73000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041c36406a750c499ac7f79f7666650f0d4f20fc27bb49ab68121c0be6554cb5cab6caf90dc3aab2e21083a8fa46976521a1e9df41ce74be59abf03e0d3691541e91c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00020000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -736,7 +751,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call( + (bool success, ) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000000000000000000000000000000000000067d4809800000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfaa000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000004146411c70ec7fee0d5d260803cb220f5365792426c5d94f7a0a4d37abb05205752c5418b1fadd059570a71f0911814e546728e1f21876f2a1c6d38d34bd235fd61c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fa478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950100000000" ); @@ -767,7 +782,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success,) = tychoRouterAddr.call( + (bool success, ) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4810d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfb15000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041ecaab75f0791c9683b001ea2f0e01a0a6aaf03e6e49c83e9c8a8e588a38e3be9230d962926628ffbf6a5370cda559ff0e7876a63ed38eebe33dbef5b5e2e46ef1b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000170005a00028000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d0139500005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2bb2b8038a1640196fbe3e38816f3e67cba72d9403ede3eca2a72b3aecc820e955b36f38437d0139500005a02030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fae461ca67b15dc8dc81ce7615e0320da1a9ab8d53ede3eca2a72b3aecc820e955b36f38437d0139501005a01030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab2260fac5e5542a773aa44fbcfedf7c193bc2c599004375dff511095cc5a197a54140a24efef3a4163ede3eca2a72b3aecc820e955b36f38437d013950100000000000000000000000000000000" ); @@ -797,7 +812,10 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false + WETH_ADDR, + WETH_DAI_POOL, + tychoRouterAddr, + false ); bytes memory swap = encodeSwap( @@ -814,7 +832,8 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.expectRevert( abi.encodeWithSelector( - TychoRouter__AmountInNotFullySpent.selector, 400000000000000000 + TychoRouter__AmountInNotFullySpent.selector, + 400000000000000000 ) ); @@ -840,7 +859,12 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(USDE_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = UniswapV4Utils.encodeExactInputSingle( - USDE_ADDR, USDT_ADDR, 100, true, 1, uint128(amountIn) + USDE_ADDR, + USDT_ADDR, + 100, + true, + 1, + uint128(amountIn) ); // add executor and selector for callback From cccb252bf2194af55b983f73815edb0cf1782776 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Fri, 14 Feb 2025 23:27:44 +0530 Subject: [PATCH 07/15] feat: update handleCallback in USV3 to do verification --- foundry/src/executors/UniswapV3Executor.sol | 73 +++++++++---------- .../test/executors/UniswapV3Executor.t.sol | 43 ++++------- 2 files changed, 48 insertions(+), 68 deletions(-) diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index 906c771..bfa3eae 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -5,7 +5,6 @@ import "@interfaces/IExecutor.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-updated/CallbackValidationV2.sol"; -import "forge-std/console.sol"; error UniswapV3Executor__InvalidDataLength(); error UniswapV3Executor__InvalidFactory(); @@ -29,11 +28,10 @@ contract UniswapV3Executor is IExecutor { } // slither-disable-next-line locked-ether - function swap(uint256 amountIn, bytes calldata data) - external - payable - returns (uint256 amountOut) - { + function swap( + uint256 amountIn, + bytes calldata data + ) external payable returns (uint256 amountOut) { ( address tokenIn, address tokenOut, @@ -66,41 +64,36 @@ contract UniswapV3Executor is IExecutor { } } - function handleCallback(bytes calldata msgData) - external - returns (bytes memory result) - { - (int256 amount0Delta, int256 amount1Delta) = - abi.decode(msgData[:64], (int256, int256)); + function handleCallback( + bytes calldata msgData + ) external returns (bytes memory result) { + (int256 amount0Delta, int256 amount1Delta) = abi.decode( + msgData[:64], + (int256, int256) + ); - bytes calldata remainingData = msgData[64:]; + address tokenIn = address(bytes20(msgData[64:84])); + address tokenOut = address(bytes20(msgData[84:104])); + uint24 poolFee = uint24(bytes3(msgData[104:107])); - (uint256 amountOwed, address tokenOwed) = - _verifyUSV3Callback(amount0Delta, amount1Delta, remainingData); + CallbackValidationV2.verifyCallback( + factory, + tokenIn, + tokenOut, + poolFee + ); - IERC20(tokenOwed).safeTransfer(msg.sender, amountOwed); - return abi.encode(amountOwed, tokenOwed); + uint256 amountOwed = amount0Delta > 0 + ? uint256(amount0Delta) + : uint256(amount1Delta); + + IERC20(tokenIn).safeTransfer(msg.sender, amountOwed); + return abi.encode(amountOwed, tokenIn); } - function _verifyUSV3Callback( - int256 amount0Delta, - int256 amount1Delta, + function _decodeData( bytes calldata data - ) internal view returns (uint256 amountIn, address tokenIn) { - tokenIn = address(bytes20(data[0:20])); - address tokenOut = address(bytes20(data[20:40])); - uint24 poolFee = uint24(bytes3(data[40:43])); - - // slither-disable-next-line unused-return - CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); - - amountIn = - amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); - - return (amountIn, tokenIn); - } - - function _decodeData(bytes calldata data) + ) internal pure returns ( @@ -123,11 +116,11 @@ contract UniswapV3Executor is IExecutor { zeroForOne = uint8(data[83]) > 0; } - function _makeV3CallbackData(address tokenIn, address tokenOut, uint24 fee) - internal - view - returns (bytes memory) - { + function _makeV3CallbackData( + address tokenIn, + address tokenOut, + uint24 fee + ) internal view returns (bytes memory) { return abi.encodePacked(tokenIn, tokenOut, fee, self); } } diff --git a/foundry/test/executors/UniswapV3Executor.t.sol b/foundry/test/executors/UniswapV3Executor.t.sol index e0d1638..fe50674 100644 --- a/foundry/test/executors/UniswapV3Executor.t.sol +++ b/foundry/test/executors/UniswapV3Executor.t.sol @@ -8,7 +8,9 @@ import {Constants} from "../Constants.sol"; contract UniswapV3ExecutorExposed is UniswapV3Executor { constructor(address _factory) UniswapV3Executor(_factory) {} - function decodeData(bytes calldata data) + function decodeData( + bytes calldata data + ) external pure returns ( @@ -42,7 +44,12 @@ contract UniswapV3ExecutorTest is Test, Constants { function testDecodeParams() public view { uint24 expectedPoolFee = 500; bytes memory data = abi.encodePacked( - WETH_ADDR, DAI_ADDR, expectedPoolFee, address(2), address(3), false + WETH_ADDR, + DAI_ADDR, + expectedPoolFee, + address(2), + address(3), + false ); ( @@ -63,8 +70,11 @@ contract UniswapV3ExecutorTest is Test, Constants { } function testDecodeParamsInvalidDataLength() public { - bytes memory invalidParams = - abi.encodePacked(WETH_ADDR, address(2), address(3)); + bytes memory invalidParams = abi.encodePacked( + WETH_ADDR, + address(2), + address(3) + ); vm.expectRevert(UniswapV3Executor__InvalidDataLength.selector); uniswapV3Exposed.decodeData(invalidParams); @@ -77,7 +87,7 @@ contract UniswapV3ExecutorTest is Test, Constants { uint256 initialPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); vm.startPrank(DAI_WETH_USV3); - bytes memory callbackData = _encodeUSV3CallbackData( + bytes memory callbackData = abi.encodePacked( int256(amountOwed), // amount0Delta int256(0), // amount1Delta WETH_ADDR, @@ -90,27 +100,4 @@ contract UniswapV3ExecutorTest is Test, Constants { uint256 finalPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); assertEq(finalPoolReserve - initialPoolReserve, amountOwed); } - - function _encodeUSV3CallbackData( - int256 amount0Delta, - int256 amount1Delta, - address tokenIn, - address tokenOut, - uint24 fee - ) internal pure returns (bytes memory) { - // Dummy selector for handleCallback - bytes4 selector = - bytes4(keccak256("handleCallback(int256,int256,bytes)")); - - bytes memory tokenData = abi.encodePacked(tokenIn, tokenOut, fee); - - // [0:4] - function selector - // [4:68] - abi.encode(amount0Delta, amount1Delta) - // [68:end] - abi.encode(tokenData) where tokenData is the packed bytes - return abi.encodePacked( - selector, - abi.encode(amount0Delta, amount1Delta), - abi.encode(tokenData) - ); - } } From 9d3b96f997d3295c14fd356211b66b4c308f0288 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Sat, 15 Feb 2025 00:34:07 +0530 Subject: [PATCH 08/15] feat: add uniswapV3SwapCallback in USV3 executor --- foundry/src/ExecutionDispatcher.sol | 10 +- foundry/src/TychoRouter.sol | 86 +++++++------ foundry/src/executors/BalancerV2Executor.sol | 26 ++-- foundry/src/executors/UniswapV2Executor.sol | 27 ++--- foundry/src/executors/UniswapV3Executor.sol | 76 +++++++----- foundry/src/executors/UniswapV4Executor.sol | 77 +++++------- foundry/test/TychoRouter.t.sol | 113 +++++------------- .../test/executors/UniswapV3Executor.t.sol | 49 +++++--- 8 files changed, 218 insertions(+), 246 deletions(-) diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/ExecutionDispatcher.sol index c48caca..01e6ff4 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/ExecutionDispatcher.sol @@ -96,13 +96,11 @@ contract ExecutionDispatcher { revert ExecutionDispatcher__UnapprovedExecutor(); } - selector = selector == bytes4(0) - ? ICallback.handleCallback.selector - : selector; + selector = + selector == bytes4(0) ? ICallback.handleCallback.selector : selector; // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success, bytes memory result) = executor.delegatecall( - abi.encodeWithSelector(selector, data) - ); + (bool success, bytes memory result) = + executor.delegatecall(abi.encodeWithSelector(selector, data)); if (!success) { revert( diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 41e8ac3..08ed017 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -57,21 +57,16 @@ contract TychoRouter is uint256 public fee; event Withdrawal( - address indexed token, - uint256 amount, - address indexed receiver + address indexed token, uint256 amount, address indexed receiver ); event FeeReceiverSet( - address indexed oldFeeReceiver, - address indexed newFeeReceiver + address indexed oldFeeReceiver, address indexed newFeeReceiver ); event FeeSet(uint256 indexed oldFee, uint256 indexed newFee); - constructor( - IPoolManager _poolManager, - address _permit2, - address weth - ) SafeCallback(_poolManager) { + constructor(IPoolManager _poolManager, address _permit2, address weth) + SafeCallback(_poolManager) + { if (_permit2 == address(0) || weth == address(0)) { revert TychoRouter__AddressZero(); } @@ -185,11 +180,10 @@ contract TychoRouter is * * @return The total amount of the buy token obtained after all swaps have been executed. */ - function _swap( - uint256 amountIn, - uint256 nTokens, - bytes calldata swaps_ - ) internal returns (uint256) { + function _swap(uint256 amountIn, uint256 nTokens, bytes calldata swaps_) + internal + returns (uint256) + { if (swaps_.length == 0) { revert TychoRouter__EmptySwaps(); } @@ -256,10 +250,10 @@ contract TychoRouter is /** * @dev Allows granting roles to multiple accounts in a single call. */ - function batchGrantRole( - bytes32 role, - address[] memory accounts - ) external onlyRole(DEFAULT_ADMIN_ROLE) { + function batchGrantRole(bytes32 role, address[] memory accounts) + external + onlyRole(DEFAULT_ADMIN_ROLE) + { for (uint256 i = 0; i < accounts.length; i++) { _grantRole(role, accounts[i]); } @@ -269,9 +263,10 @@ contract TychoRouter is * @dev Entrypoint to add or replace an approved executor contract address * @param targets address of the executor contract */ - function setExecutors( - address[] memory targets - ) external onlyRole(EXECUTOR_SETTER_ROLE) { + function setExecutors(address[] memory targets) + external + onlyRole(EXECUTOR_SETTER_ROLE) + { for (uint256 i = 0; i < targets.length; i++) { _setExecutor(targets[i]); } @@ -281,18 +276,20 @@ contract TychoRouter is * @dev Entrypoint to remove an approved executor contract address * @param target address of the executor contract */ - function removeExecutor( - address target - ) external onlyRole(EXECUTOR_SETTER_ROLE) { + function removeExecutor(address target) + external + onlyRole(EXECUTOR_SETTER_ROLE) + { _removeExecutor(target); } /** * @dev Allows setting the fee receiver. */ - function setFeeReceiver( - address newfeeReceiver - ) external onlyRole(FEE_SETTER_ROLE) { + function setFeeReceiver(address newfeeReceiver) + external + onlyRole(FEE_SETTER_ROLE) + { if (newfeeReceiver == address(0)) revert TychoRouter__AddressZero(); emit FeeReceiverSet(feeReceiver, newfeeReceiver); feeReceiver = newfeeReceiver; @@ -309,10 +306,10 @@ contract TychoRouter is /** * @dev Allows withdrawing any ERC20 funds if funds get stuck in case of a bug. */ - function withdraw( - IERC20[] memory tokens, - address receiver - ) external onlyRole(FUND_RESCUER_ROLE) { + function withdraw(IERC20[] memory tokens, address receiver) + external + onlyRole(FUND_RESCUER_ROLE) + { if (receiver == address(0)) revert TychoRouter__AddressZero(); for (uint256 i = 0; i < tokens.length; i++) { @@ -329,9 +326,10 @@ contract TychoRouter is * @dev Allows withdrawing any NATIVE funds if funds get stuck in case of a bug. * The contract should never hold any NATIVE tokens for security reasons. */ - function withdrawNative( - address receiver - ) external onlyRole(FUND_RESCUER_ROLE) { + function withdrawNative(address receiver) + external + onlyRole(FUND_RESCUER_ROLE) + { if (receiver == address(0)) revert TychoRouter__AddressZero(); uint256 amount = address(this).balance; @@ -359,9 +357,8 @@ contract TychoRouter is * @param amount of WETH to unwrap. */ function _unwrapETH(uint256 amount) internal { - uint256 unwrapAmount = amount == 0 - ? _weth.balanceOf(address(this)) - : amount; + uint256 unwrapAmount = + amount == 0 ? _weth.balanceOf(address(this)) : amount; _weth.withdraw(unwrapAmount); } @@ -380,14 +377,15 @@ contract TychoRouter is bytes calldata msgData ) external { _handleCallback( - bytes4(0), - abi.encodePacked(amount0Delta, amount1Delta, msgData) + bytes4(0), abi.encodePacked(amount0Delta, amount1Delta, msgData) ); } - function _unlockCallback( - bytes calldata data - ) internal override returns (bytes memory) { + function _unlockCallback(bytes calldata data) + internal + override + returns (bytes memory) + { require(data.length >= 20, "Invalid data length"); bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); address executor = address(uint160(bytes20(data[data.length - 20:]))); @@ -398,7 +396,7 @@ contract TychoRouter is } // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success, ) = executor.delegatecall( + (bool success,) = executor.delegatecall( abi.encodeWithSelector(selector, protocolData) ); require(success, "delegatecall to uniswap v4 callback failed"); diff --git a/foundry/src/executors/BalancerV2Executor.sol b/foundry/src/executors/BalancerV2Executor.sol index d738e92..14340cf 100644 --- a/foundry/src/executors/BalancerV2Executor.sol +++ b/foundry/src/executors/BalancerV2Executor.sol @@ -2,7 +2,10 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import { + IERC20, + SafeERC20 +} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // slither-disable-next-line solc-version import {IAsset} from "@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol"; // slither-disable-next-line solc-version @@ -16,10 +19,11 @@ contract BalancerV2Executor is IExecutor { address private constant VAULT = 0xBA12222222228d8Ba445958a75a0704d566BF2C8; // slither-disable-next-line locked-ether - function swap( - uint256 givenAmount, - bytes calldata data - ) external payable returns (uint256 calculatedAmount) { + function swap(uint256 givenAmount, bytes calldata data) + external + payable + returns (uint256 calculatedAmount) + { ( IERC20 tokenIn, IERC20 tokenOut, @@ -51,17 +55,11 @@ contract BalancerV2Executor is IExecutor { uint256 limit = 0; - calculatedAmount = IVault(VAULT).swap( - singleSwap, - funds, - limit, - block.timestamp - ); + calculatedAmount = + IVault(VAULT).swap(singleSwap, funds, limit, block.timestamp); } - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( diff --git a/foundry/src/executors/UniswapV2Executor.sol b/foundry/src/executors/UniswapV2Executor.sol index 15522b1..7239a8a 100644 --- a/foundry/src/executors/UniswapV2Executor.sol +++ b/foundry/src/executors/UniswapV2Executor.sol @@ -11,10 +11,11 @@ contract UniswapV2Executor is IExecutor { using SafeERC20 for IERC20; // slither-disable-next-line locked-ether - function swap( - uint256 givenAmount, - bytes calldata data - ) external payable returns (uint256 calculatedAmount) { + function swap(uint256 givenAmount, bytes calldata data) + external + payable + returns (uint256 calculatedAmount) + { address target; address receiver; bool zeroForOne; @@ -32,9 +33,7 @@ contract UniswapV2Executor is IExecutor { } } - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( @@ -53,20 +52,20 @@ contract UniswapV2Executor is IExecutor { zeroForOne = uint8(data[60]) > 0; } - function _getAmountOut( - address target, - uint256 amountIn, - bool zeroForOne - ) internal view returns (uint256 amount) { + function _getAmountOut(address target, uint256 amountIn, bool zeroForOne) + internal + view + returns (uint256 amount) + { IUniswapV2Pair pair = IUniswapV2Pair(target); uint112 reserveIn; uint112 reserveOut; if (zeroForOne) { // slither-disable-next-line unused-return - (reserveIn, reserveOut, ) = pair.getReserves(); + (reserveIn, reserveOut,) = pair.getReserves(); } else { // slither-disable-next-line unused-return - (reserveOut, reserveIn, ) = pair.getReserves(); + (reserveOut, reserveIn,) = pair.getReserves(); } require(reserveIn > 0 && reserveOut > 0, "L"); diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index bfa3eae..02e8769 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -5,11 +5,13 @@ import "@interfaces/IExecutor.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-updated/CallbackValidationV2.sol"; +import "@interfaces/ICallback.sol"; +import "forge-std/console.sol"; error UniswapV3Executor__InvalidDataLength(); error UniswapV3Executor__InvalidFactory(); -contract UniswapV3Executor is IExecutor { +contract UniswapV3Executor is IExecutor, ICallback { using SafeERC20 for IERC20; uint160 private constant MIN_SQRT_RATIO = 4295128739; @@ -28,10 +30,11 @@ contract UniswapV3Executor is IExecutor { } // slither-disable-next-line locked-ether - function swap( - uint256 amountIn, - bytes calldata data - ) external payable returns (uint256 amountOut) { + function swap(uint256 amountIn, bytes calldata data) + external + payable + returns (uint256 amountOut) + { ( address tokenIn, address tokenOut, @@ -64,36 +67,53 @@ contract UniswapV3Executor is IExecutor { } } - function handleCallback( - bytes calldata msgData - ) external returns (bytes memory result) { - (int256 amount0Delta, int256 amount1Delta) = abi.decode( - msgData[:64], - (int256, int256) + function uniswapV3SwapCallback( + int256 amount0Delta, + int256 amount1Delta, + bytes calldata data + ) external { + // slither-disable-next-line low-level-calls + (bool success, bytes memory result) = self.delegatecall( + abi.encodeWithSelector( + ICallback.handleCallback.selector, + abi.encodePacked( + amount0Delta, amount1Delta, data[:data.length - 20] + ) + ) ); + if (!success) { + revert( + string( + result.length > 0 + ? result + : abi.encodePacked("Callback failed") + ) + ); + } + } + + function handleCallback(bytes calldata msgData) + external + returns (bytes memory result) + { + (int256 amount0Delta, int256 amount1Delta) = + abi.decode(msgData[:64], (int256, int256)); address tokenIn = address(bytes20(msgData[64:84])); address tokenOut = address(bytes20(msgData[84:104])); uint24 poolFee = uint24(bytes3(msgData[104:107])); - CallbackValidationV2.verifyCallback( - factory, - tokenIn, - tokenOut, - poolFee - ); + // slither-disable-next-line unused-return + CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); - uint256 amountOwed = amount0Delta > 0 - ? uint256(amount0Delta) - : uint256(amount1Delta); + uint256 amountOwed = + amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); IERC20(tokenIn).safeTransfer(msg.sender, amountOwed); return abi.encode(amountOwed, tokenIn); } - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( @@ -116,11 +136,11 @@ contract UniswapV3Executor is IExecutor { zeroForOne = uint8(data[83]) > 0; } - function _makeV3CallbackData( - address tokenIn, - address tokenOut, - uint24 fee - ) internal view returns (bytes memory) { + function _makeV3CallbackData(address tokenIn, address tokenOut, uint24 fee) + internal + view + returns (bytes memory) + { return abi.encodePacked(tokenIn, tokenOut, fee, self); } } diff --git a/foundry/src/executors/UniswapV4Executor.sol b/foundry/src/executors/UniswapV4Executor.sol index 9077b1a..48899c5 100644 --- a/foundry/src/executors/UniswapV4Executor.sol +++ b/foundry/src/executors/UniswapV4Executor.sol @@ -2,9 +2,14 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; -import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import { + IERC20, + SafeERC20 +} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; -import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol"; +import { + Currency, CurrencyLibrary +} from "@uniswap/v4-core/src/types/Currency.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol"; import {V4Router} from "@uniswap/v4-periphery/src/V4Router.sol"; @@ -18,16 +23,13 @@ contract UniswapV4Executor is IExecutor, V4Router { constructor(IPoolManager _poolManager) V4Router(_poolManager) {} - function swap( - uint256, - bytes calldata data - ) external payable returns (uint256 calculatedAmount) { - ( - address tokenIn, - address tokenOut, - bool isExactInput, - uint256 amount - ) = _decodeData(data); + function swap(uint256, bytes calldata data) + external + payable + returns (uint256 calculatedAmount) + { + (address tokenIn, address tokenOut, bool isExactInput, uint256 amount) = + _decodeData(data); uint256 tokenOutBalanceBefore; uint256 tokenInBalanceBefore; @@ -62,9 +64,7 @@ contract UniswapV4Executor is IExecutor, V4Router { return calculatedAmount; } - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( @@ -74,19 +74,15 @@ contract UniswapV4Executor is IExecutor, V4Router { uint256 amount ) { - (bytes memory actions, bytes[] memory params) = abi.decode( - data, - (bytes, bytes[]) - ); + (bytes memory actions, bytes[] memory params) = + abi.decode(data, (bytes, bytes[])); // First byte of actions determines the swap type uint8 action = uint8(bytes1(actions[0])); if (action == uint8(Actions.SWAP_EXACT_IN_SINGLE)) { - IV4Router.ExactInputSingleParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactInputSingleParams) - ); + IV4Router.ExactInputSingleParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactInputSingleParams)); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -97,10 +93,8 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT_SINGLE)) { - IV4Router.ExactOutputSingleParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactOutputSingleParams) - ); + IV4Router.ExactOutputSingleParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactOutputSingleParams)); tokenIn = swapParams.zeroForOne ? address(uint160(swapParams.poolKey.currency0.toId())) @@ -111,23 +105,18 @@ contract UniswapV4Executor is IExecutor, V4Router { isExactInput = false; amount = swapParams.amountOut; } else if (action == uint8(Actions.SWAP_EXACT_IN)) { - IV4Router.ExactInputParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactInputParams) - ); + IV4Router.ExactInputParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactInputParams)); tokenIn = address(uint160(swapParams.currencyIn.toId())); - PathKey memory lastPath = swapParams.path[ - swapParams.path.length - 1 - ]; + PathKey memory lastPath = + swapParams.path[swapParams.path.length - 1]; tokenOut = address(uint160(lastPath.intermediateCurrency.toId())); isExactInput = true; amount = swapParams.amountIn; } else if (action == uint8(Actions.SWAP_EXACT_OUT)) { - IV4Router.ExactOutputParams memory swapParams = abi.decode( - params[0], - (IV4Router.ExactOutputParams) - ); + IV4Router.ExactOutputParams memory swapParams = + abi.decode(params[0], (IV4Router.ExactOutputParams)); PathKey memory firstPath = swapParams.path[0]; tokenIn = address(uint160(firstPath.intermediateCurrency.toId())); @@ -137,14 +126,12 @@ contract UniswapV4Executor is IExecutor, V4Router { } } - function _pay( - Currency token, - address payer, - uint256 amount - ) internal override { + function _pay(Currency token, address payer, uint256 amount) + internal + override + { IERC20(Currency.unwrap(token)).safeTransfer( - address(poolManager), - amount + address(poolManager), amount ); } diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index ef3b69b..4ad7dd9 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -18,9 +18,7 @@ contract TychoRouterTest is TychoRouterTestSetup { event CallbackVerifierSet(address indexed callbackVerifier); event Withdrawal( - address indexed token, - uint256 amount, - address indexed receiver + address indexed token, uint256 amount, address indexed receiver ); function testSetExecutorsValidRole() public { @@ -216,10 +214,7 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(WETH_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -256,10 +251,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ) ); @@ -298,10 +290,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, - WETH_WBTC_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_WBTC_POOL, tychoRouterAddr, false ) ); // WBTC -> USDC @@ -312,10 +301,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WBTC_ADDR, - USDC_WBTC_POOL, - tychoRouterAddr, - true + WBTC_ADDR, USDC_WBTC_POOL, tychoRouterAddr, true ) ); // WETH -> DAI @@ -326,10 +312,7 @@ contract TychoRouterTest is TychoRouterTestSetup { address(usv2Executor), bytes4(0), encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ) ); @@ -365,10 +348,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -421,10 +401,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -483,10 +460,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -518,10 +492,7 @@ contract TychoRouterTest is TychoRouterTestSetup { assertEq(amountOut, expectedAmount); uint256 daiBalance = IERC20(DAI_ADDR).balanceOf(ALICE); assertEq(daiBalance, expectedAmount); - assertEq( - IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), - 26598819248184436997 - ); + assertEq(IERC20(DAI_ADDR).balanceOf(FEE_RECEIVER), 26598819248184436997); vm.stopPrank(); } @@ -534,22 +505,19 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.startPrank(ALICE); - IAllowanceTransfer.PermitSingle - memory emptyPermitSingle = IAllowanceTransfer.PermitSingle({ - details: IAllowanceTransfer.PermitDetails({ - token: address(0), - amount: 0, - expiration: 0, - nonce: 0 - }), - spender: address(0), - sigDeadline: 0 - }); + IAllowanceTransfer.PermitSingle memory emptyPermitSingle = + IAllowanceTransfer.PermitSingle({ + details: IAllowanceTransfer.PermitDetails({ + token: address(0), + amount: 0, + expiration: 0, + nonce: 0 + }), + spender: address(0), + sigDeadline: 0 + }); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -598,12 +566,8 @@ contract TychoRouterTest is TychoRouterTestSetup { bytes memory signature ) = handlePermit2Approval(DAI_ADDR, amountIn); - bytes memory protocolData = encodeUniswapV2Swap( - DAI_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - true - ); + bytes memory protocolData = + encodeUniswapV2Swap(DAI_ADDR, WETH_DAI_POOL, tychoRouterAddr, true); bytes memory swap = encodeSwap( uint8(0), @@ -647,11 +611,7 @@ contract TychoRouterTest is TychoRouterTestSetup { uint256 expAmountOut = 1205_128428842122129186; //Swap 1 WETH for 1205.12 DAI bool zeroForOne = false; bytes memory protocolData = encodeUniswapV3Swap( - WETH_ADDR, - DAI_ADDR, - tychoRouterAddr, - DAI_WETH_USV3, - zeroForOne + WETH_ADDR, DAI_ADDR, tychoRouterAddr, DAI_WETH_USV3, zeroForOne ); bytes memory swap = encodeSwap( uint8(0), @@ -693,7 +653,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call( + (bool success,) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d481bb00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfbc3000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041f2740fde9662d8bc1f8fe8e8fc29447c1832d625f06f4a56ee5103ad555c12323af5d50eb840f73d17873383ae3b7573956d5df7b2bf76bddba768c2837894a51b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -722,7 +682,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call{value: 1 ether}( + (bool success,) = tychoRouterAddr.call{value: 1 ether}( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4806b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfa73000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041c36406a750c499ac7f79f7666650f0d4f20fc27bb49ab68121c0be6554cb5cab6caf90dc3aab2e21083a8fa46976521a1e9df41ce74be59abf03e0d3691541e91c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00020000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950000000000" ); @@ -751,7 +711,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call( + (bool success,) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000006b175474e89094c44da98b954eedeac495271d0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc20000000000000000000000006b175474e89094c44da98b954eedeac495271d0f0000000000000000000000000000000000000000000000a2a15d09519be000000000000000000000000000000000000000000000000000000000000067d4809800000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfaa000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000280000000000000000000000000000000000000000000000000000000000000004146411c70ec7fee0d5d260803cb220f5365792426c5d94f7a0a4d37abb05205752c5418b1fadd059570a71f0911814e546728e1f21876f2a1c6d38d34bd235fd61c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fa478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d013950100000000" ); @@ -782,7 +742,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // but manually replacing the executor address // `5c2f5a71f67c01775180adc06909288b4c329308` with the one in this test // `5615deb798bb3e4dfa0139dfa1b3d433cc23b72f` - (bool success, ) = tychoRouterAddr.call( + (bool success,) = tychoRouterAddr.call( hex"4860f9ed0000000000000000000000000000000000000000000000000de0b6b3a7640000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000cd09f75e2bf2a4d11f3ab23f1389fcc1621c0cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000067d4810d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000003ede3eca2a72b3aecc820e955b36f38437d013950000000000000000000000000000000000000000000000000000000067acfb15000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000041ecaab75f0791c9683b001ea2f0e01a0a6aaf03e6e49c83e9c8a8e588a38e3be9230d962926628ffbf6a5370cda559ff0e7876a63ed38eebe33dbef5b5e2e46ef1b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000170005a00028000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2a478c2975ab1ea89e8196811f51a7b7ade33eb113ede3eca2a72b3aecc820e955b36f38437d0139500005a00010000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625abc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2bb2b8038a1640196fbe3e38816f3e67cba72d9403ede3eca2a72b3aecc820e955b36f38437d0139500005a02030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab6b175474e89094c44da98b954eedeac495271d0fae461ca67b15dc8dc81ce7615e0320da1a9ab8d53ede3eca2a72b3aecc820e955b36f38437d0139501005a01030000005615deb798bb3e4dfa0139dfa1b3d433cc23b72fbd0625ab2260fac5e5542a773aa44fbcfedf7c193bc2c599004375dff511095cc5a197a54140a24efef3a4163ede3eca2a72b3aecc820e955b36f38437d013950100000000000000000000000000000000" ); @@ -812,10 +772,7 @@ contract TychoRouterTest is TychoRouterTestSetup { ) = handlePermit2Approval(WETH_ADDR, amountIn); bytes memory protocolData = encodeUniswapV2Swap( - WETH_ADDR, - WETH_DAI_POOL, - tychoRouterAddr, - false + WETH_ADDR, WETH_DAI_POOL, tychoRouterAddr, false ); bytes memory swap = encodeSwap( @@ -832,8 +789,7 @@ contract TychoRouterTest is TychoRouterTestSetup { vm.expectRevert( abi.encodeWithSelector( - TychoRouter__AmountInNotFullySpent.selector, - 400000000000000000 + TychoRouter__AmountInNotFullySpent.selector, 400000000000000000 ) ); @@ -859,12 +815,7 @@ contract TychoRouterTest is TychoRouterTestSetup { deal(USDE_ADDR, tychoRouterAddr, amountIn); bytes memory protocolData = UniswapV4Utils.encodeExactInputSingle( - USDE_ADDR, - USDT_ADDR, - 100, - true, - 1, - uint128(amountIn) + USDE_ADDR, USDT_ADDR, 100, true, 1, uint128(amountIn) ); // add executor and selector for callback diff --git a/foundry/test/executors/UniswapV3Executor.t.sol b/foundry/test/executors/UniswapV3Executor.t.sol index fe50674..fc14a5a 100644 --- a/foundry/test/executors/UniswapV3Executor.t.sol +++ b/foundry/test/executors/UniswapV3Executor.t.sol @@ -8,9 +8,7 @@ import {Constants} from "../Constants.sol"; contract UniswapV3ExecutorExposed is UniswapV3Executor { constructor(address _factory) UniswapV3Executor(_factory) {} - function decodeData( - bytes calldata data - ) + function decodeData(bytes calldata data) external pure returns ( @@ -44,12 +42,7 @@ contract UniswapV3ExecutorTest is Test, Constants { function testDecodeParams() public view { uint24 expectedPoolFee = 500; bytes memory data = abi.encodePacked( - WETH_ADDR, - DAI_ADDR, - expectedPoolFee, - address(2), - address(3), - false + WETH_ADDR, DAI_ADDR, expectedPoolFee, address(2), address(3), false ); ( @@ -70,11 +63,8 @@ contract UniswapV3ExecutorTest is Test, Constants { } function testDecodeParamsInvalidDataLength() public { - bytes memory invalidParams = abi.encodePacked( - WETH_ADDR, - address(2), - address(3) - ); + bytes memory invalidParams = + abi.encodePacked(WETH_ADDR, address(2), address(3)); vm.expectRevert(UniswapV3Executor__InvalidDataLength.selector); uniswapV3Exposed.decodeData(invalidParams); @@ -100,4 +90,35 @@ contract UniswapV3ExecutorTest is Test, Constants { uint256 finalPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); assertEq(finalPoolReserve - initialPoolReserve, amountOwed); } + + function testSwapWETHForDAI() public { + uint256 amountIn = 10 ** 18; + deal(WETH_ADDR, address(uniswapV3Exposed), amountIn); + + uint256 expAmountOut = 1205_128428842122129186; //Swap 1 WETH for 1205.12 DAI + bool zeroForOne = false; + + bytes memory data = encodeUniswapV3Swap( + WETH_ADDR, DAI_ADDR, address(this), DAI_WETH_USV3, zeroForOne + ); + + uint256 amountOut = uniswapV3Exposed.swap(amountIn, data); + + assertGe(amountOut, expAmountOut); + assertEq(IERC20(WETH_ADDR).balanceOf(address(uniswapV3Exposed)), 0); + assertGe(IERC20(DAI_ADDR).balanceOf(address(this)), expAmountOut); + } + + function encodeUniswapV3Swap( + address tokenIn, + address tokenOut, + address receiver, + address target, + bool zero2one + ) internal view returns (bytes memory) { + IUniswapV3Pool pool = IUniswapV3Pool(target); + return abi.encodePacked( + tokenIn, tokenOut, pool.fee(), receiver, target, zero2one + ); + } } From ad91e485d3a7b125f4db39cb84bb504f2d6064cf Mon Sep 17 00:00:00 2001 From: royvardhan Date: Sat, 15 Feb 2025 00:44:28 +0530 Subject: [PATCH 09/15] feat: rename execution dispatcher to dispatcher and use dispatcher for USV4 callback --- .../{ExecutionDispatcher.sol => Dispatcher.sol} | 14 +++++++------- foundry/src/TychoRouter.sol | 16 +++------------- foundry/test/ExecutionDispatcher.t.sol | 14 ++++++-------- 3 files changed, 16 insertions(+), 28 deletions(-) rename foundry/src/{ExecutionDispatcher.sol => Dispatcher.sol} (89%) diff --git a/foundry/src/ExecutionDispatcher.sol b/foundry/src/Dispatcher.sol similarity index 89% rename from foundry/src/ExecutionDispatcher.sol rename to foundry/src/Dispatcher.sol index 01e6ff4..d2a9128 100644 --- a/foundry/src/ExecutionDispatcher.sol +++ b/foundry/src/Dispatcher.sol @@ -5,11 +5,11 @@ import "@interfaces/IExecutor.sol"; import "@interfaces/ICallback.sol"; import "forge-std/console.sol"; -error ExecutionDispatcher__UnapprovedExecutor(); -error ExecutionDispatcher__NonContractExecutor(); +error Dispatcher__UnapprovedExecutor(); +error Dispatcher__NonContractExecutor(); /** - * @title ExecutionDispatcher - Dispatch execution to external contracts + * @title Dispatcher - Dispatch execution to external contracts * @author PropellerHeads Devs * @dev Provides the ability to delegate execution of swaps to external * contracts. This allows dynamically adding new supported protocols @@ -20,7 +20,7 @@ error ExecutionDispatcher__NonContractExecutor(); * Note: Executor contracts need to implement the IExecutor interface unless * an alternate selector is specified. */ -contract ExecutionDispatcher { +contract Dispatcher { mapping(address => bool) public executors; event ExecutorSet(address indexed executor); @@ -33,7 +33,7 @@ contract ExecutionDispatcher { */ function _setExecutor(address target) internal { if (target.code.length == 0) { - revert ExecutionDispatcher__NonContractExecutor(); + revert Dispatcher__NonContractExecutor(); } executors[target] = true; emit ExecutorSet(target); @@ -60,7 +60,7 @@ contract ExecutionDispatcher { bytes calldata data ) internal returns (uint256 calculatedAmount) { if (!executors[executor]) { - revert ExecutionDispatcher__UnapprovedExecutor(); + revert Dispatcher__UnapprovedExecutor(); } selector = selector == bytes4(0) ? IExecutor.swap.selector : selector; @@ -93,7 +93,7 @@ contract ExecutionDispatcher { } if (!executors[executor]) { - revert ExecutionDispatcher__UnapprovedExecutor(); + revert Dispatcher__UnapprovedExecutor(); } selector = diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 08ed017..5c26097 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -11,11 +11,10 @@ import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@permit2/src/interfaces/IAllowanceTransfer.sol"; -import "./ExecutionDispatcher.sol"; +import "./Dispatcher.sol"; import {LibSwap} from "../lib/LibSwap.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {SafeCallback} from "@uniswap/v4-periphery/src/base/SafeCallback.sol"; -import "forge-std/console.sol"; error TychoRouter__WithdrawalFailed(); error TychoRouter__AddressZero(); @@ -26,7 +25,7 @@ error TychoRouter__MessageValueMismatch(uint256 value, uint256 amount); contract TychoRouter is AccessControl, - ExecutionDispatcher, + Dispatcher, Pausable, ReentrancyGuard, SafeCallback @@ -390,16 +389,7 @@ contract TychoRouter is bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); address executor = address(uint160(bytes20(data[data.length - 20:]))); bytes memory protocolData = data[:data.length - 24]; - - if (!executors[executor]) { - revert ExecutionDispatcher__UnapprovedExecutor(); - } - - // slither-disable-next-line controlled-delegatecall,low-level-calls - (bool success,) = executor.delegatecall( - abi.encodeWithSelector(selector, protocolData) - ); - require(success, "delegatecall to uniswap v4 callback failed"); + _handleCallback(selector, abi.encodePacked(protocolData, executor)); return ""; } } diff --git a/foundry/test/ExecutionDispatcher.t.sol b/foundry/test/ExecutionDispatcher.t.sol index 7f2fb81..4f12df0 100644 --- a/foundry/test/ExecutionDispatcher.t.sol +++ b/foundry/test/ExecutionDispatcher.t.sol @@ -1,10 +1,10 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.26; -import "@src/ExecutionDispatcher.sol"; +import "@src/Dispatcher.sol"; import "./TychoRouterTestSetup.sol"; -contract ExecutionDispatcherExposed is ExecutionDispatcher { +contract DispatcherExposed is Dispatcher { function exposedCallExecutor( address executor, bytes4 selector, @@ -23,8 +23,8 @@ contract ExecutionDispatcherExposed is ExecutionDispatcher { } } -contract ExecutionDispatcherTest is Constants { - ExecutionDispatcherExposed dispatcherExposed; +contract DispatcherTest is Constants { + DispatcherExposed dispatcherExposed; event ExecutorSet(address indexed executor); event ExecutorRemoved(address indexed executor); @@ -32,7 +32,7 @@ contract ExecutionDispatcherTest is Constants { function setUp() public { uint256 forkBlock = 20673900; vm.createSelectFork(vm.rpcUrl("mainnet"), forkBlock); - dispatcherExposed = new ExecutionDispatcherExposed(); + dispatcherExposed = new DispatcherExposed(); deal(WETH_ADDR, address(dispatcherExposed), 15 ether); deployDummyContract(); } @@ -61,9 +61,7 @@ contract ExecutionDispatcherTest is Constants { function testSetExecutorNonContract() public { vm.expectRevert( - abi.encodeWithSelector( - ExecutionDispatcher__NonContractExecutor.selector - ) + abi.encodeWithSelector(Dispatcher__NonContractExecutor.selector) ); dispatcherExposed.exposedSetExecutor(BOB); } From 9b8175aff993e3c2d55653082e4df32ba4d9d27f Mon Sep 17 00:00:00 2001 From: royvardhan Date: Sat, 15 Feb 2025 01:01:16 +0530 Subject: [PATCH 10/15] chore: cleanup --- foundry/interfaces/ICallback.sol | 2 -- foundry/src/Dispatcher.sol | 3 +-- foundry/src/TychoRouter.sol | 8 ++++---- foundry/src/executors/UniswapV3Executor.sol | 1 - foundry/test/Constants.sol | 1 + foundry/test/TychoRouterTestSetup.sol | 2 +- foundry/test/executors/UniswapV3Executor.t.sol | 3 +-- 7 files changed, 8 insertions(+), 12 deletions(-) diff --git a/foundry/interfaces/ICallback.sol b/foundry/interfaces/ICallback.sol index 38decfa..e71527e 100644 --- a/foundry/interfaces/ICallback.sol +++ b/foundry/interfaces/ICallback.sol @@ -2,8 +2,6 @@ pragma solidity ^0.8.26; interface ICallback { - error UnauthorizedCaller(string exchange, address sender); - function handleCallback( bytes calldata data ) external returns (bytes memory result); diff --git a/foundry/src/Dispatcher.sol b/foundry/src/Dispatcher.sol index d2a9128..b0a69c1 100644 --- a/foundry/src/Dispatcher.sol +++ b/foundry/src/Dispatcher.sol @@ -3,7 +3,6 @@ pragma solidity ^0.8.26; import "@interfaces/IExecutor.sol"; import "@interfaces/ICallback.sol"; -import "forge-std/console.sol"; error Dispatcher__UnapprovedExecutor(); error Dispatcher__NonContractExecutor(); @@ -83,7 +82,7 @@ contract Dispatcher { } function _handleCallback(bytes4 selector, bytes memory data) internal { - // Access the last 20 bytes of the bytes memory data using assembly + // Using assembly to access the last 20 bytes of the bytes memory data address executor; // slither-disable-next-line assembly assembly { diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 5c26097..f26fa7c 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -227,10 +227,10 @@ contract TychoRouter is * This function will static call a verifier contract and should revert if the * caller is not a pool. */ - // fallback() external { - // bytes4 selector = bytes4(msg.data[:4]); - // _handleCallback(selector, msg.data[4:]); - // } + fallback() external { + bytes4 selector = bytes4(msg.data[:4]); + _handleCallback(selector, msg.data[4:]); + } /** * @dev Pauses the contract diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index 02e8769..74ff0e4 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -6,7 +6,6 @@ import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-updated/CallbackValidationV2.sol"; import "@interfaces/ICallback.sol"; -import "forge-std/console.sol"; error UniswapV3Executor__InvalidDataLength(); error UniswapV3Executor__InvalidFactory(); diff --git a/foundry/test/Constants.sol b/foundry/test/Constants.sol index ba8fbef..3b742f0 100644 --- a/foundry/test/Constants.sol +++ b/foundry/test/Constants.sol @@ -38,6 +38,7 @@ contract Constants is Test { address USDC_WBTC_POOL = 0x004375Dff511095CC5A197A54140a24eFEF3A416; // uniswap v3 + address USV3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984; address DAI_WETH_USV3 = 0xC2e9F25Be6257c210d7Adf0D4Cd6E3E881ba25f8; /** diff --git a/foundry/test/TychoRouterTestSetup.sol b/foundry/test/TychoRouterTestSetup.sol index ef913fd..6c99be8 100644 --- a/foundry/test/TychoRouterTestSetup.sol +++ b/foundry/test/TychoRouterTestSetup.sol @@ -47,7 +47,7 @@ contract TychoRouterTestSetup is Test, Constants { vm.createSelectFork(vm.rpcUrl("mainnet"), forkBlock); vm.startPrank(ADMIN); - address factoryV3 = address(0x1F98431c8aD98523631AE4a59f267346ea31F984); + address factoryV3 = USV3_FACTORY; address poolManagerAddress = 0x000000000004444c5dc75cB358380D2e3dE08A90; IPoolManager poolManager = IPoolManager(poolManagerAddress); tychoRouter = diff --git a/foundry/test/executors/UniswapV3Executor.t.sol b/foundry/test/executors/UniswapV3Executor.t.sol index fc14a5a..e9a9f57 100644 --- a/foundry/test/executors/UniswapV3Executor.t.sol +++ b/foundry/test/executors/UniswapV3Executor.t.sol @@ -30,13 +30,12 @@ contract UniswapV3ExecutorTest is Test, Constants { UniswapV3ExecutorExposed uniswapV3Exposed; IERC20 WETH = IERC20(WETH_ADDR); IERC20 DAI = IERC20(DAI_ADDR); - address factory = 0x1F98431c8aD98523631AE4a59f267346ea31F984; function setUp() public { uint256 forkBlock = 17323404; vm.createSelectFork(vm.rpcUrl("mainnet"), forkBlock); - uniswapV3Exposed = new UniswapV3ExecutorExposed(factory); + uniswapV3Exposed = new UniswapV3ExecutorExposed(USV3_FACTORY); } function testDecodeParams() public view { From 14e5c127c6273df11383864503ddf1f13e9026a1 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Sat, 15 Feb 2025 01:06:23 +0530 Subject: [PATCH 11/15] chore: rm safecallback from router --- foundry/src/TychoRouter.sol | 18 ++++-------------- foundry/test/TychoRouter.t.sol | 2 +- foundry/test/TychoRouterTestSetup.sol | 7 ++----- 3 files changed, 7 insertions(+), 20 deletions(-) diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index f26fa7c..bfdcdd3 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -14,7 +14,6 @@ import "@permit2/src/interfaces/IAllowanceTransfer.sol"; import "./Dispatcher.sol"; import {LibSwap} from "../lib/LibSwap.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; -import {SafeCallback} from "@uniswap/v4-periphery/src/base/SafeCallback.sol"; error TychoRouter__WithdrawalFailed(); error TychoRouter__AddressZero(); @@ -23,13 +22,7 @@ error TychoRouter__NegativeSlippage(uint256 amount, uint256 minAmount); error TychoRouter__AmountInNotFullySpent(uint256 leftoverAmount); error TychoRouter__MessageValueMismatch(uint256 value, uint256 amount); -contract TychoRouter is - AccessControl, - Dispatcher, - Pausable, - ReentrancyGuard, - SafeCallback -{ +contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { IAllowanceTransfer public immutable permit2; IWETH private immutable _weth; @@ -63,9 +56,7 @@ contract TychoRouter is ); event FeeSet(uint256 indexed oldFee, uint256 indexed newFee); - constructor(IPoolManager _poolManager, address _permit2, address weth) - SafeCallback(_poolManager) - { + constructor(address _permit2, address weth) { if (_permit2 == address(0) || weth == address(0)) { revert TychoRouter__AddressZero(); } @@ -380,9 +371,8 @@ contract TychoRouter is ); } - function _unlockCallback(bytes calldata data) - internal - override + function unlockCallback(bytes calldata data) + external returns (bytes memory) { require(data.length >= 20, "Invalid data length"); diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index 4ad7dd9..3116b7b 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -821,7 +821,7 @@ contract TychoRouterTest is TychoRouterTestSetup { // add executor and selector for callback bytes memory protocolDataWithCallBack = abi.encodePacked( protocolData, - SafeCallback.unlockCallback.selector, + TychoRouter.unlockCallback.selector, address(usv4Executor) ); diff --git a/foundry/test/TychoRouterTestSetup.sol b/foundry/test/TychoRouterTestSetup.sol index 6c99be8..9fb1f44 100644 --- a/foundry/test/TychoRouterTestSetup.sol +++ b/foundry/test/TychoRouterTestSetup.sol @@ -12,9 +12,7 @@ import {WETH} from "../lib/permit2/lib/solmate/src/tokens/WETH.sol"; import {PoolManager} from "@uniswap/v4-core/src/PoolManager.sol"; contract TychoRouterExposed is TychoRouter { - constructor(IPoolManager _poolManager, address _permit2, address weth) - TychoRouter(_poolManager, _permit2, weth) - {} + constructor(address _permit2, address weth) TychoRouter(_permit2, weth) {} function wrapETH(uint256 amount) external payable { return _wrapETH(amount); @@ -50,8 +48,7 @@ contract TychoRouterTestSetup is Test, Constants { address factoryV3 = USV3_FACTORY; address poolManagerAddress = 0x000000000004444c5dc75cB358380D2e3dE08A90; IPoolManager poolManager = IPoolManager(poolManagerAddress); - tychoRouter = - new TychoRouterExposed(poolManager, permit2Address, WETH_ADDR); + tychoRouter = new TychoRouterExposed(permit2Address, WETH_ADDR); tychoRouterAddr = address(tychoRouter); tychoRouter.grantRole(keccak256("FUND_RESCUER_ROLE"), FUND_RESCUER); tychoRouter.grantRole(keccak256("FEE_SETTER_ROLE"), FEE_SETTER); From 076586d77672faf1a02b20c69ea1de4ec8e6ae55 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Mon, 17 Feb 2025 21:51:09 +0530 Subject: [PATCH 12/15] feat: update _handleCallback, add verifyCallback with docs --- foundry/interfaces/ICallback.sol | 17 +++++ foundry/src/Dispatcher.sol | 16 ++--- foundry/src/TychoRouter.sol | 30 ++++++--- foundry/src/executors/UniswapV3Executor.sol | 73 ++++++++++++++------- 4 files changed, 92 insertions(+), 44 deletions(-) diff --git a/foundry/interfaces/ICallback.sol b/foundry/interfaces/ICallback.sol index e71527e..408a5fe 100644 --- a/foundry/interfaces/ICallback.sol +++ b/foundry/interfaces/ICallback.sol @@ -2,7 +2,24 @@ pragma solidity ^0.8.26; interface ICallback { + /** + * @notice Handles callback data from a protocol or contract interaction. + * @dev This method processes callback data and returns a result. Implementations + * should handle the specific callback logic required by the protocol. + * + * @param data The encoded callback data to be processed. + * @return result The encoded result of the callback processing. + */ function handleCallback( bytes calldata data ) external returns (bytes memory result); + + /** + * @notice Verifies the validity of callback data. + * @dev This view function checks if the provided callback data is valid according + * to the protocol's requirements. It should revert if the data is invalid. + * + * @param data The encoded callback data to verify. + */ + function verifyCallback(bytes calldata data) external view; } diff --git a/foundry/src/Dispatcher.sol b/foundry/src/Dispatcher.sol index b0a69c1..d23321c 100644 --- a/foundry/src/Dispatcher.sol +++ b/foundry/src/Dispatcher.sol @@ -6,6 +6,7 @@ import "@interfaces/ICallback.sol"; error Dispatcher__UnapprovedExecutor(); error Dispatcher__NonContractExecutor(); +error Dispatcher__InvalidDataLength(); /** * @title Dispatcher - Dispatch execution to external contracts @@ -81,16 +82,11 @@ contract Dispatcher { calculatedAmount = abi.decode(result, (uint256)); } - function _handleCallback(bytes4 selector, bytes memory data) internal { - // Using assembly to access the last 20 bytes of the bytes memory data - address executor; - // slither-disable-next-line assembly - assembly { - let pos := sub(add(add(data, 0x20), mload(data)), 20) - executor := mload(pos) - executor := shr(96, executor) - } - + function _handleCallback( + bytes4 selector, + address executor, + bytes memory data + ) internal { if (!executors[executor]) { revert Dispatcher__UnapprovedExecutor(); } diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index bfdcdd3..2ec2f21 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -21,6 +21,7 @@ error TychoRouter__EmptySwaps(); error TychoRouter__NegativeSlippage(uint256 amount, uint256 minAmount); error TychoRouter__AmountInNotFullySpent(uint256 leftoverAmount); error TychoRouter__MessageValueMismatch(uint256 value, uint256 amount); +error TychoRouter__InvalidDataLength(); contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { IAllowanceTransfer public immutable permit2; @@ -215,12 +216,14 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { /** * @dev We use the fallback function to allow flexibility on callback. - * This function will static call a verifier contract and should revert if the - * caller is not a pool. */ fallback() external { - bytes4 selector = bytes4(msg.data[:4]); - _handleCallback(selector, msg.data[4:]); + address executor = + address(uint160(bytes20(msg.data[msg.data.length - 20:]))); + bytes4 selector = + bytes4(msg.data[msg.data.length - 24:msg.data.length - 20]); + bytes memory protocolData = msg.data[:msg.data.length - 24]; + _handleCallback(selector, executor, protocolData); } /** @@ -364,22 +367,31 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, - bytes calldata msgData + bytes calldata data ) external { + if (data.length < 24) revert TychoRouter__InvalidDataLength(); + address executor = address(uint160(bytes20(data[data.length - 20:]))); + bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); + bytes memory protocolData = data[:data.length - 24]; _handleCallback( - bytes4(0), abi.encodePacked(amount0Delta, amount1Delta, msgData) + selector, + executor, + abi.encodePacked(amount0Delta, amount1Delta, protocolData) ); } + /** + * @dev Called by UniswapV4 pool manager after achieving unlock state. + */ function unlockCallback(bytes calldata data) external returns (bytes memory) { - require(data.length >= 20, "Invalid data length"); - bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); + if (data.length < 24) revert TychoRouter__InvalidDataLength(); address executor = address(uint160(bytes20(data[data.length - 20:]))); + bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); bytes memory protocolData = data[:data.length - 24]; - _handleCallback(selector, abi.encodePacked(protocolData, executor)); + _handleCallback(selector, executor, protocolData); return ""; } } diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index 74ff0e4..681edb2 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -29,11 +29,10 @@ contract UniswapV3Executor is IExecutor, ICallback { } // slither-disable-next-line locked-ether - function swap(uint256 amountIn, bytes calldata data) - external - payable - returns (uint256 amountOut) - { + function swap( + uint256 amountIn, + bytes calldata data + ) external payable returns (uint256 amountOut) { ( address tokenIn, address tokenOut, @@ -76,7 +75,9 @@ contract UniswapV3Executor is IExecutor, ICallback { abi.encodeWithSelector( ICallback.handleCallback.selector, abi.encodePacked( - amount0Delta, amount1Delta, data[:data.length - 20] + amount0Delta, + amount1Delta, + data[:data.length - 20] ) ) ); @@ -91,28 +92,43 @@ contract UniswapV3Executor is IExecutor, ICallback { } } - function handleCallback(bytes calldata msgData) - external - returns (bytes memory result) - { - (int256 amount0Delta, int256 amount1Delta) = - abi.decode(msgData[:64], (int256, int256)); + function handleCallback( + bytes calldata msgData + ) external returns (bytes memory result) { + (int256 amount0Delta, int256 amount1Delta) = abi.decode( + msgData[:64], + (int256, int256) + ); address tokenIn = address(bytes20(msgData[64:84])); - address tokenOut = address(bytes20(msgData[84:104])); - uint24 poolFee = uint24(bytes3(msgData[104:107])); - // slither-disable-next-line unused-return - CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); + verifyCallback(msgData[64:]); - uint256 amountOwed = - amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); + uint256 amountOwed = amount0Delta > 0 + ? uint256(amount0Delta) + : uint256(amount1Delta); IERC20(tokenIn).safeTransfer(msg.sender, amountOwed); return abi.encode(amountOwed, tokenIn); } - function _decodeData(bytes calldata data) + function verifyCallback(bytes calldata data) public view { + address tokenIn = address(bytes20(data[0:20])); + address tokenOut = address(bytes20(data[20:40])); + uint24 poolFee = uint24(bytes3(data[40:43])); + + // slither-disable-next-line unused-return + CallbackValidationV2.verifyCallback( + factory, + tokenIn, + tokenOut, + poolFee + ); + } + + function _decodeData( + bytes calldata data + ) internal pure returns ( @@ -135,11 +151,18 @@ contract UniswapV3Executor is IExecutor, ICallback { zeroForOne = uint8(data[83]) > 0; } - function _makeV3CallbackData(address tokenIn, address tokenOut, uint24 fee) - internal - view - returns (bytes memory) - { - return abi.encodePacked(tokenIn, tokenOut, fee, self); + function _makeV3CallbackData( + address tokenIn, + address tokenOut, + uint24 fee + ) internal view returns (bytes memory) { + return + abi.encodePacked( + tokenIn, + tokenOut, + fee, + ICallback.handleCallback.selector, + self + ); } } From 26049356096ffcc907c678d32f2c4964067eaab5 Mon Sep 17 00:00:00 2001 From: royvardhan Date: Mon, 17 Feb 2025 22:51:40 +0530 Subject: [PATCH 13/15] chore: update unlockCallback and uniswapV3SwapCallback --- foundry/src/TychoRouter.sol | 9 +-- foundry/src/executors/UniswapV3Executor.sol | 63 ++++++++------------- foundry/src/executors/UniswapV4Executor.sol | 1 - foundry/test/TychoRouter.t.sol | 1 + 4 files changed, 30 insertions(+), 44 deletions(-) diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 2ec2f21..49b9094 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -370,8 +370,8 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { bytes calldata data ) external { if (data.length < 24) revert TychoRouter__InvalidDataLength(); - address executor = address(uint160(bytes20(data[data.length - 20:]))); - bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); + bytes4 selector = bytes4(data[data.length - 4:]); + address executor = address(uint160(bytes20(data[data.length - 24:]))); bytes memory protocolData = data[:data.length - 24]; _handleCallback( selector, @@ -388,8 +388,9 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { returns (bytes memory) { if (data.length < 24) revert TychoRouter__InvalidDataLength(); - address executor = address(uint160(bytes20(data[data.length - 20:]))); - bytes4 selector = bytes4(data[data.length - 24:data.length - 20]); + bytes4 selector = bytes4(data[data.length - 4:]); + address executor = + address(uint160(bytes20(data[data.length - 24:data.length - 4]))); bytes memory protocolData = data[:data.length - 24]; _handleCallback(selector, executor, protocolData); return ""; diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index 681edb2..4472eef 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -29,10 +29,11 @@ contract UniswapV3Executor is IExecutor, ICallback { } // slither-disable-next-line locked-ether - function swap( - uint256 amountIn, - bytes calldata data - ) external payable returns (uint256 amountOut) { + function swap(uint256 amountIn, bytes calldata data) + external + payable + returns (uint256 amountOut) + { ( address tokenIn, address tokenOut, @@ -75,9 +76,7 @@ contract UniswapV3Executor is IExecutor, ICallback { abi.encodeWithSelector( ICallback.handleCallback.selector, abi.encodePacked( - amount0Delta, - amount1Delta, - data[:data.length - 20] + amount0Delta, amount1Delta, data[:data.length - 20] ) ) ); @@ -92,21 +91,19 @@ contract UniswapV3Executor is IExecutor, ICallback { } } - function handleCallback( - bytes calldata msgData - ) external returns (bytes memory result) { - (int256 amount0Delta, int256 amount1Delta) = abi.decode( - msgData[:64], - (int256, int256) - ); + function handleCallback(bytes calldata msgData) + external + returns (bytes memory result) + { + (int256 amount0Delta, int256 amount1Delta) = + abi.decode(msgData[:64], (int256, int256)); address tokenIn = address(bytes20(msgData[64:84])); verifyCallback(msgData[64:]); - uint256 amountOwed = amount0Delta > 0 - ? uint256(amount0Delta) - : uint256(amount1Delta); + uint256 amountOwed = + amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); IERC20(tokenIn).safeTransfer(msg.sender, amountOwed); return abi.encode(amountOwed, tokenIn); @@ -118,17 +115,10 @@ contract UniswapV3Executor is IExecutor, ICallback { uint24 poolFee = uint24(bytes3(data[40:43])); // slither-disable-next-line unused-return - CallbackValidationV2.verifyCallback( - factory, - tokenIn, - tokenOut, - poolFee - ); + CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); } - function _decodeData( - bytes calldata data - ) + function _decodeData(bytes calldata data) internal pure returns ( @@ -151,18 +141,13 @@ contract UniswapV3Executor is IExecutor, ICallback { zeroForOne = uint8(data[83]) > 0; } - function _makeV3CallbackData( - address tokenIn, - address tokenOut, - uint24 fee - ) internal view returns (bytes memory) { - return - abi.encodePacked( - tokenIn, - tokenOut, - fee, - ICallback.handleCallback.selector, - self - ); + function _makeV3CallbackData(address tokenIn, address tokenOut, uint24 fee) + internal + view + returns (bytes memory) + { + return abi.encodePacked( + tokenIn, tokenOut, fee, self, ICallback.handleCallback.selector + ); } } diff --git a/foundry/src/executors/UniswapV4Executor.sol b/foundry/src/executors/UniswapV4Executor.sol index a1e6f98..57fe796 100644 --- a/foundry/src/executors/UniswapV4Executor.sol +++ b/foundry/src/executors/UniswapV4Executor.sol @@ -17,7 +17,6 @@ import {Actions} from "@uniswap/v4-periphery/src/libraries/Actions.sol"; import {IV4Router} from "@uniswap/v4-periphery/src/interfaces/IV4Router.sol"; import {PathKey} from "@uniswap/v4-periphery/src/libraries/PathKey.sol"; - error UniswapV4Executor__InvalidDataLength(); contract UniswapV4Executor is IExecutor, V4Router { diff --git a/foundry/test/TychoRouter.t.sol b/foundry/test/TychoRouter.t.sol index a6d9106..d5787b5 100644 --- a/foundry/test/TychoRouter.t.sol +++ b/foundry/test/TychoRouter.t.sol @@ -5,6 +5,7 @@ import "@src/executors/UniswapV4Executor.sol"; import {TychoRouter} from "@src/TychoRouter.sol"; import "./TychoRouterTestSetup.sol"; import "./executors/UniswapV4Utils.sol"; +import {SafeCallback} from "@uniswap/v4-periphery/src/base/SafeCallback.sol"; contract TychoRouterTest is TychoRouterTestSetup { bytes32 public constant EXECUTOR_SETTER_ROLE = From 2aa63d7ec0f9a74e70f258d2861b84825b35dcfd Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Tue, 18 Feb 2025 11:11:43 +0000 Subject: [PATCH 14/15] feat: Change signature of _handleCallback to take only bytes calldata The selector and executor are decoded inside this function now. For Uniswap V3 I had to manually slice the msg.data from uniswapV3SwapCallback to get the data that matters for the callback Took 3 hours 12 minutes --- foundry/src/Dispatcher.sol | 9 ++-- foundry/src/TychoRouter.sol | 31 ++++------- foundry/src/executors/UniswapV3Executor.sol | 52 +++++++++---------- .../test/executors/UniswapV3Executor.t.sol | 13 +++-- 4 files changed, 47 insertions(+), 58 deletions(-) diff --git a/foundry/src/Dispatcher.sol b/foundry/src/Dispatcher.sol index d23321c..03292be 100644 --- a/foundry/src/Dispatcher.sol +++ b/foundry/src/Dispatcher.sol @@ -82,11 +82,10 @@ contract Dispatcher { calculatedAmount = abi.decode(result, (uint256)); } - function _handleCallback( - bytes4 selector, - address executor, - bytes memory data - ) internal { + function _handleCallback(bytes calldata data) internal { + bytes4 selector = bytes4(data[data.length - 4:]); + address executor = address(uint160(bytes20(data[data.length - 24:]))); + if (!executors[executor]) { revert Dispatcher__UnapprovedExecutor(); } diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 49b9094..60a9560 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -218,12 +218,7 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { * @dev We use the fallback function to allow flexibility on callback. */ fallback() external { - address executor = - address(uint160(bytes20(msg.data[msg.data.length - 20:]))); - bytes4 selector = - bytes4(msg.data[msg.data.length - 24:msg.data.length - 20]); - bytes memory protocolData = msg.data[:msg.data.length - 24]; - _handleCallback(selector, executor, protocolData); + _handleCallback(msg.data); } /** @@ -365,19 +360,17 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { * See in IUniswapV3SwapCallback for documentation. */ function uniswapV3SwapCallback( - int256 amount0Delta, - int256 amount1Delta, + int256, /* amount0Delta */ + int256, /* amount1Delta */ bytes calldata data ) external { if (data.length < 24) revert TychoRouter__InvalidDataLength(); - bytes4 selector = bytes4(data[data.length - 4:]); - address executor = address(uint160(bytes20(data[data.length - 24:]))); - bytes memory protocolData = data[:data.length - 24]; - _handleCallback( - selector, - executor, - abi.encodePacked(amount0Delta, amount1Delta, protocolData) - ); + uint256 dataOffset = 4 + 32 + 32 + 32; // Skip selector + 2 ints + data_offset + uint256 dataLength = + uint256(bytes32(msg.data[dataOffset:dataOffset + 32])); + + bytes calldata fullData = msg.data[4:dataOffset + 32 + dataLength]; + _handleCallback(fullData); } /** @@ -388,11 +381,7 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { returns (bytes memory) { if (data.length < 24) revert TychoRouter__InvalidDataLength(); - bytes4 selector = bytes4(data[data.length - 4:]); - address executor = - address(uint160(bytes20(data[data.length - 24:data.length - 4]))); - bytes memory protocolData = data[:data.length - 24]; - _handleCallback(selector, executor, protocolData); + _handleCallback(data); return ""; } } diff --git a/foundry/src/executors/UniswapV3Executor.sol b/foundry/src/executors/UniswapV3Executor.sol index 4472eef..d1719fe 100644 --- a/foundry/src/executors/UniswapV3Executor.sol +++ b/foundry/src/executors/UniswapV3Executor.sol @@ -66,41 +66,23 @@ contract UniswapV3Executor is IExecutor, ICallback { } } - function uniswapV3SwapCallback( - int256 amount0Delta, - int256 amount1Delta, - bytes calldata data - ) external { - // slither-disable-next-line low-level-calls - (bool success, bytes memory result) = self.delegatecall( - abi.encodeWithSelector( - ICallback.handleCallback.selector, - abi.encodePacked( - amount0Delta, amount1Delta, data[:data.length - 20] - ) - ) - ); - if (!success) { - revert( - string( - result.length > 0 - ? result - : abi.encodePacked("Callback failed") - ) - ); - } - } - function handleCallback(bytes calldata msgData) - external + public returns (bytes memory result) { + // The data has the following layout: + // - amount0Delta (32 bytes) + // - amount1Delta (32 bytes) + // - dataOffset (32 bytes) + // - dataLength (32 bytes) + // - protocolData (variable length) + (int256 amount0Delta, int256 amount1Delta) = abi.decode(msgData[:64], (int256, int256)); - address tokenIn = address(bytes20(msgData[64:84])); + address tokenIn = address(bytes20(msgData[128:148])); - verifyCallback(msgData[64:]); + verifyCallback(msgData[128:]); uint256 amountOwed = amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta); @@ -118,6 +100,20 @@ contract UniswapV3Executor is IExecutor, ICallback { CallbackValidationV2.verifyCallback(factory, tokenIn, tokenOut, poolFee); } + function uniswapV3SwapCallback( + int256, /* amount0Delta */ + int256, /* amount1Delta */ + bytes calldata /* data */ + ) external { + uint256 dataOffset = 4 + 32 + 32 + 32; // Skip selector + 2 ints + data_offset + uint256 dataLength = + uint256(bytes32(msg.data[dataOffset:dataOffset + 32])); + + bytes calldata fullData = msg.data[4:dataOffset + 32 + dataLength]; + + handleCallback(fullData); + } + function _decodeData(bytes calldata data) internal pure diff --git a/foundry/test/executors/UniswapV3Executor.t.sol b/foundry/test/executors/UniswapV3Executor.t.sol index e9a9f57..86b999b 100644 --- a/foundry/test/executors/UniswapV3Executor.t.sol +++ b/foundry/test/executors/UniswapV3Executor.t.sol @@ -76,12 +76,17 @@ contract UniswapV3ExecutorTest is Test, Constants { uint256 initialPoolReserve = IERC20(WETH_ADDR).balanceOf(DAI_WETH_USV3); vm.startPrank(DAI_WETH_USV3); + bytes memory protocolData = + abi.encodePacked(WETH_ADDR, DAI_ADDR, poolFee); + uint256 dataOffset = 3; // some offset + uint256 dataLength = protocolData.length; + bytes memory callbackData = abi.encodePacked( int256(amountOwed), // amount0Delta int256(0), // amount1Delta - WETH_ADDR, - DAI_ADDR, - poolFee + dataOffset, + dataLength, + protocolData ); uniswapV3Exposed.handleCallback(callbackData); vm.stopPrank(); @@ -90,7 +95,7 @@ contract UniswapV3ExecutorTest is Test, Constants { assertEq(finalPoolReserve - initialPoolReserve, amountOwed); } - function testSwapWETHForDAI() public { + function testSwapIntegration() public { uint256 amountIn = 10 ** 18; deal(WETH_ADDR, address(uniswapV3Exposed), amountIn); From c940d8b5366f463116b64dc24ddde56e87decace Mon Sep 17 00:00:00 2001 From: Diana Carvalho Date: Tue, 18 Feb 2025 14:59:26 +0000 Subject: [PATCH 15/15] docs(univ3): Add comment explaining msg.data Took 55 minutes --- foundry/src/TychoRouter.sol | 2 ++ 1 file changed, 2 insertions(+) diff --git a/foundry/src/TychoRouter.sol b/foundry/src/TychoRouter.sol index 60a9560..9e16b61 100644 --- a/foundry/src/TychoRouter.sol +++ b/foundry/src/TychoRouter.sol @@ -365,6 +365,8 @@ contract TychoRouter is AccessControl, Dispatcher, Pausable, ReentrancyGuard { bytes calldata data ) external { if (data.length < 24) revert TychoRouter__InvalidDataLength(); + // We are taking advantage of the fact that the data we need is already encoded in the correct format inside msg.data + // This way we preserve the bytes calldata (and don't need to convert it to bytes memory) uint256 dataOffset = 4 + 32 + 32 + 32; // Skip selector + 2 ints + data_offset uint256 dataLength = uint256(bytes32(msg.data[dataOffset:dataOffset + 32]));