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

# Payout keys & signing

> Sign every payout, sweep and cross-chain swap with your own Ed25519 key, so an API key alone can never move money, and retry safely with an Idempotency-Key.

Calls that move your customers' funds out need **two** things: your API key, and a signature
from a **payout key** that only your servers hold. Rach stores just the public half, so a leaked
API key, log line or proxy cannot move money.

These calls need a signature:

| Call | What it does |
| - | - |
| `POST /v1/payouts` | Send to outside addresses, one or many ([Payouts](https://docs.rach.finance/guides/caas-payouts.md)) |
| `POST /v1/sweeps` | Move every customer's balance on a chain to one address |
| `POST /v1/swaps/cross-chain` | Swap a customer's stablecoin across chains ([Swaps](https://docs.rach.finance/guides/caas-swaps.md)) |

## 1. Make a key and register it

```bash theme={null}
openssl genpkey -algorithm ed25519 -out rach-payout.pem   # private: stays on your server
openssl pkey -in rach-payout.pem -pubout                  # public: give this to Rach
```

In your **CaaS dashboard → Developers → Payout keys**, an owner or admin pastes the public key
(PEM, or the raw 32 bytes in base64 or hex) and gives it a name. You get a **key ID**. An API
key cannot register or revoke payout keys; only a signed-in owner or admin can.

You can hold several active keys, for example during a rotation. Revoking one takes effect
immediately.

## 2. Sign each request

Build this message: six lines joined by `\n`, with no trailing newline.

```text theme={null}
rach-payout-v1
POST
/caas/v1/payouts
1763715600
payout-2026-11-21-000187
3b7e…c9   ← lowercase hex SHA-256 of the exact body bytes you send
```

| Line | Value |
| - | - |
| 1 | `rach-payout-v1` |
| 2 | HTTP method, upper case |
| 3 | Path and query string: `/caas/v1/payouts` or `/v1/payouts` (both are accepted) |
| 4 | The `X-Rach-Timestamp` you send: Unix seconds |
| 5 | The `Idempotency-Key` you send |
| 6 | Hex SHA-256 of the raw request body |

Sign it with Ed25519 and send these headers:

| Header | Value |
| - | - |
| `X-API-Key` | Your API key |
| `X-Rach-Key-Id` | The payout key's ID |
| `X-Rach-Timestamp` | Unix seconds; must be within **5 minutes** of Rach's clock |
| `Idempotency-Key` | 8–128 printable characters, unique per operation |
| `X-Rach-Signature` | Base64 of the 64-byte signature |

```js Node.js theme={null}
import crypto from 'node:crypto';
import fs from 'node:fs';

const privateKey = crypto.createPrivateKey(fs.readFileSync('rach-payout.pem'));

export async function signedPost(path, payload, idempotencyKey) {
  const body = JSON.stringify(payload);            // sign exactly the bytes you send
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const bodyHash = crypto.createHash('sha256').update(body).digest('hex');
  const message = ['rach-payout-v1', 'POST', path, timestamp, idempotencyKey, bodyHash].join('\n');
  const signature = crypto.sign(null, Buffer.from(message), privateKey).toString('base64');

  return fetch(`https://api.rach.finance${path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': process.env.RACH_API_KEY,
      'X-Rach-Key-Id': process.env.RACH_PAYOUT_KEY_ID,
      'X-Rach-Timestamp': timestamp,
      'Idempotency-Key': idempotencyKey,
      'X-Rach-Signature': signature,
    },
    body,
  });
}

// await signedPost('/caas/v1/payouts', { items: [...] }, 'withdrawal-991');
```

```python Python theme={null}
import base64, hashlib, json, os, time, requests
from cryptography.hazmat.primitives.serialization import load_pem_private_key

private_key = load_pem_private_key(open("rach-payout.pem", "rb").read(), password=None)

def signed_post(path, payload, idempotency_key):
    body = json.dumps(payload, separators=(",", ":")).encode()
    timestamp = str(int(time.time()))
    message = "\n".join(["rach-payout-v1", "POST", path, timestamp, idempotency_key,
                         hashlib.sha256(body).hexdigest()]).encode()
    signature = base64.b64encode(private_key.sign(message)).decode()
    return requests.post(f"https://api.rach.finance{path}", data=body, headers={
        "Content-Type": "application/json",
        "X-API-Key": os.environ["RACH_API_KEY"],
        "X-Rach-Key-Id": os.environ["RACH_PAYOUT_KEY_ID"],
        "X-Rach-Timestamp": timestamp,
        "Idempotency-Key": idempotency_key,
        "X-Rach-Signature": signature,
    })
```

```go Go theme={null}
func signedPost(path string, payload any, idempotencyKey string, key ed25519.PrivateKey) (*http.Response, error) {
	body, _ := json.Marshal(payload)
	timestamp := strconv.FormatInt(time.Now().Unix(), 10)
	sum := sha256.Sum256(body)
	message := strings.Join([]string{"rach-payout-v1", "POST", path, timestamp, idempotencyKey, hex.EncodeToString(sum[:])}, "\n")
	req, _ := http.NewRequest("POST", "https://api.rach.finance"+path, bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-API-Key", os.Getenv("RACH_API_KEY"))
	req.Header.Set("X-Rach-Key-Id", os.Getenv("RACH_PAYOUT_KEY_ID"))
	req.Header.Set("X-Rach-Timestamp", timestamp)
	req.Header.Set("Idempotency-Key", idempotencyKey)
	req.Header.Set("X-Rach-Signature", base64.StdEncoding.EncodeToString(ed25519.Sign(key, []byte(message))))
	return http.DefaultClient.Do(req)
}
```

## 3. Retry without paying twice

The `Idempotency-Key` makes each operation happen once, however many times you send it:

* **The same key and the same request** returns the first answer again, with the header
  `Idempotency-Replayed: true`. Nothing new is sent. Retry after any timeout or `5xx` with the
  same key and a fresh timestamp and signature.
* **The same key with a different request** is refused with `409`.
* **While the first attempt is still running**, a repeat gets `409` ("still being processed").
  Wait a moment and retry.

Derive the key from your own record, such as your withdrawal ID, never from a random value
generated at send time. A crash and restart then retries the same operation instead of creating
a second one.

## Refusals

| Status | Cause |
| - | - |
| `401` | Missing or malformed headers, unknown or revoked key ID, timestamp more than 5 minutes off, or the signature does not match. Check that you hashed the exact body bytes sent, and the path. |
| `409` | The idempotency key was used for a different request, or the first attempt is still running. |
| `413` | Body larger than 2 MB. |

> [!NOTE]
>
> Webhooks from Rach to you also carry a header called `X-Rach-Signature`. That one goes the other
> way: an HMAC that Rach computes with your webhook secret. The two are unrelated.

Sandbox (test-mode) keys check the signature exactly as live keys do, then answer with a
simulated result and move nothing, so you can prove your signing before going live.


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