Swaps from EVM
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 ethers.js, web3.js, and viem
Connecting a Web3 Wallet
To interact with the blockchain, we first need to connect a wallet. Here are examples using ethers.js, web3.js, and viem.
import { ethers } from "ethers";
async function connectWallet() {
if (window.ethereum) {
const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const signer = provider.getSigner();
const account = await signer.getAddress();
return account;
} else {
console.error("Ethereum provider not found. Please install MetaMask.");
}
}import Web3 from "web3";
async function connectWallet() {
if (window.ethereum) {
const web3 = new Web3(window.ethereum);
await window.ethereum.enable();
const [account] = await web3.eth.getAccounts();
return account;
} else {
console.error("Ethereum provider not found. Please install MetaMask.");
}
}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
You get more information about quote endpoint here:
Request QuoteApproving Tokens for Transaction
Before sending a transaction, you need to approve the token. Approve allows a user to authorize a contract or application to manage a specified amount of their tokens, which is necessary for secure interaction with decentralized applications such as exchanges or DeFi protocols. This gives users control over how many tokens can be used, providing an additional layer of security.
Below are examples for different libraries.
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
You get more information about swap endpoint here:
Request DataExecuting a Transaction with the API Response Data
Using the data obtained from the Rubic API, you can now execute the transaction.
Track your transaction
Now you can track your transaction status
Endpoint: GET https://api-v2.rubic.exchange/api/routes/status
You get more information about status endpoint here:
Get Cross-Chain StatusLast updated
Was this helpful?