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
  • 1. Basic configuration
  • 2. Instant Trades -> On Chain Trades
  • 3. Cross Chain Trades
  • 4. Tokens Manager
  • 5. Common changes

Was this helpful?

  1. Integrate SDK

Migration from V2 to V3

The biggest update in rubic-sdk third version was TRON integration. It required big restructuring, because TRON is not an EVM-like chain, so most of the logic changes happened in blockchain-connected classes. Also, as common code refactoring, many classed were renamed, moved to another folder, or deleted.

This guide explains how to move from version 2 to version 3.

1. Basic configuration

Version 2

import SDK, { BLOCKCHAIN_NAME, Configuration, WalletProvider } from 'rubic-sdk';

// optional parameter
const walletProvider: WalletProvider = {
    address: '0x123...', // user wallet address
    chainId, // user wallet chain id
    core: window.ethereum
};

// optional parameter
const providerAddress = '0xabc...';

const configuration: Configuration = {
    rpcProviders: {
        // optional blockchains
        [BLOCKCHAIN_NAME.ETHEREUM]: {
            mainRpc: '<your ethereum rpc>'
        },
        [BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN]: {
            mainRpc: '<your bsc rpc>'
        },
        ...
    },
    providerAddress,
    walletProvider
};
const sdk = await SDK.createSDK(configuration);
...

// Later, if user changed address, you can update configuration:
await sdk.updateConfiguration(configuration);

Version 3

/**
    Notice that now sdk is imported as `import { SDK } from 'rubic-sdk';`
    Moreover, now you can import any object as `import { ... } from 'rubic-sdk';`
*/
import { SDK, BLOCKCHAIN_NAME, Configuration, WalletProvider, CHAIN_TYPE } from 'rubic-sdk';

// optional parameter
const walletProvider: WalletProvider = {
    // CHAIN_TYPE is new type to separate EVM and TRON data
    [CHAIN_TYPE.EVM]: {
        address: '0x123...', // user wallet address
        core: window.ethereum
    },
    // optional
    [CHAIN_TYPE.TRON]: {
        address: 'T123...', // user wallet address
        core: window.tronLink.tronWeb // or window.tronWeb
    }
};

// optional parameter
const providerAddress = {
    [CHAIN_TYPE.EVM]: '0xabc...',
    // optional
    [CHAIN_TYPE.TRON]: 'TaBc...'
}

const configuration: Configuration = {
    rpcProviders: {
        // optional blockchains
        [BLOCKCHAIN_NAME.ETHEREUM]: {
            rpcList: ['<your ethereum rpc #1>', '<your ethereum rpc #2>', ...]
        },
        [BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN]: {
            rpcList: ['<your bsc rpc>']
        },
        ...
        [BLOCKCHAIN_NAME.TRON]: {
            rpcList: [
                {
                    // use your tron rpc provider
                    fullHost: 'https://api.trongrid.io',
                    headers: { "TRON-PRO-API-KEY": 'your api key' }
                }
            ]
        }
    },
    providerAddress,
    walletProvider
};
const sdk = await SDK.createSDK(configuration);
...

// Later, if user changed address, you can update configuration:
await sdk.updateConfiguration(configuration);
// Or, if you want to update only wallet configuration, you can use
// one of next functions:
sdk.updateWalletProvider(walletProvider: WalletProvider);
sdk.updateWalletProviderCore(chainType: keyof WalletProvider, walletProviderCore: WalletProviderCore);
sdk.updateWalletAddress(chainType: keyof WalletProvider, address: string);

2. Instant Trades -> On Chain Trades

Version 2

const blockchain = BLOCKCHAIN_NAME.ETHEREUM;
const fromTokenAddress = '0x0000000000000000000000000000000000000000'; // ETH
const fromAmount = 1;
const toTokenAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7'; // USDT

const trades: Array<InstantTrade | InstantTradeError> =
    await sdk.instantTrades.calculateTrade(
        { blockchain, address: fromTokenAddress }, 
        fromAmount,
        toTokenAddress
    );
const bestTrade = trades[0];

trades.forEach((trade) => {
    const tradeType: TradeType = trade.type;
    console.log(`trade type: ${tradeType}`);

    if (trade instanceof InstantTrade) {
        console.log(`to amount: ${trade.to.tokenAmount.toFormat(3)}`);
    } else {
        console.log(`error: ${trade.error}`);
    }
});

const onConfirm = (hash: string) => console.log(hash);
const receipt = await bestTrade.swap({ onConfirm });

// gas fee data
console.log(bestTrade.gasFeeInfo);

Version 3

const blockchain = BLOCKCHAIN_NAME.ETHEREUM;
const fromTokenAddress = '0x0000000000000000000000000000000000000000'; // ETH
const fromAmount = 1;
const toTokenAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7'; // USDT

// types renamed
const trades: Array<OnChainTrade | OnChainTradeError> =
    // renamed to onChainManager
    await sdk.onChainManager.calculateTrade(
        { blockchain, address: fromTokenAddress }, 
        fromAmount,
        toTokenAddress
    );
const bestTrade = trades[0];

trades.forEach((trade) => {
    // type renamed
    const tradeType: OnChainTradeType = trade.type;
    console.log(`trade type: ${tradeType}`);
  
    if (trade instanceof OnChainTrade) {
        console.log(`to amount: ${trade.to.tokenAmount.toFormat(3)}`);
    } else {
        console.log(`error: ${trade.error}`);
    }
});

const onConfirm = (hash: string) => console.log(hash);
// now transaction hash is returned
const transactionHash = await bestTrade.swap({ onConfirm });

// if you need to get fee data, you must first check class type
if (bestTrade instanceof EvmOnChainTrade) {
    console.log(bestTrade.gasFeeInfo);
}

3. Cross Chain Trades

Cross Chain did not change much, the main updates are:

// renamed to crossChainManager
const trades = await sdk.crossChainManager.calculateTrade(
    { blockchain: fromBlockchain, address: fromTokenAddress }, 
    fromAmount,
    { blockchain: toBlockchain, address: toTokenAddress }
);
const bestTrade = trades[0];

// now transaction hash is returned instead of receipt
const transactionHash = await bestTrade.swap();

// if you need to get fee data, you must first check class type
if (bestTrade instanceof EvmCrossChainTrade) {
    console.log(bestTrade.gasData);
}

4. Tokens Manager

TokensManager class was deleted. Now you can use Token classes directly.

import { Token, PriceToken, PriceTokenAmount } from 'rubic-sdk';

// Example #1
const token: Token = await Token.createToken({ 
    blockchain: BLOCKCHAIN_NAME.TRON,
    address:  'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8'
});

// Example #2
const token: Token = new Token({ 
    blockchain: BLOCKCHAIN_NAME.TRON,
    address:  'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8',
    name: 'USD Coin',
    symbol: 'USDC',
    decimals: 6
});

// Example #3
const priceToken: PriceToken = await PriceToken.createToken({ 
    blockchain: BLOCKCHAIN_NAME.TRON,
    address:  'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8'
});
const priceTokenAmount: PriceTokenAmount = await PriceTokenAmount.createToken({ 
    blockchain: BLOCKCHAIN_NAME.TRON,
    address:  'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8',
    tokenAmount: new BigNumber(1)
});

5. Common changes

// renamed types
TRADE_TYPE -> ON_CHAIN_TRADE_TYPE
CrossChainTxStatus -> TxStatus
CrossChainMinAmountError -> MinAmountError
CrossChainMaxAmountError -> MaxAmountError
PreviousAdvanced documentationNextContact Us

Last updated 11 months ago

Was this helpful?

⚒️