### Rust Axum Service Setup Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/service-seller-sdk Set up a Rust Axum web server with payment middleware. This example demonstrates defining routes, payment configurations, and starting the server. ```rust use axum::routing::get; use axum::Json; use axum::Router; use serde_json::{json, Value}; use std::collections::HashMap; use okx_payments::middleware::payment_middleware; #[tokio::main] async fn main() { let mut routes: HashMap = HashMap::new(); routes.insert("GET /api/joke".to_string(), okx_payments::service::Route { price: "$0.001".into(), network: "eip155:196".into(), pay_to: "0x1234567890abcdef1234567890abcdef12345678".into(), max_timeout_seconds: None, extra: None, }); let server = okx_payments::service::Server::new(routes.clone()); let app = Router::new() .route("/health", get(health)) .route("/api/joke", get(joke)) .layer(payment_middleware(routes, server)); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } async fn health() -> Json { Json(json!({ "status": "ok" })) } async fn joke() -> Json { Json(json!({ "joke": "Why do programmers always confuse Halloween and Christmas? Because Oct 31 = Dec 25", "price": "$0.001" })) } ``` -------------------------------- ### Go Exact Payment Setup Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/methods-onetime Install the Go SDK and configure the Gin server for 'exact' payments. Ensure OKX API keys are set as environment variables. ```bash go get github.com/okx/payments/go/x402 ``` ```go package main import ( "net/http" "os" "time" ginfw "github.com/gin-gonic/gin" x402http "github.com/okx/payments/go/x402/http" 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": "付费资源内容"}) }) r.Run(":4000") } ``` -------------------------------- ### Install and Initialize OKXUniversalProvider Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/sdks/app-connect-cosmos-sdk Instructions for installing the SDK via npm and initializing the OKXUniversalProvider with DApp metadata. ```APIDOC ## Install SDK ```bash npm install @okxconnect/universal-provider ``` ## Initialize Provider To initialize the provider, create an instance with your DApp's metadata. ### Method `OKXUniversalProvider.init(options)` ### Parameters - **options** (object) - Required - **dappMetaData** (object) - Required - **name** (string) - Required - The name of your application. - **icon** (string) - Required - The URL of your application's icon. Recommended format is a 180x180px PNG. ### Returns - `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" }, }); ``` ``` -------------------------------- ### Installation and Initialization Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/sdks/app-connect-sui-ui Install the necessary packages and initialize the OKXUniversalConnectUI with your DApp's metadata, actions, and UI preferences. ```APIDOC ## Installation and Initialization Ensure your OKX App is updated to version 6.90.1 or later. Install the OKX Connect UI and Sui provider using npm: ```bash npm install @okxconnect/ui npm install @okxconnect/sui-provider ``` Initialize the UI with the following method: `OKXUniversalConnectUI.init(dappMetaData, actionsConfiguration, uiPreferences, language)` ### Parameters * **dappMetaData** - object * **name** - string: The name of your application. * **icon** - string: URL of your application's icon (PNG, ICO format, 180x180px recommended). * **actionsConfiguration** - object * **modals** - ('before' | 'success' | 'error')[] | 'all': Display modes for transaction reminder interfaces. Defaults to 'before'. * **returnStrategy** - string: 'none' | `${string}://${string}`. Specifies the deep link return strategy for app wallets (e.g., 'tg://resolve' for Telegram). * **uiPreferences** - object * **theme** - Theme: Can be `THEME.DARK`, `THEME.LIGHT`, or `"SYSTEM"`. * **language** - string: Defaults to 'en_US'. Supported locales include 'en_US', 'ru_RU', 'zh_CN', 'ar_AE', 'cs_CZ', 'de_DE', 'es_ES', 'es_LAT', 'fr_FR', 'id_ID', 'it_IT', 'nl_NL', 'pl_PL', 'pt_BR', 'pt_PT', 'ro_RO', 'tr_TR', 'uk_UA', 'vi_VN'. ### Returns * **OKXUniversalConnectUI** - object ### Example ```typescript import { OKXUniversalConnectUI } from "@okxconnect/ui"; const okxUniversalConnectUI = await OKXUniversalConnectUI.init({ dappMetaData: { icon: "https://static.okx.com/cdn/assets/imgs/247/58E63FEA47A2B7D7.png", name: "OKX Connect Demo" }, actionsConfiguration: { returnStrategy: 'tg://resolve', modals:"all", tmaReturnUrl:'back' }, language: "en_US", uiPreferences: { theme: THEME.LIGHT }, }); // Listen for account changes okxUniversalConnectUI.on("accountChanged", (session) => { if (session){ console.log(`accountChanged `, JSON.stringify(session)); } }); ``` ``` -------------------------------- ### DEX Swap Instruction Request Example Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-solana-swap-instruction This example demonstrates how to make a GET request to the DEX aggregator swap-instruction endpoint. Ensure you replace placeholder values with your actual API keys and parameters. ```shell curl --location --request GET 'https://web3.okx.com/api/v6/dex/aggregator/swap-instruction??chainIndex=501&userWalletAddress=J5CBzXpcYn6WR2JBah8zU4Yxct985CAFGwXRcFaX2pbS&autoSlippage=true&toTokenReferrerWalletAddress=A9bBCSy9y4vggKgcT7jkUiN77Q95soLbLYhCcbWUpy3g&amount=100000&fromTokenAddress=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&toTokenAddress=11111111111111111111111111111111&feePercent=0.875&slippagePercent=0.05&useTokenLedger=true \ --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' ``` -------------------------------- ### Installation and Import Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/sdk-nodejs Instructions on how to install the necessary packages and import modules for the Node.js SDK. ```bash npm install @okxweb3/mpp viem ``` ```typescript // Top-level: mppx runtime + namespaces import { Mppx, Errors } from '@okxweb3/mpp' // EVM common: SA API client, EIP-712 tools import { SaApiClient, verifyVoucher, buildSettleAuth } from '@okxweb3/mpp/evm' // EVM server factory import { charge, session } from '@okxweb3/mpp/evm/server' ``` -------------------------------- ### Node.js Exact Payment Setup Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/methods-onetime Install dependencies and set up the Express server for 'exact' payments. Ensure OKX API keys are configured in environment variables. ```bash npm install express @okxweb3/x402-express @okxweb3/x402-core @okxweb3/x402-evm npm install -D typescript tsx @types/express @types/node ``` ```typescript import express from "express"; import { paymentMiddleware, x402ResourceServer, } from "@okxweb3/x402-express"; import { ExactEvmScheme } from "@okxweb3/x402-evm/exact/server"; import { OKXFacilitatorClient } from "@okxweb3/x402-core"; const app = express(); const NETWORK = "eip155:196"; const PAY_TO = process.env.PAY_TO_ADDRESS || "0xYourSellerWallet"; const facilitatorClient = new OKXFacilitatorClient({ apiKey: "OKX_API_KEY", secretKey: "OKX_SECRET_KEY", passphrase: "OKX_PASSPHRASE", }); const resourceServer = new x402ResourceServer(facilitatorClient); resourceServer.register(NETWORK, new ExactEvmScheme()); app.use( paymentMiddleware( { "GET /api/premium": { accepts: [ { scheme: "exact", network: NETWORK, payTo: PAY_TO, price: "$0.10", syncSettle: true, // 同步结算:等链上确认 }, ], description: "Premium API", mimeType: "application/json", }, }, resourceServer, ), ); app.get("/api/premium", (_req, res) => { res.json({ data: "付费资源内容" }); }); app.listen(4000, () => { console.log("[Seller] listening at http://localhost:4000"); }); ``` -------------------------------- ### Install OKX DEX SDK Source: https://web3.okx.com/zh-hans/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 ``` -------------------------------- ### SDK Installation Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/sdks/app-connect-ton-sdk Instructions for installing the OKX Connect TON SDK using either a CDN link or npm. ```APIDOC ## Installation ### Via CDN Add the following script tag to your HTML file. You can replace `latest` with a specific version number (e.g., `1.6.1`). `` After inclusion, `OKXTonConnectSDK` will be available as a global object. ```javascript const connector = new OKXTonConnectSDK.OKXTonConnect(); ``` ### Via npm ```bash npm install @okxconnect/tonsdk ``` ``` -------------------------------- ### Install Fetch Package Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/sdk-nodejs Install the necessary packages for using the Fetch API with the OKX Web3 payment SDK. ```bash npm install @okxweb3/x402-fetch @okxweb3/x402-evm @okxweb3/x402-core ``` -------------------------------- ### Create Project and Install Dependencies Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/market/how-to-finish-api-payment Set up a new project directory and install required npm packages including viem, @okxweb3/x402-fetch, @okxweb3/x402-evm, dotenv, and ts-node. ```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 ``` -------------------------------- ### Install Dependencies for x402 Demo Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/market/how-to-finish-api-payment Set up a new project directory, initialize npm, and install necessary development and runtime dependencies for the x402 demo, including viem, @okxweb3/x402-fetch, @okxweb3/x402-evm, dotenv, ts-node, and typescript. ```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 ``` -------------------------------- ### Get Settle Status Request Example - GET /api/v6/pay/x402/settle/status Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/api-http-onetime Example cURL request to query the settlement status of a transaction using its txHash. ```bash curl --location --request GET 'https://web3.okx.com/api/v6/pay/x402/settle/status?txHash=0x4f46ed8eac92ddbccfb56a88ff827db3616c7beb191adabbeeded901340bd7d5' \ --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 Liquidity Request Example Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-get-liquidity This example demonstrates how to make a GET request to the /api/v6/dex/aggregator/get-liquidity endpoint to fetch liquidity pool information. 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' ``` -------------------------------- ### Example Response Parameters Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-get-liquidity This snippet shows an example of the response parameters for getting liquidity data, including a list of DEX protocols with their IDs, logos, and names. ```json { "data": [ { "id": "522", "logo": "https://static.okx.com/cdn/web3/dex/logo/Fluid_Lite.png", "name": "Fluid Lite" }, { "id": "523", "logo": "https://static.okx.com/cdn/web3/dex/logo/1010_Trading.png", "name": "1010 Trading" } ], "msg": "" } ``` -------------------------------- ### Market Token Cluster Partial Holding Example Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/market/market-token-cluster-list A partial example showing the start of a market token cluster response, focusing on holding amount, value, and percentage. ```json "holdingAmount": "1046626.6", ``` -------------------------------- ### Install OKX Connect TON UI SDK Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/sdks/app-connect-ton-ui Install the SDK using npm. This is the first step before initializing the UI. ```bash npm install @okxconnect/ui ``` -------------------------------- ### Get Quote Response Example Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-get-quote This JSON object represents a successful response from the Get Quote API, detailing the optimal swap route, token information, and estimated transaction parameters. ```json { "code": "0", "data": [ { "dexProtocol": { "dexName": "Uniswap V3", "percent": "99" }, "fromToken": { "decimal": "18", "isHoneyPot": false, "taxRate": "0", "tokenContractAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "tokenSymbol": "UNICHAIN_ETH", "tokenUnitPrice": "4191.043356462183138854" }, "fromTokenIndex": "3", "toToken": { "decimal": "6", "isHoneyPot": false, "taxRate": "0", "tokenContractAddress": "0x078d782b760474a361dda0af3839290b0ef57ad6", "tokenSymbol": "USDC", "tokenUnitPrice": "0.999692348812448693" }, "toTokenIndex": "4" }, { "dexProtocol": { "dexName": "Uniswap V4", "percent": "1" }, "fromToken": { "decimal": "6", "isHoneyPot": false, "taxRate": "0", "tokenContractAddress": "0x9151434b16b9763660705744891fa906f660ecc5", "tokenSymbol": "USDT", "tokenUnitPrice": "1.000313193103130296" }, "fromTokenIndex": "3", "toToken": { "decimal": "6", "isHoneyPot": false, "taxRate": "0", "tokenContractAddress": "0x078d782b760474a361dda0af3839290b0ef57ad6", "tokenSymbol": "USDC", "tokenUnitPrice": "0.999692348812448693" }, "toTokenIndex": "4" } ], "estimateGasFee": "1002000", "fromToken": { "decimal": "18", "isHoneyPot": false, "taxRate": "0", "tokenContractAddress": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "tokenSymbol": "UNICHAIN_ETH", "tokenUnitPrice": "4191.043356462183138854" }, "fromTokenAmount": "10000000000000000000000", "priceImpactPercent": "-67.53", "router": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee--0x927b51f251480a681271180da4de28d44ec4afb8--0x0555e30da8f98308edb960aa94c0db47230d2b9c--0x9151434b16b9763660705744891fa906f660ecc5--0x078d782b760474a361dda0af3839290b0ef57ad6", "swapMode": "exactIn", "toToken": { "decimal": "6", "isHoneyPot": false, "taxRate": "0", "tokenContractAddress": "0x078d782b760474a361dda0af3839290b0ef57ad6", "tokenSymbol": "USDC", "tokenUnitPrice": "0.999692348812448693" }, "toTokenAmount": "13614286937853", "tradeFee": "0.00001607688116316" } ``` -------------------------------- ### Install and Initialize OKX Wallet SDK Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/sdks/app-connect-starknet-sdk Install the SDK using npm and initialize the provider with your DApp's metadata. ```APIDOC ## Installation ```bash npm install @okxconnect/universal-provider ``` ## Initialization Initialize the provider with your DApp's metadata. ### Request Parameters * `dappMetaData` - object * `name` - string: The name of your application. * `icon` - string: The URL of your application's icon. Recommended format is a 180x180 PNG. ### Return Value * `OKXUniversalProvider` ### Example ```typescript import { OKXUniversalProvider } from "@okxconnect/universal-provider"; const okxUniversalProvider = await OKXUniversalProvider.init({ dappMetaData: { name: "application name", icon: "application icon url" }, }) ``` ``` -------------------------------- ### Set Up Environment Variables Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-use-swap-quick-start Configure your environment by creating a .env file with your OKX API credentials and EVM wallet information. Ensure all required fields are populated. ```bash # OKX API Credentials OKX_API_KEY=your_api_key OKX_SECRET_KEY=your_secret_key OKX_API_PASSPHRASE=your_passphrase # EVM Configuration EVM_RPC_URL=your_evm_rpc_url EVM_WALLET_ADDRESS=your_evm_wallet_address EVM_PRIVATE_KEY=your_evm_private_key ``` -------------------------------- ### Environment Setup for OKX DEX SDK Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-sdk-introduction Configure your API credentials and wallet information by creating a .env file. ```bash # OKX API Credentials OKX_API_KEY=your_api_key OKX_SECRET_KEY=your_secret_key OKX_API_PASSPHRASE=your_passphrase OKX_PROJECT_ID=your_project_id # Solana Configuration SOLANA_RPC_URL=your_solana_rpc_url SOLANA_WALLET_ADDRESS=your_solana_wallet_address SOLANA_PRIVATE_KEY=your_solana_private_key # EVM Configuration EVM_RPC_URL=your_evm_rpc_url EVM_PRIVATE_KEY=your_evm_private_key ``` -------------------------------- ### Get Transaction Detail by TxHash Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/market/tx-history-specific-transaction-detail-by-txhash This example demonstrates how to retrieve transaction details using the `GET` method with query parameters for transaction hash and chain index. It also includes necessary headers for authentication and timestamp. ```APIDOC ## GET /api/v6/dex/post-transaction/transaction-detail-by-txhash ### Description Retrieves the details of a specific transaction identified by its transaction hash. ### Method GET ### Endpoint /api/v6/dex/post-transaction/transaction-detail-by-txhash ### Query Parameters - **txHash** (string) - Required - The hash of the transaction to query. - **chainIndex** (string) - Required - The index of the blockchain. ### Request Headers - **Content-Type**: application/json - **OK-ACCESS-KEY**: Your API key. - **OK-ACCESS-SIGN**: The signature for the request. - **OK-ACCESS-PASSPHRASE**: Your API passphrase. - **OK-ACCESS-TIMESTAMP**: The timestamp of the request. ### Request Example ```shell curl --location --request GET 'https://web3.okx.com/api/v6/dex/post-transaction/transaction-detail-by-txhash?txHash=0x9ab8ccccc9f778ea91ce4c0f15517672c4bd06d166e830da41ba552e744d29a5&chainIndex=42161' \ --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' ``` ### Response #### Success Response (200) - **code** (string) - Response code. - **msg** (string) - Response message. - **data** (array) - An array containing transaction details. - **chainIndex** (string) - The index of the blockchain. - **height** (string) - The block height. - **txTime** (string) - The transaction timestamp. - **txhash** (string) - The transaction hash. - **gasLimit** (string) - The gas limit for the transaction. - **gasUsed** (string) - The gas used by the transaction. - **gasPrice** (string) - The gas price. - **txFee** (string) - The transaction fee. - **nonce** (string) - The transaction nonce. - **symbol** (string) - The symbol of the token involved. - **amount** (string) - The amount of the token involved. - **txStatus** (string) - The status of the transaction (e.g., 'success'). - **methodId** (string) - The method ID of the transaction. - **l1OriginHash** (string) - The L1 origin hash. - **fromDetails** (array) - Details of the sender. - **address** (string) - The sender's address. - **vinIndex** (string) - The input index. - **preVoutIndex** (string) - The previous output index. - **txHash** (string) - The transaction hash. - **isContract** (boolean) - Whether the sender is a contract. - **amount** (string) - The amount sent. - **toDetails** (array) - Details of the receiver. - **address** (string) - The receiver's address. - **voutIndex** (string) - The output index. - **isContract** (boolean) - Whether the receiver is a contract. - **amount** (string) - The amount received. - **internalTransactionDetails** (array) - Details of internal transactions. - **from** (string) - The sender address of the internal transaction. - **to** (string) - The receiver address of the internal transaction. - **isFromContract** (boolean) - Whether the sender is a contract. - **isToContract** (boolean) - Whether the receiver is a contract. - **amount** (string) - The amount transferred in the internal transaction. - **state** (string) - The state of the internal transaction. - **tokenTransferDetails** (array) - Details of token transfers. #### Response Example ```json { "code": "0", "msg": "success", "data": [ { "chainIndex": "42161", "height": "245222398", "txTime": "1724253417000", "txhash": "0x9ab8ccccc9f778ea91ce4c0f15517672c4bd06d166e830da41ba552e744d29a5", "gasLimit": "2000000", "gasUsed": "2000000", "gasPrice": "10000000", "txFee": "", "nonce": "0", "symbol": "ETH", "amount": "0", "txStatus": "success", "methodId": "0xc9f95d32", "l1OriginHash": "0xa6a87ba2f18cc32bbae8f3b2253a29a9617ed1eb0940d80443f6e3bf9873dbad", "fromDetails": [ { "address": "0xd297fa914353c44b2e33ebe05f21846f1048cfeb", "vinIndex": "", "preVoutIndex": "", "txHash": "", "isContract": false, "amount": "" } ], "toDetails": [ { "address": "0x000000000000000000000000000000000000006e", "voutIndex": "", "isContract": false, "amount": "" } ], "internalTransactionDetails": [ { "from": "0x0000000000000000000000000000000000000000", "to": "0xd297fa914353c44b2e33ebe05f21846f1048cfeb", "isFromContract": false, "isToContract": false, "amount": "0.02", "state": "success" }, { "from": "0xd297fa914353c44b2e33ebe05f21846f1048cfeb", "to": "0x428ab2ba90eba0a4be7af34c9ac451ab061ac010", "isFromContract": false, "isToContract": false, "amount": "0.00998", "state": "success" }, { "from": "0xd297fa914353c44b2e33ebe05f21846f1048cfeb", "to": "0x428ab2ba90eba0a4be7af34c9ac451ab061ac010", "isFromContract": false, "isToContract": false, "amount": "0.009977946366846017", "state": "success" } ], "tokenTransferDetails": [] } ] } ``` ``` -------------------------------- ### Initialize x402 Client Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/sdk-go Constructs a new x402 client with optional configuration options. Use ClientOption functions like WithPaymentSelector or WithPolicy to customize behavior. ```go import x402 "github.com/okx/payments/go/x402" client := x402.Newx402Client(opts ...ClientOption) ``` -------------------------------- ### Get Settle Status Response Example - Transaction Not Found Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/api-http-onetime JSON response when the queried transaction hash is not found. ```json { "code": "0", "msg": "success", "data": { "success": false, "errorReason": "not_found", "errorMessage": "Transaction not found for txHash: 0xabc123...", "payer": null, "transaction": null, "network": null, "status": null } } ``` -------------------------------- ### Install Go SDK Dependency Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/service-seller-sdk Add the Go SDK dependency to your project using the go get command. ```bash go get github.com/okx/payments/go/x402 ``` -------------------------------- ### Initialize x402ResourceServer in Go Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/sdk-go Constructs a new x402ResourceServer with optional configurations. Use options like WithFacilitatorClient, WithSchemeServer, and WithCacheTTL. ```go server := x402.Newx402ResourceServer(opts ...ResourceServerOption) ``` -------------------------------- ### Query Current Price Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/market/market-ai-tools-mcp-server Example natural language query to get the current price of a token. This invokes the index-current-price tool. ```shell OKB 现在多少钱? # 调用 index-current-price ``` -------------------------------- ### Query Current Token Price Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/market/market-ai-tools-skills Use this skill to get the current price of a specified token. Example query: 'OKB 现在多少钱?'. ```shell OKB 现在多少钱? # 调用 index-current-price ``` -------------------------------- ### initialize() Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/sdk-nodejs Initializes the server by fetching supported kinds from facilitators. Should be called once at startup. ```APIDOC ## initialize() ### Description Initializes the server by fetching supported kinds from facilitators. Should be called once at startup. ### Method `await server.initialize()` ``` -------------------------------- ### Javascript API Request Examples Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/home/api-access-and-usage Use these functions to make authenticated GET and POST requests to the API. Ensure your API credentials are correctly configured. ```javascript const https = require('https'); const crypto = require('crypto'); const querystring = require('querystring'); // 定义 API 凭证 const api_config = { "api_key": '', "secret_key": '', "passphrase": '', }; function preHash(timestamp, method, request_path, params) { // 根据字符串和参数创建预签名 let query_string = ''; if (method === 'GET' && params) { query_string = '?' + querystring.stringify(params); } if (method === 'POST' && params) { query_string = JSON.stringify(params); } return timestamp + method + request_path + query_string; } function sign(message, secret_key) { // 使用 HMAC-SHA256 对预签名字符串进行签名 const hmac = crypto.createHmac('sha256', secret_key); hmac.update(message); return hmac.digest('base64'); } function createSignature(method, request_path, params) { // 获取 ISO 8601 格式时间戳 const timestamp = new Date().toISOString().slice(0, -5) + 'Z'; // 生成签名 const message = preHash(timestamp, method, request_path, params); const signature = sign(message, api_config['secret_key']); return { signature, timestamp }; } function sendGetRequest(request_path, params) { // 生成签名 const { signature, timestamp } = createSignature("GET", request_path, params); // 生成请求头 const headers = { 'OK-ACCESS-KEY': api_config['api_key'], 'OK-ACCESS-SIGN': signature, 'OK-ACCESS-TIMESTAMP': timestamp, 'OK-ACCESS-PASSPHRASE': api_config['passphrase'], }; const options = { hostname: 'web3.okx.com', path: request_path + (params ? `?${querystring.stringify(params)}` : ''), method: 'GET', headers: headers }; const req = https.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log(data); }); }); req.end(); } function sendPostRequest(request_path, params) { // 生成签名 const { signature, timestamp } = createSignature("POST", request_path, params); // 生成请求头 const headers = { 'OK-ACCESS-KEY': api_config['api_key'], 'OK-ACCESS-SIGN': signature, 'OK-ACCESS-TIMESTAMP': timestamp, 'OK-ACCESS-PASSPHRASE': api_config['passphrase'], 'Content-Type': 'application/json' }; const options = { hostname: 'web3.okx.com', path: request_path, method: 'POST', headers: headers }; const req = https.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log(data); }); }); if (params) { req.write(JSON.stringify(params)); } req.end(); } // GET 请求示例 const getRequestPath = '/api/v6/dex/aggregator/quote'; const getParams = { 'chainIndex': 42161, 'amount': 1000000000000, 'toTokenAddress': '0xff970a61a04b1ca14834a43f5de4533ebddb5cc8', 'fromTokenAddress': '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1' }; sendGetRequest(getRequestPath, getParams); // POST 请求示例 const postRequestPath = '/api/v5/mktplace/nft/ordinals/listings'; const postParams = { 'slug': 'sats' }; sendPostRequest(postRequestPath, postParams); ``` -------------------------------- ### Get Liquidity Response Example Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-get-liquidity This is a successful response (status code 200) for the get-liquidity request, listing available liquidity pools with their IDs, logos, and names. ```json { "code": "0", "data": [ { "id": "34", "logo": "https://static.okx.com/cdn/wallet/logo/UNI.png", "name": "Uniswap V2" }, { "id": "29", "logo": "https://static.okx.com/cdn/wallet/logo/SUSHI.png", "name": "SushiSwap" }, { "id": "47", "logo": "https://static.okx.com/cdn/explorer/dex/logo/Dex_DefiSwap.png", "name": "DeFi Swap" }, { "id": "49", "logo": "https://static.okx.com/cdn/wallet/logo/convxswap.png", "name": "Convergence" }, { "id": "48", "logo": "https://static.okx.com/cdn/wallet/logo/luaswap.png", "name": "LuaSwap" }, { "id": "40", "logo": "https://static.okx.com/cdn/wallet/logo/SHIB.png", "name": "ShibaSwap" }, { "id": "30", "logo": "https://static.okx.com/cdn/wallet/logo/pancake.png", "name": "PancakeSwap" }, { "id": "53", "logo": "https://static.okx.com/cdn/wallet/logo/UNI.png", "name": "Uniswap V3" }, { "id": "54", "logo": "https://static.okx.com/cdn/wallet/logo/balancer.png", "name": "Balancer V1" }, { "id": "51", "logo": "https://static.okx.com/cdn/wallet/logo/balancer.png", "name": "Balancer V2" }, { "id": "55", "logo": "https://static.okx.com/cdn/wallet/logo/Curve.png", "name": "Curve V1" }, { "id": "58", "logo": "https://static.okx.com/cdn/wallet/logo/Curve.png", "name": "Curve V2" }, { "id": "52", "logo": "https://static.okx.com/cdn/wallet/logo/bancor.png", "name": "Bancor" }, { "id": "59", "logo": "https://static.okx.com/cdn/wallet/logo/Kyber.png", "name": "Kyber" }, { "id": "81", "logo": "https://static.okx.com/cdn/wallet/logo/Synapse.png", "name": "Synapse" }, { "id": "83", "logo": "https://static.okx.com/cdn/wallet/logo/Wombat.png", "name": "Wombat" }, { "id": "80", "logo": "https://static.okx.com/cdn/wallet/logo/DODO.png", "name": "DODO" }, { "id": "82", "logo": "https://static.okx.com/cdn/wallet/logo/Shell.png", "name": "Shell" }, { "id": "88", "logo": "https://static.okx.com/cdn/wallet/logo/DODO.png", "name": "DODO V2" }, { "id": "91", "logo": "https://static.okx.com/cdn/wallet/logo/Smoothy.png", "name": "Smoothy" }, { "id": "92", "logo": "https://static.okx.com/cdn/wallet/logo/RadioShack.png", "name": "RadioShack" }, { "id": "90", "logo": "https://static.okx.com/cdn/wallet/logo/ORION.png", "name": "Orion" }, { "id": "89", "logo": "https://static.okx.com/cdn/wallet/logo/FraxFinance.png", "name": "FraxSwap" }, { "id": "99", "logo": "https://static.okx.com/cdn/wallet/logo/okb.png", "name": "OKX DEX" }, { "id": "101", "logo": "https://static.okx.com/cdn/wallet/logo/dex_Swapr.png", "name": "Swapr" }, { "id": "351", "logo": "https://static.okx.com/cdn/wallet/logo/dex_DFX.png", "name": "DFX Finance V3" }, { "id": "104", "logo": "https://static.okx.com/cdn/wallet/logo/dex_bancor.png", "name": "Bancor V2" } ] } ``` -------------------------------- ### Connect Solana Button Example Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/sdks/chains/solana/provider This example demonstrates how to connect to OKX Wallet using a button click. It handles both successful connections and user rejections, logging the public key or error. ```html ``` ```javascript const connectSolanaButton = document.querySelector('.connectSolanaButton'); connectSolanaButton.addEventListener('click', () => { try { const provider = window.okxwallet.solana; const resp = await provider.connect(); console.log(resp.publicKey.toString()); // 26qv4GCcx98RihuK3c4T6ozB3J7L6VwCuFVc7Ta2A3Uo // { address: string, publicKey: string } } catch (error) { console.log(error); // { code: 4001, message: "User rejected the request."} } }); ``` -------------------------------- ### Query Wallet Balance Value Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/market/market-ai-tools-mcp-server Example natural language query to get the total asset value of a specific wallet address. This invokes the balance-total-value tool. ```shell 0xd8dA... 这个钱包的总资产价值是多少? # 调用 balance-total-value ``` -------------------------------- ### Set up Environment Variables Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/dex-use-swap-sui-quick-start Configure your OKX API credentials and Sui wallet information in a .env file. Ensure you use the correct hexWithoutFlag format for your Sui private key. ```javascript # OKX API Credentials OKX_API_KEY=your_api_key OKX_SECRET_KEY=your_secret_key OKX_API_PASSPHRASE=your_passphrase # Sui Configuration SUI_WALLET_ADDRESS=your_sui_wallet_address SUI_PRIVATE_KEY=your_sui_private_key ``` ```bash sui keytool convert ``` -------------------------------- ### Query Payment Status GET Request Example Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/api-agent-onetime Use this endpoint to poll for the payment status after submitting credentials. This is useful for both Seller and Buyer to track settlement results. ```bash curl --location --request GET 'https://web3.okx.com/api/v6/pay/a2a/p/a2a_01HZX8Q9RK3JWYV7M2N5T8P4AB/status' ``` -------------------------------- ### Connect to Wallet and Get Public Key Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/sdks/chains/nostr/provider A simple example demonstrating how to access the injected Nostr provider and retrieve the user's public key. Error handling is included. ```javascript try { const publicKey = await window.okxwallet.nostr.getPublicKey(); } catch (error) { console.log(error); } ``` -------------------------------- ### Axum Payment Middleware Basic Usage in Rust Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/sdk-rust Integrates the payment middleware into an Axum router using `payment_middleware`. This example shows basic setup with routes and a server instance. ```rust use std::time::Duration; use axum::{Router, routing::get}; use x402_axum::{ payment_middleware, payment_middleware_with_poll_deadline, payment_middleware_with_timeout_hook, payment_middleware_with_timeout_hook_and_deadline, OnSettlementTimeoutHook, RoutesConfig, }; use x402_core::server::X402ResourceServer; let app = Router::new() .route("/api/data", get(handler)) .layer(payment_middleware(routes, server)); ``` -------------------------------- ### Initialize x402ResourceServer in Go Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/payments/sdk-go Initializes the x402ResourceServer, preparing it for operation. Returns an error if initialization fails. ```go func (s *x402ResourceServer) Initialize(ctx context.Context) error ``` -------------------------------- ### Get Gas Limit Response Example (200 OK) Source: https://web3.okx.com/zh-hans/onchainos/dev-docs/trade/onchain-gateway-api-gas-limit A successful response will return a JSON object containing the estimated gas limit under the 'gasLimit' field within the 'data' array. ```json { "code": "0", "data": [ { "gasLimit": "652683" } ], "msg": "" } ```