Skip to content

Quickstart

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.

  1. Subscribe to quotes.

    Open a WebSocket to /route/subscribe and 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 is 10^24 yoctoNEAR.

    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 request
    if ('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_id for 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.

  2. Pick a quote.

    routes is 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_amount as the expected result and worst_case_amount as the minimum they will receive. estimated_gas_usage is the amount of NEAR that will likely be spent on gas and actually burnt, while estimated_max_gas_cost is all the gas the transactions attach, at NEAR’s minimum gas price: the most they can burn. The user needs at least storage_deposits + estimated_max_gas_cost NEAR, plus the input when swapping from NEAR, to execute the transactions. Keeping estimated_max_gas_cost * 10 and another 0.05 NEAR for future gas costs to swap back gives a safe margin.

  3. Have the wallet send the transactions.

    Each item in execution_instructions is 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 have is_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 JSON
    gas: String(call.gas),
    deposit: call.deposit,
    },
    })),
    })),
    });
    }
  4. Swap, and check the outcome.

    A swap that fails doesn’t fail its transaction, so ask /route/outcome how 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 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);

    If charge_fee is true, the swap went through: show amount_in and amount_out. Otherwise, show error, a message written for the trader. next_steps move 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 whose token_output differs from token_out. They’re usually empty.