# SDK reference

> The @layerhop/sdk TypeScript client reference — options, quote, simulate, buildTx, submit, reportSubmitted, status, watch, listOrders, chains, tokens, prices, balances, checkout, invoices, refunds, deposit addresses, types and errors.

Source: https://docs.layerhop.com/sdk

`@layerhop/sdk` is the typed TypeScript client for the LayerHop [REST API](/api-reference): create a `LayerHop` client, call `quote()`, `buildTx()` and `reportSubmitted()`, and track the order with `watch()`. It has no runtime dependencies (the chain and token registry and the types are bundled in), uses the global `fetch`, and works in Node 20+, browsers, edge runtimes and [React Native](/sdks/react-native).

Install it from npm with `npm install @layerhop/sdk` (or `pnpm add` / `yarn add`). The API it wraps is live at `https://api.layerhop.com/v1`.

## Which methods does the SDK have?

| Method | Endpoint | Returns |
|---|---|---|
| [`chains()`](#chains) | `GET /v1/chains` | Every routable chain |
| [`tokens(params)`](#tokensparams) | `GET /v1/tokens` | A page of tokens on a chain |
| [`lookupToken(chain, address)`](#lookuptokenchain-address) | `GET /v1/tokens/lookup` | One token's metadata (`lookupToken(address)` finds the chain) |
| [`prices(ids)`](#pricesids) | `GET /v1/prices` | USD prices |
| [`balances(address, chains?, opts?)`](#balancesaddress-chains-opts) | `GET /v1/balances` | A wallet's non-zero balances, plus any tokens you name |
| [`quote(params)`](#quoteparams) | `GET /v1/quote` | Ranked quotes from every provider |
| [`simulate(quoteId)`](#simulatequoteid) | `POST /v1/simulate` | A dry run of the transaction |
| [`buildTx(quoteId)`](#buildtxquoteid) | `POST /v1/orders` | The unsigned transaction |
| [`submit(quoteId, signedTransaction)`](#submitquoteid-signedtransaction) | `POST /v1/orders/submit` | Solana signature (`submitViaApi` only) |
| [`reportSubmitted(quoteId, txHash)`](#reportsubmittedquoteid-txhash) | `POST /v1/orders/{quoteId}/submitted` | The order's lifecycle status |
| [`status(provider, id)`](#statusprovider-id) | `GET /v1/orders/{provider}/{id}` | Provider order state |
| [`watch(provider, id, options?)`](#watchprovider-id-options) | polls `status()` | An async iterator of state changes |
| `streamOrder(quoteId, { signal }?)` | `GET /v1/orders/{quoteId}/events` (SSE) | An async iterator of `OrderSummary` until final. See [Live order status](/guides/live-status) |
| `quotes.stream(params, { intervalMs, signal }?)` | `GET /v1/quote/stream` (SSE) | An async iterator of fresh quote sets (`seq` + a `quote()` response) whenever the best route or an amount changes. See [Live quotes](/guides/live-quotes) |
| `screen(addresses)` | `POST /v1/screen` | OFAC SDN screening results. See [Address screening](/guides/address-screening) |
| `checkout.create / get / list / expire / quote / stream` | `/v1/checkout/sessions…` | [Checkout](/guides/checkout) sessions, quotes and a live session stream |
| `checkout.products.create / get / list / update / startSession` | `/v1/checkout/products…` | [Payment button](/guides/payment-buttons) products |
| [`checkout.refunds.create(sessionId, params?)`, `.list(sessionId)`](#checkoutrefunds) | `/v1/checkout/sessions/{id}/refunds` | [Refunds](/guides/refunds) of paid sessions |
| [`invoices.create / get / list / update / send / void / publicView / pay`](#invoices) | `/v1/invoices…` | [Invoices](/guides/invoices) |
| [`depositAddresses.create / get / list / refresh / disable / simulate`](#depositaddresses) | `/v1/deposit-addresses…` | [Deposit addresses](/guides/deposit-addresses) |
| [`serviceStatus()`](#servicestatus) | `GET /v1/status` | Platform status ([status.layerhop.com](/guides/status-and-monitoring)) |
| `webhooks.stream({ signal, since }?)`, `webhooks.trigger(type)`, `webhooks.resend(eventId, { endpointId }?)` | `GET /v1/webhooks/stream`, `POST /v1/webhooks/trigger`, `POST /v1/webhooks/events/{id}/resend` | Your account's webhook events live (`since` replays missed ones); sample events in test mode; send an event again |
| `usage.get({ bucket, from, to, keyId }?)`, `usage.errors({ code, keyId, limit }?)` | `GET /v1/usage`, `GET /v1/usage/errors` | Your key's account usage: requests by endpoint group and status class, p50 / p95 latency, error codes, recent errors |
| [`listOrders(params)`](#listordersparams) | `GET /v1/orders` | Orders by address |
| `buildGasless(quoteId)`, `submitGasless(quoteId, signatures)`, `gaslessStatus(quoteId)` | `POST /v1/orders`, `POST /v1/orders/gasless`, `GET /v1/orders/gasless/{quoteId}` | [Gasless swaps](/guides/gasless-swaps): typed data to sign, the signatures, the order state |
| `limitOrders.create / submit / get / list / cancel / simulate` | `/v1/limit-orders…` | [Solana limit orders](/guides/limit-and-recurring-orders) |
| `recurringOrders.create / submit / list / cancel` | `/v1/recurring-orders…` | [Solana recurring buys](/guides/limit-and-recurring-orders) |
| [`getTokenRisk(chain, address)`](#gettokenriskchain-address) | `GET /v1/tokens/{chain}/{address}/risk` | A token's safety report |
| [`createSplit / getSplit / updateSplit`](#splits-tip-jars-and-payouts) | `/v1/splits…` | [Split bills](/guides/split-the-bill) |
| [`getTipJar(address)`](#splits-tip-jars-and-payouts) | `GET /v1/tip-jars/{address}` | [Tip jar](/guides/tip-jar) counters and messages |
| [`planPayouts(params)`, `buildPayoutTransfers(params)`](#splits-tip-jars-and-payouts) | `POST /v1/payouts/plan`, `POST /v1/payouts/transfers` | [Bulk payouts](/guides/bulk-payouts): checked and grouped rows; a transfer batch to sign |

## new LayerHop(options?)

```ts
import { LayerHop } from "@layerhop/sdk";

const lh = new LayerHop({
  apiKey: process.env.LAYERHOP_API_KEY, // optional, lh_live_…
  channel: "api",
});
```

| Option | Type | Default | Description |
|---|---|---|---|
| `baseUrl` | `string` | `https://api.layerhop.com` | API origin, without `/v1`. A trailing slash is removed. |
| `apiKey` | `string` | — | Sent as the `x-api-key` header. Optional: without it, requests are rate-limited per IP. Create keys in the [dashboard](/guides/dashboard-and-api-keys); a key whose account is an active partner also selects your [partner fee](/guides/partner-fees). |
| `channel` | `"api" \| "web" \| "widget" \| "bot"` | `"api"` | [Fee channel](/concepts/fees-and-channels) sent with every quote. `api` is 0.10%. |
| `integrator` | `string` | — | Your partner id, sent as `integrator` on every quote to earn your [partner fee](/guides/partner-fees). |
| `integratorFeeBps` | `number` | — | Per-request partner fee. Honored only with a partner `apiKey`, up to your `maxFeeBps`. |
| `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (tests, proxies, retries). |
| `streaming` | `"auto" \| "fetch" \| "xhr"` | `"auto"` | How SSE streams are read. `auto` uses `fetch` where it can stream and `XMLHttpRequest` otherwise ([React Native](/sdks/react-native)). With a custom `fetch`, `fetch` is always used. |

## quote(params)

Calls [`GET /v1/quote`](/api-reference#get-quotes). Returns every successful quote, best for the user first.

```ts
quote(p: QuoteParams): Promise<QuoteResponse>
```

| Param | Type | Description |
|---|---|---|
| `srcChain` | `string \| number` | Chain id or slug, e.g. `"base"`, `8453`. |
| `srcToken` | `string` | Symbol from the [token list](/chains) or address / mint. |
| `amount` | `string` | Integer string in base units of `srcToken`. Replaced by `dstAmount` for an exact output or with `calls` / `action`. |
| `dstAmount` | `string?` | Instead of `amount`: the exact amount of `dstToken` the recipient (or the calls) receives. See [Receive an exact amount](/guides/exact-output). |
| `dstChain` | `string \| number` | Chain id or slug. |
| `dstToken` | `string` | Symbol or address / mint. |
| `sender` | `string` | Address that signs on the source chain. |
| `recipient` | `string` | Address that receives on the destination chain. |
| `slippageBps` | `number?` | Default `50`. Range 1–5000. |
| `gasOnArrival` | `boolean \| number?` | Also deliver native gas on the destination chain: `true` = $2, or a USD amount (0.5–20). See [Gas on arrival](/guides/gas-on-arrival). |
| `referrer` | `string?` | Wallet that referred this user, recorded on the order (attribution only, no fee change). See [Referral links](/guides/referrals). |
| `calls` | `{ to, data, value? }[]?` | Contract calls run on the destination chain with the output (sent as `POST /v1/quote`). See [Destination calls](/guides/destination-calls). |
| `action` | `{ type: "aave-v3-supply" }?` | A preset that builds the calls server-side. |
| `excludeProviders` | `string[]?` | Never ask these providers (ids in `EXCLUDABLE_PROVIDERS`). See [Pick a route and avoid bridges](/guides/pick-a-route). |
| `excludeBridges` | `string[]?` | Never route through these bridges (`AVOIDABLE_VENUES` with `kind: "bridge"`). |
| `excludeExchanges` | `string[]?` | Never swap through these exchanges (`AVOIDABLE_VENUES` with `kind: "exchange"`). |

Every entry of `quotes` has its own `quoteId` and the same LayerHop fee: build the one the user picks with `buildTx`, not only `best`.

```ts
interface QuoteResponse {
  best: Quote;     // same as quotes[0]
  quotes: Quote[];
  errors: { provider: string; code: string; message: string }[];
}

interface Quote {
  quoteId: string;
  provider: ProviderId;      // "jupiter" | "relay" | "debridge" | "zerox" | "kyberswap" | "lifi" | …
  dstAmount: string;         // expected output, base units
  dstAmountMin: string;      // after slippage
  estimatedSeconds: number;
  fees: { ourFeeBps: number; providerFeeUsd?: number; gasUsd?: number; integratorFeeBps?: number; integrator?: string };
  expiresAt: number;         // unix seconds
  gasOnArrival?: { amount: string; token: string; symbol: string; decimals: number; usd?: number }; // when requested and included
  srcAmount?: string;        // exact output (dstAmount): what the sender pays
  srcAmountMax?: string;     // exact output: the most the tx can take (balance checks)
  calls?: { items: { to: string; data: string; value: string }[]; executor: string; executed: boolean; simulation?: { ok: boolean; gasUsed: string; leftover?: string } };
}
```

## simulate(quoteId)

Calls [`POST /v1/simulate`](/api-reference#simulate-the-transaction). Builds the transaction for a quote and dry-runs it over RPC (EVM `eth_call` + gas estimate, Solana `simulateTransaction`) without recording an order. A failing simulation resolves with `ok: false`; it does not throw. See [Simulation](/concepts/simulation).

```ts
simulate(quoteId: string): Promise<SimulationResponse>

interface SimulationResponse {
  quoteId: string;
  provider: ProviderId;
  ok: boolean;
  vm: "evm" | "svm";
  gasEstimate?: string;           // EVM
  computeUnits?: number;          // Solana
  needsApproval?: boolean;        // EVM: allowance too low and could not be overridden
  simulated?: "tx" | "approval";  // what was actually simulated
  error?: { code: "SIMULATION_FAILED" | "RPC_ERROR"; message: string; logs?: string[] };
  tx: BuiltTx;
}
```

## buildTx(quoteId)

Calls [`POST /v1/orders`](/api-reference#build-the-transaction) and returns only the transaction.

```ts
buildTx(quoteId: string): Promise<BuiltTx>

type BuiltTx = EvmTx | SvmTx;

type EvmTx = {
  vm: "evm";
  chainId: number;
  to: string;
  data: string;
  value: string; // wei
  approval?: { token: string; spender: string; amount: string };
};

type SvmTx = {
  vm: "svm";
  serializedTx: string;   // base64 VersionedTransaction
  submitViaApi?: boolean; // sign only, then call submit()
};
```

Narrow on `tx.vm`. See [Approvals](/concepts/approvals) and [the submitViaApi flow](/concepts/submit-via-api).

## submit(quoteId, signedTransaction)

Calls [`POST /v1/orders/submit`](/api-reference#submit-a-signed-transaction). Only for `SvmTx` with `submitViaApi: true`. Returns the Solana transaction signature.

```ts
submit(quoteId: string, signedTransaction: string /* base64 */): Promise<string>
```

## reportSubmitted(quoteId, txHash)

Calls [`POST /v1/orders/{quoteId}/submitted`](/api-reference#report-the-broadcast-transaction). Call it right after the user's wallet broadcasts the transaction from `buildTx()`, so LayerHop tracks the order: it moves to `submitted`, appears in your [dashboard](/guides/dashboard-and-api-keys), fires [webhooks](/guides/webhooks) and counts toward partner earnings. Idempotent; reporting a different hash for the same quote fails with [`CONFLICT`](/errors/CONFLICT). `submit()` reports for you.

```ts
reportSubmitted(quoteId: string, txHash: string): Promise<{ quoteId: string; status: OrderLifecycleStatus }>

type OrderLifecycleStatus = "built" | "submitted" | "pending" | "filled" | "refunded" | "failed" | "expired" | "dropped";
```

## status(provider, id)

Calls [`GET /v1/orders/{provider}/{id}`](/api-reference#get-order-status). The id is URL-encoded for you. For the platform status use [`serviceStatus()`](#servicestatus).

```ts
status(provider: ProviderId, id: string): Promise<OrderStatus>

interface OrderStatus {
  provider: ProviderId;
  id: string;
  state: "pending" | "filled" | "refunded" | "failed" | "unknown";
  srcTxHash?: string;
  dstTxHash?: string;
}
```

Which `id` to pass per provider: [Order tracking](/concepts/order-tracking).

## watch(provider, id, options?)

Polls `status()` and yields each **change** of state until it is `filled`, `refunded` or `failed`, or until the timeout.

```ts
watch(provider: ProviderId, id: string, opts?: { intervalMs?: number; timeoutMs?: number }): AsyncGenerator<OrderStatus>
```

| Option | Default |
|---|---|
| `intervalMs` | `3000` |
| `timeoutMs` | `1800000` (30 minutes) |

```ts
for await (const s of lh.watch("debridge", srcTxHash)) console.log(s.state);
```

When the timeout is reached the generator simply ends; check the last state you saw. Errors from `status()` are thrown out of the loop — wrap it if you want to keep polling through transient provider errors.

## listOrders(params)

Calls [`GET /v1/orders`](/api-reference#list-orders-by-address). Lists orders where `address` is the sender or the recipient, newest first.

```ts
listOrders(p: { address: string; status?: OrderLifecycleStatus; cursor?: string; limit?: number }): Promise<{ orders: OrderSummary[]; nextCursor: string | null }>
```

Each `OrderSummary` has `quoteId`, `status`, `statusDetail`, `provider`, `channel`, source and destination chain and token, `sender`, `recipient`, `amount`, `dstAmount`, `ourFeeBps`, `partnerFeeBps`, `srcTxHash`, `dstTxHash`, `checkoutSessionId` (a checkout payment), `refundId` (a checkout refund), `depositAddressId` (a deposit to a [deposit address](/guides/deposit-addresses)), `createdAt` and `updatedAt`. Pass `nextCursor` back as `cursor` for the next page.

## invoices

[Invoices](/guides/invoices) bill a customer by email for one or more line items and are paid through checkout on the hosted page `https://layerhop.com/invoice/{id}`. `create`, `get`, `list`, `update`, `send` and `void` need an API key; `publicView` and `pay` are public (the customer's side).

```ts
invoices.create(p: CreateInvoiceParams): Promise<Invoice>        // POST /v1/invoices
invoices.get(id: string): Promise<Invoice>                       // GET /v1/invoices/{id}
invoices.list(p?: { status?: InvoiceStatus; cursor?: string; limit?: number }): Promise<InvoiceList>
invoices.update(id: string, p: UpdateInvoiceParams): Promise<Invoice>   // PATCH, drafts only
invoices.send(id: string): Promise<Invoice>                      // draft → open + email; re-sends an open one
invoices.void(id: string): Promise<Invoice>                      // draft or open → void
invoices.publicView(id: string): Promise<PublicInvoice>          // GET /v1/invoices/{id}/public
invoices.pay(id: string): Promise<{ sessionId: string; url: string }>   // POST /v1/invoices/{id}/pay

interface CreateInvoiceParams {
  lineItems: { description: string; quantity: number; unitAmount: string }[]; // base units
  settleChain: string | number;
  settleToken: string;          // "USDC" | "USDT"
  recipient: string;            // your payout address
  customerEmail?: string | null;
  customerName?: string | null;
  merchantName?: string | null;
  memo?: string | null;
  dueAt?: string | null;        // "2026-11-01" or an ISO date-time
  send?: boolean;               // finalize and email right away
}

type InvoiceStatus = "draft" | "open" | "paid" | "void";
```

```ts
const invoice = await lh.invoices.create({
  customerEmail: "ap@client.example", customerName: "Client Co",
  lineItems: [{ description: "Design work (hours)", quantity: 10, unitAmount: "80000000" }], // 10 × 80 USDC
  settleChain: "base", settleToken: "USDC", recipient: "0xYourPayoutAddress",
  dueAt: "2026-11-01", send: true,
});
console.log(invoice.number, invoice.url); // INV-0001 https://layerhop.com/invoice/inv_…
```

An `Invoice` has `id`, `number`, `status`, `lineItems`, `amount` (the total), `settlement`, `customerEmail`, `customerName`, `merchantName`, `memo`, `recipient`, `dueAt`, `url`, `sessionId` (the paying checkout session), `receiptUrl` (the PDF, once paid) and the `sentAt`, `paidAt`, `receiptSentAt`, `voidedAt`, `createdAt` and `updatedAt` timestamps. `PublicInvoice` leaves out the customer's email, the payout address and the merchant-side timestamps.

## depositAddresses

[Deposit addresses](/guides/deposit-addresses) let your user swap or bridge by sending `srcToken` to an address, without connecting a wallet. Every call needs an API key; each detected deposit becomes an order (`quoteId` starting with `dep_`) with `depositAddressId` set. `integrator` and `integratorFeeBps` default to the client options, as for `quote`.

```ts
depositAddresses.create(p: CreateDepositAddressParams): Promise<DepositAddressCreated>   // POST /v1/deposit-addresses
depositAddresses.get(id: string): Promise<DepositAddressWithDeposits>    // the address + its 20 most recent deposits
depositAddresses.list(p?: { status?: "active" | "disabled"; label?: string; cursor?: string; limit?: number }): Promise<DepositAddressList>
depositAddresses.refresh(id: string): Promise<DepositAddress>            // check for deposits now
depositAddresses.disable(id: string): Promise<DepositAddress>            // stop tracking it
depositAddresses.simulate(id: string, p: { amount: string }): Promise<DepositOrder>   // test keys only

interface CreateDepositAddressParams {
  srcChain: string | number;    // where your user deposits
  srcToken: string;             // the only token to send to the address
  dstChain: string | number;
  dstToken: string;
  recipient: string;            // receives dstToken on dstChain
  refundTo: string;             // your user's address on srcChain (never an exchange deposit address)
  reusable?: boolean;           // default true; false = one-time, exactly `amount`
  amount?: string;              // base units; required when reusable is false
  label?: string;
  metadata?: Record<string, string>;
  integrator?: string;
  integratorFeeBps?: number;
}
```

```ts
const lh = new LayerHop({ apiKey: process.env.LAYERHOP_API_KEY });
const da = await lh.depositAddresses.create({
  srcChain: "base", srcToken: "USDC", dstChain: "arbitrum", dstToken: "USDC",
  recipient: "0xUserOnArbitrum", refundTo: "0xUserOnBase", label: "user-4821",
});
console.log(da.address, da.estimate.dstAmount); // show da.address to your user
```

A `DepositAddress` has `id` (`da_…`), `livemode`, `status`, `provider`, `address`, `chainId` and `token` (what to send), `dstChainId`, `dstToken`, `recipient`, `refundTo`, `reusable`, `amount` (one-time addresses), `fees` (`ourFeeBps`, `integratorFeeBps`, `integrator`), `label`, `metadata`, `depositCount`, `lastDepositAt` and `createdAt`. `create` adds `estimate` (`amount`, `dstAmount`, `dstAmountMin`, `estimatedSeconds`); `get` adds `deposits`.

## checkout.refunds

[Refunds](/guides/refunds) of paid checkout sessions, with an API key. Refunds are non-custodial: `create` returns a quote that **you** build, sign from your own wallet (`quote.from`, by default the session's payout address) and report. LayerHop then tracks the order, adds it to the session's `refundedAmount` and sends `checkout.session.refunded`.

```ts
checkout.refunds.create(sessionId: string, p?: {
  amount?: string;                     // base units of the settlement token; default: everything not yet refunded
  reason?: string;
  from?: string;                       // the signing wallet; default: the session's payout address
  to?: "original" | "settlement";      // the payer's original chain and token (default) or the settlement token
}): Promise<RefundCreateResponse>      // { refund, quote: { quoteId, provider, srcAmount, dstAmount, dstAmountMin, estimatedSeconds, expiresAt, from }, next }
checkout.refunds.list(sessionId: string): Promise<Refund[]>
```

```ts
const { refund, quote } = await lh.checkout.refunds.create("cs_…", { amount: "10000000", reason: "Partial refund" });
const tx = await lh.buildTx(quote.quoteId);               // sign and send it from quote.from
await lh.reportSubmitted(quote.quoteId, txHash);          // refund.status: pending → submitted → completed
```

`RefundStatus` is `pending` (created, not yet sent), `submitted`, `completed` or `failed`.

## serviceStatus()

Calls [`GET /v1/status`](/api-reference), the data behind [status.layerhop.com](/guides/status-and-monitoring). Public; no key needed.

```ts
serviceStatus(): Promise<StatusResponse>

interface StatusResponse {
  status: "operational" | "degraded" | "outage";
  updatedAt: string;
  components: { id: string; name: string; group: string; status: "operational" | "degraded" | "down";
                latencyMs: number | null; uptime90d: number | null; days: { date: string; uptime: number | null }[] }[];
  incidents: { id: string; componentId: string; component: string; title: string; startedAt: string; resolvedAt: string | null }[];
  url: string;
}
```

## chains()

Calls [`GET /v1/chains`](/api-reference#list-chains) and returns `ChainInfo[]`: every chain LayerHop routes, popular first, with `logoURI`, `explorerTx`, `explorerAddress`, `providers` and `popular`.

```ts
chains(): Promise<ChainInfo[]>
```

## tokens(params)

Calls [`GET /v1/tokens`](/api-reference#list-tokens). A bare chain id or slug is shorthand for `{ chain }`.

```ts
tokens(p: { chain: string | number; q?: string; limit?: number; cursor?: string } | string | number): Promise<TokensResponse>

interface TokensResponse { tokens: TokenInfo[]; nextCursor: string | null }

interface TokenInfo {
  chainId: number;
  address: string;      // EVM checksummed; native = 0x000…000; Solana mint (native SOL = So111…112)
  symbol: string;
  name: string;
  decimals: number;
  logoURI?: string;
  priceUsd?: number;
  verified: boolean;    // on a provider list or the curated list
  popular?: boolean;    // stables, wrapped native, majors
}
```

## lookupToken(chain, address)

Calls [`GET /v1/tokens/lookup`](/api-reference#look-up-a-token). Tokens on no list are read on-chain and come back with `verified: false`. With only an address (or a `null` / `undefined` chain), the API finds the chain: Solana for a mint, otherwise the supported chain with the most pool liquidity for that address.

```ts
lookupToken(chain: string | number | null | undefined, address: string): Promise<TokenInfo>
lookupToken(address: string): Promise<TokenInfo>
```

## prices(ids)

Calls [`GET /v1/prices`](/api-reference#get-usd-prices) for up to 100 tokens. Returns USD prices keyed by the ids as given; unknown ids are omitted.

```ts
prices(ids: (string | { chainId: string | number; address: string })[]): Promise<Record<string, number>>
```

## balances(address, chains?, opts?)

Calls [`GET /v1/balances`](/api-reference#get-wallet-balances). Without `chains`, an EVM address is scanned on the popular EVM chains and a Solana address on Solana. `opts.tokens` (at most 20, `"chainId:address"` or `{ chainId, address }`) are always returned, even at zero and even when they are on no token list, and their chains are scanned too. `opts.fresh` skips the server's 20-second cache; use it right after a swap.

```ts
balances(address: string, chains?: (string | number)[], opts?: { tokens?: PriceId[]; fresh?: boolean }): Promise<BalancesResponse>

interface BalancesResponse {
  address: string;
  vm: "evm" | "svm";
  balances: (TokenInfo & { amount: string; valueUsd?: number })[];  // non-zero + requested tokens, highest value first
  totalUsd: number;
  errors: { chainId: number; message: string }[];                   // chains (or requested tokens) that could not be read
}
```

## getTokenRisk(chain, address)

Calls [`GET /v1/tokens/{chain}/{address}/risk`](/api-reference#check-a-token-for-risks): honeypots, buy / sell / transfer taxes, owner powers, unpublished code, very few holders and fake majors (a token calling itself USDC at the wrong address). `level` is `ok`, `caution`, `danger` or `unknown`; `unknown` means no source answered and should never block a swap. Ask for an explicit confirmation before a buy on `danger`.

```ts
const risk = await lh.getTokenRisk("base", "0x532f27101965dd16442E59d40670FaF5eBB142E4");
if (risk.level === "danger") console.warn(risk.reasons.map((r) => r.message).join(" "));
```

## Splits, tip jars and payouts

All public (no key) and none of them signs anything.

- `createSplit({ recipient, chain, token, total, participants | shares, note? })` returns the split plus `editToken`, shown only once. Each participant pays with `quote({ ..., purpose: "split", splitId, splitShare })`. `getSplit(id)` shows who paid; `updateSplit(id, editToken, { labels?, note?, status? })` renames shares, changes the note (`null` clears it) or closes the split.
- `getTipJar(address)` returns `tippers`, `tips` and the latest 10 messages. Tips are quotes with `purpose: "tip"` and an optional `note`.
- `planPayouts({ srcChain, srcToken, sender, rows | csv })` checks up to 100 rows (human amounts, ENS / `.sol` names resolved read-only) and groups them: `transfers` batches you build with `buildPayoutTransfers({ chain, token, sender, transfers })` (EVM `calls` or a Solana `serializedTx`, no LayerHop fee) and `routes` you quote one by one with `purpose: "payout"`.

```ts
const split = await lh.createSplit({ recipient: "alice.eth", chain: "base", token: "USDC", total: "120000000", participants: 4 });
const plan = await lh.planPayouts({ srcChain: "base", srcToken: "USDC", sender: "0xYou", csv: "alice.eth,250,USDC,base\nbob.eth,40,USDC,arbitrum" });
for (const b of plan.transfers) {
  const batch = await lh.buildPayoutTransfers({ chain: b.chainId, token: b.token, sender: "0xYou", transfers: b.rows.map((i) => ({ recipient: plan.rows[i]!.recipient!.address, amount: plan.rows[i]!.amount! })) });
  // check every call against its row, then let the payer's wallet sign batch.calls
}
```

## LayerHopApiError

Every non-2xx response is thrown as `LayerHopApiError`:

| Property | Type | Description |
|---|---|---|
| `code` | `string` | Stable [error code](/errors) (`"INTERNAL"` if the body had none). |
| `message` | `string` | Human-readable message. |
| `status` | `number` | HTTP status. |
| `requestId` | `string?` | Request id for support. |
| `details` | `object?` | Extra data on some errors: `errors` (per provider) on `NO_ROUTE`, `minAmount` / `minAmountUsd` / `minAmountApprox` on `AMOUNT_TOO_SMALL`, `suggestions` on a live `NO_ROUTE`. |

```ts
import { LayerHopApiError, parseRouteSuggestions } from "@layerhop/sdk";

try {
  await lh.quote(params);
} catch (e) {
  if (e instanceof LayerHopApiError && e.code === "NO_ROUTE") {
    // dst_token / src_token: one quote with the changed token; via_hub: two steps (s.steps[0], then s.steps[1])
    for (const s of parseRouteSuggestions(e.details)) console.log(s.kind, s.message);
  }
}
```

`buildTx()` throws a plain `Error` for a gasless quote (use `buildGasless()`). A Tron quote's `buildTx()` returns a `TronTx` (`vm: "tvm"`): send `approval.unsigned` first when present, then `unsigned`, both signed unchanged by a Tron wallet, and report the main transaction's `txID` (64 hex characters, no `0x`).

## Re-exports

For convenience the SDK re-exports from `@layerhop/shared`:

| Export | What |
|---|---|
| `CHAINS`, `getChain(idOrSlug)` | The [chain registry](/chains). |
| `TOKENS`, `findToken(chainId, symbolOrAddress)` | The built-in token list. |
| `SOLANA_CHAIN_ID` | `7565164`, LayerHop's id for Solana. |
| `EVM_NATIVE`, `SOL_NATIVE` | Native coin addresses (`0x000…000`, wrapped-SOL mint). |
| `AVOIDABLE_VENUES`, `EXCLUDABLE_PROVIDERS` | Ids and names for the quote avoid-lists ([Pick a route and avoid bridges](/guides/pick-a-route)). |
| Types | `BuiltTx`, `EvmTx`, `SvmTx`, `OrderStatus`, `ProviderId`, `FeeChannel`. |

```ts
import { findToken, getChain } from "@layerhop/sdk";

const base = getChain("base")!;               // { id: 8453, … }
const usdc = findToken(base.id, "USDC")!;     // { decimals: 6, address: "0x8335…" }
const amount = (100n * 10n ** BigInt(usdc.decimals)).toString(); // "100000000"
```

## Other SDKs and tools

- [React hooks](/sdks/react): `useQuote`, `useSwap`, `useOrderStatus`, `useTokens` on top of this SDK.
- [React Native & Expo](/sdks/react-native): the widget and checkout as native components, wallet deep links. This SDK runs in React Native too (streams fall back to `XMLHttpRequest`).
- [Wallets](/guides/wallets): `@layerhop/wagmi` (`executeQuote`, `useExecuteQuote`, approve + swap in one EIP-5792 confirmation) and `@layerhop/solana` (`executeSolanaQuote` for wallet-adapter, Wallet Standard and embedded wallets).
- [Python](/sdks/python), [Go](/sdks/go), [Rust](/sdks/rust), [Swift](/sdks/swift), [Kotlin](/sdks/kotlin) (JVM + Android) and [C#](/sdks/csharp) (.NET + Unity) clients with the quote, order, tracking, checkout, invoice and refund methods.
- [CLI](/cli): quotes, order status, deep links, `init` and a local mock devnet.
