FlashLiquidatorUnified

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/strategy/liquidation/FlashLiquidatorUnified.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { Currency } from "@uniswap/v4-core/src/types/Currency.sol";

import { AFlashLoan } from "../../flashloan/AFlashLoan.sol";
import { ISwapper } from "../../swaps/uniswap/ISwapper.sol";

// --- Minimal interfaces ---
interface IPriceOracleGetterLike {
    function getAssetPrice(address asset) external view returns (uint256);
}

interface IPoolAddressesProviderLike {
    function getPriceOracle() external view returns (address);
    function getPoolDataProvider() external view returns (address);
}

interface IProtocolDataProviderLike {
    function getReserveTokensAddresses(
        address asset
    ) external view returns (
        address aTokenAddress,
        address stableDebtTokenAddress,
        address variableDebtTokenAddress
    );
    function getUserReserveData(
        address asset,
        address user
    ) external view returns (
        uint256 currentATokenBalance,
        uint256 currentStableDebt,
        uint256 currentVariableDebt,
        uint256 principalStableDebt,
        uint256 scaledVariableDebt,
        uint256 stableBorrowRate,
        uint256 liquidityRate,
        uint40 stableRateLastUpdated,
        bool usageAsCollateralEnabled
    );

    function getReserveConfigurationData(address asset) external view returns (
        uint256 decimals,
        uint256 ltv,
        uint256 liquidationThreshold,
        uint256 liquidationBonus,
        uint256 reserveFactor,
        bool usageAsCollateralEnabled,
        bool borrowingEnabled,
        bool isStableBorrowRateEnabled,
        bool isPaused
    );

    function getLiquidationProtocolFee(address asset) external view returns (uint256);
}

/// @notice Uniswap V2 Router interface for exactOutput swaps
interface IUniswapV2Router02 {
    /// @notice Swap tokens for an exact amount of output tokens
    /// @param amountOut The exact amount of output tokens to receive
    /// @param amountInMax The maximum amount of input tokens to spend
    /// @param path Array of token addresses representing the swap path
    /// @param to Recipient address
    /// @param deadline Unix timestamp after which the transaction will revert
    /// @return amounts Array of input/output amounts for each pair in the path
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

/// @notice Uniswap V3 SwapRouter interface for encoded path swaps
interface ISwapRouter {
    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swap with encoded path (supports multi-hop)
    /// @param params The parameters necessary for the swap
    /// @return amountIn The amount of input token actually used
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

/// @title FlashLiquidatorUnified
/// @notice Unified liquidator supporting Uniswap V2, V3, and V4 protocols
/// @dev Routes are passed as calldata - no on-chain route storage
contract FlashLiquidatorUnified is AFlashLoan, ReentrancyGuard {
    using SafeERC20 for IERC20;

    /// @notice Supported Uniswap protocol versions
    enum Protocol {
        V2,  // Uniswap V2 with address[] paths
        V3,  // Uniswap V3 with encoded paths
        V4   // Uniswap V4 with PoolKey structures
    }

    /// @notice Route data for a specific protocol
    struct SwapRoute {
        Protocol protocol;  // Which Uniswap version to use
        bytes data;         // Protocol-specific encoded route data
    }

    /// @dev Uniswap V2 Router for simple token swaps
    IUniswapV2Router02 public immutable SWAP_ROUTER_V2;

    /// @dev Uniswap V3 SwapRouter for multi-hop swaps
    ISwapRouter public immutable SWAP_ROUTER_V3;

    /// @dev Uniswap V4 Swapper for PoolKey-based swaps
    ISwapper public immutable SWAPPER_V4;

    /// @dev Config values (modifiable by owner)
    uint16 public defaultCloseFactorBps = 5000; // 50% when HF ∈ [threshold, 1)
    uint16 public maxCloseFactorBps = 10_000;   // 100% when HF < threshold
    uint256 public closeFactorHfThresholdWad = 950_000_000_000_000_000; // 0.95e18
    uint16 public flashFeeBps = 10;      // conservative est. for profitability calc
    uint16 public slippageBps = 50; // 0.50% conservative haircut
    mapping(address => uint16) public liquidationBonusBps; // optional override per collateral
    address public DATA_PROVIDER;
    
    /// @dev New security parameters
    uint256 public swapDeadline = 120; // 2 minutes default for swap deadline
    uint256 public maxFlashFeeBps = 50; // 0.5% maximum acceptable flash loan fee

    /// @dev Temporary job slot used across the flash-loan callback
    struct Job {
        address user;               // Account to liquidate
        address collateralToken;    // Collateral to seize
        address debtToken;          // Debt asset to repay (and flash-borrow)
        uint256 repayAmount;        // Amount of debt to cover
        SwapRoute route;            // Route for swapping collateral -> debt
    }

    Job private _job;
    bool private _inFlash;
    uint256 private _minProfit = 0; // Default: no minimum profit requirement

    event LiquidationPlanned(address indexed user, address indexed collateral, address indexed debt, uint256 repayAmount, Protocol protocol);
    event LiquidationExecuted(address indexed user, uint256 collateralSeized, uint256 debtRepaid, uint256 premiumPaid, uint256 collateralLeftover);
    event LiquidationSwap(address indexed collateral, address indexed debt, Protocol protocol, uint256 exactOut, uint256 amountInUsed, uint256 seized, uint256 netLeftover);
    event EmergencyWithdrawal(address indexed token, address indexed to, uint256 amount);
    event MinProfitUpdated(uint256 oldValue, uint256 newValue);
    event SlippageBpsUpdated(uint16 oldValue, uint16 newValue);
    event SwapDeadlineUpdated(uint256 oldValue, uint256 newValue);
    event MaxFlashFeeBpsUpdated(uint256 oldValue, uint256 newValue);

    constructor(
        address _addressesProvider,
        address _swapRouterV2,
        address _swapRouterV3,
        address _swapperV4
    ) AFlashLoan(_addressesProvider) {
        require(_swapRouterV2 != address(0), "swapRouterV2=0");
        require(_swapRouterV3 != address(0), "swapRouterV3=0");
        require(_swapperV4 != address(0), "swapperV4=0");
        SWAP_ROUTER_V2 = IUniswapV2Router02(_swapRouterV2);
        SWAP_ROUTER_V3 = ISwapRouter(_swapRouterV3);
        SWAPPER_V4 = ISwapper(_swapperV4);
    }

    /// @notice Initiates a flash-loan powered liquidation on `user`
    /// @param user Account to liquidate
    /// @param collateralToken Collateral asset to seize
    /// @param debtToken Debt asset to repay
    /// @param repayAmount Amount of debt to cover (≤ close factor)
    /// @param route Swap route with protocol and encoded data
    function liquidate(
        address user,
        address collateralToken,
        address debtToken,
        uint256 repayAmount,
        SwapRoute calldata route
    ) public onlyOwner nonReentrant {
        require(user != address(0) && collateralToken != address(0) && debtToken != address(0), "zero address");
        require(repayAmount > 0, "zero repay amount");
        require(route.data.length > 0, "empty route data");
        
        // Validate user is liquidatable (health factor < 1)
        if (DATA_PROVIDER != address(0)) {
            (, uint256 totalDebt,,,, uint256 healthFactor) = 
                POOL.getUserAccountData(user);
            require(healthFactor < 1e18, "user not liquidatable");
            require(totalDebt > 0, "no debt to liquidate");
        }
        
        // Validate route based on protocol
        if (collateralToken != debtToken) {
            _validateRoute(collateralToken, debtToken, route);
        }

        _job = Job({
            user: user,
            collateralToken: collateralToken,
            debtToken: debtToken,
            repayAmount: repayAmount,
            route: route
        });

        emit LiquidationPlanned(user, collateralToken, debtToken, repayAmount, route.protocol);

        _inFlash = true;
        // Borrow the debt asset to perform the liquidation
        requestFlashLoan(debtToken, repayAmount);
        _inFlash = false;

        // Clear job to avoid stale reuse
        delete _job;
    }

    /// @inheritdoc AFlashLoan
    function executeStrategy(
        address asset,
        uint256 amount,
        uint256 premium,
        address /*initiator*/,
        bytes calldata /*params*/
    ) internal override returns (uint256) {
        require(_inFlash, "not in flash");
        Job memory j = _job;
        require(asset == j.debtToken, "flash!=debt");
        require(amount == j.repayAmount, "amt mismatch");
        
        // Validate flash loan fee is within acceptable range
        uint256 actualFeeBps = (premium * 10_000) / amount;
        require(actualFeeBps <= maxFlashFeeBps, "flash fee too high");

        // 1) Approve Pool to pull debt for liquidation
        IERC20(asset).forceApprove(address(POOL), amount);

        // 2) Liquidate target account; receive underlying collateral (not aTokens)
        uint256 collBefore = IERC20(j.collateralToken).balanceOf(address(this));
        POOL.liquidationCall(j.collateralToken, j.debtToken, j.user, amount, false);
        uint256 collAfter = IERC20(j.collateralToken).balanceOf(address(this));
        require(collAfter >= collBefore, "collateral balance decreased");
        uint256 seized = collAfter - collBefore;
        require(seized > 0, "no collateral seized");

        uint256 exactOut = amount + premium;
        require(exactOut <= type(uint128).max, "amount too big");
        require(seized <= type(uint128).max, "seized too big");

        uint256 amountInUsed;
        uint256 netLeftover;
        
        if (j.collateralToken == j.debtToken) {
            // Same-asset case: no swap needed
            require(seized >= exactOut, "seized<repay");
            netLeftover = seized - exactOut;
            require(netLeftover >= _minProfit, "insufficient profit same-asset");
            amountInUsed = exactOut;
        } else {
            // Execute swap based on protocol
            uint256 maxAmountIn = seized;
            
            // Apply slippage protection
            if (slippageBps > 0) {
                // Calculate minimum expected proceeds after slippage
                uint256 minProfit = (seized * uint256(slippageBps)) / 10_000;
                
                // Seized collateral must cover: debt repayment + flash fee + min profit
                uint256 minRequired = exactOut + minProfit;
                require(seized > minRequired, "insufficient collateral for profitable liquidation");
                
                // Max amount we can spend on swap (reserve minProfit as safety buffer)
                maxAmountIn = seized - minProfit;
            }
            
            require(maxAmountIn >= exactOut, "max collateral < debt owed");
            require(maxAmountIn <= type(uint128).max, "maxAmountIn overflow");
            
            // Route to appropriate swap handler
            amountInUsed = _executeSwap(
                j.collateralToken,
                j.debtToken,
                exactOut,
                maxAmountIn,
                j.route
            );
            
            netLeftover = seized > amountInUsed ? (seized - amountInUsed) : 0;
            emit LiquidationSwap(j.collateralToken, j.debtToken, j.route.protocol, exactOut, amountInUsed, seized, netLeftover);
        }

        _requireMinProfit(netLeftover);
        emit LiquidationExecuted(j.user, seized, amount, premium, netLeftover);
        return amount + premium;
    }

    // --- Protocol-specific swap handlers ---

    /// @notice Execute swap based on protocol
    /// @param tokenIn Collateral token (input)
    /// @param tokenOut Debt token (output)
    /// @param amountOut Exact amount of debt token needed
    /// @param maxAmountIn Maximum collateral to spend
    /// @param route Swap route with protocol and data
    /// @return amountIn Actual amount of collateral used
    function _executeSwap(
        address tokenIn,
        address tokenOut,
        uint256 amountOut,
        uint256 maxAmountIn,
        SwapRoute memory route
    ) internal returns (uint256 amountIn) {
        // Record balance before swap for verification
        uint256 debtBalanceBefore = IERC20(tokenOut).balanceOf(address(this));
        
        if (route.protocol == Protocol.V2) {
            amountIn = _swapV2(tokenIn, amountOut, maxAmountIn, route.data);
        } else if (route.protocol == Protocol.V3) {
            amountIn = _swapV3(tokenIn, amountOut, maxAmountIn, route.data);
        } else if (route.protocol == Protocol.V4) {
            amountIn = _swapV4(tokenIn, tokenOut, amountOut, maxAmountIn, route.data);
        } else {
            revert("Invalid protocol");
        }
        
        // Verify we actually received the expected debt tokens
        uint256 debtBalanceAfter = IERC20(tokenOut).balanceOf(address(this));
        uint256 received = debtBalanceAfter - debtBalanceBefore;
        require(received >= amountOut, "swap output mismatch");
    }

    /// @notice Execute V2 swap using address array path
    /// @param tokenIn Collateral token (input)
    /// @param amountOut Exact amount of debt token needed (output)
    /// @param maxAmountIn Maximum collateral to spend
    /// @param encodedPath ABI-encoded address[] path (collateral -> debt)
    /// @return amountIn Actual amount of collateral used
    function _swapV2(
        address tokenIn,
        uint256 amountOut,
        uint256 maxAmountIn,
        bytes memory encodedPath
    ) internal returns (uint256 amountIn) {
        // Decode the address array
        address[] memory path = abi.decode(encodedPath, (address[]));
        
        // Validate path
        require(path.length >= 2, "V2: path too short");
        require(path[0] == tokenIn, "V2: path start mismatch");
        
        // Approve V2 router to spend collateral
        _ensureMaxApproval(IERC20(tokenIn), address(SWAP_ROUTER_V2));
        
        // Execute V2 swapTokensForExactTokens
        // Swap UP TO maxAmountIn of tokenIn to get EXACTLY amountOut of tokenOut
        uint256[] memory amounts = SWAP_ROUTER_V2.swapTokensForExactTokens(
            amountOut,           // amountOut: exact amount we need
            maxAmountIn,         // amountInMax: maximum we're willing to spend
            path,                // path: [tokenIn, ..., tokenOut]
            address(this),       // to: this contract receives the tokens
            block.timestamp + swapDeadline // deadline: configurable
        );
        
        // amounts[0] is the actual amount of tokenIn used
        amountIn = amounts[0];
        
        // Verify we didn't exceed max (should be guaranteed by router)
        require(amountIn <= maxAmountIn, "V2: excessive input amount");
    }

    /// @notice Execute V3 swap using encoded path
    /// @param tokenIn Collateral token
    /// @param amountOut Exact amount of debt token needed
    /// @param maxAmountIn Maximum collateral to spend
    /// @param encodedPath V3 encoded path (debt -> collateral for exactOutput)
    /// @return amountIn Actual amount of collateral used
    function _swapV3(
        address tokenIn,
        uint256 amountOut,
        uint256 maxAmountIn,
        bytes memory encodedPath
    ) internal returns (uint256 amountIn) {
        // Approve V3 router to spend collateral
        _ensureMaxApproval(IERC20(tokenIn), address(SWAP_ROUTER_V3));
        
        // Execute V3 exactOutput swap
        amountIn = SWAP_ROUTER_V3.exactOutput(
            ISwapRouter.ExactOutputParams({
                path: encodedPath,
                recipient: address(this),
                deadline: block.timestamp + swapDeadline,  // configurable deadline
                amountOut: amountOut,
                amountInMaximum: maxAmountIn
            })
        );
    }

    /// @notice Execute V4 swap using PoolKey
    /// @param tokenIn Collateral token
    /// @param tokenOut Debt token
    /// @param amountOut Exact amount of debt token needed
    /// @param maxAmountIn Maximum collateral to spend
    /// @param poolKeyData Encoded PoolKey and direction flag
    /// @return amountIn Actual amount of collateral used
    function _swapV4(
        address tokenIn,
        address tokenOut,
        uint256 amountOut,
        uint256 maxAmountIn,
        bytes memory poolKeyData
    ) internal returns (uint256 amountIn) {
        // Decode PoolKey and direction flag
        (PoolKey memory key, bool collateralIsToken0) = abi.decode(poolKeyData, (PoolKey, bool));
        
        // Validate PoolKey matches tokens
        address t0 = Currency.unwrap(key.currency0);
        address t1 = Currency.unwrap(key.currency1);
        require(
            (tokenIn == t0 && tokenOut == t1) || (tokenIn == t1 && tokenOut == t0),
            "V4: key tokens mismatch"
        );
        require(collateralIsToken0 == (tokenIn == t0), "V4: direction mismatch");
        
        // Validate no overflow on uint128 cast
        require(amountOut <= type(uint128).max, "V4: amountOut overflow");
        require(maxAmountIn <= type(uint128).max, "V4: maxAmountIn overflow");
        
        // Approve V4 swapper to spend collateral
        _ensureMaxApproval(IERC20(tokenIn), address(SWAPPER_V4));
        
        // Execute V4 exactOutput swap
        amountIn = SWAPPER_V4.swapExactOutputSingle(
            key,
            uint128(amountOut),
            uint128(maxAmountIn),
            collateralIsToken0,
            false,  // zeroForOne is derived from collateralIsToken0
            block.timestamp + swapDeadline,  // configurable deadline
            address(this)
        );
    }

    // --- Route validation ---

    /// @notice Validate route data matches collateral/debt pair
    /// @param collateralToken Expected collateral token
    /// @param debtToken Expected debt token
    /// @param route Swap route to validate
    function _validateRoute(
        address collateralToken,
        address debtToken,
        SwapRoute calldata route
    ) internal pure {
        if (route.protocol == Protocol.V2) {
            _validateV2Path(collateralToken, debtToken, route.data);
        } else if (route.protocol == Protocol.V3) {
            _validateV3Path(collateralToken, debtToken, route.data);
        } else if (route.protocol == Protocol.V4) {
            _validateV4PoolKey(collateralToken, debtToken, route.data);
        }
    }

    /// @notice Validate V2 path
    /// @dev For exactOutput, path goes: collateral (input) -> debt (output)
    /// @param collateralToken Expected collateral token (path start)
    /// @param debtToken Expected debt token (path end)
    /// @param encodedPath ABI-encoded address[] path
    function _validateV2Path(
        address collateralToken,
        address debtToken,
        bytes calldata encodedPath
    ) internal pure {
        address[] memory path = abi.decode(encodedPath, (address[]));
        require(path.length >= 2, "V2: path too short");
        
        // Path starts with collateral token (what we spend)
        require(path[0] == collateralToken, "V2: path doesn't start with collateral token");
        
        // Path ends with debt token (what we receive)
        require(path[path.length - 1] == debtToken, "V2: path doesn't end with debt token");
    }

    /// @notice Validate V3 encoded path
    /// @dev For exactOutput, path is reversed: debt (output) -> collateral (input)
    /// @param collateralToken Expected collateral token (path end)
    /// @param debtToken Expected debt token (path start)
    /// @param path Encoded V3 path
    function _validateV3Path(
        address collateralToken,
        address debtToken,
        bytes calldata path
    ) internal pure {
        require(path.length >= 43, "V3: path too short"); // Minimum: 20 + 3 + 20 bytes
        
        // Path starts with debt token (what we need to receive)
        address pathStart = address(uint160(bytes20(path[0:20])));
        require(pathStart == debtToken, "V3: path doesn't start with debt token");
        
        // Path ends with collateral token (what we spend)
        address pathEnd = address(uint160(bytes20(path[path.length - 20:])));
        require(pathEnd == collateralToken, "V3: path doesn't end with collateral token");
    }

    /// @notice Validate V4 PoolKey
    /// @param collateralToken Expected collateral token
    /// @param debtToken Expected debt token
    /// @param poolKeyData Encoded PoolKey and direction flag
    function _validateV4PoolKey(
        address collateralToken,
        address debtToken,
        bytes calldata poolKeyData
    ) internal pure {
        (PoolKey memory key, bool collateralIsToken0) = abi.decode(poolKeyData, (PoolKey, bool));
        
        address t0 = Currency.unwrap(key.currency0);
        address t1 = Currency.unwrap(key.currency1);
        
        // Validate pool key tokens are non-zero
        require(t0 != address(0) && t1 != address(0), "V4: zero pool token");
        
        // Validate tokens match the pool key
        require(
            (collateralToken == t0 && debtToken == t1) || (collateralToken == t1 && debtToken == t0),
            "V4: key tokens mismatch"
        );
        
        // Validate direction flag matches actual token positions
        require(collateralIsToken0 == (collateralToken == t0), "V4: direction mismatch");
        
        // Validate token ordering in pool key (Uniswap v4 requires token0 < token1)
        require(t0 < t1, "V4: invalid pool key ordering");
    }

    // --- Internal helpers ---

    function _ensureMaxApproval(IERC20 token, address spender) internal {
        if (token.allowance(address(this), spender) < type(uint256).max) {
            token.forceApprove(spender, type(uint256).max);
        }
    }

    function _requireMinProfit(uint256 leftover) internal view {
        require(leftover >= _minProfit, "profit below minimum threshold");
    }

    // --- Config management ---

    function setMinProfit(uint256 minProfit) external onlyOwner {
        uint256 oldValue = _minProfit;
        _minProfit = minProfit;
        emit MinProfitUpdated(oldValue, minProfit);
    }

    function setDataProvider(address dataProvider) external onlyOwner { 
        require(dataProvider != address(0), "zero address"); 
        DATA_PROVIDER = dataProvider; 
    }
    
    function setDefaultCloseFactorBps(uint16 bps) external onlyOwner { 
        require(bps <= 10_000, "invalid bps"); 
        defaultCloseFactorBps = bps; 
    }
    
    function setMaxCloseFactorBps(uint16 bps) external onlyOwner { 
        require(bps <= 10_000, "invalid bps"); 
        maxCloseFactorBps = bps; 
    }
    
    function setCloseFactorHfThresholdWad(uint256 wad) external onlyOwner { 
        require(wad <= 1e20, "invalid threshold"); 
        closeFactorHfThresholdWad = wad; 
    }
    
    function setCloseFactorBps(uint16 bps) external onlyOwner { 
        require(bps <= 10_000, "invalid bps"); 
        defaultCloseFactorBps = bps; 
    }
    
    function setSlippageBps(uint16 bps) external onlyOwner { 
        require(bps <= 1_000, "invalid slippage"); 
        uint16 oldValue = slippageBps;
        slippageBps = bps;
        emit SlippageBpsUpdated(oldValue, bps);
    }
    
    function setSwapDeadline(uint256 _seconds) external onlyOwner {
        require(_seconds >= 60 && _seconds <= 600, "deadline out of range");
        uint256 oldValue = swapDeadline;
        swapDeadline = _seconds;
        emit SwapDeadlineUpdated(oldValue, _seconds);
    }
    
    function setMaxFlashFeeBps(uint256 bps) external onlyOwner {
        require(bps <= 100, "max fee too high");
        uint256 oldValue = maxFlashFeeBps;
        maxFlashFeeBps = bps;
        emit MaxFlashFeeBpsUpdated(oldValue, bps);
    }
    
    /// @notice Emergency withdrawal for owner (only when not in flash loan)
    /// @dev Use with extreme caution - only for recovering stuck funds
    function emergencyWithdraw(
        address token,
        address to,
        uint256 amount
    ) external onlyOwner {
        require(!_inFlash, "cannot withdraw during flash loan");
        require(to != address(0), "zero address");
        IERC20(token).safeTransfer(to, amount);
        emit EmergencyWithdrawal(token, to, amount);
    }
    
    function setFlashFeeBps(uint16 bps) external onlyOwner { 
        require(bps <= 1000, "invalid flash fee"); 
        flashFeeBps = bps; 
    }
    
    function setLiquidationBonusBps(address collateral, uint16 bps) external onlyOwner { 
        require(bps >= 10_000, "bonus below 100%"); 
        liquidationBonusBps[collateral] = bps; 
    }

    function resetApproval(address token, address spender) external onlyOwner {
        IERC20(token).forceApprove(spender, 0);
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

import {StorageSlot} from "./StorageSlot.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}
"
    },
    "lib/v4-core/src/types/PoolKey.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}
"
    },
    "lib/v4-core/src/types/Currency.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}
"
    },
    "contracts/flashloan/AFlashLoan.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@protocol-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
import "@protocol-v3/contracts/interfaces/IPoolAddressesProvider.sol";
import "../ownership/MultiOwnable.sol";

/**
 * @title FlashLoan
 * @author antonis@typesystem.xyz
 * @notice This contract is a simple example of how to receive a flash loan from Aave V3.
 * It is not meant to be used in production without extensive testing and security audits.
 * This version uses MultiOwnable to support multiple owners.
 */
abstract contract AFlashLoan is FlashLoanSimpleReceiverBase, MultiOwnable {
    using SafeERC20 for IERC20;

    error OnlyPool();
    error InvalidInitiator();
    event FlashLoanReceived(address indexed asset, uint256 amount, uint256 premium);
    event FlashLoanRepaid(address indexed asset, uint256 amountOwed);
    error EtherTransferFailed();

    /**
     * @dev The constructor sets the owner of the contract and the Aave Pool Addresses Provider.
     * @param _addressProvider The address of the Aave V3 PoolAddressesProvider contract.
     * This can be found in the Aave developer documentation for the specific network.
     */
    constructor(address _addressProvider)
        FlashLoanSimpleReceiverBase(IPoolAddressesProvider(_addressProvider))
    {}

    /**
     * @dev This is the function that is called by the Aave Pool to execute the flash loan.
     * @param asset The address of the asset being flash loaned.
     * @param amount The amount of the asset being flash loaned.
     * @param premium The fee required to be paid for the flash loan.
     * @param initiator The address that initiated the flash loan.
     * @param params Additional data passed to the flash loan.
     * @return A boolean indicating if the flash loan was successful.
     */    
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 premium,
        address initiator,
        bytes calldata params
    ) external override returns (bool) {
        // Ensure this is Aave Pool calling
        if (msg.sender != address(POOL)) revert OnlyPool();
        // Ensure we only honor loans we initiated ourselves
        if (initiator != address(this)) revert InvalidInitiator();
        emit FlashLoanReceived(asset, amount, premium);

        // Calculate the total amount to be repaid (loaned amount + premium)
        uint256 amountOwed = executeStrategy(asset, amount, premium, initiator, params);

        // Expect this contract to be pre-funded to cover amount + premium.

        // Approve the Aave Pool to pull the funds from this contract to repay the loan
        IERC20(asset).forceApprove(address(POOL), amountOwed);

        emit FlashLoanRepaid(asset, amountOwed);

        return true;
    }

    /**
     * @dev This function is meant to be implemented by child contracts.
     * @param asset The address of the asset being flash loaned.
     * @param amount The amount of the asset being flash loaned.
     * @param premium The fee required to be paid for the flash loan.
     * @param initiator The address that initiated the flash loan.
     * @param params Additional data passed to the flash loan.
     * @return A uint256 of the amount owed.
     */
    function executeStrategy(address asset, uint256 amount, uint256 premium, address initiator, bytes calldata params) internal virtual returns (uint256);


    /**
     * @dev Initiates a flash loan.
     * @param _token The address of the ERC20 token to be loaned.
     * @param _amount The amount of the token to be loaned.
     */
    function requestFlashLoan(address _token, uint256 _amount) internal onlyOwner {
        // No external payer; params left empty.
        bytes memory params = "";
        POOL.flashLoanSimple(address(this), _token, _amount, params, 0);
    }

    /**
     * @dev Allows the owner to withdraw any profits (in the form of the specified ERC20 token)
     * from this contract.
     * @param _tokenAddress The address of the ERC20 token to withdraw.
     */
    function withdraw(address _tokenAddress) external onlyOwner {
        address to = owners[0];
        IERC20 token = IERC20(_tokenAddress);
        token.safeTransfer(to, token.balanceOf(address(this)));
    }

    /**
     * @dev Allows the owner to withdraw any ETH profits from this contract.
     */
    function withdrawEth() external onlyOwner {
        address payable to = payable(owners[0]);
        (bool ok, ) = to.call{value: address(this).balance}("");
        if (!ok) revert EtherTransferFailed();
    }

    /**
     * @dev Receive function to accept ETH.
     */
    receive() external payable {}
}
"
    },
    "contracts/swaps/uniswap/ISwapper.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol";
import { ISignatureTransfer } from "@uniswap/permit2/src/interfaces/ISignatureTransfer.sol";

/// @title ISwapper
/// @notice Interface mirroring all public/external methods exposed by UniswapV4Swapper
interface ISwapper {
    /// @notice Approve Permit2 to pull `token` from this contract, and allow Universal Router via Permit2
    function approveTokenWithPermit2(address token, uint160 amount, uint48 expiration) external;

    /// @notice Swap exact input for >= min output (single v4 pool)
    function swapExactInputSingle(
        PoolKey memory key,
        uint128 amountIn,
        uint128 minAmountOut,
        bool zeroForOne,
        uint256 deadline,
        address recipient
    ) external returns (uint256 amountOut);

    /// @notice Swap up to `amountInMaximum` to receive exactly `amountOut` (single v4 pool)
    function swapExactOutputSingle(
        PoolKey memory key,
        uint128 amountOut,
        uint128 amountInMaximum,
        bool zeroForOne,
        bool unwrapOutput,
        uint256 deadline,
        address recipient
    ) external returns (uint256 amountIn);

    /// @notice Simplified overload: swap exact input by providing tokens and pool params
    function swapExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        int24 tickSpacing,
        address hooks,
        uint128 amountIn,
        uint128 minAmountOut,
        uint256 deadline,
        address recipient
    ) external returns (uint256 amountOut);

    /// @notice Simplified overload: swap exact output by providing tokens and pool params
    function swapExactOutputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        int24 tickSpacing,
        address hooks,
        uint128 amountOut,
        uint128 amountInMaximum,
        uint256 deadline,
        address recipient
    ) external returns (uint256 amountIn);

    /// @notice Swap exact input ETH for >= min output (wraps to WETH internally)
    function swapExactInputSingleETH(
        PoolKey memory key,
        uint128 minAmountOut,
        bool zeroForOne,
        uint256 deadline,
        address recipient
    ) external payable returns (uint256 amountOut);

    /// @notice Swap up to `amountInMaximum` ETH to receive exactly `amountOut` (wraps to WETH internally)
    function swapExactOutputSingleETH(
        PoolKey memory key,
        uint128 amountOut,
        uint128 amountInMaximum,
        bool zeroForOne,
        uint256 deadline,
        address recipient,
        bool unwrap
    ) external payable returns (uint256 amountIn);

    /// @notice Swap exact input using Permit2 for token transfer
    function swapExactInputSingleWithPermit2(
        PoolKey memory key,
        uint128 amountIn,
        uint128 minAmountOut,
        bool zeroForOne,
        uint256 deadline,
        address recipient,
        ISignatureTransfer.PermitTransferFrom calldata permit,
        bytes calldata signature
    ) external returns (uint256 amountOut);

    /// @notice Swap exact output using Permit2 for token transfer
    function swapExactOutputSingleWithPermit2(
        PoolKey memory key,
        uint128 amountOut,
        uint128 amountInMaximum,
        bool zeroForOne,
        uint256 deadline,
        address recipient,
        ISignatureTransfer.PermitTransferFrom calldata permit,
        bytes calldata signature
    ) external returns (uint256 amountIn);
}"
    },
    "lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transfer

Tags:
ERC20, ERC165, Multisig, Swap, Liquidity, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xf0340be19ad720ce811199a80d06885955b011d9|verified:true|block:23636185|tx:0x30d0b26b04c4b18a96f048dbc808fa2253161765d44395b8ac727090c27d692d|first_check:1761297359

Submitted on: 2025-10-24 11:16:02

Comments

Log in to comment.

No comments yet.