> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rubic.finance/llms.txt
> Use this file to discover all available pages before exploring further.

# Swaps from EVM

> 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`.

<Tabs>
  <Tab title="Ethers.js">
    ```javascript theme={null}
    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.");
        }
    }
    ```
  </Tab>

  <Tab title="Web3.js">
    ```javascript theme={null}
    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.");
        }
    }
    ```
  </Tab>

  <Tab title="Viem">
    ```javascript theme={null}
    import { createWalletClient, custom } from 'viem';
    import { mainnet } from 'viem/chains';

    async function connectWallet() {
        if (window.ethereum) {
            const walletClient = createWalletClient({
                chain: mainnet,
                transport: custom(window.ethereum),
            });
            const [account] = await walletClient.requestAddresses();
            return account;
        } else {
            console.error("Ethereum provider not found. Please install MetaMask.");
        }
    }
    ```
  </Tab>
</Tabs>

## 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`

```javascript theme={null}
async function quoteBest() {
    const response = await fetch("https://api-v2.rubic.exchange/api/routes/quoteBest", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            "srcTokenAddress": "0x0000000000000000000000000000000000000000",
            "srcTokenAmount": "1.05",
            "srcTokenBlockchain": "ETH",
            "dstTokenAddress": "0x0000000000000000000000000000000000000000",
            "dstTokenBlockchain": "POLYGON",
            "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": "8248.453781656313882666",
    //     "destinationTokenMinAmount": "8001.000168206624466186",
    //
    //     "destinationUsdAmount": 2637.13,
    //     "destinationUsdMinAmount": 2558.02,
    //
    //     "destinationWeiAmount": "8248453781656313882666",
    //     "destinationWeiMinAmount": "8001000168206624466186",
    //
    //     "durationInMinutes": 5,
    //     "priceImpact": 0.14,
    //     "slippage": 0.03
    // }
    console.log(transaction.approvalAddress);
    // This is the address you need to give approve to spend tokens.
    // See next section for details.
    // 0x3335733c454805df6a77f825f266e136FB4a3333
    console.log(id);
    // This is the swap ID. It will be needed later for swap request.
    return data;
}
```

You can get more information about quote endpoint here: [Request Quote](https://dev-docs.rubic.exchange/docs/api-docs/request-quote)

## Approving 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.

<Tabs>
  <Tab title="Ethers.js">
    ```javascript theme={null}
    import { ethers } from "ethers";
    import { TOKEN_ABI } from "./TokenABI"; // replace with the correct ABI

    async function approveToken(
        // Token address
        tokenAddress,
        // Contract to give approve to.
        // Put here transaction.approvalAddress obtained on previous step
        spenderAddress,
        // Amount of tokens to approve.
        // For security reasons it's better to set approve
        // amount equal to from amount
        amount,
        // Signer object, obtained while ethers.js initializing
        signer 
    ) {
        const tokenContract = new ethers.Contract(tokenAddress, TOKEN_ABI, signer);
        const tx = await tokenContract.approve(spenderAddress, amount);
        await tx.wait();
        console.log("Approval successful:", tx.hash);
    }
    ```
  </Tab>

  <Tab title="Web3.js">
    ```javascript theme={null}
    import Web3 from "web3";
    import { TOKEN_ABI } from "./TokenABI"; // replace with the correct ABI

    async function approveToken(
        // Token addres
        tokenAddress,
        // Contract to give approve to.
        // Put here transaction.approvalAddress obtained on previous step
        spenderAddress,
        // Amount of tokens to approve.
        // For security reasons it's better to set approve
        // amount equal to from amount
        amount,
        // Wallet address
        account
    ) {
        const web3 = new Web3(window.ethereum);
        const tokenContract = new web3.eth.Contract(TOKEN_ABI, tokenAddress);
        const tx = await tokenContract.methods.approve(spenderAddress, amount).send({ from: account });
        console.log("Approval successful:", tx.transactionHash);
    }
    ```
  </Tab>

  <Tab title="Viem">
    ```javascript theme={null}
    import { createWalletClient, encodeFunctionData } from 'viem';
    import { TOKEN_ABI } from './TokenABI'; // replace with the correct ABI

    async function approveToken(
        // Token addr
        tokenAddress,
        // Contract to give approve to.
        // Put here transaction.approvalAddress obtained on previous step
        spenderAddress,
        // Amount of tokens to approve.
        // For security reasons it's better to set approve
        // amount equal to from amount
        amount,
        // Wallet client object, obtained while viem initializing
        walletClient,
        // Wallet addres
        account
    ) {
        const txHash = await walletClient.writeContract({
            address: tokenAddress, 
            abi: TOKEN_ABI,
            functionName: 'approve',
            args: [spenderAddress, amount]
        });
        console.log("Approval successful:", txHash);
    }
    ```
  </Tab>
</Tabs>

## 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`

```javascript theme={null}
async function getSwapData() {
    const response = await fetch("https://api-v2.rubic.exchange/api/routes/swap", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            "srcTokenAddress": "0x0000000000000000000000000000000000000000",
            "srcTokenAmount": "1.05",
            "srcTokenBlockchain": "ETH",
            "dstTokenAddress": "0x0000000000000000000000000000000000000000",
            "dstTokenBlockchain": "POLYGON",
            "referrer": "rubic.exchange",
            "fromAddress": "USER WALLET ADDRESS",
            "id": "ID FROM QUOTE STEP"
          })
    });
    const result = await response.json();
    const { transaction } = result;
    console.log(transaction);
    // {
    //     "approvalAddress": "0x3335733c454805df6a77f825f266e136FB4a3333",
    //     "data": "0xe1fcde8e0000000...00000000000000000000000000000000000000000000000",
    //     "to": "0x3335733c454805df6a77f825f266e136FB4a3333",
    //     "value": "1050785817564594203"
    // },
    return result;
}
```

You can get more information about swap endpoint here: [Request Data](https://dev-docs.rubic.exchange/docs/api-docs/request-data)

## Executing a Transaction with the API Response Data

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

<Tabs>
  <Tab title="Ethers.js">
    ```javascript theme={null}
    async function executeSwap(
        // Transaction object, obtained on previous step from Rubic API
        transaction,
        // Signer object, obtained while ethers.js initializing
        signer
    ) {
        const tx = await signer.sendTransaction({
            to: transaction.to,
            data: transaction.data,
            value: transaction.value,
        });
        await tx.wait();
        console.log("Transaction executed:", tx.hash);
    }
    ```
  </Tab>

  <Tab title="Web3.js">
    ```javascript theme={null}
    async function executeSwap(
        // Transaction object, obtained on previous step from Rubic API
        transaction,
        // Wallt address
        account
    ) {
        const web3 = new Web3(window.ethereum);
        const tx = await web3.eth.sendTransaction({
            from: account,
            to: transaction.to,
            data: transaction.data,
            value: transaction.value,
        });
        console.log("Transaction executed:", tx.transactionHash);
    }
    ```
  </Tab>

  <Tab title="Viem">
    ```javascript theme={null}
    async function executeSwap(
        // Transaction object, obtained on previous step from Rubic AP
        transaction,
        // Wallet client object, obtained while viem initializing
        walletClient,
        // Wallt addres
        account
    ) {
        const txHash = await walletClient.sendTransaction({
            account,
            to: transaction.to,
            data: transaction.data,
            value: transaction.value,
        });
        console.log("Transaction executed:", txHash);
    }
    ```
  </Tab>
</Tabs>

## Track your transaction

Now you can track your transaction status

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

```javascript theme={null}
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 can get more information about status endpoint here: [Get cross-chain status](https://dev-docs.rubic.exchange/docs/api-docs/get-crosschain-status)
