> For the complete documentation index, see [llms.txt](https://docs.swapper.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.swapper.finance/api-v1/sdk.md).

# TypeScript SDK

The [`@swapper-finance/deposit-sdk`](https://docs.swapper.finance/widget-integration/iframe-sdk.md) package includes **`SwapperApiClient`**, a typed client for API v1: chains and tokens, quotes ready to sign, transfer status, and deposit addresses — with retries, timeouts, rate-limit headers and typed errors handled for you.

* **Zero runtime dependencies.** It uses the global `fetch` (Node.js 18+, browsers, Deno, Bun, edge runtimes).
* **Typed from the API contract.** Every request and response is typed (`Step`, `Estimate`, `FeeCost`, `StatusResponse`, …).
* **Wallet-agnostic.** It never signs: send the returned `transactionRequest` with viem, ethers, a Solana wallet, or a custodial API.

```bash
npm install @swapper-finance/deposit-sdk
```

`SwapperApiClient` is included from version 0.5.0 of the package.

## Create a client

```typescript
import { SwapperApiClient } from "@swapper-finance/deposit-sdk";

// On your server, with an API key
const swapper = new SwapperApiClient({ apiKey: process.env.SWAPPER_API_KEY });

// Or on the free tier (server or browser), with your integratorId
const swapper = new SwapperApiClient({ integrator: "YOUR_INTEGRATOR_ID" });
```

| Option       | Default                          | Description                                                                                                                          |
| ------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `apiKey`     | —                                | Secret API key, sent in the `x-swapper-api-key` header. See [Authentication](https://docs.swapper.finance/api-v1/authentication.md). |
| `integrator` | —                                | Your `integratorId`, sent with every request **when there is no `apiKey`**. Required for quotes on the free tier.                    |
| `baseUrl`    | `https://swapper.finance/api/v1` | API base URL.                                                                                                                        |
| `timeoutMs`  | `30000`                          | Timeout of each attempt, in milliseconds.                                                                                            |
| `maxRetries` | `2`                              | Automatic retries on `429`, `5xx`, network errors and timeouts. `0` disables them.                                                   |

* **With an `apiKey`**, the client does **not** send `integrator` unless you pass it to `getQuote` explicitly — the key already identifies you, and an `integrator` that doesn't match it fails with `INVALID_INTEGRATOR`.
* **Without a key**, `integrator` is sent on every request: it's required on quotes, and on the other endpoints it counts the call under your integrator on the dashboard's API usage page.

{% hint style="warning" %}
**Keep API keys on your servers.** If `SwapperApiClient` is given an `apiKey` in a browser, it logs a one-time warning. From the browser, use the free tier and protect your `integratorId` with [allowed origins](https://docs.swapper.finance/api-v1/authentication.md#browser-requests-and-allowed-origins).
{% endhint %}

## Quick start

Quote **10 USDC on Base** into **ETH on Arbitrum**, approve if needed, send, and track the transfer:

```typescript
import {
  SwapperApiClient,
  approvalNeeded,
  feeFromBps,
  NATIVE_TOKEN_ADDRESS,
} from "@swapper-finance/deposit-sdk";

const swapper = new SwapperApiClient({ apiKey: process.env.SWAPPER_API_KEY });

// 1. Quote
const quote = await swapper.getQuote({
  fromChain: 8453,
  toChain: 42161,
  fromToken: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
  toToken: NATIVE_TOKEN_ADDRESS,
  fromAmount: "10000000", // 10 USDC, in the smallest unit
  fromAddress: userAddress,
  fee: feeFromBps(30), // optional integrator fee: 0.003 = 0.3%, needs an API key
});

// 2. Approve (ERC-20 sources only)
if (approvalNeeded(quote)) {
  // If the allowance of quote.estimate.approvalAddress is below
  // quote.action.fromAmount, approve it first.
}

// 3. Send quote.transactionRequest with the user's wallet
const txHash = await sendWithWallet(quote.transactionRequest);

// 4. Track until DONE or FAILED
const status = await swapper.waitForStatus({
  txHash,
  fromChain: quote.action.fromChainId,
  toChain: quote.action.toChainId,
});
console.log(status.status, status.substatus); // "DONE" "COMPLETED"
```

A typical setup keeps the key on your backend: the backend calls `getQuote` and returns `quote.transactionRequest` to your frontend, the user's wallet signs and sends it, your frontend reports the transaction hash, and the backend tracks it with `waitForStatus`.

### Sending with viem

`transactionRequest` holds plain strings, so it maps onto any wallet library. With [viem](https://viem.sh) (not a dependency of the SDK):

```typescript
import { createPublicClient, createWalletClient, erc20Abi, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";
import { approvalNeeded } from "@swapper-finance/deposit-sdk";

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const wallet = createWalletClient({ account, chain: base, transport: http() });
const publicClient = createPublicClient({ chain: base, transport: http() });

if (approvalNeeded(quote)) {
  const token = quote.action.fromToken.address as `0x${string}`;
  const spender = quote.estimate.approvalAddress as `0x${string}`;
  const amount = BigInt(quote.action.fromAmount);
  const allowance = await publicClient.readContract({
    address: token,
    abi: erc20Abi,
    functionName: "allowance",
    args: [account.address, spender],
  });
  if (allowance < amount) {
    const hash = await wallet.writeContract({
      address: token,
      abi: erc20Abi,
      functionName: "approve",
      args: [spender, amount],
    });
    await publicClient.waitForTransactionReceipt({ hash });
  }
}

const tx = quote.transactionRequest;
const txHash = await wallet.sendTransaction({
  to: tx.to as `0x${string}`,
  data: tx.data as `0x${string}`,
  value: BigInt(tx.value ?? 0),
  gas: tx.gasLimit ? BigInt(tx.gasLimit) : undefined,
});
```

With ethers v6, pass the fields straight through: `signer.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, gasLimit: tx.gasLimit })`. On Solana, `transactionRequest.data` is a base64-encoded `VersionedTransaction` to sign and send, and no approval is needed. See [Quote → Executing a quote](https://docs.swapper.finance/api-v1/endpoints/quote.md#executing-a-quote).

## Methods

Each method returns the response body of its endpoint, and takes an optional last argument `{ signal?: AbortSignal, requestId?: string }`. Chains (`ChainIdOrKey = string | number`) can be given by Swapper chain id or key — `"8453"`, `"mainnet-beta"`, `"base"`, `"solana"` — and EVM ids also as numbers (`8453`). Responses always carry the chain id, as a string.

| Method                                                                                                                    | Endpoint                                                                                                                         | Returns                                      |
| ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| `getChains({ ecosystems? })`                                                                                              | [`GET /v1/chains`](https://docs.swapper.finance/api-v1/endpoints/chains-and-tokens.md#list-chains)                               | `{ chains: Chain[] }`                        |
| `getTokens({ chains?, ecosystems? })`                                                                                     | [`GET /v1/tokens`](https://docs.swapper.finance/api-v1/endpoints/chains-and-tokens.md#list-tokens)                               | `{ tokens: { [chainId: string]: Token[] } }` |
| `getToken({ chain, token })`                                                                                              | [`GET /v1/token`](https://docs.swapper.finance/api-v1/endpoints/chains-and-tokens.md#get-one-token)                              | `Token`                                      |
| `getQuote({ fromChain, toChain, fromToken, toToken, fromAmount, fromAddress, toAddress?, slippage?, fee?, integrator? })` | [`POST /v1/quote`](https://docs.swapper.finance/api-v1/endpoints/quote.md)                                                       | `Step` (alias `Quote`)                       |
| `getStatus({ txHash, fromChain?, toChain? })`                                                                             | [`GET /v1/status`](https://docs.swapper.finance/api-v1/endpoints/status.md)                                                      | `StatusResponse`                             |
| `waitForStatus(params, options?)`                                                                                         | polls `GET /v1/status`                                                                                                           | `StatusResponse` (final)                     |
| `createDepositAddress({ fromChain, fromToken, toChain, toToken, toAddress, refundAddress? })`                             | [`POST /v1/deposit-address`](https://docs.swapper.finance/api-v1/endpoints/deposit-addresses.md#get-a-deposit-address) (API key) | `DepositAddress`                             |
| `getDepositAddressStatus({ address })`                                                                                    | [`GET /v1/deposit-address/status`](https://docs.swapper.finance/api-v1/endpoints/deposit-addresses.md#track-deposits)            | `{ address, transfers: StatusResponse[] }`   |

`fromAmount` takes a string or a `bigint`. `slippage` and `fee` are decimal fractions (`0.005` = 0.5%); `feeFromBps(30)` gives `0.003`. `ecosystems` is an array of `Ecosystem` (`"evm"`, `"solana"`):

```typescript
const { chains } = await swapper.getChains({ ecosystems: ["evm"] });
const { tokens } = await swapper.getTokens({ chains: [8453, "arbitrum"] });
const baseTokens = tokens["8453"];
```

## Deposit addresses

```ts
const { address } = await swapper.createDepositAddress({
  fromChain: 8453,
  fromToken: "USDC",
  toChain: 42161,
  toToken: "USDC",
  toAddress: "0x1111111111111111111111111111111111111111",
});
// Show `address` with the token and network to send: only USDC on Base.

// While you expect a deposit, every 10–15 s:
const { transfers } = await swapper.getDepositAddressStatus({ address });
```

`createDepositAddress` needs the client's `apiKey`. The same parameters always return the same address, so it's safe to call again (and is retried like a read). Checking the status is what records new deposits and sends their webhook — see [Deposit Addresses → Polling](https://docs.swapper.finance/api-v1/endpoints/deposit-addresses.md#polling).

## Tracking with `waitForStatus`

```typescript
const status = await swapper.waitForStatus(
  { txHash, fromChain: 8453, toChain: 42161 },
  {
    intervalMs: 5_000, // default
    timeoutMs: 30 * 60_000, // default: 30 minutes
    onUpdate: (s) => console.log(s.status, s.substatus),
  },
);
```

`waitForStatus` polls until the transfer is `DONE` or `FAILED` and resolves with that status — check `substatus`, since `DONE` can also be `REFUNDED`. Along the way it:

* keeps polling through `NOT_FOUND` for up to `notFoundTimeoutMs` (10 minutes by default) — normal right after broadcasting — then rejects with `TRANSFER_NOT_FOUND`;
* keeps polling through `429` (waiting at least `Retry-After`), `5xx` and network errors;
* throws any other error at once, rejects with `TIMEOUT` after `timeoutMs`, and stops with `ABORTED` when its `signal` fires.

{% hint style="warning" %}
**Track every transfer you quote.** A transfer is only recorded at Swapper — and your [integrator fee](https://docs.swapper.finance/api-v1/integrator-fees.md#getting-paid) only accrued, and your [webhook](https://docs.swapper.finance/tracking-deposits/webhooks.md) only sent — once its status has been requested. Call `waitForStatus` right after the transaction is broadcast, and pass `fromChain`.
{% endhint %}

## Errors

Every failure is a `SwapperApiError`:

```typescript
import { SwapperApiError } from "@swapper-finance/deposit-sdk";

try {
  await swapper.getQuote(params);
} catch (err) {
  if (err instanceof SwapperApiError) {
    if (err.code === "NO_ROUTE_FOUND") {
      // try another amount or pair
    }
    console.error(err.code, err.status, err.message, err.requestId);
  }
}
```

| Property     | Description                                                                                                                                                   |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code`       | The API's [error code](https://docs.swapper.finance/api-v1/errors.md#error-codes) (`INVALID_FEE`, `NO_ROUTE_FOUND`, …), or a client code below. Branch on it. |
| `status`     | HTTP status; `0` when no response was received.                                                                                                               |
| `requestId`  | The request's `X-Request-Id`. Always set — the client sends its own id, so even timeouts have one. Include it when you contact support.                       |
| `retryAfter` | Seconds to wait, from `Retry-After` (on `429`).                                                                                                               |
| `rateLimit`  | The failed response's `X-RateLimit-*` headers, when present.                                                                                                  |
| `retryable`  | `true` for `429`, `5xx`, network errors and timeouts.                                                                                                         |

Codes set by the client itself:

| Code                 | Meaning                                                                                       |
| -------------------- | --------------------------------------------------------------------------------------------- |
| `NETWORK_ERROR`      | No response (DNS failure, connection refused or reset).                                       |
| `TIMEOUT`            | No response within `timeoutMs`, or `waitForStatus` reached its own `timeoutMs`.               |
| `ABORTED`            | Your `AbortSignal` fired.                                                                     |
| `INVALID_RESPONSE`   | The body wasn't the API's JSON (e.g. a proxy's HTML error page); `status` is the HTTP status. |
| `TRANSFER_NOT_FOUND` | `waitForStatus` still got `NOT_FOUND` after `notFoundTimeoutMs`.                              |

## Retries and rate limits

* **Retries.** `429`, `5xx`, network errors and timeouts are retried up to `maxRetries` times with exponential backoff and jitter. A `429` is retried after `Retry-After` (up to 60 seconds; a longer wait is left to you). Other `4xx` errors are never retried, as recommended in [Errors](https://docs.swapper.finance/api-v1/errors.md#handling-errors).
* **Rate-limit headers.** `swapper.lastRateLimit` holds the [`X-RateLimit-*` headers](https://docs.swapper.finance/api-v1/rate-limits.md#response-headers) of the most recent response that carried them — `{ limit, remaining, reset }`, with `reset` in unix seconds — or `undefined` before the first one.

```typescript
await swapper.getChains();
console.log(swapper.lastRateLimit); // { limit: 1200, remaining: 1199, reset: 1791125700 }
```

## Helpers

| Export                  | Description                                                                                                                                                                                                               |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NATIVE_TOKEN_ADDRESS`  | `0x0000000000000000000000000000000000000000`, the native token on EVM chains.                                                                                                                                             |
| `approvalNeeded(quote)` | `true` when the quote's source token is an ERC-20 that must be approved for `estimate.approvalAddress`; `false` for native tokens and Solana. It doesn't read the chain — compare the current allowance before approving. |
| `feeFromBps(bps)`       | Whole basis points → the `fee` fraction: `feeFromBps(30) === 0.003`. Throws for fractional or negative values.                                                                                                            |

All request and response types are exported too: `Chain`, `Token`, `Step` / `Quote`, `Action`, `Estimate`, `FeeCost`, `GasCost`, `TransactionRequest`, `StatusResponse`, `TransactionInfo`, `ErrorCode`, `RateLimitInfo`, and the request types `QuoteRequest`, `GetStatusRequest`, `TokensRequest`, …, `ChainIdOrKey` and `Ecosystem`.
