> ## Documentation Index
> Fetch the complete documentation index at: https://docs.olympex.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Rotate an API key

> Replace the API key that signs the request with a new API key ID and secret key, keeping the old one valid for a grace period or revoking it at once.

`POST /accounts/me/keys/rotate` creates a new API key for your account and retires the key that signs the request. Olympex generates the new API key ID and secret key and returns the secret key in this response. Your passphrase doesn't change. In `graceful` mode, the default, the old key keeps working for a grace period, so you can deploy the new key without downtime. In `compromised` mode, Olympex revokes the old key at once.

The API console doesn't call the key endpoints: run them from your server, where your credentials live.

Signed endpoint. Send `Content-Type: application/json`, the canonical JSON body, the four headers `x-api-key-id`, `x-value-info`, `x-passphrase` and `x-signature` described in [Sign requests](https://docs.olympex.io/authentication/sign-requests.md), and an `Idempotency-Key` header (not signed, up to 200 characters). Sign with the key you rotate; it must be `active`. Body fields, all optional: `mode` (`graceful` or `compromised`, default `graceful`), `gracePeriodSeconds` (integer, 60 to 604800, default 86400) and `reason` (up to 200 characters). Send `{}` for the defaults. The response holds the new `apiKeyId` and `secretKey`, `previousApiKeyId`, `previousKeyExpiresAt` and `secretRecoverableUntil`, with `Cache-Control: no-store`; store the secret key before anything else and never log it. Generate the `Idempotency-Key` once per rotation and persist it with the body before the first attempt: a retry with the same `Idempotency-Key`, the same body and the same signing key returns the same new key and secret key until `secretRecoverableUntil` (15 minutes). After that, the secret key can't be retrieved again. The same `Idempotency-Key` with another body or another signing key returns `409 CONFLICT`. A `rotating` key that starts a new rotation gets `404 NOT_FOUND` "Key not found". An account can send 5 rotation requests per hour, retries included: over that, `429 RATE_LIMIT_EXCEEDED` means the request didn't run, so wait up to an hour. On `503 SERVICE_UNAVAILABLE`, nothing changed: retry after a few seconds with the same `Idempotency-Key` and body.

## Choose the mode

| `mode` | Old key after the call | Use it when |
| - | - | - |
| `graceful` (default) | `rotating`: it signs requests until `previousKeyExpiresAt`, `gracePeriodSeconds` from now, then becomes `expired`. | You rotate on a schedule, or replace a key you have no reason to distrust. |
| `compromised` | `revoked` at once. `previousKeyExpiresAt` is the time of the rotation. | The old secret key or passphrase may be exposed. |

`gracePeriodSeconds` goes from 60 to 604800 (7 days), and defaults to 86400 (24 hours). Choose a period longer than it takes you to deploy the new key everywhere, then [revoke](https://docs.olympex.io/api-reference/accounts/revoke-api-key.md) the old key as soon as your services use the new one.

Only an `active` key can start a rotation. A `rotating` key that tries gets `404 NOT_FOUND` with the message `"Key not found"`. The new key can rotate again during the grace period, which leaves more than one `rotating` key: [list your keys](https://docs.olympex.io/api-reference/accounts/list-api-keys.md) and revoke the ones you no longer use.

## Retry with the same Idempotency-Key

The `Idempotency-Key` header identifies one rotation, not one attempt. Generate it once, for example as a UUID, and store it with the exact body before you send the first attempt. If an attempt times out or returns a `5xx`, sign it again (with a new timestamp and nonce) and send it with the same `Idempotency-Key`, the same body and the same signing key. Olympex then returns the same new API key ID and secret key, and creates no other key.

* **The window is 15 minutes.** A retry returns the secret key until `secretRecoverableUntil`. After that, no endpoint returns that secret key again, so store it as soon as you receive it.
* **Change nothing.** The same `Idempotency-Key` with another body or another signing key returns `409 CONFLICT` with the message `"Idempotency key was reused with a different payload"`. Key order and whitespace don't count: Olympex compares the canonical body.
* **A new rotation needs a new key.** Never generate a new `Idempotency-Key` to retry an attempt whose outcome you don't know: that starts a second rotation if the first one succeeded. On a `409`, [list your keys](https://docs.olympex.io/api-reference/accounts/list-api-keys.md) first.
* **A graceful retry also needs the old key.** It must still be `rotating`, so the retry deadline is the earlier of `secretRecoverableUntil` and `previousKeyExpiresAt`.
* **Retries count toward the rate limit.** An account can send 5 rotation requests per hour, retries with the same `Idempotency-Key` included, on every plan. Over that, the API answers `429` `RATE_LIMIT_EXCEEDED` and the request doesn't run: wait up to an hour, then send it again with the same `Idempotency-Key` and body. Don't retry a `429` sooner. A `503` `SERVICE_UNAVAILABLE` means Olympex refused the rotation for now and changed nothing: retry it after a few seconds.

> [!WARNING]
>
> A `compromised` rotation revokes the old key in the same call, so if you lose its response, you can't retry it: the gateway rejects the old key with `403`, and the account has no key you hold. Email [partners@olympex.io](mailto:partners@olympex.io) with the API key IDs (never a secret key or the passphrase), and create a new account if you need to keep working.

## Store the new key first

The response carries `Cache-Control: no-store`. Keep it out of caches, logs and error reports.

1. Write `apiKeyId` and `secretKey` to your secrets manager before you report success. Keep the passphrase: it signs for the new key too.
2. Confirm that the new key works, for example by calling [`GET /accounts/me/keys`](https://docs.olympex.io/api-reference/accounts/list-api-keys) with it.
3. Deploy the new key to every service that signs requests.
4. Revoke the old key once nothing uses it, instead of waiting for `previousKeyExpiresAt`.

```bash cURL theme={null}
# Rotate the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
# Needs openssl, curl and OLYMPEX_API_KEY_ID, OLYMPEX_SECRET_KEY, OLYMPEX_PASSPHRASE.
# To retry, set IDEMPOTENCY_KEY to the value of the first attempt and keep BODY the same.
IDEMPOTENCY_KEY="${IDEMPOTENCY_KEY:-$(openssl rand -hex 16)}"
METHOD=POST
ENDPOINT=/accounts/me/keys/rotate
QUERY=''
BODY='{"gracePeriodSeconds":86400,"mode":"graceful","reason":"scheduled rotation"}'
TS="${OLYMPEX_TIMESTAMP:-$(date +%s)}"
NONCE="${OLYMPEX_NONCE:-$(openssl rand -hex 12)}"
BODY_HASH="$(printf '%s' "$BODY" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')"
VALUE_INFO="$(printf '%s\n%s\n%s' "$TS" "$NONCE" "$BODY_HASH")"
MESSAGE="$(printf 'OLPX-HMAC-SHA256-V2\n%s\n%s\n%s\n%s\n%s\n%s' "$TS" "$NONCE" "$METHOD" "/api/v1$ENDPOINT" "$QUERY" "$BODY_HASH")"
# The response holds the new secret key: it goes to a file only you can read, not to the terminal.
( umask 077
  curl -sS -X "$METHOD" "https://api-rest.olympex.io/api/v1$ENDPOINT${QUERY:+?$QUERY}" \
    -H "content-type: application/json" \
    -H "idempotency-key: $IDEMPOTENCY_KEY" \
    -H "x-api-key-id: $OLYMPEX_API_KEY_ID" \
    -H "x-value-info: $(printf '%s' "$VALUE_INFO" | openssl base64 -A)" \
    -H "x-passphrase: $OLYMPEX_PASSPHRASE" \
    -H "x-signature: $(printf '%s' "$MESSAGE" | openssl dgst -sha256 -hmac "$OLYMPEX_SECRET_KEY" -binary | od -An -v -tx1 | tr -d ' \n')" \
    --data-raw "$BODY" -o olympex-rotation-response.json )
```

```ts TypeScript theme={null}
// Node.js 18+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { credentialsFromEnv, olympexRequest, OlympexApiError } from "./sign-request.ts"; // /authentication/sign-requests

type Rotation = { apiKeyId: string; secretKey: string; previousApiKeyId: string; previousKeyExpiresAt: string; secretRecoverableUntil: string };

const PENDING = "olympex-rotation.pending.json"; // this rotation's Idempotency-Key and body, kept until the new key is stored
const ENV_FILE = "olympex.env.new"; // stand-in for your secrets manager
const current = credentialsFromEnv();

// One Idempotency-Key per rotation, saved with the body before the first attempt.
if (!existsSync(PENDING)) {
  const body = { gracePeriodSeconds: 86400, mode: "graceful", reason: "scheduled rotation" };
  writeFileSync(PENDING, JSON.stringify({ idempotencyKey: randomUUID(), body }), { mode: 0o600, flag: "wx" });
}
const { idempotencyKey, body } = JSON.parse(readFileSync(PENDING, "utf8"));

// A retry with the same Idempotency-Key, body and signing key returns the same new key.
const rotate = async (): Promise<Rotation> => {
  for (let attempt = 1; ; attempt++) {
    try {
      return await olympexRequest<Rotation>("POST", "/accounts/me/keys/rotate", body, current, { "Idempotency-Key": idempotencyKey });
    } catch (error) {
      const retryable = !(error instanceof OlympexApiError) || error.status >= 500; // no response or 5xx; a 429 needs up to an hour
      if (!retryable || attempt === 4) throw error; // PENDING stays: run again within 15 minutes to retry the same rotation
      await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
    }
  }
};
const rotation = await rotate();

// Store the new key before anything else, then confirm that it signs.
writeFileSync(ENV_FILE, `OLYMPEX_API_KEY_ID=${rotation.apiKeyId}\nOLYMPEX_SECRET_KEY=${rotation.secretKey}\n`, { mode: 0o600, flag: "wx" });
rmSync(PENDING);
await olympexRequest("GET", "/accounts/me/keys", undefined, { ...current, apiKeyId: rotation.apiKeyId, secretKey: rotation.secretKey });
console.log(`New key ${rotation.apiKeyId} works and is in ${ENV_FILE}. ${rotation.previousApiKeyId} signs until ${rotation.previousKeyExpiresAt}.`);
```

```python Python theme={null}
# Python 3.8+. Rotates the API key in OLYMPEX_API_KEY_ID; the old key keeps working for 24 hours.
import json
import os
import time
import uuid

import requests

from sign_request import OlympexApiError, credentials_from_env, olympex_request  # /authentication/sign-requests

PENDING = "olympex-rotation.pending.json"  # this rotation's Idempotency-Key and body, kept until the new key is stored
ENV_FILE = "olympex.env.new"  # stand-in for your secrets manager
current = credentials_from_env()


def write_private(path, text):
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "w") as file:
        file.write(text)


# One Idempotency-Key per rotation, saved with the body before the first attempt.
if not os.path.exists(PENDING):
    body = {"gracePeriodSeconds": 86400, "mode": "graceful", "reason": "scheduled rotation"}
    write_private(PENDING, json.dumps({"idempotency_key": str(uuid.uuid4()), "body": body}))
with open(PENDING) as file:
    pending = json.load(file)

# A retry with the same Idempotency-Key, body and signing key returns the same new key.
for attempt in range(1, 5):
    try:
        rotation = olympex_request(
            "POST", "/accounts/me/keys/rotate", pending["body"], current, headers={"Idempotency-Key": pending["idempotency_key"]}
        )
        break
    except (OlympexApiError, requests.RequestException) as error:
        status = getattr(error, "status", None)  # None: no response
        if (status is not None and status < 500) or attempt == 4:  # a 429 needs up to an hour
            raise  # PENDING stays: run again within 15 minutes to retry the same rotation
        time.sleep(2**attempt)

# Store the new key before anything else, then confirm that it signs.
write_private(ENV_FILE, f"OLYMPEX_API_KEY_ID={rotation['apiKeyId']}\nOLYMPEX_SECRET_KEY={rotation['secretKey']}\n")
os.remove(PENDING)
olympex_request("GET", "/accounts/me/keys", credentials={**current, "api_key_id": rotation["apiKeyId"], "secret_key": rotation["secretKey"]})
print(f"New key {rotation['apiKeyId']} works and is in {ENV_FILE}. {rotation['previousApiKeyId']} signs until {rotation['previousKeyExpiresAt']}.")
```

```json 200 Graceful theme={null}
{
  "success": true,
  "data": {
    "apiKeyId": "00000000-0000-4000-8000-000000000001",
    "secretKey": "aol_DocsTestVector_notARealSecret_000000000",
    "previousApiKeyId": "00000000-0000-4000-8000-000000000000",
    "previousKeyExpiresAt": "2026-10-31T13:06:45.989Z",
    "secretRecoverableUntil": "2026-10-30T13:21:45.989Z"
  },
  "meta": {
    "requestId": "GDxwAjXioAMEPWA=",
    "version": "v1",
    "accountType": "integrator",
    "apiKeyId": "00000000-0000-4000-8000-000000000000"
  }
}
```

```json 400 theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Idempotency-Key header is required",
    "details": []
  },
  "meta": {
    "requestId": "GDxv6g_loAMEZ7w=",
    "version": "v1",
    "accountType": "integrator",
    "apiKeyId": "00000000-0000-4000-8000-000000000000"
  }
}
```

```json 409 theme={null}
{
  "success": false,
  "error": {
    "code": "CONFLICT",
    "message": "Idempotency key was reused with a different payload",
    "details": []
  },
  "meta": {
    "requestId": "GDxwCjFXIAMEZQw=",
    "version": "v1",
    "accountType": "integrator",
    "apiKeyId": "00000000-0000-4000-8000-000000000000"
  }
}
```

```json 429 theme={null}
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many key administration requests",
    "details": []
  },
  "meta": {
    "requestId": "GQ1D7ixyIAMEPHA=",
    "version": "v1",
    "accountType": "integrator",
    "apiKeyId": "00000000-0000-4000-8000-000000000000"
  }
}
```

```json 403 theme={null}
{
  "message": "Forbidden"
}
```


## OpenAPI

````yaml api-reference/openapi.json POST /accounts/me/keys/rotate
openapi: 3.0.3
info:
  title: Olympex REST API
  version: 1.0.0
  description: >-
    Aggregated swap quotes and transactions, limit orders and DCA strategies on
    EVM chains, plus the chain and token catalog and the management of your API
    keys. Every response uses the same envelope, except the API gateway's own
    responses (`{"message": …}`): `401` or `403` when the signed headers are
    missing or rejected, `429` when it throttles requests, and `500` or `503`
    when it can't get a response from Olympex in time. Each API account has a
    rate limit on every signed endpoint, shared by all its API keys: over it,
    the API answers `429` with `RATE_LIMIT_EXCEEDED`. See [Rate
    limits](https://docs.olympex.io/authentication/limits#rate-limits). Chain
    IDs are integers on every endpoint. Signed endpoints require four signed
    headers; see [Sign
    requests](https://docs.olympex.io/authentication/sign-requests).
  termsOfService: https://docs.olympex.io/legal/terms
  contact:
    name: Olympex partnerships
    email: partners@olympex.io
    url: https://docs.olympex.io
servers:
  - url: https://api-rest.olympex.io/api/v1
    description: Olympex REST API v1
security: []
tags:
  - name: Accounts
    description: Create an API account and manage its API keys.
  - name: Quotes
    description: Aggregated single-chain and cross-chain quotes.
  - name: Swap
    description: Unsigned transaction calldata for a quoted route.
  - name: TxStatus
    description: Track a cross-chain transfer after you broadcast it.
  - name: Transactions
    description: On-chain status of a transaction you broadcast.
  - name: Chains and tokens
    description: Enabled chains and the tokens listed on each.
  - name: Limit orders
    description: Orders that Olympex executes when the market reaches your price.
  - name: DCA
    description: Strategies that buy a token in equal orders over time.
  - name: Docs
    description: Machine-readable API description.
paths:
  /accounts/me/keys/rotate:
    post:
      tags:
        - Accounts
      summary: Rotate an API key
      description: >-
        Creates a new API key for the account and retires the key that signed
        the request. Olympex generates the new API key ID and secret key, and
        the passphrase stays the same. `graceful`, the default, keeps the old
        key valid for `gracePeriodSeconds` so you can deploy the new one without
        downtime; `compromised` revokes the old key at once. Only an `active`
        key can start a rotation. Send a new `Idempotency-Key` for each
        rotation. A retry with the same `Idempotency-Key`, the same body and the
        same signing key returns the same new key and secret key until
        `secretRecoverableUntil`, 15 minutes after the rotation. The response
        carries `Cache-Control: no-store`.
      operationId: rotateApiKey
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          description: >-
            Identifies one rotation, not one attempt. Generate a new UUID for
            each rotation, store it with the body before you send the request,
            and send the same value on every retry of that rotation. Up to 200
            characters, not empty. It isn't part of the signature.
          schema:
            type: string
            maxLength: 200
          example: 6f9c1d2e-8a4b-4c3d-9e1f-0a2b3c4d5e6f
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RotateApiKeyRequest'
            examples:
              graceful:
                summary: Scheduled rotation, 24-hour grace period
                value:
                  gracePeriodSeconds: 86400
                  mode: graceful
                  reason: scheduled rotation
              compromised:
                summary: 'Exposed secret key: revoke the old key at once'
                value:
                  mode: compromised
                  reason: secret exposed in a log
      responses:
        '200':
          description: >-
            The new API key. Store `secretKey` before you do anything else. The
            response carries `Cache-Control: no-store`: don't cache or log it.
          headers:
            Cache-Control:
              description: Always `no-store`.
              schema:
                type: string
                example: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RotateApiKeySuccessResponse'
              examples:
                graceful:
                  summary: Graceful rotation
                  value:
                    success: true
                    data:
                      apiKeyId: 00000000-0000-4000-8000-000000000001
                      secretKey: aol_DocsTestVector_notARealSecret_000000000
                      previousApiKeyId: 00000000-0000-4000-8000-000000000000
                      previousKeyExpiresAt: '2026-10-31T13:06:45.989Z'
                      secretRecoverableUntil: '2026-10-30T13:21:45.989Z'
                    meta:
                      requestId: GDxwAjXioAMEPWA=
                      version: v1
                      accountType: integrator
                      apiKeyId: 00000000-0000-4000-8000-000000000000
                compromised:
                  summary: Compromised rotation
                  value:
                    success: true
                    data:
                      apiKeyId: 00000000-0000-4000-8000-000000000002
                      secretKey: aol_DocsTestVector_notARealSecret_000000000
                      previousApiKeyId: 00000000-0000-4000-8000-000000000001
                      previousKeyExpiresAt: '2026-10-30T13:06:48.517Z'
                      secretRecoverableUntil: '2026-10-30T13:21:48.517Z'
                    meta:
                      requestId: GDxwZigJoAMEZ1A=
                      version: v1
                      accountType: integrator
                      apiKeyId: 00000000-0000-4000-8000-000000000001
        '400':
          description: >-
            Validation error (`VALIDATION_ERROR`) with empty `details`. The
            message is `"Idempotency-Key header is required"` when the header is
            missing, empty or longer than 200 characters, and `"Invalid rotation
            body"` when `mode` isn't `graceful` or `compromised`,
            `gracePeriodSeconds` is outside 60 to 604800, or `reason` is longer
            than 200 characters. Unknown body fields are ignored.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              examples:
                idempotencyKey:
                  summary: Missing Idempotency-Key
                  value:
                    success: false
                    error:
                      code: VALIDATION_ERROR
                      message: Idempotency-Key header is required
                      details: []
                    meta:
                      requestId: GDxv6g_loAMEZ7w=
                      version: v1
                      accountType: integrator
                      apiKeyId: 00000000-0000-4000-8000-000000000000
                body:
                  summary: Field out of range
                  value:
                    success: false
                    error:
                      code: VALIDATION_ERROR
                      message: Invalid rotation body
                      details: []
                    meta:
                      requestId: GDxv8jtfoAMEPEw=
                      version: v1
                      accountType: integrator
                      apiKeyId: 00000000-0000-4000-8000-000000000000
        '401':
          description: >-
            A signing header is missing. The gateway answers with
            `{"message":"Unauthorized"}` before your request reaches Olympex;
            the handler answers with the `UNAUTHORIZED` envelope when the
            authorizer context is missing.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/GatewayError'
                  - $ref: '#/components/schemas/ErrorResponse'
              example:
                message: Unauthorized
        '403':
          description: >-
            Authentication failed: unknown, revoked or expired API key, wrong
            passphrase, invalid signature, timestamp outside the ±300 s window,
            reused nonce, or inactive account (gateway
            `{"message":"Forbidden"}`).
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/GatewayError'
                  - $ref: '#/components/schemas/ErrorResponse'
              examples:
                gateway:
                  summary: Signature rejected by the gateway
                  value:
                    message: Forbidden
        '404':
          description: >-
            The key that signed the request isn't `active` (`NOT_FOUND` "Key not
            found"). A `rotating` key can't start another rotation, but it can
            retry its own with the same `Idempotency-Key` and body until
            `secretRecoverableUntil`. An unknown path or method also returns
            `NOT_FOUND`. If key management is unavailable, the three key
            endpoints return `NOT_FOUND` too: treat that as unavailable, not as
            a missing account.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              examples:
                notActive:
                  summary: Signed by a rotating key
                  value:
                    success: false
                    error:
                      code: NOT_FOUND
                      message: Key not found
                      details: []
                    meta:
                      requestId: GDxwJi0WIAMEPyA=
                      version: v1
                      accountType: integrator
                      apiKeyId: 00000000-0000-4000-8000-000000000000
                unknownRoute:
                  summary: Unknown path or method
                  value:
                    success: false
                    error:
                      code: NOT_FOUND
                      message: No route for GET /api/v1/quote
                      details: []
                    meta:
                      requestId: E7edogG4IAMEPYA=
                      version: v1
        '409':
          description: >-
            `CONFLICT`: the `Idempotency-Key` was already used with a different
            body or another signing key ("Idempotency key was reused with a
            different payload"), or a rotation of this key is already in
            progress. List the keys to see whether the rotation happened before
            you start a new one.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error:
                  code: CONFLICT
                  message: Idempotency key was reused with a different payload
                  details: []
                meta:
                  requestId: GDxwCjFXIAMEZQw=
                  version: v1
                  accountType: integrator
                  apiKeyId: 00000000-0000-4000-8000-000000000000
        '429':
          description: >-
            The account sent more than 5 rotation requests in an hour
            (`RATE_LIMIT_EXCEEDED`, "Too many key administration requests").
            Retries with the same `Idempotency-Key` count too. The limit is the
            same on every plan. This request didn't run: wait up to an hour,
            then send it again with the same `Idempotency-Key` and body. See
            [Rate limits](/authentication/limits#rate-limits).
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ErrorResponse'
                  - $ref: '#/components/schemas/GatewayError'
              example:
                success: false
                error:
                  code: RATE_LIMIT_EXCEEDED
                  message: Too many key administration requests
                  details: []
                meta:
                  requestId: GQ1D7ixyIAMEPHA=
                  version: v1
                  accountType: integrator
                  apiKeyId: 00000000-0000-4000-8000-000000000000
        '500':
          description: >-
            Olympex could not complete the request (`INTERNAL_ERROR`), or the
            gateway could not get a response (`{"message":"Internal Server
            Error"}`), which also happens on the first request after a quiet
            period. Retry with backoff. Retry the same rotation: same
            `Idempotency-Key`, same body, same signing key.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ErrorResponse'
                  - $ref: '#/components/schemas/GatewayError'
              example:
                success: false
                error:
                  code: INTERNAL_ERROR
                  message: Unexpected internal error
                  details: []
                meta:
                  requestId: GDxv-gPgIAMEPBA=
                  version: v1
                  accountType: integrator
                  apiKeyId: 00000000-0000-4000-8000-000000000000
        '503':
          description: >-
            Olympex can't check the key-management rate limit right now, so it
            refused the request and changed nothing (`SERVICE_UNAVAILABLE`).
            Retry after a few seconds, with the same `Idempotency-Key` and body.
            The gateway answers `503` with `{"message":"Service Unavailable"}`
            when a request runs past its timeout of about 30 seconds.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ErrorResponse'
                  - $ref: '#/components/schemas/GatewayError'
      security:
        - ApiKeyId: []
          ValueInfo: []
          Passphrase: []
          Signature: []
components:
  schemas:
    RotateApiKeyRequest:
      type: object
      properties:
        mode:
          type: string
          enum:
            - graceful
            - compromised
          default: graceful
          description: >-
            `graceful` keeps the old key valid for `gracePeriodSeconds`.
            `compromised` revokes it at once: use it only when the old secret
            key or passphrase may be exposed.
        gracePeriodSeconds:
          type: integer
          minimum: 60
          maximum: 604800
          default: 86400
          description: >-
            How long the old key keeps signing after a `graceful` rotation, in
            seconds: from 60 to 604800 (7 days). The default is 86400 (24
            hours).
        reason:
          type: string
          maxLength: 200
          description: >-
            Why you rotate, for Olympex's audit record. Up to 200 characters.
            Never put a credential in it.
    RotateApiKeySuccessResponse:
      type: object
      required:
        - success
        - data
        - meta
      properties:
        success:
          type: boolean
          enum:
            - true
        data:
          type: object
          required:
            - apiKeyId
            - secretKey
            - previousApiKeyId
            - previousKeyExpiresAt
            - secretRecoverableUntil
          properties:
            apiKeyId:
              type: string
              format: uuid
              description: >-
                The new API key ID. Send it in `x-api-key-id` with the new
                secret key and the same passphrase.
            secretKey:
              type: string
              description: >-
                The new secret key. Store it before you do anything else: only a
                retry of this rotation returns it again, until
                `secretRecoverableUntil`, and `GET /accounts/me/keys` never
                does.
            previousApiKeyId:
              type: string
              format: uuid
              description: The API key ID that signed this request.
            previousKeyExpiresAt:
              type: string
              format: date-time
              description: >-
                `graceful`: the old key signs requests until this time, then
                becomes `expired`. `compromised`: the time of the rotation; the
                old key is already `revoked`.
            secretRecoverableUntil:
              type: string
              format: date-time
              description: >-
                15 minutes after the rotation. Until then, a retry with the same
                `Idempotency-Key`, body and signing key returns this same key
                and secret key. After it, no endpoint returns the secret key
                again.
        meta:
          $ref: '#/components/schemas/Meta'
    ErrorResponse:
      type: object
      required:
        - success
        - error
        - meta
      properties:
        success:
          type: boolean
          enum:
            - false
        error:
          $ref: '#/components/schemas/ErrorBody'
        meta:
          $ref: '#/components/schemas/Meta'
    GatewayError:
      type: object
      required:
        - message
      description: >-
        Returned by the API gateway itself: `401` or `403` when the signed
        headers are missing or rejected, `429` when it throttles requests, and
        `500` or `503` when it can't get a response from Olympex in time. It has
        no `success`, `error` or `meta`.
      properties:
        message:
          type: string
          example: Forbidden
    Meta:
      type: object
      required:
        - requestId
        - version
      properties:
        requestId:
          type: string
          description: Unique ID for this request. Include it when you contact support.
        version:
          type: string
          default: v1
          description: API version that served the request.
        accountType:
          type: string
          description: >-
            Account type resolved by the signature check, for example
            `integrator`. Present when the request was authenticated; absent on
            the `404` for an unknown path or method.
        apiKeyId:
          type: string
          format: uuid
          description: >-
            The API key ID that signed the request. Present when the request was
            authenticated; absent on the `404` for an unknown path or method.
    ErrorBody:
      type: object
      required:
        - code
        - message
        - details
      properties:
        code:
          type: string
          description: >-
            Machine-readable error code. `VALIDATION_ERROR` (400),
            `UNAUTHORIZED` (401), `FORBIDDEN` (403), `NOT_FOUND` (404, also for
            an unknown path or method), `CONFLICT` (409), `NO_ROUTE` (422),
            `RATE_LIMIT_EXCEEDED` (429), `SERVICE_UNAVAILABLE` (503, from key
            rotation and revocation), and for 500: `QUOTE_ERROR`,
            `CROSS_CHAIN_QUOTE_ERROR`, `SWAP_ERROR`, `CROSS_CHAIN_SWAP_ERROR`,
            `SUPPORT_CHAIN_ERROR`, `ENABLED_CHAINS_ERROR`, `TOKEN_LIST_ERROR`,
            `TX_STATUS_ERROR`, `INTERNAL_ERROR`. Olympex can add codes: handle
            an unknown code by its HTTP status.
        message:
          type: string
          description: Human-readable summary. Don't parse it.
        details:
          type: array
          items:
            $ref: '#/components/schemas/ErrorDetail'
    ErrorDetail:
      type: object
      additionalProperties: true
      description: >-
        Validation errors carry `field` and `message`; other errors carry
        `message` only.
      properties:
        field:
          type: string
          description: >-
            Dot path of the invalid field, for example `params.chainId`. Empty
            for the top level.
        message:
          type: string
  securitySchemes:
    ApiKeyId:
      type: apiKey
      in: header
      name: x-api-key-id
      description: >-
        Your API key ID (UUID). See [Sign
        requests](https://docs.olympex.io/authentication/sign-requests).
    ValueInfo:
      type: apiKey
      in: header
      name: x-value-info
      description: >-
        Base64 of `timestamp + "\n" + nonce + "\n" + bodyHash`, where
        `timestamp` is Unix seconds, `nonce` is 24 new hexadecimal characters
        and `bodyHash` is the unpadded base64url SHA-256 of the canonical body.
    Passphrase:
      type: apiKey
      in: header
      name: x-passphrase
      description: Your account passphrase. Treat it like the secret key.
    Signature:
      type: apiKey
      in: header
      name: x-signature
      description: >-
        Lowercase hex HMAC-SHA256 (signature v2), keyed with your secret key
        string (UTF-8, not decoded), of seven lines joined with `\n`, with no
        trailing newline: `OLPX-HMAC-SHA256-V2`, `timestamp`, `nonce`, the
        uppercase method, `path`, `canonicalQuery` and `bodyHash`. `path` is the
        request path including `/api/v1`, without the query string, for example
        `/api/v1/limit-order/<id>`. `canonicalQuery` is the query parameters
        decoded (`+` is a space), sorted by key and then by value, re-encoded
        per RFC 3986 and joined with `&`, or the empty string when there is no
        query. Headers signed for one request are rejected on any other. See
        [Sign requests](https://docs.olympex.io/authentication/sign-requests).

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.