介绍
Node.js 环境设置

Node.js 环境设置#

1. 导入必要的 Node.js 库#

首先,导入必要的 Node.js 库并设置你的环境变量。

const cryptoJS = require('crypto-js'); // Import encryption modules for subsequent encryption calculations
const { Web3 } = require('web3'); // Import the Web3 library for interacting with Ethereum
const fetch = (...args) =>
import('node-fetch').then(({ default: fetch }) => fetch(...args)); // Import the fetch library for making HTTP requests

2. 设置你的环境变量#

定义后续请求和 API URL 的基本变量,并初始化 Web3。Web3 是一组库,允许你使用 HTTP、IPC 或 WebSocket 与本地或远程以太坊节点进行交互。

const apiBaseUrl = 'https://www.okx.com/'; // Define the underlying path of the request
const web3RpcUrl = 'https://.....pro'; // The URL for the Ethereum node you want to connect to
const privateKey = '0x...xxx'; // Set the private key of your wallet (replace '0x...xxx' with your actual private key). NEVER SHARE THIS WITH ANYONE!
const chainId = '1';
const fromTokenAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';    // Native token address
const toTokenAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7';

const userWalletAddress = '0x...35'; // User wallet address
const secretKey = '31...D2'; // The key obtained from the previous application
const apiKey = '42d0fd46-6f11-4681-a64a-9ba17d99d406'; // The api Key obtained from the previous application
const passphrase = '*********'; // The password created when applying for the key
const date = new Date(); // Get the current time
const timestamp = date.toISOString(); // Convert the current time to the desired format
const web3 = new Web3(new Web3.providers.HttpProvider(web3RpcUrl)); //Establishing web3 link

3. 定义辅助函数#

定义将用于与 欧易 API 交互的辅助函数。

// Construct full API request URL
const getRequestUrl = (apiBaseUrl, api, queryParams) => {
    return apiBaseUrl + api + '?' + new URLSearchParams(queryParams).toString();
  };
  const apiRequestUrl = getRequestUrl(apiBaseUrl, '/swap', swapParams);

4. 组装头部参数#

设置头部属性。除了 apiRequestUrl 参数外,所有其他参数都是通用的,而 apiRequestUrl 参数是基于不同请求生成的。

const headersParams = {
    'Content-Type': 'application/json',
    'OK-ACCESS-KEY': apiKey,
    'OK-ACCESS-SIGN': cryptoJS.enc.Base64.stringify(
      cryptoJS.HmacSHA256(timestamp + 'GET' + '/api/v5/dex/aggregator/xxx?xxx=xxx', secretKey)
    ),
    'OK-ACCESS-TIMESTAMP': timestamp,
    'OK-ACCESS-PASSPHRASE': passphrase,
  };