LayerHopDocsLaunch app (opens in a new tab)

Node.js + viem: cross-chain swap script

A complete Node.js script that gets a LayerHop quote, builds the transaction, sends the ERC-20 approval and swap with viem, reports the hash and waits until the order is filled.

This recipe is a single TypeScript file for Node 20+ that performs a cross-chain swap from an EVM wallet with viem and the LayerHop REST API. It quotes, builds, approves, sends, reports and polls, with no SDK. It suits bots, treasury scripts and CI jobs where a key you control signs the transaction.

Warning

This script signs and broadcasts real transactions with PRIVATE_KEY. Try it first with an lh_test_ API key (test mode): test transactions are placeholders sent to a dead address, so the script refuses to broadcast when the response says livemode: false. Never commit keys.

What do I need first?#

  • Node 20 or newer and npm i viem tsx.
  • A funded EVM wallet. Set PRIVATE_KEY (hex) and optionally LAYERHOP_API_KEY.
  • A recipient on the destination chain: an EVM address, or a Solana address for a Solana destination.

1. Write the script#

TypeScript
// swap.ts  (run: npx tsx swap.ts)
import { createPublicClient, createWalletClient, erc20Abi, extractChain, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import * as chains from "viem/chains";

const API = process.env.LAYERHOP_API_URL ?? "https://api.layerhop.com/v1";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);

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

// 1. Quote: 100 USDC on Base to USDC on Arbitrum. Amounts are integer strings in base units.
const qs = new URLSearchParams({
  srcChain: "base", srcToken: "USDC", amount: "100000000",
  dstChain: "arbitrum", dstToken: "USDC",
  sender: account.address, recipient: account.address, slippageBps: "50",
});
const { best } = await lh<{ best: any }>(`quote?${qs}`);
console.log(`via ${best.provider}: receive >= ${best.dstAmountMin} in ~${best.estimatedSeconds}s, LayerHop fee ${best.fees.ourFeeBps} bps`);

// 2. Build the transaction right before sending.
const built = await lh<{ tx: any; livemode?: boolean }>("orders", { method: "POST", body: JSON.stringify({ quoteId: best.quoteId }) });
if (built.livemode === false) throw new Error("Test-mode transaction: do not broadcast");
const tx = built.tx;
if (tx.vm !== "evm") throw new Error("This script handles EVM source transactions only");

// 3. viem clients on the transaction's chain.
const chain = extractChain({ chains: Object.values(chains) as any, id: tx.chainId });
const pub = createPublicClient({ chain, transport: http() });
const wallet = createWalletClient({ account, chain, transport: http() });

// 4. ERC-20 approval first, only when the allowance is short.
if (tx.approval) {
  const { token, spender, amount } = tx.approval;
  const allowance = await pub.readContract({ address: token, abi: erc20Abi, functionName: "allowance", args: [account.address, spender] });
  if (allowance < BigInt(amount)) {
    const approveHash = await wallet.writeContract({ address: token, abi: erc20Abi, functionName: "approve", args: [spender, BigInt(amount)] });
    await pub.waitForTransactionReceipt({ hash: approveHash });
    console.log("approved", approveHash);
  }
}

// 5. Optional: dry-run with eth_call before spending gas (throws if it would revert).
await pub.call({ account, to: tx.to, data: tx.data, value: BigInt(tx.value) });

// 6. Send, then report so LayerHop tracks the order.
const hash = await wallet.sendTransaction({ to: tx.to, data: tx.data, value: BigInt(tx.value) });
console.log("sent", hash);
await lh(`orders/${best.quoteId}/submitted`, { method: "POST", body: JSON.stringify({ txHash: hash }) });

// 7. Poll until the order is final.
const final = new Set(["filled", "refunded", "failed", "dropped"]);
for (;;) {
  const s = await lh<{ state: string; dstTxHash?: string }>(`orders/${best.provider}/${hash}`);
  console.log(s.state, s.dstTxHash ?? "");
  if (final.has(s.state)) break;
  await new Promise((r) => setTimeout(r, 3000));
}

How does it work?#

The script makes the same calls as the Quickstart: GET /v1/quote, POST /v1/orders, the wallet's approval and swap, POST /v1/orders/{quoteId}/submitted and GET /v1/orders/{provider}/{id}. fees.ourFeeBps is LayerHop's fee and dstAmountMin is the minimum after slippage. For a hosted dry run instead of eth_call, see Simulation.

How do I handle an expired quote?#

Quotes expire 30 to 60 seconds after they are made (expiresAt, unix seconds). If building or sending is slow, the API answers QUOTE_EXPIRED: request a new quote and build again. Retry only PROVIDER_ERROR, PROVIDER_TIMEOUT and INTERNAL, with backoff. See Error handling.

How do I do this from Solana?#

For a Solana source, tx.vm is svm and tx.serializedTx is a base64 VersionedTransaction to sign with @solana/web3.js. See Solana to EVM and The submitViaApi flow.

Can I use the SDK instead?#

Yes. @layerhop/sdk replaces the lh() helper with lh.quote, lh.buildTx, lh.reportSubmitted and lh.watch (SDK reference).

Next: Next.js + wagmi, Python, API reference.

Last updated