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.
asyncfunctionquoteBest() {constresponse=awaitfetch("https://api-v2.rubic.exchange/api/quoteBest", { method:"POST", headers: {"Content-Type":"application/json", }, body: {"srcTokenAddress":"0x0000000000000000000000000000000000000000","srcTokenAmount":"10","srcTokenBlockchain":"TON""dstTokenAddress": "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs","dstTokenBlockchain":"TON","referrer":"rubic.exchange" } });constdata=awaitresponse.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.
asyncfunctiongetStatus(// Your transaction hash, otained while executing transaction hash) {constresponse=awaitfetch(`https://api-v2.rubic.exchange/api/routes/status?srcTxHash=${hash}`);constdata=awaitresponse.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 completedreturn status;}
You get more information about status endpoint here: