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.
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.
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.
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.
{ 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.
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.
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
asyncfunctionsend_transaction() {constrpcUrl='https://binance.llamarpc.com';constprivateKey=''; // wallet privateKeyconstprovider=newethers.JsonRpcProvider(rpcUrl);// get from swapconstparams: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 }constgasLimit=awaitprovider.estimateGas(params);params.gasLimit = gasLimit;constwallet=newethers.Wallet(privateKey, provider);const { hash } =awaitwallet.sendTransaction(params);return hash;}