# Demo Code

本页面提供签名和请求的代码示例，可直接用于开发集成。

***

## HMAC 签名示例

### 签名原文构造

签名原文由 5 行组成，用 `\n` 连接：

```
HTTP_METHOD
API_PATH
TIMESTAMP_MS
NONCE_UUID
REQUEST_BODY
```

### Node.js 示例

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

function computeSignature(secret, method, path, timestamp, nonce, body) {
  const payload = `${method}\n${path}\n${timestamp}\n${nonce}\n${body}`;
  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(payload);
  return hmac.digest('hex');
}

// 使用示例
const secret = 'your-api-secret-here';
const method = 'POST';
const path = '/api/v1/orders/calldata';
const timestamp = Date.now().toString();
const nonce = crypto.randomUUID();
const body = JSON.stringify({
  stockAddress: '0x0000000000000000000000000000000000000001',
  side: 'Buy',
  type: 'Market',
  notional: '10',
  deadline: 1893456000
});

const signature = computeSignature(secret, method, path, timestamp, nonce, body);
console.log('x-api-sign:', signature);
```

### 完整 HTTP 请求示例（cURL）

```bash
API_KEY="your-api-key"
API_SECRET="your-api-secret"
METHOD="POST"
PATH="/api/v1/orders/calldata"
TIMESTAMP=$(date +%s%3N)
NONCE=$(uuidgen)
BODY='{"stockAddress":"0x0000000000000000000000000000000000000001","side":"Buy","type":"Market","notional":"10","deadline":1893456000}'

# 计算签名
PAYLOAD="${METHOD}\n${PATH}\n${TIMESTAMP}\n${NONCE}\n${BODY}"
SIGNATURE=$(echo -n -e "$PAYLOAD" | openssl dgst -sha256 -hmac "$API_SECRET" | awk '{print $2}')

curl -X ${METHOD} "https://rwa-api.anchored.finance/rwa/trading${PATH}" \
  -H "Content-Type: application/json" \
  -H "x-api-key: ${API_KEY}" \
  -H "x-api-ts: ${TIMESTAMP}" \
  -H "x-api-nonce: ${NONCE}" \
  -H "x-api-sign: ${SIGNATURE}" \
  -H "x-api-chain-id: 143" \
  -H "x-api-p: Anchored" \
  -d "${BODY}"
```

### 请求头说明

| Header           | 类型     | 必须      | 说明                              |
| ---------------- | ------ | ------- | ------------------------------- |
| `x-api-key`      | string | 是       | API Key                         |
| `x-api-ts`       | string | 是       | 毫秒级时间戳，45 秒内有效                  |
| `x-api-nonce`    | string | 是       | UUID v4，防重放                     |
| `x-api-sign`     | string | 是       | HMAC-SHA256 签名（hex）             |
| `x-api-chain-id` | string | 是（交易接口） | 链 ID：1/143/10143/84532/11155111 |
| `x-api-p`        | string | 是（交易接口） | 产品：Anchored / MondayTrade       |

***

## EIP-712 签名示例

> EIP-712 签名需要钱包支持（如 MetaMask），浏览器内无法模拟。需配合 `/api/v1/1ct/prepare` 返回的 `signPayload` 使用。

### signPayload 示例（来自 /1ct/prepare）

```json
{
  "domain": {
    "name": "OneClickRouter",
    "version": "1",
    "chainId": 10143,
    "verifyingContract": "0x1111111111111111111111111111111111111111"
  },
  "types": {
    "Delegate": [
      { "name": "user", "type": "address" },
      { "name": "delegatee", "type": "address" },
      { "name": "nonce", "type": "uint64" },
      { "name": "deadline", "type": "uint32" }
    ]
  },
  "primaryType": "Delegate",
  "message": {
    "user": "0x3333333333333333333333333333333333333333",
    "delegatee": "0x2222222222222222222222222222222222222222",
    "nonce": 0,
    "deadline": 1893456000
  }
}
```

### ethers v6 签名代码

```javascript
import { Wallet } from "ethers";

// prepareResponse 来自 /api/v1/1ct/prepare
const { signPayload, deadline } = prepareResponse;
const wallet = new Wallet(process.env.USER_PRIVATE_KEY);

if (wallet.address.toLowerCase() !== signPayload.message.user.toLowerCase()) {
  throw new Error("signer address must match signPayload.message.user");
}

const signature = await wallet.signTypedData(
  { ...signPayload.domain, chainId: BigInt(signPayload.domain.chainId) },
  { Delegate: signPayload.types.Delegate },
  {
    ...signPayload.message,
    nonce: BigInt(signPayload.message.nonce),
    deadline: BigInt(signPayload.message.deadline),
  }
);

console.log({ signature, deadline });
```

***

## 下单请求示例

### 市价买单

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Buy",
  "type": "Market",
  "notional": "10",
  "deadline": 1893456000
}
```

### 市价卖单

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Sell",
  "type": "Market",
  "quantity": "1.25",
  "deadline": 1893456000
}
```

### 限价单

```json
{
  "stockAddress": "0x0000000000000000000000000000000000000001",
  "side": "Buy",
  "type": "Limit",
  "quantity": "1.25",
  "price": "180.50",
  "timeInForce": "DAY",
  "deadline": 1893456000
}
```

### cURL

```bash
curl -X POST "https://rwa-api.anchored.finance/rwa/trading/api/v1/orders/calldata" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $API_KEY" \
  -H "x-api-ts: $(date +%s%3N)" \
  -H "x-api-nonce: $(uuidgen)" \
  -H "x-api-sign: <computed-signature>" \
  -H "x-api-chain-id: 10143" \
  -H "x-api-p: Anchored" \
  -d '{"stockAddress":"0x0000000000000000000000000000000000000001","side":"Buy","type":"Market","notional":"10","deadline":1893456000}'
```


---

# 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/fu-lu/demo-code.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.
