### Get Liquidity Sources Request Example
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-get-liquidity
This example demonstrates how to make a GET request to the OKX aggregation protocol to retrieve available liquidity sources for a specific chain. Ensure you include the necessary authentication headers.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/aggregator/get-liquidity?chainIndex=1' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### OKX DEX Swap API Request Example
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-swap
This example demonstrates how to make a GET request to the OKX DEX Swap API to find optimal swap routes. Ensure you replace placeholder API keys and provide correct token addresses and chain information.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/aggregator/swap?chainIndex=1&amount=100000000000&fromTokenAddress=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&toTokenAddress=0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599&approveAmount=10000000&approveTransaction=true&slippagePercent=0.1&userWalletAddress=0x77660f108043c9e300b4e30a35a61dd19f5ae28a' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### Get Supported Chains Request Example
Source: https://web3.okx.com/onchainos/dev-docs/wallet/defi-product-supported-chains
This is an example of a GET request to the /api/v6/defi/product/supported-chains endpoint. No request parameters are required.
```plaintext
GET /api/v6/defi/product/supported-chains
```
--------------------------------
### Installation and Initialization
Source: https://web3.okx.com/onchainos/dev-docs/sdks/app-connect-cosmos-sdk
Install the OKX Universal Provider SDK and initialize it with your DApp's metadata.
```APIDOC
## Installation and Initialization
### Installation
```bash
npm install @okxconnect/universal-provider
```
### Initialization
To initialize the provider, create an object for subsequent operations.
```typescript
import { OKXUniversalProvider } from "@okxconnect/universal-provider";
const okxUniversalProvider = await OKXUniversalProvider.init({
dappMetaData: {
name: "application name",
icon: "application icon url"
},
})
```
#### Request Parameters
* `dappMetaData` - object
* `name` - string: The name of the application.
* `icon` - string: URL of the application icon (PNG, ICO recommended, 180x180px).
#### Returns Value
* `OKXUniversalProvider`
```
--------------------------------
### Get Token Developer Info Request Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-memepump-get-token-developer-info
Example of how to make a GET request to the tokenDevInfo endpoint with necessary parameters and headers.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/market/memepump/tokenDevInfo?chainIndex=501&tokenContractAddress=7Gf9...pump' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### Go MPP Pay-as-you-go Server Setup
Source: https://web3.okx.com/onchainos/dev-docs/payments/pay-as-you-go
Sets up an HTTP server using Go and the MPP library for pay-as-you-go services. Requires environment variables for API keys and private keys. Uses Gin for routing.
```plaintext
require github.com/okx/payments/go/mpp v0.1.0
```
```go
package main
import (
"log"
"math/big"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/okx/payments/go/mpp/evm"
mppgin "github.com/okx/payments/go/mpp/http/gin"
"github.com/okx/payments/go/mpp/saclient"
"github.com/okx/payments/go/mpp/server"
"github.com/okx/payments/go/mpp/store"
)
func main() {
saClient := saclient.NewOKXSAClient(
os.Getenv("OKX_BASE_URL"),
os.Getenv("OKX_API_KEY"),
os.Getenv("OKX_SECRET_KEY"),
os.Getenv("OKX_PASSPHRASE"),
)
// Payee signer for settle/close — any evm.Signer implementation.
// PrivateKeySigner / KMS / custom remote signer.
signer, err := evm.NewPrivateKeySignerFromHex(os.Getenv("PRIVATE_KEY"))
if err != nil {
log.Fatalf("signer: %v", err)
}
// Default in-memory store; swap via FileStore / custom Store for persistence.
channelStore, err := store.NewFileStore[store.ChannelState]("mpp-data")
if err != nil {
log.Fatalf("store: %v", err)
}
sessionMethod, err := evm.NewEVMSessionMethod(evm.EVMSessionMethodConfig{
ChainID: 196, // X Layer
Recipient: "0x...378211",
SAClient: saClient,
Signer: signer,
Store: channelStore,
EscrowContract: os.Getenv("ESCROW_CONTRACT"),
PerRequestCost: big.NewInt(100),
MinVoucherDelta: big.NewInt(0),
FeePayer: true,
})
if err != nil {
log.Fatalf("session method: %v", err)
}
mpp := server.NewMpp(server.EVMConfig{
ChainID: 196,
Recipient: "0x...378211",
SecretKey: os.Getenv("MPP_SECRET_KEY"),
Realm: "test realm",
```
--------------------------------
### Get Total Value by Address Response Example
Source: https://web3.okx.com/onchainos/dev-docs/market/balance-total-value
This is a successful response example for the 'Get Total Value by Address' request, showing the total asset balance in USD.
```json
{
"code": "0",
"msg": "success",
"data": [
{
"totalValue": "1172.895057177065864522056725546579939398"
}
]
}
```
--------------------------------
### Install Go Dependencies for Exact Path
Source: https://web3.okx.com/onchainos/dev-docs/payments/methods-onetime
Install the X402 Go package for handling payments.
```bash
go get github.com/okx/payments/go/x402
```
--------------------------------
### Connect and Switch Ethereum Chain Example
Source: https://web3.okx.com/onchainos/dev-docs/sdks/chains/evm/web-add-network
An interactive example demonstrating how to connect to Ethereum and switch between chains (e.g., OKT Chain and Binance Smart Chain) using buttons. It includes error handling for adding a new chain if it's not already present.
```html
```
```javascript
const connectEthereumButton = document.querySelector('.connectEthereumButton');
const switchChainButton = document.querySelector('.switchChainButton');
let accounts = [];
//Sending Ethereum to an address
switchChainButton.addEventListener('click', () => {
try {
const chainId = okxwallet.chainId === "0x42" ? "0x38" : "0x42";
await okxwallet.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: chainId }]
});
} catch (switchError) {
// This error code indicates that the chain has not been added to OKX Wallet.
if (error.code === 4902) {
try {
await okxwallet.request({
method: "wallet_addEthereumChain",
params: [{ chainId: "0xf00", rpcUrl: "https://..." /* ... */ }]
});
} catch (addError) {
// handle "add" error
}
}
// handle other "switch" errors
}
});
connectEthereumButton.addEventListener('click', () => {
getAccount();
});
async function getAccount() {
try{
accounts = await okxwallet.request({ method: 'eth_requestAccounts' });
}catch(error){
console.log(error);
}
}
```
--------------------------------
### Get Token Bundle Details Response Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-memepump-get-token-bundle-details
Example JSON response for a successful request to get token bundle details. It includes metrics like bundler performance, total bundlers, and bundled values.
```json
{
"code": "0",
"msg": "",
"data": {
"bundlerAthPercent": "0.92",
"totalBundlers": "9",
"bundledValueNative": "375",
"bundledTokenAmount": "4880000"
}
}
```
--------------------------------
### ExactEvmScheme Client Initialization
Source: https://web3.okx.com/onchainos/dev-docs/payments/sdk-go
Shows how to initialize an ExactEvmScheme client using a private key for signing and a configuration object.
```go
import (
"github.com/okx/payments/go/x402/mechanisms/evm"
evmsigners "github.com/okx/payments/go/x402/mechanisms/evm/signers"
evmclient "github.com/okx/payments/go/x402/mechanisms/evm/exact/client"
)
signer, err := evmsigners.NewClientSignerFromPrivateKey("0x...")
scheme := evmclient.NewExactEvmScheme(signer, config)
scheme.Scheme() // "exact"
```
--------------------------------
### Get Latest News Feed Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-social-news-latest
This example demonstrates how to make a GET request to the /api/v6/dex/market/social/news/latest endpoint to retrieve the latest news feed. It includes parameters for limiting results, setting detail level, and specifying the language.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/market/social/news/latest?limit=10&detailLevel=1&language=en_US' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### Install SDK Dependencies
Source: https://web3.okx.com/onchainos/dev-docs/payments/sdk-nodejs
Install the necessary packages for the OKX Web3 SDK and Viem.
```bash
npm install @okxweb3/mpp viem
```
--------------------------------
### Example: Get Current Price
Source: https://web3.okx.com/onchainos/dev-docs/market/market-ai-tools-skills
An example of a natural-language query to retrieve the current price of a token. The agent maps this to the 'index-current-price' skill.
```shell
What is the current price of OKB?
# Call index-current-price
```
--------------------------------
### Initialize Sui Environment and Dependencies
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-use-swap-sui-quick-start
Import necessary Node.js libraries for Sui interaction and OKX DEX API. Install dependencies and set up essential environment variables like API keys and wallet details. Initialize the Sui client and wallet.
```javascript
// Required libraries
import { SuiWallet } from "@okxweb3/coin-sui";
import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';
import { Transaction } from '@mysten/sui/transactions';
import cryptoJS from "crypto-js";
// Install dependencies
// npm i @okxweb3/coin-sui
// npm i @mysten/sui
// npm i crypto-js
// Set up environment variables
const apiKey = 'your_api_key';
const secretKey = 'your_secret_key';
const apiPassphrase = 'your_passphrase';
const userAddress = 'your_sui_wallet_address';
const userPrivateKey = 'your_sui_wallet_private_key';
// Constants
const SUI_CHAIN_ID = "784";
const DEFAULT_GAS_BUDGET = 50000000;
const MAX_RETRIES = 3;
// Initialize Sui client
const wallet = new SuiWallet();
const client = new SuiClient({
url: getFullnodeUrl('mainnet')
});
// For Sui, you need to use the hexWithoutFlag format of your private key
// You can convert your key using sui keytool:
// sui keytool convert
```
--------------------------------
### Initialize X402 Resource Server
Source: https://web3.okx.com/onchainos/dev-docs/payments/sdk-go
Create a new instance of the X402 resource server with optional configuration options.
```go
server := x402.Newx402ResourceServer(opts ...ResourceServerOption)
```
--------------------------------
### Get Gas Limit Response Example
Source: https://web3.okx.com/onchainos/dev-docs/trade/onchain-gateway-api-gas-limit
This is an example of a successful response from the gas-limit endpoint, showing the estimated gas limit for the requested transaction.
```json
{
"code": "0",
"data": [
{
"gasLimit": "652683"
}
],
"msg": ""
}
```
--------------------------------
### Get Token Developer Info Response Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-memepump-get-token-developer-info
Example of a successful JSON response containing developer launch and holding information for a token.
```json
{
"code": "0",
"msg": "",
"data": {
"devLaunchedInfo": {
"totalToken": "18",
"rugPullCount": "3",
"migratedCount": "11",
"goldenGemCount": "2"
},
"devHoldingInfo": {
"devHoldingPercent": "2.35",
"devAddress": "3kXoZt...q1Re",
"fundingAddress": "Fv8N...tuQ",
"devBalance": "0.064",
"lastFundedTimestamp": "2025-06-26T06:37:39Z"
}
}
}
```
--------------------------------
### Go Server Setup for Dual Payment Methods
Source: https://web3.okx.com/onchainos/dev-docs/payments/methods-onetime
Initializes the Go server using Gin to handle payments via MPP and x402 adapters. Requires environment variables for configuration.
```go
package main
import (
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
mppadapters "github.com/okx/payments/go/mpp/adapters"
"github.com/okx/payments/go/mpp/evm"
"github.com/okx/payments/go/mpp/saclient"
"github.com/okx/payments/go/mpp/server"
pr "github.com/okx/payments/go/paymentrouter"
prgin "github.com/okx/payments/go/paymentrouter/gin"
"github.com/okx/payments/go/x402"
x402adapters "github.com/okx/payments/go/x402/adapters"
x402http "github.com/okx/payments/go/x402/http"
exact "github.com/okx/payments/go/x402/mechanisms/evm/exact/server"
)
// Protocol-agnostic. Runs only after one of the adapters has verified payment.
func generateImg(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"imageUrl": "https://placehold.co/512x512/png?text=AI+Generated",
"prompt": "a sunset over mountains",
})
}
func main() {
payTo := os.Getenv("PAY_TO_ADDRESS")
saClient := saclient.NewOKXSAClient(
os.Getenv("OKX_BASE_URL"),
```
--------------------------------
### Example: Get Candlestick Data
Source: https://web3.okx.com/onchainos/dev-docs/market/market-ai-tools-skills
An example of a natural-language query to retrieve historical candlestick data for a token. The agent maps this to the 'market-candlesticks' skill.
```shell
Show me OKB’s 4-hour candlesticks for the past week.
# Call market-candlesticks
```
--------------------------------
### Net/HTTP Payment Middleware Setup
Source: https://web3.okx.com/onchainos/dev-docs/payments/sdk-go
Demonstrates applying the payment middleware to a standard Go http.Handler, returning a new http.Handler.
```go
import x402nethttp "github.com/okx/payments/go/x402/http/nethttp"
handler := x402nethttp.PaymentMiddleware(routes, server, opts ...MiddlewareOption)(yourHandler)
handler := x402nethttp.X402Payment(Config{ ... })(yourHandler)
handler := x402nethttp.SimpleX402Payment(payTo, price, network, facilitatorURL)(yourHandler)
http.ListenAndServe(":4021", handler)
```
--------------------------------
### Initialize x402 Client
Source: https://web3.okx.com/onchainos/dev-docs/payments/sdk-go
Constructs a new x402 client with optional configuration functions like WithPaymentSelector or WithPolicy.
```go
import x402 "github.com/okx/payments/go/x402"
client := x402.Newx402Client(opts ...ClientOption)
```
--------------------------------
### Get Top KOLs for Token Request Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-social-vibe-top-kols
This snippet shows how to make a GET request to the top-kols API endpoint. It includes example parameters for chain ID, token address, sorting, time frame, and limit. Ensure you include the necessary authentication headers.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/market/social/vibe/top-kols?chainIndex=1&tokenAddress=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2&sortBy=1&timeFrame=1&limit=20' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### Get a Quote for a Token Pair
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-use-swap-quick-start
Retrieve a quote for a token swap before execution. This example shows how to get a quote for USDC to WETH on Base Chain.
```typescript
const quote = await client.dex.getQuote({
chainIndex: '8453', // Base Chain
fromTokenAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
toTokenAddress: '0x4200000000000000000000000000000000000006', // WETH
amount: '1000000', // 1 USDC (in smallest units)
slippagePercent: '0.5' // 0.5%
});
```
--------------------------------
### Install x402 SDK Dependencies
Source: https://web3.okx.com/onchainos/dev-docs/market/how-to-finish-api-payment
Install the necessary Node.js packages for the x402 demo project, including viem, the x402 SDK, and development tools.
```bash
mkdir x402-demo && cd x402-demo
npm init -y
npm install --save-dev @types/node
npm install viem @okxweb3/x402-fetch @okxweb3/x402-evm dotenv ts-node typescript
```
--------------------------------
### Initialize OKXUniversalProvider
Source: https://web3.okx.com/onchainos/dev-docs/sdks/app-connect-aptos-sdk
Create an instance of OKXUniversalProvider to connect to the wallet and manage transactions. Provide your DApp's metadata.
```typescript
import { OKXUniversalProvider } from "@okxconnect/universal-provider";
const okxUniversalProvider = await OKXUniversalProvider.init({
dappMetaData: {
name: "application name",
icon: "application icon url"
},
})
```
--------------------------------
### Get Supported Chains Request Example
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-get-aggregator-supported-chains
Demonstrates how to make a GET request to the supported chains API endpoint with authentication headers and a chain index parameter.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/aggregator/supported/chain?chainIndex=1' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### Example: Get Total Wallet Value
Source: https://web3.okx.com/onchainos/dev-docs/market/market-ai-tools-skills
An example of a natural-language query to calculate the total asset value of a given wallet address. The agent maps this to the 'balance-total-value' skill.
```shell
What is the total asset value of wallet 0xd8dA...?
# Call balance-total-value
```
--------------------------------
### React Quickstart with DEX Widget
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-widget
Basic integration of the OKX Swap Widget in a React application. Handles wallet connection events.
```javascript
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 ;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
```
--------------------------------
### Set Up Environment and Utilities
Source: https://web3.okx.com/onchainos/dev-docs/home/run-your-first-dapp
Imports necessary libraries, defines environment variables for wallet and API access, and sets up utility functions for API authentication. This is the initial setup for interacting with the Trade API.
```typescript
// --------------------- npm package ---------------------
import { Web3 } from 'web3';
import axios from 'axios';
import * as dotenv from 'dotenv';
import CryptoJS from 'crypto-js';
// The URL for the Ethereum node you want to connect to
const web3 = new Web3('https://......com');
// --------------------- environment variable ---------------------
// Load hidden environment variables
dotenv.config();
// Your wallet information - REPLACE WITH YOUR OWN VALUES
const WALLET_ADDRESS: string = process.env.EVM_WALLET_ADDRESS || '0xYourWalletAddress';
const PRIVATE_KEY: string = process.env.EVM_PRIVATE_KEY || 'YourPrivateKey';
// Token addresses for swap on Base Chain
const ETH_ADDRESS: string = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'; // Native ETH
const USDC_ADDRESS: string = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; // USDC on Base
// Chain ID for Base Chain
const chainIndex: string = '8453';
// API URL
const baseUrl: string = 'https://web3.okx.com/api/v6/';
// Amount to swap in smallest unit (0.0005 ETH)
const SWAP_AMOUNT: string = '500000000000000'; // 0.0005 ETH
const SLIPPAGEPERCENT: string = '0.5'; // 0.5% slippagePercent tolerance
// --------------------- util function ---------------------
export function getHeaders(timestamp: string, method: string, requestPath: string, queryString = "") {
// Check https://web3.okx.com/zh-hans/web3/build/docs/waas/rest-authentication for api-key
const apiKey = process.env.OKX_API_KEY;
const secretKey = process.env.OKX_SECRET_KEY;
const apiPassphrase = process.env.OKX_API_PASSPHRASE;
const projectId = process.env.OKX_PROJECT_ID;
if (!apiKey || !secretKey || !apiPassphrase || !projectId) {
throw new Error("Missing required environment variables");
}
const stringToSign = timestamp + method + requestPath + queryString;
return {
"Content-Type": "application/json",
"OK-ACCESS-KEY": apiKey,
"OK-ACCESS-SIGN": CryptoJS.enc.Base64.stringify(
CryptoJS.HmacSHA256(stringToSign, secretKey)
),
"OK-ACCESS-TIMESTAMP": timestamp,
"OK-ACCESS-PASSPHRASE": apiPassphrase,
"OK-ACCESS-PROJECT": projectId,
};
};
```
--------------------------------
### Get DEX Swap Quote
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-ai-tools-skills
Request a quote for swapping one token for another on a specific chain. This example shows how to get USDC for OKB on X-layer, invoking the 'dex-quote' skill.
```shell
How much USDC will I get for 1 OKB on X-layer?
# Call dex-quote
```
--------------------------------
### Get Product Details API Response Example
Source: https://web3.okx.com/onchainos/dev-docs/wallet/defi-product-detail
This JSON object represents a successful response from the GET /api/v6/defi/product/detail endpoint, detailing a specific investment product like Aave V3 USDC.
```json
{
"code": 0,
"msg": "",
"data": {
"investmentId": 9502,
"investmentName": "USDC",
"platformName": "Aave V3",
"platformLogo": "https://static.coinall.ltd/cdn/web3/protocol/logo/aave-v3.png/type=png_350_0?v=1774409445039",
"investType": 1,
"tvl": "3423591587.48413",
"rate": "0.02140",
"rateType": 0,
"rateTypeDesc": "APY",
"network": "Ethereum",
"networkLogo": "https://static.coinall.ltd/cdn/wallet/logo/ETH-20220328.png",
"underlyingToken": [
{
"tokenSymbol": "USDC",
"tokenLogo": "https://static.coinall.ltd/cdn/wallet/logo/USDC.png",
"tokenAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"isBaseToken": false
}
],
"rateDetails": [
{
"tokenAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"tokenSymbol": "USDC",
"rate": "0.0214",
"title": "Supply APY",
"type": 1
}
],
"aboutToken": [
{
"tokenSymbol": "USDC",
"tokenLogo": "https://static.coinall.ltd/cdn/wallet/logo/USDC.png",
"tokenAddress": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
"isBaseToken": false,
"marketCap": "55468602892.82830569743700036",
"price": "0.99988"
}
],
"isSupportClaim": false,
"isInvestable": true,
"isSupportRedeem": true,
"analysisPlatformId": "10",
"chainIndex": "1",
"detailPath": "aave-v3-ethereum-usdc-9502",
"platformUrl": "https://app.aave.com",
"utilizationRate": "0.755200",
"hasRateChart": true,
"hasTvlChart": false
}
}
```
--------------------------------
### Install OKX Connect UI and Solana Provider
Source: https://web3.okx.com/onchainos/dev-docs/sdks/app-connect-solana-ui
Install the necessary packages for OKX Connect UI and the Solana provider using npm.
```bash
npm install @okxconnect/ui
npm install @okxconnect/solana-provider
```
--------------------------------
### Install OKX Connect UI via npm
Source: https://web3.okx.com/onchainos/dev-docs/sdks/app-connect-evm-ui
Install the OKX Connect UI SDK using npm. Ensure you have Node.js and npm installed.
```bash
npm install @okxconnect/ui
```
--------------------------------
### Get Similar Tokens Response Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-memepump-get-similar-tokens
Example JSON response for the similar tokens request, showing a list of similar tokens with their contract addresses, symbols, logos, market caps, and transaction timestamps.
```json
{
"code": "0",
"msg": "",
"data": {
"similarToken": [
{
"tokenContractAddress": "8Hd92...xYp1",
"tokenSymbol": "TETAX",
"tokenLogo": "https://static.okx.com/cdn/assets/imgs/tetax.png",
"marketCapUsd": "245800.32",
"lastTxTimestamp": "2025-03-08T12:45:21Z",
"createdTimestamp": "2025-03-01T08:00:00Z"
},
{
"tokenContractAddress": "9Ks81...LpQ9",
"tokenSymbol": "TETAN",
"tokenLogo": "https://static.okx.com/cdn/assets/imgs/tetan.png",
"marketCapUsd": "158920.00",
"lastTxTimestamp": "2025-03-08T12:40:10Z",
"createdTimestamp": "2025-02-28T15:12:00Z"
}
]
}
}
```
--------------------------------
### Get Token Vibe Timeline Request
Source: https://web3.okx.com/onchainos/dev-docs/market/market-social-vibe-timeline
This example demonstrates how to make a GET request to the API to retrieve the vibe timeline for a token. Ensure you include your API key, signature, passphrase, and timestamp in the headers.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/market/social/vibe/timeline?chainIndex=1&tokenAddress=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2&timeFrame=1' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### Install OKX DEX SDK
Source: https://web3.okx.com/onchainos/dev-docs/trade/dex-sdk-introduction
Install the OKX DEX SDK using npm, yarn, or pnpm.
```bash
npm install @okx-dex/okx-dex-sdk
# or
yarn add @okx-dex/okx-dex-sdk
# or
pnpm add @okx-dex/okx-dex-sdk
```
--------------------------------
### Get Total Value by Address Request Example
Source: https://web3.okx.com/onchainos/dev-docs/market/balance-total-value
This snippet shows how to make a GET request to retrieve the total value of assets for a specific address and chains. Ensure you include the necessary authentication headers.
```shell
curl --location --request GET 'https://web3.okx.com/api/v6/dex/balance/total-value-by-address?address=0x0b32aa5c1e71715206fe29b7badb21ad95f272c0&chains=1&assetType=0' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z'
```
--------------------------------
### Go Exact Payment Server Setup
Source: https://web3.okx.com/onchainos/dev-docs/payments/methods-onetime
Implement an HTTP server in Go using the Gin framework to manage 'exact' payments. This involves setting up the OKX Facilitator Client, defining payment routes, and integrating the X402 payment middleware.
```go
package main
import (
"net/http"
"os"
"time"
ginfw "github.com/gin-gonic/gin"
x402http "github.com/okx/payments/go/x402"
ginmw "github.com/okx/payments/go/x402/http/gin"
evm "github.com/okx/payments/go/x402/mechanisms/evm/exact/server"
)
func main() {
facilitator, _ := x402http.NewOKXFacilitatorClient(&x402http.OKXFacilitatorConfig{
Auth: x402http.OKXAuthConfig{
APIKey: os.Getenv("OKX_API_KEY"),
SecretKey: os.Getenv("OKX_SECRET_KEY"),
Passphrase: os.Getenv("OKX_PASSPHRASE"),
},
})
routes := x402http.RoutesConfig{
"GET /api/premium": {
Accepts: x402http.PaymentOptions{
{
Scheme: "exact",
Price: "$0.10",
Network: "eip155:196",
PayTo: "0xYourSellerWallet",
SyncSettle: true,
},
},
Description: "Premium API",
MimeType: "application/json",
},
}
r := ginfw.Default()
r.Use(ginmw.X402Payment(ginmw.Config{
Routes: routes,
Facilitator: facilitator,
Schemes: []ginmw.SchemeConfig{
{Network: "eip155:196", Server: evm.NewExactEvmScheme()},
},
Timeout: 30 * time.Second,
}))
r.GET("/api/premium", func(c *ginfw.Context) {
c.JSON(http.StatusOK, ginfw.H{"data": "premium content"})
})
r.Run(":4000")
}
```
--------------------------------
### Initialize OKXUniversalProvider
Source: https://web3.okx.com/onchainos/dev-docs/sdks/app-connect-aptos-sdk
Initializes the OKXUniversalProvider with DApp metadata. This is the first step before connecting to a wallet.
```APIDOC
## Initialize OKXUniversalProvider
### Description
Initializes the OKXUniversalProvider with DApp metadata. This object is used to connect to the wallet, send transactions, and more.
### Method
`OKXUniversalProvider.init(params)`
### Parameters
#### Request Parameters
- **dappMetaData** (object) - Required - Metadata for the DApp.
- **name** (string) - Required - The name of the app.
- **icon** (string) - Required - URL of the application icon (e.g., PNG, ICO, 180x180px).
### Return Value
- `OKXUniversalProvider` - An instance of the provider.
### Example
```typescript
import { OKXUniversalProvider } from "@okxconnect/universal-provider";
const okxUniversalProvider = await OKXUniversalProvider.init({
dappMetaData: {
name: "application name",
icon: "application icon url"
},
})
```
```
--------------------------------
### Get Gas Limit Request Example
Source: https://web3.okx.com/onchainos/dev-docs/trade/onchain-gateway-api-gas-limit
This example demonstrates how to make a POST request to the gas-limit endpoint to retrieve an estimated gas limit. Ensure you include the necessary authentication headers and provide the correct transaction details.
```shell
curl --location --request POST 'https://web3.okx.com/api/v6/dex/pre-transaction/gas-limit' \
--header 'Content-Type: application/json' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z' \
--data-raw '{
"fromAddress": "0x383c8208b4711256753b70729ba0cf0cda55efad",
"toAddress": "0x4ad041bbc6fa102394773c6d8f6d634320773af4",
"txAmount": "31600000000000000",
"chainIndex": "1",
"extJson": {
"inputData":"041bbc6fa102394773c6d8f6d634320773af4"
}
}'
```
--------------------------------
### Node.js MPP Pay-as-you-go Server Setup
Source: https://web3.okx.com/onchainos/dev-docs/payments/pay-as-you-go
Sets up an HTTP server using Node.js and the MPP library for pay-as-you-go services. Requires environment variables for API keys and private keys. Use a WalletClient or KMS in production.
```json
{
"type": "module",
"dependencies": {
"@okxweb3/mpp": "^0.1.0",
"viem": "^2.21.0"
}
}
```
```typescript
// server.ts
// Run: npx tsx --env-file=.env server.ts
import * as http from "node:http";
import { privateKeyToAccount } from "viem/accounts";
import { Mppx } from "@okxweb3/mpp";
import { session } from "@okxweb3/mpp/evm/server";
import { SaApiClient } from "@okxweb3/mpp/evm";
const UNIT_PRICE_BASE_UNITS = "100"; // 0.0001 of a 6-decimal token
const UNIT_TYPE = "request";
const SUGGESTED_DEPOSIT = "10000"; // 100× unit price
const saClient = new SaApiClient({
apiKey: process.env.OKX_API_KEY!,
secretKey: process.env.OKX_SECRET_KEY!,
passphrase: process.env.OKX_PASSPHRASE!,
});
// viem LocalAccount — replace with WalletClient / KMS / HSM signer in production.
// The session method fast-fails on startup if signer.address !== expected payee.
const sellerSigner = privateKeyToAccount(
process.env.MPP_MERCHANT_PRIVATE_KEY! as `0x${string}`,
);
// Default in-memory store. Pass `store: ...` for SQLite / Redis / Postgres.
const mppx = Mppx.create({
methods: [session({ saClient, signer: sellerSigner })],
realm: "test realm",
secretKey: process.env.MPP_SECRET_KEY!,
});
// Per-route session config. Charged per call; voucher accumulates;
// settle batches on /session/manage close action.
const SESSION = {
amount: UNIT_PRICE_BASE_UNITS,
currency: "0x...adb21711", // currency
recipient: "0x...378211", // receipt
description: "Pay-per-use API",
unitType: UNIT_TYPE,
suggestedDeposit: SUGGESTED_DEPOSIT,
methodDetails: {
chainId: 196, // X Layer
escrowContract: process.env.MPP_ESCROW!, // 40-hex escrow address
feePayer: true,
minVoucherDelta: "0",
},
} as const;
// Routes by `payload.action`: open / voucher / topUp / close.
// mppx.session(...)(request) handles all four uniformly:
// - 402 → challenge response
// - 200 → action-specific result; withReceipt() attaches Payment-Receipt
async function manage(request: Request): Promise {
const result = await mppx.session(SESSION)(request);
if (result.status === 402) return result.challenge;
// open / topUp / close → empty 204; voucher → resource body.
return result.withReceipt(Response.json({ status: "ok" }));
}
http.createServer(async (req, res) => {
const url = `http://${req.headers.host ?? "localhost:4023"}${req.url}`;
const webReq = new Request(url, {
method: req.method,
headers: new Headers(req.headers as Record),
});
const path = new URL(url).pathname;
const webRes =
path === "/session/manage"
? await manage(webReq)
: new Response("not found", { status: 404 });
res.statusCode = webRes.status;
webRes.headers.forEach((v, k) => res.setHeader(k, v));
res.end(await webRes.text());
}).listen(4023);
```
--------------------------------
### Get Latest Signal List Request Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-signal-list
This example demonstrates how to make a POST request to the /api/v6/dex/market/signal/list endpoint to retrieve token signal data. It includes common headers and a JSON payload with various filtering parameters.
```shell
curl --location --request POST 'https://web3.okx.com/api/v6/dex/market/signal/list' \
--header 'Content-Type: application/json' \
--header 'OK-ACCESS-KEY: 37c541a1-****-****-****-10fe7a038418' \
--header 'OK-ACCESS-SIGN: leaV********3uw=' \
--header 'OK-ACCESS-PASSPHRASE: 1****6' \
--header 'OK-ACCESS-TIMESTAMP: 2023-10-18T12:21:41.274Z' \
--data-raw '[
{
"chainIndex": "501",
"walletType": "1,2,3",
"minAmountUsd": "1000",
"maxAmountUsd": "500000",
"minAddressCount": "2",
"maxAddressCount": "50",
"tokenAddress": "",
"minMarketCapUsd": "168564",
"maxMarketCapUsd": "",
"minLiquidityUsd": "333",
"maxLiquidityUsd": ""
}
]'
```
--------------------------------
### Smart Money Leaderboard List Response Example
Source: https://web3.okx.com/onchainos/dev-docs/market/market-signal-leaderboard-list
This is an example of a successful response (HTTP 200) for the Get Smart Money Leaderboard List request. It includes wallet details, PnL, win rate, and top tokens.
```json
{
"code": "0",
"data": [
{
"walletAddress": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
"realizedPnlUsd": "125430.56",
"realizedPnlPercent": "312.45",
"winRatePercent": "68.5",
"avgBuyValueUsd": "2340.00",
"topPnlTokenList": [
{
"tokenContractAddress": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"tokenSymbol": "USDC",
"tokenPnlUsd": "45230.12",
"tokenPnlPercent": "156.78"
},
{
"tokenContractAddress": "So11111111111111111111111111111111111111112",
"tokenSymbol": "SOL",
"tokenPnlUsd": "38120.00",
"tokenPnlPercent": "98.34"
},
{
"tokenContractAddress": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",
"tokenSymbol": "BONK",
"tokenPnlUsd": "20450.88",
"tokenPnlPercent": "204.60"
}
],
"txVolume": "890234.50",
"txs": "342",
"lastActiveTimestamp": "1697630501000"
}
],
"msg": ""
}
```
--------------------------------
### Initialize ExactSvmScheme (client)
Source: https://web3.okx.com/onchainos/dev-docs/payments/sdk-go
Create an ExactSvmScheme client signer using a private key. Requires SVM signers and client packages.
```go
import (
svmsigners "github.com/okx/payments/go/x402/mechanisms/svm/signers"
svmclient "github.com/okx/payments/go/x402/mechanisms/svm/exact/client"
)
signer, err := svmsigners.NewClientSignerFromPrivateKey(solanaPrivateKey)
scheme := svmclient.NewExactSvmScheme(signer, config)
```