# Quote Endpoint

The quote endpoint finds the optimal swap route between two tokens and returns detailed execution information including ready-to-use transaction data.

## Endpoint

```
GET /api/v1/quote
```

## Request Parameters

### Required Parameters

| Parameter | Type   | Description                                   |
| --------- | ------ | --------------------------------------------- |
| `from`    | string | Input token identifier (e.g., `WEGLD-bd4d79`) |
| `to`      | string | Output token identifier (e.g., `USDC-c76f1f`) |

### Amount Parameters

Provide exactly one of the following:

| Parameter   | Type   | Description                                                          |
| ----------- | ------ | -------------------------------------------------------------------- |
| `amountIn`  | string | Amount to swap in smallest units. Returns maximum achievable output. |
| `amountOut` | string | Desired output amount in smallest units. Returns required input.     |

Providing both or neither returns an error. See [Error Reference](https://github.com/XOXNO/docs/blob/main/developers/aggregator-api/error-reference.md).

### Optional Parameters

| Parameter         | Type    | Default  | Description                                                                                                               |
| ----------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| `slippage`        | number  | `0.01`   | Slippage tolerance as a decimal (0.01 = 1%)                                                                               |
| `maxSplits`       | number  | `5`      | Maximum number of route splits                                                                                            |
| `maxHops`         | number  | `10`     | Maximum swaps per individual route path                                                                                   |
| `includePaths`    | boolean | `true`   | Include detailed path breakdown in response                                                                               |
| `referralId`      | number  | `0`      | Referral ID for fee sharing                                                                                               |
| `algorithm`       | string  | `hybrid` | Split allocation algorithm: `greedy`, `lagrangian`, or `hybrid`                                                           |
| `maxBuiltinCalls` | number  | —        | Cap on smart contract calls per transaction (gas optimization)                                                            |
| `includeLpRoutes` | boolean | `false`  | Allow LP tokens as intermediate hops (auto-enabled when `from` or `to` is an LP token)                                    |
| `sender`          | string  | —        | Sender address (bech32). When provided, returns a complete `transaction` object ready for signing instead of raw `txData` |

### Algorithm Parameter

| Value        | Behavior                                                                                                                                                         |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `greedy`     | Incrementally allocates trade chunks to the highest-rate path. Fast (\~99% optimal). Applies early termination when marginal rates decline.                      |
| `lagrangian` | Uses binary search on the Lagrange multiplier to equalize marginal rates across all active paths. Mathematically optimal for convex AMMs. Best for large trades. |
| `hybrid`     | Runs both algorithms and returns whichever produces greater output. Recommended for all use cases.                                                               |

### LP Routing (`includeLpRoutes`)

When `from` or `to` is an LP token, the router automatically handles mint and burn operations — no flag required.

Set `includeLpRoutes=true` only to allow LP tokens as **intermediate hops** in routes between two non-LP tokens, when doing so might improve output.

{% hint style="info" %}
`includeLpRoutes=true` increases the number of candidate paths and may slightly increase response latency.
{% endhint %}

### Transaction Building (`sender`)

Pass the caller's bech32 address to receive a complete, ready-to-sign `transaction` object instead of raw `txData`.

When `sender` is present the API:

1. Fetches the sender's current nonce from the gateway.
2. Simulates the transaction to measure exact gas cost (adds a buffer).
3. Constructs the correct envelope — native EGLD value transfer for `EGLD` input, `ESDTTransfer` data prefix for all other tokens.
4. Returns the `transaction` field and omits `txData` and `instructions`.

```json
{
  "transaction": {
    "sender": "erd1qyu5...",
    "receiver": "erd1qqqqqqqqqqqqqpgq5rf2...",
    "value": "0",
    "nonce": 42,
    "data": "ESDTTransfer@...",
    "gasLimit": 15000000,
    "gasPrice": 1000000000,
    "chainID": "1",
    "version": 1
  }
}
```

{% hint style="warning" %}
If fetching the nonce or simulating gas takes longer than 5 seconds, the API falls back to returning `txData` without a `transaction` object. Handle both shapes in your client.
{% endhint %}

### Arbitrage Parameters <a href="#arbitrage-mode" id="arbitrage-mode"></a>

When `from` equals `to`, the API switches to arbitrage detection mode and finds profitable cycles in the DEX graph:

| Parameter      | Type    | Default | Description                                              |
| -------------- | ------- | ------- | -------------------------------------------------------- |
| `minProfitBps` | number  | `10`    | Minimum profit threshold in basis points (10 bps = 0.1%) |
| `maxCycles`    | number  | `5`     | Maximum number of arbitrage cycles to return             |
| `fastMode`     | boolean | `false` | Use faster but less exhaustive cycle search              |

{% hint style="warning" %}
Arbitrage mode is compute-intensive. Use `fastMode=true` and set a meaningful `minProfitBps` to avoid unnecessary load.
{% endhint %}

## Response Format

### Successful Response

```json
{
  "from": "WEGLD-bd4d79",
  "to": "USDC-c76f1f",
  "amountIn": "1000000000000000000",
  "amountOut": "42500000",
  "amountInShort": 1.0,
  "amountOutShort": 42.5,
  "amountOutMin": "42075000",
  "amountOutMinShort": 42.075,
  "slippage": 0.01,
  "priceImpact": 0.0012,
  "rate": 42.5,
  "rateInverse": 0.0235,
  "paths": [...],
  "instructions": [...],
  "txData": "c3dhcEV4YWN0QW1...",
  "estimatedBuiltinCalls": 3,
  "feeBps": 30,
  "feeAmount": "127500",
  "feeAmountShort": 0.1275
}
```

### Response Fields

| Field               | Type   | Description                                                                                                                               |
| ------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `from`              | string | Input token identifier                                                                                                                    |
| `to`                | string | Output token identifier                                                                                                                   |
| `amountIn`          | string | Input amount in smallest units                                                                                                            |
| `amountOut`         | string | Output amount in smallest units                                                                                                           |
| `amountInShort`     | number | Human-readable input amount (divided by token decimals)                                                                                   |
| `amountOutShort`    | number | Human-readable output amount                                                                                                              |
| `amountOutMin`      | string | Minimum output after slippage, in smallest units (forward quotes)                                                                         |
| `amountOutMinShort` | number | Human-readable minimum output (forward quotes)                                                                                            |
| `amountInMax`       | string | Maximum input after slippage, in smallest units (reverse quotes only)                                                                     |
| `amountInMaxShort`  | number | Human-readable maximum input (reverse quotes only)                                                                                        |
| `amountInUsd`       | number | USD value of input amount (omitted if price unavailable)                                                                                  |
| `amountOutUsd`      | number | USD value of output amount (omitted if price unavailable)                                                                                 |
| `amountOutMinUsd`   | number | USD value of minimum output after slippage (omitted if price unavailable)                                                                 |
| `slippage`          | number | Applied slippage tolerance                                                                                                                |
| `priceImpact`       | number | Estimated price impact as a decimal (0.01 = 1%)                                                                                           |
| `rate`              | number | Exchange rate: output units per input unit                                                                                                |
| `rateInverse`       | number | Inverse rate: input units per output unit                                                                                                 |
| `paths`             | array  | Detailed route breakdown; present when `includePaths=true`                                                                                |
| `txData`            | string | Hex-encoded transaction data; omitted when `transaction` is present                                                                       |
| `feeBps`            | number | Protocol fee in basis points                                                                                                              |
| `feeAmount`         | string | Fee amount in smallest units                                                                                                              |
| `feeAmountShort`    | number | Human-readable fee amount                                                                                                                 |
| `feeToken`          | string | Token identifier the fee is charged on                                                                                                    |
| `transaction`       | object | Complete transaction ready for signing; present only when `sender` is provided (see [Transaction Building](#transaction-building-sender)) |
| `arbitrage`         | object | Arbitrage metadata; present only for same-token (`from == to`) forward quotes                                                             |

## Path Object

When `includePaths=true`, each element in the `paths` array describes one route leg:

```json
{
  "amountIn": "500000000000000000",
  "amountOut": "21250000",
  "amountInShort": 0.5,
  "amountOutShort": 21.25,
  "splitPpm": 500000,
  "swaps": [
    {
      "dex": "xExchange",
      "pairId": 42,
      "address": "erd1qqq...",
      "from": "WEGLD-bd4d79",
      "to": "USDC-c76f1f",
      "amountIn": "500000000000000000",
      "amountOut": "21250000",
      "amountInShort": 0.5,
      "amountOutShort": 21.25
    }
  ]
}
```

| Field             | Type   | Description                                                                             |
| ----------------- | ------ | --------------------------------------------------------------------------------------- |
| `splitPpm`        | number | Fraction of total input allocated to this path, in parts per million (1,000,000 = 100%) |
| `swaps`           | array  | Ordered list of individual pool swaps within this path                                  |
| `swaps[].dex`     | string | DEX name: `xExchange`, `AshSwap`, `JEX`, or `OneDex`                                    |
| `swaps[].address` | string | Pool smart contract address (bech32)                                                    |

## Using Transaction Data <a href="#using-transaction-data" id="using-transaction-data"></a>

{% hint style="info" %}
Pass `sender` to receive a fully-built `transaction` object. The API fetches the sender's nonce, simulates gas, and constructs the correct EGLD or ESDT envelope automatically — no manual assembly needed.
{% endhint %}

### What `txData` contains

When `sender` is omitted, `txData` contains **only the aggregator endpoint call** — the function name and its arguments:

```
xo@<token_out_hex>@<min_amount_hex>@...
```

It does **not** include any token transfer prefix. You must wrap it inside the correct MultiversX transaction envelope depending on your input token:

| Input token    | Transaction shape                                                                                                       |
| -------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `EGLD`         | Send native value to the aggregator contract; use `txData` as the `data` field directly                                 |
| ESDT (single)  | `ESDTTransfer@<token_hex>@<amount_hex>@<txData>` — receiver is the aggregator contract                                  |
| Multiple ESDTs | `MultiESDTNFTTransfer@<aggregator_hex>@<count>@<token1>@<nonce1>@<amount1>@...@<txData>` — receiver is your own address |

Refer to the [MultiversX docs on ESDT transfers with SC execution](https://docs.multiversx.com/developers/esdt-tokens/#transfers-to-a-smart-contract) for the full encoding rules before assembling the transaction data field manually.

{% hint style="warning" %}
A common mistake is using `txData` as the full `data` field for an ESDT swap. Without the `ESDTTransfer` prefix the contract never receives the tokens and the transaction will fail.
{% endhint %}

{% hint style="warning" %}
`txData` encodes the minimum output amount derived from the `slippage` parameter. A different slippage value produces different `txData`. Do not reuse `txData` across quote requests.
{% endhint %}

## Examples

### Forward Quote

```bash
curl "https://swap.xoxno.com/api/v1/quote?\
from=WEGLD-bd4d79&\
to=USDC-c76f1f&\
amountIn=1000000000000000000&\
slippage=0.005"
```

### Reverse Quote

```bash
curl "https://swap.xoxno.com/api/v1/quote?\
from=WEGLD-bd4d79&\
to=USDC-c76f1f&\
amountOut=100000000&\
slippage=0.01"
```

### Large Trade with Split Optimization

```bash
curl "https://swap.xoxno.com/api/v1/quote?\
from=WEGLD-bd4d79&\
to=USDC-c76f1f&\
amountIn=100000000000000000000&\
maxSplits=8&\
algorithm=lagrangian"
```

### Arbitrage Detection

```bash
curl "https://swap.xoxno.com/api/v1/quote?\
from=WEGLD-bd4d79&\
to=WEGLD-bd4d79&\
amountIn=10000000000000000000&\
minProfitBps=50"
```

### Quote with Ready-to-Sign Transaction

```bash
curl "https://swap.xoxno.com/api/v1/quote?\
from=WEGLD-bd4d79&\
to=USDC-c76f1f&\
amountIn=1000000000000000000&\
sender=erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"
```

### Minimal Response (High-Frequency Polling)

```bash
curl "https://swap.xoxno.com/api/v1/quote?\
from=WEGLD-bd4d79&\
to=USDC-c76f1f&\
amountIn=1000000000000000000&\
includePaths=false"
```

## Error Responses

| Error                                                   | Cause                                           |
| ------------------------------------------------------- | ----------------------------------------------- |
| `"unknown token_in 'X'"`                                | Input token identifier not recognized           |
| `"unknown token_out 'X'"`                               | Output token identifier not recognized          |
| `"routing failed: no path between tokens"`              | No liquidity path connects the requested tokens |
| `"invalid amount_in: expected unsigned integer amount"` | Amount is non-numeric, negative, or fractional  |
| `"specify either amount_in or amount_out, not both"`    | Both `amountIn` and `amountOut` provided        |
| `"amount_in or amount_out must be provided"`            | Neither `amountIn` nor `amountOut` provided     |

See [Error Reference](https://github.com/XOXNO/docs/blob/main/developers/aggregator-api/error-reference.md) for HTTP status codes, full error bodies, and resolution steps.

## Token Identifiers

MultiversX token identifiers use the format `TICKER-hexcode`:

| Token        | Identifier     |
| ------------ | -------------- |
| Wrapped EGLD | `WEGLD-bd4d79` |
| USDC         | `USDC-c76f1f`  |
| USDT         | `USDT-f8c08c`  |
| UTK          | `UTK-2f80e9`   |
| MEX          | `MEX-455c57`   |

{% hint style="info" %}
Use the [pair-config endpoint](/developers/aggregator-api/pair-config.md) to verify that a token is supported before requesting a quote. It also returns the token's decimal precision, which is required to convert amounts correctly.
{% endhint %}

## Rate Limiting

* 100 requests per second per IP address
* Each request computes routes fresh against current pool state; responses are not cached
* For high-frequency applications, use `includePaths=false` to reduce response size and processing time

## Related Topics

* [Pair Configuration](/developers/aggregator-api/pair-config.md) — Verify token support before quoting
* [Integration Guide](/developers/aggregator-api/integration-guide.md) — Complete integration walkthrough
* [Error Reference](https://github.com/XOXNO/docs/blob/main/developers/aggregator-api/error-reference.md) — Full error code reference


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.xoxno.com/developers/aggregator-api/quote.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
