Links

Recommend Workflow

Check our Best Practice
Before you start developing a DeFi trading project, you should understand the industry’s most general DeFi trading workflow. Here is the process we designed for the user to make a transaction:
  1. 1.
    Choose a chain.
  2. 2.
    Choose your wallet.
  3. 3.
    Choose the token pair.
  4. 4.
    Input the amount you want to trade.
  5. 5.
    Swap. To make this process successful, we recommend using the Open API and Wallet plugin we provide to achieve DeFi trading.

Choose Pair List

You can call the get Token List API to get all the available tokens we have on the blockchain you choose.
  • Method: Get
  • URL: https://open-api.openocean.finance/v3/:chain/tokenList
  • Parameters:
Parameter
Type
Example
Description
chain
string
avax
The chain name you want to search token
Your request will look like this:
https://open-api.openocean.finance/v3/avax/tokenList
And your response will look like this:
{
code: 200,
data: [
{
"id": 1619,
"code": "avaware-usd",
"name": "Avaware USD",
"address": "0x783C08b5F26E3daf8C4681F3bf49844e425b6393",
"decimals": 18,
"symbol": "AUSD",
"icon": "https://cloudstorage.openocean.finance/images/1646208600388_8016544631355003.png",
"chain": "avax",
"createtime": "2022-03-02T08:10:07.000Z",
"hot": null,
"sort": "2022-03-02T08:10:07.000Z",
"chainId": null
},
...
...
]
}
You need to save the token information you need for further operations.
Here is the SDK method for you to get the token list
import { OpenoceanSdk } from '@openocean.finance/openocean-sdk'
const OpenoceanSdk = new openoceanSdk()
const { api } = openoceanSdk
api.getTokenList({
chain: 'avax',
}).then((data) => {
console.log(data)
}).catch((error) => {
return
});

Connect Wallet

Connect wallet is the first step you need to participate in DeFi trading. For example, you want to connect to MetaMask, so you have to get the MetaMask wallet constructor from OpenOcean wallet.
import { MetaMask } from "@openocean.finance/wallet";
const connectWallet( params ) {
const myWallet = new MetaMask()
const result = await myWallet.requestConnect(params.chainId);
// you can use the requestConnect function to trigger your wallet
}
Or you can trigger the wallet directly by the SDK.
import { OpenoceanSdk } from '@openocean.finance/openocean-sdk'
const OpenoceanSdk = new openoceanSdk()
const { api } = openoceanSdk
async connectWallet (walletName, chainName) {
let _swapSdk = await swapSdk.connectWallet({
chainName: chainName,
walletName: walletName
// specialized the chain and wallet name for wallet initalization
})
if (_swapSdk&&_swapSdk.wallet) {
// return 200 means the wallet object is inited
console.log('success')
// return _swapSdk.wallet
return swapSdk.wallet
} else {
return
}
}
const myWallet=await connectWallet();

Run the contract in project

Once you get your wallet connected, you can use Web3.js or ethers. These are tools to create the operable object for the contract, which serves for token approving, balance checking, and swapping.
  • Here is the example to init a contract object for you to call the abi in contract
const { sdk } = myWallet;
contract = new sdk.eth.Contract(Contract_abi, inToken_address);
// For example, by running this code, you get the contract to check the inToken's balance
Or, if you want to use ethers.
const { sdk } = myWallet;
const { currentProvider } = sdk;
myEtherWallet = new ethers.providers.Web3Provider(currentProvider);
//transfer your web3 wallet object to ether
signer = myEtherWallet.getSigner();
contract = new ethers.Contract(ContractAddress, contract.abi, signer);

Get Balance

Once your wallet is connected and the address is displayed, you can use the SDK or directly use wallet object to get the balance from your wallet.
  • Use wallet API:
const { sdk } = myWallet;
const contract = new sdk.eth.Contract(ERC20_abi, inToken);
balance = await contract.methods.balanceOf(result.address).call();
//Save the result object which can be used here for balance checking.
  • Use Open API:
getBalance() {
if(this.address) {
let params = {
chainId: 1,
account: your wallet address,
inTokenAddress:`${previousTokenAddress},${nextTokenAddress}`
};
axios.get('https://open-api.openocean.finance/v1/cross/getBalance', { params }).then(res => {
const { data } = res.data
const previousBalance = data[0].balance
const nextBalance = data[1].balance
}).catch(e => console.log(e));
}
},
  • Use SDK:
api.getBalance({
account: '0x9548f567Aa2bf71a6691B634F9808346C804c0D0',
chain: 'bsc',
inTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
}).then((data) => {console.log(data)}).catch((error) => {console.log(error)});

Approve

Approving assets is necessary for DeFi users to authorize 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.
  • Use wallet Function:
const gas = await contract.methods.approve(toContract, approveAmount).estimateGas({ from: account });
// get your gas fee
return await contract.methods.approve(toContract, approveAmount).send({
from: account,
gasPrice,
gas,
});
  • Use SDK:
let approve = await swapSdk.approve({
chain: 'bsc',
tokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
contractAddress: '0x6352a56caadc4f1e25cd6c75970fa768a3304e64',
amount: 2 * (10 ** 18), //the amount you want approve(here is the maximum amout you can approve)
})
if (!approve.code) {
approve.on('error', (error) => {
console.log(error)
}).on('transactionHash', (hash) => {
console.log(hash)
}).on('receipt', (data) => {
console.log(data)
}).on('success', (data) => {
console.log(data)
})
} else {
this.message = approve.message
}

Quote

You can directly use Open API to quote the token exchange amount.
  • Method: Get
  • URL: https://open-api.openocean.finance/v3/:chain/quote
  • Parameters:
Parameter
Type
Example
Description
chain
string
bsc, avax, fantom
platform(openoceanv2,1inch,matcha,paraswap)
inTokenAddress
string
0x9029FdFAe9A03135846381c7cE16595C3554e10A
sell token address
outTokenAddress
string
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
buy token address
amount
number
10
sell amount
gasPrice
number
5
you can set it yourself or get it through GetGasPrice
slippage
number
1
1 equals 1%, ranges 0.01% to100%
For example, you want to pick up the price between OOE and BNB by Axios.
const res = await axios.get( "https://open-api.openocean.finance/v3/bsc/quote", {
chain: 'bsc'
inTokenAddress: '0x9029FdFAe9A03135846381c7cE16595C3554e10A',
outTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
amount: 10,
gasPrice: 5,
slippage:1,
}).then((res) => {
const result = res.data
}).catch((err) => {
throw new Error(err)
})
If you call it right, you will get a result like this:
{
code: 200,
data: {
"inToken": {
"symbol": "AUSD",
"name": "Avaware USD",
"address": "0x783C08b5F26E3daf8C4681F3bf49844e425b6393",
"decimals": 18
},
"outToken": {
"symbol": "EMBR",
"name": "EmbrToken",
"address": "0xD81D45E7635400dDD9c028839e9a9eF479006B28",
"decimals": 18
},
"inAmount": "5000000000000000000",
"outAmount": "126261357830302882735",
"estimatedGas": "189669",
"dexes": [
{
"dexIndex": 1,
"dexCode": "SushiSwap",
"swapAmount": "0"
},
...
],
"path": {
}
}
}
or the api modules in SDK: For example we quote Ont chain
async quoteOnt () {
let req = await api.getGasPrice({
chain: 'ont',
})
api.quote({
chain: 'ont',
inTokenAddress: '00c59fcd27a562d6397883eab1f2fff56e58ef80',
outTokenAddress: '33ae7eae016193ba0fe238b223623bc78faac158',
amount: 1,
gasPrice: req.data.gasPrice,
slippage: 1,
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.log(error)
});
},

Swap

Here is the last step! Now you have several ways to swap the token you selected. You can directly use our swap API to trigger the trade, which will not awaken your personal wallet, but you have to provide your private key to the API. You can also use the swap_quote API to get the transaction body from our API server. Here is a case for you to make a transaction on BNB Chain.
The work flow we recommand for API users, is using Swapquote API to get transaction body, then use the wallet to request your transaction on chain.
async swap() {
if(this.address && this.inAmount > 0) {
let params = {
chain: 'bsc'
inTokenAddress: '0x9029FdFAe9A03135846381c7cE16595C3554e10A',
outTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
amount: 5,
gasPrice: 5,
slippage:100,
};
const res = await axios.get("https://open-api.openocean.finance/v3/bsc/swap_quote?inTokenAddress=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&outTokenAddress=0x55d398326f99059ff775485246999027b3197955&amount=5&gasPrice=5&slippage=100&account=0x929B44e589AC4dD99c0282614e9a844Ea9483C69");
if(res) {
const {estimatedGas,data,gasPrice} = res.data.data;
const swapParams = {
from:this.address,
to:'0x6352a56caadc4f1e25cd6c75970fa768a3304e64', //this is the only contract you can use if you decide to make transaction by our API.
gas: estimatedGas,
gasPrice: gasPrice,
data
};
const result = await this.myWallet.sdk.eth.sendTransaction(swapParams)
};
else {
return
},
On the SDK workflow:
For example, we want make a swap on terra chain.
async YourSwapFunction () {
let req = await api.getGasPrice({
chain: 'terra',
})
let swapData = await swapSdk.swapQuote({
chain: 'terra',
inTokenAddress: 'uusd',
outTokenAddress: 'terra13awdgcx40tz5uygkgm79dytez3x87rpg4uhnvu',
amount: 0.01,
slippage: 1,
account: this.wallet.address,
gasPrice: req.data.gasPrice,
})
if (swapData.code == 200) {
swapSdk.swap(swapData.data)
.on('error', (error) => {
console.log(error)
})
.on('transactionHash', (hash) => {
console.log(hash)
})
.on('receipt', (data) => {
console.log(data)
})
.on('success', (data) => {
console.log(data)
})
} else {
console.log(swapData.message)
}
},

Demo

Please note, API & SDK demo is not available on mobile version.
Check out the link below to our online Demo.
Demo