Relatick
Integrate

End-to-end example

One TypeScript script from pool discovery to a confirmed swap.

This example swaps 1,000 USDC for USDT on Ethereum in five steps: find the pools, ask the API for a route, turn the route into a router call, check it, and send it. It uses the API for discovery and routing and the SDK to build the transaction.

No API key is needed for the calls below.

Before you start

npm install @metric.xyz/metric-omm-sdk-v1 viem

You need an RPC URL and a funded account on the chain you trade on.

The script

import { createPublicClient, createWalletClient, erc20Abi, http, maxUint256 } from "viem";
import { mainnet } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
import {
  ChainId,
  getAddressesOrThrow,
  prepareExactInputFromRoute,
  encodeExactInputSingleCalldata,
  encodeExactInputCalldata,
} from "@metric.xyz/metric-omm-sdk-v1";

const API = "https://api.metric.xyz/public/v1";
const CHAIN_ID = ChainId.ETHEREUM; // 1

const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
const USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
const AMOUNT_IN = 1_000_000_000n; // 1,000 USDC (6 decimals)
const SLIPPAGE_PERCENT = 0.5;

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const publicClient = createPublicClient({ chain: mainnet, transport: http(process.env.RPC_URL) });
const walletClient = createWalletClient({ account, chain: mainnet, transport: http(process.env.RPC_URL) });
const addresses = getAddressesOrThrow(CHAIN_ID);

async function main() {
  // 1. Discover pools. Route only to pools that are healthy and not paused.
  //    The list is paginated; this reads the first page. pauseLevel is left out when a pool isn't paused.
  const metadata = await fetch(`${API}/evm/${CHAIN_ID}/metadata`).then((r) => r.json());
  const tradable = metadata.data.filter(
    (p: any) => p.priceProviderStatus === "healthy" && (p.pauseLevel ?? 0) === 0,
  );
  console.log(`${tradable.length} tradable pools on the first page`);

  // 2. Ask for a route. maxRoutes: 1 returns a single path, which is what the SDK executes.
  const route = await fetch(`${API}/evm/${CHAIN_ID}/route`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      tokenIn: USDC,
      tokenOut: USDT,
      amountIn: AMOUNT_IN.toString(),
      maxRoutes: 1,
    }),
  }).then((r) => r.json());
  if (!route.routes?.length) throw new Error("No route found");
  console.log(`Route: ${route.routes[0].routeType}, expected out ${route.amountOut}`);

  // 3. Turn the route into router parameters. The minimum output is set from your slippage tolerance.
  const prepared = await prepareExactInputFromRoute({
    publicClient,
    route,
    recipient: account.address,
    deadline: BigInt(Math.floor(Date.now() / 1000) + 1200),
    slippagePercent: SLIPPAGE_PERCENT,
  });
  const data =
    prepared.kind === "single"
      ? encodeExactInputSingleCalldata(prepared.params)
      : encodeExactInputCalldata(prepared.params);

  // 4. Approve the router if needed, then simulate the exact transaction from your own address.
  const allowance = await publicClient.readContract({
    address: USDC,
    abi: erc20Abi,
    functionName: "allowance",
    args: [account.address, addresses.simpleRouter],
  });
  if (allowance < AMOUNT_IN) {
    const approveHash = await walletClient.writeContract({
      address: USDC,
      abi: erc20Abi,
      functionName: "approve",
      args: [addresses.simpleRouter, maxUint256],
    });
    await publicClient.waitForTransactionReceipt({ hash: approveHash });
  }
  await publicClient.call({ account: account.address, to: addresses.simpleRouter, data }); // throws if the swap would revert

  // 5. Send it.
  const hash = await walletClient.sendTransaction({ to: addresses.simpleRouter, data });
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
  console.log(`Swap ${receipt.status}: ${hash}`);
}

main();

What the route response looks like

The fields the script relies on, from a real response:

{
  "tradeType": "exact_in",
  "amountIn": "1000000000",
  "amountOut": "1001110769",
  "routes": [
    {
      "routeType": "direct",
      "amountIn": "1000000000",
      "amountOut": "1001110769",
      "legs": [
        {
          "poolAddress": "0xaef2ad7aBB651945e6D24276715f25BDED0ad41e",
          "pair": "USDC/USDT",
          "zeroForOne": true,
          "tokenIn": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
          "tokenOut": "0xdac17f958d2ee523a2206206994597c13d831ec7",
          "amountIn": "1000000000",
          "amountOut": "1001110769",
          "priceLimitX64": "0"
        }
      ]
    }
  ]
}

Full field list: Find best route.

What to watch for

  • Each leg's priceLimitX64 is the no-limit value (0 or the maximum, depending on direction). Your protection is the minimum output, which the SDK sets from slippagePercent.
  • The route is an estimate from a depth snapshot. The simulation in step 4 is what tells you whether the swap will go through, including checks made by a pool's extensions.
  • Simulate with your real address. Some pools allow only certain callers, and a simulation from another address can pass where yours would fail.
  • Pairs that depend on price updates, such as WETH/USDC on Ethereum. Their fresh price lands in the same block as the trade, so the simulation in step 4 reverts between trades even though the swap can succeed when sent through a participating builder. This example uses a stablecoin pair, which doesn't have that constraint. For the others, see Freshness and ordering.
  • Split routes. With maxRoutes above 1 the API can split the order across paths. The SDK's route helpers execute a single path, so keep maxRoutes: 1 or execute each path yourself.
  • Native ETH. Request the route with the wrapped token, then use the SDK's native-payment or unwrap helpers. See the SDK page.
  • If it reverts: Why a swap reverts.

Last updated 29 days ago