# Demo Code

This page provides code examples for signing and request construction, ready for development integration.

***

## HMAC Signature Example

### Signature Payload Construction

The signature payload consists of 5 lines joined by `\n`:

```
HTTP_METHOD
API_PATH
TIMESTAMP_MS
NONCE_UUID
REQUEST_BODY
```

### Node.js Example

```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');
}

// Usage
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);
```

### Full HTTP Request Example (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}'

# Compute signature
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}"
```

### Request Headers Reference

| Header           | Type   | Required      | Description                                    |
| ---------------- | ------ | ------------- | ---------------------------------------------- |
| `x-api-key`      | string | Yes           | API Key                                        |
| `x-api-ts`       | string | Yes           | Millisecond timestamp, valid within 45 seconds |
| `x-api-nonce`    | string | Yes           | UUID v4, anti-replay                           |
| `x-api-sign`     | string | Yes           | HMAC-SHA256 signature (hex)                    |
| `x-api-chain-id` | string | Yes (trading) | Chain ID: 1/143/10143/84532/11155111           |
| `x-api-p`        | string | Yes (trading) | Product: Anchored / MondayTrade                |

***

## EIP-712 Signature Example

> EIP-712 signing requires wallet support (e.g., MetaMask) and cannot be simulated in the browser. Use the `signPayload` from `/api/v1/1ct/prepare`.

### signPayload Example (from /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 Signing Code

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

// prepareResponse from /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 });
```

***

## Order Request Examples

### Market Buy

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

### Market Sell

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

### Limit Order

```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-en/appendix/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.
