> 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/add-fees-to-swap/executing-swaps-with-provider-fees.md). Agents can also search and read this documentation through its [MCP server](https://docs.aqua.network/~gitbook/mcp).

# Executing swaps with provider fees

Execute swaps through your fee collector, charging your provider fee on each one.

Route a swap through your deployed fee collector and keep a fraction of the output. Pass a `ProviderFeeConfig` to any quote or swap: the SDK keeps the fee arithmetic exact (ceiling rounding, both amount modes), targets the collector with client-built authorization, and the collector pulls the tokens, takes your cut from the output, and drives the router itself.

{% 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). The [complete code examples](#complete-code-examples) run a full swap in one script, and the [contract-level flow](#contract-level-flow-any-language) below covers other languages. Deploy a collector first — see [Deploying a new fee collector](https://docs.aqua.network/developers/code-examples/add-fees-to-swap/deploying-a-new-fee-collector.md).
{% endhint %}

### Swap with your fee

The fee is `fee_fraction / fee_denominator` of the swap's output: with the denominator 10,000, `fee_fraction=10` is 0.1% and `fee_fraction=30` is 0.3%. The denominator must match the value your collector was deployed with, and `fee_fraction` must stay at or below its `max_swap_fee_fraction`:

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

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

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

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

fee = ProviderFeeConfig(
    contract_id="C...",     # your deployed collector
    fee_fraction=10,        # 10 / 10_000 -> 0.1% of the output
    fee_denominator=10_000,
)

receipt = aqua.swap(XLM, AQUA, amount_in=10_0000000, provider_fee=fee, retries=3)
print(f"user received: {receipt.amount_out}")   # net of your fee
```

{% endtab %}

{% tab title="JavaScript" %}

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

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

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

const fee = {
  contractId: "C...",     // your deployed collector
  feeFraction: 10,        // 10 / 10000 -> 0.1% of the output
  feeDenominator: 10_000,
};

const receipt = await aqua.swap({ from: XLM, to: AQUA, amountIn: 10_0000000n, providerFee: fee, retries: 3 });
console.log(`user received: ${receipt.amountOut}`);   // net of your fee
```

{% endtab %}
{% endtabs %}

Both amount modes work. With `amount_out` the SDK quotes the gross amount the route must produce so the user still receives exactly the requested output after your fee.

If you attached to the collector with `aqua.fee_collector(...)`, `fee_config()` builds the same configuration with the contract id filled in — see [Claiming & swapping accumulated fees](https://docs.aqua.network/developers/code-examples/add-fees-to-swap/claiming-and-swapping-accumulated-fees.md).

### Send the output to a third party

Set `recipient` to deliver the net output to another address — it does not sign anything. The recipient opens its own trustline for the output asset; `ensure_trustline` covers only the signer's account. If the recipient lacks the trustline, the error names the recipient, not your signer:

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

```python
fee_to_recipient = ProviderFeeConfig(
    contract_id="C...",
    fee_fraction=10,
    fee_denominator=10_000,
    recipient="G...",       # receives the net output; no signature required
)

receipt = aqua.swap(XLM, AQUA, amount_in=10_0000000, provider_fee=fee_to_recipient)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const feeToRecipient = {
  contractId: "C...",
  feeFraction: 10,
  feeDenominator: 10_000,
  recipient: "G...",       // receives the net output; no signature required
};

const recipientReceipt = await aqua.swap({ from: XLM, to: AQUA, amountIn: 10_0000000n, providerFee: feeToRecipient });
```

{% endtab %}
{% endtabs %}

With `amount_out`, the recipient receives exactly the requested output, and any unused input returns to your signer, not to the recipient.

{% hint style="warning" %}
Recipients need a collector deployed on or after 2 October 2026 UTC. Collectors are never upgraded and keep the methods they were deployed with, so an earlier collector can lack recipient support: the swap then fails in simulation with `Error(WasmVm, MissingValue)`. Swaps without `recipient` work on every collector. If your collector lacks recipient support, [deploy a new collector](https://docs.aqua.network/developers/code-examples/add-fees-to-swap/deploying-a-new-fee-collector.md).
{% endhint %}

Your cut accumulates on the collector contract in the output tokens of the swaps. Collect it with [Claiming & swapping accumulated fees](https://docs.aqua.network/developers/code-examples/add-fees-to-swap/claiming-and-swapping-accumulated-fees.md).

### Complete code examples

This code performs a swap through your fee collector on the Stellar mainnet and keeps a 0.3% provider fee from the output. 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 and the address of your collector. The collector must be deployed with the denominator 10,000 and a `max_swap_fee_fraction` of at least 30. The script creates the AQUA trustline when the account has none. Save the JavaScript version as a `.mjs` file: it uses top-level `await`.

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

```python
from stellar_sdk import Keypair
from aquarius import AquariusClient, AquariusError, Asset, ProviderFeeConfig, 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: 0.5%
slippage = 0.005

# Your deployed fee collector and your fee: 30 / 10,000 = 0.3% of the output.
# fee_denominator must match the value the collector was deployed with.
provider_fee = ProviderFeeConfig(
    contract_id="C...",
    fee_fraction=30,
    fee_denominator=10_000,
)

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

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

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

    # 1. Find the swap path; the estimate and the guard are net of your fee
    if is_send:
        quote = aqua.quote(token_in, token_out, amount_in=amount, slippage=slippage, provider_fee=provider_fee)
        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, provider_fee=provider_fee)
        print(f"Estimated input: {quote.amount_in / 1e7} {token_in.code}, maximum: {quote.guard / 1e7}")
    print(f"Route: {quote.route}")

    # 2. Execute the swap through the collector; 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}")
print(f"Your fee accrues on {provider_fee.contract_id} in {token_out.code}")
```

{% endtab %}

{% tab title="JavaScript" %}

```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: 0.5%
const slippage = 0.005;

// Your deployed fee collector and your fee: 30 / 10,000 = 0.3% of the output.
// feeDenominator must match the value the collector was deployed with.
const providerFee = {
  contractId: "C...",
  feeFraction: 30,
  feeDenominator: 10_000,
};

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

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

console.log(`Swapping ${tokenIn.code} for ${tokenOut.code} through the fee collector...`);
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; the estimate and the guard are net of your fee
  let quote;
  if (isSend) {
    quote = await aqua.quote({ from: tokenIn, to: tokenOut, amountIn: amount, slippage, providerFee });
    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, providerFee });
    console.log(`Estimated input: ${Number(quote.amountIn) / 1e7} ${tokenIn.code}, maximum: ${Number(quote.guard) / 1e7}`);
  }
  console.log(`Route: ${quote.route}`);

  // 2. Execute the swap through the collector; 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}`);
console.log(`Your fee accrues on ${providerFee.contractId} in ${tokenOut.code}`);
```

{% endtab %}
{% endtabs %}

### Contract-level flow (any language)

The SDK calls the collector's `swap_chained` or `swap_chained_strict_receive`, or their `_to` variants when `recipient` is set, with the route from the [Find Path API](https://docs.aqua.network/developers/reference/backend-api.md). The functions and their parameters are listed in [Provider fee contracts](https://docs.aqua.network/developers/reference/router-and-pool-contracts.md#provider-fee-contracts), and the authorization tree of each call in [Contract authorization](https://docs.aqua.network/developers/reference/contract-authorization.md#authorization-trees).
