Tycho
  • Quickstart
  • Overview
  • Motivation
  • Concepts
  • How to Contribute
    • Bounties
  • For Solvers
    • Indexer
      • Tycho RPC
      • Tycho Client
        • Binary / CLI
        • Rust Client
        • Python Client
    • Simulation
    • Execution
      • Encoding
      • Executing
      • Contract Addresses
      • Execution Venues
    • Hosted Endpoints
    • Supported Protocols
  • For DEXs
    • Protocol Integration
      • Indexing
        • 1. Setup
        • 2. Implementation
        • 3. Testing
          • How to Run
        • Common Problems & Patterns
          • Tracking Components
          • Tracking Contract Storage
          • Normalizing relative ERC20 Balances
          • Tracking Contract Balances
          • Custom protobuf models
        • Best Practices
        • Reserved Attributes
      • Simulation
        • Ethereum: Solidity
      • Execution
        • Code Architecture
      • Contributing guidelines
Powered by GitBook
On this page
  • Run the Quickstart
  • What it does
  • How the Quickstart works
  • 1. Set up
  • 2. Connect to Tycho Indexer
  • 3. Simulate swap
  • 4. Encode a swap
  • 5. Simulate or execute the best swap
  • Recap
  • What's next?
Export as PDF

Quickstart

NextOverview

Last updated 20 days ago

A quickstart to swap onchain with Tycho. By the end of this quickstart, you will:

  • Fetch real-time market data from Tycho Indexer.

  • Simulate swaps between token pairs to calculate spot prices and output amounts using Tycho Simulation.

  • Encode the best trade, for a certain token pair, and simulate or execute it using Tycho Execution.

Want to chat with our docs? Download an LLM-friendly .

Run the Quickstart

Clone the ; you'll find code there.

To run the quickstart with execution, run the following commands:

export RPC_URL=https://ethereum.publicnode.com
export PK=<your-private-key>
cargo run --release --example quickstart -- --swapper-pk $PK
export RPC_URL=https://base-rpc.publicnode.com
export PK=<your-private-key>
cargo run --release --example quickstart -- --chain base --swapper-pk $PK
export RPC_URL=https://unichain-rpc.publicnode.com
export PK=<your-private-key>
cargo run --release --example quickstart -- --chain unichain --swapper-pk $PK

If you don't have an RPC URL, here's a list of public ones for , , and .

The --swapper-pk flag is not necessary if you would like to run the quickstart without simulation or execution.

What it does

The quickstart fetches all protocol states and returns you the best amount out (best price) for a given token pair (by default, 10 USDC to WETH).

Additionally, it returns calldata to execute the swap on this pool with the Tycho Router.

You should see an output like the following:

Looking for pool with best price for 10 USDC -> WETH

==================== Received block 14222319 ====================

The best swap (out of 6 possible pools) is:
Protocol: "uniswap_v3"
Pool address: "0x65081cb48d74a32e9ccfed75164b8c09972dbcf1"
Swap: 10.000000 USDC -> 0.006293 WETH 
Price: 0.000629 WETH per USDC, 1589.052587 USDC per WETH

Signer private key was not provided. Skipping simulation/execution...

If you would like to see the results for a different token, amount, or chain, you can set additional flags:

export TYCHO_URL=<tycho-api-url-for-chain>
export TYCHO_API_KEY=<tycho-api-key-for-chain>
cargo run --release --example quickstart -- --sell-token "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" --buy-token "0x4200000000000000000000000000000000000006" --sell-amount 10 --chain "base" --swapper-pk $PK

This example would look for the best swap for 10 USDC -> WETH on Base.

Logs

If you would like to see all the Tycho Indexer and Simulation logs run with RUST_LOG=info:

RUST_LOG=info cargo run --release --example quickstart --swapper-pk $PK

How the Quickstart works

The quickstart is a minimal example of how to:

  1. Setup and load necessary data (such as available tokens).

  2. Connect to the Tycho Indexer to fetch on-chain protocol data (e.g., Uniswap V2, Balancer V2) and build a Protocol Stream that streams updates (like new pools, states) in real-time.

  3. Simulate swaps on all available pools for a specified pair (e.g. USDC, WETH), and print out the most USDC you can get for 1 WETH.

  4. Encode a swap to swap 1 WETH against the best pool.

  5. Execute the swap against the Tycho Router.

1. Set up

To run Tycho Indexer, set up the following environment variables:

  • URL (by default "tycho-beta.propellerheads.xyz")

  • API key (by default, the test key is sampletoken)

  • TVL threshold: A filter to only get snapshot data for pools with TVL greater than the specified threshold (in ETH). Here, the default is 10,000 ETH to limit the data you pull.

The Indexer stream or the Simulation does not manage tokens; you must manage them.

To simplify this, load_all_tokens gets all current token information from Tycho Indexer RPC for you.

2. Connect to Tycho Indexer

The protocol stream connects to Tycho Indexer to fetch the real-time state of protocols.

let mut protocol_stream = ProtocolStreamBuilder::new(&tycho_url, Chain::Ethereum)
    .exchange::<UniswapV2State>("uniswap_v2", tvl_filter.clone(), None)
    .exchange::<EVMPoolState<PreCachedDB>>(
        "vm:balancer_v2",
        tvl_filter.clone(),
        Some(balancer_pool_filter),
    )
    .auth_key(Some(tycho_api_key.clone()))
    .set_tokens(all_tokens.clone())
    .await
    .build()
    .await
    .expect("Failed building protocol stream");

Here, you subscribe to Uniswap V2 and Balancer V2 only. To include additional protocols like Uniswap V3, simply add:

.exchange::<UniswapV3State>("uniswap_v3", tvl_filter.clone(), None)

Note: The protocol stream will supply all protocol states in the first BlockUpdate object. All subsequent BlockUpdates contain only new and changed protocol states (i.e., deltas).

3. Simulate swap

get_best_swap uses Tycho Simulation to simulate swaps and calculate buy amounts. We inspect all protocols updated in the current block (i.e. those with balance changes).

a. Simulating token swaps

let result = state.get_amount_out(amount_in, &tokens[0], &tokens[1])

result is a GetAmountOutResult that has information on the amount out, gas cost, and the new state of the protocol. For example, if you want to do another swap after this one, you could do

let other_result = result.new_state.get_amount_out(other_amount_in, &tokens[0], &tokens[1])

By inspecting each of the amount outs, we then choose the protocol component that gives us the highest amount out.

4. Encode a swap

After choosing the best swap, we can proceed to use Tycho Execution to encode it.

a. Create encoder

let encoder = EVMEncoderBuilder::new()
    .chain(Chain::Ethereum)
    .initialize_tycho_router_with_permit2(cli.swapper_pk.clone())
    .expect("Failed to create encoder builder")
    .build()
    .expect("Failed to build encoder");

b. Create a solution object

let simple_swap = Swap::new(
    protocol_component,
    sell_token.address.clone(),
    buy_token.address.clone(),
    // Split defines the fraction of the amount to be swapped.
    0f64,
);

// Then we create a solution object with the previous swap
let solution = Solution {
    sender: user_address.clone(),
    receiver: user_address,
    given_token: sell_token.address,
    given_amount: sell_amount,
    checked_token: buy_token.address,
    slippage: Some(0.0025), // 0.25% slippage
    expected_amount: Some(expected_amount),
    exact_out: false,     // it's an exact in solution
    checked_amount: None, // the amount out will not be checked in execution
    swaps: vec![simple_swap],
    router_address: Bytes::from_str("0x023eea66B260FA2E109B0764774837629cC41FeF")
        .expect("Failed to create router address"),
    ..Default::default()
};

c. Encode swap

let tx = encoder
    .encode_router_calldata(vec![solution])
    .expect("Failed to encode router calldata")[0];

5. Simulate or execute the best swap

This step allows you to test or perform real transactions based on the best available swap options. To be able to do this step, you need to pass your wallet's private key in the run command. Handle it securely and never expose it publicly.

cargo run --release --example quickstart -- --swapper-pk $PK

When you provide your private key, the quickstart will check your token balances and display them before showing you options:

Your balance: 100.000000 USDC
Your WETH balance: 1.500000 WETH

If you don't have enough tokens for the swap, you'll see a warning:

Your balance: 5.000000 USDC
⚠️ Warning: Insufficient balance for swap. You have 5.000000 USDC but need 10.000000 USDC
Your WETH balance: 1.500000 WETH

You'll then encounter the following prompt:

Would you like to simulate or execute this swap?
Please be aware that the market might move while you make your decision, which might lead to a revert if you've set a min amount out or slippage.
Warning: slippage is set to 0.25% during execution by default.

? What would you like to do? ›
❯ Simulate the swap
  Execute the swap
  Skip this swap

You have three options:

  1. Simulate the swap: Tests the swap without executing it on-chain. It will simulate an approval (for permit2) and a swap transaction on the node. You will see something similar to this:

Simulating by performing an approval (for permit2) and a swap transaction...

Simulated Block 21944458:
  Transaction 1: Status: true, Gas Used: 46098
  Transaction 2: Status: true, Gas Used: 182743

If status is false, the simulation has failed. You can print the full simulation output for detailed failure information.

  1. Execute the swap: Performs the swap on-chain using your real funds. The process involves performing an approval (for permit2) and a swap transaction. You'll receive transaction hashes and statuses like:

Executing by performing an approval (for permit2) and a swap transaction...

Approval transaction sent with hash: 0xf2a9217016397b09f5274e225754029ebda31743b4da7dd1441e13971e1f43b0 and status: true

Swap transaction sent with hash: 0x0b26c9965b4ee39b5646ab93070f018c027ac3d0c9d56548a6db4412be7abbc8 and status: true

✅ Swap executed successfully! Exiting the session...

Summary: Swapped 10.000000 USDC → 0.006293 WETH at a price of 0.000629 WETH per USDC

After a successful execution, the program will exit. If the transaction fails, the program will continue streaming new blocks.

  1. Skip this swap: Ignores this swap and the program resumes listening for blocks.

Market conditions can change rapidly. Delays in making your decision might lead to transaction reverts, especially if you've set parameters like minimum amount out or slippage. Always ensure you're comfortable with the potential risks before executing swaps.

Recap

In this quickstart, you explored how to use Tycho to:

  1. Connect to the Tycho Indexer: Retrieve real-time protocol data filtered by TVL.

  2. Fetch Token and Pool Data: Load all token details and process protocol updates.

  3. Simulate Token Swaps: Compute the output amount, gas cost, and updated protocol state for a swap.

  4. Encode a Swap: Create a solution from the best pool state and retrieve calldata to execute against a Tycho router.

  5. Execute a Swap: Execute the best trade using the Tycho Router.

What's next?

To dive deeper:

For a full list of supported protocols and which simulation state (like UniswapV3State) to use for them, see .

Knowing the best protocol component (i.e., pool), we can now put the swap into the expected input format for our encoder. For more info about the Swap and Solution models, please have a look .

Important Note

Integrate with your Solver: Add Tycho pool liquidity to your solver, starting from this .

Learn more about : Read more about the datatypes necessary to encode an execution against a Tycho router or executor.

Learn more about : Explore advanced features like custom filters, protocol-specific simulations, and state transitions.

Explore : To add or modify the data Tycho indexes.

⚠️
text file of the full Tycho docs
Tycho Simulation repository
the quickstart
Ethereum Mainnet
Unichain
Base
Supported Protocols
guide
Tycho Execution
Tycho Simulation
Tycho Indexer
here