Skip to content
Verified contractExactUNLICENSED

NonLinearFallbackExtension

Address0x39c858ab91caa4da7d72e49b23460115109cd589
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,404,575
Creation transaction
0x503cdc5508…164b82127d

contracts/router/modules/NonLinearFallbackExtension.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
pragma abicoder v2;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ISwapStructs} from "../interfaces/ISwapStructs.sol";
import {
    NonLinearSwapModuleStorage,
    INonLinearFallbackExtension,
    INonLinearCandidateExecutor
} from "./NonLinearSwapModuleStorage.sol";

/// The type 98/99 fallback wrapper of the NonLinearSwapModule, moved out of
/// the core to keep the core below the EIP-170 code size limit (G19).
///
/// The core calls runFallbackRoute by delegatecall only: the code runs in the
/// storage and with the balances of the core, after the core set its
/// reentrancy lock and wrapped native input. The extension writes no storage.
/// It reads the wallet-unsafe set of the core (the shared layout), and it runs
/// each candidate as a self-call to the core (executeNonLinearCandidate), so a
/// failed candidate reverts in full before the next one runs. The code is the
/// earlier in-module wrapper, unchanged in behavior: same checks, same errors,
/// same NonLinearFallbackUsed event (emitted by the core address).
contract NonLinearFallbackExtension is NonLinearSwapModuleStorage, INonLinearFallbackExtension {
    struct NonLinearFallbackData {
        NonLinearRouteStep[] primaryPaths;
        NonLinearRouteStep[] fallbackPaths;
    }

    struct NonLinearGasCappedFallbackData {
        NonLinearRouteStep[] primaryPaths;
        NonLinearRouteStep[] fallbackPaths;
        /// Gas forwarded to the primary attempt.
        uint256 primaryGas;
        /// Gas that must remain for the fallback after the primary attempt.
        uint256 fallbackGas;
    }

    /// The type-96 probed route switch: two whole routes and the freshness
    /// reads that decide between them (ABI shared with the backend).
    struct Probe {
        address target; // a Titan-family router: isActive(tokenIn, tokenOut)
        address tokenIn;
        address tokenOut;
    }

    struct ProbedRouteData {
        bytes primary; // abi.encode(NonLinearRouteStep[]): the full route (oracle venues allowed)
        bytes fallbackRoute; // abi.encode(NonLinearRouteStep[]): the wallet-safe route
        Probe[] probes; // one per oracle step of the primary with a block-keyed read
        uint256 primaryGas; // gas the primary needs; 0 = no guard
    }

    /// IPropAMM.isActive(address,address). A read above this gas, a revert or
    /// a short answer reads as stale.
    bytes4 private constant IS_ACTIVE = 0xae131deb;
    uint256 private constant PROBE_GAS = 20_000;

    /// The core checks this value at construction.
    bytes32 public constant override EXTENSION_ID = keccak256("akka.nonlinear.fallback-extension.v1");

    address private immutable _self;

    error NonLinearFallbackOnlyDelegateCall();

    constructor() Ownable(msg.sender) {
        _self = address(this);
        // The extension's own storage is never used (only the core's, by
        // delegatecall): no owner, so its owner() reads 0.
        _transferOwnership(address(0));
    }

    /// payable: a delegatecall keeps the msg.value of the core's call (native input).
    function runFallbackRoute(NonLinearRouteStep calldata wrapper, uint256 srcAmount, uint256 amountOutMin)
        external
        payable
        override
        returns (uint256 receivedAmount)
    {
        // A direct call would run on the (empty) storage of this contract.
        if (address(this) == _self) revert NonLinearFallbackOnlyDelegateCall();
        if (wrapper.percentage != 1_000_000 || wrapper.srcToken == wrapper.dstToken) {
            revert NonLinearFallbackInvalidWrapper();
        }
        if (wrapper.liquidityType == PROBED_LT) return _runProbed(wrapper, srcAmount);
        NonLinearRouteStep[] memory primaryPaths;
        NonLinearRouteStep[] memory fallbackPaths;
        uint256 primaryGas; // 0 = uncapped (legacy type 99)
        if (wrapper.liquidityType == GAS_CAPPED_FALLBACK_LT) {
            NonLinearGasCappedFallbackData memory capped = abi.decode(wrapper.data, (NonLinearGasCappedFallbackData));
            if (capped.primaryGas == 0 || capped.fallbackGas == 0) {
                revert NonLinearFallbackInvalidWrapper();
            }
            primaryPaths = capped.primaryPaths;
            fallbackPaths = capped.fallbackPaths;
            primaryGas = capped.primaryGas;
            // Refuse up front rather than starve either half: a starved
            // primary would silently downgrade the user to the fallback, a
            // starved fallback would fail the whole swap after the primary
            // already failed.
            uint256 required = capped.primaryGas + capped.fallbackGas;
            if (gasleft() < required) {
                revert NonLinearFallbackInsufficientGas(gasleft(), required);
            }
        } else {
            NonLinearFallbackData memory legacy = abi.decode(wrapper.data, (NonLinearFallbackData));
            primaryPaths = legacy.primaryPaths;
            fallbackPaths = legacy.fallbackPaths;
        }
        _validateCandidate(primaryPaths, wrapper.srcToken, wrapper.dstToken, false);
        _validateCandidate(fallbackPaths, wrapper.srcToken, wrapper.dstToken, true);

        receivedAmount = _executeWithFallback(
            primaryPaths, fallbackPaths, primaryGas, srcAmount, wrapper.srcToken, wrapper.dstToken, amountOutMin
        );
    }

    // ------------------------------------------------- probed switch (96)

    /// One freshness read. False, a revert or a short answer = stale.
    function _fresh(Probe memory p) private view returns (bool) {
        (bool ok, bytes memory ret) =
            p.target.staticcall{gas: PROBE_GAS}(abi.encodeWithSelector(IS_ACTIVE, p.tokenIn, p.tokenOut));
        return ok && ret.length >= 32 && abi.decode(ret, (bool));
    }

    /// The calldata of executeRouteFrame(NonLinearRoute, src, out, requireSafe)
    /// built from the encoded step list as it came (abi.encode(NonLinearRouteStep[])
    /// = one offset word, then the array), with no decode into memory: the
    /// head (offset 0x80, src, out, requireSafe), the struct head (srcAmount,
    /// 0, 0, 0, the paths offset 0xa0) and the array bytes. The frame reads the
    /// route from calldata. The core deposited native input before the
    /// delegatecall: the routes start from the wrapped token.
    function _frameCall(bytes memory encoded, uint256 srcAmount, address src, address out, bool requireSafe)
        private
        returns (bool ok, uint256 held)
    {
        bytes memory head = abi.encodeWithSelector(
            INonLinearCandidateExecutor.executeRouteFrame.selector,
            uint256(0x80),
            src,
            out,
            requireSafe,
            srcAmount,
            uint256(0),
            uint256(0),
            uint256(0),
            uint256(0xa0)
        );
        uint256 tailLen = encoded.length - 32;
        bytes memory cd = new bytes(head.length + tailLen);
        assembly ("memory-safe") {
            mcopy(add(cd, 32), add(head, 32), mload(head))
            mcopy(add(add(cd, 32), mload(head)), add(encoded, 64), tailLen)
        }
        bytes memory ret;
        (ok, ret) = address(this).call(cd);
        if (ok) {
            if (ret.length < 32) revert NonLinearFallbackInvalidRoute();
            held = abi.decode(ret, (uint256));
        }
    }

    /// The type-96 switch. Every probe fresh and enough gas: the primary runs
    /// in a revertable frame of the core's normal route loop; a revert (a read
    /// that lied) runs the fallback. A stale read or the gas guard runs the
    /// fallback at once, with no attempt. Only the route that runs is decoded
    /// (by the frame, from calldata). The caller pays out the held output once,
    /// with the route minimum and the signed cap.
    function _runProbed(NonLinearRouteStep calldata wrapper, uint256 srcAmount)
        private
        returns (uint256 held)
    {
        ProbedRouteData memory d = abi.decode(wrapper.data, (ProbedRouteData));
        // An empty step list encodes to 64 bytes (offset, length 0): both routes must hold steps.
        if (d.primary.length <= 64 || d.fallbackRoute.length <= 64) revert NonLinearFallbackInvalidRoute();
        uint8 reason;
        for (uint256 i; i < d.probes.length; ++i) {
            if (!_fresh(d.probes[i])) {
                reason = 1;
                break;
            }
        }
        if (reason == 0 && d.primaryGas != 0 && gasleft() < d.primaryGas) reason = 2;
        if (reason == 0) {
            bool ok;
            (ok, held) = _frameCall(d.primary, srcAmount, wrapper.srcToken, wrapper.dstToken, false);
            if (ok) {
                emit ProbedRouteUsed(true, 0);
                return held;
            }
            reason = 3;
        }
        bool okF;
        (okF, held) = _frameCall(d.fallbackRoute, srcAmount, wrapper.srcToken, wrapper.dstToken, true);
        if (!okF) revert NonLinearFallbackInvalidRoute();
        emit ProbedRouteUsed(false, reason);
    }

    function _validateCandidate(
        NonLinearRouteStep[] memory paths,
        address expectedSrcToken,
        address expectedDstToken,
        bool isFallback
    ) private view {
        if (
            paths.length == 0 || expectedSrcToken == expectedDstToken || paths[0].srcToken != expectedSrcToken
                || paths[paths.length - 1].dstToken != expectedDstToken
        ) revert NonLinearFallbackInvalidRoute();

        // The error names keep the Metric-era identifiers; they cover every
        // wallet-unsafe type.
        bool hasWalletUnsafe;
        for (uint256 i; i < paths.length; ++i) {
            if (
                paths[i].srcToken == address(0) || paths[i].dstToken == address(0)
                    || paths[i].srcToken == paths[i].dstToken || paths[i].percentage == 0
                    || paths[i].percentage > 1_000_000 || paths[i].liquidityType == FALLBACK_LT
                    || paths[i].liquidityType == GAS_CAPPED_FALLBACK_LT
            ) revert NonLinearFallbackInvalidRoute();
            bool unsafeType = _walletUnsafe[paths[i].liquidityType];
            if (isFallback && unsafeType) revert NonLinearFallbackMetricInFallback();
            if (unsafeType) hasWalletUnsafe = true;
        }
        if (!isFallback && !hasWalletUnsafe) revert NonLinearFallbackMetricMissing();
    }

    function _revertSelector(bytes memory reason) private pure returns (bytes4 selector) {
        if (reason.length < 4) return bytes4(0);
        assembly ("memory-safe") {
            selector := mload(add(reason, 32))
        }
    }

    /// Runs the primary candidate in a revertable self-call and, if it fails
    /// for any reason (revert, out-of-gas at the cap, invalid opcode), the
    /// fallback candidate. primaryGas == 0 forwards all remaining gas (legacy
    /// type 99); else the primary attempt is capped at primaryGas.
    function _executeWithFallback(
        NonLinearRouteStep[] memory primaryPaths,
        NonLinearRouteStep[] memory fallbackPaths,
        uint256 primaryGas,
        uint256 srcAmount,
        address srcToken,
        address dstToken,
        uint256 amountOutMin
    ) private returns (uint256 receivedAmount) {
        // address(this) is the core (delegatecall context).
        INonLinearCandidateExecutor core = INonLinearCandidateExecutor(address(this));
        bool primaryOk;
        bytes memory primaryReason;
        if (primaryGas == 0) {
            try core.executeNonLinearCandidate(primaryPaths, srcAmount, srcToken, dstToken, amountOutMin) returns (
                uint256 primaryAmountOut
            ) {
                primaryOk = true;
                receivedAmount = primaryAmountOut;
            } catch (bytes memory reason) {
                primaryReason = reason;
            }
        } else {
            try core.executeNonLinearCandidate{gas: primaryGas}(
                primaryPaths, srcAmount, srcToken, dstToken, amountOutMin
            ) returns (uint256 primaryAmountOut) {
                primaryOk = true;
                receivedAmount = primaryAmountOut;
            } catch (bytes memory reason) {
                primaryReason = reason;
            }
        }
        if (!primaryOk) {
            receivedAmount = core.executeNonLinearCandidate(fallbackPaths, srcAmount, srcToken, dstToken, amountOutMin);
            emit NonLinearFallbackUsed(_revertSelector(primaryReason));
        }
    }

    // ---------------------------------------------------------- candidates

    /// The body of the core's executeNonLinearCandidate: the core checks
    /// msg.sender == itself, then calls this function by delegatecall with the
    /// same arguments. Each step runs in the core's swap code (a self-call to
    /// executeCandidateStep) between two balance reads of its tokens.
    function runCandidate(
        NonLinearRouteStep[] calldata paths,
        uint256 srcAmount,
        address expectedSrcToken,
        address expectedDstToken,
        uint256 amountOutMin
    ) external override returns (uint256 amountOut) {
        if (address(this) == _self) revert NonLinearFallbackOnlyDelegateCall();
        amountOut = _executeCandidateSteps(paths, srcAmount, expectedSrcToken, expectedDstToken);
        if (amountOut < amountOutMin) revert NonLinearFallbackInsufficientOutput(amountOut, amountOutMin);
    }

    /// Balance kept per token by the core (base units).
    uint256 private constant DUST = 1;

    function _ledgerIndex(address[] memory tokens, uint256 tokenCount, address token)
        private
        pure
        returns (uint256 index, bool found)
    {
        for (uint256 i; i < tokenCount; ++i) {
            if (tokens[i] == token) return (i, true);
        }
    }

    function _tokenDustUnit(address token) private view returns (uint256) {
        try IERC20MetadataLike(token).decimals() returns (uint8 tokenDecimals) {
            // One unit at six-decimal precision for each outgoing step.
            // Reject unusual metadata to keep the guard narrow.
            if (tokenDecimals <= 6 || tokenDecimals > 36) return 1;
            return 10 ** (tokenDecimals - 6);
        } catch {
            return 1;
        }
    }

    function _allowedCandidateDust(address token, NonLinearRouteStep[] calldata paths)
        private
        view
        returns (uint256 allowedDust)
    {
        uint256 outgoingSteps;
        for (uint256 i; i < paths.length; ++i) {
            if (paths[i].srcToken == token) ++outgoingSteps;
        }
        allowedDust = _tokenDustUnit(token) * outgoingSteps;
    }

    function _executeMeasuredStep(NonLinearRouteStep calldata step, uint256 stepInputAmount)
        private
        returns (uint256 stepAmountIn, uint256 stepAmountOut)
    {
        // address(this) is the core (delegatecall context).
        uint256 beforeSrc = IERC20Balance(step.srcToken).balanceOf(address(this));
        uint256 beforeDst = IERC20Balance(step.dstToken).balanceOf(address(this));
        INonLinearCandidateExecutor(address(this)).executeCandidateStep(
            step, stepInputAmount, beforeSrc > DUST ? beforeSrc - DUST : 0
        );
        uint256 afterSrc = IERC20Balance(step.srcToken).balanceOf(address(this));
        uint256 afterDst = IERC20Balance(step.dstToken).balanceOf(address(this));
        if (afterSrc >= beforeSrc || afterDst <= beforeDst) revert NonLinearFallbackInvalidRoute();
        stepAmountIn = beforeSrc - afterSrc;
        stepAmountOut = afterDst - beforeDst;
        if (stepAmountIn > stepInputAmount) revert NonLinearFallbackInvalidRoute();
    }

    function _executeCandidateSteps(
        NonLinearRouteStep[] calldata paths,
        uint256 srcAmount,
        address expectedSrcToken,
        address expectedDstToken
    ) private returns (uint256 amountOut) {
        address[] memory tokens = new address[](paths.length + 1);
        uint256[] memory amounts = new uint256[](paths.length + 1);
        tokens[0] = expectedSrcToken;
        amounts[0] = srcAmount;
        uint256 tokenCount = 1;

        address currentSrcToken;
        uint256 currentSrcAmount;
        uint256 currentSrcSpent;

        for (uint256 i; i < paths.length; ++i) {
            NonLinearRouteStep calldata step = paths[i];
            (uint256 srcIndex, bool srcFound) = _ledgerIndex(tokens, tokenCount, step.srcToken);
            if (!srcFound || amounts[srcIndex] == 0) revert NonLinearFallbackInvalidRoute();

            if (step.srcToken != currentSrcToken) {
                currentSrcToken = step.srcToken;
                currentSrcAmount = amounts[srcIndex];
                currentSrcSpent = 0;
            }

            uint256 stepInputAmount = (currentSrcAmount * step.percentage) / 1_000_000;
            if (
                stepInputAmount == 0 || currentSrcSpent + stepInputAmount > currentSrcAmount
                    || stepInputAmount > amounts[srcIndex]
            ) revert NonLinearFallbackInvalidRoute();

            (uint256 stepAmountIn, uint256 stepAmountOut) = _executeMeasuredStep(step, stepInputAmount);
            if (stepAmountIn > amounts[srcIndex]) revert NonLinearFallbackInvalidRoute();
            amounts[srcIndex] -= stepAmountIn;
            currentSrcSpent += stepAmountIn;

            (uint256 dstIndex, bool dstFound) = _ledgerIndex(tokens, tokenCount, step.dstToken);
            if (!dstFound) {
                dstIndex = tokenCount;
                tokens[tokenCount] = step.dstToken;
                ++tokenCount;
            }
            amounts[dstIndex] += stepAmountOut;
        }

        // A candidate must use its input. Permit split and decimal-conversion
        // dust. Raw token units are not comparable across token decimals.
        for (uint256 i; i < tokenCount; ++i) {
            if (tokens[i] != expectedDstToken && amounts[i] > _allowedCandidateDust(tokens[i], paths)) {
                revert NonLinearFallbackInvalidRoute();
            }
        }

        (uint256 finalIndex, bool finalFound) = _ledgerIndex(tokens, tokenCount, expectedDstToken);
        if (!finalFound || amounts[finalIndex] == 0) revert NonLinearFallbackInvalidRoute();
        return amounts[finalIndex];
    }
}

interface IERC20MetadataLike {
    function decimals() external view returns (uint8);
}

interface IERC20Balance {
    function balanceOf(address account) external view returns (uint256);
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

contracts/router/interfaces/ISwapStructs.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

interface ISwapStructs {
    struct PathDescription {
        address srcToken;
        address dstToken;
        address pairAddr;
        uint fee;
        uint256 srcAmount;
        uint256 dstMinAmount;
        uint feeSrc;
        uint feeDst;
        uint liquidityType;
        bytes data;
    }

    struct SplitedPathDescription {
        uint256 srcAmount;
        uint256 dstMinAmount;
        uint isFromNative;
        uint isToNative;
        PathDescription[] paths;
    }

    struct NonLinearRouteStep {
        address srcToken;
        address dstToken;
        address pairAddr;
        uint256 percentage;
        uint fee;
        uint feeSrc;
        uint feeDst;
        uint liquidityType;
        bytes data;
    }

    struct NonLinearRoute {
        uint256 srcAmount;
        uint256 dstMinAmount;
        uint isFromNative;
        uint isToNative;
        NonLinearRouteStep[] paths;
    }

    struct SignatureData {
        uint256 fee;
        uint8 v;
        bytes32 r;
        bytes32 s;
    }

    struct TokenAmount {
        address token;
        uint256 amount;
    }
}

contracts/router/modules/NonLinearSwapModuleStorage.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
pragma abicoder v2;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ISwapStructs} from "../interfaces/ISwapStructs.sol";

/// The NonLinearSwapModule core calls its FallbackExtension by delegatecall:
/// the extension runs in the storage of the core.
interface INonLinearFallbackExtension is ISwapStructs {
    function EXTENSION_ID() external view returns (bytes32);

    /// Runs the one-step route whose step is the type 98/99 wrapper. Returns the
    /// amount of the wrapper's dstToken that the winning candidate left in the core.
    function runFallbackRoute(NonLinearRouteStep calldata wrapper, uint256 srcAmount, uint256 amountOutMin)
        external
        payable
        returns (uint256 receivedAmount);

    /// The body of the core's executeNonLinearCandidate (same arguments).
    function runCandidate(
        NonLinearRouteStep[] calldata paths,
        uint256 srcAmount,
        address expectedSrcToken,
        address expectedDstToken,
        uint256 amountOutMin
    ) external returns (uint256 amountOut);
}

/// The self-calls of the core that the extension code makes (it runs in the core).
interface INonLinearCandidateExecutor is ISwapStructs {
    /// One candidate in a revertable frame (the extension's runCandidate by delegatecall).
    function executeNonLinearCandidate(
        NonLinearRouteStep[] calldata paths,
        uint256 srcAmount,
        address expectedSrcToken,
        address expectedDstToken,
        uint256 amountOutMin
    ) external returns (uint256 amountOut);

    /// One step of a candidate: the core's swap code (inline venues or the handler).
    function executeCandidateStep(NonLinearRouteStep calldata step, uint256 stepInputAmount, uint256 available)
        external
        returns (uint256 amountOut);

    /// A whole route in the core's normal route loop, held in the core (no
    /// payout). The type-96 switch runs its primary in this revertable frame
    /// and its fallback in the same frame without a try.
    /// `src`/`out` and the shape checks run on the calldata here (no memory
    /// decode of the route); requireSafe refuses a wallet-unsafe type (W).
    function executeRouteFrame(NonLinearRoute calldata data, address src, address out, bool requireSafe)
        external
        returns (uint256 held);
}

/// Storage layout, errors and events of the NonLinearSwapModule core and of
/// its FallbackExtension. The extension runs by delegatecall in the storage of
/// the core, so both contracts inherit this one layout. Append only.
///
/// Stage-1 gas build (2026-10-22): a new deploy, not an upgrade in place. The
/// layout is new: one handler mapping replaces the 47 handler slots, and the
/// WETH address, the V4 PoolManager and the inline switches are immutables of
/// the core.
abstract contract NonLinearSwapModuleStorage is Ownable {
    /// slot 1: receives the output above the signed cap (the surplus).
    address internal treasuryAddress;
    /// slot 2: liquidityType => swap handler.
    mapping(uint256 => address) internal _swapHandlers;
    /// slot 3: liquidity types whose legs fail a wallet's pre-signature
    /// simulation (oracle or precompile priced venues).
    mapping(uint256 => bool) internal _walletUnsafe;
    /// slot 4: the same set as a list (WRAPPED_ORACLE_TYPES).
    uint256[] internal _walletUnsafeTypes;

    uint256 internal constant FALLBACK_LT = 99;
    uint256 internal constant GAS_CAPPED_FALLBACK_LT = 98;
    /// The probed route switch: two whole routes, a freshness read decides.
    uint256 internal constant PROBED_LT = 96;

    // Error names keep their earlier identifiers (ABI stability for the backend
    // and the monitors).
    error NonLinearFallbackOnlySelf();
    error NonLinearFallbackInvalidWrapper();
    error NonLinearFallbackInvalidRoute();
    error NonLinearFallbackMetricMissing();
    error NonLinearFallbackMetricInFallback();
    error NonLinearFallbackInsufficientOutput(uint256 amountOut, uint256 minimum);
    error NonLinearFallbackInsufficientGas(uint256 available, uint256 required);
    error NonLinearReentrancy();

    event NonLinearFallbackUsed(bytes4 indexed primaryError);
    /// The type-96 switch: primary = the full route ran. reason: 0 primary
    /// filled, 1 a probe said stale, 2 the gas guard, 3 the primary reverted.
    event ProbedRouteUsed(bool indexed primary, uint8 reason);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.