# SWQoS

> The staked (SWQoS) sendTransaction hostnames, how a send is routed, and when a staked send falls back.

Source: https://docs.constant-k.com/rpc/sending-transactions/staked/

Staked sends go through stake-weighted quality of service: a leader reserves 80% of its inbound transaction capacity for connections from staked validators and divides that share in proportion to stake, so staked traffic is less likely to be dropped when the leader is busy. Solana's [Stake-weighted Quality of Service](https://solana.com/docs/defi/stake-weighted-qos) guide covers the mechanism.

## Staked endpoints

The staked path is selected by hostname. There is no header, no extra parameter and no request to make first.

| Region                                | URL                                                                 |
| :------------------------------------ | :------------------------------------------------------------------ |
| <Flag region="newyork" /> New York    | `https://staked-rpc-newyork.constant-k.com/?api-key=YOUR_API_KEY`   |
| <Flag region="frankfurt" /> Frankfurt | `https://staked-rpc-frankfurt.constant-k.com/?api-key=YOUR_API_KEY` |
| <Flag region="amsterdam" /> Amsterdam | `https://staked-rpc-amsterdam.constant-k.com/?api-key=YOUR_API_KEY` |

The staked hostnames are included in every plan, and serve one transaction per call. Every other method works there too, against the same limits as the regular RPC hostname, so `getLatestBlockhash` and `getSignatureStatuses` calls do not have to move.

> **maxRetries and skipPreflight are fixed on staked hostnames:** `maxRetries` is always `0` and `skipPreflight` is always `true`. Setting them has no effect, so rebroadcasting is the client's own job, as in the example below. Everything else, including the transaction, `encoding` and `minContextSlot`, is passed through unchanged.

Rebroadcasting on the two paths differs. See [Rebroadcasting](https://docs.constant-k.com/rpc/sending-transactions/network/#rebroadcasting).

### Which path a send took

Every response from a staked hostname carries an `X-CK-Tx-Route` header. It is the only way to confirm that a send went over SWQoS. The [example](#example) below reads it.

| Value                              | Path taken                                                                 |
| :--------------------------------- | :------------------------------------------------------------------------- |
| Any value that is not listed below | The staked route. The value names it.                                      |
| Any value starting with `local_`   | The constant-k node. The suffix gives the reason, below.                   |
| `passthrough`                      | The request was not a `sendTransaction`, so the staked path did not apply. |

> **The header reports the route chosen, not the outcome at the leader:** A staked value means the transaction was handed to the staked route. If that route then returns an error, the transaction is sent from the constant-k node instead, and the response still carries the staked value, because the header is written before that happens. No RPC can report whether a leader included a transaction; `getSignatureStatuses` is what settles that.

### When a staked send falls back

A send that cannot take the staked path is not refused. The host sends the transaction from the constant-k node instead and returns the signature as usual, so a fallback is visible only in the header.

| Value                     | Reason                                                                                                                                                                 |
| :------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `local_tier`              | The plan does not include the staked path.                                                                                                                             |
| `local_cap_key`           | Over the plan's staked sends per second for that region.                                                                                                               |
| `local_cap_site`          | The region's shared staked capacity is full.                                                                                                                           |
| `local_budget`            | constant-k's own staked budget for the region is spent for the month. This is not a per-customer allowance.                                                            |
| `local_dedup`             | The same encoded transaction was sent in the last 60 seconds. See [Resending the same transaction](https://docs.constant-k.com/rpc/sending-transactions/network/#resending-the-same-transaction). |
| `local_badparams`         | The transaction parameter is not a string.                                                                                                                             |
| `local_oversize`          | The request body is over 8 KB.                                                                                                                                         |
| `local_off`, `local_hold` | The staked route is not taking sends at the moment.                                                                                                                    |

## Rates

| Plan         | Staked path (SWQoS) |
| :----------- | :------------------ |
| Free         | 1 rps               |
| Operator     | 1/s                 |
| Blade Runner | 5/s                 |
| Nexus        | 20/s                |

The figure is a rate per second, not a monthly allowance, and nothing accrues or expires. Staked sends also have a sustained rate, the most a key can average over 24 hours, all regions together. A key over it is slowed, never cut off. Limits are counted per region. See [Upstream limits](https://docs.constant-k.com/get-started/upstream-limits/).

## Example

**TypeScript**

```bash
npm install @solana/kit @solana-program/system @solana-program/compute-budget
```

```ts title="staked-send.ts"
import { readFileSync } from "node:fs";
import {
  address,
  appendTransactionMessageInstructions,
  createKeyPairSignerFromBytes,
  createSolanaRpc,
  createTransactionMessage,
  getBase64EncodedWireTransaction,
  lamports,
  pipe,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  signTransactionMessageWithSigners,
} from "@solana/kit";
import {
  getSetComputeUnitLimitInstruction,
  getSetComputeUnitPriceInstruction,
} from "@solana-program/compute-budget";
import { getTransferSolInstruction } from "@solana-program/system";

const endpoint = `https://staked-rpc-newyork.constant-k.com/?api-key=${process.env.CK_API_KEY}`;
const rpc = createSolanaRpc(endpoint);

// A Solana CLI keypair file (JSON array of 64 bytes)
const payer = await createKeyPairSignerFromBytes(
  new Uint8Array(JSON.parse(readFileSync(process.env.KEYPAIR_PATH!, "utf8"))),
);

const { value: latestBlockhash } = await rpc
  .getLatestBlockhash({ commitment: "confirmed" })
  .send();

const message = pipe(
  createTransactionMessage({ version: 0 }),
  (m) => setTransactionMessageFeePayerSigner(payer, m),
  (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
  (m) =>
    appendTransactionMessageInstructions(
      [
        getSetComputeUnitLimitInstruction({ units: 1_000 }),
        getSetComputeUnitPriceInstruction({ microLamports: 10_000n }),
        getTransferSolInstruction({
          source: payer,
          destination: address("RECIPIENT_ADDRESS"),
          amount: lamports(1_000_000n), // 0.001 SOL
        }),
      ],
      m,
    ),
);

const signedTx = await signTransactionMessageWithSigners(message);
const wireTx = getBase64EncodedWireTransaction(signedTx);

// fetch, so the X-CK-Tx-Route response header is visible
const response = await fetch(endpoint, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "sendTransaction",
    params: [wireTx, { encoding: "base64" }],
  }),
});

const { result, error } = await response.json();
if (error) {
  throw new Error(JSON.stringify(error));
}

console.log("Sent:", result, "Route:", response.headers.get("x-ck-tx-route"));
```

**cURL**

```bash
curl -sS -D - -o /dev/null "https://staked-rpc-newyork.constant-k.com/?api-key=YOUR_API_KEY" \
  -X POST -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"sendTransaction","params":["BASE64_SIGNED_TRANSACTION",{"encoding":"base64"}]}' \
  | grep -i "x-ck-tx-route"
```

**Python**

```python title="staked_send.py"
import base64
import os

import requests

URL = f"https://staked-rpc-newyork.constant-k.com/?api-key={os.environ['CK_API_KEY']}"

def send(signed_tx: bytes) -> tuple[str, str | None]:
    """signed_tx: a signed, serialized transaction, e.g. bytes(tx) from solders."""
    params = [base64.b64encode(signed_tx).decode(), {"encoding": "base64"}]
    response = requests.post(
        URL,
        json={"jsonrpc": "2.0", "id": 1, "method": "sendTransaction", "params": params},
        timeout=10,
    )
    body = response.json()
    if "error" in body:
        raise RuntimeError(body["error"])
    return body["result"], response.headers.get("x-ck-tx-route")
```
