# Swap

Quote, create, follow, cancel, and list swaps that convert one Trading balance asset into another through the spot order books.

`client.swap` converts one asset of an account's Trading balance into another with immediate-or-cancel spot orders on that account. The route is the direct market between the two assets, or two markets through USDT or USDC. A swap trades at market or as a TWAP over up to 24 hours, and pays the account's spot taker fee on each market and no other fee. The source and destination stay in the same Trading account: there is no deposit address, external payout, or bridge. QuickSwap, which swaps external deposits across chains, is a separate broker API (`swap.quickswap.v1`) and is not part of `client.swap`. Errors carry `detail: { service: "swap", code }`. Tree-shaken builds reach the same service with `swapService(core)` from `@polyester/sdk/services/swap`.

`quote`, `create`, and `list` are account-scoped, so their inputs accept an optional `account` field (`"main"`, `"active"`, or `{ subaccountId }`). See [Account scoping](https://testnet.polyester.com/docs/sdk/typescript/guides/accounts-and-balances) for how the default resolves. `get` and `cancel` select one of the caller's swaps by its ID.

Every method, `cancel` and `list` included, needs the `swap` policy action on API keys and the `swap` permission for subaccount members. The swap's orders also follow the subaccount's spot trading policy. An API key acts only on its own account; a root-scoped key that selects a subaccount is refused with `SWAP_NOT_PERMITTED`. `quote` and `create` need an active subaccount; `get`, `list`, and `cancel` also work on an inactive one, so its open swaps can be found and canceled. A subaccount policy does not limit `cancel`. No step-up is required.

The flow is `quote`, then `create` with the same terms and the quote's `minAmountOut` and `expiresAt`, then `get` until `isTerminal`. A market swap usually finishes within seconds, a TWAP by its deadline. Swaps are sized by source amount only.

## Methods

| Method   | Summary                                                       |
| -------- | ------------------------------------------------------------- |
| `quote`  | Price a swap against current order-book depth for 30 seconds. |
| `create` | Create the swap for an idempotency key and start executing.   |
| `get`    | Read one swap by `swapId` or `idempotencyKey`.                |
| `cancel` | Stop a swap that has not ended.                               |
| `list`   | Page through an account's swaps, newest first.                |

### `quote(input, options?)`

Prices a swap against current order-book depth and the account's taker fee. The quote reserves neither funds nor liquidity; only `minAmountOut` binds. It expires 30 seconds after `quotedAt`.

```ts
const terms = {
	account: "main" as const,
	sourceAssetId: 2,
	destinationAssetId: 1,
	amount: "250",
};

const quote = await client.swap.quote({ ...terms, maxSlippageBps: 50 });

console.log(quote.expectedAmountOut, quote.minAmountOut, quote.priceImpactBps, quote.expiresAt);
```

#### `QuoteSwapInput`

| Field                | Type            | Required | Notes                                                                                  |
| -------------------- | --------------- | -------- | -------------------------------------------------------------------------------------- |
| `sourceAssetId`      | `number`        | yes      | Unified asset ID spent, as in balances and internal transfers.                         |
| `destinationAssetId` | `number`        | yes      | Unified asset ID received. Must differ from the source.                                |
| `amount`             | decimal string  | yes      | Source amount, greater than `0`, up to 18 decimal places.                              |
| `maxSlippageBps`     | `number`        | yes      | Accepted shortfall from the expected output, 1 to 1000 bps.                            |
| `execution`          | `SwapExecution` | no       | `{ type: "market" }` (the default) or `{ type: "twap", durationMs, sliceIntervalMs }`. |
| `account`            | `AccountScope`  | no       | Scope override.                                                                        |

Only whole order steps of the market trade; the rest of `amount` stays on the account. Read each pair's order steps and size limits from [`marketData.getSpotConfig`](https://testnet.polyester.com/docs/sdk/typescript/reference/public-trades). `execution` is part of the swap's terms, so quote and create with the same one.

#### TWAP execution

A `twap` execution spreads the swap evenly over `durationMs` in slices `sliceIntervalMs` apart. `durationMs` is 60000 (1 minute) to 86400000 (24 hours), and `sliceIntervalMs` is at least 10000 (10 seconds) and at most `durationMs`. The root export carries these bounds as `SWAP_TWAP_MIN_DURATION_MS`, `SWAP_TWAP_MAX_DURATION_MS`, and `SWAP_TWAP_MIN_SLICE_INTERVAL_MS`.

```ts
const twapQuote = await client.swap.quote({
	...terms,
	maxSlippageBps: 50,
	execution: { type: "twap", durationMs: 30 * 60_000, sliceIntervalMs: 60_000 },
});

console.log(twapQuote.totalSlices); // 30
```

The schedule has one slice per slot, `durationMs / sliceIntervalMs` rounded up, and starts when execution starts, not when the swap is created. Each slice trades what is left of the amount over the slots left. A slice's first order is sent only within its slot; a missed slot is skipped, never sent late. A TWAP is quoted as the whole amount now. Every slice must be a valid order, so a TWAP needs a larger amount than a market swap, and many short slices need more than a few long ones.

On a two-leg route, a slice's second leg can be sent after its slot, before the deadline, once the first leg settles, and the next slice waits for it. Intermediate asset that no second-leg order can convert within price protection or order limits is carried into the next slice.

### `create(input, options?)`

Creates the swap for `idempotencyKey` and starts executing it, after pricing the terms again: it is created only while the quote is unexpired and `minAmountOut` is achievable. The result is usually still `executing`; follow it with `get`. Pass `account` explicitly, as `terms` does above, so a retry after the active subaccount changes sends the same request.

```ts
const idempotencyKey = crypto.randomUUID();

let swap = await client.swap.create({
	...terms,
	minAmountOut: quote.minAmountOut,
	quoteExpiresAt: quote.expiresAt!,
	idempotencyKey,
});
```

#### `CreateSwapInput`

Takes the quoted terms as in `QuoteSwapInput` (`sourceAssetId`, `destinationAssetId`, `amount`, `execution`, and `account`, without `maxSlippageBps`), plus:

| Field            | Type           | Required | Notes                                                                                         |
| ---------------- | -------------- | -------- | --------------------------------------------------------------------------------------------- |
| `minAmountOut`   | decimal string | yes      | Least destination amount after fees for the whole amount; usually the quote's `minAmountOut`. |
| `quoteExpiresAt` | `number`       | yes      | The quote's `expiresAt` (epoch ms). Refused with `QUOTE_EXPIRED` after it.                    |
| `idempotencyKey` | `string`       | yes      | Chosen by you, unique per caller. Sent exactly as given, never trimmed.                       |

An idempotency key is unique within the caller's main account, its subaccounts included, and has 1 to 128 characters from letters, digits, `.`, `_`, `:`, and `-`. Keys starting `aw:` are reserved for auto-withdraw conversions and throw `ValidationError`. The same key and input return the existing swap, even after the quote expires; `execution` is part of that input. Reusing a key with different input throws `AlreadyExistsError` (`IDEMPOTENCY_CONFLICT`), with the original swap's ID as `detail.swapId`. `QUOTE_EXPIRED` and `PROTECTION_UNACHIEVABLE` throw `PreconditionFailedError` and create nothing: quote again and create with a new key.

> **Retry an unknown outcome with the same key**
>
> A `TimeoutError`, `ServiceUnavailableError`, or `NetworkError` from `create` leaves the outcome unknown: the swap may have been created. Call `create` again with the same input and `idempotencyKey`, which returns the same swap, or read it with `get({ idempotencyKey })`. A new key could create a second swap.

### `get(input, options?)`

Reads one of the caller's swaps by `swapId`, or by the `idempotencyKey` it was created with. Pass exactly one. Reading needs the `swap` permission on the swap's funding account. An unknown swap throws `ResourceNotFoundError` (`SWAP_NOT_FOUND`).

```ts
while (!swap.isTerminal) {
	await new Promise((resolve) => setTimeout(resolve, 1000));
	swap = await client.swap.get({ swapId: swap.swapId });
}

console.log(swap.status, swap.reason, swap.executedAmount, swap.receivedAmount);
```

Poll until `isTerminal`, not until `progress.deadline`: orders sent before the deadline can settle after it.

### `cancel(input, options?)`

Cancels one of the caller's swaps that has not ended, by `swapId`. It is most useful for a TWAP. No new slice or first-leg order starts; orders already sent finish, and nothing that traded is undone. On a two-leg route, a slice whose first leg traded still converts its own intermediate asset within the swap's price protection, but intermediate carried from earlier slices is not converted. The untraded source amount and any unconverted intermediate asset stay on the account.

```ts
let swap = await client.swap.cancel({ swapId });

while (!swap.isTerminal) {
	await new Promise((resolve) => setTimeout(resolve, 1000));
	swap = await client.swap.get({ swapId });
}
```

The returned swap has `cancelRequestedAt` set. It is `canceling` while work already sent finishes, `reconciling` while an order's outcome is being confirmed (it can move between the two), or already terminal. It ends as:

- `canceled` with reason `user_canceled`: the cancel stopped it. The amounts show exactly what traded.
- `completed`, `partially_completed`, or `failed`: the cancel came too late to stop anything, so the swap ends with the outcome it would have had. `cancelRequestedAt` is still set.

TWAP slots the cancel left unused, and slices whose intermediate asset it left unconverted, report the slice reason `canceled`. A first cancel after `progress.deadline` changes nothing: a swap that has not ended comes back unchanged, without `cancelRequestedAt`, so check that field to confirm the cancel was recorded.

Cancel is idempotent once recorded: repeating it returns the swap with its original `cancelRequestedAt`, so retry a `TimeoutError`, `ServiceUnavailableError`, or `NetworkError` with the same request. A swap that ended without a cancel throws `PreconditionFailedError` (`SWAP_ALREADY_FINAL`, with `detail.swapId`); read it with `get`. An auto-withdraw conversion throws `PreconditionFailedError` (`SWAP_NOT_CANCELABLE`) and ends only with its auto-withdraw run.

### `list(input?, options?)`

Returns `{ swaps, nextPageToken }`: the caller's swaps funded by the resolved account, newest first by creation time, each the same `Swap` that `get` returns. Use it to find a swap whose ID and key you no longer have, such as after a page reload during a TWAP.

| Field       | Type           | Required | Notes                                                                                        |
| ----------- | -------------- | -------- | -------------------------------------------------------------------------------------------- |
| `openOnly`  | `boolean`      | no       | Only swaps that have not ended (`isTerminal` false), `canceling` and `reconciling` included. |
| `limit`     | `number`       | no       | 0 to 50; `0` or omitted uses 20.                                                             |
| `pageToken` | `string`       | no       | The previous `nextPageToken`, with the same `account` and `openOnly`.                        |
| `account`   | `AccountScope` | no       | Scope override. An inactive subaccount can still be listed.                                  |

```ts
let pageToken = "";
do {
	const page = await client.swap.list({ openOnly: true, pageToken });
	for (const s of page.swaps) console.log(s.swapId, s.status, s.progress?.completedSlices);
	pageToken = page.nextPageToken;
} while (pageToken !== "");
```

An empty `nextPageToken` means there are no more swaps. A malformed `pageToken`, or one from another listing, throws `ValidationError`. A listing never repeats a swap or skips one that existed when it started and still matches. A swap created during a listing appears on a later page only if it sorts after the last swap already listed; with `openOnly`, a swap that ends between pages is left out of later pages.

## Execution and minimum output

Each order is an immediate-or-cancel limit order at a protection price derived from the accepted minimum after fees. Every part that trades nets at least the `minAmountOut` rate, and anything that cannot trade within protection stays on the account. The minimum is a rate for the requested amount, not a promise that the whole amount trades. A remainder smaller than an order step can stay even after `completed`.

> **A failed swap can contain fills**
>
> Only an order the exchange accepts late, under severe delay, can pay a later scheduled fee and net less than the minimum rate. The swap then ends `failed` with reason `minimum_not_met`, and its amounts and balances show what actually traded. Reconcile them before submitting another conversion.

| `status`              | Meaning                                                                           |
| --------------------- | --------------------------------------------------------------------------------- |
| `executing`           | Orders are being placed, filled, or settled.                                      |
| `reconciling`         | An order's outcome is being established. Balances already show settled fills.     |
| `canceling`           | Canceled. No new slice or first-leg order starts, and orders already sent finish. |
| `completed`           | Terminal. The amount traded, allowing a remainder smaller than an order step.     |
| `partially_completed` | Terminal. Some of the amount traded; `reason` says why it stopped.                |
| `failed`              | Terminal. Usually nothing traded; check `reason` and the amounts.                 |
| `canceled`            | Terminal. Canceled before the whole amount traded; `reason` is `user_canceled`.   |

`isTerminal` is `true` for the four terminal statuses. Handle `canceling` and `canceled` even if your app never cancels: another client of the same account can. `reason` is `null` unless the swap is `partially_completed`, `failed`, or `canceled`:

| `reason`                     | Meaning                                                                                                   |
| ---------------------------- | --------------------------------------------------------------------------------------------------------- |
| `insufficient_balance`       | The Trading balance did not cover the amount when the order was placed.                                   |
| `price_protection`           | The order books could not fill the rest at a price that meets `minAmountOut`.                             |
| `market_unavailable`         | The market was closed, halted, restricted, or without liquidity.                                          |
| `order_size_out_of_range`    | The order was outside the market's size limits.                                                           |
| `rate_limited`               | The account's order rate limit was reached.                                                               |
| `order_rejected`             | The order was refused, for example by the subaccount's trading policy.                                    |
| `expired`                    | The execution window ended before the order could be placed, or a TWAP's deadline left slots untraded.    |
| `minimum_not_met`            | A fill netted less than the minimum rate. The amounts show exactly what traded.                           |
| `max_order_quantity`         | A buy reached the market's maximum order quantity, which changed after the quote; the rest stays unspent. |
| `intermediate_below_minimum` | On a two-leg route, intermediate asset below the second market's minimum order stays on the account.      |
| `user_canceled`              | The swap was canceled before its whole amount traded.                                                     |

Reconcile with `executedAmount`, `unspentAmount`, `receivedAmount`, and each entry of `legs`. Sum `fee` per `feeAssetId`, since legs can charge different assets. On a two-leg route, `intermediateRemainder` is intermediate asset that was not converted and is on the account. These amounts count settled fills only and are final once `isTerminal` is `true`.

Creating a swap draws on the account's placement pool and canceling one on its cancellation pool; quotes, reads, and lists use the trading-read pool. See [Trading rate limits](https://testnet.polyester.com/docs/sdk/typescript/reference/rate-limits).

## Errors

Refusals carry their code on the error's `detail` (`detail.service === "swap"`):

| Error                     | `detail.code`                                | What to do                                                                                                                                                                                                    |
| ------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ValidationError`         | `AMOUNT_OUT_OF_RANGE`                        | Correct the amount. `detail.minAmount` and `detail.maxAmount` give the current range in source units when known (for a TWAP, the least amount that quotes for its schedule). Guidance, not reserved capacity. |
| `PreconditionFailedError` | `QUOTE_EXPIRED`, `PROTECTION_UNACHIEVABLE`   | Nothing was created. Quote again, and create with a new key.                                                                                                                                                  |
| `PreconditionFailedError` | `ROUTE_UNSUPPORTED`, `DIRECTION_UNSUPPORTED` | Choose another pair: no direct market or route through USDT or USDC exists, or a buy on the route would pay its fee in the asset it spends.                                                                   |
| `ServiceUnavailableError` | `QUOTE_UNAVAILABLE`, `SERVICE_UNAVAILABLE`   | Back off and retry. Repeat a `create` or `cancel` with the same input.                                                                                                                                        |
| `AlreadyExistsError`      | `IDEMPOTENCY_CONFLICT`                       | The key was used with different input; `detail.swapId` is that swap.                                                                                                                                          |
| `ResourceNotFoundError`   | `SWAP_NOT_FOUND`                             | Check the selector and the authenticated account.                                                                                                                                                             |
| `PreconditionFailedError` | `SWAP_ALREADY_FINAL`                         | The swap ended before a cancel was recorded. Read `detail.swapId` with `get`.                                                                                                                                 |
| `PreconditionFailedError` | `SWAP_NOT_CANCELABLE`                        | An auto-withdraw conversion; let it finish.                                                                                                                                                                   |
| `PermissionError`         | `SWAP_NOT_PERMITTED`                         | The role or policy does not grant `swap`, or a root-scoped API key selected a subaccount.                                                                                                                     |

For a bad `account` on `quote`, `create`, or `list`, `INVALID_SUBACCOUNT_ID` throws `ValidationError` and `SUBACCOUNT_NOT_FOUND` throws `ResourceNotFoundError`. `SUBACCOUNT_INACTIVE` throws `PreconditionFailedError` on `quote` and `create` only. These request errors are distinct from a swap's `status` and `reason`. The `SwapErrorCode` type names every code.

## Shapes

Amounts are decimal strings and times are epoch milliseconds. Enum fields read `"unspecified"` for a value this SDK build does not know.

```ts
import type {
	Swap,
	SwapExecution,
	SwapLeg,
	SwapOrder,
	SwapProgress,
	SwapQuote,
	SwapQuoteLeg,
	SwapReason,
	SwapSlice,
	SwapSliceReason,
	SwapStatus,
} from "@polyester/sdk";

type SwapExecution =
	{ type: "market" } | { type: "twap"; durationMs: number; sliceIntervalMs: number };

interface SwapQuote {
	subaccountId: string | null; // null for the root account
	sourceAssetId: number;
	destinationAssetId: number;
	amount: string; // source amount quoted
	execution: SwapExecution | { type: "unspecified" };
	legs: SwapQuoteLeg[]; // the direct market, or two markets through intermediateAssetId
	intermediateAssetId: number | null; // USDT or USDC on a two-leg route; null when direct
	priceImpactBps: number; // end to end over every leg, rounded up
	totalSlices: number; // 1 at market
	expectedAmountOut: string; // estimated destination amount after fees at current depth
	minAmountOut: string; // after fees at the requested slippage; pass to create
	quotedAt: number | null;
	expiresAt: number | null; // 30 seconds after quotedAt; pass to create as quoteExpiresAt
}

interface SwapQuoteLeg {
	symbolId: number;
	side: "buy" | "sell" | "unspecified";
	averagePrice: string; // estimated average fill price, quote per base, for display
	priceImpactBps: number; // distance of averagePrice from the best price, rounded up
	takerFeeRatePercent: string; // the account's spot taker fee rate, e.g. "0.1"
	fee: string; // estimated, in feeAssetId (the asset the leg receives)
	feeAssetId: number;
}

interface Swap {
	swapId: string;
	idempotencyKey: string;
	subaccountId: string | null; // funding subaccount; null for the root account
	sourceAssetId: number;
	destinationAssetId: number;
	amount: string; // source amount requested
	minAmountOut: string; // least destination amount after fees for the whole amount
	status: SwapStatus | "unspecified";
	reason: SwapReason | "unspecified" | null;
	isTerminal: boolean; // stop polling once true
	executedAmount: string; // source spent in settled fills
	unspentAmount: string; // source that never left the account
	receivedAmount: string; // destination received after fees
	orders: SwapOrder[]; // spot orders, in placement order
	createdAt: number | null;
	execution: SwapExecution | { type: "unspecified" };
	intermediateAssetId: number | null; // null for a direct route
	intermediateRemainder: string; // unconverted intermediate on the account; "0" when direct
	legs: SwapLeg[]; // the route's markets in order, with settled totals
	progress: SwapProgress | null; // null before execution is planned
	cancelRequestedAt: number | null; // set once by the first recorded cancel
}

interface SwapLeg {
	leg: number; // zero-based position of the market in the route
	symbolId: number;
	side: "buy" | "sell" | "unspecified";
	spent: string; // fees in the spent asset included
	received: string; // after fees
	fee: string; // in feeAssetId (the asset the leg receives)
	feeAssetId: number;
}

interface SwapOrder {
	orderId: string | null; // spot order ID once the market accepted it
	symbolId: number;
	side: "buy" | "sell" | "unspecified";
	leg: number;
	status: "placing" | "placed" | "refused" | "not_placed" | "unconfirmed" | "unspecified";
	limitPrice: string; // IOC limit, quote per base: the worst price that nets the minimum rate
	spent: string;
	received: string;
	fee: string; // in the asset the order receives
	slice: number; // zero-based TWAP slice; 0 at market
}

interface SwapProgress {
	completedSlices: number; // slices that traded source amount and are over, listed or not
	totalSlices: number; // 1 at market
	startedAt: number | null; // a TWAP's first slot; null at market and until planned
	deadline: number | null; // last moment an order may be sent; null until planned
	slices: SwapSlice[]; // a TWAP's first 50 slices, future ones included; empty at market
	slicesTruncated: boolean; // true when the TWAP has more than 50 slices
}

interface SwapSlice {
	index: number; // zero-based position in the frozen schedule
	plannedAt: number | null; // scheduled start of the slot
	executedAt: number | null; // when its first order was sent
	finishedAt: number | null; // when its outcome became final
	state:
		"planned" | "executing" | "traded" | "partly_traded" | "skipped" | "failed" | "unspecified";
	reason: SwapSliceReason | "unspecified" | null; // why a final slice did not trade in full
	completed: boolean; // traded source amount and is over
	inputTraded: string; // source the first leg spent
	outputReceived: string; // destination after fees; can include carried intermediate
	secondLegInput: string; // intermediate the second leg spent; "0" when direct
	intermediateCarried: string; // intermediate no second leg converted by the slice's end
	carryReason: SwapSliceReason | "unspecified" | null; // why that intermediate was carried
}
```

A slice is `planned` until an order is sent and `executing` until its outcome is final. `traded` traded its planned orders in full, `partly_traded` left an order partly unfilled or intermediate unconverted, and `skipped` and `failed` traded no input. Slice reasons are `slot_missed`, `deadline_reached`, `market_closed`, `below_minimum`, `above_maximum`, `protection_not_met`, `refused`, `insufficient_liquidity`, `execution_ended`, and `canceled`.

## Related

- [Balances](https://testnet.polyester.com/docs/sdk/typescript/reference/balances) for the Trading balances a swap spends and credits.
- [Auto-withdraw](https://testnet.polyester.com/docs/sdk/typescript/reference/auto-withdraw) for payout-asset rules that convert through Swap.
- [Dust conversion](https://testnet.polyester.com/docs/sdk/typescript/reference/dust-conversion) for balances too small to swap.
- [API keys](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys) for the `swap` policy action.
- [Errors](https://testnet.polyester.com/docs/sdk/typescript/reference/errors) for the error classes and `detail`.
- [Swap](https://testnet.polyester.com/docs/developer-docs/shared-concepts/swap) in the developer docs for the underlying API.
