> For the complete documentation index, see [llms.txt](https://docs.aqua.network/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.aqua.network/developers/code-examples/executing-swaps-through-optimal-path.md).

# Executing swaps through optimal path

Swap through the best route across Aquarius pools with the official SDK — quote an exact-input or exact-output swap, check its guard, and execute it.

Swapping through the best route gives the best result Aquarius can offer: the route can pass through up to 4 pools for an exact-input swap and up to 3 for an exact-output swap. `quote()` requests the route from the Find Path API, and `execute()` submits it through the AMM router with a slippage guard derived from the quote.

{% hint style="info" %}
This page uses the [official SDKs](https://docs.aqua.network/developers/integrating-with-aquarius.md#official-sdks) (0.6.0 or later). For other languages, the route request is documented in the [Backend API reference](https://docs.aqua.network/developers/reference/backend-api.md) and the router call with its authorization in [Contract authorization](https://docs.aqua.network/developers/reference/contract-authorization.md).
{% endhint %}

{% hint style="warning" %}
The signer's account needs a trustline for the asset it receives — otherwise the swap fails until the trustline exists. `ensure_trustline` below creates it on the signer's account when it is missing. See the [Stellar documentation on trustlines](https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/accounts#trustlines).
{% endhint %}

See the [complete code examples](#complete-code-examples) at the bottom of this page.

### Executing swap: step by step guide

To perform a swap, follow these steps.

#### 1. Set up the client

This example swaps XLM to AQUA on mainnet. Everything below works identically on [testnet](https://docs.aqua.network/developers/testing-on-testnet.md) with `network="testnet"` and the testnet AQUA issuer.

{% tabs %}
{% tab title="Python" %}

```python
from stellar_sdk import Keypair
from aquarius import AquariusClient, Asset, SlippageError, XLM

AQUA = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA")

aqua = AquariusClient(network="mainnet", signer=Keypair.from_secret("S..."))
aqua.ensure_trustline(AQUA)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import { Keypair } from "@stellar/stellar-sdk";
import { AquariusClient, Asset, SlippageError, XLM } from "@aquariusdefi/sdk";

const AQUA = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA");

const aqua = new AquariusClient({ network: "mainnet", signer: Keypair.fromSecret("S...") });
await aqua.ensureTrustline(AQUA);
```

{% endtab %}
{% endtabs %}

#### 2. Quote an exact-input swap

Pass `amount_in` to fix the amount you send, like a strict-send payment. The quote needs no signer and submits nothing:

{% tabs %}
{% tab title="Python" %}

```python
quote = aqua.quote(XLM, AQUA, amount_in=1_0000000, slippage=0.01)   # 1 XLM in stroops

print(f"estimated out: {quote.amount_out}")    # base units of AQUA
print(f"guaranteed minimum: {quote.guard}")    # estimate reduced by slippage
print(f"pools: {quote.route}")                 # pool contract addresses along the route
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const quote = await aqua.quote({ from: XLM, to: AQUA, amountIn: 1_0000000n, slippage: 0.01 });   // 1 XLM in stroops

console.log(`estimated out: ${quote.amountOut}`);   // base units of AQUA
console.log(`guaranteed minimum: ${quote.guard}`);  // estimate reduced by slippage
console.log(`pools: ${quote.route}`);               // pool contract addresses along the route
```

{% endtab %}
{% endtabs %}

#### 3. Execute the quote

`execute()` submits the quoted route with the guard as the on-chain minimum and returns the amounts from the confirmed transaction. If the pools move past the guard before the transaction is included, it fails with a `SlippageError`; `requote()` returns a fresh quote for the same parameters, to show before executing again:

{% tabs %}
{% tab title="Python" %}

```python
try:
    receipt = quote.execute()
except SlippageError as error:
    quote = error.requote()
    print(f"price moved; new estimate: {quote.amount_out}")
    receipt = quote.execute()

print(f"swapped: {receipt.amount_in} -> {receipt.amount_out}")
print(f"transaction: {receipt.tx_hash}")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
let receipt;
try {
  receipt = await quote.execute();
} catch (error) {
  if (!(error instanceof SlippageError)) throw error;
  const fresh = await error.requote();
  console.log(`price moved; new estimate: ${fresh.amountOut}`);
  receipt = await fresh.execute();
}

console.log(`swapped: ${receipt.amountIn} -> ${receipt.amountOut}`);
console.log(`transaction: ${receipt.txHash}`);
```

{% endtab %}
{% endtabs %}

`execute()` waits until the RPC confirms the transaction. If confirmation does not arrive in time, it raises `TxTimeoutError`, which carries the transaction hash in `tx_hash` (`txHash` in JavaScript). Check that hash before deciding whether another swap is needed.

For bots, `swap()` combines quote and execute, and re-quotes up to `retries` times after a `SlippageError`:

{% tabs %}
{% tab title="Python" %}

```python
receipt = aqua.swap(XLM, AQUA, amount_in=1_0000000, slippage=0.01, retries=3)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const botReceipt = await aqua.swap({ from: XLM, to: AQUA, amountIn: 1_0000000n, slippage: 0.01, retries: 3 });
```

{% endtab %}
{% endtabs %}

#### 4. Quote an exact-output swap

Pass `amount_out` instead to fix the amount you receive, like a strict-receive payment. The guard is then the maximum input the swap may spend; the router refunds whatever the route does not use:

{% tabs %}
{% tab title="Python" %}

```python
quote = aqua.quote(XLM, AQUA, amount_out=1_0000000, slippage=0.01)   # 1 AQUA in stroops

print(f"estimated in: {quote.amount_in}")      # base units of XLM
print(f"maximum in: {quote.guard}")            # estimate raised by slippage

receipt = quote.execute()
print(f"swapped: {receipt.amount_in} -> {receipt.amount_out}")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const exactOut = await aqua.quote({ from: XLM, to: AQUA, amountOut: 1_0000000n, slippage: 0.01 });   // 1 AQUA in stroops

console.log(`estimated in: ${exactOut.amountIn}`);   // base units of XLM
console.log(`maximum in: ${exactOut.guard}`);        // estimate raised by slippage

const exactOutReceipt = await exactOut.execute();
console.log(`swapped: ${exactOutReceipt.amountIn} -> ${exactOutReceipt.amountOut}`);
```

{% endtab %}
{% endtabs %}

### Sign in an external wallet

`build_transaction()` (`buildTransaction()` in JavaScript) returns the simulated, unsigned transaction envelope XDR of a quote, with the same authorization and guard as `execute()`. Hand it to a wallet, a hardware signer, or a multisig flow, and submit the signed envelope yourself.

### How the route is found

`quote()` sends the token contract addresses and the amount to the Find Path API: `/find-path/` for an exact-input swap, `/find-path-strict-receive/` for an exact-output swap. The response carries the route as `swap_chain_xdr`, which the SDK passes unchanged to the router's `swap_chained` or `swap_chained_strict_receive`, with the guard as `out_min` or `max_in`. When no route exists, `quote()` raises `NoRouteError`.

The request and response fields are in the [Backend API reference](https://docs.aqua.network/developers/reference/backend-api.md), the router functions in [Router & pool contracts](https://docs.aqua.network/developers/reference/router-and-pool-contracts.md), and the authorization each swap needs in [Contract authorization](https://docs.aqua.network/developers/reference/contract-authorization.md). To swap against one pool you choose, without the Find Path API, see [Executing swaps through specific pool](https://docs.aqua.network/developers/code-examples/executing-swaps-through-specific-pool.md).

### Complete code examples

This code performs a swap using Aquarius AMM on the Stellar mainnet. Depending on the `is_send` parameter: if `is_send` is `True`, it swaps 1 XLM for AQUA; if `is_send` is `False`, it swaps XLM for 1 AQUA.

To execute the code, provide the secret key of a Stellar account with at least 3 XLM. The script creates the AQUA trustline when the account has none. Save the JavaScript version as a `.mjs` file: it uses top-level `await`.

<details>

<summary>Copy the full code Python</summary>

```python
from stellar_sdk import Keypair
from aquarius import AquariusClient, AquariusError, Asset, SlippageError, XLM

# =========================================
# Configuration & Setup
# =========================================

# This account must have at least 3 XLM.
user_secret_key = "S..."

# Input and output tokens
token_in = XLM
token_out = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA")

# If True, the swap behaves like strict-send: the amount of the sending asset is fixed.
# If False, the swap behaves like strict-receive: the amount of the receiving asset is fixed.
is_send = True

# Amount of 1 XLM or 1 AQUA in stroops (depending on is_send)
amount = 1_0000000

# Slippage tolerance: 1%
slippage = 0.01

aqua = AquariusClient(network="mainnet", signer=Keypair.from_secret(user_secret_key))

# =========================================
# Entry Point
# =========================================

print(f"Swapping {token_in.code} for {token_out.code}...")
try:
    # The output asset needs a trustline; this creates it when it is missing.
    aqua.ensure_trustline(token_out)

    # 1. Find the swap path and estimated amounts
    if is_send:
        quote = aqua.quote(token_in, token_out, amount_in=amount, slippage=slippage)
        print(f"Estimated output: {quote.amount_out / 1e7} {token_out.code}, minimum: {quote.guard / 1e7}")
    else:
        quote = aqua.quote(token_in, token_out, amount_out=amount, slippage=slippage)
        print(f"Estimated input: {quote.amount_in / 1e7} {token_in.code}, maximum: {quote.guard / 1e7}")
    print(f"Route: {quote.route}")

    # 2. Execute the swap; re-quote once if the price moved past the guard
    try:
        receipt = quote.execute()
    except SlippageError as error:
        quote = error.requote()
        print("Price moved; executing a fresh quote")
        receipt = quote.execute()
except AquariusError as error:
    if error.tx_hash:
        print(f"Failed or unconfirmed transaction: {error.tx_hash}")
    raise

print(f"Transaction: {receipt.tx_hash}")
print(f"Swapped: {receipt.amount_in / 1e7} {token_in.code} => {receipt.amount_out / 1e7} {token_out.code}")
```

</details>

<details>

<summary>Copy the full code JavaScript</summary>

```javascript
import { Keypair } from "@stellar/stellar-sdk";
import { AquariusClient, AquariusError, Asset, SlippageError, XLM } from "@aquariusdefi/sdk";

// =========================================
// Configuration & Setup
// =========================================

// This account must have at least 3 XLM.
const userSecretKey = "S...";

// Input and output tokens
const tokenIn = XLM;
const tokenOut = Asset.classic("AQUA", "GBNZILSTVQZ4R7IKQDGHYGY2QXL5QOFJYQMXPKWRRM5PAV7Y4M67AQUA");

// If true, the swap behaves like strict-send: the amount of the sending asset is fixed.
// If false, the swap behaves like strict-receive: the amount of the receiving asset is fixed.
const isSend = true;

// Amount of 1 XLM or 1 AQUA in stroops (depending on isSend)
const amount = 1_0000000n;

// Slippage tolerance: 1%
const slippage = 0.01;

const aqua = new AquariusClient({ network: "mainnet", signer: Keypair.fromSecret(userSecretKey) });

// =========================================
// Entry Point
// =========================================

console.log(`Swapping ${tokenIn.code} for ${tokenOut.code}...`);
let receipt;
try {
  // The output asset needs a trustline; this creates it when it is missing.
  await aqua.ensureTrustline(tokenOut);

  // 1. Find the swap path and estimated amounts
  let quote;
  if (isSend) {
    quote = await aqua.quote({ from: tokenIn, to: tokenOut, amountIn: amount, slippage });
    console.log(`Estimated output: ${Number(quote.amountOut) / 1e7} ${tokenOut.code}, minimum: ${Number(quote.guard) / 1e7}`);
  } else {
    quote = await aqua.quote({ from: tokenIn, to: tokenOut, amountOut: amount, slippage });
    console.log(`Estimated input: ${Number(quote.amountIn) / 1e7} ${tokenIn.code}, maximum: ${Number(quote.guard) / 1e7}`);
  }
  console.log(`Route: ${quote.route}`);

  // 2. Execute the swap; re-quote once if the price moved past the guard
  try {
    receipt = await quote.execute();
  } catch (error) {
    if (!(error instanceof SlippageError)) throw error;
    quote = await error.requote();
    console.log("Price moved; executing a fresh quote");
    receipt = await quote.execute();
  }
} catch (error) {
  if (error instanceof AquariusError && error.txHash) {
    console.log(`Failed or unconfirmed transaction: ${error.txHash}`);
  }
  throw error;
}

console.log(`Transaction: ${receipt.txHash}`);
console.log(`Swapped: ${Number(receipt.amountIn) / 1e7} ${tokenIn.code} => ${Number(receipt.amountOut) / 1e7} ${tokenOut.code}`);
```

</details>

### Swap example transactions

* Swap through 1 pool: <https://stellar.expert/explorer/public/tx/c52f43d518f8cebe8ec849fd5d50c394faa036f96399d723f1f2d286e36c7b94>
* Swap through 2 pools: <https://stellar.expert/explorer/public/tx/d80b317ec117d77433e268e3b544eefdaa702a3fe92169e1f793f613863de1f2>
