Skip to content
Verified contractExactUNLICENSED

FLAMMTychoSwapAdapter

Address0x6d4fa456e85d64e38ad73f1eac0e562ef37b9717
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.35

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,396,609
Creation transaction
0x2b81572867…9d5156968a
Libraries
src/core/mm/MMRouterLib.sol:MMRouterLib0xa474…d2b4e5src/core/flamm/FLAMMLane.sol:FLAMMLane0x0988…d22e98src/core/flamm/FLAMMRoute.sol:FLAMMRoute0x312e…0fdaa9src/periphery/FLAMMMaxima.sol:FLAMMMaxima0x4a99…d6259csrc/core/flamm/FLAMMLawLib.sol:FLAMMLawLib0x5d47…27cc62src/core/flamm/FLAMMOpsLib.sol:FLAMMOpsLib0x0bfe…043753src/core/mm/AaveV3ReadsLib.sol:AaveV3ReadsLib0xd53f…ed5983src/core/flamm/FLAMMFlowLib.sol:FLAMMFlowLib0x2577…4e3473src/core/flamm/FLAMMGateLib.sol:FLAMMGateLib0xf0be…2b9555src/core/flamm/FLAMMKeptLib.sol:FLAMMKeptLib0x7a11…58517bsrc/core/mm/CTokenMarketLib.sol:CTokenMarketLib0x18c5…b2071csrc/core/flamm/FLAMMAdmitLib.sol:FLAMMAdmitLib0xa6db…bdcbcbsrc/core/flamm/FLAMMBlindLib.sol:FLAMMBlindLib0x0b8d…2e7e5csrc/core/flamm/FLAMMClaimLib.sol:FLAMMClaimLib0x02b4…731ccesrc/core/flamm/FLAMMFenceLib.sol:FLAMMFenceLib0xa16d…a201e8src/core/flamm/FLAMMFloatLib.sol:FLAMMFloatLib0x539e…a79737src/core/flamm/FLAMMQuoteLib.sol:FLAMMQuoteLib0xa4d3…d5ce2esrc/core/flamm/FLAMMTopUpLib.sol:FLAMMTopUpLib0x7c55…d233dfsrc/core/mm/CTokenRewardsLib.sol:CTokenRewardsLib0xcda6…a4dcf7src/core/mm/MMRouterAdminLib.sol:MMRouterAdminLib0x8423…7adc96src/core/flamm/FLAMMPolicyLib.sol:FLAMMPolicyLib0xa6b4…0c67f9src/core/flamm/FLAMMSettleLib.sol:FLAMMSettleLib0xb489…d3c7cbsrc/core/flamm/FLAMMSharedLib.sol:FLAMMSharedLib0xfaae…2511basrc/periphery/FLAMMExitMaxima.sol:FLAMMExitMaxima0x480f…4e0a81src/hooks/everlong/LeverageLib.sol:LeverageLib0x1b1d…40ad11src/core/flamm/FLAMMMaintainLib.sol:FLAMMMaintainLib0x9499…409cc2src/core/flamm/FLAMMPairQuoteLib.sol:FLAMMPairQuoteLib0x0775…d94cbesrc/hooks/everlong/EverlongOpsLib.sol:EverlongOpsLib0xabe4…7426f7

65 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/periphery/FLAMMTychoSwapAdapter.sol

// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
import {IPriceFeed} from "src/interfaces/core/IPriceFeed.sol";
import {FLAMMFactory} from "src/factory/FLAMMFactory.sol";
import {NonReentrant} from "src/libraries/ReentrancyGuardLib.sol";
import {SafeTransferLib} from "src/libraries/SafeTransferLib.sol";

/// @notice PropellerHeads Tycho `ISwapAdapter` over every Factory pool and every pair it trades. A pool id is the pool
///         address, right-aligned in 32 bytes; its tokens are every token it lists, the pool asset first. Sell orders
///         only (the pool has no exact-output form).
///         APPROVE-AND-CALL ONLY: `swap` pulls its input and refunds only what that pull left, and the pool takes its
///         input by its own rule (`IFLAMM.swap`): it pulls what the fill uses, or nothing where it already holds the
///         whole input past its tracked custody, and then the refund is the whole input. Tokens transferred here
///         directly are unrecoverable (no owner, no rescue), even in the same transaction as `swap`.
/// @dev How it reads the pool:
///      - Every pair is quoted by its tokens (`IFLAMM.previewSwap(address, address, uint256)`, which answers the hook
///        pair as its two-token form does).
///      - Where the pool refuses a pair (outside either trade mask, a token it does not list, an aged print, a pause),
///        its price reads zero and its limits read zero, so a walk of every pair of the pool's tokens never fails on
///        one it refuses; a swap there reverts as the pool's own swap does.
///      - A fill cut at the pool's ceiling (its gate room, or its held output where it cannot borrow) or notional cap
///        refunds the unused input to the caller, unless the pool already holds the whole input past its tracked
///        custody, where a clip reverts (`InputUnused`); a sell larger than its venue can fund reverts.
///      - Prices are the pool's `previewSwap` fractions in raw token units (buy per sell); limits are what the pool
///        would fill now, funding included, except that where a venue's cash is under a lever-up's payout a sell at
///        the limit can fill on the swap hook's leverage curve and revert (`IFLAMM.previewSwap`).
contract FLAMMTychoSwapAdapter is NonReentrant {
    /// @dev Tycho `Capability` ordinals.
    uint256 internal constant CAP_SELL_ORDER = 1;
    uint256 internal constant CAP_PRICE_FUNCTION = 3;
    uint256 internal constant CAP_MARGINAL_PRICE = 9;
    /// @dev The smallest marginal-price probe in sell-token base units (the pool refuses zero; `_probe` sizes the
    ///      one used), and the largest input the limit search tries.
    uint256 internal constant PROBE = 1e6;
    uint256 internal constant LIMIT_PROBE = 2 ** 96;

    /// @notice Tycho's price form: `numerator / denominator`, raw buy-token units per raw sell-token unit.
    struct Fraction {
        uint256 numerator;
        uint256 denominator;
    }

    /// @notice Tycho's order side; this adapter serves `Sell` alone.
    enum OrderSide {
        Sell,
        Buy
    }

    /// @notice Tycho's swap result: the output, the gas `swap` reports and the marginal price after the fill.
    struct Trade {
        uint256 calculatedAmount;
        uint256 gasUsed;
        Fraction price;
    }

    /// @notice The Factory whose pools this adapter serves, read for its registry only: `isPool` and `pools`.
    FLAMMFactory public immutable FACTORY;

    /// @notice A Factory address with no code at construction.
    error ZeroFactory();
    /// @notice A pool id that is not a right-aligned address of a Factory pool.
    error UnknownPool();
    /// @notice A token paired with itself.
    error BadPair();
    /// @notice A `swap` on the buy side.
    error UnsupportedSide();

    /// @param factory The Factory whose pools this adapter serves.
    constructor(address factory) {
        if (factory.code.length == 0) revert ZeroFactory();
        FACTORY = FLAMMFactory(factory);
    }

    /// @notice Average fill price for each amount (`amountOut / amountInUsed`); a zero amount asks for the
    ///         marginal price and is probed with dust, sized once, where the first zero asks for it. Zero (`0 / 1`)
    ///         where the pool refuses the quote.
    function price(bytes32 poolId, address sellToken, address buyToken, uint256[] memory specifiedAmounts)
        external
        view
        returns (Fraction[] memory prices)
    {
        IFLAMM pool = _pair(poolId, sellToken, buyToken);
        uint256 probe;
        prices = new Fraction[](specifiedAmounts.length);
        for (uint256 i; i < specifiedAmounts.length; ++i) {
            uint256 amountIn = specifiedAmounts[i];
            if (amountIn == 0 && probe == 0) probe = _probe(pool, sellToken);
            (, uint256 used, uint256 out) = _preview(pool, sellToken, buyToken, amountIn == 0 ? probe : amountIn);
            prices[i] = _fraction(out, used);
        }
    }

    /// @notice Sell exactly `specifiedAmount` of `sellToken` (pulled from the caller) into the pool; the output
    ///         and any unfilled input go back to the caller. `trade.price` is the marginal price after the fill.
    ///         `trade.gasUsed` reads the path the fill took, the pull unless the pool already holds the input: the
    ///         pool's grant, its swap and the clear, what an executor holding the input pays per hop when the pool
    ///         pulls. The pull into this contract and the refund are left out.
    function swap(bytes32 poolId, address sellToken, address buyToken, OrderSide side, uint256 specifiedAmount)
        external
        nonReentrant
        returns (Trade memory trade)
    {
        if (side != OrderSide.Sell) revert UnsupportedSide();
        IFLAMM pool = _pair(poolId, sellToken, buyToken);
        uint256 in0 = IERC20(sellToken).balanceOf(address(this));
        SafeTransferLib.safeTransferFrom(sellToken, msg.sender, address(this), specifiedAmount);
        uint256 gasBefore = gasleft();
        SafeTransferLib.safeApprove(sellToken, address(pool), specifiedAmount);
        (, uint256 out) = pool.swap(sellToken, buyToken, specifiedAmount, 0, msg.sender, block.timestamp);
        SafeTransferLib.safeApprove(sellToken, address(pool), 0);
        trade.gasUsed = gasBefore - gasleft();
        // No cross-check of the pool's report against the balances: pools are permissionless and `minOut` is 0, so
        // it would protect nothing against a hostile pool and would turn a mid-call hook donation into a revert.
        uint256 unused = IERC20(sellToken).balanceOf(address(this)) - in0;
        if (unused != 0) SafeTransferLib.safeTransfer(sellToken, msg.sender, unused);
        trade.calculatedAmount = out;
        (, uint256 used, uint256 probeOut) = _preview(pool, sellToken, buyToken, _probe(pool, sellToken));
        trade.price = _fraction(probeOut, used);
    }

    /// @notice `[maxSellIn, maxBuyOut]` the pool would fill now; zeros when it cannot quote.
    function getLimits(bytes32 poolId, address sellToken, address buyToken)
        external
        view
        returns (uint256[] memory limits)
    {
        IFLAMM pool = _pair(poolId, sellToken, buyToken);
        limits = new uint256[](2);
        (limits[0], limits[1]) = _limits(pool, sellToken, buyToken);
    }

    /// @notice Tycho's capabilities, the same for every pool and pair: sell orders, the price function and the marginal
    ///         price.
    function getCapabilities(bytes32, address, address) external pure returns (uint256[] memory caps) {
        caps = new uint256[](3);
        caps[0] = CAP_SELL_ORDER;
        caps[1] = CAP_PRICE_FUNCTION;
        caps[2] = CAP_MARGINAL_PRICE;
    }

    /// @notice Every token the pool lists, the pool asset first, as the pool indexes them.
    function getTokens(bytes32 poolId) external view returns (address[] memory tokens) {
        IFLAMM pool = _pool(poolId);
        uint256 n = pool.tokenCount();
        tokens = new address[](n);
        tokens[0] = pool.asset();
        tokens[1] = pool.loanAsset();
        for (uint256 t = 2; t < n; ++t) {
            tokens[t] = pool.tokenConfig(uint8(t)).token;
        }
    }

    /// @notice At most `limit` pool ids from `offset`, in the Factory's order; none past its last pool.
    function getPoolIds(uint256 offset, uint256 limit) external view returns (bytes32[] memory ids) {
        address[] memory all = FACTORY.pools();
        if (offset >= all.length) return ids;
        uint256 n = all.length - offset < limit ? all.length - offset : limit;
        ids = new bytes32[](n);
        for (uint256 i; i < n; ++i) {
            ids[i] = bytes32(uint256(uint160(all[offset + i])));
        }
    }

    // ------------------------------------------------------------------ internals
    /// @dev The pool `poolId` names, `UnknownPool` unless the Factory lists it.
    function _pool(bytes32 poolId) private view returns (IFLAMM pool) {
        uint256 word = uint256(poolId);
        if (word >> 160 != 0 || !FACTORY.isPool(address(uint160(word)))) revert UnknownPool();
        pool = IFLAMM(address(uint160(word)));
    }

    /// @dev The pool; any pair of two tokens is the pool's to quote or refuse. `BadPair` for a token paired with
    ///      itself.
    function _pair(bytes32 poolId, address sellToken, address buyToken) private view returns (IFLAMM pool) {
        pool = _pool(poolId);
        if (sellToken == buyToken) revert BadPair();
    }

    /// @dev Doubles a dust probe until the pool clips or refuses the fill, then bisects the refusal edge to within
    ///      1/1024. Zeros when even dust is refused.
    function _limits(IFLAMM pool, address sell, address buy) private view returns (uint256 maxIn, uint256 maxOut) {
        uint256 lo;
        uint256 hi;
        uint256 x = _probe(pool, sell);
        while (true) {
            (bool ok, uint256 used, uint256 out) = _preview(pool, sell, buy, x);
            if (ok) {
                (maxIn, maxOut, lo) = (used, out, x);
                if (used < x || x == LIMIT_PROBE) return (maxIn, maxOut);
            } else {
                if (lo == 0) return (0, 0);
                hi = x;
            }
            if (hi == 0) x = x * 2 < LIMIT_PROBE ? x * 2 : LIMIT_PROBE;
            else if (hi - lo <= lo / 1024) return (maxIn, maxOut);
            else x = (lo + hi) / 2;
        }
    }

    /// @dev `PROBE`, or about a dollar of the sell token at the pool's feed when that is more (capped at
    ///      `LIMIT_PROBE`), so a side whose `PROBE` is worth nothing still quotes: 1e6 wei of an 18-decimal asset sold
    ///      for USDC, or of WETH buying cbBTC.
    function _probe(IFLAMM pool, address sell) private view returns (uint256) {
        try pool.priceFeed() returns (address feed) {
            try IPriceFeed(feed).peekUsd(sell) returns (bool ok, uint256 usdWad, uint48) {
                if (ok && usdWad != 0) {
                    uint256 dollar = Math.mulDiv(1e18, 10 ** IERC20Metadata(sell).decimals(), usdWad, Math.Rounding.Up);
                    if (dollar > PROBE) return dollar < LIMIT_PROBE ? dollar : LIMIT_PROBE;
                }
            } catch {}
        } catch {}
        return PROBE;
    }

    /// @dev The pool's quote of `amountIn` of `sell` for `buy`, by their tokens; `ok` false where it refuses.
    function _preview(IFLAMM pool, address sell, address buy, uint256 amountIn)
        private
        view
        returns (bool ok, uint256 used, uint256 out)
    {
        try pool.previewSwap(sell, buy, amountIn) returns (uint256 u, uint256 o, uint256) {
            return (true, u, o);
        } catch {}
    }

    /// @dev `out / used`, or `0 / 1` where nothing was used.
    function _fraction(uint256 out, uint256 used) private pure returns (Fraction memory) {
        return used == 0 ? Fraction(0, 1) : Fraction(out, used);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/core/mm/MMRouterLib.sol": {
      "MMRouterLib": "0xA4749766934833DfBeaF4Fc0d79c150A1Dd2B4E5"
    },
    "src/core/flamm/FLAMMLane.sol": {
      "FLAMMLane": "0x0988077AB06F1efd8cFa3f08FC60CAf3e6d22e98"
    },
    "src/core/flamm/FLAMMRoute.sol": {
      "FLAMMRoute": "0x312ee92ecd113F925dD513d450b062C8740fDaA9"
    },
    "src/periphery/FLAMMMaxima.sol": {
      "FLAMMMaxima": "0x4A997343D91c981BF63274fc222AA96D32d6259c"
    },
    "src/core/flamm/FLAMMLawLib.sol": {
      "FLAMMLawLib": "0x5D473B15E032756Cd81fc66B8F1e9BE2f427cc62"
    },
    "src/core/flamm/FLAMMOpsLib.sol": {
      "FLAMMOpsLib": "0x0BFe60fB1f5223F1A2b7B02Ef18f5C33fb043753"
    },
    "src/core/mm/AaveV3ReadsLib.sol": {
      "AaveV3ReadsLib": "0xD53F6170226A74D453e84414Ffc2FFcE5ded5983"
    },
    "src/core/flamm/FLAMMFlowLib.sol": {
      "FLAMMFlowLib": "0x2577D707D41209489b2EF53101a4f6baDd4E3473"
    },
    "src/core/flamm/FLAMMGateLib.sol": {
      "FLAMMGateLib": "0xF0BE115A2D6F27274F2e9EE50B89Ed42db2B9555"
    },
    "src/core/flamm/FLAMMKeptLib.sol": {
      "FLAMMKeptLib": "0x7a11899232dd9F17c28bF062Ec2ee2267158517b"
    },
    "src/core/mm/CTokenMarketLib.sol": {
      "CTokenMarketLib": "0x18c53F2aCAbcDEEdb575A136f49fa4C43EB2071c"
    },
    "src/core/flamm/FLAMMAdmitLib.sol": {
      "FLAMMAdmitLib": "0xA6dBD8cD5Cd10F8a5857cbeD54a28405ffbDcBCb"
    },
    "src/core/flamm/FLAMMBlindLib.sol": {
      "FLAMMBlindLib": "0x0b8d436F1a7AE25C5d16955ed4CDa781E42e7E5C"
    },
    "src/core/flamm/FLAMMClaimLib.sol": {
      "FLAMMClaimLib": "0x02b4354a56630ab165A880B1198a603E62731cCE"
    },
    "src/core/flamm/FLAMMFenceLib.sol": {
      "FLAMMFenceLib": "0xA16ddA83f47a42F875f141b6954595D584a201e8"
    },
    "src/core/flamm/FLAMMFloatLib.sol": {
      "FLAMMFloatLib": "0x539EfC2b17cF0fdF254AAaB925b3A7c360A79737"
    },
    "src/core/flamm/FLAMMQuoteLib.sol": {
      "FLAMMQuoteLib": "0xa4D34f4882a529574840881e755BCFae2bd5ce2e"
    },
    "src/core/flamm/FLAMMTopUpLib.sol": {
      "FLAMMTopUpLib": "0x7C55a535Ce298b1e5e6d00F645088F777ad233DF"
    },
    "src/core/mm/CTokenRewardsLib.sol": {
      "CTokenRewardsLib": "0xcda63d7eCCF838F2732Bff676706BDE5abA4DcF7"
    },
    "src/core/mm/MMRouterAdminLib.sol": {
      "MMRouterAdminLib": "0x8423744b3F304ED0B43043d7ad4E7d8A247aDc96"
    },
    "src/core/flamm/FLAMMPolicyLib.sol": {
      "FLAMMPolicyLib": "0xa6B495B2BdcDcf4F327844d9aaA0eD4C550c67F9"
    },
    "src/core/flamm/FLAMMSettleLib.sol": {
      "FLAMMSettleLib": "0xB4890a27205505BDAA05717B6c3aB38b2dd3C7Cb"
    },
    "src/core/flamm/FLAMMSharedLib.sol": {
      "FLAMMSharedLib": "0xFaAEd38962aEb6c282Ac36E0cdE9313AbA2511ba"
    },
    "src/periphery/FLAMMExitMaxima.sol": {
      "FLAMMExitMaxima": "0x480f51866554e92649c9d3502bA31AA4234e0a81"
    },
    "src/hooks/everlong/LeverageLib.sol": {
      "LeverageLib": "0x1B1D1C42d26c169dB59D8681d0FD4C9a2840Ad11"
    },
    "src/core/flamm/FLAMMMaintainLib.sol": {
      "FLAMMMaintainLib": "0x94998f13fc5d5D2271c90b835c6a805dad409cC2"
    },
    "src/core/flamm/FLAMMPairQuoteLib.sol": {
      "FLAMMPairQuoteLib": "0x077523D1427aE408105fe8592F907ECDa0D94cbE"
    },
    "src/hooks/everlong/EverlongOpsLib.sol": {
      "EverlongOpsLib": "0xAbe4447C954E3C7a405f8E75116BF9f5787426F7"
    }
  },
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
    "solady/=lib/solady/src/",
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.