DEX API
Build swap applications on EVM

Build swap applications on EVM#

In this guide, we will provide an example token swap through OKX DEX, using ETH from the Ethereum chain to purchase USDT. This process includes:

  • Set up your environment
  • Obtain swap information and build transaction data
  • Check allowance
  • Send swap transaction
  • Get approval and send swap transaction

1. Set up your environment#

Import the necessary Node.js libraries and set your environment variables as well as define helper functions and assembly parameters Node.js Environment Settings.

2. Obtain swap information and build transaction data#

2.1 Define your swap parameters#

Next, define the parameters for the swap you want to perform.

const swapParams = {
  chainId,
  fromTokenAddress,
  toTokenAddress,
  amount: '1000000000000000',
  slippage: '0.03',
  userWalletAddress,
  referrerAddress: '', // Optional
  feePercent: '', // Optional
};

2.2 Define helper functions#

Define helper functions that will be used to interact with the DEX swap API.

const getSwapData = async () => {
  const apiRequestUrl = getRequestUrl(apiBaseUrl, '/swap', swapParams);
  return fetch(apiRequestUrl, {
    method: 'get',
    headers: headersParams,
  })
    .then((res) => res.json())
    .then((res) => {
      return res;
    });
};

2.3 Build transaction data#

Transaction parameters are assembled to initiate transactions.

const { data } = await getSwapData();
const transaction = data[0]?.tx;
const nonce = await web3.eth.getTransactionCount(userWalletAddress, 'latest');
// You can obtain the latest nonce and process the hexadecimal numbers starting with 0x according to your needs
let signTransactionParams = {
  data: transaction.data,
  gasPrice: transaction.gasPrice,
  gas: transaction.gas,
  to: transaction.to,
  value: transaction.value,
  nonce,
};

3. Check allowance#

3.1 Please refer to the tutorial#

Get allowance

  • The variable allowanceAmount in the following text represents the actual allowance amount on the blockchain.

3.2 Get allowance amount#

Obtain the specific quantity. If allowanceAmount !== '0', please check step 4. If allowanceAmount === '0', please check step 5.

const { data: allowanceData } = await getAllowanceData();
const allowanceAmount = allowanceData?.[0]?.allowanceAmount;

4. Send swap transaction#

Tip
If allowanceAmount is greater than zero, it indicates that the approval operation has been performed and the transaction can be directly sent.
if (allowanceAmount !== '0') {
  const { rawTransaction } = await web3.eth.accounts.signTransaction(
    signTransactionParams,
    privateKey
  );
  const chainTxInfo = await web3.eth.sendSignedTransaction(rawTransaction);
  console.log('chainTxInfo', chainTxInfo);
}

5. Get approval and send swap transaction#

Tip
If allowanceAmount === '0', it indicates that approval has not been granted, and approval operations need to be performed at this time.

5.1 Define your transaction approval parameters#

Next, define the parameters for the transaction approval you want to perform.

const getApproveTransactionParams = {
  chainId,
  tokenContractAddress: fromTokenAddress,
  userWalletAddress,
  approveAmount: '...',
};

5.2 Define helper functions#

Define helper functions that will be used to interact with the DEX transaction approval API.

const approveTransaction = async () => {
  const apiRequestUrl = getRequestUrl(
    apiBaseUrl,
    '/approve-transaction',
    getApproveTransactionParams
  );

  return fetch(apiRequestUrl, {
    method: 'get',
    headers: headersParams,
  })
    .then((res) => res.json())
    .then((res) => {
      return res;
    });
};

5.3 Get transaction tx#

Get tx information after obtaining approval.

const { data } = await approveTransaction();

5.4 Merge transaction tx#

Update tx to approved tx.

signTransactionParams = {
  ...signTransactionParams,
  ...{ data: data[0].data },
};

5.5 Send swap transaction#

Obtain signature tx information and send transaction.

if (allowanceAmount === '0') {
  const { rawTransaction } = await web3.eth.accounts.signTransaction(
    signTransactionParams,
    privateKey
  );
  const chainTxInfo = await web3.eth.sendSignedTransaction(rawTransaction);
  console.log('chainTxInfo', chainTxInfo);
}