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 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
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.
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
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. 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.
const twapQuote = await client.swap.quote({
...terms,
maxSlippageBps: 50,
execution: { type: "twap", durationMs: 30 * 60_000, sliceIntervalMs: 60_000 },
});
console.log(twapQuote.totalSlices); // 30The 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.
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:
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.
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).
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.
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:
canceledwith reasonuser_canceled: the cancel stopped it. The amounts show exactly what traded.completed,partially_completed, orfailed: the cancel came too late to stop anything, so the swap ends with the outcome it would have had.cancelRequestedAtis 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.
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.
failed with reason minimum_not_met, and its amounts and balances show what actually traded. Reconcile them
before submitting another conversion.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:
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.
Errors
Refusals carry their code on the error's detail (detail.service === "swap"):
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.
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 for the Trading balances a swap spends and credits.
- Auto-withdraw for payout-asset rules that convert through Swap.
- Dust conversion for balances too small to swap.
- API keys for the
swappolicy action. - Errors for the error classes and
detail. - Swap in the developer docs for the underlying API.