LayerHopDocsLaunch app (opens in a new tab)

Next.js + wagmi: cross-chain swap recipe

Complete Next.js App Router and wagmi/viem recipe for a cross-chain swap with the LayerHop API, from quote to ERC-20 approval, transaction, order report and status polling.

This recipe adds a working cross-chain swap to a Next.js App Router app that already uses wagmi and viem. The browser asks the LayerHop API for a quote (GET /v1/quote), builds the transaction (POST /v1/orders), sends the ERC-20 approval and the swap with the user's wallet, reports the hash (POST /v1/orders/{quoteId}/submitted) and polls GET /v1/orders/{provider}/{id} until the order is final. LayerHop never holds keys: the wallet signs everything.

What do I need first?#

  • Next.js 14 or 15 (App Router), wagmi v2 and viem v2, with WagmiProvider and a connector already set up.
  • An EVM source chain. This recipe sends from EVM; for a Solana source see the Solana to EVM guide.
  • Optional: an API key from the dashboard, kept on the server. Without a key the API limits requests per IP.
  • While developing, use an lh_test_ key and test mode: its transactions are placeholders, never broadcast them.

1. Proxy the API from a route handler#

Calling the API through your own route keeps the API key out of the browser. Only the paths this recipe needs are allowed.

TypeScript
// app/api/lh/[...path]/route.ts
const API = "https://api.layerhop.com/v1";
const ALLOWED = /^(quote|orders|orders\/[^/]+\/submitted|orders\/[^/]+\/[^/]+)$/;

async function forward(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
  const path = (await params).path.join("/");
  if (!ALLOWED.test(path)) return Response.json({ error: { code: "NOT_FOUND", message: "Not allowed" } }, { status: 404 });
  const headers: Record<string, string> = { "content-type": "application/json" };
  if (process.env.LAYERHOP_API_KEY) headers["x-api-key"] = process.env.LAYERHOP_API_KEY;
  const res = await fetch(`${API}/${path}${new URL(req.url).search}`, {
    method: req.method,
    headers,
    body: req.method === "GET" ? undefined : await req.text(),
  });
  return new Response(await res.text(), { status: res.status, headers: { "content-type": "application/json" } });
}

export const GET = forward;
export const POST = forward;

2. Write the swap component#

TSX
// components/Swap.tsx
"use client";
import { useState } from "react";
import { erc20Abi } from "viem";
import { useAccount, useChainId, usePublicClient, useSendTransaction, useSwitchChain, useWriteContract } from "wagmi";

type Quote = {
  quoteId: string;
  provider: string;
  dstAmount: string;
  dstAmountMin: string;
  estimatedSeconds: number;
  expiresAt: number; // unix seconds
  fees: { ourFeeBps: number };
};
type EvmTx = {
  vm: "evm";
  chainId: number;
  to: `0x${string}`;
  data: `0x${string}`;
  value: string;
  approval?: { token: `0x${string}`; spender: `0x${string}`; amount: string };
};

async function lh<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`/api/lh/${path}`, { ...init, headers: { "content-type": "application/json" } });
  const body = await res.json();
  if (!res.ok) throw new Error(`${body.error?.code ?? res.status}: ${body.error?.message ?? "request failed"}`);
  return body as T;
}

export function Swap({ recipient }: { recipient: string }) {
  const { address } = useAccount();
  const chainId = useChainId();
  const pub = usePublicClient();
  const { switchChainAsync } = useSwitchChain();
  const { sendTransactionAsync } = useSendTransaction();
  const { writeContractAsync } = useWriteContract();
  const [quote, setQuote] = useState<Quote>();
  const [log, setLog] = useState<string[]>([]);
  const say = (m: string) => setLog((l) => [...l, m]);

  async function getQuote() {
    // 100 USDC on Base to SOL on Solana. Amounts are integer strings in base units (USDC has 6 decimals).
    const qs = new URLSearchParams({
      srcChain: "base", srcToken: "USDC", amount: "100000000",
      dstChain: "solana", dstToken: "SOL",
      sender: address!, recipient, slippageBps: "50",
    });
    const { best } = await lh<{ best: Quote }>(`quote?${qs}`);
    setQuote(best);
  }

  async function execute() {
    if (!quote || !address) return;
    if (quote.expiresAt * 1000 < Date.now()) return say("Quote expired, get a new one.");

    // Build right before signing: some providers expect the transaction on chain within ~30 s.
    const { tx } = await lh<{ tx: EvmTx }>("orders", { method: "POST", body: JSON.stringify({ quoteId: quote.quoteId }) });
    if (tx.vm !== "evm") throw new Error("This recipe handles EVM source transactions");
    if (chainId !== tx.chainId) await switchChainAsync({ chainId: tx.chainId });

    if (tx.approval) {
      const { token, spender, amount } = tx.approval;
      const allowance = await pub!.readContract({ address: token, abi: erc20Abi, functionName: "allowance", args: [address, spender] });
      if (allowance < BigInt(amount)) {
        say("Approve the token in your wallet...");
        const approveHash = await writeContractAsync({ address: token, abi: erc20Abi, functionName: "approve", args: [spender, BigInt(amount)] });
        await pub!.waitForTransactionReceipt({ hash: approveHash });
      }
    }

    say("Confirm the swap in your wallet...");
    const hash = await sendTransactionAsync({ to: tx.to, data: tx.data, value: BigInt(tx.value) });
    say(`Sent ${hash}`);

    await lh(`orders/${quote.quoteId}/submitted`, { method: "POST", body: JSON.stringify({ txHash: hash }) });
    await track(quote.provider, hash);
  }

  async function track(provider: string, id: string) {
    const final = new Set(["filled", "refunded", "failed", "dropped"]);
    let last = "";
    for (let i = 0; i < 600; i++) {
      const s = await lh<{ state: string; dstTxHash?: string }>(`orders/${provider}/${id}`);
      if (s.state !== last) { last = s.state; say(`${s.state}${s.dstTxHash ? ` (${s.dstTxHash})` : ""}`); }
      if (final.has(s.state)) return;
      await new Promise((r) => setTimeout(r, 3000));
    }
  }

  return (
    <div>
      <button onClick={getQuote} disabled={!address}>Quote 100 USDC to SOL</button>
      {quote && <p>Receive about {quote.dstAmount} (min {quote.dstAmountMin}) base units in ~{quote.estimatedSeconds}s via {quote.provider}</p>}
      {quote && <button onClick={execute}>Swap</button>}
      <pre>{log.join("\n")}</pre>
    </div>
  );
}

Render it from any page, for example <Swap recipient="9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM" />.

How does it work?#

  1. GET /v1/quote fans out to every provider and returns best plus the other quotes, each with its own quoteId, dstAmount, dstAmountMin, fees and expiresAt (reference).
  2. POST /v1/orders with { "quoteId" } returns tx. On EVM it is { vm, chainId, to, data, value, approval? } (reference). If approval is present, the user approves spender for amount first (Approvals).
  3. The user's wallet sends the transaction. POST /v1/orders/{quoteId}/submitted with { "txHash" } starts server-side tracking and lets webhooks fire (reference).
  4. GET /v1/orders/{provider}/{id} returns state: pending, then filled, refunded, failed or dropped. For cross-chain providers pass the source transaction hash as id (Order tracking).

Errors have a stable code such as QUOTE_EXPIRED or NO_ROUTE; see Error handling.

Can I use the TypeScript SDK instead of fetch?#

Yes. @layerhop/sdk wraps the same endpoints (lh.quote, lh.buildTx, lh.reportSubmitted, lh.watch) and has no dependencies. The Quickstart shows the identical flow with it. Use the SDK in server code and keep the route handler above for the browser.

Should the API key go in the browser?#

No. A key in client code is public. Keep it in the route handler as shown, or omit it and accept the per-IP limit while you build. Keys identify your orders for webhooks and your partner fee.

Does LayerHop ever sign or send the transaction?#

No. LayerHop returns an unsigned transaction and the user's own wallet signs and broadcasts it. See Non-custodial by design.

Next: API reference, Node.js + viem script, Webhook receiver.

Last updated