# Authentication

## Two key types

| Key type        | API used                                                  | Auth scheme                         | What it covers                                                                                                              |
| --------------- | --------------------------------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Consumption key | [Consumption API](/docs/api-reference/consumption-api.md) | Bearer header or `x-api-key` header | Inference only. Chat completions on the OpenAI-compatible host, messages on the Anthropic Messages host.                    |
| Trading key     | [Trading API](/docs/api-reference/trading-api.md)         | Ed25519-signed requests             | Everything beyond inference: instrument specifications, market data, balances, past trades, transfers, and order placement. |

If you only consume inference and let Auto Mode buy on your behalf, a Consumption key is enough. The moment you want to read your account balance, fetch instrument specifications programmatically, list past purchases, or place orders yourself, you need a Trading key. Trading keys cover the entire Trading API surface, not just order placement.

Both key types are generated in the dashboard at [app.thegrid.ai/profile/api-keys](https://app.thegrid.ai/profile/api-keys).

## Consumption keys

A standard Bearer token. The same key value works on both the OpenAI-compatible host and the Anthropic Messages host. Only the header name changes.

### Generate a Consumption key

1. Sign in at [app.thegrid.ai](https://app.thegrid.ai).
2. Open `Profile > API Keys`.
3. Click `Create new key`, name it something you recognize later (one key per project is a sensible default), and copy the value. The full key is shown once.

### Use a Consumption key

On the OpenAI-compatible host (`https://api.thegrid.ai/v1`), pass the standard Bearer header:

```bash
curl -L https://api.thegrid.ai/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "Text-Prime", "messages": [{"role": "user", "content": "Hello"}]}'
```

On the Anthropic Messages host (`https://messages-beta.api.thegrid.ai/v1`), pass the Anthropic-style header instead. Same key value, different header name:

```
x-api-key: YOUR_API_KEY
```

## Trading keys

The Trading API uses Ed25519 signature authentication. Every request is signed with your private key, and we verify it against the public key you registered in the dashboard.

### Generate an Ed25519 keypair

Generate the keypair locally using a public Ed25519 library. The private key never leaves your machine; only the public key gets registered with us.

{% tabs %}
{% tab title="Python" %}
Uses the [`cryptography`](https://cryptography.io/) library (`pip install cryptography`):

```bash
python -c "
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
import base64
sk = Ed25519PrivateKey.generate()
print('private:', base64.b64encode(sk.private_bytes_raw()).decode())
print('public:', base64.b64encode(sk.public_key().public_bytes_raw()).decode())
"
```

{% endtab %}

{% tab title="Node" %}
Uses [`tweetnacl`](https://www.npmjs.com/package/tweetnacl) (`npm install tweetnacl`):

```bash
node -e "
const nacl = require('tweetnacl');
const kp = nacl.sign.keyPair();
console.log('private:', Buffer.from(kp.secretKey).toString('base64'));
console.log('public:', Buffer.from(kp.publicKey).toString('base64'));
"
```

{% endtab %}

{% tab title="Go" %}
Uses the standard library [`crypto/ed25519`](https://pkg.go.dev/crypto/ed25519) (no external dependencies):

```bash
cat <<'EOF' > genkey.go
package main

import (
    "crypto/ed25519"
    "crypto/rand"
    "encoding/base64"
    "fmt"
)

func main() {
    pub, priv, _ := ed25519.GenerateKey(rand.Reader)
    fmt.Println("private:", base64.StdEncoding.EncodeToString(priv))
    fmt.Println("public:", base64.StdEncoding.EncodeToString(pub))
}
EOF
go run genkey.go
```

{% endtab %}
{% endtabs %}

Save the private key in a secrets manager. Treat it like a database credential.

### Register the public key

In the dashboard at [app.thegrid.ai/profile/api-keys](https://app.thegrid.ai/profile/api-keys), open the Trading keys section and paste the public key value. The dashboard returns the fingerprint (SHA256 of the public key, base64-encoded without padding); you'll send that fingerprint on every signed request.

### Sign a request

The string you sign is the concatenation of:

1. Unix timestamp in seconds, as a string
2. HTTP method, uppercase (`POST`, `GET`, `DELETE`)
3. Request path including any query string (e.g., `/v1/orders?status=open`)
4. Request body as a string, or the empty string for `GET` and `DELETE`

Sign that string with your Ed25519 private key, then base64-encode the resulting signature. Send three headers on every Trading API request:

| Header                  | Value                                                                                                                           |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `x-thegrid-signature`   | Base64-encoded Ed25519 signature of `<timestamp><METHOD><path><body>`.                                                          |
| `x-thegrid-timestamp`   | Unix timestamp in seconds, as a string. Must be within 30 seconds of server time, otherwise the request is rejected with `401`. |
| `x-thegrid-fingerprint` | SHA256 hash of your public key, base64-encoded without padding. The dashboard shows this value when you register the key.       |

If you see `401` on otherwise-correct requests, check your machine's clock first. Timestamp drift is the most common cause.

## Key management

Keep keys out of your source tree. Use environment variables for Consumption keys, and a secrets manager (AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault, your CI/CD secret store) for Trading private keys.

```bash
export GRID_API_KEY="..."
```

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.thegrid.ai/v1",
    api_key=os.environ["GRID_API_KEY"],
)
```

### Rotation

Rotate keys periodically and any time you suspect exposure:

1. Generate a new key in the dashboard.
2. Roll your application to use the new key.
3. Delete the old key from the dashboard.

The dashboard supports multiple active keys per account, so you can roll without downtime.

### Compromised keys

Delete a compromised key in the dashboard immediately. It stops working at the API edge as soon as the deletion propagates. If you suspect billing impact, contact <support@thegrid.ai> with the key fingerprint and approximate compromise window.

## Where next

* [Consumption API](/docs/api-reference/consumption-api.md): endpoints that take Consumption keys
* [Trading API](/docs/api-reference/trading-api.md): endpoints that take Trading keys
* [Errors and rate limits](/docs/api-reference/errors-and-rate-limits.md): what `401` looks like and how to debug it


---

# 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://thegrid.ai/docs/api-reference/authentication.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.
