SDK
GitHub: openocean-api
Install OpenOcean Aggregator SDK
1 npm i @openocean.finance/openocean-sdk
Or with yarn:
1 yarn add @openocean.finance/openocean-sdk
If you want to build a wallet and contract object yourself, you will need web3 and bignumber.js:
1 npm install bignumber.js 2 npm install web3
How to use the SDK in your project
1 import { OpenoceanSdk } from '@openocean.finance/openocean-sdk' 2 const openoceanSdk = new OpenoceanSdk() 3 const { api, swapSdk, config } = openoceanSdk
You can then use all the functions exposed by the SDK (api and swapSdk).
Start programming now
Before you start developing a DeFi trading project, understand the general DeFi trading workflow:
- Choose a chain.
- Choose your wallet.
- Choose the token pair.
- Input the amount you want to trade.
- Swap. We recommend using the Open API and Wallet plugin we provide.
Full Vue example
1 <template> 2 <div id="app"> 3 <div v-if="chain">chain: {{ chain.chainName }}</div> 4 <div v-if="myWallet">walletName: {{ myWallet.name }}, address: {{ myWallet.address }}</div> 5 <div v-if="inToken">inToken: {{ inToken.symbol }} Balance: {{ inTokenBalance }}</div> 6 <div v-if="outToken">outToken: {{ outToken.symbol }} Balance: {{ outTokenBalance }}</div> 7 <div> 8 <h3>ConnectWallet</h3> 9 <button @click="connectWallet('eth')">connectWallet eth</button> 10 <button @click="connectWallet('bsc')">connectWallet bsc</button> 11 <button @click="connectWallet('polygon')">connectWallet polygon</button> 12 </div> 13 <div> 14 <h3>Quote</h3> 15 <div v-if="inToken && outToken">{{ inAmount }} {{ inToken.symbol }} swap to {{ outAmount }} {{ outToken.symbol }}</div> 16 <button @click="quote">quote</button> 17 </div> 18 <div><h3>Swap</h3><button @click="swap">swap</button></div> 19 <div><h3>GetBalance</h3><button @click="getBalance">GetBalance</button></div> 20 </div> 21 </template> 22
23 <script> 24 import { OpenoceanSdk } from '@openocean.finance/openocean-sdk'; 25 import BigNumber from 'bignumber.js'; 26 const genSdk = new OpenoceanSdk() 27 const { api, swapSdk, config } = genSdk 28
29 export default { 30 data() { 31 return { 32 chainName: 'bsc', walletName: 'MetaMask', 33 inToken: null, outToken: null, gasPrice: 5, 34 inTokenBalance: null, outTokenBalance: null, inAmount: 1, outAmount: null, 35 myWallet: null, chain: null, 36 } 37 }, 38 methods: { 39 async getGasPrice() { this.gasPrice = await api.getGasPrice({ chain: this.chainName }) }, 40 async getTokenList() { 41 let { data } = await api.getTokenList({ chain: this.chainName }) 42 this.inToken = data.find(item => item.symbol == 'USDC') 43 this.outToken = data.find(item => item.symbol == 'BUSD') 44 this.getBalance() 45 }, 46 async quote() { 47 let response = await api.quote({ 48 chain: this.chainName, inTokenAddress: this.inToken.address, 49 outTokenAddress: this.outToken.address, amount: this.inAmount, gasPrice: this.gasPrice 50 }) 51 if (response.code == 200) 52 this.outAmount = new BigNumber(response.data.outAmount).div(10 ** this.outToken.decimals).toFixed(4) 53 else alert('Error:' + response.message) 54 }, 55 async swap() { 56 if (!this.myWallet) { alert('Please connect the wallet.'); return } 57 if (this.inTokenBalance < this.inAmount) { alert(this.inToken.symbol + ' Insufficient balance.'); return } 58 let { data } = await api.exchange({ chain: this.chainName }) 59 let allowance = await this.getAllowance(data.approveContract) 60 if (new BigNumber(allowance).lt(this.inAmount)) { await this.approve(data.approveContract); return } 61 let response = await swapSdk.swapQuote({ 62 chain: this.chainName, inTokenAddress: this.inToken.address, outTokenAddress: this.outToken.address, 63 amount: this.inAmount, gasPrice: this.gasPrice, slippage: 1, account: this.myWallet.address, 64 }) 65 if (response.code == 200) { 66 swapSdk.swap(response.data) 67 .on('error', (error) => {}) 68 .on('transactionHash', (hash) => {}) 69 .on('receipt', (data) => { this.getBalance() }) 70 .on('success', (data) => {}) 71 } else alert('Error:' + response.message) 72 }, 73 async connectWallet(chainName) { 74 try { 75 if (chainName) this.chainName = chainName 76 let data = await swapSdk.connectWallet({ chainName: this.chainName, walletName: this.walletName }) 77 if (data) { this.myWallet = data.wallet; this.chain = data.chain; this.getTokenList(); this.getGasPrice() } 78 } catch (error) { this.myWallet = null; this.chain = null } 79 }, 80 async getBalance() { 81 if (!this.myWallet) { alert('Please connect the wallet.'); return } 82 this.inTokenBalance = (await swapSdk.getBalance({ account: this.myWallet.address, chain: this.chainName, tokenAddressOrSymbol: this.inToken.address, decimals: this.inToken.decimals })).short 83 this.outTokenBalance = (await swapSdk.getBalance({ account: this.myWallet.address, chain: this.chainName, tokenAddressOrSymbol: this.outToken.address, decimals: this.outToken.decimals })).short 84 }, 85 async getAllowance(approveContract) { 86 return await swapSdk.getAllowance({ chain: this.chainName, decimals: this.inToken.decimals, tokenAddress: this.inToken.address, approveContract, account: this.myWallet.address }) 87 }, 88 async approve(approveContract) { 89 let approve = await swapSdk.approve({ chain: this.chainName, tokenAddress: this.inToken.address, approveContract, gasPrice: this.gasPrice, decimals: this.inToken.decimals, amount: this.inAmount }) 90 if (!approve.code) approve.on('error', () => {}).on('transactionHash', () => {}).on('receipt', () => {}).on('success', () => {}) 91 } 92 } 93 } 94 </script>
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 |
Example request:
1 https://open-api.openocean.finance/v3/bsc/tokenList
Example response:
1 { 2 "code": 200, 3 "data": [ 4 { 5 "id": 2377, 6 "code": "grove", 7 "name": "GroveCoin", 8 "address": "0xf33893de6eb6ae9a67442e066ae9abd228f5290c", 9 "decimals": 8, 10 "symbol": "GRV", 11 "icon": "https://s3.openocean.finance/token_logos/logos/1681183267288_9630165967657189.png", 12 "chain": "bsc", 13 "createtime": "2023-04-11T03:21:09.000Z", 14 "hot": null, 15 "sort": "2023-04-11T03:21:09.000Z", 16 "chainId": null, 17 "customSymbol": null, 18 "customAddress": null, 19 "usd": "0.948606" 20 }, 21 ... 22 ] 23 }
You need to save the token information you need for further operations. Here is the SDK method for you to get the token list:
1 async getTokenList () { 2 let { data } = await api.getTokenList({ chain: 'bsc' }) 3 this.inToken = data.find(item => item.symbol == 'USDC') 4 this.outToken = data.find(item => item.symbol == 'BUSD') 5 }
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.
Please note that multiple browser wallets can conflict — only open one (e.g. MetaMask, TrustWallet, Coin98Wallet can't be open at the same time).
Using wallet directly:
1 import { MetaMask } from "@openocean.finance/wallet"; 2
3 const connectWallet = async (params) => { 4 const myWallet = new MetaMask() 5 const result = await myWallet.requestConnect(params.chainId); 6 // you can use the requestConnect function to trigger your wallet 7 }
Or trigger the wallet directly by the SDK:
1 async connectWallet () { 2 try { 3 let AllChainNames = config.chains.chainNames 4 let AllWalletNames = config.wallets.walletList.map(item => item.key) 5 // ["MetaMask","CryptoCom","TrustWallet",...] 6 // ["eth","ropsten","rinkeby","bsc","solana","flow","polygon","avax",...] 7 let data = await swapSdk.connectWallet({ 8 chainName: this.chainName, 9 walletName: this.walletName 10 }) 11 if (data) { 12 this.myWallet = data.wallet 13 // this.chain = data.chain 14 // this.getBalance() 15 } 16 } catch (error) { 17 this.myWallet = null 18 this.chain = null 19 } 20 }
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.
Example to init a contract object to call the ABI (e.g. check inToken balance):
1 const { sdk } = myWallet; 2 contract = new sdk.eth.Contract(Contract_abi, inToken_address); 3 // For example, by running this code, you get the contract to check the inToken's balance
Or, if you want to use ethers:
1 const { sdk } = myWallet; 2 const { currentProvider } = sdk; 3 myEtherWallet = new ethers.providers.Web3Provider(currentProvider); 4 // transfer your web3 wallet object to ether 5 signer = myEtherWallet.getSigner(); 6 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 the wallet object to get the balance from your wallet.
Use wallet API:
1 const { sdk } = myWallet; 2 const contract = new sdk.eth.Contract(ERC20_abi, inToken); 3 balance = await contract.methods.balanceOf(result.address).call(); 4 // Save the result object which can be used here for balance checking.
Use Open API:
1 getBalance() { 2 if (this.address) { 3 let params = { 4 chain: 'bsc', 5 chainId: 56, 6 account: your wallet address, 7 inTokenAddress: `${previousTokenAddress},${nextTokenAddress}` 8 }; 9 axios.get(`https://open-api.openocean.finance/v3/${params.chain}/getBalance`, { params }).then(res => { 10 const { data } = res.data 11 const previousBalance = data[0].balance 12 const nextBalance = data[1].balance 13 }).catch(e => console.log(e)); 14 } 15 }
Use SDK:
1 async getBalance () { 2 if (!this.myWallet) { 3 alert('Please connect the wallet.') 4 return 5 } 6 let inBalance = await swapSdk.getBalance({ 7 account: this.myWallet.address, 8 chain: this.chainName, 9 tokenAddressOrSymbol: this.inToken.address, 10 decimals: this.inToken.decimals, 11 }) 12 this.inTokenBalance = inBalance.short 13
14 let outBalance = await swapSdk.getBalance({ 15 account: this.myWallet.address, 16 chain: this.chainName, 17 tokenAddressOrSymbol: this.outToken.address, 18 decimals: this.outToken.decimals, 19 }) 20 this.outTokenBalance = outBalance.short 21 }
GetGasPrice
Use Open API:
1 getGasPrice () { 2 let chainName = 'bsc'; 3 let data = await axios.get(`https://open-api.openocean.finance/v3/${chainName}/gasPrice`) 4 }
Use SDK:
1 async getGasPrice () { 2 this.gasPrice = await api.getGasPrice({ 3 chain: this.chainName, 4 }) 5 }
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:
1 const gas = await contract.methods.approve(toContract, approveAmount).estimateGas({ from: account }); 2 // get your gas fee 3 return await contract.methods.approve(toContract, approveAmount).send({ 4 from: account, 5 gasPrice, 6 gas, 7 });
Use SDK:
1 async approve (approveContract) { 2 let approve = await swapSdk.approve({ 3 chain: this.chainName, 4 tokenAddress: this.inToken.address, 5 approveContract: approveContract, 6 gasPrice: this.gasPrice, 7 decimals: this.inToken.decimals, 8 amount: this.inAmount 9 }) 10 if (!approve.code) { 11 approve.on('error', (error) => { debugger }) 12 .on('transactionHash', (hash) => { debugger }) 13 .on('receipt', (data) => { debugger }) 14 .on('success', (data) => { debugger }) 15 } 16 }
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 | Chain name |
| inTokenAddress | string | 0x9029FdFAe9A03135846381c7cE16595C3554e10A | Sell token address |
| outTokenAddress | string | 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE | Buy token address |
| amount | number | 10 | Sell amount |
| gasPrice | number | 5 | Set yourself or get through GetGasPrice |
| slippage | number | 1 | 1 equals 1%, ranges 0.01% to 100% |
Example — get price between OOE and BNB with Axios:
1 const res = await axios.get("https://open-api.openocean.finance/v3/bsc/quote", { 2 chain: 'bsc', 3 inTokenAddress: '0x9029FdFAe9A03135846381c7cE16595C3554e10A', 4 outTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', 5 amount: 10, 6 gasPrice: 5, 7 slippage: 1, 8 }).then((res) => { 9 const result = res.data 10 }).catch((err) => { 11 throw new Error(err) 12 })
Example response:
1 { 2 code: 200, 3 data: { 4 "inToken": { "symbol": "AUSD", "name": "Avaware USD", "address": "0x783C08b5F26E3daf8C4681F3bf49844e425b6393", "decimals": 18 }, 5 "outToken": { "symbol": "EMBR", "name": "EmbrToken", "address": "0xD81D45E7635400dDD9c028839e9a9eF479006B28", "decimals": 18 }, 6 "inAmount": "5000000000000000000", 7 "outAmount": "126261357830302882735", 8 "estimatedGas": "189669", 9 "dexes": [ { "dexIndex": 1, "dexCode": "SushiSwap", "swapAmount": "0" }, ... ], 10 "path": { } 11 } 12 }
Or use the API module in SDK (e.g. quote on Ont chain):
1 async quote () { 2 let response = await api.quote({ 3 chain: this.chainName, 4 inTokenAddress: this.inToken.address, 5 outTokenAddress: this.outToken.address, 6 amount: this.inAmount, 7 gasPrice: this.gasPrice 8 }) 9 if (response.code == 200) { 10 this.outAmount = new BigNumber(response.data.outAmount).div(10 ** this.outToken.decimals).toFixed(4) 11 } else { 12 alert('Error:' + response.message) 13 } 14 }
Swap
Here is the last step! 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), or use the swap_quote API to get the transaction body from our API server. The workflow we recommend for API users is: use Swapquote API to get transaction body, then use the wallet to request your transaction on chain.
Example — make a transaction on BNB Chain (Open API + wallet):
1 async swap() { 2 if (this.address && this.inAmount > 0) { 3 let params = { 4 chain: 'bsc', 5 inTokenAddress: '0x9029FdFAe9A03135846381c7cE16595C3554e10A', 6 outTokenAddress: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', 7 amount: 5, 8 gasPrice: 5, 9 slippage: 100, 10 }; 11 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"); 12 if (res) { 13 const { estimatedGas, data, gasPrice } = res.data.data; 14 const swapParams = { 15 from: this.address, 16 to: '0x6352a56caadc4f1e25cd6c75970fa768a3304e64', 17 gas: estimatedGas, 18 gasPrice: gasPrice, 19 data 20 }; 21 const result = await this.myWallet.sdk.eth.sendTransaction(swapParams) 22 } else { 23 return 24 } 25 } 26 }
On the SDK workflow (e.g. make a swap on Terra chain):
1 async swap () { 2 if (!this.myWallet) { 3 alert('Please connect the wallet.') 4 return 5 } 6 if (this.inTokenBalance < this.inAmount) { 7 alert(`${this.inToken.symbol} Insufficient balance.`) 8 return 9 } 10 let { data } = await api.exchange({ chain: this.chainName }) 11 let allowance = await this.getAllowance(data.approveContract) 12 if (new BigNumber(allowance).lt(this.inAmount)) { 13 await this.approve(data.approveContract) 14 return 15 } 16 let response = await swapSdk.swapQuote({ 17 chain: this.chainName, 18 inTokenAddress: this.inToken.address, 19 outTokenAddress: this.outToken.address, 20 amount: this.inAmount, 21 gasPrice: this.gasPrice, 22 slippage: 1, // 1% 23 account: this.myWallet.address, 24 }) 25 if (response.code == 200) { 26 swapSdk.swap(response.data) 27 .on('error', (error) => { debugger }) 28 .on('transactionHash', (hash) => { debugger }) 29 .on('receipt', (data) => { 30 debugger 31 this.getBalance() 32 }) 33 .on('success', (data) => { debugger }) 34 } else { 35 alert('Error:' + response.message) 36 } 37 }