> For the complete documentation index, see [llms.txt](https://docs.lighter.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.lighter.xyz/developers/integration-guides/api-keys.md). Agents can also search and read this documentation through its [MCP server](https://docs.lighter.xyz/~gitbook/mcp).

# API keys

{% hint style="info" %}
**Lighter on Robinhood Chain**

On RH, API key indexes 0–3 and 157 are reserved for Lighter's apps; use 4–156 or 158–254. See [Lighter on Robinhood Chain](https://docs.lighter.xyz/developers/robinhood-chain/overview.md) for everything that differs on RH.
{% endhint %}

You can use API keys to trade and manage your Lighter account programmatically. Each API key will be assigned an index, ranging from 0 to 254 - note that indexes `{0,1,2,3}` are reserved for desktop and mobile interfaces.

Each account (master or sub-account) has its own set of API keys (indexes 0–254), each with its own key pair and nonce.

A key is either Schnorr (`key_type: 0`) or standard secp256k1 ECDSA (`key_type: 1`). Both have the same permissions. See [ECDSA API keys](https://docs.lighter.xyz/developers/integration-guides/ecdsa-api-keys.md).

## Permissions

| Property          | Value                                                                                                                               |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Scope             | One account index (master, sub-account or pool)                                                                                     |
| Index range       | 0–254. **0–3 reserved** for Lighter's web/mobile apps. Use 4–254.                                                                   |
| Special index 255 | "All keys" – only for querying [apikeys](https://docs.lighter.xyz/api/api-keys)                                                     |
| Nonce             | Independent per key (see [Core concepts](https://docs.lighter.xyz/developers/getting-started/core-concepts.md#nonce))               |
| Registration      | `ChangePubKey` (Schnorr) or `ChangeECDSAPubKey` (ECDSA), requires the L1 wallet signature (or an on-chain call)                     |
| Can do            | Trade, cancel, modify, leverage/margin, sub-accounts, secure withdrawals, same-owner transfers, auth-gated REST and WebSocket reads |
| Cannot do alone   | Transfers to another L1 owner, fast withdrawals, approving an integrator with fees (these also need the L1 signature)               |
| Optional limits   | Market whitelist, IP whitelist and expiry (see [API key restrictions](#api-key-restrictions))                                       |

Secure withdrawals only need the API key because they can only go back to the L1 address that created the account. Fast withdrawals and transfers can go to other L1 addresses, so they also need a signature from the wallet's private key. See [When an L1 signature is required](https://docs.lighter.xyz/developers/reference/wasm-signer.md#when-an-l1-signature-is-required).

List keys on an account:

```shell
curl "https://mainnet.zklighter.elliot.ai/api/v1/apikeys?account_index=123&api_key_index=255"
```

## Authentication

To interact with certain endpoints, you will need to generate an auth token using your API private key. You can do so using our [GO SDK](https://github.com/elliottech/lighter-go), the create\_auth\_token\_with\_expiry() function in our [Python SDK](https://github.com/elliottech/lighter-python), or the WASM signer:

```typescript
const deadline = Math.floor(Date.now() / 1000) + 3600; // unix seconds, max 8h ahead
const { authToken } = check(lighter.CreateAuthToken(deadline, API_KEY_INDEX, ACCOUNT_INDEX));
```

Each auth token can have a maximum expiry of 8 hours, and it uses the following structure: `{expiry_unix}:{account_index}:{api_key_index}:{random_hex}`. Refresh tokens before they expire.

Use it as:

* REST: `Authorization: <token>` header.
* WebSocket: `"auth": "<token>"` inside the subscribe message for private channels. On Lighter mainnet, you can also authenticate the whole connection (`Authorization` header, `auth` query parameter or an `auth` message) to get your tier's [WebSocket limits](https://docs.lighter.xyz/developers/reference/rate-limits.md#authenticated-connections).

Authenticating a REST request also makes it count against your L1 address instead of your IP. WebSocket connection, subscription and message limits are always counted per IP; `sendTx` and `sendTxBatch` sent over WebSocket follow the transaction limits. See [Rate Limits](https://docs.lighter.xyz/developers/reference/rate-limits.md).

## Read-only Authentication

Using an API-key-signed auth token, you can generate read-only auth tokens - those won't allow placing trades nor request withdrawals (essentially, you won't be able to sign transactions hence initialize a signer client), but you will be able to access auth-gated data via API. Each read-only token can have a maximum expiry of 10 years, and a minimum of 5 minutes. Read-only tokens are limited to `read.*` scopes. They will use the following structure: `ro:{account_index}:{single|all}:{expiry_unix}:{random_hex}`. `all` covers the master account and its sub-accounts; `single` covers one account index.

You can generate one using the [tokens/create](https://docs.lighter.xyz/api/api-keys) endpoint, or [via front-end](https://app.lighter.xyz/read-only-tokens/). On Lighter, `tokens/create` costs **10,000** request weight, about 40% of the 24,000/minute Plus or Premium/Advanced budget. On Robinhood Chain, it costs **23,000**; see the [RH rate limits](https://docs.lighter.xyz/developers/reference/rate-limits.md). Create tokens once and store them; don't create one per session.

Read-only tokens cannot write events through `event/create`, `event/update` or `event/registerOrderBook`. Use an API-key-signed auth token for the authorized operator account; see [Events and metadata](https://docs.lighter.xyz/developers/binary-options/deploy-events.md).

{% hint style="success" %}
**Read-only tokens for dashboards and AI agents**

Giving a dashboard, tax tool or AI agent access to a user's Lighter data? Use a **read-only token**, not an API key.
{% endhint %}

## Maker-only API keys

Clients on a Premium/Advanced account may mark up to 251 keys per account index as maker-only. Those keys will be restricted to 0ms speed bump transactions only:

* Post-only (ALO) orders
* Modify orders on ALO orders
* Cancel, and Cancel All orders

The direct benefit of using this configuration is having access to an optimized execution path, with reduced scheduling latency. It also keeps your cancels from waiting behind slower transactions: transactions on one key execute in nonce order, so a cancel waits for anything sent before it on that key. Send everything else on a separate, normal key. Keys reserved by our front-end (0-3) cannot be set as maker-only, and we apply a one-hour cooldown in between changes.

You can set a list of keys as maker-only using [setMakerOnlyApiKeys](https://docs.lighter.xyz/api/api-keys), and get a list of maker-only keys using [getMakerOnlyApiKeys](https://docs.lighter.xyz/api/api-keys).

## API key restrictions

You can limit what each API key can do. The account's L1 wallet signs every change through [setApiKeyRestrictions](https://docs.lighter.xyz/api/api-keys), so someone who holds only the API private key cannot loosen the limits.

| Restriction      | Effect                                            | Limit                       |
| ---------------- | ------------------------------------------------- | --------------------------- |
| Market whitelist | The key can only trade listed markets             | 16 market ids and 16 series |
| IP whitelist     | The key can only be used from listed IP addresses | 16 addresses, IPv4 or IPv6  |
| Expiry           | The key stops working at `valid_until`            | At most 180 days ahead      |

Every restriction applies to every transaction the key signs except `ChangePubKey`, which the L1 wallet signs. The owner can therefore always replace a restricted or expired key.

### Market whitelist

A key with a market whitelist can only send these transactions:

* Create, modify and cancel orders in a listed market. A grouped order needs every order in a listed market.
* Cancel all orders in one listed market.
* Update leverage or margin in a listed market.

Orders in other markets fail with `71002`. Every other transaction fails with `71003`, including withdrawals, transfers, cancel-all across all markets, and scheduled cancel-all. A key with a market whitelist therefore cannot set or abort a dead man's switch. Use a separate key for that.

Its auth tokens still authenticate reads over REST and WebSocket. Any other request authenticated with them fails with `71003`, for example creating a read-only token or changing account settings.

Series such as binary options get a new market id for each instance. Whitelist them by tag, for example: `"series": [{"creator_account_index": 3, "tag": "btc-updown-5m"}]`.

### IP whitelist

The IP whitelist applies to transactions and to every request authenticated with an auth token signed by this key, over REST and WebSocket. This includes creating new read-only `ro:` tokens. Read-only tokens created earlier are not IP restricted.

### Expiry

* After `valid_until`, the key cannot sign transactions, and requests authenticated with its auth tokens fail. Both return `71001`. The L1 wallet can set a later expiry or clear it.
* Expiry does not cancel the key's open orders. Cancel them with another key if needed.
* Read-only `ro:` tokens created earlier stay valid until their own expiry.

### Key rotation

Restrictions belong to the key's public key. When `ChangePubKey` registers a new public key at the same index, the new key starts with no restrictions. Call setApiKeyRestrictions again for the new public key.

### Setting restrictions

Send form data, not JSON, to `POST /api/v1/setApiKeyRestrictions`. Each request replaces all restrictions on the key. The parameters are listed in the [API reference](https://docs.lighter.xyz/api/api-keys). The main rules:

* `market_ids`, `series` and `allowed_ips` are JSON array strings with up to 16 entries each, for example `[0,1]`. Every market id must be a current market, and each series `tag` is 1 to 100 characters.
* `allowed_ips` lists individual IPv4 or IPv6 addresses, for example `["203.0.113.7"]`. CIDR ranges are not accepted.
* `public_key` is the key's current public key, as returned by [apikeys](https://docs.lighter.xyz/api/api-keys).
* `valid_until` is in Unix seconds, in the future and at most 180 days ahead. `0` means no expiry.
* `timestamp` is the Unix time in seconds when you signed. See [Timestamp rules](#timestamp-rules).
* `signature` is the `0x`-prefixed `personal_sign` signature of the [signing message](#signing-message).

The response is `{"code": 200}` on success. Changes take effect within about one second.

To clear all restrictions, send `market_ids` as `[]`, `series` and `allowed_ips` as `[]` (or omit them) and `valid_until` as `0`. The same signing and timestamp rules apply.

### Signing message

The account's L1 wallet signs this message with `personal_sign` (EIP-191). Lines are separated by `\n` and there is no trailing newline.

```
Set API Key Restrictions

account index: {account_index}
api key index: {api_key_index}
pubkey: 0x{public_key}
market ids: {market_ids}
series: {series}
allowed ips: {allowed_ips}
valid until: {valid_until}
timestamp: {timestamp}
chainId: {chain_id}
Only sign this message for a trusted client!
```

Fill the placeholders as follows:

* `account_index`, `api_key_index`, `valid_until`, `timestamp` and `chain_id`: `0x` followed by 16 lowercase hex digits, zero-padded. For example, `123` becomes `0x000000000000007b`.
* `public_key`: lowercase hex without `0x` (the template already contains `0x`).
* `market_ids`, `series` and `allowed_ips`: the exact strings you send in the request, byte for byte. `[1, 2]` and `[1,2]` produce different messages. An omitted or empty `series` or `allowed_ips` is signed as `[]`.
* `chain_id`: the L2 chain ID you sign transactions with. See [Environments & endpoints](https://docs.lighter.xyz/developers/getting-started/environments.md).

Smart-contract wallets such as Safe cannot produce this signature, so accounts owned by one cannot set restrictions. See [Multi-signature and smart wallets](https://docs.lighter.xyz/developers/integration-guides/multi-signature-wallets.md).

```typescript
const hex16 = (n: number | bigint) => "0x" + BigInt(n).toString(16).padStart(16, "0");

const marketIds = "[0,1]";
const series = "[]";
const allowedIps = '["203.0.113.7"]';
const validUntil = Math.floor(Date.now() / 1000) + 30 * 24 * 3600; // 30 days, or 0 for no expiry
const timestamp = Math.floor(Date.now() / 1000);
const pubKey = publicKey.replace(/^0x/, "").toLowerCase();

const message = [
  "Set API Key Restrictions",
  "",
  `account index: ${hex16(accountIndex)}`,
  `api key index: ${hex16(apiKeyIndex)}`,
  `pubkey: 0x${pubKey}`,
  `market ids: ${marketIds}`,
  `series: ${series}`,
  `allowed ips: ${allowedIps}`,
  `valid until: ${hex16(validUntil)}`,
  `timestamp: ${hex16(timestamp)}`,
  `chainId: ${hex16(CHAIN_ID)}`,
  "Only sign this message for a trusted client!",
].join("\n");

const signature = await signer.signMessage(message); // ethers, personal_sign

const res = await fetch(`${BASE_URL}/api/v1/setApiKeyRestrictions`, {
  method: "POST",
  body: new URLSearchParams({
    account_index: String(accountIndex),
    api_key_index: String(apiKeyIndex),
    public_key: pubKey,
    market_ids: marketIds,
    series,
    allowed_ips: allowedIps,
    valid_until: String(validUntil),
    timestamp: String(timestamp),
    signature,
  }),
}).then(r => r.json());
if (res.code !== 200) throw new Error(`setApiKeyRestrictions failed: ${res.code} ${res.message}`);
```

### Timestamp rules

`timestamp` is in seconds and must meet both rules, or the request fails with `71004`:

* It is within 10 minutes of server time, in either direction.
* It is greater than the `timestamp` of the restrictions currently stored for this `account_index` and `api_key_index`. This blocks replays of an older signed request. Two updates signed in the same second also fail.

### Reading restrictions

[apikeys](https://docs.lighter.xyz/api/api-keys) returns each key's `restrictions` when you send an auth token for `account_index`, and omits them otherwise. Read-only `ro:` tokens work too, so anyone you give one for the account can read these fields, including `allowed_ips`.

| Field         | Type      | Description                                                                                                     |
| ------------- | --------- | --------------------------------------------------------------------------------------------------------------- |
| `market_ids`  | int64\[]  | Public market ids the key may trade. Empty, with `series` also empty, means no market whitelist.                |
| `series`      | object\[] | Market series the key may trade, in addition to `market_ids`. Each entry has `creator_account_index` and `tag`. |
| `allowed_ips` | string\[] | IP addresses the key may be used from. Empty allows any IP.                                                     |
| `valid_until` | int64     | Unix seconds when the key expires. `0` means no expiry.                                                         |

A key without restrictions returns empty lists and `valid_until: 0`.

```json
{
  "code": 200,
  "api_keys": [
    {
      "account_index": 123,
      "api_key_index": 4,
      "nonce": 722,
      "public_key": "…",
      "transaction_time": 1257894000000000,
      "restrictions": {
        "market_ids": [0, 1],
        "series": [{ "creator_account_index": 3, "tag": "btc-updown-5m" }],
        "allowed_ips": ["203.0.113.7"],
        "valid_until": 1767139200
      }
    }
  ]
}
```

### Restriction errors

| Code    | Meaning                     | What to check                                                                                                                                                |
| ------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `71001` | API key has expired         | The key's `valid_until` has passed. Register a new key, or set a later expiry with setApiKeyRestrictions.                                                    |
| `71002` | Market not allowed          | The market is not in the key's `market_ids` or a listed series.                                                                                              |
| `71003` | Action not allowed          | A key with a market whitelist can only create, modify and cancel orders, cancel all in one listed market, update leverage or margin, and authenticate reads. |
| `71004` | Stale restriction timestamp | See [Timestamp rules](#timestamp-rules).                                                                                                                     |
| `71005` | Public key mismatch         | `public_key` must be the key's current public key. It changes when `ChangePubKey` registers a new key at this index.                                         |
| `71006` | IP address not allowed      | The request's IP address must be in the key's `allowed_ips`.                                                                                                 |

setApiKeyRestrictions can also return `20001` (invalid parameter or signature) and `21100`, `21109` or `21110` (account or API key not found, invalid API key index). The message names the problem.

## How to create API keys programmatically

While generating the API keys does not require your L1 private key, associating them with your Lighter account does. See [Create accounts programmatically](https://docs.lighter.xyz/pages/d1q7WUTUJVmxIIgcv84o#id-2.-register-an-api-key) for a TypeScript example, or use the [Python SDK](https://github.com/elliottech/lighter-python/blob/main/examples/system_setup.py#L58) or the [GO SDK](https://github.com/elliottech/lighter-go/blob/0d4ddf155950e8ad62164a9d34a139750deebe37/README.md?plain=1#L26). You can also interact with Lighter's smart contract directly using the [ChangePubKey function](https://app.lighter.xyz/ethereum-gateway/) (this is particularly helpful if you're running a multi-sig).

## Nonce management

Each API key has its own nonce. Nonce rules, skipping nonces, which rejected transactions consume a nonce, and why to use a separate API key per workload are covered in [Core concepts](https://docs.lighter.xyz/developers/getting-started/core-concepts.md#nonce).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.lighter.xyz/developers/integration-guides/api-keys.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
