# Node.js 签名示例

完整的 Node.js 签名实现，可直接用于接入 Trading API。

## 安装依赖

```bash
npm install node:crypto
```

## 签名函数

```js
import crypto from "node:crypto";

function canonicalUri(path, query = {}) {
  const pairs = [];
  for (const key of Object.keys(query).sort()) {
    const value = query[key];
    if (Array.isArray(value)) {
      for (const item of value) pairs.push(`${key}=${item}`);
    } else if (value !== undefined && value !== null) {
      pairs.push(`${key}=${value}`);
    }
  }
  return pairs.length === 0 ? path : `${path}?${pairs.join("&")}`;
}

function signTradingApi({ method, path, query, timestamp, nonce, rawBody, apiSecret }) {
  const uri = canonicalUri(path, query);
  const payload = [
    method.toUpperCase(),
    uri,
    String(timestamp),
    nonce,
    rawBody ?? ""
  ].join("\n");

  return crypto
    .createHmac("sha256", apiSecret)
    .update(payload, "utf8")
    .digest("hex");
}
```

## 完整请求示例

```js
import crypto from "node:crypto";

// 构造请求体
const body = JSON.stringify({
  stockAddress: "0x0000000000000000000000000000000000000001",
  side: "Buy",
  type: "Market",
  notional: "10",
  deadline: 1893456000
});

const timestamp = Date.now();
const nonce = crypto.randomUUID();
const signature = signTradingApi({
  method: "POST",
  path: "/api/v1/orders/calldata",
  query: {},
  timestamp,
  nonce,
  rawBody: body,
  apiSecret: process.env.TRADING_API_SECRET
});

// 组装最终请求头
const headers = {
  "content-type": "application/json",
  "x-api-key": process.env.TRADING_API_KEY,
  "x-api-ts": String(timestamp),
  "x-api-nonce": nonce,
  "x-api-sign": signature,
  "x-api-chain-id": "10143",
  "x-api-p": "Anchored"
};

// 发送请求
const response = await fetch(
  "https://rwa-api.anchored.finance/rwa/trading/api/v1/orders/calldata",
  { method: "POST", headers, body }
);

const result = await response.json();
console.log(result);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.anchored.finance/trading-api-docs-zh/jian-quan/nodejs-example.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
