# Rust library

> dex-aggregator-rs, the DEX Aggregator client for Rust: live quotes that it checks before they're signed, swaps with near-kit or near-api, and a connection that reconnects by itself, natively or in WebAssembly.

This page is part of the DEX Aggregator docs. The aggregator is at `https://router.intear.tech`, with live quotes at `wss://router.intear.tech/route/subscribe`, on NEAR mainnet only. https://docs.intear.tech/dex-aggregator/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.

[`dex-aggregator-rs`](https://github.com/INTEARnear/dex-aggregator-rs) is a client of the DEX Aggregator for Rust, for accounts that hold their key, like bots and wallets. It does what [Swapping](https://docs.intear.tech/dex-aggregator/guides/executing-routes.md#swapping) describes, with the fees paid from the outcome, and checks the router's transactions before anything is signed: a quote whose transactions do anything else than the swap you asked for is rejected.

:::caution
The crate isn't fully audited yet.
:::

It's on GitHub, not on crates.io:

```toml title="Cargo.toml"
dex-aggregator-rs = { git = "https://github.com/INTEARnear/dex-aggregator-rs", features = ["near-kit"] }
```

The whole file, tested in CI: https://docs.intear.tech/snippets/rust/Cargo.toml

The examples below also use [near-kit](https://docs.rs/near-kit) 0.34, [tokio](https://docs.rs/tokio) and [anyhow](https://docs.rs/anyhow).

## Swapping

```rust
use dex_aggregator_rs::{
    RouterAmount, RouterConnection, RouterConnectionOptions, Slippage, SwapAmount, SwapOutcome,
    SwapRequest,
};
use near_kit::SigningNear;

let request = SwapRequest::new(
    "near".parse()?,
    "usdt.tether-token.near".parse()?,
    SwapAmount::ExactIn(10u128.pow(24)), // 1 NEAR
    Slippage::Fixed(0.01),               // 1%
    trader.account_id().clone(),
);
// The router estimates the price, so the least to take for 1 NEAR comes from a price you trust
let least_amount_out = 1_000_000; // 1 USDt

let (connection, driver) = RouterConnection::new(RouterConnectionOptions::default());
tokio::spawn(driver);
let mut quotes = connection.subscribe(request)?;
let best = loop {
    match quotes.next().await {
        Some(Ok(update)) => {
            // `update.rejected` has the quotes whose transactions aren't safe to sign, and why
            let best = update.quotes.into_iter().next().filter(|best| {
                matches!(best.quote().worst_case_amount, RouterAmount::AmountOut(amount) if amount >= least_amount_out)
            });
            if let Some(best) = best {
                break best;
            }
        }
        // The route request is sent again after it
        Some(Err(error)) => eprintln!("The router failed: {error}"),
        None => anyhow::bail!("The connection to the router closed"),
    }
};
drop(quotes); // stops the route request

let swap = best.execute(trader).await?;
let next_steps = swap.next_steps(&connection).await?;
let outcome = next_steps.outcome().clone();
// Moves the tokens where the trader asked for them, and pays the fees once the swap went through
next_steps.execute(trader).await?;
```

The whole file, tested in CI: https://docs.intear.tech/snippets/rust/src/library.rs

The `trader` is near-kit's `SigningNear`, like `Near::mainnet().build().with_signer(near_kit::signer::from_env()?)` with `NEAR_ACCOUNT_ID` and `NEAR_PRIVATE_KEY` set.

1. `RouterConnection::new` gives the connection, and the future that keeps it, to spawn. On the web, spawn it with `wasm_bindgen_futures::spawn_local`.
2. `subscribe` sends the route request, with `fees_in_next_steps`. `next` gives each update of it: `quotes`, the `CheckedQuote`s that passed the [checks](#whats-checked), best first, and `rejected`, the others, each with the router's JSON and the `error`. Dropping the `QuoteSubscription` stops the route request, and a new `subscribe` replaces it.
3. The checks can't tell a bad price: the quote's estimate and worst case come from the router. Compare them with a price you trust before swapping.
4. `CheckedQuote::execute` sends the quote's transactions one after another, and gives an `ExecutedSwap`, whose `tx_hashes` tell what the swap did when the router doesn't.
5. `ExecutedSwap::next_steps` asks the router for the [outcome](https://docs.intear.tech/dex-aggregator/reference/outcome.md#response), and checks its next steps. Show `amount_in` and `amount_out` if `charge_fee` is `true`, or `error` otherwise.
6. `NextSteps::execute` sends them: they move the tokens where the trader asked for them, and, once the swap went through, pay the fees and the [quote improvement fee](https://docs.intear.tech/dex-aggregator/guides/referral-fees.md#quote-improvement-fee).

`SwapRequest::new` takes the tokens, the amount, the slippage and the trader. Its other fields, `fees`, `quote_improvement_receiver`, `referrer_id`, `signing_public_key` and `dexes`, are the [route parameters](https://docs.intear.tech/dex-aggregator/reference/route.md#optional) of the same names. A token is a [token ID](https://docs.intear.tech/dex-aggregator/guides/tokens.md#token-id-format), or just the contract of a NEP-141.

### Errors

| Error | When |
| --- | --- |
| `ExecutionError::WrongSigner` | The sender's account isn't the request's `trader_account_id`. Nothing is sent |
| `ExecutionError::Interrupted` | The sender failed on a transaction, after the ones in `tx_hashes` executed |
| `NextStepsError::Outcome(OutcomeError::TimedOut)` | The router didn't tell the outcome in `outcome_timeout` on one connection, with its last error |
| `NextStepsError::Outcome(OutcomeError::Malformed)` | The outcome isn't shaped like the router's outcomes |
| `NextStepsError::Outcome(OutcomeError::Closed)` | The connection was closed |
| `NextStepsError::Unsafe` | The next steps didn't pass the checks |

## Senders

A `TransactionSender` signs a transaction, sends it, and returns its hash once it executed, also when a receipt of it failed: the outcome tells what the transactions did, and its next steps return what a failed swap left behind. It has to wait for the execution, since the router's transactions after the first rely on what the ones before them did. Each library has its own feature:

| Feature | Sender |
| --- | --- |
| `near-kit` | near-kit's `SigningNear` itself, whatever its wait level |
| `near-api` | `adapters::near_api::NearApiSender { account_id, signer, network }`, for [near-api](https://docs.rs/near-api) |

Both wait until a transaction executed optimistically. To sign another way, implement `TransactionSender`: its `account_id`, and `send_transaction`, which gets the transaction's `receiver_id` and function calls, with their arguments as JSON.

## What's checked

`CheckedQuote::new`, on every quote of a subscription, and `ExecutedSwap::next_steps` only accept the calls the router makes, with exactly the arguments it passes, typed and by name, and Intear DEX's operations as the engine reads them, with its own [types](https://github.com/INTEARnear/dex/tree/main/intear-dex-types). They check that:

- the quote has no fee transactions, and its transactions spend at most the exact input, or the quote's worst case of an exact-out swap, with the `fee_amount` that its next steps pay, and wrap at most that much NEAR
- the fees add up to no more than the request's `fees`
- the swaps give at least the quote's worst case of exact input, which is within the requested slippage of its estimate, or the requested output of exact output
- they only call the swap's tokens, wNEAR, Rhea, Rhea DCL and Intear DEX, and only send the trader's tokens to those DEXs and to the requested fee receivers
- Intear DEX's operations only swap an amount of the input for the output, also through other tokens, withdraw to the trader, run none of the engine's other operations, pay oracles no more than `MAX_ORACLE_FEES` (1 NEAR, 1 USDt, 1 USDC or 1000 TEAR), and take the requested referral fees and quote improvement fee
- storage deposits attach no more than the quote's `storage_deposits`, and no more than `MAX_STORAGE_DEPOSITS` (1 NEAR) in all, next steps included, and leave no more than `MAX_STORAGE_DEPOSIT_FOR_OTHERS` (0.05 NEAR) on Rhea to each account other than the trader
- next steps don't swap, only pay fees after a swap that went through, no more than the quote's `fee_amount`, and pay the quote improvement fee that leaves the trader with exactly the quote's estimate
- there are at most 20 transactions, as many as the router finds the outcome of

A check that fails gives an `UnsafeTransactionsError`, with every problem in `problems`.

## When the router goes offline

The connection reconnects whenever it's lost, waiting twice as long after each failed attempt, and once it's back, sends the route request again, and every outcome request that wasn't answered: the router answers them from the quotes it stored, also after it restarted. Right after a restart, it can answer with no routes until it has loaded the pools. `status()` is a `tokio::sync::watch::Receiver` of `Connecting`, `Open`, `Reconnecting` with the error, and `Closed`.

A route request or an outcome request that the router answers with an error is sent again after the same delays, and the subscription gives the route request's errors as a `RouterError`. An outcome is asked for until the router hasn't told it for `outcome_timeout` on one connection. While the router is offline, outcomes wait for it, and each connection gives it that long again, so put a timeout of your own around `next_steps` to give up on a swap.

| Field of `RouterConnectionOptions` | Default | |
| --- | --- | --- |
| `url` | `wss://router.intear.tech/route/subscribe` | |
| `min_retry_delay`, `max_retry_delay` | 250 ms, 10 s | Waits twice as long after each failed attempt to connect, or each error of the router |
| `connect_timeout` | 10 s | Gives up on an attempt to connect, and tries again |
| `outcome_timeout` | 180 s | Gives up on an outcome the router hasn't told on one connection |
| `ping_interval` | 10 s | Not on the web. Pings the router once it's been quiet this long, and connects again when it doesn't answer in as long |

`connection.outcome(quote_id, &tx_hashes, OutcomeWaitUntil::Swap)` asks for an [answer at the swap](https://docs.intear.tech/dex-aggregator/reference/outcome.md#answering-at-the-swap). The connection closes once `close` is called or every clone of it is dropped, which fails the outcomes it waits for.
