> 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/architecture/order-router-app-v4.md).

# Order Router App V4

{% hint style="info" %}
V4 ([3757715482](https://lora.algokit.io/mainnet/application/3757715482)) is the Order Router App: every API swap executes through it. Since November 5, 2026 the API no longer builds groups for the [V3 Order Router App](/haystack-dev/haystack-router/architecture/order-router-app.md) (3172554435).
{% endhint %}

## Overview

V4 performs a whole swap in a single `route` application call:

1. It records a baseline balance for every asset of the route.
2. It runs the route's sub-swaps (contract-to-contract calls to the DEXs) on its balance above those baselines.
3. It settles: it checks the output, pays the fees, and pays the beneficiary.

What differs from V3:

* **One call per swap.** `route` replaces `User_opt_into_assets`, `User_swap` and `User_swap_finalize`.
* **Persistent holdings.** The app stays opted into assets between swaps. Anything sent to it outside a swap stays in the baselines and is never spent or paid out.
* **Its own opcode budget.** The route issues the op-ups it needs, paid from the group's fee credit. The group's other app calls to V4 (carriers) only add references, so integrators keep the group's slots for their own transactions.
* **Exact fixed-output.** The beneficiary receives exactly the target, and the surplus is swapped back to the input asset on chain, sized from the actual output.
* **Every payout goes to the beneficiary:** the output, a refund, and ALGO the swap didn't use.
* **An ARC-28 `Swap` event** records each swap's amounts and fees.

## Why V4

The differences above add up to better execution for swappers and more room for integrators. The figures below come from our October 2026 evaluation: quotes on a snapshot of mainnet pools, and mainnet simulation of the groups the API builds.

* **Larger routes.** A V3 group splits a route into `User_swap` calls of at most 3 sub-swaps and 8 references each, and a swap trades at most 8 ASAs. The router therefore had to leave out routes that would have paid more. V4 runs every sub-swap in one call, with no limit on the assets a swap trades, so the router can split a large trade across more pools and hubs. On large multi-hop trades that V3's limits constrained, V4 delivered 0.7% to 3.1% more, net of every fee.
* **Better prices net of fees.** Across our multi-hop trade ladder, V4 delivered more on most trades of $10k and above, by a median of 0.04% to 0.35%.
* **Lower network fees.** The same route costs about 10% less in network fees on V4, in 38% fewer transactions.
* **Room for your own transactions.** The route buys its own opcode budget, so a V4 group needs no budget transactions. The slots it leaves free are yours for your own transactions in the same atomic group.
* **Exact fixed-output, with slippage that protects it.** The beneficiary receives exactly the target, and the surplus comes back in the input asset. When the pair has a pool for the refund, the slippage you allow is put to work, so the swap still delivers if prices move against it within part of the slippage. See `slippage` in [`fetchExecuteSwapTxns`](/haystack-dev/haystack-router/api-order-router.md).
* **Wider splits.** With no limit on assets, a trade with enough price impact can split across up to 12 intermediate assets, where V3 allows 6. The router keeps this plan only when it delivers more net of network fees. On our multi-hop trade ladder, 146 of 247 trades quoted better, by up to 9.5%, and none quoted worse. On mainnet simulation, 31 of 38 trades delivered more net of every fee, and the rest the same. On V4, `maxDepth=5` quotes the same as `4`, because the wider splits already deliver what longer paths added.
* **Results you can read on chain.** Each swap emits a `Swap` event with its amounts, refund and fees, so you don't need to reconstruct the result from inner transactions.

The first swap of an asset V4 doesn't yet hold pays 0.1 ALGO for the app's opt-in, once, for every later swap of it. V4 already holds the assets traded on Haystack Router in recent weeks.

## ABI

The app is [ARC-4](https://arc.algorand.foundation/ARCs/arc-0004) compliant. Its [ARC-56](https://arc.algorand.foundation/ARCs/arc-0056) spec, which can be loaded into Lora:

{% file src="/files/uDDD4jQ2gHnUaxffSIfH" %}
ARC-56 JSON
{% endfile %}

### `route`

`route(txn input, uint64[] assets, address[] accounts, SubSwap[] swaps, Settlement settlement, SubSwap refund, byte[] note)void`

Swaps `input` along `swaps`, then settles.

#### Parameters

1. `input`: the swapper's transfer of the input to the app account, directly before this call. It is a payment for ALGO, or an asset transfer, and it must not close out or be a clawback.
2. `assets`: the route's asset table. Sub-swaps and the settlement refer to assets by their index in it.
3. `accounts`: accounts that sub-swaps refer to by index (Tinyman pool addresses).
4. `swaps`: the sub-swaps, in execution order.
5. `settlement`: what the swap must deliver, and to whom.
6. `refund`: the fixed-output refund sub-swap, or a sub-swap with protocol `255` for none.
7. `note`: the note of the route's inner transactions.

A `SubSwap` is 39 bytes:

| Field        | Type       | Description                                                                                                                                                                                                                        |
| ------------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `protocol`   | `uint8`    | 0=algofi, 1=pact, 2=humble, 3=tinyman-v2, 6=folks deposit, 7=folks withdraw, 8=tALGO mint, 9=tALGO unmint, 10=xALGO mint, 11=xALGO unmint, 12=pact-v2, 13=pact-v2 concentrated liquidity (V4.3; not on V3)                         |
| `assetIn`    | `uint8`    | Index of the input asset in `assets`                                                                                                                                                                                               |
| `assetOut`   | `uint8`    | Index of the output asset in `assets`                                                                                                                                                                                              |
| `app`        | `uint64`   | The pool's app ID                                                                                                                                                                                                                  |
| `app2`       | `uint64`   | The second app: the AlgoFi or Folks manager, `0` when unused                                                                                                                                                                       |
| `account`    | `uint8`    | Index of the pool's account in `accounts` (Tinyman), `255` for none                                                                                                                                                                |
| `percentBps` | `uint16`   | The share, from 1 to 10000 bps, of the app's balance of the input asset above its baseline that the sub-swap swaps                                                                                                                 |
| `argLen`     | `uint8`    | How many bytes of `arg` the protocol uses (at most 16)                                                                                                                                                                             |
| `arg`        | `byte[16]` | Protocol-specific, zero-padded: the AlgoFi pool call's fee, Humble's direction, Tinyman's asset order, ... A Pact concentrated liquidity sub-swap carries the range of tick groups its box references cover, which the app ignores |

`Settlement`:

| Field               | Type      | Description                                                                          |
| ------------------- | --------- | ------------------------------------------------------------------------------------ |
| `assetIn`           | `uint8`   | Index of the input asset in `assets`; must be the input transfer's asset             |
| `assetOut`          | `uint8`   | Index of the output asset in `assets`                                                |
| `type`              | `uint8`   | `0` fixed-input, `1` fixed-output                                                    |
| `amount`            | `uint64`  | Fixed-input: the minimum the beneficiary receives. Fixed-output: the exact target    |
| `expectedAmountOut` | `uint64`  | Fixed-input: the quoted output; output above it becomes fees, within the 3% cap      |
| `feeBps`            | `uint16`  | Fee in basis points, at least 10 (see [Fees](/haystack-dev/haystack-router/fees.md)) |
| `minRefund`         | `uint64`  | Fixed-output: the smallest surplus the refund sub-swap swaps back                    |
| `beneficiary`       | `address` | Receives the output, any refund, and ALGO the swap didn't use                        |
| `referrer`          | `address` | The referrer escrow, or the protocol treasury escrow when there is no referrer       |

#### Execution

1. **Baselines.** The baseline of each asset in `assets` is the app's balance before the swap: less the input for the input asset, and less the ALGO credit (below) for ALGO. The app opts into any asset it doesn't hold yet.
2. **ALGO credit.** This is an ALGO input, plus one payment to the app from the same sender directly before the input. It pays the AlgoFi pool calls' fees and 0.1 ALGO for each asset the route opts the app into. What the route doesn't use goes to the beneficiary.
3. **Sub-swaps.** Each sub-swap swaps `percentBps` of the app's balance of its input asset above its baseline. A sub-swap with nothing to swap is skipped.
4. **Back at baseline.** Every intermediate asset, and a fixed-input's input asset, must be back at its baseline.
5. **Fixed-input.** The fee is `feeBps` of the output, plus any output above `expectedAmountOut`, capped at 3% of `expectedAmountOut`. The output after fees must be at least `amount`, and the beneficiary receives all of it.
6. **Fixed-output.** The fee is `feeBps` of the output before fees, rounded up, so that the output less the fee is the target, capped at 3% of the target. The output must cover the target plus the fee, and the beneficiary receives exactly the target. Then:

   * If the surplus is at least `minRefund`, `refund` swaps exactly the surplus back to the input asset.
   * Otherwise, or with no refund sub-swap, the beneficiary receives the surplus in the output asset.

   Input the sub-swaps didn't spend comes back to the beneficiary with the refund.
7. **Fees** are split 75% / 25% between the protocol treasury and the referrer, or paid in full to the treasury when there is no referrer.
8. **The event:** the route emits the `Swap` event.

### `refs`

`refs()void`

Does nothing. A carrier: it adds resource references (foreign arrays or an access list) that the route's inner calls need to a group, beyond the 8 one call can name.

### `opt_in`

`opt_in(pay funding, uint64[] assets)void`

Opts the app into `assets`. `funding` must pay the app 0.1 ALGO per asset, and assets the app already holds are refunded to the funder. Anyone can call it.

### Administration

* `propose_admin(address)` and `accept_admin()`: hand the admin role over in two steps.
* `set_paused(bool)`: while paused, `route` fails.
* `opt_out(uint64 asset, address closeTo)`: closes the app's holding of an asset to `closeTo`. Nothing is owed between swaps, so a holding is only ever dust.
* `sweep(uint64 asset)`: sends the app's dust of an asset to the protocol treasury.
* Only the admin can call these methods, and only the admin can update the app. Production builds can't be deleted.

Global state: `admin`, `pending_admin`, `paused`, `total_swaps`.

### `Swap` event

Every `route` call logs one [ARC-28](https://arc.algorand.foundation/ARCs/arc-0028) event:

`Swap(uint64,uint64,uint8,uint64,uint64,uint64,uint64,uint64,uint64,uint64,uint64,uint64,address,address,address)`

Its selector is `0x6d221c27`, and the log is 189 bytes long.

| Field           | Type      | Description                                                                                                                                                  |
| --------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `assetIn`       | `uint64`  | Input asset ID                                                                                                                                               |
| `assetOut`      | `uint64`  | Output asset ID                                                                                                                                              |
| `type`          | `uint8`   | `0` fixed-input, `1` fixed-output                                                                                                                            |
| `amount`        | `uint64`  | Fixed-input: the minimum out. Fixed-output: the target                                                                                                       |
| `amountIn`      | `uint64`  | The input transfer's amount                                                                                                                                  |
| `outDelta`      | `uint64`  | The app's output above its baseline, before fees                                                                                                             |
| `delivered`     | `uint64`  | What the beneficiary received of the output asset                                                                                                            |
| `refundSwapped` | `uint64`  | Fixed-output: the surplus the refund sub-swap swapped back                                                                                                   |
| `refunded`      | `uint64`  | The input asset returned to the beneficiary: the refund and input the sub-swaps didn't spend. For an ALGO input, all ALGO returned, including unused funding |
| `algoReturned`  | `uint64`  | For an ASA input, the ALGO returned to the beneficiary: unused funding and the fees of AlgoFi sub-swaps that were skipped                                    |
| `treasuryFee`   | `uint64`  | The protocol treasury's fee, in the output asset                                                                                                             |
| `referrerFee`   | `uint64`  | The referrer's fee, in the output asset                                                                                                                      |
| `sender`        | `address` | The input transfer's sender                                                                                                                                  |
| `beneficiary`   | `address` | The beneficiary                                                                                                                                              |
| `referrer`      | `address` | The referrer escrow (or the protocol treasury escrow)                                                                                                        |

## Transaction Group

The group returned by [`fetchExecuteSwapTxns`](/haystack-dev/haystack-router/api-order-router.md) for a V4 quote is laid out as follows:

1. (optional) The swapper's opt-in to the output asset, if the quote was requested with `optIn=true` and the output asset is not ALGO.
2. (optional) Treasury escrow opt-ins, if a fee escrow is not yet opted into the output asset. Each is a 0.1 ALGO payment from the swapper to the escrow, then the swapper's call to the Referrer Treasury App's `opt_escrow_into_assets`.
3. (optional) Carriers: `refs` calls, for routes whose references don't fit on the `route` call.
4. (optional) When the app doesn't hold an ASA input yet, its opt-in, which must come before the input transfer: a payment of 0.1 ALGO per asset from the swapper to the app account, then an `opt_in` call for the input and the route's other missing assets.
5. (optional) For an ASA input, a payment from the swapper to the app account covering the route's costs: the AlgoFi pool calls' fees, and 0.1 ALGO for each asset the route opts the app into. For an ALGO input, this is added to the input amount instead.
6. The swapper's transfer of the input to the app account.
7. The `route` call.

The app calls can be sent by any account. The API sends them from a single-use account and returns them pre-signed, so the swapper only signs their own transactions.

Only the input transfer carries a fee: the group's whole budget, by fee pooling. That budget covers every transaction's minimum fee, the route's inner transactions and op-ups, and the surcharge on `route` calls whose arguments exceed 2,048 bytes (0.1 microALGO per byte past 2,048, reached at about 40 sub-swaps). The exceptions are the output opt-in and the escrow opt-in calls, which pay their own fees.

Every transaction of the group carries an [ARC-2](https://arc.algorand.foundation/ARCs/arc-0002) note, `hayrouter/v1:j{"tag":"<client tag>","n":<nonce>}`, and the route passes it as the note of its inner transactions. Carriers add `"carrier": <index>`. The swapper's payments add `"pays"`:

* `"route-costs"` for the payment in step 5;
* `"opt-in"` for the `opt_in` payment;
* `"escrow-opt-in"` for an escrow's opt-in payment.

To read a swap's result, decode the `route` call's `Swap` event. The [SDK](/haystack-dev/haystack-router/sdk.md) does this for `getSummary()` from version 3.2.0.
