Skip to content

Executing a route

Every quote has execution_instructions, an ordered list of transactions that perform the swap. You don’t need to know anything about the DEX contracts: sign what you get, in order, then ask for the outcome. It tells you whether the swap went through, and gives you the transactions that pay your app fees and move tokens that ended up in the wrong place.

How it works depends on who signs:

  • You hold the key, like a bot, a server or a wallet: request quotes with fees_in_next_steps over the WebSocket, and pay the fees from the outcome. See Swapping.
  • A web app that has the trader’s wallet sign: request quotes without it, so the wallet asks the trader once for the swap and its fees. See Swapping from a web app.

The JavaScript library and the Rust library do all of this, and check the router’s transactions before they’re signed.

Right now there’s only one kind of instruction, NearTransaction:

{
"NearTransaction": {
"receiver_id": "wrap.near",
"actions": [
{
"FunctionCall": {
"method_name": "near_deposit",
"args": "e30=",
"gas": 5000000000000,
"deposit": "1000000000000000000000000"
}
}
],
"is_fee_transaction": false
}
}
Field Type Meaning
receiver_id string The contract the transaction is sent to
actions array Actions of the transaction, in order
is_fee_transaction boolean Pays app fees after the swap, see Fee transactions

The transaction is signed by the trader, the account you passed as trader_account_id.

Send the transactions one at a time, in the given order, and wait for each to succeed before sending the next. Later steps depend on earlier ones: a storage deposit has to land before a token can be received, NEAR has to be wrapped before wNEAR can be swapped, and so on. If a transaction fails, stop.

A swap that fails, for example because the price moved past the slippage limit, doesn’t fail its transaction: the DEX refunds the input, and the transaction succeeds. Only the outcome tells you whether the swap went through.

  1. Open a WebSocket to /route/subscribe and request quotes with fees_in_next_steps: true and a trader_account_id:

    {
    "id": 1,
    "query": "token_in=near&token_out=nep141:usdt.tether-token.near&amount_in=1000000000000000000000000&slippage_type=Fixed&slippage=0.01&trader_account_id=alice.near",
    "fees_in_next_steps": true
    }

    The quotes come without their fee transactions, and each has a quote_id.

  2. Sign and send the best quote’s execution_instructions, in order.

  3. Ask for the outcome of the quote’s transactions, on the same socket:

    { "id": 2, "outcome": { "quote_id": 4611686, "tx_hashes": ["9FtHUFBQsZ2MG77K3x3MJ9wjX3UT8zE1TczCrhZEcG8U"] } }

    The router waits for the transactions to execute, and answers with the same id:

    { "id": 2, "outcome": { "charge_fee": true, "amount_in": "1000000000000000000000000", "amount_out": "4880007", ... } }

    Route updates of the first request keep coming meanwhile, with "id": 1. Keep the socket open until the outcome arrives: closing it cancels the request.

  4. If charge_fee is true, the swap went through: show amount_in and amount_out. Otherwise, show error, a message written for the trader. See the outcome for every field.

  5. Execute next_steps, in order, the same way as the route’s instructions. Once the swap went through, they pay the fees. They also move tokens that ended up somewhere else to where the trader wanted them, like the output of a route whose token_output differs from token_out, or the wNEAR left over from a failed swap from NEAR. Without fees, they’re usually empty.

With near-api-js, on Node.js 22 or later, which has WebSocket:

import { Account, actions } from 'near-api-js';
const account = new Account('alice.near', 'https://free.rpc.fastnear.com', 'ed25519:<private key>');
/**
* Signs and sends the transactions one by one, in order, and returns their hashes. Throws if one
* fails.
*/
export async function sendTransactions(account, instructions) {
const txHashes = [];
for (const { NearTransaction: tx } of instructions) {
const { transaction_outcome } = await account.signAndSendTransaction({
receiverId: tx.receiver_id,
actions: tx.actions.map(({ FunctionCall: call }) =>
actions.functionCall(
call.method_name,
Buffer.from(call.args, 'base64'),
BigInt(call.gas),
BigInt(call.deposit),
),
),
});
txHashes.push(transaction_outcome.id);
}
return txHashes;
}
const socket = new WebSocket('wss://router.intear.tech/route/subscribe');
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true });
socket.addEventListener('error', () => reject(new Error('Failed to connect to the router')), { once: true });
});
/**
* Sends the message, and resolves with the first update of its id
*/
function request(message) {
socket.send(JSON.stringify(message));
return new Promise((resolve, reject) => {
socket.addEventListener('close', () => reject(new Error('The router closed the connection')));
socket.addEventListener('message', function onMessage(event) {
const update = JSON.parse(event.data);
if (update.id !== message.id) return; // an update of the other request
socket.removeEventListener('message', onMessage);
resolve(update);
});
});
}
const quotes = await request({
id: 1,
query: new URLSearchParams({
token_in: 'near',
token_out: 'nep141:usdt.tether-token.near',
amount_in: '1000000000000000000000000', // 1 NEAR
slippage_type: 'Fixed',
slippage: '0.01', // 1%
trader_account_id: account.accountId,
}).toString(),
fees_in_next_steps: true,
});
if ('error' in quotes) throw new Error(quotes.error);
const quote = quotes.routes[0];
if (!quote) throw new Error('No route found');
const txHashes = await sendTransactions(account, quote.execution_instructions);
const answer = await request({ id: 2, outcome: { quote_id: quote.quote_id, tx_hashes: txHashes } });
socket.close();
if ('error' in answer) throw new Error(answer.error);
// Pays the fees if the swap went through, and moves what ended up somewhere else
await sendTransactions(account, answer.outcome.next_steps);

Add "wait_until": "swap" to the outcome request to get the answer as soon as the swap executed, before the output reaches the trader, callbacks and gas refunds. Show it then. Its next_steps are empty when it says settled: false, so ask for the outcome again without wait_until, and execute the next_steps of that answer. A swap that failed is only answered once everything executed, with settled: true and its next_steps.

Pass the key you sign with as signing_public_key in the route request too. Each quote then has signing: the key’s nonce and a recent block hash, so you can sign without asking an RPC for them first. The first transaction takes nonce + 1, and each one after it the nonce after the one before.

A web app doesn’t hold the trader’s key: the wallet signs, and asks the trader to approve. Request quotes without fees_in_next_steps, and the fee transactions are in execution_instructions, marked with is_fee_transaction: true. Send all the transactions in one request, so the trader approves the swap and its fees at once, instead of a second time just for the fees. It’s then the wallet’s job to cancel the fee transactions when it sees that the swap failed. Use this only when the wallet signs: anywhere else, use fees_in_next_steps.

With NEAR Connect, whose signAndSendTransactions sends the transactions in order after one approval:

import { NearConnector } from '@hot-labs/near-connect';
const connector = new NearConnector({ network: 'mainnet' });
await connector.connect();
const wallet = await connector.wallet();
/**
* Has the wallet sign and send the transactions, in order, after one approval
*/
function sendTransactions(wallet, instructions) {
return wallet.signAndSendTransactions({
transactions: instructions.map(({ NearTransaction: tx }) => ({
receiverId: tx.receiver_id,
actions: tx.actions.map(({ FunctionCall: call }) => ({
type: 'FunctionCall',
params: {
methodName: call.method_name,
args: JSON.parse(atob(call.args)), // args are base64-encoded JSON
gas: String(call.gas),
deposit: call.deposit,
},
})),
})),
});
}
// Fee transactions included: the wallet doesn't send them if the swap fails
const results = await sendTransactions(wallet, quote.execution_instructions);
// The outcome of the transactions before the fee transactions, which come last
const swapTransactions = quote.execution_instructions.filter(({ NearTransaction: tx }) => !tx.is_fee_transaction);
const txHashes = results.slice(0, swapTransactions.length).map((result) => result.transaction_outcome.id);
const params = new URLSearchParams({
// The token_in, token_out and trader_account_id of the route request
token_in: 'near',
token_out: 'nep141:usdt.tether-token.near',
trader_account_id: 'alice.near',
tx_hashes: txHashes.join(','),
fee_amount: quote.fee_amount,
});
const response = await fetch(`https://router.intear.tech/route/outcome?${params}`);
if (!response.ok) throw new Error(await response.text());
const outcome = await response.json();
// Moves what ended up somewhere else, like the wNEAR of a failed swap from NEAR
if (outcome.next_steps.length > 0) await sendTransactions(wallet, outcome.next_steps);

The outcome comes from GET /route/outcome: pass it the hashes of the transactions before the fee transactions, and the quote’s fee_amount, so that next_steps leave what the fee transactions pay in the wallet. Show amount_in and amount_out, or error, and execute next_steps as above. They don’t pay fees here: the fee transactions were already sent. With wait_until=swap, it answers sooner in the same way.

Routes with app fees on Rhea and Rhea DCL pay them in fee transactions, because Rhea’s own referral system is very limited and permissioned. They send the fees in the input token, after a storage_deposit for each account that isn’t registered with the token yet. Their fee_amount is what they pay out of the wallet balance of the input token, wNEAR for NEAR.

  • With fees_in_next_steps, they’re left out of the quote, and the outcome has them in its next_steps once the swap went through.
  • Without it, they’re the last transactions of execution_instructions, after any conversion of the output.

IntearDex routes have no fee transactions: Intear DEX takes the fees in the swap, and only if it goes through. See App fees for each DEX.

Each quote tells you what it costs in NEAR, on top of the swap amount:

Field Use it for
estimated_gas_usage The gas fee to show to the user
estimated_max_gas_cost The most gas can cost, if all attached gas is burnt. Make sure the wallet has at least this much
storage_deposits NEAR spent on storage deposits. Usually only non-zero the first time the trader uses a token or DEX

So before swapping, the trader needs at least storage_deposits + estimated_max_gas_cost NEAR, plus the input when swapping from NEAR: amount_in, or worst_case_amount.amount_in for exact output. With fees_in_next_steps, these still count the fee transactions.

These costs are already taken into account when quotes are sorted, so a route with slightly more output but much higher costs ranks lower.

A quote is based on the pool state at the moment it was found. Pools change every block, so don’t execute a quote that’s more than a few seconds old. Use the newest quote of the WebSocket, which sends new ones as pools change. A quote with a fee discount fails once the discount expires, about 10 minutes after the quote.