# Starting a Swap

## Details

Request a Deposit Address to make a swap between two assets towards a given destination address.

Your broker fee will automatically be taken into account.

A Deposit Address will be provided where the user can either manually send funds to, or you can implement a wallet signing solution to do this automatically. Once received the swap will happen and the funds will be sent to the destination address.

The deposit and refund rules for each source chain, with a quote request per route and asset pair, are on the [Chainflip Swap Routes](https://docs.chainflip-broker.io/routes/) pages.

## API Endpoint

[`/swap`](https://chainflip-broker.io/docs/ui/index.html#tag/Swap/operation/startSwap) - Start a swap.

## Parameters

To start a swap, you are required to provide the following parameters:

* `sourceAsset` - The asset to swap from, for example `btc.btc`
* `destinationAsset` - The asset to swap to, for example `eth.arb`
* `destinationAddress` - The address on the destination chain to swap to, for example `0x2578f4fa0f36138c76389095bf74331a4f57bcc0`

There are also additional optional parameters:

### Boost

For Bitcoin swaps, a fee can be supplied to turn it into a Boost swap, speeding up the time of a swap. This allows the user to swap Bitcoin faster than the estimated half hour (3 Bitcoin confirmations, which take 10 minutes per confirmation). Thanks to this a Bitcoin swap can happen in minutes instead of half an hour.

We advise to set the `boostFee` to `30` to make sure a swap is boosted. The user will only pay the lowest possible fee.

* `boostFee`- The maximum accepted boost fee in basis points (100th of a percent) for a Boost swap. Must be between `0` and `100`. We advise `30` to make sure a swap gets boosted; the user then always pays the lowest fee that was enough to boost it. The [Boost quote](https://docs.chainflip-broker.io/features/ask-quote/#boost) also carries `maxBoostFeeBps`, the value Chainflip itself opens that boosted swap with.

[Boost](https://docs.chainflip-broker.io/reference/glossary/#boost) is defined in the glossary.

### Slippage Protection

In order to prevent high slippage you **are required** to pass in a minimum required price. If the swap does not meet this price, the source assets will be returned to the `refundAddress`.

* `minimumPrice` - The minimum accepted price in human-readable form, for example `2768.95` for ETH.
* `refundAddress` - Address on the source chain to which the refund will be sent, if the minimum price cannot be met.
* `retryDurationInBlocks` - Optional. Number of blocks after which a deposit is refunded, if the minimum price cannot be met. One block corresponds to 6 seconds. Omitted or negative, it is `150` (15 minutes). A value above Chainflip's current runtime limit (600 blocks = one hour at the time of writing) is lowered to that limit and the swap proceeds. Every quote carries Chainflip's recommendation as `recommendedRetryDurationInBlocks`.

The glossary defines [minimum price](https://docs.chainflip-broker.io/reference/glossary/#minimum-price), [retry duration](https://docs.chainflip-broker.io/reference/glossary/#retry-duration) and [refund address](https://docs.chainflip-broker.io/reference/glossary/#refund-address).

#### Live Price Protection

On top of `minimumPrice`, which is fixed when the channel opens, you can limit how far the execution price may fall below Chainflip's live oracle price at the moment each chunk is swapped:

* `livePriceSlippageTolerancePercent` - Optional. The accepted shortfall against the oracle price in percent, between `0` and `100` with at most 2 decimals (for example `0.5`). A swap that would execute below it is retried and, once `retryDurationInBlocks` has passed, refunded. When set, a stale oracle price also counts as a violation.

Use the quote's `recommendedLivePriceSlippageTolerancePercent` when it has one; a quote without it means Chainflip has no oracle-based protection to recommend for the pair. When either asset has no oracle price on Chainflip (FLIP, for example), the parameter is omitted and the swap proceeds without it, under Chainflip's default protection. Leaving the parameter out keeps Chainflip's default live price protection for the pair, if it has one. The [transaction payloads](https://docs.chainflip-broker.io/features/tx-payload/) and the MCP `start_swap` and `start_dca_swap` tools take the same parameter. The [swap status](https://docs.chainflip-broker.io/features/get-status/) shows the applied value as `fillOrKillParams.maximumOraclePriceSlippage`, in basis points (`0.5` percent is `50`).

#### Example Slippage Calculation

Have a look at the following examples to determine the `minimumPrice` parameter:

##### BTC -> ETH Swap

* You want to set a slippage limit of `2%`
* In the quote response there is `"estimatedPrice": 28.22379438638571497457`
* Use the following formula: `minimumPrice = estimatedPrice * (1 - slippageLimit / 100)`
* This gives: `28.22379438638571497457 * 98 / 100 = 27.6593184987`
* Pass `27.6593184987` as `minimumPrice` parameter to apply a `2%` slippage limit

##### USDT -> BTC Swap

* You want to set a slippage of `1%`
* In the quote response there is `"estimatedPrice": 0.00001056302864588782`
* Use the following formula: `minimumPrice = estimatedPrice * (1 - slippageLimit / 100)`
* This gives: `0.00001056302864588782 * 99 / 100 = 0.00001045739`
* Pass `0.00001045739` as `minimumPrice` parameter to apply a `1%` slippage limit

##### SOL -> USDC Swap

* You want to set a slippage of `5%`
* In the quote response there is `"estimatedPrice": 184.59038231365019505646`
* Use the following formula: `minimumPrice = estimatedPrice * (1 - slippageLimit / 100)`
* This gives: `184.59038231365019505646 * 95 / 100 = 175.360863198`
* Pass `175.360863198` as `minimumPrice` parameter to apply a `5%` slippage limit

### DCA

To perform a swap spread out over time, you can pass in DCA parameters. These will split the swap amount in a specific `numberOfChunks` and treat every chunk as a separate swap every `chunkIntervalBlocks`, where a block is 6 seconds.

If DCA parameters are combined with [Slippage Protection](https://docs.chainflip-broker.io/features/start-swap/#slippage-protection) parameters, the price will be checked at every chunk. Once slippage protection kicks in, the remaining unswapped chunks will be refunded to the user.

A DCA swap can also be a [Boost](https://docs.chainflip-broker.io/features/start-swap/#boost) swap, allowing the user to more quickly get their Bitcoin swapping.

* `numberOfChunks` - The number of "sub-swaps" to perform for a DCA swap. A value below `1` is treated as `1`.
* `chunkIntervalBlocks` - The delay between the "sub-swaps" of a DCA swap in number of blocks. Optional when `numberOfChunks` is set; it defaults to `2` (12 seconds), the recommended value. One block is 6 seconds, so an interval of 5 would account for a sub-swap to happen every 30 seconds. A negative value, or `0` with more than one chunk, becomes `2`. Passing `chunkIntervalBlocks` without `numberOfChunks` is a plain input validation `400`.

The total duration `(numberOfChunks - 1) * chunkIntervalBlocks` must fit Chainflip's current runtime limit (14400 blocks, 24 hours, at the time of writing). A longer schedule is shortened so the swap proceeds: the interval first, down to `2` blocks, then the number of chunks. Only when the limit cannot be read, or Chainflip's node rejects the schedule for another reason, does the request answer `400` with code `invalid_dca_parameters`, and no channel is opened.

[DCA](https://docs.chainflip-broker.io/reference/glossary/#dca) is defined in the glossary.

### Custom Commission BPS

You can also provide the `commissionBps` parameter to get override your configured commission. Note this can never be lower than your default according to the [Commission Protection](https://docs.chainflip-broker.io/use-cases/#commission-protection) feature.

* `commissionBps` - An optional override to the charged commission bps. Must be between 0 and 995.

How your commission and the operating fee make up the [broker fee](https://docs.chainflip-broker.io/reference/glossary/#broker-fee) is explained in the glossary.

### Extra affiliates

You can provide up to four extra affiliates to share a commission with.

The glossary explains how Chainflip [affiliates](https://docs.chainflip-broker.io/reference/glossary/#affiliate) share the broker fee.

* `affiliate1` - The ss58 affiliate broker address for the first affiliate.
* `affiliate1CommissionBps` - The commission to assign to the first affiliate.
* `affiliate2` - The ss58 affiliate broker address for the second affiliate.
* `affiliate2CommissionBps` - The commission to assign to the second affiliate.
* `affiliate3` - The ss58 affiliate broker address for the third affiliate.
* `affiliate3CommissionBps` - The commission to assign to the third affiliate.
* `affiliate4` - The ss58 affiliate broker address for the fourth affiliate.
* `affiliate4CommissionBps` - The commission to assign to the fourth affiliate.

Commissions get added up to your total commission charged to the user.

## Response

The response provides the `address` to send the `sourceAsset` funds to, plus the identifiers you need to track the swap:

* `address` - The deposit address. Show it to the user, or use it in a wallet integration.
* `destinationAddress` - The destination address the swap was accepted for, echoed back exactly as you supplied it: no case, prefix or format changes, so a `.hub` SS58 address comes back as SS58 and a public-key hex comes back as that hex (the swap record stores the public-key form). Use it to check, in the same call, which destination the API accepted. It is the API's record of your request, not a confirmation from the broker: the broker does not report the destination back when it opens the channel.
* `issuedBlock`, `network`, `channelId` - Together these identify the deposit channel, which you can pass to [status-by-deposit-channel](https://docs.chainflip-broker.io/features/get-status/).
* `sourceExpiryBlock` - The block on the source network at which the deposit channel expires.
* `explorerUrl` - Link to the channel on the Chainflip explorer, useful to show the user the swap is real.
* `channelOpeningFee` (and `channelOpeningFeeNative`) - The channel opening fee in FLIP. Usually effectively zero, but worth reading if you display total cost.

Once the user sends funds, follow the swap with [Get Swap Status](https://docs.chainflip-broker.io/features/get-status/).

## Error Responses

When a deposit address cannot be issued, the response is an [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807) problem details object. Failures that originate at the broker (for example Chainflip's channel cap is hit, or an asset is disabled) carry a stable, machine-readable `code` next to the human-readable `detail`. The HTTP status follows the code: `503` for temporary conditions such as the channel cap, maintenance or a disabled asset, `500` only for unclassified failures.

Parameter values Chainflip's node rejects and that cannot be adjusted are coded `400`: `invalid_refund_parameters` (a retry duration above the runtime limit is lowered instead), `invalid_dca_parameters` (a schedule above the runtime limit is shortened instead) and, rarely, `live_price_protection_unavailable` (normally live price protection on an oracle-less pair is omitted instead). The detail names the node's reason, and no channel is opened. Plain input validation failures (`400`, with an `errors` object) and route denial (`403`) do not carry a code on this endpoint; on a `400`, check for `code` before assuming an `errors` object.

A `503` with `chainflip_safe_mode` is a local refusal: Chainflip's safe mode has paused swapping or deposits for the source chain, so no channel is opened. Do not send funds until governance lifts the pause; the detail names the blocking flags.

A `POST /swap` with a cross-chain message (CCM) payload to a destination network that does not support cross-chain messaging, such as Bitcoin, is rejected with `400` (`Cross-chain messaging is not supported on Bitcoin.`) and no channel is opened.

See [Error Codes](https://docs.chainflip-broker.io/features/error-codes/) for the full list, what each one means, and how to handle unknown or missing codes.

```json
{
    "type": "https://tools.ietf.org/html/rfc9110#section-15.6.4",
    "title": "Service Unavailable",
    "status": 503,
    "detail": "Too many swaps are ongoing right now, please try again later",
    "traceId": "00-6e04726aca44787669d57a48b1833007-ddd09a1fe1f24426-00",
    "code": "too_many_channels"
}
```

## Example

> **Tip**
>
> Want to test first? Change the API base URL to `https://perseverance.chainflip-broker.io`. The [Testing](https://docs.chainflip-broker.io/environments/testing/) environment swaps testnet assets with no real value.
>
> Swap the API key in the examples for your own [production API key](https://chainflip-broker.io/register). Testing requires a separate [testnet API key](https://perseverance.chainflip-broker.io/register).

The following example is based on the quote received in [Asking for a Quote](https://docs.chainflip-broker.io/features/ask-quote/#example). 

We will be applying a `2.5%` slippage limit using `94162.97655452752291823391` as `estimatedPrice`.

After using our [slippage protection calculations](https://docs.chainflip-broker.io/features/start-swap/#slippage-protection) we get the following `minimumPrice`: \
`94162.97655452752291823391 * 97.5 / 100 = 91808.9021407`

We will also be retrying for `15 minutes` in case our slippage limit is hit. We calculate `15 minutes` is `900 seconds`, divided by `6 seconds per block`, giving us a `retryDurationInBlocks` of `150`.

```bash
curl --location 'https://chainflip-broker.io/swap?apiKey=87517a91d5f34dbabfc1e410946a3a3c&sourceAsset=btc.btc&destinationAsset=usdt.eth&destinationAddress=DESTINATION_EVM_ADDRESS&refundAddress=SOURCE_BTC_ADDRESS&minimumPrice=91808.9021407&retryDurationInBlocks=150'
```

*Example response captured on the testing environment; response shape is identical on production. These values are illustrative, not output from the production request above.*

```json
{
    "id": 268,
    "address": "tb1pwkx9h364f3kvy3nx7gz2wpw8tgdyujhnmc82836km76za5f0dvpsacn3ce",
    "issuedBlock": 4136443,
    "network": "Bitcoin",
    "channelId": 1006,
    "sourceExpiryBlock": 3581992,
    "explorerUrl": "https://scan.perseverance.chainflip.io/channels/4136443-Bitcoin-1006",
    "channelOpeningFee": 0.00000000000001,
    "channelOpeningFeeNative": "10000",
    "destinationAddress": "DESTINATION_EVM_ADDRESS"
}
```
