Rubic Documents
  • RUBIC
    • Overview
    • Rubic's Ecosystem
    • Security
    • Tokenomics
    • Roadmap
    • Rubic Discord Roles
    • “Swap to Earn” Program on Rubic
    • MEV-bot Protection
    • B2B Cross-Chain Toolkit
      • Use Cases
      • Why Rubic?
    • Refund Guidelines for Stuck Transactions
  • ⚒️Integrate SDK
    • SDK Overview
    • SDK Architecture
    • SDK Advantages
    • SDK Integration
    • 1️⃣Install SDK
    • 2️⃣Set up SDK
    • 3️⃣Trade calculation
    • 4️⃣Swap Execution
    • 📜Advanced documentation
    • Migration from V2 to V3
    • Contact Us
  • Integrate Widget
    • Widget Overview
    • Instruction
    • White Label Widget Integration Instruction
    • Partners
    • Listing of tokens
  • Rubic API
    • 🔐Tokens API
    • Referrer And Rate Limits
    • Rubic API
      • Supported chains
      • Supported providers
      • Request Quote
      • Request Data
      • Get Cross-Chain Status
      • Integration example
        • Swaps from EVM
        • Swaps from Solana
        • Swaps from TON
        • Swaps from Tron
        • Swaps from Bitcoin
        • Swaps VIA deposit
      • Swagger
      • Models
        • OnChainTradeType
        • CrossChainTradeType
        • FeesDto
        • RoutingDto
        • TransactionDto
        • ErrorDto
      • Errors
    • Monetization And Fees
  • FAQ
    • What is Rubic?
    • How to start using Rubic?
    • Who can use our service?
    • Is KYC required?
    • What are the minimum and maximum trade sizes?
    • Should I list my token before using your service?
    • How to create a Swap?
    • How long does it take to complete a transaction?
    • How is the privacy and security of the transaction ensured?
    • How does Rubic unite different DEX platforms?
    • Why does Rubic offer a choice between different providers?
    • How do I add the BNB Smart Chain and Polygon networks to MetaMask?
    • What should I do when I see the message: “Trading on Uniswap is not available?”
    • What should I do if Uniswap doesn’t display any rates?
    • How can we integrate the Rubic Relay widget?
    • How do we get listed on Rubic?
    • How to Complete swaps to/from TON network using Rubic
  • Contacts
    • Community
    • PR Marketing
    • Business Development
    • Support
    • Influencers Collaboration Requests
  • Legal Documentation
    • Privacy Policy
    • Terms of Use
    • Third-Party Software
  • Audits
    • MixBytes Audit
  • Pitch Deck
Powered by GitBook
On this page
  • Connecting a Web3 Wallet
  • Retrieving Token Quotes
  • Retrieving Data to Execute a Transaction
  • Executing a Transaction with the API Response Data
  • Track your transaction

Was this helpful?

  1. Rubic API
  2. Rubic API
  3. Integration example

Swaps from TON

Connecting a Web3 Wallet and Executing a Transaction through Rubic API

This page explains how to connect a Web3 wallet, retrieve token quotes, approve tokens, and execute a transaction using Rubic API, with examples using TonConnectUI

Connecting a Web3 Wallet

To interact with the blockchain, we first need to connect a wallet. Here are examples using TonConnectUI.

import { TonConnectUI } from '@tonconnect/ui';

async function connectWallet() {
    const tonConnect = new TonConnectUI(...);

    try {
          await this.tonConnect.connector.restoreConnection();
      } catch {}
      const isConnected = (await this.tonConnect.connectionRestored) && 
          tonConnect.connected;

      if (!isConnected) {
        const payload = await RetroBridgeApiService.getMessageToAuthWallet();
        this.tonConnect.setConnectRequestParameters({
          state: 'ready',
          value: { tonProof: this.window.btoa(payload) }
        });
        await this.openWalletModal();
      }
}

Retrieving Token Quotes

Now that the wallet is connected, we can request token quotes from Rubic API.

Endpoint: POST https://api-v2.rubic.exchange/api/routes/quoteBest

async function quoteBest() {
    const response = await fetch("https://api-v2.rubic.exchange/api/routes/quoteBest", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: {
            "srcTokenAddress": "0x0000000000000000000000000000000000000000",
            "srcTokenAmount": "10",
            "srcTokenBlockchain": "TON"
            "dstTokenAddress": "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs",
            "dstTokenBlockchain": "TON",
            "referrer": "rubic.exchange"
          }
    });
    const data = await response.json();
    const { estimate, transaction, id } = data;
    console.log(estimate);
    // {
    //     This is an estimated amount you will get after the swap.
    //     "destinationTokenAmount": "59.859216",
    //     "destinationTokenMinAmount": "59.260624",
    //
    //     "destinationUsdAmount": 59.86,
    //     "destinationUsdMinAmount": 59.26,
    //
    //     "destinationWeiAmount": "59859216",
    //     "destinationWeiMinAmount": "59260624",
    //
    //     "durationInMinutes": 5,
    //     "priceImpact": 0.21,
    //     "slippage": 0.01
    // }
    console.log(id);
    // This is the swap ID. It will be needed later for swap request.
    return data;
}

You get more information about quote endpoint here:

Retrieving Data to Execute a Transaction

To perform a token swap through Rubic API, we need to get the necessary data for the transaction.

Endpoint: POST https://api-v2.rubic.exchange/api/routes/swap

async function getSwapData() {
    const response = await fetch("https://api-v2.rubic.exchange/api/routes/swap", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: {
            "srcTokenAddress": "0x0000000000000000000000000000000000000000",
            "srcTokenAmount": "10",
            "srcTokenBlockchain": "TON"
            "dstTokenAddress": "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs",
            "dstTokenBlockchain": "TON",
            "referrer": "rubic.exchange"
            "fromAddress": "USER WALLET ADDRESS",
            "id": "ID FROM QUOTE STEP",
            "receiver": "RECEIVER ADDRESS"
          }
    });
    const result = await response.json();
    const { transaction } = result;
    console.log(transaction);
    // {
    //     "tonMessages": [{
    //                        "address": "0:1150b518b2626ad51899f98887f8824b70065456455f7fe2813f012699a4061f",
    //                        "amount": "10270000000",
    //                        "payload": "te6cckEBAgEAqgABbw+KfqUAA...VtY85yV2h5cGA/o2ZlxGelAhaWKht7fpKSyms="
    //                    }]
    // }
    return result;
}

You get more information about swap endpoint here:

Executing a Transaction with the API Response Data

Using the data obtained from the Rubic API, you can now execute the transaction.

import { base64 } from 'ethers/lib/utils';
import { VersionedTransaction } from '@solana/web3.js';

async function executeSwap(
    // Transaction object, obtained on previous step from Rubic API
    transaction,
    // Connection object
    tonConnect
) {
    const { boc } = await tonConnect.sendTransaction({
        validUntil: Math.floor(Date.now() / 1000) + 360,
        messages: transaction.messages
    });
    return boc;       
}

Track your transaction

Now you can track your transaction status

Endpoint: GET https://api-v2.rubic.exchange/api/routes/status

async function getStatus(
    // Your transaction hash, otained while executing transaction
    hash
) {
    const response = await fetch(`https://api-v2.rubic.exchange/api/info/status?srcTxHash=${hash}`);
    const data = await response.json();
    const { status, destinationTxHash } = data;
    console.log(status);
    // Current TX status can be one of
    // 'PENDING' | 'LONG_PENDING' | 'REVERT' |
    // 'REVERTED' | 'FAIL' | 'READY_TO_CLAIM' |
    // 'SUCCESS' | 'NOT_FOUND';
    console.log(status);
    // shows the hash on the target network if the transaction
    // is successfully completed
    return status;
}

You get more information about status endpoint here:

PreviousSwaps from SolanaNextSwaps from Tron

Last updated 2 months ago

Was this helpful?

Request Quote
Request Data
Get Cross-Chain Status