Quickstart
This page is also Markdown, for agents: /dex-aggregator/quickstart.md, and /llms.txt lists every page.
This page goes through swapping 1 NEAR to USDt in a web app, where the trader’s wallet signs. It takes a WebSocket for live quotes, one wallet approval to execute the best one, and one request to find out how the swap went.
The examples use NEAR Connect (@hot-labs/near-connect). Signing with a key you hold, like in a bot, on a server or in Rust? Follow Swapping instead. The JavaScript and Rust libraries do both, and check the router’s transactions before they’re signed.
-
Subscribe to quotes.
Open a WebSocket to
/route/subscribeand send it the swap. It answers with quotes as soon as it found them, and again whenever pools change them, so the one you show is always fresh. All amounts are raw integers in the token’s smallest unit: 1 NEAR is10^24yoctoNEAR.const socket = new WebSocket('wss://router.intear.tech/route/subscribe');let latestId = 0;function requestQuotes(params) {latestId += 1;socket.send(JSON.stringify({ id: latestId, query: new URLSearchParams(params).toString() }));}socket.addEventListener('message', (event) => {const update = JSON.parse(event.data);if (update.id !== latestId) return; // an update of an older requestif ('error' in update) {showError(update.error);} else {showQuotes(update.routes);}});socket.addEventListener('open', () => {requestQuotes({token_in: 'near',token_out: 'nep141:usdt.tether-token.near',amount_in: '1000000000000000000000000',slippage_type: 'Fixed',slippage: '0.01',trader_account_id: 'alice.near',});});Always pass
trader_account_idfor real quotes. Without it, the route can’t include the storage deposits and registrations the trader is missing, and the swap may fail or lose tokens. It’s an optional field, since you might want to still show the rates even when user’s wallet is not connected yet. See Live quotes for when the user changes the form. -
Pick a quote.
routesis an array of quotes, one per DEX that found a route, sorted best first. It’s already ranked by what the trader gets after gas and storage costs, so in most cases you take the first one. An empty array means no DEX found a route.[{"dex_id": "RheaDcl","estimated_amount": { "amount_out": "4880007" },"worst_case_amount": { "amount_out": "4831206" },"token_output": "nep141:usdt.tether-token.near","execution_instructions": [ ... ],"estimated_gas_usage": "8231794617168100000000","estimated_max_gas_cost": "12521020071713600000000","storage_deposits": "1250000000000000000000","fee_amount": "0","needs_unwrap": false}]Show the user
estimated_amountas the expected result andworst_case_amountas the minimum they will receive.estimated_gas_usageis the amount of NEAR that will likely be spent on gas and actually burnt, whileestimated_max_gas_costis all the gas the transactions attach, at NEAR’s minimum gas price: the most they can burn. The user needs at leaststorage_deposits + estimated_max_gas_costNEAR, plus the input when swapping from NEAR, to execute the transactions. Keepingestimated_max_gas_cost * 10and another 0.05 NEAR for future gas costs to swap back gives a safe margin. -
Have the wallet send the transactions.
Each item in
execution_instructionsis a NEAR transaction. Pass them all to the wallet at once: it asks the trader to approve them, then sends them one by one, in order. With app fees, the last ones haveis_fee_transaction: true. Send them too: the wallet doesn’t send them if the swap fails.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 JSONgas: String(call.gas),deposit: call.deposit,},})),})),});} -
Swap, and check the outcome.
A swap that fails doesn’t fail its transaction, so ask
/route/outcomehow it went, with the hashes of the transactions before the fee transactions. It waits for them to execute, so you can call it right away.// Fee transactions included: the wallet doesn't send them if the swap failsconst results = await sendTransactions(wallet, quote.execution_instructions);// The outcome of the transactions before the fee transactions, which come lastconst 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 requesttoken_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 NEARif (outcome.next_steps.length > 0) await sendTransactions(wallet, outcome.next_steps);If
charge_feeistrue, the swap went through: showamount_inandamount_out. Otherwise, showerror, a message written for the trader.next_stepsmove tokens that ended up somewhere else to where the trader wanted them, like the wNEAR left over from a failed swap from NEAR, or the output of a route whosetoken_outputdiffers fromtoken_out. They’re usually empty.
What’s next
Section titled “What’s next”- Try different parameters in the Playground.
- See Executing a route for the instruction format and signing with your own key.
- Earn from the volume you bring with app fees.