Guide
An overview guide on how to integrate OpenOcean Swap API
OpenOcean Swap API Integration Guide
In the following guide, it will introduce how to use this OpenOcean's swap API in the most efficient way.
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 for 30+ on EVM and Non-EVM chains, refer the docs of supported chains to check in details.
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
You can use the get Token List API to to retrieve all available tokens on the selected blockchain. Next, select input token from the chain to swap. Make sure to save the token information for further use.
Example request
import axios from 'axios';
async function tokenList() {
const { data } = await axios({
url: `https://open-api.openocean.finance/v4/bsc/tokenList`,
method: 'GET',
});
const tokenList = data?.data;
return tokenList;
}
Example response
{
"code": 200,
"data": [
{
"id": 2908,
"code": "trustswap",
"name": "Trust Swap",
"address": "0x94eafeeef7ffa66203fdc9349c54d601472a79dc",
"decimals": 18,
"symbol": "SWAP",
"icon": "https://s3.openocean.finance/token_logos/logos/1727977942735_22094853568022899.png",
"chain": "bsc",
"createtime": "2024-10-03T17:52:30.000Z",
"hot": null,
"sort": "2024-10-03T17:52:30.000Z",
"chainId": null,
"customSymbol": null,
"customAddress": null,
"usd": "0.110158"
},
```
]
}
2. Get gasPrice
Example request
async function gasPrice() {
const { data } = await axios({
url: `https://open-api.openocean.finance/v4/bsc/gasPrice`,
method: 'GET',
});
const gasPrice = data?.without_decimals?.standard;
console.log(`bsc gasPrice is ${gasPrice} Gwei`);
return gasPrice;
}
Example response
{
"code": 200,
"data": {
"standard": 1000000000,
"fast": 1000000000,
"instant": 1000000000
},
"without_decimals": {
"standard": 1,
"fast": 1,
"instant": 1
}
}
3. (Optional) Set a Token Allowance
Before proceeding with the swap, you'll need to set a token allowance. This process is to grant a third party to allow access your tokens on your behalf. In this case, you'll need to specify the amount of tokens, and approve for the swap contract to trade your ERC20 tokens.
Example request
async function allowance() {
const { data } = await axios({
url: `https://open-api.openocean.finance/v4/bsc/allowance`,
method: 'GET',
params: {
account: '0xB3cbe...', // wallet address
inTokenAddress: '0x55d398326f99059ff775485246999027b3197955' // usdt token address
}
})
const allowance = data?.data[0]?.allowance;
console.log(`usdt allowance is ${allowance}`);
return allowance;
}
Example response
{
code: 200,
data: [
{
symbol: 'USDT',
allowance: '115792089237316200000000000000000000000000000000000000000000', // without decimals
raw: '115792089237316200000000000000000000000000000000000000000000000000000000000000' // wei with decimals
}
]
}
4. Token Approve
Approving assets is necessary for Defi users to grant the contract to use their tokens to swap. As with the getBalance
method, you can use the wallet method or directly use our SDK to get a specific token approved for trading. You can use the getAllowance
API to query the allowance data from our server.
Example:
import { ethers, Contract } from 'ethers';
async function approve() {
const rpcUrl = 'https://binance.llamarpc.com';
let provider = new ethers.JsonRpcProvider(rpcUrl);
const privateKey = ''; //wallet address;
const inTokenAddress = '0x55d398326f99059ff775485246999027b3197955'; // token address
const contractAddress = ''; // contract address
const wallet = new ethers.Wallet(privateKey, provider);
const contract = await new Contract(inTokenAddress, abi, wallet); // abi, erc20 abi
try {
await contract.approve(contractAddress, new BigNumber('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff').toFixed(0, 1));
} catch (error) {
return error;
}
return true;
}
5. Price Quote
In this API, you are able to fetch the price quote for selected token pairs. In the following, we used token pair of OOE/BNB on BNB chain as an example.
Example request
const res = await axios.get( "https://open-api.openocean.finance/v4/bsc/quote", { chain: 'bsc'
inTokenAddress: '0x8ea5219a16c2dbF1d6335A6aa0c6bd45c50347C5',
outTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
amount: 10,
gasPrice: 1,
slippage:1,
}).then((res) => {
const result = res.data
}).catch((err) => {
throw new Error(err)
})
Example response:
{
"code": 200,
"data": {
"inToken": {
"address": "0x8ea5219a16c2dbF1d6335A6aa0c6bd45c50347C5",
"decimals": 18,
"symbol": "OOE",
"name": "OpenOcean",
"usd": "0.00785727",
"volume": 0.0785727
},
"outToken": {
"address": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
"decimals": 18,
"symbol": "BNB",
"name": "Binance Coin",
"usd": "597.06",
"volume": 0.07931000455452637
},
"inAmount": "10000000000000000000",
"outAmount": "132834228644569",
"estimatedGas": "179172",
"path": {
"from": "0x8ea5219a16c2dbF1d6335A6aa0c6bd45c50347C5",
"to": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
"parts": 10,
"routes": [
{
"parts": 10,
"percentage": 100,
"subRoutes": [
{
"from": "0x8ea5219a16c2dbF1d6335A6aa0c6bd45c50347C5",
"to": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
"parts": 25,
"dexes": [
{
"dex": "OpenOcean",
"id": "0xC6394f580157D7e8ae16f5fa1F8640d292EEDdB2",
"parts": 25,
"percentage": 100
}
]
}
]
}
]
},
"save": 0,
"price_impact": "0.93%"
}
}
6. Get Transaction Body
You can use swap quote API to get transaction calldata, then submit the transaction on-chain using your wallet.
Example request
async function swap() {
const params = {
inTokenAddress: '0x55d398326f99059ff775485246999027b3197955', // usdt token address
outTokenAddress: '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', // usdc token address
slippage: 1, // 1 means 1%
amount: 1, // without decimals
gasPrice: 1, // without decimals, get from gasPrice api
account: '0xB3cbe...' // wallet address
}
const { data } = await axios({
url: `https://open-api.openocean.finance/v4/bsc/swap`,
method: 'GET',
params
})
console.log(data)
return data;
}
Example response
{
code: 200,
data: {
inToken: {
address: '0x55d398326f99059ff775485246999027b3197955',
decimals: 18,
symbol: 'USDT',
name: 'Tether USD',
usd: '0.997832',
volume: 0.997832
},
outToken: {
address: '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d',
decimals: 18,
symbol: 'USDC',
name: 'USD Coin',
usd: '0.998723',
volume: 0.997356644511025
},
inAmount: '1000000000000000000',
outAmount: '998631897444061017',
estimatedGas: 519772,
minOutAmount: '988645578469620406',
from: '', // wallet address
to: '0x6352a56caadC4F1E25CD6c75970Fa768A3304e64', // contract address
value: '0',
gasPrice: '1000000000',
data: '0x90411a32...', // input data
chainId: 56,
rfqDeadline: 0,
gmxFee: 0,
price_impact: '-0.05%'
}
}
7. Send transaction
Once your wallet plugin is triggered, it confirms that the sendTransaction
function has been successfully called with all parameters set. When our swap gets processed and executed on chain, the transaction hash will be generated.
Example request
async function send_transaction() {
const rpcUrl = 'https://binance.llamarpc.com';
const privateKey = ''; // wallet privateKey
const provider = new ethers.JsonRpcProvider(rpcUrl);
// get from swap
const params: any = {
from: '', // wallet address, get from swap
to: '', // contract address, get from swap
gasPrice: '', // wei, get from swap
data: '', // input data, get from swap
value: '', // native token amount, get from swap
gasLimit: '' // get from swap
}
const gasLimit = await provider.estimateGas(params);
params.gasLimit = gasLimit;
const wallet = new ethers.Wallet(privateKey, provider);
const { hash } = await wallet.sendTransaction(params);
return hash;
}
Last updated