# Swaps

> Swapping on Qoq: the Borsh swap message with its routes, swaps on pools with a fixed price, the oracle request that pools an oracle prices need, quoting them, and how prices are computed.

This page is part of the Qoq docs. Qoq is the DEX `slimedragon.near/amp` on the Intear DEX contract, `dex.intear.near`, and every call goes to that contract. https://docs.intear.tech/qoq/llms-full.txt has all of its pages in one file, and https://docs.intear.tech/llms.txt lists every page of the Intear docs.

A Qoq swap is an Intear DEX [swap](https://docs.intear.tech/intear-dex/guides/swaps.md) with `"dex_id": "slimedragon.near/amp"`. The `message` of the swap says which pools to go through. On pools with a fixed price, everything else works as on any DEX of the engine: [`swap_simple`](https://docs.intear.tech/intear-dex/guides/swaps.md#swap_simple), [`simulate_swap_simple`](https://docs.intear.tech/intear-dex/guides/swaps.md#simulate), and `SwapSimple` [operations](https://docs.intear.tech/intear-dex/guides/operations.md), with exact input or exact output. Pools that an oracle prices need an [oracle request](#pools-an-oracle-prices) first.

The examples on this page swap from alice.near's inner balance, after a [storage deposit](https://docs.intear.tech/intear-dex/guides/storage.md#accounts), [registering](https://docs.intear.tech/intear-dex/guides/inner-balances.md#register-assets) USDt and USDC, and [depositing](https://docs.intear.tech/intear-dex/guides/inner-balances.md#deposit) 10 USDt. Together they're [one script](#the-whole-script).

```sh
near contract call-function as-transaction dex.intear.near storage_deposit \
  json-args '{}' \
  prepaid-gas '30.0 Tgas' attached-deposit '0.01 NEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send

near contract call-function as-transaction dex.intear.near register_assets \
  json-args '{
    "asset_ids": [
      "nep141:usdt.tether-token.near",
      "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1"
    ]
  }' \
  prepaid-gas '30.0 Tgas' attached-deposit '1 yoctoNEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send

near contract call-function as-transaction usdt.tether-token.near ft_transfer_call \
  json-args '{"receiver_id": "dex.intear.near", "amount": "10000000", "msg": ""}' \
  prepaid-gas '50.0 Tgas' attached-deposit '1 yoctoNEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send
```

The whole file, tested in CI: https://docs.intear.tech/snippets/cli/qoq-swaps.sh

## The message

The message is a Borsh `SwapArgs`, a list of routes:

```rust
struct SwapArgs {
    routes: Vec<SwapRoute>,
}

struct SwapRoute {
    /// Share of the amount that goes through this route, 1000000 = 100%
    fraction: u32,
    /// Pools to swap through, in order
    pool_ids: Vec<u32>,
}
```

Each pool of a route swaps the output of the one before into its other asset, and the last one must output `asset_out`. With several routes, each takes its `fraction` of the amount, and the fractions must add up to 1000000. The first route also takes what's left after rounding. Unlike [Plach](https://docs.intear.tech/plach/guides/swaps.md#the-message), there's no shorter form for one pool. This message swaps the whole amount through pool 1:

```
01 00 00 00    1 route
40 42 0f 00      fraction: 1000000 (100%)
01 00 00 00      1 pool
01 00 00 00        1
```

That's `AQAAAEBCDwABAAAAAQAAAA==` in base64. [Fee discounts](https://docs.intear.tech/intear-dex/guides/swaps.md#fee-discounts) and [referral fees](https://docs.intear.tech/intear-dex/guides/referral-fees.md) are arguments of the engine's swap, not part of the message. Messages from before fee discounts moved to the engine can have one after the routes, which Qoq reads past.

## Pools with a fixed price

A pool with a fixed price swaps like any DEX. This one asks how much USDC 1 USDt gets in pool 1, and accepts 1% less:

```sh
# 1 USDt to USDC through pool 1
USDC_OUT=$(near contract call-function as-read-only dex.intear.near simulate_swap_simple \
  json-args '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwABAAAAAQAAAA==",
    "trader": "alice.near",
    "asset_in": "nep141:usdt.tether-token.near",
    "asset_out": "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
    "amount": {"ExactIn": "1000000"}
  }' \
  network-config mainnet now | jq -r '.[1]')
MIN_USDC_OUT=$((USDC_OUT * 99 / 100))
```

The whole file, tested in CI: https://docs.intear.tech/snippets/cli/qoq-swaps.sh

```sh
near contract call-function as-transaction dex.intear.near swap_simple \
  json-args "$(jq -n --arg min_usdc_out "$MIN_USDC_OUT" '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwABAAAAAQAAAA==",
    "asset_in": "nep141:usdt.tether-token.near",
    "asset_out": "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
    "amount": {"ExactIn": "1000000"},
    "constraint": $min_usdc_out
  }')" \
  prepaid-gas '100.0 Tgas' attached-deposit '1 yoctoNEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send
```

The whole file, tested in CI: https://docs.intear.tech/snippets/cli/qoq-swaps.sh

## Pools an oracle prices

A swap through a pool that an oracle prices must start with an [`OracleRequest`](https://docs.intear.tech/intear-dex/guides/oracles.md#asking-an-oracle) for the prices of its assets. Without one, it fails with `Swaps on these pools must start with an oracle request of the prices of near, nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1 from ed25519:7EK1MhudQrXZBZjvnvvcNXiQ2ByYBkXg8rUhbKL69CGo`, which also says what to ask for. So these swaps run in [`execute_operations`](https://docs.intear.tech/intear-dex/guides/operations.md#execute_operations) or in the operations of a deposit, not in `swap_simple`:

```json
{
  "operations": [
    {
      "OracleRequest": {
        "oracle_key": "ed25519:7EK1MhudQrXZBZjvnvvcNXiQ2ByYBkXg8rUhbKL69CGo",
        "dex_id": "slimedragon.near/amp",
        "request": "AgAAAAABQAAAADE3MjA4NjI4Zjg0ZjVkNmFkMzNmMGRhM2JiYmViMjdmZmNiMzk4ZWFjNTAxYTMxYmQ2YWQyMDExZTM2MTMzYTE=",
        "fee": ["near", "400000000000000000000"],
        "swap": null
      }
    },
    {
      "SwapSimple": {
        "dex_id": "slimedragon.near/amp",
        "message": "AQAAAEBCDwABAAAAAAAAAA==",
        "asset_in": "near",
        "asset_out": "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
        "amount": { "Amount": { "ExactIn": "1000000000000000000000000" } },
        "constraint": "2800000"
      }
    }
  ]
}
```

- `oracle_key` is the oracle of the pool, in its [`PoolView`](https://docs.intear.tech/qoq/reference/types.md#poolview). All pools of a swap that an oracle prices must have the same one, or the swap fails with `Pools of a swap must ask the same oracle`.
- `request` is the Borsh of `PricesRequest { asset_ids: Vec<AssetId> }`: the assets of every pool of the message that an oracle prices, in the order the routes go through them, the first asset of each pool before its second, each asset once. Pools with a fixed price are left out. For pool 0, that's NEAR and USDC.
- `fee` is what the oracle takes, exactly as the engine's `oracle_fees` returns it. Pool 0's oracle takes 0.0004 NEAR, 0.001 USDC or 0.001 USDt.

The operations after the request run once the oracle responds. [Oracles](https://docs.intear.tech/intear-dex/guides/oracles.md) has how the request is paid and what happens if the operations don't run. The [DEX Aggregator](https://docs.intear.tech/dex-aggregator.md) builds these operations for you.

### The response

The oracle responds with the Borsh of a `PricesResponse`: the prices of the requested assets on several exchanges.

```rust
struct PricesResponse {
    exchanges: Vec<ExchangePrices>,
}

struct ExchangePrices {
    exchange: String,
    /// The price of a whole token of each requested asset, in their order,
    /// in the exchange's quote currency, with 18 decimals
    prices: Vec<u128>,
}
```

For each pool, Qoq divides each exchange's price of its first asset by its price of the second, and swaps at the median of those prices. A response must have prices from at least 3 exchanges with different names, one for each requested asset, none of them zero, and the highest at most 0.5% above the lowest. Otherwise, the swap fails with one of the [oracle response errors](https://docs.intear.tech/qoq/reference/errors.md#oracle-responses). Qoq doesn't check how old the prices are: a response only counts if the oracle sends it while the operations wait, within 200 blocks.

### Quoting

`simulate_swap_simple` can't ask an oracle, so it takes the response in `oracle_response`, with the oracle's key and the request. This quotes 1 NEAR to USDC in pool 0, at a price of NEAR of about 2.9 USDC on three exchanges:

```sh
# Pool 0's request for the prices of NEAR and USDC, and a response with their
# prices on 3 exchanges, as its oracle would respond
REQUEST=AgAAAAABQAAAADE3MjA4NjI4Zjg0ZjVkNmFkMzNmMGRhM2JiYmViMjdmZmNiMzk4ZWFjNTAxYTMxYmQ2YWQyMDExZTM2MTMzYTE=
RESPONSE=AwAAAAcAAABiaW5hbmNlAgAAAAAAopii3j4oAAAAAAAAAAAAAGSns7bgDQAAAAAAAAAAAwAAAG9reAIAAAAAgGg9IWxCKAAAAAAAAAAAAABkp7O24A0AAAAAAAAAAAUAAABieWJpdAIAAAAAgNvzI1E7KAAAAAAAAAAAAABkp7O24A0AAAAAAAAAAA==

# 1 NEAR to USDC through pool 0
near contract call-function as-read-only dex.intear.near simulate_swap_simple \
  json-args "$(jq -n --arg request "$REQUEST" --arg response "$RESPONSE" '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwABAAAAAAAAAA==",
    "trader": "alice.near",
    "asset_in": "near",
    "asset_out": "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
    "amount": {"ExactIn": "1000000000000000000000000"},
    "oracle_response": {
      "oracle_key": "ed25519:7EK1MhudQrXZBZjvnvvcNXiQ2ByYBkXg8rUhbKL69CGo",
      "request": $request,
      "response": $response
    }
  }')" \
  network-config mainnet now
```

The whole file, tested in CI: https://docs.intear.tech/snippets/cli/qoq-swaps.sh

It returns `[amount_in, amount_out]`, about 2.9 USDC for the 1 NEAR. A route through pool 0 and then pool 1 to USDt asks the oracle the same, since pool 1 has a fixed price:

```sh
# 1 NEAR to USDt through pool 0, then pool 1. Pool 1 has a fixed price, so the
# request is the same.
near contract call-function as-read-only dex.intear.near simulate_swap_simple \
  json-args "$(jq -n --arg request "$REQUEST" --arg response "$RESPONSE" '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwACAAAAAAAAAAEAAAA=",
    "trader": "alice.near",
    "asset_in": "near",
    "asset_out": "nep141:usdt.tether-token.near",
    "amount": {"ExactIn": "1000000000000000000000000"},
    "oracle_response": {
      "oracle_key": "ed25519:7EK1MhudQrXZBZjvnvvcNXiQ2ByYBkXg8rUhbKL69CGo",
      "request": $request,
      "response": $response
    }
  }')" \
  network-config mainnet now
```

The whole file, tested in CI: https://docs.intear.tech/snippets/cli/qoq-swaps.sh

A quote is only as good as the prices you pass. The DEX Aggregator quotes Qoq with the latest prices of its oracle.

## How prices are computed

A pool values both of its balances in whole tokens of its second asset: the first at its price, `amount * price / 10^decimals`, and the second one for one. Then it swaps on Curve's StableSwap curve with the pool's **amplification**, `A`. While the two values are equal, the pool trades at its price. As a pool gets out of balance, its price moves away from the oracle's: slowly with a high `A`, like the 1000 of pool 1, and faster with a low one, like the 400 of pool 0. So a swap that brings a pool back into balance gets a bit more than the price, and one that moves it further gets a bit less.

The fee comes out of the input. Of it, 80% goes to the pool's [liquidity providers](https://docs.intear.tech/qoq/guides/liquidity.md#fees) and 20% to Qoq's protocol fee, each rounded down, and a [fee discount](https://docs.intear.tech/intear-dex/guides/swaps.md#fee-discounts) lowers both. With an exact input, the rest of the input is swapped and the output is rounded down, a tiny bit lower for the rounding of the curve, as in Curve. With an exact output, the input is rounded up, and so are the fees on top of it.

Each pool a swap goes through logs a [`Swap`](https://docs.intear.tech/qoq/reference/events.md#swap) event with its amounts, its fees and the price it swapped at, and a [`PoolUpdated`](https://docs.intear.tech/qoq/reference/events.md#poolupdated) event with its new balances. A pool that an oracle prices keeps the price of its last swap in `last_price`, but only to show it: every swap asks the oracle again.

## The whole script

```sh
#!/usr/bin/env bash
# Reads a Qoq pool, swaps USDt for USDC in the pool with a fixed price, and
# quotes swaps of NEAR in the pool that an oracle prices. alice.near holds USDt
# in the wallet and has never used Intear DEX.
set -euo pipefail

near contract call-function as-read-only dex.intear.near dex_view \
  json-args '{"dex_id": "slimedragon.near/amp", "method": "get_pool_count", "args": ""}' \
  network-config mainnet now

near contract call-function as-read-only dex.intear.near dex_view \
  json-args '{"dex_id": "slimedragon.near/amp", "method": "get_pool", "args": "AQAAAA=="}' \
  network-config mainnet now

near contract call-function as-transaction dex.intear.near storage_deposit \
  json-args '{}' \
  prepaid-gas '30.0 Tgas' attached-deposit '0.01 NEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send

near contract call-function as-transaction dex.intear.near register_assets \
  json-args '{
    "asset_ids": [
      "nep141:usdt.tether-token.near",
      "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1"
    ]
  }' \
  prepaid-gas '30.0 Tgas' attached-deposit '1 yoctoNEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send

near contract call-function as-transaction usdt.tether-token.near ft_transfer_call \
  json-args '{"receiver_id": "dex.intear.near", "amount": "10000000", "msg": ""}' \
  prepaid-gas '50.0 Tgas' attached-deposit '1 yoctoNEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send

# 1 USDt to USDC through pool 1
USDC_OUT=$(near contract call-function as-read-only dex.intear.near simulate_swap_simple \
  json-args '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwABAAAAAQAAAA==",
    "trader": "alice.near",
    "asset_in": "nep141:usdt.tether-token.near",
    "asset_out": "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
    "amount": {"ExactIn": "1000000"}
  }' \
  network-config mainnet now | jq -r '.[1]')
MIN_USDC_OUT=$((USDC_OUT * 99 / 100))

near contract call-function as-transaction dex.intear.near swap_simple \
  json-args "$(jq -n --arg min_usdc_out "$MIN_USDC_OUT" '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwABAAAAAQAAAA==",
    "asset_in": "nep141:usdt.tether-token.near",
    "asset_out": "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
    "amount": {"ExactIn": "1000000"},
    "constraint": $min_usdc_out
  }')" \
  prepaid-gas '100.0 Tgas' attached-deposit '1 yoctoNEAR' \
  sign-as alice.near network-config mainnet sign-with-keychain send

# Pool 0's request for the prices of NEAR and USDC, and a response with their
# prices on 3 exchanges, as its oracle would respond
REQUEST=AgAAAAABQAAAADE3MjA4NjI4Zjg0ZjVkNmFkMzNmMGRhM2JiYmViMjdmZmNiMzk4ZWFjNTAxYTMxYmQ2YWQyMDExZTM2MTMzYTE=
RESPONSE=AwAAAAcAAABiaW5hbmNlAgAAAAAAopii3j4oAAAAAAAAAAAAAGSns7bgDQAAAAAAAAAAAwAAAG9reAIAAAAAgGg9IWxCKAAAAAAAAAAAAABkp7O24A0AAAAAAAAAAAUAAABieWJpdAIAAAAAgNvzI1E7KAAAAAAAAAAAAABkp7O24A0AAAAAAAAAAA==

# 1 NEAR to USDC through pool 0
near contract call-function as-read-only dex.intear.near simulate_swap_simple \
  json-args "$(jq -n --arg request "$REQUEST" --arg response "$RESPONSE" '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwABAAAAAAAAAA==",
    "trader": "alice.near",
    "asset_in": "near",
    "asset_out": "nep141:17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1",
    "amount": {"ExactIn": "1000000000000000000000000"},
    "oracle_response": {
      "oracle_key": "ed25519:7EK1MhudQrXZBZjvnvvcNXiQ2ByYBkXg8rUhbKL69CGo",
      "request": $request,
      "response": $response
    }
  }')" \
  network-config mainnet now

# 1 NEAR to USDt through pool 0, then pool 1. Pool 1 has a fixed price, so the
# request is the same.
near contract call-function as-read-only dex.intear.near simulate_swap_simple \
  json-args "$(jq -n --arg request "$REQUEST" --arg response "$RESPONSE" '{
    "dex_id": "slimedragon.near/amp",
    "message": "AQAAAEBCDwACAAAAAAAAAAEAAAA=",
    "trader": "alice.near",
    "asset_in": "near",
    "asset_out": "nep141:usdt.tether-token.near",
    "amount": {"ExactIn": "1000000000000000000000000"},
    "oracle_response": {
      "oracle_key": "ed25519:7EK1MhudQrXZBZjvnvvcNXiQ2ByYBkXg8rUhbKL69CGo",
      "request": $request,
      "response": $response
    }
  }')" \
  network-config mainnet now
```
