# JavaScript library

> @intear/dex-aggregator, the DEX Aggregator client for JavaScript and TypeScript: live quotes that it checks before they're signed, swaps with a signer or a NEAR Connect wallet, and a connection that reconnects by itself.

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.

[`@intear/dex-aggregator`](https://www.npmjs.com/package/@intear/dex-aggregator) is a client of the DEX Aggregator for JavaScript and TypeScript. It does what [Executing a route](https://docs.intear.tech/dex-aggregator/guides/executing-routes.md) describes, and checks the router's transactions before anything is signed: a quote whose transactions do anything else than the swap you asked for is left out. [dex.intea.rs](https://dex.intea.rs) swaps with it.

:::caution
The library is a reference implementation that isn't fully reviewed yet. Its source is on [GitHub](https://github.com/INTEARnear/dex-aggregator-js).
:::

```sh
npm install @intear/dex-aggregator
```

It has no dependencies and comes with TypeScript types. It needs a `WebSocket`, so a browser, or Node.js 22 or later.

## Swapping with a signer

For accounts that sign without asking anyone, like bots and custodial wallets: quotes with `feesInNextSteps`, and their fees paid from the outcome, as in [Swapping](https://docs.intear.tech/dex-aggregator/guides/executing-routes.md#swapping). With the [near-api-js](https://github.com/near/near-api-js) `account` of alice.near, like `new Account('alice.near', 'https://free.rpc.fastnear.com', 'ed25519:<private key>')`:

```js
import { RouterConnection, swapWithSigner } from '@intear/dex-aggregator';
import { actions } from 'near-api-js';

const signer = {
  async signAndSendTransaction({ receiverId, actions: calls }) {
    const { transaction_outcome } = await account.signAndSendTransaction({
      receiverId,
      actions: calls.map((call) =>
        call.type === 'Transfer'
          ? actions.transfer(BigInt(call.params.deposit))
          : actions.functionCall(call.params.methodName, call.params.args, BigInt(call.params.gas), BigInt(call.params.deposit)),
      ),
      // The library needs the hash of a transaction that failed, too
      throwOnFailure: false,
    });
    return transaction_outcome.id;
  },
};

const request = {
  tokenIn: 'near',
  tokenOut: 'usdt.tether-token.near',
  amount: { exactIn: 10n ** 24n }, // 1 NEAR
  slippage: { type: 'fixed', slippage: 0.01 }, // 1%
  traderAccountId: 'alice.near',
};
// The router estimates the price, so the least to take for 1 NEAR comes from a price you trust
const leastAmountOut = 1_000_000n; // 1 USDt

const connection = new RouterConnection();
const result = new Promise((resolve, reject) => {
  const stop = connection.subscribe(request, {
    feesInNextSteps: true,
    onQuotes: ({ quotes }) => {
      const [best] = quotes;
      if (best === undefined || BigInt(best.worst_case_amount.amount_out ?? 0) < leastAmountOut) return;
      stop();
      swapWithSigner({ signer, connection, request, quote: best })
        .then(resolve, reject)
        .finally(() => connection.close());
    },
    onError: (error) => console.error('The router failed, asking again:', error.message),
  });
});
```

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

- `new RouterConnection()` connects to `/route/subscribe`. `subscribe(request, options)` sends a route request, and calls `onQuotes` with each update of it: `quotes`, the ones that passed the [checks](#whats-checked), best first, and `rejected`, the others, each with its `error`. It returns what stops the route request, and a new `subscribe` replaces 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.
- `swapWithSigner` checks the quote again, sends its transactions one after another, asks the connection for their outcome, checks its next steps, and sends them. It resolves with `{ outcome, nextStepsError }`: the [outcome](https://docs.intear.tech/dex-aggregator/reference/outcome.md#response), and what failed when sending the next steps, or `null`. Show `amount_in` and `amount_out` if `outcome.charge_fee` is `true`, or `outcome.error` otherwise.
- `onSwapSent` gets the hashes of the swap's transactions once they executed, which tell what the swap did when the router doesn't, and `onOutcome` gets the outcome before its next steps are signed.
- When the signer fails on a transaction, `swapWithSigner` throws a `SwapInterruptedError`, with the hashes of the ones that executed before it in `txHashes`.

A signer is an object with `signAndSendTransaction(transaction)`, which signs the transaction, sends it, and resolves with 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. The transaction is `{ receiverId, actions }`, as NEAR Connect takes it, with the arguments of a function call as a JSON object. near-api-js throws on a failed transaction unless it's given `throwOnFailure: false`.

### The request

| Field | Type | Route parameter |
| --- | --- | --- |
| `tokenIn`, `tokenOut` | string | `token_in`, `token_out`: a [token ID](https://docs.intear.tech/dex-aggregator/guides/tokens.md#token-id-format), or just the contract of a NEP-141 |
| `amount` | `{ exactIn: bigint }` or `{ exactOut: bigint }` | `amount_in` or `amount_out` |
| `slippage` | `{ type: 'fixed', slippage }` or `{ type: 'auto', minSlippage, maxSlippage }` | [Slippage](https://docs.intear.tech/dex-aggregator/guides/slippage.md) |
| `traderAccountId` | string | `trader_account_id`, needed to swap |
| `fees` | object, optional | `fees`, like `{ 'app.near': 0.005 }` for 0.5% |
| `quoteImprovementReceiver` | string, optional | [`quote_improvement_receiver`](https://docs.intear.tech/dex-aggregator/guides/referral-fees.md#quote-improvement-fee) |
| `referrerId`, `signingPublicKey` | string, optional | `referrer_id`, `signing_public_key` |
| `dexes` | array of strings, optional | `dexes` |

`routeQuery(request)` gives the query string of the request, for [`GET /route`](https://docs.intear.tech/dex-aggregator/reference/route.md).

## Swapping with NEAR Connect

For a web app whose wallet signs, with a quote of a subscription without `feesInNextSteps`, and a [NEAR Connect](https://github.com/hot-dao/near-selector) wallet:

```js
import { swapWithNearConnect } from '@intear/dex-aggregator';

return swapWithNearConnect({
  wallet,
  request,
  quote,
  onSwapSent: (txHashes) => console.log('Swapped in', txHashes),
});
```

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

`swapWithNearConnect` asks the wallet for the quote's transactions, its fee transactions included, in one approval, as in [Swapping from a web app](https://docs.intear.tech/dex-aggregator/guides/executing-routes.md#swapping-from-a-web-app): the wallet doesn't send the fee transactions of a swap that it sees failed. Once [`/route/outcome`](https://docs.intear.tech/dex-aggregator/reference/outcome.md) says what the transactions before the fee transactions did, it asks the wallet again for the outcome's next steps, if there are any. It resolves with `{ outcome, nextStepsError }` too, where `nextStepsError` is what that second request threw, like when the trader rejected it.

## What's checked

`validateQuote(request, quote)` runs on every quote of a subscription, and again before a swap, and `validateNextSteps(request, quote, outcome)` before the next steps are signed. They only accept the calls the router makes, with exactly the arguments it passes, and check that:

- the transactions spend at most the exact input, or the quote's worst case of an exact-out swap, fees included, also the ones 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 the input for the output, also through other tokens, withdraw to the trader, 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 throws an `UnsafeTransactionsError`, with every problem in `problems`, also when a quote or an outcome isn't shaped like the router's.

## Reconnecting

`RouterConnection` reconnects whenever its connection is lost, 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.

A route request or an outcome request that the router answers with an error is sent again after a delay, and `onError` of the subscription tells of the route request's errors. When the error's [`status`](https://docs.intear.tech/dex-aggregator/reference/subscribe.md#server-messages) says the request is wrong, a `4xx` other than `429`, the outcome fails at once, and the subscription ends. Otherwise, an outcome is asked for until `outcomeTimeoutMs`, then fails with the router's last error. `swapWithNearConnect` asks `/route/outcome` again the same way, with its own `retryDelayMs` and `outcomeTimeoutMs`.

| Option of `new RouterConnection()` | Default | |
| --- | --- | --- |
| `url` | `wss://router.intear.tech/route/subscribe` | |
| `WebSocket` | the global `WebSocket` | Or another, like the `ws` package's |
| `reconnectDelayMs` | `{ min: 250, max: 10000 }` | Waits twice as long after each failed attempt to connect, or to get an outcome |
| `connectTimeoutMs` | `10000` | Gives up on an attempt to connect, and tries again |
| `outcomeTimeoutMs` | `180000` | Gives up on an outcome |
| `onStatusChange` | | Called when `status` changes from `connecting` to `open`, `reconnecting` or `closed` |

`connection.outcome(quoteId, txHashes, waitUntil)` asks for an outcome itself, with `'swap'` for an [answer at the swap](https://docs.intear.tech/dex-aggregator/reference/outcome.md#answering-at-the-swap), and `connection.close()` closes the connection and fails the outcomes it waits for.
