> For the complete documentation index, see [llms.txt](https://docs-unified.crypto-chief.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-unified.crypto-chief.com/getting-started/authentication.md). Agents can also search and read this documentation through its [MCP server](https://docs-unified.crypto-chief.com/~gitbook/mcp).

# Authentication

## Authentication

The key is your **project UUID**: the **Merchant ID** under **Project Settings → Details**. It is the same key as in your RPC Gateway URLs and in Swap API calls, and Unified API calls spend the same platform API credits.

Send it in the `X-API-Key` header:

```
GET https://api-unified.crypto-chief.com/v1/networks
X-API-Key: <project UUID>
```

Or put it in the path, the way the Swap API takes it:

```
GET https://api-unified.crypto-chief.com/<project UUID>/v1/networks
```

Both forms reach the same operations and are charged the same. There is no request signature.

{% hint style="warning" %}
**This is not the secret API key.** Crypto Processing and EventStream sign requests with a secret API key; never send that key to the Unified API, in a header or in a URL. The project UUID is the only credential here: anyone who has it can spend your credits. Keep it server-side, out of browser code, mobile apps and public repositories.
{% endhint %}

### Domain and IP allow-lists

A project's domain and IP allow-lists apply to Unified API calls the same way as to other platform calls:

* the domain allow-list is on and the `Origin` or `Referer` domain is not in it — `403 DOMAIN_NOT_ALLOWED`;
* the IP allow-list is on and the caller's IP is not in it — `403 IP_NOT_ALLOWED`.

A missing, unknown or frozen key is `401 UNAUTHORIZED`:

```json
{
  "error": "UNAUTHORIZED",
  "message": "Missing or invalid API key.",
  "request_id": "req_01JDX9K8P2M4N6Q8R0T2V4W6Y8"
}
```

These checks run before the call; refused calls are not charged ([Billing](https://docs-unified.crypto-chief.com/getting-started/billing.md)).

### Methods and bodies

* Reads are `GET` with query parameters. List parameters (`networks`, `assets`, `type`, `include`) are comma-separated: `networks=ETH_MAINNET,BSC_MAINNET`.
* `POST` takes a JSON object body with `Content-Type: application/json`: [batch balances](https://docs-unified.crypto-chief.com/api-reference/balances.md#batch-balances), [event search](https://docs-unified.crypto-chief.com/api-reference/events.md), [broadcast](https://docs-unified.crypto-chief.com/api-reference/transactions.md#broadcast-a-transaction) and [simulation](https://docs-unified.crypto-chief.com/api-reference/transactions.md#simulate-a-transaction).
* Percent-encode path segments built from addresses, hashes, asset ids and names: `encodeURIComponent` in JavaScript, `rawurlencode` in PHP, `url.PathEscape` in Go, `urllib.parse.quote(value, safe="")` in Python. TON addresses (`0:…`), XRP currency ids (`USD:r…`) and CashAddr addresses (`bitcoincash:…`) contain `:`.

### Request ID

Every response carries `X-Request-Id`, and every error body repeats it as `request_id`. Quote it when contacting support about a call.

### Response headers

| Header                                                            | Meaning                                                                       |
| ----------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `X-Request-Id`                                                    | Identifier of this call                                                       |
| `X-Credits-Used`                                                  | Credits this call cost, after refunds of failed networks or batch items       |
| `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` | Your project's request limit, what is left of it, and seconds until it resets |
| `Retry-After`                                                     | Seconds to wait, on `429` and `503`                                           |

## Calling the API

Each tab defines `api(method, path, query, body)`: it sends the request with the key from the environment variable `CC_API_KEY` and returns the HTTP status, the parsed JSON and the response headers. The examples in this documentation use this helper.

A successful call returns the response object. A failed one returns `error`, `message`, `request_id` and sometimes `details` — see [Errors](https://docs-unified.crypto-chief.com/getting-started/errors.md). Response objects can have their own `status` field (a transaction status, a per-network status), so the helpers keep the HTTP status separate.

{% tabs %}
{% tab title="JavaScript" %}

```javascript
const API_KEY = process.env.CC_API_KEY;
const BASE = "https://api-unified.crypto-chief.com/v1";

async function api(method, path, query = {}, body) {
  const url = new URL(BASE + path);
  for (const [k, v] of Object.entries(query)) {
    if (v === undefined || v === null) continue;
    url.searchParams.set(k, Array.isArray(v) ? v.join(",") : String(v));
  }
  const res = await fetch(url, {
    method,
    headers: {
      "X-API-Key": API_KEY,
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  return { http: res.status, data, headers: res.headers };
}

// Example: the EVM mainnets.
const { http, data, headers } = await api("GET", "/networks", { family: "evm", testnet: false });
if (http !== 200) throw new Error(`${http} ${data.error}: ${data.message} (${data.request_id})`);
console.log(data.items.map((n) => n.id), "credits:", headers.get("x-credits-used"));
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
const BASE = 'https://api-unified.crypto-chief.com/v1';

function api(string $method, string $path, array $query = [], ?array $body = null): array {
    $query = array_map(
        fn($v) => is_bool($v) ? ($v ? 'true' : 'false') : (is_array($v) ? implode(',', $v) : $v),
        array_filter($query, fn($v) => $v !== null)
    );
    $url = BASE . $path . ($query ? '?' . http_build_query($query) : '');
    $headers = ['X-API-Key: ' . getenv('CC_API_KEY')];
    $opts = [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true];
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
        $opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
    }
    $opts[CURLOPT_HTTPHEADER] = $headers;
    $ch = curl_init($url);
    curl_setopt_array($ch, $opts);
    $raw = (string) curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);
    $head = [];
    foreach (explode("\r\n", substr($raw, 0, $headerSize)) as $line) {
        if (str_contains($line, ':')) {
            [$k, $v] = explode(':', $line, 2);
            $head[strtolower(trim($k))] = trim($v);
        }
    }
    $data = json_decode(substr($raw, $headerSize), true) ?: [];
    return ['http' => $status, 'data' => $data, 'headers' => $head];
}

// Example: the EVM mainnets.
$r = api('GET', '/networks', ['family' => 'evm', 'testnet' => false]);
if ($r['http'] !== 200) {
    throw new RuntimeException("{$r['http']} {$r['data']['error']}: {$r['data']['message']}");
}
echo implode(', ', array_column($r['data']['items'], 'id')), "\n";
echo 'credits: ', $r['headers']['x-credits-used'] ?? '0', "\n";
```

{% endtab %}

{% tab title="GO" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
)

var apiKey = os.Getenv("CC_API_KEY")

const base = "https://api-unified.crypto-chief.com/v1"

// api sends the request and returns the HTTP status, the decoded body and the
// response headers. Error bodies decode to {"error", "message", "request_id", "details"}.
func api(method, path string, query url.Values, body any) (int, map[string]any, http.Header, error) {
	u := base + path
	if len(query) > 0 {
		u += "?" + query.Encode()
	}
	var rd io.Reader
	if body != nil {
		raw, err := json.Marshal(body)
		if err != nil {
			return 0, nil, nil, err
		}
		rd = bytes.NewReader(raw)
	}
	req, err := http.NewRequest(method, u, rd)
	if err != nil {
		return 0, nil, nil, err
	}
	req.Header.Set("X-API-Key", apiKey)
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return 0, nil, nil, err
	}
	defer res.Body.Close()
	payload, err := io.ReadAll(res.Body)
	if err != nil {
		return res.StatusCode, nil, res.Header, err
	}
	out := map[string]any{}
	if err := json.Unmarshal(payload, &out); err != nil {
		return res.StatusCode, nil, res.Header, fmt.Errorf("HTTP %d: %s", res.StatusCode, payload)
	}
	return res.StatusCode, out, res.Header, nil
}

func main() {
	// Example: the EVM mainnets.
	status, data, hdr, err := api(http.MethodGet, "/networks", url.Values{"family": {"evm"}, "testnet": {"false"}}, nil)
	if err != nil {
		log.Fatal(err)
	}
	if status != http.StatusOK {
		log.Fatalf("%d %v: %v (%v)", status, data["error"], data["message"], data["request_id"])
	}
	for _, n := range data["items"].([]any) {
		fmt.Println(n.(map[string]any)["id"])
	}
	fmt.Println("credits:", hdr.Get("X-Credits-Used"))
}
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

BASE = "https://api-unified.crypto-chief.com/v1"
session = requests.Session()
session.headers["X-API-Key"] = os.environ["CC_API_KEY"]

def api(method, path, query=None, body=None):
    params = {}
    for k, v in (query or {}).items():
        if v is None:
            continue
        if isinstance(v, bool):
            v = "true" if v else "false"
        elif isinstance(v, (list, tuple)):
            v = ",".join(v)
        params[k] = v
    r = session.request(method, BASE + path, params=params, json=body, timeout=30)
    try:
        data = r.json()
    except ValueError:
        data = {}
    return r.status_code, data, r.headers

# Example: the EVM mainnets.
status, data, headers = api("GET", "/networks", {"family": "evm", "testnet": False})
if status != 200:
    raise RuntimeError(f"{status} {data.get('error')}: {data.get('message')} ({data.get('request_id')})")
print([n["id"] for n in data["items"]], "credits:", headers.get("X-Credits-Used"))
```

{% endtab %}

{% tab title="curl" %}

```bash
export CC_API_KEY="your-project-uuid"

# Example: the EVM mainnets.
curl -s "https://api-unified.crypto-chief.com/v1/networks?family=evm&testnet=false" \
  -H "X-API-Key: $CC_API_KEY"

# A POST with a JSON body.
curl -s -X POST "https://api-unified.crypto-chief.com/v1/addresses/balances" \
  -H "X-API-Key: $CC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"items":[{"ref":"w1","network":"BTC_MAINNET","address":"bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq"}]}'
```

{% endtab %}
{% endtabs %}

## What goes wrong

| Symptom                    | Cause                                                                      |
| -------------------------- | -------------------------------------------------------------------------- |
| `401 UNAUTHORIZED`         | No key, an unknown key, or a frozen project                                |
| `403 DOMAIN_NOT_ALLOWED`   | The domain allow-list is on and the `Origin`/`Referer` domain is not in it |
| `403 IP_NOT_ALLOWED`       | The IP allow-list is on and the caller's IP is not in it                   |
| `402 INSUFFICIENT_CREDITS` | The credit balance will not cover the call                                 |

None of them is charged. The full list is in [Errors](https://docs-unified.crypto-chief.com/getting-started/errors.md).
