> For the complete documentation index, see [llms.txt](https://txnlab.gitbook.io/haystack-dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://txnlab.gitbook.io/haystack-dev/haystack-router/api-order-router.md).

# Swap API

Haystack Order Router API specifications for fetching quotes and executing swaps.

## Overview

Base URL: `https://hayrouter.txnlab.dev`

Swapping takes two calls:

1. `GET /api/fetchQuote` finds the best route and returns a quote, including an opaque `txnPayload`.
2. `POST /api/fetchExecuteSwapTxns` turns that `txnPayload` into a transaction group for the swapper to sign and submit.

{% hint style="info" %}
The [TypeScript SDK](/haystack-dev/haystack-router/sdk.md) wraps both calls, including signing and submission. Use it unless you need to call the API directly.
{% endhint %}

#### Prices: use the Haystack API

{% hint style="danger" %}
**Don't call `fetchQuote` to get prices.** A quote searches routes across every pool the router aggregates for one exact trade, so it is slow, and it uses up your rate limit. Quote only for a swap a user is about to make, once they've entered an amount.
{% endhint %}

For prices, use the [Haystack API](/haystack-dev/haystack-api/overview.md), which is far faster:

* [`GET /api/assets/prices`](/haystack-dev/haystack-api/assets.md#prices): the current price of up to 100 assets in one call, in ALGO and USD.
* [WebSocket](/haystack-dev/haystack-api/websocket.md): live price updates as trades happen.

A quote isn't a price anyway: it is what one trade of that size would deliver, after price impact and fees.

The Haystack API has its own [free-tier key](/haystack-dev/getting-started/api-keys.md#getting-a-key) for servers, scripts and apps. The router's free key doesn't work there.

#### API keys and rate limits

An API key is required for `fetchQuote` and `fetchExecuteSwapTxns`. [API Keys](/haystack-dev/getting-started/api-keys.md) covers the key kinds and how to get one. Send it in the `X-API-Key` header:

```bash
curl -H "X-API-Key: hay_pk_4zhj33wahuxfplteyif5xpcgnm" "https://hayrouter.txnlab.dev/api/fetchQuote?fromASAID=0&toASAID=31566704&amount=100000000&type=fixed-input"
```

A key in the URL ends up in server logs, browser history and caches, so the header is the recommended way. The `apiKey` query parameter (GET) and `apiKey` body field (POST) still work for existing integrations; when a request carries both, the header wins. Browsers may send the header cross-origin: the API allows it in CORS preflights.

Keys starting with `hay_sk_` are secret keys, for your own servers only. They are accepted only in the header or the body, and a request with one in the URL is rejected with `400`, even when the header also carries a key.

The public free-tier key `hay_pk_4zhj33wahuxfplteyif5xpcgnm` is limited to 60 requests per minute per IP, shared between `fetchQuote` and `fetchExecuteSwapTxns`. It works from any origin, in browsers and on servers. For a key with a higher limit, see [Getting a key](/haystack-dev/getting-started/api-keys.md#getting-a-key) for what to send us.

{% hint style="warning" %}
The previous free-tier key, `1b72df7e-1131-4449-8ce1-29b79dd3f51e`, is deprecated. Its limit falls from 60 to 10 requests per minute per IP between December 1, 2026 and March 1, 2027, and it stops working on April 1, 2027. Responses to it carry a `Deprecation` header, and a `Sunset` header giving March 1, 2027, when its limit reaches 10. Switch to the key above, which works the same way.
{% endhint %}

Every API key executes its swaps through the [V4 Order Router App](/haystack-dev/haystack-router/architecture/order-router-app-v4.md). Since November 5, 2026 the API no longer builds for the [V3 app](/haystack-dev/haystack-router/architecture/order-router-app.md): a quote made for V3 gets `400 Quote is no longer executable, fetch a new quote` from `fetchExecuteSwapTxns`. Integrations using the [SDK](/haystack-dev/haystack-router/sdk.md) need version 3.2.0 or later.

Requests over the limit receive `429 Too Many Requests` with the plain-text body `Rate limit exceeded` and a `Retry-After` header: the seconds until the limit resets. Wait that long before retrying. On `fetchQuote` and `fetchAssets` the 429 can arrive after a delay of up to 5 seconds, which `Retry-After` already counts; `fetchExecuteSwapTxns` returns it immediately. `fetchAssets` has no key and is limited to 10 requests per minute per IP.

When the router is too busy to compute a quote in time, `fetchQuote` answers `503 Service Unavailable` with `Retry-After: 1` and a plain-text body naming the reason. The router was either busy, or the quote ran past its 10-second limit. Retry after that second; the next request may reach a less busy server. The [SDK](/haystack-dev/haystack-router/sdk.md) does this for you from version 3.6.0: it waits the `Retry-After` and retries once, then passes a second 503 to you as an `HTTPError`. Earlier versions throw the first.

#### Errors

Error responses are plain text (`Content-Type: text/plain`) containing a short message, for example `invalid api key`. The one exception is an unregistered referrer on `fetchQuote`, which returns JSON: `{"error": "..."}`.

#### Networks

Only Algorand `mainnet` is supported.

#### Pre-bonding HayLaunch tokens

Every API key can quote and swap a HayLaunch token still on its bonding curve, but a buy credits a balance in the HayLaunch app rather than an ASA in the wallet, and the quote needs the `slippage` you will execute with. See [Special Tokens & Accounts](/haystack-dev/haystack-router/special-tokens.md#pre-bonding-haylaunch-tokens).

#### First Stage taxed tokens

On V4 the router wraps swaps of First Stage tokens (MOOJ and others) from or into a frozen holding in First Stage's own calls, and quotes net of the tax. Pass the swapper's `address` to `fetchQuote`. See [Special Tokens & Accounts](/haystack-dev/haystack-router/special-tokens.md#first-stage-taxed-tokens).

#### Falcon (post-quantum) accounts

A Falcon-1024 signature (passkey accounts, Pera and Lute quantum accounts) costs 0.002 ALGO more per transaction. Pass `signerType=falcon` to `fetchQuote`, and check `fetchExecuteSwapTxns`'s `signerType` to know whether the group's fees include it. See [Special Tokens & Accounts](/haystack-dev/haystack-router/special-tokens.md#falcon-post-quantum-accounts).

## Fetch the Haystack quote for a given swap.

<mark style="color:blue;">`GET`</mark> `https://hayrouter.txnlab.dev/api/fetchQuote`

#### Query Parameters

| Name                                        | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| apiKey                                      | String  | API key, when not sent in the `X-API-Key` header (recommended). Never a `hay_sk_` secret key. See [API keys and rate limits](#api-keys-and-rate-limits).                                                                                                                                                                                                                                                                                                 |
| fromASAID<mark style="color:red;">\*</mark> | Integer | The asset ID of the input asset for the swap (ALGO ID is 0).                                                                                                                                                                                                                                                                                                                                                                                             |
| toASAID<mark style="color:red;">\*</mark>   | Integer | The asset ID of the output asset for the swap (ALGO ID is 0).                                                                                                                                                                                                                                                                                                                                                                                            |
| amount<mark style="color:red;">\*</mark>    | Integer | Swap amount. The input swap amount, if the swap type is `fixed-input`, or the desired output swap amount, if the swap type is `fixed-output`. **The amount is expected to be in base units (not normalized to account for decimals)**. Eg. an amount of 1000001 for asset ALGO would equate to 1.000001 ALGO (since ALGO is displayed with 6 decimals).                                                                                                  |
| type<mark style="color:red;">\*</mark>      | String  | Swap type. Either `fixed-input` or `fixed-output`.                                                                                                                                                                                                                                                                                                                                                                                                       |
| disabledProtocols                           | String  | <p>Comma-delimited list of protocols to exclude from routing (case-insensitive). Valid protocol names are:<br>- <code>Pact</code> (includes Pact stableswap, Pact V2 and Pact V2 concentrated liquidity pools)<br>- <code>TinymanV2</code><br>- <code>Humble</code><br>- <code>Algofi</code> (includes AlgoFi nanoswap and lending pools)<br>- <code>Folks</code><br>- <code>TAlgo</code><br>- <code>XAlgo</code><br>Unrecognized names are ignored.</p> |
| maxDepth                                    | Integer | Maximum number of hops in a single route path. The default is `4`, the maximum is `5`. On [V4](/haystack-dev/haystack-router/architecture/order-router-app-v4.md#why-v4), `5` quotes the same as `4`: V4's wider split routes already deliver what longer paths added.                                                                                                                                                                                   |
| maxGroupSize                                | Integer | The max allowable size of the transaction group for the quote to be generated. The default is `16` (the Algorand maximum). Slots needed by the transactions `fetchExecuteSwapTxns` prepends (see `optIn`) are reserved automatically.                                                                                                                                                                                                                    |
| optIn                                       | Boolean | <p>Set to <code>true</code> to have the transactions returned from <code>fetchExecuteSwapTxns</code> include the swapper's opt-in to the output asset. The default is <code>false</code>.</p><p>Whether or not an opt-in is necessary is up to the caller to determine. Ignored when the output asset is ALGO. Uses one slot of <code>maxGroupSize</code>.</p>                                                                                           |
| referrerAddress                             | String  | Algorand address of the referrer, who will receive 25% of the swap fees in their referrer escrow. The address must be registered with the [referral program](/haystack-dev/haystack-router/referral-program.md), otherwise the request fails with a 400. When not set, the protocol treasury receives the full fee.                                                                                                                                      |
| feeBps                                      | Integer | <p>Fee in basis points charged on the output, split 75% / 25% between treasury and referrer.<br>The default and minimum is <code>10</code> (0.10%); lower values are raised to 10. The order router app caps total fees (including captured positive slippage) at 3% of the expected output. See <a href="/haystack-dev/haystack-router/fees.md">Fees</a>.</p>                                                                                           |
| slippage                                    | Number  | Slippage tolerance in percent, from 0 (inclusive) to 100 (exclusive). Used only by quotes into or out of a [pre-bonding HayLaunch token](/haystack-dev/haystack-router/special-tokens.md#pre-bonding-haylaunch-tokens), which are priced on the floors `fetchExecuteSwapTxns` will use at this slippage. Pass the value you will execute with. Other quotes ignore it.                                                                                   |
| address                                     | String  | Algorand address of the swapper. Used only by quotes of a [First Stage taxed token](/haystack-dev/haystack-router/special-tokens.md#first-stage-taxed-tokens), which are taxed and wrapped only when this account's holding is frozen; without it, they are quoted unwrapped. Other quotes ignore it. An invalid address returns `400 Invalid address`.                                                                                                  |
| signerType                                  | String  | The kind of key the swapper's account signs with: `ed25519` (the default) or `falcon`. With `falcon`, the group's fees include the extra fee of each transaction the swapper signs; see [Falcon (post-quantum) accounts](/haystack-dev/haystack-router/special-tokens.md#falcon-post-quantum-accounts). Other values return a 400.                                                                                                                       |
| atomicOnly                                  | Boolean | Guarantee that the swap can be executed using a single transaction group. Either `true` or `false`. The default is `true`.                                                                                                                                                                                                                                                                                                                               |
| chain                                       | String  | Chain for the given swap. Only `mainnet` (the default) is supported. Unknown values are rejected with `400 Invalid chain`.                                                                                                                                                                                                                                                                                                                               |

#### Request headers

| Name      | Description                                                                                                         |
| --------- | ------------------------------------------------------------------------------------------------------------------- |
| X-API-Key | API key (recommended over the `apiKey` query parameter). See [API keys and rate limits](#api-keys-and-rate-limits). |

#### Example request

```bash
curl -H "X-API-Key: hay_pk_4zhj33wahuxfplteyif5xpcgnm" "https://hayrouter.txnlab.dev/api/fetchQuote?fromASAID=0&toASAID=31566704&amount=100000000&type=fixed-input"
```

#### Response fields

| Field                          | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `quote`                        | The Haystack quote, in base units. For `fixed-input` quotes, the output amount the swapper receives (net of the Haystack fee). For `fixed-output` quotes, the input amount required.                                                                                                                                                                                                                                                                                                                                                           |
| `profit`                       | `{ amount, asa }`: how much better `quote` (after the Haystack fee) is than the best entry in `quotes` (swapping directly on that pool, with no Haystack fee), in base units of `asa`: more output for `fixed-input`, less input for `fixed-output`. `0` when the route doesn't beat the best direct pool after the fee; never negative. `asa` is an [asset object](#fetch-the-list-of-supported-assets).                                                                                                                                      |
| `priceBaseline`                | Baseline (spot) price of the pools the route uses, before price impact. Informational: `userPriceImpact` is computed from USD prices, not from this value.                                                                                                                                                                                                                                                                                                                                                                                     |
| `userPriceImpact`              | Price impact to the user in percent, including fees, computed from the USD values below.                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `usdIn` / `usdOut`             | Approximate USD value of the input and output amounts. `0` if either asset has no USD price.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `route`                        | The routing of the swap: a list of `{ percentage, path }` splits. Each `path` is a list of hops `{ name, class, in, out }`, where `in`/`out` are asset objects. A hop split across several pools has a combined name, e.g. `"tinyman-V2: 0.36% fee tier (97%), algofi: 0.75% fee tier (3%)"`.                                                                                                                                                                                                                                                  |
| `flattenedRoute`               | Share of the route handled by each protocol (0–1, summing to 1), for display. Each split's percentage is divided evenly across its hops, then by each pool's share within a hop.                                                                                                                                                                                                                                                                                                                                                               |
| `quotes`                       | Quotes from individual pools that trade the pair directly (`{ class, name, value }`), best first, before the Haystack fee. Useful for comparison; an empty array when no pool trades the pair directly.                                                                                                                                                                                                                                                                                                                                        |
| `protocolFees`                 | Estimated fees per protocol, in base units. The `deflex` key holds the Haystack Order Router fee.                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `requiredAppOptIns`            | Application IDs the swapper must be opted into before executing. Currently always empty.                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `txnPayload`                   | `{ iv, data }`: an opaque, encrypted payload. Pass it unchanged to `fetchExecuteSwapTxns` as `txnPayloadJSON`.                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `launch`                       | Present only when one side is a [pre-bonding HayLaunch token](/haystack-dev/haystack-router/special-tokens.md#pre-bonding-haylaunch-tokens): `side` (`buy` or `sell`), `tokenNum`, `bondingTokenId`, and `bondingSurplus` (the bonding asset, in base units, the swap is quoted to leave in the wallet). A buy that sells out the curve adds `graduates: true` and `refund` (the bonding asset it returns unspent). For a buy, `quote` is launch tokens out; for a sell, the output asset. `quotes` and `profit` are cleared for these quotes. |
| `firstStage`                   | Present only when the swap wraps a [First Stage taxed token](/haystack-dev/haystack-router/special-tokens.md#first-stage-taxed-tokens): `fromTax` (the input's sell tax) and `toTax` (the output's buy tax), in base units of that side's asset, and `wrapped`, the sides (`from`, `to`) wrapped in First Stage's calls when their holding is frozen. `quote` is already net of these taxes.                                                                                                                                                   |
| `signerType`                   | `"falcon"` when the request asked for it and the router supports it. Absent otherwise. Whether a group's fees include a Falcon signer's extra fees is `fetchExecuteSwapTxns`'s `signerType`. See [Falcon (post-quantum) accounts](/haystack-dev/haystack-router/special-tokens.md#falcon-post-quantum-accounts).                                                                                                                                                                                                                               |
| `fromASAID`, `toASAID`, `type` | Echo of the request.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `traceId`                      | Request trace ID. Include it when reporting issues.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `aggregatedArtifacts`, `ui`    | Internal routing details used by the Haystack app. Informational only and subject to change.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

If no route is found, the response is still `200` with `quote: 0`, an empty `route`, and an empty `txnPayload.data`. The other fields are only partly filled in that case (for example, `traceId` is empty and `type` is returned as `to` or `from`). Check that `quote` is greater than 0 before calling `fetchExecuteSwapTxns`, which rejects the empty payload with a 400.

{% tabs %}
{% tab title="200: OK The Haystack quote object." %}

```javascript
{
  traceId: '20c56a6e0dfb38da68be907710717e99',
  quote: 12354576, // 12.354576 USDC out for 100 ALGO in, net of the Haystack fee
  profit: {
    amount: 0,
    asa: { id: 31566704, name: 'USDC', unit_name: 'USDC', decimals: 6, is_verified: true, verification_tier_pera: 1, total_swaps: '22515259', price_algo: 8.094882239006449, price_usd: 1 }
  },
  priceBaseline: 7.931309971357813,
  userPriceImpact: -0.008837832855350274, // negative: the output is worth slightly more than the input at reference prices
  usdIn: 12.35348421971285,
  usdOut: 12.354576,
  route: [
    {
      percentage: 56, // 56% of the input: ALGO -> USDC directly on Pact V2
      path: [
        { name: 'pact-v2: 0.36% fee tier', class: [['PactV2Swapper']], in: { id: 0, unit_name: 'ALGO', /* ... */ }, out: { id: 31566704, unit_name: 'USDC', /* ... */ } }
      ]
    },
    {
      percentage: 42, // ALGO -> xALGO -> FOLKS -> USDC, with the last hop split across three pools
      path: [
        { name: 'xalgo: 0% fee tier', class: [['XAlgoSwapper']], in: { id: 0, /* ... */ }, out: { id: 1134696561, unit_name: 'xALGO', /* ... */ } },
        { name: 'tinyman-V2: 0.36% fee tier', class: [['TinymanV2Swapper']], in: { id: 1134696561, /* ... */ }, out: { id: 3203964481, unit_name: 'FOLKS', /* ... */ } },
        {
          name: 'pact-v2: 1% fee tier (24%), tinyman-V2: 0.36% fee tier (65%), pact: 1% fee tier (11%)',
          class: [['PactV2Swapper'], ['TinymanV2Swapper'], ['PactConstantProductSwapper']],
          in: { id: 3203964481, /* ... */ },
          out: { id: 31566704, /* ... */ }
        }
      ]
    },
    {
      percentage: 2, // ALGO -> USDt -> USDC
      path: [
        { name: 'algofi: 0.75% fee tier', class: [['AlgoFiConstantProductSwapper']], in: { id: 0, /* ... */ }, out: { id: 312769, unit_name: 'USDt', /* ... */ } },
        { name: 'pact-stable: 0.04% fee tier', class: [['PactStableSwapper']], in: { id: 312769, /* ... */ }, out: { id: 31566704, /* ... */ } }
      ]
    }
  ],
  flattenedRoute: { algofi: 0.01, pact: 0.0154, 'pact-stable': 0.01, 'pact-v2': 0.5936, 'tinyman-V2': 0.231, xalgo: 0.14 },
  quotes: [ // direct single-pool quotes (before the Haystack fee), best first
    { class: 'PactV2Swapper', name: 'pact-v2: 0.36% fee tier', value: 12357433 },
    { class: 'PactConstantProductSwapper', name: 'pact: 0.3% fee tier', value: 12327684 },
    { class: 'AlgoFiConstantProductSwapper', name: 'algofi: 0.25% fee tier', value: 12320245 },
    { class: 'TinymanV2Swapper', name: 'tinyman-V2: 0.36% fee tier', value: 12294553 }
  ],
  protocolFees: { algofi: 933, deflex: 12368, pact: 1921, 'pact-stable': 49, 'pact-v2': 29188, 'tinyman-V2': 10310, xalgo: 0 },
  requiredAppOptIns: [],
  txnPayload: {
    iv: '',
    data: 'aXhQWFlzYClifGluI14ue35yTlZgfC5mY0gmIConKjR7QkRRJCAoQjg5LUJO...' // opaque, pass back unchanged
  },
  fromASAID: 0,
  toASAID: 31566704,
  type: 'fixed-input',
  aggregatedArtifacts: { /* internal */ },
  ui: { /* internal */ }
}
```

{% endtab %}

{% tab title="400: Bad Request One of the input params does not match validation criteria." %}

```
invalid api key
```

Other messages include:

* `secret API keys must be sent in the X-API-Key header, not the URL`
* `Invalid chain`
* `type argument must be 'fixed-input' or 'fixed-output'`
* `feeBps must be an integer between 0 and 9999`
* `Invalid referrer address`
* `invalid assets` (followed by the details, e.g. an unknown asset ID)
* `same-asset swaps are not supported` (`fromASAID` equal to `toASAID`)
* `Slippage must be a number between 0 (inclusive) and 100 (exclusive)`
* `pre-bonding HayLaunch tokens support fixed-input quotes only`
* `swaps between two pre-bonding HayLaunch tokens are not supported`

An unregistered `referrerAddress` returns JSON:

```json
{"error": "Referrer address '<address>' has not registered with the Haystack Router treasury. Please register at https://hay.app/refer/"}
```

{% endtab %}

{% tab title="429: Too Many Requests Rate limit exceeded." %}

```
Rate limit exceeded
```

{% endtab %}

{% tab title="500: Internal Server Error An exception was thrown and not gracefully handled." %}
Plain-text error message.
{% endtab %}

{% tab title="503: Service Unavailable The router is too busy to quote in time." %}

```
quote not started: the router is busy
```

or `quote stopped at its deadline`. Retry after the `Retry-After` header's 1 second.
{% endtab %}
{% endtabs %}

## Fetch the transaction group for a given Haystack quote.

<mark style="color:green;">`POST`</mark> `https://hayrouter.txnlab.dev/api/fetchExecuteSwapTxns`

Returns a single atomic transaction group that executes the quote through the Order Router App. The group is laid out as described in [Order Router App V4](/haystack-dev/haystack-router/architecture/order-router-app-v4.md#transaction-group).

For `fixed-output` swaps, the beneficiary receives exactly the target, and the surplus is swapped back to the input asset; when it is too small to swap back, or the pair has no pool to swap it back on, it is delivered in the output asset instead. Input the route didn't use is returned to the beneficiary.

#### Request headers

| Name         | Description                                                                                                    |
| ------------ | -------------------------------------------------------------------------------------------------------------- |
| X-API-Key    | API key (recommended over the `apiKey` body field). See [API keys and rate limits](#api-keys-and-rate-limits). |
| Content-Type | `application/json`                                                                                             |

#### Request Body

| Name                                             | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| address<mark style="color:red;">\*</mark>        | String | Algorand address of the swapper.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| txnPayloadJSON<mark style="color:red;">\*</mark> | Object | Txn payload from the Haystack quote (value at `txnPayload` key), unchanged.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| slippage<mark style="color:red;">\*</mark>       | Number | Slippage tolerance in percent, from 0 (inclusive) to 100 (exclusive), e.g. `0.5` for 0.5%. For `fixed-input`, the minimum output is `quote × (1 − slippage / 100)`. For `fixed-output`, the output is exact and the input sent is raised to `quote / (1 − slippage / 100)`. When the route swaps its surplus back, that extra input is swapped forward through the same pool and the excess swapped back, so the swap still delivers if prices move against it by up to about half the slippage, at a cost of about two pool fees on the extra input. On other routes, and on swaps too small for this to cover its network fee, the extra input is not used. Unused input is sent to the beneficiary. |
| apiKey                                           | String | API key, when not sent in the `X-API-Key` header (recommended). See [API keys and rate limits](#api-keys-and-rate-limits).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| beneficiary                                      | String | Algorand address that receives the swap output. The default is `address`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |

#### Response fields

| Field                 | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `txns`                | The transactions of the group, in order. Each has `data` (base64 msgpack of the unsigned transaction), `group` (base64 group ID), `logicSigBlob` and `signature`.                                                                                                                                                                                                                                                                                                        |
| `txns[].logicSigBlob` | `false` for transactions the swapper must sign. For transactions the server has already signed, the signed transaction bytes, encoded as an object mapping each byte index to its value (`{"0": 130, "1": 163, ...}`). Submit these as-is.                                                                                                                                                                                                                               |
| `txns[].signature`    | `false` for transactions the swapper must sign; otherwise describes how the server signed the transaction. Can be ignored.                                                                                                                                                                                                                                                                                                                                               |
| `groupMetadata`       | One entry per group: `group`, `labelText`, `amount` (the input amount sent, after slippage), `swapCount`, `labelMetadata`, `plannedRefund`, `routerVersion` and `signerType`. `labelText` is `Haystack Router fixed-input swap` or `Haystack Router fixed-output swap`. `routerVersion` is `4`, and absent for a swap with no Order Router call (a pre-bonding HayLaunch token bought or sold directly for its bonding asset). `signerType` is as below, for that group. |
| `plannedRefundTotal`  | Reserved, currently always `0`.                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `signerType`          | `"falcon"` when the group's fees include a Falcon signer's extra fees. Absent otherwise: then the swapper's group needs 0.002 ALGO more on its input transfer for each transaction a Falcon account signs. See [Falcon (post-quantum) accounts](/haystack-dev/haystack-router/special-tokens.md#falcon-post-quantum-accounts).                                                                                                                                           |

{% tabs %}
{% tab title="200: OK The transaction group to execute the swap." %}

```javascript
{
  txns: [ // transactions to execute for the swap, in order. See example JS below on how to submit for execution.
    {
      data: 'i6RhcGFhk8QE3NM248QIAAAA...',
      group: 'XHmXA4NW4bGZ3ve5ud6+B2WfN5IHuO1/ERrWrJ9lrWw=',
      logicSigBlob: { '0': 130, '1': 163, '2': 115, /* ... */ }, // pre-signed by the server
      signature: { type: 'secret_key', value: { /* ... */ } }
    },
    {
      data: 'jKRhYW10zgAS/U6kYXJjdsQgJJ7tSYDoXgAAoG+8QrTmjs6fbpp2Geim8iP9hwacOmejZmVlzfYYomZ2zgPn6EmjZ2VurG1haW5uZXQtdjEuMKJnaMQgwGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit+jZ3JwxCBceZcDg1bhsZne97m53r4HZZ83kge47X8RGtasn2WtbKJsds4D5+wxpG5vdGXEFGRlZmxleC1mcmVlLTAuODQ1NDcwo3NuZMQgs7y0WruVAmUiLrbpwoi9eMUKKDMtiy9MtX50JxuXoOykdHlwZaVheGZlcqR4YWlkzgHhq3A=',
      group: 'XHmXA4NW4bGZ3ve5ud6+B2WfN5IHuO1/ERrWrJ9lrWw=',
      logicSigBlob: false, // the swapper's input transfer: must be signed by the swapper
      signature: false
    },
    // ... the remaining pre-signed order router app calls
  ],
  groupMetadata: [
    {
      group: 'XHmXA4NW4bGZ3ve5ud6+B2WfN5IHuO1/ERrWrJ9lrWw=',
      labelText: 'Deflex from Swap',
      labelMetadata: null,
      amount: 1244494,
      swapCount: 4,
      plannedRefund: 0
    }
  ],
  plannedRefundTotal: 0
}

/* EXAMPLE JS TO SUBMIT TXN GROUP (algosdk v3)

import algosdk from 'algosdk'

const account = algosdk.mnemonicToSecretKey('<insert_mnemonic>')

const signedTxns = response.txns.map((txn) => {
  if (txn.logicSigBlob !== false) {
    // already signed by the server: rebuild the bytes from the index -> byte object
    return Uint8Array.from(Object.values(txn.logicSigBlob))
  }
  const decoded = algosdk.decodeUnsignedTransaction(Buffer.from(txn.data, 'base64'))
  return decoded.signTxn(account.sk)
})

const algod = new algosdk.Algodv2('', 'https://mainnet-api.4160.nodely.dev', '')
const { txid } = await algod.sendRawTransaction(signedTxns).do()
await algosdk.waitForConfirmation(algod, txid, 4)
*/
```

{% endtab %}

{% tab title="400: Bad Request One of the input params does not match validation criteria." %}

```
Invalid Algorand address
```

Other messages include:

* `invalid api key`
* `Invalid request body`
* `Slippage must be a valid number`
* `Slippage must be a number between 0 (inclusive) and 100 (exclusive)`
* `Invalid txnPayload data`
* `Failed to parse decrypted payload` (also returned for the empty payload of a quote with `quote: 0`)
* `Failed to parse artifacts from payload`
* `Quote is no longer executable, fetch a new quote` (a V4 quote for a key no longer on V4)
* A `beneficiary` on a [pre-bonding HayLaunch](/haystack-dev/haystack-router/special-tokens.md#pre-bonding-haylaunch-tokens) buy, or on a sell straight to the bonding asset
* `first stage: …`: a [First Stage](/haystack-dev/haystack-router/special-tokens.md#first-stage-taxed-tokens) sell whose amount and tax exceed the swapper's balance; a `beneficiary` whose holding of the First Stage output is frozen; or a `fixed-output` buy whose tax rose since the quote, so that the swapper would keep less than `amount` (fetch a new quote)
  {% endtab %}

{% tab title="409: Conflict The HayLaunch token has graduated since the quote." %}

```
haylaunch: token has completed bonding; request a new quote
```

The token now trades in its pool. Fetch a new quote.
{% endtab %}

{% tab title="429: Too Many Requests Rate limit exceeded." %}

```
Rate limit exceeded
```

{% endtab %}

{% tab title="500: Internal Server Error An exception was thrown and not gracefully handled." %}
Plain-text error message.
{% endtab %}
{% endtabs %}

## Fetch the list of supported assets

<mark style="color:blue;">`GET`</mark> `https://hayrouter.txnlab.dev/api/fetchAssets`

Returns every asset the router can quote, ordered by number of swaps, followed by the [pre-bonding HayLaunch tokens](/haystack-dev/haystack-router/special-tokens.md#pre-bonding-haylaunch-tokens) not already listed. Each pre-bonding token carries `launch: { platform: 'haylaunch', tokenNum, bondingTokenId }`; other assets have no `launch` field. No API key is required; limited to 10 requests per minute per IP.

#### Query Parameters

| Name  | Type   | Description                                |
| ----- | ------ | ------------------------------------------ |
| chain | String | Only `mainnet` (the default) is supported. |

{% tabs %}
{% tab title="200: OK The list of assets." %}

```javascript
[
  {
    id: 0,
    name: 'Algorand',
    unit_name: 'ALGO',
    decimals: 6,
    is_verified: true,
    verification_tier_pera: 2,
    total_swaps: '58824953',
    price_algo: 1, // price in ALGO
    price_usd: 0.12382559885241336 // price in USD (derived from USDC)
  },
  {
    id: 31566704,
    name: 'USDC',
    unit_name: 'USDC',
    decimals: 6,
    is_verified: true,
    verification_tier_pera: 1,
    total_swaps: '22508991',
    price_algo: 8.075874530531374,
    price_usd: 1
  },
  // ...
  {
    id: 3412345678, // a pre-bonding HayLaunch token
    name: 'Example',
    unit_name: 'EX',
    // ...
    launch: { platform: 'haylaunch', tokenNum: 123, bondingTokenId: 0 } // bonded against ALGO
  }
]
```

{% endtab %}
{% endtabs %}

## Fetch the referrer escrow address

<mark style="color:blue;">`GET`</mark> `https://hayrouter.txnlab.dev/api/treasuryAddress`

Returns the escrow account that holds a referrer's commissions. See [Referral Program](/haystack-dev/haystack-router/referral-program.md).

#### Query Parameters

| Name                                      | Type   | Description                       |
| ----------------------------------------- | ------ | --------------------------------- |
| address<mark style="color:red;">\*</mark> | String | Algorand address of the referrer. |

{% tabs %}
{% tab title="200: OK The referrer escrow address." %}

```json
{"address": "IKICDF5JZGTBIKRSRHO7P75QBU7MLSFYPCXT64DIM6C6W5PMPOEX5R2TYI"}
```

{% endtab %}

{% tab title="400: Bad Request Missing or invalid address." %}

```
Invalid address provided
```

{% endtab %}
{% endtabs %}

## Fetch treasury escrow account details

<mark style="color:blue;">`GET`</mark> `https://hayrouter.txnlab.dev/api/fetchTreasuryDetails`

Returns the on-chain account state of the treasury escrow accounts that receive fees: the protocol treasury escrow, plus the referrer's escrow when `referrerAddress` is given. The server refreshes its copy every minute, and responses may be cached by a CDN for up to 10 minutes. An invalid `referrerAddress` returns a 500.

#### Query Parameters

| Name            | Type   | Description                                |
| --------------- | ------ | ------------------------------------------ |
| referrerAddress | String | Algorand address of the referrer.          |
| chain           | String | Only `mainnet` (the default) is supported. |

{% tabs %}
{% tab title="200: OK Escrow account details, keyed by escrow address." %}

```javascript
{
  treasuryDetails: {
    '<escrow address>': {
      address: '<escrow address>',
      amount: 1234567,
      assets: [ /* asset holdings */ ],
      'apps-local-state': [ /* ... */ ],
      // ... remaining algod account fields
    }
  }
}
```

{% endtab %}
{% endtabs %}

## Health check

<mark style="color:blue;">`GET`</mark> `https://hayrouter.txnlab.dev/api/health`

Returns `200` with the plain-text body `OK`.
