Transaction Example
A complete walkthrough of executing a token swap using the OpenOcean API, from getting a quote to signing and broadcasting the transaction.
Swap Overview
The swap function enables users to seamlessly exchange one asset/token for another directly at the best swap rate. The swap API supports 40+ EVM and Non-EVM chains; refer to the supported chains docs for details.
The current API supports both V3 and V4, with the following example using V4. For detailed parameter settings, please refer to the Swap API documentation before getting started.
Swap Tokens in 7 Steps
- (Optional) Get token info
- Get gasPrice
- (Optional) Set a token allowance
- Set token approvals and signature
- Price quote
- Get transaction body
- Send transaction and signature
1. Get Token Info
Use the get Token List API to retrieve all available tokens on the selected blockchain. Select the input token and save the token information for further use.
Example request
1 import axios from 'axios'; 2
3 async function tokenList() { 4 const { data } = await axios({ 5 url: `https://open-api.openocean.finance/v4/bsc/tokenList`, 6 method: 'GET', 7 }); 8 const tokenList = data?.data; 9 return tokenList; 10 }
Example response
1 { 2 "code": 200, 3 "data": [ 4 { 5 "id": 2908, 6 "code": "trustswap", 7 "name": "Trust Swap", 8 "address": "0x94eaf...", 9 "decimals": 18, 10 "symbol": "SWAP", 11 "icon": "...", 12 "chain": "bsc" 13 } 14 ] 15 }
2. Get gasPrice
Example request
1 async function gasPrice() { 2 const { data } = await axios({ 3 url: `https://open-api.openocean.finance/v4/bsc/gasPrice`, 4 method: 'GET', 5 }); 6 const gasPrice = data?.without_decimals?.standard; 7 console.log(`bsc gasPrice is ${gasPrice} Gwei`); 8 return gasPrice; 9 }
Example response
1 { 2 "code": 200, 3 "data": { 4 "standard": 1000000000, 5 "fast": 1000000000, 6 "instant": 1000000000 7 }, 8 "without_decimals": { 9 "standard": 1, 10 "fast": 1, 11 "instant": 1 12 } 13 }
3. (Optional) Set a Token Allowance
Before swapping, set a token allowance to grant the swap contract access to your ERC20 tokens.
1 async function allowance() { 2 const { data } = await axios({ 3 url: `https://open-api.openocean.finance/v4/bsc/allowance`, 4 method: 'GET', 5 params: { 6 account: '0xB3cbe...', 7 inTokenAddress: '0x55d398326f99059ff775485246999027b3197955' 8 } 9 }); 10 const allowance = data?.data[0]?.allowance; 11 return allowance; 12 }
4. Token Approve
Approving assets is necessary for DeFi users to grant the contract to use their tokens to swap. Use the wallet or SDK; you can use the getAllowance API to query allowance from our server.
1 import { ethers, Contract } from 'ethers'; 2 import BigNumber from 'bignumber.js'; 3
4 async function approve() { 5 const rpcUrl = 'https://binance.llamarpc.com'; 6 let provider = new ethers.JsonRpcProvider(rpcUrl); 7 const privateKey = ''; 8 const inTokenAddress = '0x55d398326f99059ff775485246999027b3197955'; 9 const contractAddress = ''; 10 const wallet = new ethers.Wallet(privateKey, provider); 11 12 const abi = ['function approve(address spender, uint256 amount) returns (bool)']; 13 const contract = await new Contract(inTokenAddress, abi, wallet); 14 15 try { 16 await contract.approve( 17 contractAddress, 18 new BigNumber('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff').toFixed(0, 1) 19 ); 20 } catch (error) { 21 return error; 22 } 23 return true; 24 }
5. Price Quote
Fetch the price quote for selected token pairs (e.g. OOE/BNB on BNB chain).
1 const res = await axios.get("https://open-api.openocean.finance/v4/bsc/quote", { 2 params: { 3 chain: 'bsc', 4 inTokenAddress: '0x8ea5219a16c2dbF1d6335A6aa0c6bd45c50347C5', 5 outTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', 6 amount: 10, 7 gasPrice: 1, 8 slippage: 1, 9 } 10 }).then((res) => res.data).catch((err) => { throw new Error(err) });
Response includes inToken, outToken, inAmount, outAmount, estimatedGas, path, price_impact, etc.
6. Get Transaction Body
Use the swap quote API to get transaction calldata, then submit on-chain using your wallet.
1 async function swap() { 2 const params = { 3 chain: 'bsc', 4 inTokenAddress: '0x55d398326f99059ff775485246999027b3197955', 5 outTokenAddress: '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', 6 slippage: 1, 7 amount: 1, 8 gasPrice: 1, 9 account: '0xB3cbe...' 10 }; 11 const { data } = await axios({ 12 url: `https://open-api.openocean.finance/v4/bsc/swap`, 13 method: 'GET', 14 params 15 }); 16 return data; 17 }
7. Send transaction
Once the wallet confirms sendTransaction with all parameters, the swap is processed on chain and a transaction hash is generated.
1 async function send_transaction() { 2 const rpcUrl = 'https://binance.llamarpc.com'; 3 const privateKey = ''; 4 const provider = new ethers.JsonRpcProvider(rpcUrl); 5 6 // Get params from swap response 7 const params = { 8 from: '', 9 to: '', 10 gasPrice: '', 11 data: '', 12 value: '', 13 gasLimit: '' 14 }; 15 16 const gasLimit = await provider.estimateGas(params); 17 params.gasLimit = gasLimit; 18 19 const wallet = new ethers.Wallet(privateKey, provider); 20 const { hash } = await wallet.sendTransaction(params); 21 return hash; 22 }
Full Example Code
For complete working examples including error handling and TypeScript support, check out our GitHub repository.