# Dust conversion

Convert Trading balances too small to trade into one target asset.

`client.dustConversion` converts dust, Trading balances too small to trade, into one target asset at index prices less a disclosed fee. Every method is authenticated and account-scoped, so each input accepts 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.

The flow is `listBalances` to show what converts, `quote` to price it, `create` with the quote, then `get` while the conversion is `processing`. A conversion moves every source and credits the payout atomically, or moves nothing.

Limits:

- A balance converts when no open market takes an order for it and it is worth at most 10 USD.
- One conversion takes at most 20 balances, worth at most 200 USD together.
- An account converts once every 6 hours; refused conversions do not count.
- Each target asset has a daily limit.

Quoting, converting, and reading conversions need the `convert-dust` policy action on API keys and the `convert_dust` permission on subaccounts (owner, admin, trader, or leveraged trader). A subaccount's default policy does not grant it. `listBalances` needs `read-balances`. No step-up is required: the value stays in the account.

## Methods

| Method         | Summary                                                      |
| -------------- | ------------------------------------------------------------ |
| `listBalances` | List Trading balances with their eligibility for one target. |
| `quote`        | Price the account's dust into a target for 30 seconds.       |
| `create`       | Convert a quote, or return the conversion already made.      |
| `get`          | Read one conversion.                                         |
| `list`         | Page through the account's conversions, newest first.        |

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

Lists every nonzero available Trading balance with its eligibility for one target, and the payout the eligible ones would bring now. Reserves nothing. Pass `targetAssetId`, one of the result's `targets`, or omit it for the first target. An unknown `targetAssetId` throws `ValidationError`.

```ts
const view = await client.dustConversion.listBalances();

console.log(view.targets, view.targetAssetId, view.payout, view.targetAvailable);
for (const balance of view.balances) {
	console.log(balance.assetId, balance.amount, balance.eligibility, balance.usdValue);
}
```

`eligibility` says whether a balance converts:

| `eligibility`       | Meaning                                                                               |
| ------------------- | ------------------------------------------------------------------------------------- |
| `eligible`          | Converts.                                                                             |
| `target_asset`      | The conversion's target.                                                              |
| `tradable`          | An open market takes an order for it. Sell or spend it instead.                       |
| `above_value_limit` | Worth more than 10 USD.                                                               |
| `no_price`          | Has no current index price.                                                           |
| `unsupported_asset` | Never converts.                                                                       |
| `source_limit`      | Waits for the next conversion, which takes at most 20 balances, highest-valued first. |

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

Prices the account's dust into `targetAssetId`, one of `listBalances`' `targets`. The quote is valid for 30 seconds and reserves nothing. An empty `quoteId` means nothing converts; the quote's `balances` say why. A target that cannot be paid now throws `PreconditionFailedError` with `detail.code === "DUST_TARGET_UNAVAILABLE"`.

```ts
const quote = await client.dustConversion.quote({ targetAssetId: view.targetAssetId });

if (quote.quoteId) {
	console.log(quote.payout, quote.feeBps, quote.expiresAt);
}
```

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

Converts a quote at current index prices, or returns the conversion already made under `idempotencyKey`. Every source must still be the whole balance the quote showed. `account` must select the quote's account. The result is `completed`, or `processing` while its outcome is not known yet; read it again with `get`.

```ts
let conversion = await client.dustConversion.create({
	quoteId: quote.quoteId,
	idempotencyKey: crypto.randomUUID(),
});

if (conversion.state === "processing") {
	conversion = await client.dustConversion.get({ conversionId: conversion.conversionId });
}
```

| Field            | Type           | Required | Notes                                                        |
| ---------------- | -------------- | -------- | ------------------------------------------------------------ |
| `quoteId`        | `string`       | yes      | From `quote`, at most 30 seconds old. A quote converts once. |
| `idempotencyKey` | `string`       | yes      | Reusing it returns the same conversion.                      |
| `account`        | `AccountScope` | no       | Must select the quote's account.                             |

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

| Error                     | `detail.code`                                                                                                   | What to do                                                                                                            |
| ------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `PreconditionFailedError` | `DUST_QUOTE_EXPIRED`, `DUST_PRICE_MOVED`, `DUST_BALANCE_CHANGED`, `DUST_NOT_ELIGIBLE`, `DUST_CONVERSION_FAILED` | Quote again. `DUST_PRICE_MOVED` means the payout fell more than 1% below the quote.                                   |
| `PreconditionFailedError` | `DUST_WINDOW_ACTIVE`, `DUST_DAILY_LIMIT`                                                                        | Try later: the account converted within 6 hours or a conversion is processing, or the target reached its daily limit. |
| `RateLimitError`          | `DUST_BUSY`                                                                                                     | Retry shortly.                                                                                                        |
| `AlreadyExistsError`      | `IDEMPOTENCY_CONFLICT`                                                                                          | The key or the quote was already used for another conversion.                                                         |
| `ServiceUnavailableError` |                                                                                                                 | Retry the same request.                                                                                               |

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

Reads one of the account's conversions by `conversionId`. An unknown one throws `ResourceNotFoundError`.

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

Returns `{ conversions, nextPageToken }`, newest first. `limit` is 1 to 100 (default 20). Pass the previous `nextPageToken` as `pageToken`, with the same account; an empty `nextPageToken` means there are no more.

```ts
let pageToken = "";
do {
	const page = await client.dustConversion.list({ pageToken, limit: 50 });
	for (const c of page.conversions) console.log(c.conversionId, c.state, c.payout);
	pageToken = page.nextPageToken;
} while (pageToken !== "");
```

## Shapes

Amounts are decimal strings and times are epoch milliseconds.

```ts
import type {
	DustAssetEligibility,
	DustBalance,
	DustConversion,
	DustConversionQuote,
	ListDustBalancesResult,
} from "@polyester/sdk";

interface ListDustBalancesResult {
	targetAssetId: number; // the target the balances were judged for
	targets: number[]; // every asset the account can convert dust into, in preference order
	feeBps: number; // fee taken from the payout
	balances: DustBalance[]; // every nonzero available Trading balance, by asset id
	grossUsd: string; // eligible balances' total USD value, rounded down
	payout: string; // target amount they would bring now, after the fee
	targetAvailable: boolean; // false when the target cannot be paid now; quote is then refused
}

interface DustBalance {
	assetId: number;
	amount: string; // the whole available balance
	eligibility: DustAssetEligibility; // "unspecified" for a value this build does not know
	usdValue: string | null; // rounded down; null without a current price
}

interface DustConversionQuote {
	quoteId: string; // pass to create; "" when nothing converts
	expiresAt: number | null; // create refuses the quote after this with DUST_QUOTE_EXPIRED
	targetAssetId: number;
	feeBps: number;
	grossUsd: string; // sources' total USD value, rounded down
	payout: string; // after the fee, rounded down to the target's quantity precision
	balances: DustBalance[]; // sources and others, by asset id
	prices: { assetId: number; price: string; asOf: number | null }[]; // USD per whole unit
}

interface DustConversion {
	conversionId: string;
	quoteId: string;
	state: "processing" | "completed" | "refused" | "unspecified";
	refusalCode: string | null; // e.g. "DUST_BALANCE_CHANGED" when refused; null otherwise
	targetAssetId: number;
	sources: { assetId: number; amount: string }[]; // whole quoted balances moved, by asset id
	payout: string; // credited after the fee, at the index prices when it was created
	quotedPayout: string; // the payout the quote showed
	fee: string; // in the target asset
	feeBps: number;
	createdAt: number | null;
	completedAt: number | null; // null until completed
}
```

A `processing` conversion completes or is refused with no further request. `completed` moved every source and credited the payout atomically; `refused` moved nothing.

In [`transfers.list`](https://testnet.polyester.com/docs/sdk/typescript/reference/transfers), each source debited and the payout credited after the fee is a ledger transfer of type `dust_convert`, which the `transferCode` filter also accepts. A conversion's legs can arrive separately; read the conversion itself for its sources, payout, and fee.

## Related

- [Balances](https://testnet.polyester.com/docs/sdk/typescript/reference/balances) for the Trading balances that dust comes from.
- [Transfers](https://testnet.polyester.com/docs/sdk/typescript/reference/transfers) for the `dust_convert` ledger legs.
- [Funding services](https://testnet.polyester.com/docs/sdk/typescript/reference/funding-services) for the other funding methods.
