// SPDX-License-Identifier: MIT pragma solidity 0.8.26; import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol"; import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol"; import {PoolKey} from "v4-core/types/PoolKey.sol"; import {Currency} from "v4-core/types/Currency.sol"; import {BalanceDelta} from "v4-core/types/BalanceDelta.sol"; import {SwapParams} from "v4-core/types/PoolOperation.sol"; /// @title FirmquoteRouter /// @notice A plain single-pool v4 router: unlock, swap, pay the input, take the output. It knows nothing about /// Firmquote; any v4 router does the same job. contract FirmquoteRouter is IUnlockCallback { error NotPoolManager(); error Expired(); error Slippage(); error TransferFailed(); uint160 internal constant MIN_SQRT = 4295128739; uint160 internal constant MAX_SQRT = 1461446703485210103287273052203988822378723970342; IPoolManager public immutable poolManager; constructor(IPoolManager pm) { poolManager = pm; } struct Job { PoolKey key; bool zeroForOne; int256 amountSpecified; // < 0 exact in, > 0 exact out (v4 sign) uint256 limit; // min out (exact in) or max in (exact out) address payer; address to; } /// @return amountIn paid by the caller, amountOut sent to `to` function swap(PoolKey calldata key, bool zeroForOne, int256 amountSpecified, uint256 limit, address to, uint256 deadline) external payable returns (uint256 amountIn, uint256 amountOut) { if (block.timestamp > deadline) revert Expired(); (amountIn, amountOut) = abi.decode( poolManager.unlock(abi.encode(Job(key, zeroForOne, amountSpecified, limit, msg.sender, to))), (uint256, uint256) ); if (address(this).balance > 0) _send(msg.sender, address(this).balance); // native left over } function unlockCallback(bytes calldata data) external returns (bytes memory) { if (msg.sender != address(poolManager)) revert NotPoolManager(); Job memory j = abi.decode(data, (Job)); BalanceDelta d = poolManager.swap( j.key, SwapParams(j.zeroForOne, j.amountSpecified, j.zeroForOne ? MIN_SQRT + 1 : MAX_SQRT - 1), "" ); (int128 a0, int128 a1) = (d.amount0(), d.amount1()); (Currency cIn, Currency cOut) = j.zeroForOne ? (j.key.currency0, j.key.currency1) : (j.key.currency1, j.key.currency0); uint256 inAmt = uint256(int256(-(j.zeroForOne ? a0 : a1))); uint256 outAmt = uint256(int256(j.zeroForOne ? a1 : a0)); if (j.amountSpecified < 0 ? outAmt < j.limit : inAmt > j.limit) revert Slippage(); poolManager.sync(cIn); if (cIn.isAddressZero()) { poolManager.settle{value: inAmt}(); } else { (bool ok, bytes memory r) = Currency.unwrap(cIn).call(abi.encodeWithSelector(0x23b872dd, j.payer, address(poolManager), inAmt)); if (!ok || (r.length != 0 && !abi.decode(r, (bool)))) revert TransferFailed(); poolManager.settle(); } poolManager.take(cOut, j.to, outAmt); return abi.encode(inAmt, outAmt); } function _send(address to, uint256 v) internal { (bool ok,) = to.call{value: v}(""); if (!ok) revert TransferFailed(); } receive() external payable {} }