# Node.js Guide for Calling Mefree.NET API

This guide explains how to use **Node.js** to interact with the Mefree.NET API, including signature generation, HTTP requests, and example usage.

***

#### **1. Overview of the Signature Rules**

**1.1 Signature String Rules**

To authenticate with Mefree.NET API, requests must include a signature. Follow these steps:

1. **Construct the String to Sign**:

   ```
   sign = timestamp + method + requestPath
   ```

   * **timestamp**: The current UTC timestamp in ISO 8601 format, e.g., `2024-11-26T12:34:56.789Z`.
   * **method**: HTTP method (e.g., `GET`, `POST`).
   * **requestPath**: The API endpoint path, including query parameters if present, such as:
     * `/api/config`
     * `/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1`
2. **Generate the Signature**:
   * Use the **HMAC-SHA256** algorithm to hash the string using your **Secret Key**.
   * Encode the resulting hash with **Base64**.

***

**1.2 Required HTTP Headers**

Every API request must include the following headers:

* `Content-Type: application/json`
* `MF-ACCESS-KEY`: Your API Key.
* `MF-ACCESS-SIGN`: The signature generated above.
* `MF-ACCESS-TIMESTAMP`: Current UTC timestamp.

***

#### **2. Environment Setup**

1. Ensure you have **Node.js** installed (version 14+ recommended).
2. Install the required dependencies:

   ```bash
   npm install axios crypto
   ```

***

#### **3. Signature Generation Function**

Below is the Node.js function to generate the required signature:

```javascript
const crypto = require("crypto");

/**
 * Generate HMAC-SHA256 signature.
 * @param {string} timestamp - Current UTC timestamp in ISO 8601 format.
 * @param {string} method - HTTP method (e.g., GET or POST).
 * @param {string} requestPath - API endpoint path (including query parameters).
 * @param {string} secretKey - Your API Secret Key.
 * @returns {string} - Base64-encoded signature.
 */
function generateSignature(timestamp, method, requestPath, secretKey) {
  const message = `${timestamp}${method}${requestPath}`;
  const hmac = crypto.createHmac("sha256", secretKey);
  hmac.update(message);
  return hmac.digest("base64");
}

/**
 * Get the current UTC timestamp in ISO 8601 format.
 * @returns {string} - Timestamp in ISO 8601 format (e.g., 2024-11-26T12:34:56.789Z).
 */
function getUtcTimestamp() {
  return new Date().toISOString();
}
```

***

#### **4. Sending HTTP Requests**

Use the `axios` library to send HTTP requests with the required headers.

```javascript
const axios = require("axios");

const BASE_URL = "https://api.mefree.net";
const API_KEY = "your_api_key";       // Replace with your API Key
const SECRET_KEY = "your_secret_key"; // Replace with your Secret Key

/**
 * Send an HTTP request to the Mefree.NET API.
 * @param {string} method - HTTP method (GET or POST).
 * @param {string} requestPath - API endpoint path (including query parameters).
 * @returns {Promise<object>} - The JSON response from the API.
 */
async function sendRequest(method, requestPath) {
  const timestamp = getUtcTimestamp();
  const signature = generateSignature(timestamp, method, requestPath, SECRET_KEY);

  const headers = {
    "Content-Type": "application/json",
    "MF-ACCESS-KEY": API_KEY,
    "MF-ACCESS-SIGN": signature,
    "MF-ACCESS-TIMESTAMP": timestamp,
  };

  const url = `${BASE_URL}${requestPath}`;

  try {
    const response = await axios({
      method,
      url,
      headers,
    });
    return response.data;
  } catch (error) {
    console.error("Request failed:", error.response?.data || error.message);
    throw error;
  }
}
```

***

#### **5. Example API Calls**

**5.1 Get Account Information**

**API Endpoint**: `/api/config`\
**HTTP Method**: `GET`

**Code Example**:

```javascript
(async () => {
  try {
    const response = await sendRequest("GET", "/api/config");
    console.log("Account Information:", response);
  } catch (error) {
    console.error("Failed to fetch account information.");
  }
})();
```

***

**5.2 Create an Order**

**API Endpoint**: `/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1`\
**HTTP Method**: `POST`

**Code Example**:

```javascript
(async () => {
  try {
    const requestPath = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1";
    const response = await sendRequest("POST", requestPath);
    console.log("Order Created:", response);
  } catch (error) {
    console.error("Failed to create order.");
  }
})();
```

***

**5.3 Query Order Status**

**API Endpoint**: `/api/order/{pay_hash}`\
**HTTP Method**: `GET`

**Code Example**:

```javascript
(async () => {
  try {
    const payHash = "abcd1234"; // Replace with the actual pay_hash
    const requestPath = `/api/order/${payHash}`;
    const response = await sendRequest("GET", requestPath);
    console.log("Order Status:", response);
  } catch (error) {
    console.error("Failed to fetch order status.");
  }
})();
```

***

#### **6. Common Issues**

**6.1 Invalid Signature (401 Unauthorized)**

* Double-check the `MF-ACCESS-KEY` matches your API Key.
* Verify the signature generation logic:
  * Ensure the string format is `timestamp + method + requestPath`.
  * Use the correct `SECRET_KEY`.
* Ensure the timestamp is in UTC format and not older than 5 seconds.

**6.2 Bad Request (400)**

* Check that the request path and query parameters are correct.
* Ensure the `Content-Type` header is set to `application/json`.

**6.3 Too Many Requests (429)**

* Respect the API rate limits. Add throttling in your code if necessary.

***

#### **7. Summary**

This guide demonstrates how to interact with the Mefree.NET API using Node.js. It includes the signature generation logic, HTTP request handling, and examples for common API calls. For additional support, refer to the [official API documentation](https://mefree.net/) or contact Mefree support.
