Skip to content
Verified contractExactMIT

AcrossSwapAdapter

Address0xa4a7ae1eaeca66bd904149d6728472cabbe06ab8
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.19

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.19+commit.7dd6d404
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,371,743
Creation transaction
0x0be173b4b7…4fc8ca4c1e

contracts/bridges/adapters/AcrossSwapAdapter.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SwapStep } from "contracts/dex/SwapTypes.sol";

import { BridgeAdapterBase } from "./BridgeAdapterBase.sol";
import { BridgeSwapReceiver } from "contracts/bridges/BridgeSwapReceiver.sol";
import { SwapRouter } from "contracts/SwapRouter.sol";
import {
    IAcrossMessageHandler
} from "contracts/bridges/interfaces/IAcrossMessageHandler.sol";

/// @notice Across fills must complete the swap: a graceful token fallback
/// lets eth_estimateGas converge on a successful but underfunded delivery.
/// SpokePool propagates handler reverts, leaving the fill retryable instead.
contract AcrossSwapAdapter is BridgeAdapterBase, IAcrossMessageHandler {
    BridgeSwapReceiver public immutable receiver;

    constructor(
        address receiver_,
        address admin_,
        address guardian_
    ) BridgeAdapterBase(admin_, guardian_) {
        receiver = BridgeSwapReceiver(payable(receiver_));
    }

    function handleV3AcrossMessage(
        address tokenSent,
        uint256 amount,
        address, // relayer
        bytes memory message
    ) external override {
        _onlyWhitelistedEndpoint();
        // Payload format extended with a trailing `uint256 swapDeadline`.
        // Source-side encoders MUST set this; `type(uint256).max` opts out.
        (
            address recipient,
            SwapStep[] memory swapSteps,
            uint256 minAmountOut,
            uint256 nativeGasDrop,
            uint256 swapDeadline
        ) = abi.decode(
            message, (address, SwapStep[], uint256, uint256, uint256)
        );
        uint256 forwarded =
            _forwardAvailable(tokenSent, address(receiver), amount);
        receiver.executeSwapStrict(
            tokenSent,
            forwarded,
            recipient,
            swapSteps,
            minAmountOut,
            nativeGasDrop,
            swapDeadline
        );
    }
}

contracts/SwapRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { IRouterAllowlist } from "contracts/interfaces/IRouterAllowlist.sol";
import {
    IUniswapV3Factory
} from "contracts/interfaces/external/uniswap/IUniswapV3Factory.sol";
import {
    IAlgebraFactory
} from "contracts/interfaces/external/algebra/IAlgebraFactory.sol";
import {
    IUniswapV3Pool,
    IUniswapV3PoolImmutables
} from "contracts/interfaces/external/uniswap/IUniswapV3Pool.sol";
import {
    ISlipstreamFactory
} from "contracts/interfaces/external/aerodrome/ISlipstreamFactory.sol";
import { IDexAdapter } from "contracts/dex/IDexAdapter.sol";
import { DexType, SwapStep } from "contracts/dex/SwapTypes.sol";

/// @title SwapRouter
/// @notice A router that executes multi-hop swaps across different DEXs
/// @dev Called via AggregatorConnector like Paraswap/Odos. Each
/// `DexType` is handled by a hot-swappable adapter registered via
/// `setDexAdapter`. SwapRouter owns custody of tokens and ETH; adapters
/// orchestrate via `adapterApprove` / `adapterCall` / `adapterPull`
/// while marked as `_activeAdapter`.
contract SwapRouter {
    // ══════════════════════════════════════════════════════════════════════════════
    // CONSTANTS
    // ══════════════════════════════════════════════════════════════════════════════

    /// @notice Maximum fee in basis points (1%)
    uint256 public constant MAX_FEE_BPS = 100;

    /// @notice Basis points denominator
    uint256 public constant BPS_DENOMINATOR = 10_000;

    // ══════════════════════════════════════════════════════════════════════════════
    // IMMUTABLES
    // ══════════════════════════════════════════════════════════════════════════════

    /// @notice Router allowlist for security
    IRouterAllowlist public immutable allowlist;

    /// @notice Wrapped native token address (WETH/WAVAX/etc.)
    address public immutable wrappedNative;

    // ══════════════════════════════════════════════════════════════════════════════
    // STORAGE
    // ══════════════════════════════════════════════════════════════════════════════

    /// @notice Admin address for configuration
    address public admin;

    /// @notice Optional guardian authorised to clear adapter slots in an
    /// emergency. Gives the protocol a faster, lower-trust kill switch on a
    /// faulty / compromised adapter without waiting on the slower admin key.
    /// Guardian cannot register or replace adapters; only `address(0)` it.
    /// Defaults to unset.
    address public guardian;

    /// @notice Fee in basis points (default 1 bp = 0.01%)
    uint256 public feeBps = 1;

    /// @notice Per-`DexType` adapter address. `_executeStep` dispatches
    /// every swap through the registered adapter; an unset slot reverts
    /// with `AdapterNotSet`.
    /// @dev Keyed by `uint8` (not `DexType`) so future enum entries can
    /// be appended without breaking the public ABI on already-deployed
    /// instances.
    mapping(uint8 dexType => address adapter) public dexAdapter;

    /// @notice Adapter currently authorised to call `adapterApprove` /
    /// `adapterCall` / `adapterPull`. Set immediately before
    /// `IDexAdapter.swap` and cleared after it returns. Regular storage
    /// (not TSTORE/TLOAD) because not every chain in the deployment
    /// matrix is confirmed Cancun-capable; explicit clear gives the
    /// same single-call-scoping guarantee at a small gas cost.
    address private _activeAdapter;

    /// Bind direct V3 / Algebra pool callbacks to an in-flight swap.
    /// Direct-pool adapters call
    /// `adapterArmPoolCallback(pool, tokenIn, maxAmountIn)` immediately
    /// before invoking `pool.swap` via `adapterCall`. The pool callback
    /// then requires `msg.sender == _armedCallbackPool`, the token being
    /// paid to match `_armedCallbackToken`, and the requested payment to
    /// be `<= _armedCallbackMax`. Without arming, the callback refuses
    /// to pay regardless of whether `msg.sender` is a factory-derived
    /// pool, so unrelated callers cannot drain residual balances by
    /// directly invoking a valid pool with `payer = SwapRouter`.
    /// Cleared together with `_activeAdapter` in `_dispatchAdapter`.
    address private _armedCallbackPool;
    address private _armedCallbackToken;
    uint256 private _armedCallbackMax;

    /// @notice Fee recipient, changeable by the router admin through governance.
    address public feeCollector;

    // ══════════════════════════════════════════════════════════════════════════════
    // ERRORS
    // ══════════════════════════════════════════════════════════════════════════════

    error AdapterNotSet(uint8 dexType);
    error AdapterNotContract();
    error NotAdapter();
    error SwapFailed(bytes error);
    error InsufficientOutputAmount(uint256 received, uint256 minRequired);
    error InvalidStepsLength();
    error InvalidSplitLength();
    error InvalidEthInput();
    error Expired();
    error NotAdmin();
    error InvalidAddress();
    error FeeTooHigh();
    error InvalidPool();
    error InvalidTokenIn();
    error InvalidTokenPath();
    error FeeOnTransferNotSupported();
    error UnarmedPoolCallback();
    error CallbackTokenMismatch();
    error CallbackAmountExceedsArmed();
    error ResidualInputConsumed();
    error ResidualOutputBalanceMismatch();
    error NotGuardianOrAdmin();

    // ══════════════════════════════════════════════════════════════════════════════
    // EVENTS
    // ══════════════════════════════════════════════════════════════════════════════

    event MultiSwap(
        address indexed sender,
        address indexed tokenIn,
        address indexed tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        uint256 amountOut,
        uint256 feeAmount
    );

    event Sweep(address indexed token, uint256 amount);

    event FeeUpdated(uint256 oldFeeBps, uint256 newFeeBps);

    event FeeCollectorUpdated(
        address indexed oldCollector, address indexed newCollector
    );


    event AdminUpdated(address oldAdmin, address newAdmin);

    event GuardianUpdated(address oldGuardian, address newGuardian);

    event DexAdapterSet(
        uint8 indexed dexType, address oldAdapter, address newAdapter
    );

    // ══════════════════════════════════════════════════════════════════════════════
    // STRUCTS
    // ══════════════════════════════════════════════════════════════════════════════
    //
    // `DexType` and `SwapStep` are declared at file scope in
    // `contracts/dex/SwapTypes.sol` so per-DEX adapters can reference them
    // without depending on this concrete `SwapRouter` implementation.

    // ══════════════════════════════════════════════════════════════════════════════
    // CONSTRUCTOR
    // ══════════════════════════════════════════════════════════════════════════════

    /// @param allowlist_ Router allowlist contract
    /// @param admin_ Admin address for configuration
    /// @param feeCollector_ Address to receive fees
    constructor(
        address allowlist_,
        address admin_,
        address feeCollector_,
        address wrappedNative_
    ) {
        if (allowlist_ == address(0)) revert InvalidAddress();
        if (admin_ == address(0)) revert InvalidAddress();
        if (feeCollector_ == address(0)) revert InvalidAddress();
        if (wrappedNative_ == address(0)) revert InvalidAddress();
        allowlist = IRouterAllowlist(allowlist_);
        admin = admin_;
        feeCollector = feeCollector_;
        wrappedNative = wrappedNative_;
    }

    // ══════════════════════════════════════════════════════════════════════════════
    // EXTERNAL FUNCTIONS
    // ══════════════════════════════════════════════════════════════════════════════

    /// @notice Execute a multi-step swap
    /// @param steps Array of swap steps to execute
    /// @param amountIn Amount of input token
    /// @param minAmountOut Minimum output amount
    /// @param recipient Address to receive output tokens
    /// @param deadline Transaction deadline
    /// @return amountOut Actual output amount
    function swap(
        SwapStep[] calldata steps,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external payable returns (uint256 amountOut) {
        (amountOut,) = _swap(steps, amountIn, minAmountOut, recipient, deadline);
    }

    /// @notice Execute a multi-step swap and return both output and fee.
    /// @dev Used by `BridgeRouter` for exact bridge telemetry without inferring
    /// fees from fee-collector balance changes.
    function swapWithFee(
        SwapStep[] calldata steps,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external payable returns (uint256 amountOut, uint256 fee) {
        return _swap(steps, amountIn, minAmountOut, recipient, deadline);
    }

    function _swap(
        SwapStep[] calldata steps,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) internal returns (uint256 amountOut, uint256 fee) {
        if (block.timestamp > deadline) revert Expired();
        if (steps.length == 0) revert InvalidStepsLength();

        // Snapshot the tokenIn balance before pulling so we can verify the
        // swap loop fully consumed (or refunded) what we pulled. Without
        // this, an adapter such as Velodrome's UniversalRouter `SWEEP` can
        // leave residual tokenIn in the router for an unrelated caller to
        // drain.
        address tokenIn0 = steps[0].tokenIn;
        uint256 tokenInBalanceBefore = tokenIn0 == address(0)
            ? 0
            : IERC20(tokenIn0).balanceOf(address(this));

        // Execute all steps — use actual received amount (may differ for FOT
        // tokens)
        uint256 currentAmount = _pullInput(tokenIn0, amountIn);
        for (uint256 i; i < steps.length; i++) {
            if (i > 0 && steps[i].tokenIn != steps[i - 1].tokenOut) {
                revert InvalidTokenPath();
            }
            currentAmount = _executeStep(steps[i], currentAmount);
        }

        // Apply fee and transfer output
        address tokenOut = steps[steps.length - 1].tokenOut;
        (amountOut, fee) = _applyFeeAndTransfer(
            tokenOut, currentAmount, minAmountOut, recipient
        );

        // Balance the input ledger.
        // Any tokenIn residue left by the swap loop is refunded to the
        // recipient; any consumption of pre-existing residue (post < pre)
        // is treated as a draining attempt and reverts.
        _settleTokenInResidual(tokenIn0, recipient, tokenInBalanceBefore);

        emit MultiSwap(
            msg.sender,
            tokenIn0,
            tokenOut,
            amountIn,
            minAmountOut,
            amountOut,
            fee
        );
    }

    function _settleTokenInResidual(
        address tokenIn,
        address recipient,
        uint256 balanceBefore
    ) internal {
        if (tokenIn == address(0)) return;
        // The anti-drain check runs for every route, including the
        // tokenIn == tokenOut case: a cyclic route (A->B->A) whose adapter
        // over-pays tokenIn must not be able to drain the router's
        // pre-existing same-token balance. In an honest same-token swap the
        // output has already been sent by `_applyFeeAndTransfer`, so
        // `residual == 0` and the refund below is a no-op — only a genuine
        // drain trips `ResidualInputConsumed`.
        uint256 balanceAfter = IERC20(tokenIn).balanceOf(address(this));
        if (balanceAfter < balanceBefore) revert ResidualInputConsumed();
        uint256 residual = balanceAfter - balanceBefore;
        if (residual > 0) {
            SafeTransferLib.safeTransfer(tokenIn, recipient, residual);
        }
    }

    /// @notice Execute a split swap across multiple parallel routes
    /// @dev All routes must have the same input token and output token
    /// @param routes Array of routes, each route is an array of swap steps
    /// @param amounts Amount of input token for each route
    /// @param minAmountOut Minimum total output amount
    /// @param recipient Address to receive output tokens
    /// @param deadline Transaction deadline
    /// @return amountOut Total output amount after fees
    function swapSplit(
        SwapStep[][] calldata routes,
        uint256[] calldata amounts,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external payable returns (uint256 amountOut) {
        if (block.timestamp > deadline) revert Expired();
        if (routes.length == 0 || routes.length != amounts.length) {
            revert InvalidSplitLength();
        }
        // Validate before indexing `routes[0]`. Without this guard, a caller
        // passing an empty first route triggers a Solidity array OOB panic
        // instead of the intended `InvalidStepsLength` revert.
        if (routes[0].length == 0) revert InvalidStepsLength();

        // All routes must have same input and output token
        address tokenIn = routes[0][0].tokenIn;
        address tokenOut = routes[0][routes[0].length - 1].tokenOut;

        // Calculate total input and validate routes
        uint256 totalAmountIn =
            _validateAndSumAmounts(routes, amounts, tokenIn, tokenOut);

        // See `_swap` — same snapshot pattern, mirrored for the split path.
        uint256 tokenInBalanceBefore = tokenIn == address(0)
            ? 0
            : IERC20(tokenIn).balanceOf(address(this));

        uint256 actualReceived = _pullInput(tokenIn, totalAmountIn);
        if (actualReceived != totalAmountIn) {
            revert FeeOnTransferNotSupported();
        }

        // Execute all routes and sum outputs
        uint256 totalOutput = _executeRoutes(routes, amounts);

        // Apply fee and transfer
        uint256 fee;
        (amountOut, fee) = _applyFeeAndTransfer(
            tokenOut, totalOutput, minAmountOut, recipient
        );

        _settleTokenInResidual(tokenIn, recipient, tokenInBalanceBefore);

        emit MultiSwap(
            msg.sender,
            tokenIn,
            tokenOut,
            totalAmountIn,
            minAmountOut,
            amountOut,
            fee
        );
    }

    function _validateAndSumAmounts(
        SwapStep[][] calldata routes,
        uint256[] calldata amounts,
        address tokenIn,
        address tokenOut
    ) internal pure returns (uint256 total) {
        if (routes[0].length == 0) revert InvalidStepsLength();
        total = amounts[0];
        for (uint256 i = 1; i < amounts.length; i++) {
            total += amounts[i];
            if (routes[i].length == 0) revert InvalidStepsLength();
            if (routes[i][0].tokenIn != tokenIn) revert InvalidStepsLength();
            if (routes[i][routes[i].length - 1].tokenOut != tokenOut) {
                revert InvalidStepsLength();
            }
        }
    }

    function _executeRoutes(
        SwapStep[][] calldata routes,
        uint256[] calldata amounts
    ) internal returns (uint256 totalOutput) {
        for (uint256 r; r < routes.length; r++) {
            totalOutput += _executeSingleRoute(routes[r], amounts[r]);
        }
    }

    function _executeSingleRoute(
        SwapStep[] calldata steps,
        uint256 amountIn
    ) internal returns (uint256 currentAmount) {
        currentAmount = amountIn;
        for (uint256 s; s < steps.length; s++) {
            if (s > 0 && steps[s].tokenIn != steps[s - 1].tokenOut) {
                revert InvalidTokenPath();
            }
            currentAmount = _executeStep(steps[s], currentAmount);
        }
    }

    function _applyFeeAndTransfer(
        address tokenOut,
        uint256 totalOutput,
        uint256 minAmountOut,
        address recipient
    ) internal returns (uint256 amountAfterFee, uint256 fee) {
        fee = (totalOutput * feeBps) / BPS_DENOMINATOR;
        amountAfterFee = totalOutput - fee;

        if (amountAfterFee < minAmountOut) {
            revert InsufficientOutputAmount(amountAfterFee, minAmountOut);
        }

        if (tokenOut == address(0)) {
            if (fee > 0) {
                SafeTransferLib.safeTransferETH(feeCollector, fee);
            }
            SafeTransferLib.safeTransferETH(recipient, amountAfterFee);
        } else {
            // Send the guaranteed user amount first, then collect whatever
            // output remains above the router's pre-swap balance. Rebasing /
            // scaled-balance tokens such as Aave aTokens can round each
            // nominal transfer to a different scaled amount. Sending the
            // formula fee first can therefore leave one nominal unit less
            // than `amountAfterFee` and make the user transfer revert.
            // Re-reading the residual after the user transfer preserves the
            // guaranteed output and confines the rounding adjustment to the
            // fee (normally by one smallest unit).
            uint256 balanceWithoutOutput =
                IERC20(tokenOut).balanceOf(address(this)) - totalOutput;
            SafeTransferLib.safeTransfer(tokenOut, recipient, amountAfterFee);
            uint256 balanceAfterRecipient =
                IERC20(tokenOut).balanceOf(address(this));
            if (balanceAfterRecipient >= balanceWithoutOutput) {
                fee = balanceAfterRecipient - balanceWithoutOutput;
            } else {
                // Scaled-balance conversion can debit one displayed unit more
                // than the nominal recipient transfer. Tolerate only that
                // single-unit rounding drift; a larger shortfall is a real
                // residual-balance mismatch.
                if (balanceWithoutOutput - balanceAfterRecipient > 1) {
                    revert ResidualOutputBalanceMismatch();
                }
                fee = 0;
            }

            if (fee > 0) {
                SafeTransferLib.safeTransfer(tokenOut, feeCollector, fee);
            }
            // Do not require exact post-fee equality with
            // `balanceWithoutOutput`: aTokens convert the nominal fee to a
            // scaled amount and can leave the displayed router balance one
            // unit either side of that derived baseline. Both checks tolerate
            // exactly that rounding unit and no more.
        }
    }

    /// @notice Sweep stuck ERC20 tokens to fee collector
    /// @param token Token to sweep
    function sweep(
        address token
    ) external {
        if (msg.sender != admin) revert NotAdmin();
        uint256 balance = IERC20(token).balanceOf(address(this));
        if (balance > 0) {
            SafeTransferLib.safeTransfer(token, feeCollector, balance);
            emit Sweep(token, balance);
        }
    }

    /// @notice Sweep stuck ETH to fee collector
    function sweepETH() external {
        if (msg.sender != admin) revert NotAdmin();
        uint256 balance = address(this).balance;
        if (balance > 0) {
            SafeTransferLib.safeTransferETH(feeCollector, balance);
            emit Sweep(address(0), balance);
        }
    }

    /// @notice Set a new admin
    /// @param newAdmin Address of the new admin
    function setAdmin(
        address newAdmin
    ) external {
        if (msg.sender != admin) revert NotAdmin();
        if (newAdmin == address(0)) revert InvalidAddress();
        emit AdminUpdated(admin, newAdmin);
        admin = newAdmin;
    }

    /// @notice Set the swap fee
    /// @param newFeeBps New fee in basis points
    function setFee(
        uint256 newFeeBps
    ) external {
        if (msg.sender != admin) revert NotAdmin();
        if (newFeeBps > MAX_FEE_BPS) revert FeeTooHigh();
        uint256 oldFeeBps = feeBps;
        feeBps = newFeeBps;
        emit FeeUpdated(oldFeeBps, newFeeBps);
    }

    /// @notice Change the recipient of swap fees and admin sweeps.
    /// @custom:access Restricted to the router admin.
    function setFeeCollector(
        address newCollector
    ) external {
        if (msg.sender != admin) revert NotAdmin();
        if (newCollector == address(0)) revert InvalidAddress();
        address oldCollector = feeCollector;
        if (oldCollector == newCollector) return;
        feeCollector = newCollector;
        emit FeeCollectorUpdated(oldCollector, newCollector);
    }

    /// @notice Register or replace the adapter handling `dexType`.
    /// Setting `adapter` to `address(0)` clears the slot, causing
    /// subsequent swaps for that `DexType` to revert with
    /// `AdapterNotSet`. Non-zero `adapter` must be a contract; this
    /// mirrors the EOA-rejection that `RouterAllowlist.setRouter`
    /// already does for external routers.
    function setDexAdapter(uint8 dexType, address adapter) external {
        if (msg.sender != admin) revert NotAdmin();
        if (adapter != address(0) && adapter.code.length == 0) {
            revert AdapterNotContract();
        }
        address oldAdapter = dexAdapter[dexType];
        if (oldAdapter == adapter) return;
        dexAdapter[dexType] = adapter;
        emit DexAdapterSet(dexType, oldAdapter, adapter);
    }

    /// @notice Clear the adapter for `dexType`. After this call any
    /// swap step with that type reverts with `AdapterNotSet`.
    /// @dev Callable by the guardian as well as the admin. Re-registering an
    /// adapter still requires `setDexAdapter` and the admin key.
    function emergencyDisableAdapter(uint8 dexType) external {
        if (msg.sender != admin && msg.sender != guardian) {
            revert NotGuardianOrAdmin();
        }
        address oldAdapter = dexAdapter[dexType];
        if (oldAdapter == address(0)) return;
        dexAdapter[dexType] = address(0);
        emit DexAdapterSet(dexType, oldAdapter, address(0));
    }

    /// @notice Rotate the optional emergency guardian. Admin-only.
    function setGuardian(
        address newGuardian
    ) external {
        if (msg.sender != admin) revert NotAdmin();
        if (newGuardian == guardian) return;
        emit GuardianUpdated(guardian, newGuardian);
        guardian = newGuardian;
    }

    /// @notice Set an ERC20 approval from this contract to `spender` on
    /// behalf of the active adapter. Used by router-style adapters so
    /// the eventual `transferFrom` lifts tokens directly from
    /// `SwapRouter`, keeping the single-FOT-hit accounting (a re-pull
    /// into an adapter would tax the transfer twice).
    function adapterApprove(
        address token,
        address spender,
        uint256 amount
    ) external {
        if (msg.sender != _activeAdapter) revert NotAdapter();
        SafeTransferLib.safeApprove(token, spender, 0);
        if (amount > 0) {
            SafeTransferLib.safeApprove(token, spender, amount);
        }
    }

    /// @notice Execute an external call from this contract on behalf of
    /// the active adapter. Bubbles raw revert data so typed errors
    /// (e.g. `InvalidPool()` from `uniswapV3SwapCallback`) reach
    /// consumers unchanged.
    function adapterCall(
        address target,
        uint256 value,
        bytes calldata data
    ) external returns (bytes memory) {
        if (msg.sender != _activeAdapter) revert NotAdapter();
        (bool success, bytes memory result) =
            target.call{ value: value }(data);
        if (!success) {
            if (result.length == 0) revert SwapFailed(result);
            assembly {
                revert(add(result, 0x20), mload(result))
            }
        }
        return result;
    }

    /// @notice Transfer custody of `amount` of `token` from this
    /// contract to `to`. Adapters use this for the pre-deposit-style
    /// router pattern (Velodrome UniversalRouter with
    /// `payerIsUser = false`) and inside pool callbacks (where MSR
    /// itself is the payer but the active adapter scheduled the swap).
    function adapterPull(
        address token,
        uint256 amount,
        address to
    ) external {
        if (msg.sender != _activeAdapter) revert NotAdapter();
        SafeTransferLib.safeTransfer(token, to, amount);
    }

    /// @notice Arm the V3 / Algebra pool callback for the next pool call
    /// in the current dispatch.
    /// Only the active adapter may call this. The armed slot persists
    /// until the next call to this function or until `_dispatchAdapter`
    /// clears it at the end of `IDexAdapter.swap`, so each call sets the
    /// expectations for the next direct pool callback.
    function adapterArmPoolCallback(
        address pool,
        address tokenToPay,
        uint256 maxAmountToPay
    ) external {
        if (msg.sender != _activeAdapter) revert NotAdapter();
        _armedCallbackPool = pool;
        _armedCallbackToken = tokenToPay;
        _armedCallbackMax = maxAmountToPay;
    }

    // ══════════════════════════════════════════════════════════════════════════════
    // INTERNAL FUNCTIONS
    // ══════════════════════════════════════════════════════════════════════════════

    function _pullInput(
        address tokenIn,
        uint256 amountIn
    ) internal returns (uint256) {
        if (msg.value > 0) {
            if (amountIn != msg.value) revert InvalidEthInput();
            if (tokenIn != address(0)) revert InvalidEthInput();
            return amountIn;
        } else {
            if (tokenIn == address(0)) revert InvalidEthInput();
            uint256 balanceBefore = IERC20(tokenIn).balanceOf(address(this));
            SafeTransferLib.safeTransferFrom(
                tokenIn, msg.sender, address(this), amountIn
            );
            return IERC20(tokenIn).balanceOf(address(this)) - balanceBefore;
        }
    }

    function _executeStep(
        SwapStep calldata step,
        uint256 amountIn
    ) internal returns (uint256) {
        // Router allowlist check (all except direct pool swaps and wrap/unwrap)
        if (
            step.dexType != uint8(DexType.UniswapV3Pool)
                && step.dexType != uint8(DexType.AlgebraPool)
                && step.dexType != uint8(DexType.WrapWETH)
                && step.dexType != uint8(DexType.UnwrapWETH)
        ) {
            allowlist.requireAllowed(step.router);
        }

        // All swap types except WrapWETH, UnwrapWETH, and UniswapV4 require
        // ERC20 tokenIn (not native ETH)
        if (
            step.dexType != uint8(DexType.WrapWETH)
                && step.dexType != uint8(DexType.UnwrapWETH)
                && step.dexType != uint8(DexType.UniswapV4)
                && step.dexType != uint8(DexType.PancakeInfinity)
        ) {
            if (step.tokenIn == address(0)) revert InvalidAddress();
        }

        address adapter = dexAdapter[step.dexType];
        if (adapter == address(0)) revert AdapterNotSet(step.dexType);
        return _dispatchAdapter(adapter, step, amountIn);
    }

    /// @dev Dispatch the step through a registered DEX adapter. Sets
    /// the active-adapter slot so the adapter can call back into
    /// `adapterApprove` / `adapterCall` / `adapterPull` for the
    /// duration of one swap, measures the `tokenOut` balance delta as
    /// the authoritative output amount, then clears the slot.
    function _dispatchAdapter(
        address adapter,
        SwapStep calldata step,
        uint256 amountIn
    ) internal returns (uint256) {
        uint256 balanceBefore = _balanceOf(step.tokenOut);
        _activeAdapter = adapter;
        IDexAdapter(adapter).swap(step, amountIn);
        _activeAdapter = address(0);
        // Backstop clear of any callback arming the adapter set. The pool
        // callback disarms on use (`_consumeArmedPoolCallback`), so this only
        // fires when an adapter armed but its pool never called back; the
        // guard skips the 0-over-0 writes on router-style and already-
        // disarmed swaps.
        if (_armedCallbackPool != address(0)) {
            _armedCallbackPool = address(0);
            _armedCallbackToken = address(0);
            _armedCallbackMax = 0;
        }
        return _balanceDelta(step.tokenOut, balanceBefore);
    }

    function _balanceOf(
        address token
    ) internal view returns (uint256) {
        if (token == address(0)) {
            return address(this).balance;
        }
        return IERC20(token).balanceOf(address(this));
    }

    function _balanceDelta(
        address token,
        uint256 balanceBefore
    ) internal view returns (uint256) {
        return _balanceOf(token) - balanceBefore;
    }

    // ══════════════════════════════════════════════════════════════════════════════
    // POOL CALLBACK HELPERS
    //
    // Direct-pool adapters (`UniswapV3PoolAdapter`, `AlgebraPoolAdapter`)
    // invoke `pool.swap(...)` via `adapterCall`, so `SwapRouter` is the
    // caller and the pool dispatches its payment callback here. The
    // callback re-validates that `msg.sender` is a pool produced by an
    // allow-listed factory (independent of the adapter's pre-call
    // check) and then pays the requested amount from this contract's
    // balance.
    // ══════════════════════════════════════════════════════════════════════════════

    function _readFeeAndTickSpacing(
        address pool
    ) internal view returns (uint24 fee, int24 tickSpacing) {
        (bool ok, bytes memory data) = pool.staticcall(
            abi.encodeWithSelector(IUniswapV3PoolImmutables.fee.selector)
        );
        if (ok && data.length >= 32) {
            fee = abi.decode(data, (uint24));
        }

        (ok, data) = pool.staticcall(
            abi.encodeWithSelector(
                IUniswapV3PoolImmutables.tickSpacing.selector
            )
        );
        if (ok && data.length >= 32) {
            tickSpacing = abi.decode(data, (int24));
        }
    }

    function _isPoolFromFactory(
        address factory,
        address token0,
        address token1,
        uint24 fee,
        int24 tickSpacing,
        address pool
    ) internal view returns (bool) {
        (bool ok, address expected) =
            _tryGetV3Pool(factory, token0, token1, fee);
        if (ok && expected == pool) return true;

        (ok, expected) =
            _tryGetSlipstreamPool(factory, token0, token1, tickSpacing);
        if (ok && expected == pool) return true;

        return false;
    }

    function _tryGetV3Pool(
        address factory,
        address token0,
        address token1,
        uint24 fee
    ) internal view returns (bool, address) {
        (bool success, bytes memory data) = factory.staticcall(
            abi.encodeWithSelector(
                IUniswapV3Factory.getPool.selector, token0, token1, fee
            )
        );
        if (!success || data.length < 32) {
            return (false, address(0));
        }
        return (true, abi.decode(data, (address)));
    }

    function _tryGetSlipstreamPool(
        address factory,
        address token0,
        address token1,
        int24 tickSpacing
    ) internal view returns (bool, address) {
        (bool success, bytes memory data) = factory.staticcall(
            abi.encodeWithSelector(
                ISlipstreamFactory.getPool.selector, token0, token1, tickSpacing
            )
        );
        if (!success || data.length < 32) {
            return (false, address(0));
        }
        return (true, abi.decode(data, (address)));
    }

    function _validateAlgebraPoolTokenIn(
        address pool,
        address tokenIn,
        address customDeployer
    ) internal view {
        (address token0, address token1, address factory) =
            _readAlgebraPoolTokensAndFactory(pool);

        allowlist.requireAllowedFactory(factory);
        if (!_isAlgebraPoolFromFactory(
                factory, token0, token1, pool, customDeployer
            )) {
            revert InvalidPool();
        }

        if (tokenIn != token0 && tokenIn != token1) {
            revert InvalidTokenIn();
        }
    }

    function _readAlgebraPoolTokensAndFactory(
        address pool
    ) internal view returns (address token0, address token1, address factory) {
        IUniswapV3Pool algebraPool = IUniswapV3Pool(pool);
        token0 = algebraPool.token0();
        token1 = algebraPool.token1();
        factory = algebraPool.factory();
    }

    function _isAlgebraPoolFromFactory(
        address factory,
        address token0,
        address token1,
        address pool,
        address customDeployer
    ) internal view returns (bool) {
        (bool ok, address expected) =
            _tryGetAlgebraPoolByPair(factory, token0, token1);
        if (ok) {
            if (expected == pool) return true;
            if (expected != address(0) && customDeployer == address(0)) {
                return false;
            }
        }

        if (customDeployer != address(0)) {
            allowlist.requireAllowedCustomDeployer(factory, customDeployer);
            (ok, expected) = _tryGetAlgebraCustomPoolByPair(
                factory, customDeployer, token0, token1
            );
            if (ok && expected == pool) return true;
        }

        return false;
    }

    function _tryGetAlgebraPoolByPair(
        address factory,
        address token0,
        address token1
    ) internal view returns (bool, address) {
        (bool success, bytes memory data) = factory.staticcall(
            abi.encodeWithSelector(
                IAlgebraFactory.poolByPair.selector, token0, token1
            )
        );
        if (!success || data.length < 32) {
            return (false, address(0));
        }
        return (true, abi.decode(data, (address)));
    }

    function _tryGetAlgebraCustomPoolByPair(
        address factory,
        address deployer,
        address token0,
        address token1
    ) internal view returns (bool, address) {
        (bool success, bytes memory data) = factory.staticcall(
            abi.encodeWithSelector(
                IAlgebraFactory.customPoolByPair.selector,
                deployer,
                token0,
                token1
            )
        );
        if (!success || data.length < 32) {
            return (false, address(0));
        }
        return (true, abi.decode(data, (address)));
    }

    /// @dev Validate that the current direct-pool callback is the one the
    /// active adapter armed (matching `msg.sender`), return the armed
    /// (token, max) for the payment check, then immediately clear the
    /// arming. Disarming on first use means one arming authorizes exactly
    /// one pool payment, so a second callback from the same pool in the same
    /// dispatch (a re-entrant or multi-callback pool, or a future multi-hop
    /// adapter) reverts as unarmed instead of reusing the armed
    /// (pool, token, max). `_dispatchAdapter` still clears the slots after
    /// `swap` returns, which covers an arming whose pool never called back.
    /// The single `msg.sender != _armedCallbackPool` check also catches the
    /// unarmed state (an EVM `msg.sender` is never the zero address).
    function _consumeArmedPoolCallback()
        internal
        returns (address armedToken, uint256 armedMax)
    {
        if (msg.sender != _armedCallbackPool) revert UnarmedPoolCallback();
        armedToken = _armedCallbackToken;
        armedMax = _armedCallbackMax;
        _armedCallbackPool = address(0);
        _armedCallbackToken = address(0);
        _armedCallbackMax = 0;
    }

    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external {
        if (amount0Delta <= 0 && amount1Delta <= 0) return;

        // Refuse callbacks not arming-scoped to the current adapter
        // dispatch, and disarm on use so one arming authorizes exactly one
        // pool payment.
        (address armedToken, uint256 armedMax) = _consumeArmedPoolCallback();

        IUniswapV3Pool v3pool = IUniswapV3Pool(msg.sender);
        address token0 = v3pool.token0();
        address token1 = v3pool.token1();
        address factory = v3pool.factory();

        allowlist.requireAllowedFactory(factory);
        (uint24 fee, int24 tickSpacing) = _readFeeAndTickSpacing(msg.sender);
        if (!_isPoolFromFactory(
                factory, token0, token1, fee, tickSpacing, msg.sender
            )) {
            revert InvalidPool();
        }

        address payer = abi.decode(data, (address));
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 amountToPay =
            amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta);
        address tokenToPay = amount0Delta > 0 ? token0 : token1;

        if (payer == address(this)) {
            if (tokenToPay != armedToken) {
                revert CallbackTokenMismatch();
            }
            if (amountToPay > armedMax) {
                revert CallbackAmountExceedsArmed();
            }
            SafeTransferLib.safeTransfer(tokenToPay, msg.sender, amountToPay);
        }
    }

    /// @notice Callback for Algebra pool swaps
    /// @dev Called by the pool during swap to request token payment
    function algebraSwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external {
        // Require an active arming whose pool matches `msg.sender`, and
        // disarm on use.
        (address armedToken, uint256 armedMax) = _consumeArmedPoolCallback();

        // Decode callback data
        (address tokenIn, address payer, address customDeployer) =
            abi.decode(data, (address, address, address));
        _validateAlgebraPoolTokenIn(msg.sender, tokenIn, customDeployer);

        // Determine which token to pay (positive delta = tokens owed to pool)
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 amountToPay =
            amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta);

        // Transfer tokens to the pool
        if (payer == address(this)) {
            if (tokenIn != armedToken) {
                revert CallbackTokenMismatch();
            }
            if (amountToPay > armedMax) {
                revert CallbackAmountExceedsArmed();
            }
            SafeTransferLib.safeTransfer(tokenIn, msg.sender, amountToPay);
        }
    }

    receive() external payable { }
}

contracts/base/Admin.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/// @title Admin contract
/// @author vfat.tools
/// @notice Provides an administration mechanism allowing restricted functions
abstract contract Admin {
    /// ERRORS ///

    /// @notice Thrown when the caller is not the admin
    error NotAdminError(); //0xb5c42b3b

    /// EVENTS ///

    /// @notice Emitted when a new admin is set
    /// @param oldAdmin Address of the old admin
    /// @param newAdmin Address of the new admin
    event AdminSet(address oldAdmin, address newAdmin);

    /// STORAGE ///

    /// @notice Address of the current admin
    address public admin;

    /// MODIFIERS ///

    /// @dev Restricts a function to the admin
    modifier onlyAdmin() {
        if (msg.sender != admin) revert NotAdminError();
        _;
    }

    /// WRITE FUNCTIONS ///

    /// @param admin_ Address of the admin
    constructor(
        address admin_
    ) {
        emit AdminSet(address(0), admin_);
        admin = admin_;
    }

    /// @notice Sets a new admin
    /// @param newAdmin Address of the new admin
    /// @custom:access Restricted to protocol admin.
    function setAdmin(
        address newAdmin
    ) external onlyAdmin {
        emit AdminSet(admin, newAdmin);
        admin = newAdmin;
    }
}

contracts/base/GuardianAdmin.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { Admin } from "contracts/base/Admin.sol";

/// @title GuardianAdmin
/// @author vfat.tools
/// @notice Extends Admin with an optional guardian that can perform
/// emergency disable-only actions on inheriting bridge contracts.
abstract contract GuardianAdmin is Admin {
    /// ERRORS ///

    /// @notice Thrown when the caller is neither guardian nor admin
    error NotGuardianOrAdminError();

    /// EVENTS ///

    /// @notice Emitted when a new guardian is set
    /// @param oldGuardian Address of the old guardian
    /// @param newGuardian Address of the new guardian
    event GuardianSet(address oldGuardian, address newGuardian);

    /// STORAGE ///

    /// @notice Address of the current emergency guardian
    address public guardian;

    /// MODIFIERS ///

    /// @dev Restricts a function to the guardian or admin
    modifier onlyGuardianOrAdmin() {
        _onlyGuardianOrAdmin();
        _;
    }

    constructor(
        address admin_,
        address guardian_
    ) Admin(admin_) {
        if (guardian_ != address(0)) {
            emit GuardianSet(address(0), guardian_);
            guardian = guardian_;
        }
    }

    /// @notice Sets a new guardian
    /// @param newGuardian Address of the new guardian
    /// @custom:access Restricted to protocol admin.
    function setGuardian(
        address newGuardian
    ) external onlyAdmin {
        if (newGuardian == guardian) return;
        emit GuardianSet(guardian, newGuardian);
        guardian = newGuardian;
    }

    function _onlyGuardianOrAdmin() internal view {
        if (msg.sender != guardian && msg.sender != admin) {
            revert NotGuardianOrAdminError();
        }
    }
}

contracts/bridges/BridgeSwapReceiver.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { SwapStep } from "contracts/dex/SwapTypes.sol";

import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { GuardianAdmin } from "contracts/base/GuardianAdmin.sol";
import { SwapRouter } from "contracts/SwapRouter.sol";

interface IWETHBridgeSwapReceiver {
    function withdraw(
        uint256
    ) external;
}

/// @title BridgeSwapReceiver
/// @author vfat.tools
/// @notice Receives bridged tokens from whitelisted adapters and swaps them
/// via SwapRouter. Bridge-specific callback handling is delegated to
/// per-bridge adapter contracts (e.g. StargateSwapAdapter).
contract BridgeSwapReceiver is GuardianAdmin {
    /// ERRORS ///
    error NotWhitelistedAdapter();
    error ZeroAddress();
    error OnlySelf();
    error NativeGasDropTokenNotWrappedNative();
    error NativeGasDropExceedsAmount();
    error NativeGasDropTokenConflicts();
    error AdapterNotAContract();

    /// EVENTS ///

    event BridgeSwapExecuted(
        address indexed recipient,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOut
    );

    event BridgeSwapFallback(
        address indexed recipient, address token, uint256 amount
    );

    event WhitelistedAdapterSet(address adapter, bool whitelisted);

    /// STORAGE ///

    SwapRouter public immutable msr;

    mapping(address => bool) public whitelistedAdapters;
    address[] private _adapters;
    mapping(address => uint256) private _adapterIndexPlusOne;

    /// CONSTRUCTOR ///

    /// @param msr_ SwapRouter address
    /// @param admin_ Admin address for configuration
    constructor(
        address msr_,
        address admin_,
        address guardian_
    ) GuardianAdmin(admin_, guardian_) {
        if (msr_ == address(0)) revert ZeroAddress();
        msr = SwapRouter(payable(msr_));
    }

    /// PUBLIC VIEW ///

    /// @notice Enumerate the currently-allowed adapters.
    function adapters() external view returns (address[] memory) {
        return _adapters;
    }

    /// ADMIN FUNCTIONS ///

    /// @notice Whitelist or remove a bridge adapter
    /// @param adapter Bridge adapter address
    /// @param whitelisted Whether the adapter is whitelisted
    function setWhitelistedAdapter(
        address adapter,
        bool whitelisted
    ) external onlyAdmin {
        _setWhitelistedAdapter(adapter, whitelisted);
    }

    /// @notice Emergency-disable an adapter without waiting on governance.
    /// Re-enabling still requires the admin path.
    function emergencyDisableAdapter(
        address adapter
    ) external onlyGuardianOrAdmin {
        _setWhitelistedAdapter(adapter, false);
    }

    function _setWhitelistedAdapter(
        address adapter,
        bool whitelisted
    ) internal {
        // Same-chain adapters must be contracts.
        if (whitelisted && adapter.code.length == 0) {
            revert AdapterNotAContract();
        }
        bool currentlyAllowed = whitelistedAdapters[adapter];
        if (currentlyAllowed == whitelisted) return;

        whitelistedAdapters[adapter] = whitelisted;
        if (whitelisted) {
            _adapterIndexPlusOne[adapter] = _adapters.length + 1;
            _adapters.push(adapter);
        } else {
            uint256 indexPlusOne = _adapterIndexPlusOne[adapter];
            uint256 index = indexPlusOne - 1;
            uint256 lastIndex = _adapters.length - 1;
            if (index != lastIndex) {
                address last = _adapters[lastIndex];
                _adapters[index] = last;
                _adapterIndexPlusOne[last] = index + 1;
            }
            _adapters.pop();
            delete _adapterIndexPlusOne[adapter];
        }
        emit WhitelistedAdapterSet(adapter, whitelisted);
    }

    /// @notice Rescue tokens stuck in this contract
    function rescueTokens(
        address token,
        address to,
        uint256 amount
    ) external onlyAdmin {
        SafeTransferLib.safeTransfer(token, to, amount);
    }

    /// @notice Rescue ETH stuck in this contract
    function rescueETH(
        address to
    ) external onlyAdmin {
        SafeTransferLib.safeTransferETH(to, address(this).balance);
    }

    /// ADAPTER ENTRY POINT ///

    /// @notice Execute a swap with bridged tokens. Callable only by
    /// whitelisted adapters which have already transferred tokens here.
    /// @param nativeGasDrop Native gas to leave for `recipient` on this
    /// callback execution chain, denominated in wei. Supported only when
    /// `token` is this chain's wrapped native token.
    /// @param swapDeadline Deadline passed through to `SwapRouter.swap`.
    /// Source-chain senders MUST bound how long the destination swap can
    /// remain executable, otherwise a delayed bridge delivery can still
    /// execute a stale quote whenever `minAmountOut` is met. Pass
    /// `type(uint256).max` to opt out.
    function executeSwap(
        address token,
        uint256 amount,
        address recipient,
        SwapStep[] calldata swapSteps,
        uint256 minAmountOut,
        uint256 nativeGasDrop,
        uint256 swapDeadline
    ) external {
        _onlyWhitelistedAdapter();
        _swapOrFallback(
            token,
            amount,
            recipient,
            swapSteps,
            minAmountOut,
            nativeGasDrop,
            swapDeadline
        );
    }

    /// @notice Execute without a token fallback when the bridge reverts its
    /// delivery on handler failure. Across needs this so gas estimation can
    /// only succeed when the destination swap actually completes.
    function executeSwapStrict(
        address token,
        uint256 amount,
        address recipient,
        SwapStep[] calldata swapSteps,
        uint256 minAmountOut,
        uint256 nativeGasDrop,
        uint256 swapDeadline
    ) external {
        _onlyWhitelistedAdapter();
        (address tokenOut, uint256 swapAmount, uint256 amountOut) = this.swapExternal(
            token,
            amount,
            recipient,
            swapSteps,
            minAmountOut,
            nativeGasDrop,
            swapDeadline
        );
        emit BridgeSwapExecuted(
            recipient, token, tokenOut, swapAmount, amountOut
        );
    }

    /// @notice Execute a swap while reserving native gas from a separately
    /// bridged wrapped-native token.
    /// @param nativeGasDropToken Token delivered by the adapter for the gas
    /// drop. Must be this chain's wrapped native token and must differ from
    /// `token`; use `executeSwap(..., nativeGasDrop)` for primary-WETH drops.
    /// @param nativeGasDrop Amount of `nativeGasDropToken` to unwrap and send
    /// to `recipient`, denominated in wei.
    function executeSwapWithNativeGasDropToken(
        address token,
        uint256 amount,
        address nativeGasDropToken,
        uint256 nativeGasDrop,
        address recipient,
        SwapStep[] calldata swapSteps,
        uint256 minAmountOut,
        uint256 swapDeadline
    ) external {
        _onlyWhitelistedAdapter();
        _swapOrFallbackWithNativeGasDropToken(
            token,
            amount,
            nativeGasDropToken,
            nativeGasDrop,
            recipient,
            swapSteps,
            minAmountOut,
            swapDeadline
        );
    }

    /// INTERNAL ///

    function _onlyWhitelistedAdapter() internal view {
        if (!whitelistedAdapters[msg.sender]) {
            revert NotWhitelistedAdapter();
        }
    }

    /// @dev Approve MSR, attempt swap, fall back to direct transfer on failure
    function _swapOrFallback(
        address token,
        uint256 amount,
        address recipient,
        SwapStep[] calldata swapSteps,
        uint256 minAmountOut,
        uint256 nativeGasDrop,
        uint256 swapDeadline
    ) internal {
        try this.swapExternal(
            token,
            amount,
            recipient,
            swapSteps,
            minAmountOut,
            nativeGasDrop,
            swapDeadline
        ) returns (
            address tokenOut, uint256 swapAmount, uint256 amountOut
        ) {
            emit BridgeSwapExecuted(
                recipient, token, tokenOut, swapAmount, amountOut
            );
        } catch {
            uint256 fallbackAmount =
                _transferAvailable(token, recipient, amount);
            emit BridgeSwapFallback(recipient, token, fallbackAmount);
        }
    }

    function _swapOrFallbackWithNativeGasDropToken(
        address token,
        uint256 amount,
        address nativeGasDropToken,
        uint256 nativeGasDrop,
        address recipient,
        SwapStep[] calldata swapSteps,
        uint256 minAmountOut,
        uint256 swapDeadline
    ) internal {
        try this.swapWithNativeGasDropTokenExternal(
            token,
            amount,
            nativeGasDropToken,
            nativeGasDrop,
            recipient,
            swapSteps,
            minAmountOut,
            swapDeadline
        ) returns (
            address tokenOut, uint256 swapAmount, uint256 amountOut
        ) {
            emit BridgeSwapExecuted(
                recipient, token, tokenOut, swapAmount, amountOut
            );
        } catch {
            uint256 fallbackAmount =
                _transferAvailable(token, recipient, amount);
            if (nativeGasDrop > 0) {
                _transferAvailable(nativeGasDropToken, recipient, nativeGasDrop);
            }
            emit BridgeSwapFallback(recipient, token, fallbackAmount);
        }
    }

    function swapExternal(
        address token,
        uint256 amount,
        address recipient,
        SwapStep[] calldata swapSteps,
        uint256 minAmountOut,
        uint256 nativeGasDrop,
        uint256 swapDeadline
    )
        external
        returns (address tokenOut, uint256 swapAmount, uint256 amountOut)
    {
        if (msg.sender != address(this)) {
            revert OnlySelf();
        }

        swapAmount =
            _reserveNativeGasDrop(token, amount, recipient, nativeGasDrop);
        SafeTransferLib.safeApprove(token, address(msr), 0);
        SafeTransferLib.safeApprove(token, address(msr), swapAmount);

        // Honour the source-side deadline instead of `block.timestamp`.
        amountOut = msr.swap(
            swapSteps, swapAmount, minAmountOut, recipient, swapDeadline
        );

        SafeTransferLib.safeApprove(token, address(msr), 0);
        tokenOut = swapSteps[swapSteps.length - 1].tokenOut;
    }

    function swapWithNativeGasDropTokenExternal(
        address token,
        uint256 amount,
        address nativeGasDropToken,
        uint256 nativeGasDrop,
        address recipient,
        SwapStep[] calldata swapSteps,
        uint256 minAmountOut,
        uint256 swapDeadline
    )
        external
        returns (address tokenOut, uint256 swapAmount, uint256 amountOut)
    {
        if (msg.sender != address(this)) {
            revert OnlySelf();
        }

        _sendNativeGasDropToken(
            token, nativeGasDropToken, recipient, nativeGasDrop
        );
        swapAmount = amount;

        SafeTransferLib.safeApprove(token, address(msr), 0);
        SafeTransferLib.safeApprove(token, address(msr), swapAmount);

        amountOut = msr.swap(
            swapSteps, swapAmount, minAmountOut, recipient, swapDeadline
        );

        SafeTransferLib.safeApprove(token, address(msr), 0);
        tokenOut = swapSteps[swapSteps.length - 1].tokenOut;
    }

    function _reserveNativeGasDrop(
        address token,
        uint256 amount,
        address recipient,
        uint256 nativeGasDrop
    ) internal returns (uint256 swapAmount) {
        if (nativeGasDrop == 0) return amount;
        if (nativeGasDrop >= amount) revert NativeGasDropExceedsAmount();

        address wrappedNative = msr.wrappedNative();
        if (token != wrappedNative) {
            revert NativeGasDropTokenNotWrappedNative();
        }

        IWETHBridgeSwapReceiver(wrappedNative).withdraw(nativeGasDrop);
        SafeTransferLib.safeTransferETH(recipient, nativeGasDrop);

        return amount - nativeGasDrop;
    }

    function _sendNativeGasDropToken(
        address token,
        address nativeGasDropToken,
        address recipient,
        uint256 nativeGasDrop
    ) internal {
        if (nativeGasDrop == 0) return;

        address wrappedNative = msr.wrappedNative();
        if (nativeGasDropToken != wrappedNative) {
            revert NativeGasDropTokenNotWrappedNative();
        }
        if (nativeGasDropToken == token) {
            revert NativeGasDropTokenConflicts();
        }

        IWETHBridgeSwapReceiver(wrappedNative).withdraw(nativeGasDrop);
        SafeTransferLib.safeTransferETH(recipient, nativeGasDrop);
    }

    function _tokenBalance(
        address token,
        address account
    ) internal view returns (uint256) {
        (bool success, bytes memory data) =
            token.staticcall(abi.encodeWithSelector(0x70a08231, account));
        if (!success || data.length < 32) return 0;
        return abi.decode(data, (uint256));
    }

    function _transferAvailable(
        address token,
        address to,
        uint256 amount
    ) internal returns (uint256 sent) {
        uint256 available = _tokenBalance(token, address(this));
        sent = available < amount ? available : amount;
        if (sent > 0) {
            SafeTransferLib.safeTransfer(token, to, sent);
        }
    }

    receive() external payable { }
}

contracts/bridges/adapters/BridgeAdapterBase.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol";
import { GuardianAdmin } from "contracts/base/GuardianAdmin.sol";

/// @title BridgeAdapterBase
/// @notice Shared base for bridge adapters: endpoint whitelist + rescue.
abstract contract BridgeAdapterBase is GuardianAdmin {
    error NotWhitelistedBridgeEndpoint();
    /// Thrown when admin tries to whitelist a non-contract address as a
    /// local callback endpoint.
    error EndpointNotAContract();

    event WhitelistedBridgeEndpointSet(address endpoint, bool whitelisted);

    mapping(address => bool) public whitelistedBridgeEndpoints;
    address[] private _bridgeEndpoints;
    mapping(address => uint256) private _bridgeEndpointIndexPlusOne;

    constructor(
        address admin_,
        address guardian_
    ) GuardianAdmin(admin_, guardian_) { }

    /// @notice Enumerate the currently-allowed bridge endpoints.
    function bridgeEndpoints() external view returns (address[] memory) {
        return _bridgeEndpoints;
    }

    function setWhitelistedBridgeEndpoint(
        address endpoint,
        bool whitelisted
    ) external onlyAdmin {
        _setWhitelistedBridgeEndpoint(endpoint, whitelisted);
    }

    /// @notice Emergency-disable a bridge endpoint without waiting on
    /// governance. Re-enabling still requires the admin path.
    function emergencyDisableBridgeEndpoint(
        address endpoint
    ) external onlyGuardianOrAdmin {
        _setWhitelistedBridgeEndpoint(endpoint, false);
    }

    function _setWhitelistedBridgeEndpoint(
        address endpoint,
        bool whitelisted
    ) internal {
        // Same-chain callback endpoint must be a contract. Matches
        // RouterAllowlist.setBridge / setRouter.
        if (whitelisted && endpoint.code.length == 0) {
            revert EndpointNotAContract();
        }
        bool currentlyAllowed = whitelistedBridgeEndpoints[endpoint];
        if (currentlyAllowed == whitelisted) return;

        whitelistedBridgeEndpoints[endpoint] = whitelisted;
        if (whitelisted) {
            _bridgeEndpointIndexPlusOne[endpoint] = _bridgeEndpoints.length + 1;
            _bridgeEndpoints.push(endpoint);
        } else {
            uint256 indexPlusOne = _bridgeEndpointIndexPlusOne[endpoint];
            // currentlyAllowed == true so the index must be set
            uint256 index = indexPlusOne - 1;
            uint256 lastIndex = _bridgeEndpoints.length - 1;
            if (index != lastIndex) {
                address last = _bridgeEndpoints[lastIndex];
                _bridgeEndpoints[index] = last;
                _bridgeEndpointIndexPlusOne[last] = index + 1;
            }
            _bridgeEndpoints.pop();
            delete _bridgeEndpointIndexPlusOne[endpoint];
        }
        emit WhitelistedBridgeEndpointSet(endpoint, whitelisted);
    }

    function rescueTokens(
        address token,
        address to,
        uint256 amount
    ) external virtual onlyAdmin {
        SafeTransferLib.safeTransfer(token, to, amount);
    }

    function rescueETH(
        address to
    ) external virtual onlyAdmin {
        SafeTransferLib.safeTransferETH(to, address(this).balance);
    }

    function _onlyWhitelistedEndpoint() internal view {
        if (!whitelistedBridgeEndpoints[msg.sender]) {
            revert NotWhitelistedBridgeEndpoint();
        }
    }

    /// @dev Forward up to `amount` tokens to `to`, capped to the adapter's
    /// current balance so a bridge under-delivery does not revert the
    /// forwarding leg. The returned `sent` is the nominal amount transferred
    /// out by this contract; for fee-on-transfer or tax tokens the recipient
    /// may receive less than `sent`, which downstream callers do not measure.
    function _forwardAvailable(
        address token,
        address to,
        uint256 amount
    ) internal returns (uint256 sent) {
        uint256 available = _tokenBalance(token);
        sent = available < amount ? available : amount;
        if (sent > 0) {
            SafeTransferLib.safeTransfer(token, to, sent);
        }
    }

    function _tokenBalance(
        address token
    ) internal view returns (uint256) {
        (bool success, bytes memory data) = token.staticcall(
            abi.encodeWithSelector(0x70a08231, address(this))
        );
        if (!success || data.length < 32) return 0;
        return abi.decode(data, (uint256));
    }
}

contracts/bridges/interfaces/IAcrossMessageHandler.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/// @title IAcrossMessageHandler
/// @notice Interface for contracts that receive cross-chain messages via Across
interface IAcrossMessageHandler {
    /// @notice Called by Across SpokePool when bridged tokens arrive with a
    /// message
    /// @param tokenSent Address of the token delivered
    /// @param amount Amount of tokens delivered
    /// @param relayer Address of the relayer that filled the deposit
    /// @param message Encoded destination-chain execution params
    function handleV3AcrossMessage(
        address tokenSent,
        uint256 amount,
        address relayer,
        bytes memory message
    ) external;
}

contracts/dex/IDexAdapter.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import { SwapStep } from "contracts/dex/SwapTypes.sol";

/// @title IDexAdapter
/// @notice Interface implemented by per-DEX adapter contracts that
/// `SwapRouter` dispatches to when its `dexAdapter[dexType]` slot is set.
/// @dev Under the Option C custody model, the adapter starts with no
/// tokens and pulls them from `SwapRouter` via `adapterPull` while
/// `SwapRouter` holds it as the in-flight active adapter. Output tokens
/// land back in `SwapRouter`, which measures the balance delta to compute
/// the hop's effective output. The function is `payable` so `SwapRouter`
/// can forward native ETH custody alongside the swap when
/// `step.tokenIn == address(0)`. The interface intentionally does not
/// import the concrete `SwapRouter` contract — adapters depend on the
/// shared `SwapTypes` only.
interface IDexAdapter {
    /// @notice Adapter implementation version. Off-chain tooling
    /// (vfat-api, deploy scripts) reads this to detect which adapter
    /// build is currently wired into `SwapRouter`.
    function version() external view returns (uint16);

    /// @notice Execute a single swap step on behalf of the calling
    /// `SwapRouter`. The adapter addresses every callback and output to its
    /// caller, so any router that registers it may dispatch to it.
    /// @param step Swap step parameters (dex type, router, tokens, dex-
    /// specific data) as defined by `SwapRouter`'s public ABI.
    /// @param amountIn Amount of `step.tokenIn` available for this step.
    /// @return amountOut Amount of `step.tokenOut` the adapter believes
    /// it delivered to `SwapRouter`. Informational only — `SwapRouter`
    /// cross-checks via a balance delta.
    function swap(
        SwapStep calldata step,
        uint256 amountIn
    ) external payable returns (uint256 amountOut);
}

contracts/dex/SwapTypes.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/// @notice DEX types `SwapRouter` knows how to dispatch. This enum is a
/// set of named constants only — `SwapStep.dexType` is a raw `uint8` (not
/// this enum), so the dispatch table `dexAdapter[uint8]` carries the byte
/// directly with no enum range-check at the ABI boundary. A new *standard*
/// type (allow-listed router + ERC20 `tokenIn`) can therefore be appended
/// and dispatched on an already-deployed `SwapRouter` via `setDexAdapter`
/// alone — no redeploy. NOTE this does NOT cover a type that needs a new
/// `SwapRouter._executeStep` exemption (router-allowlist bypass or
/// native-ETH `tokenIn`); those exemption lists are hardcoded and still
/// require a `SwapRouter` redeploy. Append new entries rather than
/// reordering existing ones.
enum DexType {
    UniswapV2,
    UniswapV3Router02,
    Solidly,
    Algebra,
    UniswapV4,
    VelodromeUniversalRouter,
    UniswapV3Router,
    AerodromeRouter,
    AlgebraPool,
    SlipstreamRouter,
    BlackholeV2Router,
    UniswapV3Pool,
    WrapWETH,
    UnwrapWETH,
    CamelotV2Router,
    PancakeInfinity,
    AaveSupply,
    AaveWithdraw,
    BaselineRelay,
    FlowStateMarket,
    SolidlyPool,
    AeroMetarouter,
    UniswapV2Fot,
    BushAggregatorRouter,
    LiquidityBook,
    CurveStableNgPool,
    MorphoVaultV2Deposit,
    MorphoVaultV2Redeem,
    AeroTokenMigration
}

/// @notice One hop of a multi-step swap. Stable, ABI-stable struct used
/// by `SwapRouter`, every `IDexAdapter`, every bridge swap receiver, and
/// every off-chain encoder (vfat-api, deploy scripts).
struct SwapStep {
    /// @dev Raw `uint8` (not the `DexType` enum) so dispatch is purely
    /// `dexAdapter[dexType]` — adding a new DEX type never requires
    /// redeploying `SwapRouter`. Compare against `uint8(DexType.X)`.
    uint8 dexType;
    address router;
    address tokenIn;
    address tokenOut;
    bytes dexData;
}

contracts/interfaces/IRouterAllowlist.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

interface IRouterAllowlist {
    /// @notice Check if a router is allowed
    /// @param router The router address to check
    /// @return True if the router is allowed
    function isAllowed(address router) external view returns (bool);

    /// @notice Revert if the router is not allowed
    /// @param router The router address to check
    function requireAllowed(address router) external view;

    /// @notice Check if a factory is allowed
    /// @param factory The factory address to check
    /// @return True if the factory is allowed
    function isAllowedFactory(address factory) external view returns (bool);

    /// @notice Revert if the factory is not allowed
    /// @param factory The factory address to check
    function requireAllowedFactory(address factory) external view;

    /// @notice Check if a custom pool deployer is allowed for a factory
    /// @param factory The factory address to check
    /// @param deployer The custom pool deployer address to check
    /// @return True if the custom deployer is allowed for the factory
    function isAllowedCustomDeployer(address factory, address deployer) external view returns (bool);

    /// @notice Revert if the custom pool deployer is not allowed for a factory
    /// @param factory The factory address to check
    /// @param deployer The custom pool deployer address to check
    function requireAllowedCustomDeployer(address factory, address deployer) external view;

    /// @notice Check if a v4 hook is allowed
    /// @param hook The hook address to check
    /// @return True if the hook is allowed
    function isAllowedHook(address hook) external view returns (bool);

    /// @notice Revert if the v4 hook is not allowed
    /// @param hook The hook address to check
    function requireAllowedHook(address hook) external view;

    /// @notice Check if a bridge contract is allowed
    /// @param bridge The bridge contract address
    /// @return True if the bridge is allowed
    function isAllowedBridge(address bridge) external view returns (bool);

    /// @notice Revert if the bridge contract is not allowed
    /// @param bridge The bridge contract address
    function requireAllowedBridge(address bridge) external view;

    /// @notice Check if a function selector is allowed for a bridge contract
    /// @param bridge The bridge contract address
    /// @param selector The function selector
    /// @return True if the selector is allowed
    function isAllowedSelector(address bridge, bytes4 selector) external view returns (bool);

    /// @notice Revert if the function selector is not allowed for a bridge contract
    /// @param bridge The bridge contract address
    /// @param selector The function selector
    function requireAllowedSelector(address bridge, bytes4 selector) external view;

    /// @notice Enumerate the currently-allowed function selectors for a bridge
    /// @param bridge The bridge contract address
    /// @return selectors The set of selectors currently marked allowed for the bridge
    function bridgeSelectors(address bridge) external view returns (bytes4[] memory selectors);
}

contracts/interfaces/external/aerodrome/ISlipstreamFactory.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ISlipstreamFactory {
    function getPool(address token0, address token1, int24 tickSpacing) external view returns (address);
}

contracts/interfaces/external/algebra/IAlgebraFactory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;

enum YieldMode {
    AUTOMATIC,
    VOID,
    CLAIMABLE
}
/// @title The interface for the Algebra Factory
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces

interface IAlgebraFactory {
    /// @notice Emitted when a process of ownership renounce is started
    /// @param timestamp The timestamp of event
    /// @param finishTimestamp The timestamp when ownership renounce will be
    /// possible to finish
    event RenounceOwnershipStart(uint256 timestamp, uint256 finishTimestamp);

    /// @notice Emitted when a process of ownership renounce cancelled
    /// @param timestamp The timestamp of event
    event RenounceOwnershipStop(uint256 timestamp);

    /// @notice Emitted when a process of ownership renounce finished
    /// @param timestamp The timestamp of ownership renouncement
    event RenounceOwnershipFinish(uint256 timestamp);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param pool The address of the created pool
    event Pool(address indexed token0, address indexed token1, address pool);

    /// @notice Emitted when the default community fee is changed
    /// @param newDefaultCommunityFee The new default community fee value
    event DefaultCommunityFee(uint16 newDefaultCommunityFee);

    /// @notice Emitted when the default tickspacing is changed
    /// @param newDefaultTickspacing The new default tickspacing value
    event DefaultTickspacing(int24 newDefaultTickspacing);

    /// @notice Emitted when the default fee is changed
    /// @param newDefaultFee The new default fee value
    event DefaultFee(uint16 newDefaultFee);

    /// @notice Emitted when the defaultPluginFactory address is changed
    /// @param defaultPluginFactoryAddress The new defaultPluginFactory address
    event DefaultPluginFactory(address defaultPluginFactoryAddress);

    /// @notice Emitted when the vaultFactory address is changed
    /// @param newVaultFactory The new vaultFactory address
    event VaultFactory(address newVaultFactory);

    /// @notice Emitted when the pools creation mode is changed
    /// @param mode_ The new pools creation mode
    event PublicPoolCreationMode(bool mode_);

    /// @dev Emitted when set new default blast governor address is changed.
    /// @param defaultBlastGovernor The new default blast governor address
    event DefaultBlastGovernor(address indexed defaultBlastGovernor);

    /// @dev Emitted when set new default blast points address is changed.
    /// @param defaultBlastPoints The new default blast points address
    event DefaultBlastPoints(address indexed defaultBlastPoints);

    /// @dev Emitted when set new default blast points operator address is
    /// changed.
    /// @param defaultBlastPointsOperator The new default blast points operator
    /// address
    event DefaultBlastPointsOperator(
        address indexed defaultBlastPointsOperator
    );

    /// @notice Emitted when the rebase configuration for a token is set or
    /// updated
    /// @param token The address of the token whose rebase configuration has
    /// been set or updated
    /// @param isRebase Indicates whether the token is set as a rebasing token
    /// @param mode The yield mode that has been set for the token, defining its
    /// rebasing behavior
    event ConfigurationForRebaseToken(
        address token, bool isRebase, YieldMode mode
    );

    /// @dev Emitted when the rebasing tokens governor address is set.
    /// @param oldRebasingTokensGovernor The previous address of the rebasing
    /// tokens governor.
    /// @param newRebasingTokensGovernor The new address of the rebasing tokens
    /// governor.
    event SetRebasingTokensGovernor(
        address indexed oldRebasingTokensGovernor,
        address indexed newRebasingTokensGovernor
    );

    /// @notice role that can change communityFee and tickspacing in pools
    /// @return The hash corresponding to this role
    function POOLS_ADMINISTRATOR_ROLE() external view returns (bytes32);

    /// @notice role that can create pools when public pool creation is disabled
    /// @return The hash corresponding to this role
    function POOLS_CREATOR_ROLE() external view returns (bytes32);

    /// @notice Returns `true` if `account` has been granted `role` or `account`
    /// is owner.
    /// @param role The hash corresponding to the role
    /// @param account The address for which the role is checked
    /// @return bool Whether the address has this role or the owner role or not
    function hasRoleOrOwner(
        bytes32 role,
        address account
    ) external view returns (bool);

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via transferOwnership(address
    /// newOwner)
    /// @return The address of the factory owner
    function owner() external view returns (address);

    /// @notice Returns the current default blast governor
    /// @return The address of the default blast governor
    function defaultBlastGovernor() external view returns (address);

    /// @notice Returns the current default blast points
    /// @return The address of the default blast points
    function defaultBlastPoints() external view returns (address);

    /// @notice Returns the current default blast points operator
    /// @return The address of the default blast points operator
    function defaultBlastPointsOperator() external view returns (address);

    /// @notice Retrieves the yield mode configuration for a specified token
    /// @param token The address of the token for which to retrieve the yield
    /// mode
    /// @return The yield mode (rebasing configuration) set for the given token
    function configurationForBlastRebaseTokens(
        address token
    ) external view returns (YieldMode);

    /// @notice Return if a token is marked as a rebasing token in the factory
    /// configuration
    /// @param token The address of the token to check
    /// @return True if the token is a rebasing token, false otherwise
    function isRebaseToken(
        address token
    ) external view returns (bool);

    /// @notice Returns the current poolDeployerAddress
    /// @return The address of the poolDeployer
    function poolDeployer() external view returns (address);

    /// @notice Returns the status of enable public pool creation mode
    /// @return bool Whether the public creation mode is enable or not
    function isPublicPoolCreationMode() external view returns (bool);

    /// @notice Returns the default community fee
    /// @return Fee which will be set at the creation of the pool
    function defaultCommunityFee() external view returns (uint16);

    /// @notice Returns the default fee
    /// @return Fee which will be set at the creation of the pool
    function defaultFee() external view returns (uint16);

    /// @notice Returns the default tickspacing
    /// @return Tickspacing which will be set at the creation of the pool
    function defaultTickspacing() external view returns (int24);

    /// @notice Return the current pluginFactory address
    /// @dev This contract is used to automatically set a plugin address in new
    /// liquidity pools
    /// @return Algebra plugin factory
    function defaultPluginFactory() external view returns (address);

    /// @notice Address of the rebasing tokens governor
    /// @return rebasing tokens governor
    function rebasingTokensGovernor() external view returns (address);

    /// @notice Return the current vaultFactory address
    /// @dev This contract is used to automatically set a vault address in new
    /// liquidity pools
    /// @return Algebra vault factory
    function vaultFactory() external view returns (address);

    /// @notice Returns the default communityFee, tickspacing, fee and
    /// communityFeeVault for pool
    /// @param pool the address of liquidity pool
    /// @return communityFee which will be set at the creation of the pool
    /// @return tickSpacing which will be set at the creation of the pool
    /// @return fee which will be set at the creation of the pool
    /// @return communityFeeVault the address of communityFeeVault
    function defaultConfigurationForPool(
        address pool
    )
        external
        view
        returns (
            uint16 communityFee,
            int24 tickSpacing,
            uint16 fee,
            address communityFeeVault
        );

    /// @notice Deterministically computes the pool address given the token0 and
    /// token1
    /// @dev The method does not check if such a pool has been created
    /// @param token0 first token
    /// @param token1 second token
    /// @return pool The contract address of the Algebra pool
    function computePoolAddress(
        address token0,
        address token1
    ) external view returns (address pool);

    /// @notice Returns the pool address for a given pair of tokens, or address
    /// 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or
    /// token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @return pool The pool address
    function poolByPair(
        address tokenA,
        address tokenB
    ) external view returns (address pool);

    /// @notice Returns the custom pool address for a given deployer and pair
    /// @param deployer The custom pool deployer address
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @return customPool The custom pool address
    function customPoolByPair(
        address deployer,
        address tokenA,
        address tokenB
    ) external view returns (address customPool);

    /// @notice returns keccak256 of AlgebraPool init bytecode.
    /// @dev the hash value changes with any change in the pool bytecode
    /// @return Keccak256 hash of AlgebraPool contract init bytecode
    function POOL_INIT_CODE_HASH() external view returns (bytes32);

    /// @return timestamp The timestamp of the beginning of the
    /// renounceOwnership process
    function renounceOwnershipStartTimestamp()
        external
        view
        returns (uint256 timestamp);

    /// @notice Creates a pool for the given two tokens
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or
    /// token1/token0.
    /// The call will revert if the pool already exists or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB
    ) external returns (address pool);

    /// @dev updates pools creation mode
    /// @param mode_ the new mode for pools creation proccess
    function setIsPublicPoolCreationMode(
        bool mode_
    ) external;

    /// @notice Sets the rebase configuration for a specific token
    /// @param token_ The address of the token to configure
    /// @param isRebase_ A boolean indicating whether the token is a rebasing
    /// token or not
    /// @param mode_ The yield mode to apply, defining how the rebasing
    /// mechanism should operate
    function setConfigurationForRebaseToken(
        address token_,
        bool isRebase_,
        YieldMode mode_
    ) external;

    /// @notice Sets the address of the rebasing tokens governor.
    /// @dev Updates the address of the rebasing tokens governor. Can only be
    /// called by an account with the DEFAULT_ADMIN_ROLE.
    /// @param rebasingTokensGovernor_ The new address of the rebasing tokens
    /// governor.
    /// Emits a {SetRebasingTokensGovernor} event.
    function setRebasingTokensGovernor(
        address rebasingTokensGovernor_
    ) external;

    /// @dev updates default community fee for new pools
    /// @param newDefaultCommunityFee The new community fee, _must_ be <=
    /// MAX_COMMUNITY_FEE
    function setDefaultCommunityFee(
        uint16 newDefaultCommunityFee
    ) external;

    /// @dev updates default fee for new pools
    /// @param newDefaultFee The new  fee, _must_ be <= MAX_DEFAULT_FEE
    function setDefaultFee(
        uint16 newDefaultFee
    ) external;

    /// @dev updates default tickspacing for new pools
    /// @param newDefaultTickspacing The new tickspacing, _must_ be <=
    /// MAX_TICK_SPACING and >= MIN_TICK_SPACING
    function setDefaultTickspacing(
        int24 newDefaultTickspacing
    ) external;

    /// @dev updates pluginFactory address
    /// @param newDefaultPluginFactory address of new plugin factory
    function setDefaultPluginFactory(
        address newDefaultPluginFactory
    ) external;

    /// @dev updates vaultFactory address
    /// @param newVaultFactory address of new vault factory
    function setVaultFactory(
        address newVaultFactory
    ) external;

    /// @notice Starts process of renounceOwnership. After that, a certain
    /// period
    /// of time must pass before the ownership renounce can be completed.
    function startRenounceOwnership() external;

    /// @notice Stops process of renounceOwnership and removes timer.
    function stopRenounceOwnership() external;

    /// @dev updates default blast governor address on the factory
    /// @param defaultBlastGovernor_ The new defautl blast governor address
    function setDefaultBlastGovernor(
        address defaultBlastGovernor_
    ) external;

    /// @dev updates default blast points address on the factory
    /// @param defaultBlastPoints_ The new defautl blast points address
    function setDefaultBlastPoints(
        address defaultBlastPoints_
    ) external;

    /// @dev updates default blast points operator address on the factory
    /// @param defaultBlastPointsOperator_ The new defautl blast points operator
    /// address
    function setDefaultBlastPointsOperator(
        address defaultBlastPointsOperator_
    ) external;
}

contracts/interfaces/external/uniswap/IUniswapV3Factory.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and
/// control over the protocol fees
interface IUniswapV3Factory {
    /// @notice Emitted when the owner of the factory is changed
    /// @param oldOwner The owner before the owner was changed
    /// @param newOwner The owner after the owner was changed
    event OwnerChanged(address indexed oldOwner, address indexed newOwner);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in
    /// hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via
    /// the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or
    /// 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard
    /// coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns
    /// 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(
        uint24 fee
    ) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee,
    /// or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or
    /// token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in
    /// hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or
    /// token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee
    /// is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external returns (address pool);

    /// @notice Updates the owner of the factory
    /// @dev Must be called by the current owner
    /// @param _owner The new owner of the factory
    function setOwner(
        address _owner
    ) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip
    /// (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all
    /// pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}

contracts/interfaces/external/uniswap/IUniswapV3Pool.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods
/// will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the
    /// IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and
    /// always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick,
    /// i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always
    /// positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick
    /// in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from
    /// overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding
    /// in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any
/// frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is
    /// exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a
    /// sqrt(token1/token0) Q64.96 value
    /// @return tick The current tick of the pool, i.e. according to the last
    /// tick transition that was run.
    /// This value may not always be equal to
    /// SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// @return observationIndex The index of the last oracle observation that
    /// was written,
    /// @return observationCardinality The current maximum number of
    /// observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of
    /// observations, to be updated when the observation.
    /// @return feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted
    /// 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap
    /// fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit
    /// of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit
    /// of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees()
        external
        view
        returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all
    /// ticks
    /// @return The liquidity at the current price of the pool
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses
    /// the pool either as tick lower or
    /// tick upper
    /// @return liquidityNet how much liquidity changes when the pool price
    /// crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the
    /// tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the
    /// tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other
    /// side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity
    /// on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick
    /// from the current tick,
    /// @return initialized Set to true if the tick is initialized, i.e.
    /// liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if
    /// liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in
    /// comparison to previous snapshots for
    /// a specific position.
    function ticks(
        int24 tick
    )
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See
    /// TickBitmap for more information
    function tickBitmap(
        int16 wordPosition
    ) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the
    /// owner, tickLower and tickUpper
    /// @return liquidity The amount of liquidity in the position,
    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick
    /// range as of the last mint/burn/poke,
    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick
    /// range as of the last mint/burn/poke,
    /// @return tokensOwed0 the computed amount of token0 owed to the position
    /// as of the last mint/burn/poke,
    /// @return tokensOwed1 the computed amount of token1 owed to the position
    /// as of the last mint/burn/poke
    function positions(
        bytes32 key
    )
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to
    /// get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the
    /// life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range
    /// liquidity for the life of the pool as of the observation timestamp,
    /// @return initialized whether the observation has been initialized and the
    /// values are safe to use
    function observations(
        uint256 index
    )
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );

    function observe(
        uint32[] calldata secondsAgos
    )
        external
        view
        returns (
            int56[] memory tickCumulatives,
            uint160[] memory secondsPerLiquidityCumulativeX128s
        );
}

interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState {
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount
    ) external returns (bool);
}

lib/solmate/src/tokens/ERC20.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

lib/solmate/src/utils/SafeTransferLib.sol

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                                ERRORS
    //////////////////////////////////////////////////////////////*/

    error ETHTransferFailed();
    error TransferFromFailed();
    error TransferFailed();
    error ApproveFailed();

    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        if (!success) revert ETHTransferFailed();
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

            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 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // 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(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        if (!success) revert TransferFromFailed();
    }

    function safeTransfer(
        address token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            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(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        if (!success) revert TransferFailed();
    }

    function safeApprove(
        address token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            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(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        if (!success) revert ApproveFailed();
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "solmate/=lib/solmate/src/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@morpho-blue/=lib/morpho-blue/src/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "morpho-blue/=lib/morpho-blue/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.