DEX API

Use Widget#

Integrate the powerful OKX Widget into your product! With this widget, you can create an effective trading interface within 30 minutes.

Install#

yarn add @okxweb3/dex-widget
// or
npm install @okxweb3/dex-widget
// or
pnpm add @okxweb3/dex-widget

Quickstart#

Here is an example which shows how to use @okxweb3/dex-widget in a React project. You can find more examples through this link.

Demo:https://okx.github.io/dex-widget/

import React, { useRef, useEffect } from 'react';
import ReactDOM from 'react-dom/client';

import { createOkxSwapWidget } from '@okxweb3/dex-widget';

function App() {
  const widgetRef = useRef();

  useEffect(() => {
    const params = {
      width: 375,
      providerType: 'EVM',
    };
    const provider = window.ethereum;

    const listeners = [
      {
        event: 'ON_CONNECT_WALLET',
        handler: () => {
          provider.enable();
        },
      },
    ];

    const instance = createOkxSwapWidget(widgetRef.current, {
      params,
      provider,
      listeners,
    });
    return () => {
      instance.destroy();
    };
  }, []);

  return <div ref={widgetRef} />;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Wallet provider#

You should pass the wallet provider information from your application if you want to connect a wallet. Then add the ON_CONNECT_WALLET event to seamlessly use the widget as part of your application.

  • If it’s on Ethereum or other EVM networks, the provider must comply with EIP-1193 to implement the interface.
  • If it’s on Solana, the provider must pass the wallet provider information from your application, e.g. window.solana, window.okexchain.solana.
import { createOkxSwapWidget, ProviderType } from '@okxweb3/dex-widget';

const widgetEthInstance = createOkxSwapWidget(
  document.getElementById('widget'),
  {
    params: {
      providerType: ProviderType.EVM,
    },
    provider: window.ethereum, // e.g. window.okexchain
  }
);

const widgetSolanaInstance = createOkxSwapWidget(
  document.getElementById('widget'),
  {
    params: {
      providerType: ProviderType.SOLANA,
    },
    provider: window.solana, // window.okexchain.solana
  }
);

You can check out this link。 for an example of using the Rainbow kit to connect to a wallet.

Params#

The following sheet contains the descriptions of the params.

ParameterTypeDefaultDescription
widthnumber450The width of the widget in css values (px). If the width is not set, the display style for the width will be: 450px when the screen width > 767px. 100% when the screen width < 768px. 375px when the screen width < 375px.
themeTHEMElightThe swap widget provides a default light theme and a dark theme as options. You can change the theme of the widget by following the example below.
langstringen_usThe widget language is adjustable. Check the Multilanguage section for more details.
tradeTypeTradeTypeautoThe type of transaction. It can be “swap”, “bridge”, or “auto”.Note: “Auto” includes “swap” and “bridge”.
chainIdsArray<string>[]The ID of the blockchain on which the single-chain swap will take place. Check the ChainId config section for all the networks that you can choose from.
feeConfigIFeeConfig{}You can enable a fee for all transactions in the widget. Check the Fee customization section for more details.
tokenPairITokenPair{}The default token pair you have set for Swap, can be found in the default tokenPair configuration section for more details.
bridgeTokenPairITokenPair{}The default token pair you have set for Bridge, can be found in the default tokenPair configuration section for more details.
providerTypeProviderType' 'ProviderType represents the type of the provider and corresponds to it one-to-one. For example, if the provider is Solana, then the providerType would be SOLANA.

Type description#

interface IFeeConfig {
    [key: string]: {
        feePercent?: string | number;
        referrerAddress?: {
            [key: string]: {
                feePercent: string | number;
            };
        };
    };
}

interface ITokenPair {
    fromChain: string | number;
    toChain: string | number;
    fromToken?: string;
    toToken?: string;
}

enum ProviderType {
    EVM = 'EVM',
    SOLANA = 'SOLANA',
    WALLET_CONNECT = 'WALLET_CONNECT',
}

enum TradeType {
    SWAP = 'swap',
    BRIDGE = 'bridge',
    AUTO = 'auto',
}

enum THEME {
    LIGHT = 'light',
    DARK = 'dark',
}

Multilanguage#

langDescription
en_usEnglish,Default
zh_cn简体中文
zh_tw繁體中文
fr_frFrançais (Afrique)
id_idBahasa Indonesia
ru_ruРусский
tr_trTürkçe
vi_vnTiếng Việt
de_deDeutsch
it_itItaliano
pl_plPolski
pt_ptPortuguês (Portugal)
es_esEspañol (España)
pt_brPortuguês (Brasil)
es_419Español (Latinoamérica)
cs_czČeština
ro_roRomână
uk_uaУкраїнська
ar_ehالعربية
nl_nlNederlands

ChainId config#

NetworkChainIdNative token contract
Ethereum10xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
zkSync Era3240xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Optimism100xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Polygon1370xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Avalanche C431140xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Arbitrum421610xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Linea591440xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Base84530xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Mantle50000xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Scroll5343520xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
X layer1960xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Blast814570xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
BNB Chain560xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
Solana50111111111111111111111111111111111

default tokenPair config#

tokenPair: If tokenPair not configured, the default network for single-chain swaps is set to Ethereum, with ETH as fromToken and USDC as toToken.

bridgeTokenPair: If bridgeTokenPair not configured, the default bridge transaction is set to one from Ethereum to BNB Chain, with ETH as fromToken and BNB as toToken.

import React, { useEffect, useRef } from 'react';
import {
  OkxSwapWidgetParams,
  ProviderType,
  TradeType,
} from '@okxweb3/dex-widget';

const provider = window.ethereum;

export function EvmWidget() {
  const widgetRef = useRef();

  const params = {
    chainIds: ['1', '10'],
    lang: 'zh_cn',
    providerType: ProviderType.EVM,
    theme: 'dark',
    tradeType: TradeType.AUTO,
    tokenPair: {
      fromChain: 1, //ETH
      toChain: 1, // ETH
      fromToken: '0xdac17f958d2ee523a2206206994597c13d831ec7', // USDT
      toToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // ETH
    },
    bridgeTokenPair: {
      fromChain: 1, //ETH
      toChain: 56, // BNB
      fromToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // ETH
      toToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // BNB
    },
  };
  const initialConfig = {
    params,
    provider,
    listeners: [
      {
        event: 'ON_CONNECT_WALLET',
        handler: (token, preToken) => {
          provider.enable();
        },
      },
    ],
  };

  useEffect(() => {
    const widgetHandler = createOkxSwapWidget(widgetRef.current, initialConfig);

    return () => {
      widgetHandler?.destroy();
    };
  }, []);

  return <div ref={widgetRef} />;
}
ParameterTypeDescription
fromChainStringThe ID of the source network that the fromToken belongs to (e.g., 1: Ethereum. Check ChainId config for a full list of the supported networks and the corresponding chain IDs).
fromTokenStringThe contract address of the token to be sold. E.g., ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE. If the fromToken is a blockchain’s native token, check the chain ID to get the contract address.
toChainStringThe ID of the destination network that the toToken belongs to (e.g., 1: Ethereum. Check ChainId config for a full list of the supported networks and the corresponding chain IDs).
toTokenString"The contract address of a token to be bought. E.g., USDC: 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48. If the toToken is a blockchain’s native token, check the chain ID to get the contract address."

Fee customization#

You may enable feeConfig to collect fees on the transactions executed by your users on different networks through the widget by adding the following parameters:

You need to declare the chainId, feePercent, and referrerAddress.

For Ethereum or other EVM networks, you can set the feePercent and the referrerAddress to receive the fees.

For Solana, SOL and SPL-token commissions are different. SOL commissions use wallet addresses, and SPL-token commissions use token accounts.

You can adjust the fee rate of the commission received by the referrerAddress by adding feePercent:

// EVM feeConfig example
feeConfig: {
    [chainId]: {
        referrerAddress: 'xxx',
        feePercent: [0-3],
    }
}

// Solana feeConfig example

feeConfig: {
    [chainId]: {
        feePercent: [0-3],
        referrerAddress: {
          [tokenContractA]: {
            referrerAccount: 'account/abc',
            feePercent: '1',
          },
          [tokenContractB]: {
            referrerAccount: 'account/abc',
            feePercent: '2',
          }
        }
    }
}

// Full Example
feeConfig: {
  1: {// Ethereum chainId
    feePercent: 3, // The percentage of Fee
    referrerAddress: '0x38a3b108eb2b97c307bf5788909f8c12afd0cd6b', // eth address that receives the fee
  },
  56: { // Bnb Chain chainId
    feePercent: 3, //
    referrerAddress: '0x38a3b108eb2b97c307bf5788909f8c12afd0cd6b', // bnb address that receives the fee
  },
  501: { // solana chainId
    referrerAddress: {
      '11111111111111111111111111111111': { //solana SOL contract address
        account: '6rocMMKG1DNg93RDfVL2xVdrA5nbAT8cFMbdvVTHUF4m',
        feePercent: 1,
      },
      EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: { //solana USDC contract address
        account: 'C6XW7mFvCuVxYFTi9zTQrUcwkvhfGYAvuosXz6pLDZsa', //solana USDC token account that receives the fee
        feePercent: 1,
      },
      JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN: { //solana JUP contract address
        account: 'Ezq6jTC3CwnsXDSdtgy8Sa4xi1iA6fxuEeXxWFPLG9sc', //solana JUP token account that receives the fee
        feePercent: 1,
      },
    },
  },
  8453: {
    feePercent: 3,
    referrerAddress: '0x38a3b108eb2b97c307bf5788909f8c12afd0cd6b',
  },
}

feePercent#

The percentage of fromTokenAmount that will be sent to the referrer’s address. The rest of the token amount will be set as the input amount to be sold. The fee rate is in basis points (BPS). One basis point is equivalent to 0.01% (1/100th of a percent). The fee rate can’t exceed 3% (300 BPS).

referrerAddress#

The referrerAddress is the address that receives the fee.

Make sure that the fee recipient address exists on its respective network as defined in the parameters sheet.

Widget update#

updateParams#

Updateable attributes: theme, lang, width

// 1. Create and initialize the widget
const widgetHandler = createOkxSwapWidget(container, initialConfig);

// 2. Update the widget's parameters (e.g., change theme or size)
widgetHandler.updateParams({
  width: 700,
  theme: 'light',
  lang: 'tr_tr',
});

updateProvider#

The widget supports EVM and Solana. When switching from EVM to Solana, remember to update the corresponding widget’s provider, and vice versa.

If you don’t pass in provider information for the first rendering and want the widget to respond to a wallet connection, you need to call updateProvider.

// 3. Update the provider if the user connects a different wallet, EVM => SOLANA
widgetHandler.updateProvider(window.solana, ProviderType.SOLANA);
// SOLANA => EVM
// widgetHandler.updateProvider(window.ethereum, ProviderType.EVM);

updateListeners#

You can update the events that the widget listens to.

// 4. Modify event listeners to handle new types of events
widgetHandler.updateListeners([
  {
    event: OkxEvents.ON_FROM_CHAIN_CHANGE,
    handler: (payload) => {
      //
    },
  },
]);
  • Listeners mainly listen to the interfaces exposed externally by the widget, enabling customized processing through various events. The updateListeners function is used to modify custom processing after switching chains.
  • By adding event listeners, you can capture and handle data passed out from the iframe. This data usually represents events or state changes happening within the iframe and is passed to the external page through events.
  • The received data can be processed and manipulated flexibly according to your needs. This allows you to implement different logic or update UI elements based on the type or content of the data passed.
  • With the updateListeners method, you can add handlers for different types of events, such as OkxEvents.ON_TOKEN_CHANGE. When the event is triggered, the handler will receive the relevant payload data for further processing.

destroy#

Call this method when removing the widget module.

const widgetHandler = createOkxSwapWidget(container, initialConfig);

widgetHandler.destory();

Note:#

  • Whenever you refresh or update, make sure to call the destroy method to remove previously connected events in order to prevent duplicate requests.

Event Listeners#

Widget provides event listeners for ON_CONNECT_WALLET and ON_FROM_CHAIN_CHANGE.

  • ON_CONNECT_WALLET: This event is triggered when the widget is not connected to a wallet and the connect wallet button is clicked.
  • ON_FROM_CHAIN_CHANGE: This event is triggered when fromChain changes.

Here’s how to use them:

import {createOkxSwapWidget, OkxSwapWidgetParams, OkxEventListeners, OkxEvents} from '@cowprotocol/widget-lib'

const params: OkxSwapWidgetParams = {
    // ...
}

const listeners: OkxEventListeners = [
    {
        event: OkxEvents.ON_CONNECT_WALLET,
        handler: () => {
            // open connect wallet method, eg openConnectModal of the rainbow kit.
            window.ethereum.enable()
        }
    },
    {
        event: OkxEvents.ON_FROM_CHAIN_CHANGE,
        handler: (token) => {
            //
        }
    },
]

const { updateListeners } = createCowSwapWidget(container, { params, listeners, provider })