Skip to main content

Quick start

tip

The guide below will provide an example of a swap on the Binance Smart Chain network, but you can do the same on any network supported by 1inch Aggregation Protocol

Let's assume that you want to exchange 0.1 1INCH for DAI at the best exchange rate on the market.

const swapParams = {    fromTokenAddress: '0x111111111117dc0aa78b770fa6a738034120c302', // 1INCH    toTokenAddress: '0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3', // DAI    amount: '100000000000000000',    fromAddress: 'YOUR_WALLET_ADDRESS',    slippage: 1,    disableEstimate: false,    allowPartialFill: false,};
info

amount: '100000000000000000' - we set this value, because 1INCH token has decimals = 18

You can read more about this here.

info

About slippage, disableEstimate, allowPartialFill and other params, please, read Swap params


Check allowance#

Before making an asset exchange, we need to make sure that 1inch router has permission to exchange assets with your wallet. This is part of the ERC-20 standard, you can read more about this here.

const Web3 = require('web3');const fetch = require('node-fetch');const yesno = require('yesno');
const chainId = 56;const web3RpcUrl = 'https://bsc-dataseed.binance.org';const walletAddress = '0x...xxx'; // Set your wallet addressconst privateKey = '0x...xxx'; // Set private key of your wallet. Be careful! Don't share this key to anyone!
const swapParams = {    fromTokenAddress: '0x111111111117dc0aa78b770fa6a738034120c302', // 1INCH    toTokenAddress: '0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3', // DAI    amount: '100000000000000000',    fromAddress: walletAddress,    slippage: 1,    disableEstimate: false,    allowPartialFill: false,};
const broadcastApiUrl = 'https://tx-gateway.1inch.io/v1.1/' + chainId + '/broadcast';const apiBaseUrl = 'https://api.1inch.io/v5.0/' + chainId;const web3 = new Web3(web3RpcUrl);
function apiRequestUrl(methodName, queryParams) {    return apiBaseUrl + methodName + '?' + (new URLSearchParams(queryParams)).toString();}
function checkAllowance(tokenAddress, walletAddress) {    return fetch(apiRequestUrl('/approve/allowance', {tokenAddress, walletAddress}))        .then(res => res.json())        .then(res => res.allowance);}
const allowance = await checkAllowance(swapParams.fromTokenAddress, walletAddress);
console.log('Allowance: ', allowance);

If you have not previously exchanged this asset using 1inch Aggregation Protocol, then the following value will be displayed in the console: > Allowance: 0

This means that at the moment 1inch router is allowed to exchange 0 tokens for your wallet.


Allow exchange with 1inch router#

Ok, to allow 1inch router to exchange your tokens, we must create a transaction, indicating in it that the 1inch router is allowed to exchange a specified number of tokens:

caution

Be careful! Creating a transaction requires payment of a fee, the cost of the fee will be spent from your account.

const Web3 = require('web3');const fetch = require('node-fetch');const yesno = require('yesno');
const chainId = 56;const web3RpcUrl = 'https://bsc-dataseed.binance.org';const walletAddress = '0x...xxx'; // Set your wallet addressconst privateKey = '0x...xxx'; // Set private key of your wallet. Be careful! Don't share this key to anyone!
const swapParams = {    fromTokenAddress: '0x111111111117dc0aa78b770fa6a738034120c302', // 1INCH    toTokenAddress: '0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3', // DAI    amount: '100000000000000000',    fromAddress: walletAddress,    slippage: 1,    disableEstimate: false,    allowPartialFill: false,};
const broadcastApiUrl = 'https://tx-gateway.1inch.io/v1.1/' + chainId + '/broadcast';const apiBaseUrl = 'https://api.1inch.io/v5.0/' + chainId;const web3 = new Web3(web3RpcUrl);
function apiRequestUrl(methodName, queryParams) {    return apiBaseUrl + methodName + '?' + (new URLSearchParams(queryParams)).toString();}
async function broadCastRawTransaction(rawTransaction) {    return fetch(broadcastApiUrl, {        method: 'post',        body: JSON.stringify({rawTransaction}),        headers: {'Content-Type': 'application/json'}    })        .then(res => res.json())        .then(res => {            return res.transactionHash;        });}
async function signAndSendTransaction(transaction) {    const {rawTransaction} = await web3.eth.accounts.signTransaction(transaction, privateKey);
    return await broadCastRawTransaction(rawTransaction);}
async function buildTxForApproveTradeWithRouter(tokenAddress, amount) {    const url = apiRequestUrl(        '/approve/transaction',        amount ? {tokenAddress, amount} : {tokenAddress}    );
    const transaction = await fetch(url).then(res => res.json());
    const gasLimit = await web3.eth.estimateGas({        ...transaction,        from: walletAddress    });
    return {        ...transaction,        gas: gasLimit    };}
// First, let's build the body of the transactionconst transactionForSign = await buildTxForApproveTradeWithRouter(swapParams.fromTokenAddress);console.log('Transaction for approve: ', transactionForSign);
const ok = await yesno({    question: 'Do you want to send a transaction to approve trade with 1inch router?'});
// Before signing a transaction, make sure that all parameters in it are specified correctlyif (!ok) {    return false;}
// Send a transaction and get its hashconst approveTxHash = await signAndSendTransaction(transactionForSign);
console.log('Approve tx hash: ', approveTxHash);

After running this code in the console, you should see something like this:

> Approve tx hash: 0xb87c133e203fe66b487e27ab0afde71842dc34ab97aca60c147c7662505312a6

Having a hash of the transaction, you can monitor its execution using the blockchain explorer. For the BSC network, we use a bscscan.com: https://bscscan.com/tx/0xb87c133e203fe66b487e27ab0afde71842dc34ab97aca60c147c7662505312a6


caution

Before proceeding, please make sure that the transaction has a status of Success!


Do exchange!#

const Web3 = require('web3');const fetch = require('node-fetch');const yesno = require('yesno');
const chainId = 56;const web3RpcUrl = 'https://bsc-dataseed.binance.org';const walletAddress = '0x...xxx';const privateKey = '0x...xxx';
const swapParams = {    fromTokenAddress: '0x111111111117dc0aa78b770fa6a738034120c302', // 1INCH    toTokenAddress: '0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3', // DAI    amount: '100000000000000000',    fromAddress: walletAddress,    slippage: 1,    disableEstimate: false,    allowPartialFill: false,};
const broadcastApiUrl = 'https://tx-gateway.1inch.io/v1.1/' + chainId + '/broadcast';const apiBaseUrl = 'https://api.1inch.io/v5.0/' + chainId;const web3 = new Web3(web3RpcUrl);
function apiRequestUrl(methodName, queryParams) {    return apiBaseUrl + methodName + '?' + (new URLSearchParams(queryParams)).toString();}
async function broadCastRawTransaction(rawTransaction) {    return fetch(broadcastApiUrl, {        method: 'post',        body: JSON.stringify({rawTransaction}),        headers: {'Content-Type': 'application/json'}    })    .then(res => res.json())    .then(res => {        return res.transactionHash;    });}
async function signAndSendTransaction(transaction) {    const {rawTransaction} = await web3.eth.accounts.signTransaction(transaction, privateKey);
    return await broadCastRawTransaction(rawTransaction);}
async function buildTxForSwap(swapParams) {    const url = apiRequestUrl('/swap', swapParams);
    return fetch(url).then(res => res.json()).then(res => res.tx);}
// First, let's build the body of the transactionconst swapTransaction = await buildTxForSwap(swapParams);console.log('Transaction for swap: ', swapTransaction);
const ok = await yesno({    question: 'Do you want to send a transaction to exchange with 1inch router?'});
// Before signing a transaction, make sure that all parameters in it are specified correctlyif (!ok) {    return false;}
// Send a transaction and get its hashconst swapTxHash = await signAndSendTransaction(swapTransaction);console.log('Swap transaction hash: ', swapTxHash);

After running this code in the console, you should see something like this:

> Swap tx hash: 0xe591e17cc2b33e6a244fb2a98deb83b4659f94cf867ef7730b614d1feaa7cf9d

Let's check the result of the transaction on the explorer: https://bscscan.com/tx/0xe591e17cc2b33e6a244fb2a98deb83b4659f94cf867ef7730b614d1feaa7cf9d