Rust library
This page is also Markdown, for agents: /dex-aggregator/guides/rust-library.md, and /llms.txt lists every page.
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 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.
It’s on GitHub, not on crates.io:
dex-aggregator-rs = { git = "https://github.com/INTEARnear/dex-aggregator-rs", features = ["near-kit"] }The examples below also use near-kit 0.34, tokio and anyhow.
Swapping
Section titled “Swapping”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 trustlet 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 throughnext_steps.execute(trader).await?;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.
RouterConnection::newgives the connection, and the future that keeps it, to spawn. On the web, spawn it withwasm_bindgen_futures::spawn_local.subscribesends the route request, withfees_in_next_steps.nextgives each update of it:quotes, theCheckedQuotes that passed the checks, best first, andrejected, the others, each with the router’s JSON and theerror. Dropping theQuoteSubscriptionstops the route request, and a newsubscribereplaces it.- 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.
CheckedQuote::executesends the quote’s transactions one after another, and gives anExecutedSwap, whosetx_hashestell what the swap did when the router doesn’t.ExecutedSwap::next_stepsasks the router for the outcome, and checks its next steps. Showamount_inandamount_outifcharge_feeistrue, orerrorotherwise.NextSteps::executesends 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.
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 of the same names. A token is a token ID, or just the contract of a NEP-141.
Errors
Section titled “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
Section titled “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 |
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
Section titled “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. 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_amountthat 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 thanMAX_STORAGE_DEPOSITS(1 NEAR) in all, next steps included, and leave no more thanMAX_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
Section titled “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. The connection closes once close is called or every clone of it is dropped, which fails the outcomes it waits for.