Page cover

DEX Integration

JuliaOS provides comprehensive functionality for interacting with Decentralized Exchanges (DEXes) across multiple blockchain networks, enabling sophisticated trading strategies for agents and swarms.

Concept

Decentralized Exchanges (DEXes) allow users to trade cryptocurrency assets directly on the blockchain without relying on a centralized intermediary. They typically use one of several models:

  • Automated Market Maker (AMM): Uses liquidity pools and mathematical formulas to determine prices (e.g., Uniswap, SushiSwap)

  • Order Book: Matches buy and sell orders similar to traditional exchanges (e.g., Serum)

  • Hybrid Models: Combines elements of AMMs and order books (e.g., Raydium)

  • Aggregators: Routes trades across multiple DEXes for optimal execution (e.g., 1inch, Jupiter)

Functionality in JuliaOS (DEX.jl)

The core DEX logic resides in the Julia backend module /julia/src/DEX.jl. Its main capabilities include:

  • Listing Supported DEXes: Identifying which DEXes are configured for specific chains

  • Getting Swap Quotes: Calculating the expected output amount for a potential swap, considering available liquidity and fees

  • Encoding Swap Data: Generating the correct calldata needed to execute a swap transaction on a specific DEX contract

  • Preparing Unsigned Transactions: Combining the quote, encoded data, nonce, gas estimates, etc., into a complete, unsigned transaction object

  • Routing: Finding the optimal path for trades across multiple DEXes and liquidity pools

  • Price Impact Calculation: Estimating the price impact of trades to avoid excessive slippage

  • Historical Data: Retrieving historical swap data for analysis and strategy development

Important: The DEX.jl module prepares swap transactions but does not sign or send them. Signing is handled client-side (see Wallets and Architecture Overview).

Supported DEXes

JuliaOS supports a wide range of DEXes across multiple blockchain networks:

Ethereum and EVM-Compatible Chains

  • Uniswap V2 & V3: The leading AMM on Ethereum with concentrated liquidity in V3

    • Implementation: Full support for quotes, routing, and transaction preparation

    • Features: Multi-hop routing, concentrated liquidity positions, fee tiers

    • Chains: Ethereum, Polygon, Arbitrum, Optimism, Base

  • SushiSwap: Fork of Uniswap V2 with additional features

    • Implementation: Full support for quotes and transaction preparation

    • Features: Multi-hop routing, farming integrations

    • Chains: Ethereum, Polygon, Arbitrum, Optimism, Avalanche, Fantom, BSC

  • Curve Finance: Specialized AMM for stablecoin and similar-asset swaps

    • Implementation: Full support for stablecoin pools

    • Features: Low slippage for stablecoin trades, metapools

    • Chains: Ethereum, Polygon, Arbitrum, Optimism, Avalanche, Fantom

  • Balancer: AMM with customizable multi-token pools

    • Implementation: Support for weighted pools and stable pools

    • Features: Multi-token pools, custom weights

    • Chains: Ethereum, Polygon, Arbitrum, Optimism, Avalanche

  • PancakeSwap: Leading DEX on BNB Chain

    • Implementation: Full support for quotes and transaction preparation

    • Features: Multi-hop routing, farming integrations

    • Chains: BSC, Ethereum, Arbitrum

  • Trader Joe: Leading DEX on Avalanche

    • Implementation: Full support for quotes and transaction preparation

    • Features: Multi-hop routing, farming integrations

    • Chains: Avalanche, Arbitrum

  • SpookySwap: Leading DEX on Fantom

    • Implementation: Full support for quotes and transaction preparation

    • Features: Multi-hop routing, farming integrations

    • Chains: Fantom

  • QuickSwap: Leading DEX on Polygon

    • Implementation: Full support for quotes and transaction preparation

    • Features: Multi-hop routing, farming integrations

    • Chains: Polygon

Solana

  • Raydium: Leading AMM on Solana with order book integration

    • Implementation: Full support for quotes and transaction preparation

    • Features: AMM pools, concentrated liquidity, order book integration

    • Chains: Solana

  • Orca: AMM on Solana with concentrated liquidity

    • Implementation: Full support for quotes and transaction preparation

    • Features: Concentrated liquidity, whirlpools

    • Chains: Solana

  • Saber: Specialized AMM for stablecoin and wrapped asset swaps

    • Implementation: Support for stablecoin and wrapped asset pools

    • Features: Low slippage for similar-asset trades

    • Chains: Solana

Aggregators

  • 1inch: Leading DEX aggregator for EVM chains

    • Implementation: API integration for optimal routing across multiple DEXes

    • Features: Split routes, gas optimization, MEV protection

    • Chains: Ethereum, Polygon, Arbitrum, Optimism, Avalanche, Fantom, BSC

  • Jupiter: Leading DEX aggregator for Solana

    • Implementation: API integration for optimal routing across Solana DEXes

    • Features: Split routes, slippage protection

    • Chains: Solana

  • Paraswap: DEX aggregator with MEV protection

    • Implementation: API integration for optimal routing

    • Features: MEV protection, multi-path routing

    • Chains: Ethereum, Polygon, Arbitrum, Optimism, Avalanche, BSC

  • 0x Protocol: DEX aggregator and infrastructure

    • Implementation: API integration for quotes and routing

    • Features: RFQ system, professional market makers

    • Chains: Ethereum, Polygon, Arbitrum, Optimism, Avalanche, BSC

Advanced Features

Smart Routing

JuliaOS implements smart routing algorithms to find the optimal path for trades:

  • Multi-DEX Routing: Routes trades across multiple DEXes to find the best price

  • Multi-Hop Routing: Executes trades through intermediate tokens for better rates

  • Split Routing: Splits trades across multiple pools to minimize price impact

  • Gas-Aware Routing: Considers gas costs when determining the optimal route

Price Impact Protection

To protect users from excessive slippage, JuliaOS includes:

  • Price Impact Estimation: Calculates the expected price impact before execution

  • Slippage Tolerance: Configurable slippage tolerance for trades

  • Minimum Output: Enforces a minimum output amount for trades

Trading Analytics

JuliaOS provides analytics capabilities for DEX trading:

  • Historical Data: Retrieves historical swap data for analysis

  • Volume Analysis: Analyzes trading volume across DEXes and pools

  • Liquidity Analysis: Evaluates liquidity depth in pools

  • Gas Cost Analysis: Tracks gas costs for different DEXes and routes

Using DEX Features

From Julia Backend

using JuliaOS.DEX

# Get a quote for swapping ETH to USDC on Uniswap V3
quote = DEX.get_quote(
    "ethereum",      # Chain
    "uniswap_v3",    # DEX
    "ETH",           # Input token
    "USDC",          # Output token
    1.0,             # Input amount (1 ETH)
    0.005            # Max slippage (0.5%)
)

# Prepare an unsigned swap transaction
tx = DEX.execute_swap(
    "ethereum",      # Chain
    "uniswap_v3",    # DEX
    "ETH",           # Input token
    "USDC",          # Output token
    1.0,             # Input amount
    quote.min_output, # Minimum output amount
    "0x123..."       # Recipient address
)

From TypeScript Framework

import { JuliaBridge } from '@juliaos/julia-bridge';
import { DEX } from '@juliaos/framework';

// Initialize the bridge
const bridge = new JuliaBridge({ host: 'localhost', port: 8052 });
await bridge.initialize();

// Create the DEX module
const dex = new DEX(bridge);

// Get a quote
const quote = await dex.getQuote({
  chain: 'ethereum',
  dex: 'uniswap_v3',
  inputToken: 'ETH',
  outputToken: 'USDC',
  inputAmount: 1.0,
  maxSlippage: 0.005
});

// Execute a swap (returns unsigned transaction)
const tx = await dex.executeSwap({
  chain: 'ethereum',
  dex: 'uniswap_v3',
  inputToken: 'ETH',
  outputToken: 'USDC',
  inputAmount: 1.0,
  minOutputAmount: quote.minOutput,
  recipient: '0x123...'
});

From Python Wrapper

import asyncio
from juliaos import JuliaOS

async def dex_example():
    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Get a quote
    quote = await juliaos_client.dex.get_quote(
        chain="ethereum",
        dex="uniswap_v3",
        input_token="ETH",
        output_token="USDC",
        input_amount=1.0,
        max_slippage=0.005
    )

    # Execute a swap (returns unsigned transaction)
    tx = await juliaos_client.dex.execute_swap(
        chain="ethereum",
        dex="uniswap_v3",
        input_token="ETH",
        output_token="USDC",
        input_amount=1.0,
        min_output_amount=quote["min_output"],
        recipient="0x123..."
    )

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

From Trading Agents

Trading agents can use DEX functionality through their specialized methods:

import asyncio
from juliaos import JuliaOS
from juliaos.agents.specialized import TradingAgent

async def trading_agent_example():
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create a trading agent
    trading_agent = await TradingAgent.create(
        juliaos_client,
        name="MyTradingAgent",
        risk_level="medium",
        max_position_size=1000.0
    )

    # Execute a trade using the agent
    trade_result = await trading_agent.execute_trade(
        pair="ETH/USDC",
        side="buy",
        amount=1.0,
        max_slippage=0.005
    )

Integration Flow

The typical flow for DEX interactions in JuliaOS:

  1. Request: Agent, swarm, or user initiates a trade request

  2. Routing: DEX.jl determines the optimal route across DEXes

  3. Quoting: DEX.jl gets quotes from the selected DEX(es)

  4. Transaction Preparation: DEX.jl prepares an unsigned transaction

  5. Signing: Client-side wallet signs the transaction

  6. Submission: Signed transaction is submitted to the blockchain

  7. Confirmation: Transaction is confirmed and results are recorded

See:

  • Swap Execution Flow in DEX API

  • Bridge API (Backend)