# HTTP

用一个 HTTP/1.1 请求发送已签名的交易；中继一接受交易就会应答。

## 身份验证

向发送路由发出的每个请求，都在 `api-key` 请求头中带上密钥：

```http
api-key: <key>
```

- 密钥是控制台（TX Landing）中的 base58 密钥。它也是你的 [QUIC](/docs/zh/tx-landing/quic/) 客户端证书所用的密钥。
- 中继只从请求头读取密钥。放在 URL 中的密钥（`?api-key=`）不会被读取。
- 缺少密钥或密钥未知时，应答 `401` `{"error":"unauthorized"}`。新密钥在约 60 秒内到达每个中继。
- 中继在端口 80 上监听，不使用 TLS，因此密钥以未加密方式传输。不提供 HTTPS；QUIC 是加密的。

## 路由

| 路由 | 请求体 | 密钥 |
|---|---|---|
| `POST /v1/sendTransaction` | JSON-RPC `sendTransaction`，交易为 base64 | 需要 |
| `POST /v1/sendRawTransaction` | 交易：字节配 `Content-Type: application/octet-stream`，或 base64 配 `Content-Type: text/plain` | 需要 |
| `GET /ping` | 无。应答 `200` `pong`。 | 不需要 |

路径须完全一致且区分大小写：其他任何路径（包括 `/`）均应答 `404`。不提供 HTTP/2。`/v1/sendTransaction` 只接受 `sendTransaction`；其他所有 JSON-RPC 方法均应答 `400`，代码为 `-32601`。

交易必须已签名，并带有至少 0.001 SOL (1,000,000 lamports) 的[小费](/docs/zh/tx-landing/endpoints/#tip-rule)（Pro 与 Scale 档位为 0.0005 SOL (500,000 lamports)）。示例使用法兰克福；任何[端点](/docs/zh/tx-landing/endpoints/)都可以。

## sendTransaction

**curl**

```sh
TX_BASE64='<your signed transaction, base64>'

curl http://fra.landing.soyas.xyz/v1/sendTransaction \
  -H "api-key: $SOYAS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"sendTransaction","params":["'"$TX_BASE64"'"]}'
```

**Python**

```python
import base64
import requests

session = requests.Session()  # keeps the connection open between requests

# tx: the signed transaction's wire bytes (solders: bytes(tx)).
def send_transaction(api_key: str, tx: bytes) -> str:
    resp = session.post(
        "http://fra.landing.soyas.xyz/v1/sendTransaction",
        headers={"api-key": api_key},
        json={
            "jsonrpc": "2.0",
            "id": 1,
            "method": "sendTransaction",
            "params": [base64.b64encode(tx).decode()],
        },
    )
    if resp.status_code != 200:
        raise RuntimeError(f"{resp.status_code}: {resp.text}")
    return resp.json()["result"]
```

**Go**

```go
import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
)

// tx: the signed transaction's wire bytes (solana-go: tx.MarshalBinary()).
func sendTransaction(apiKey string, tx []byte) (string, error) {
	body, _ := json.Marshal(map[string]any{
		"jsonrpc": "2.0",
		"id":      1,
		"method":  "sendTransaction",
		"params":  []any{base64.StdEncoding.EncodeToString(tx)},
	})
	req, _ := http.NewRequest("POST", "http://fra.landing.soyas.xyz/v1/sendTransaction", bytes.NewReader(body))
	req.Header.Set("api-key", apiKey)
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	var out struct {
		Result string          `json:"result"`
		Error  json.RawMessage `json:"error"`
	}
	if json.NewDecoder(resp.Body).Decode(&out); out.Result == "" {
		return "", fmt.Errorf("%s: %s", resp.Status, out.Error)
	}
	return out.Result, nil
}
```

**Rust**

```rust
use base64::Engine as _;
use serde_json::{json, Value};
use solana_sdk::transaction::VersionedTransaction;

async fn send_transaction(
    http: &reqwest::Client,
    api_key: &str,
    tx: &VersionedTransaction,
) -> anyhow::Result<String> {
    let tx_base64 = base64::engine::general_purpose::STANDARD.encode(bincode::serialize(tx)?);
    let resp = http
        .post("http://fra.landing.soyas.xyz/v1/sendTransaction")
        .header("api-key", api_key)
        .json(&json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "sendTransaction",
            "params": [tx_base64],
        }))
        .send()
        .await?;
    let status = resp.status();
    let body: Value = resp.json().await.unwrap_or_default();
    match body["result"].as_str() {
        Some(signature) => Ok(signature.to_string()),
        None => anyhow::bail!("{status}: {body}"),
    }
}
```

- 交易使用 base64（标准字母表，带填充）；base58 会被拒绝。选项（`skipPreflight`、`maxRetries`……）会被忽略。`id` 原样返回。
- 每个请求一笔交易：批量请求（JSON 数组）会被拒绝。

## sendRawTransaction

**curl**

```sh
# tx.bin: your signed transaction, serialized
curl http://fra.landing.soyas.xyz/v1/sendRawTransaction \
  -H "api-key: $SOYAS_API_KEY" \
  -H "Content-Type: application/octet-stream" \
  --data-binary @tx.bin
```

**Python**

```python
import requests

session = requests.Session()  # keeps the connection open between requests

# tx: the signed transaction's wire bytes (solders: bytes(tx)).
def send_raw_transaction(api_key: str, tx: bytes) -> str:
    resp = session.post(
        "http://fra.landing.soyas.xyz/v1/sendRawTransaction",
        headers={"api-key": api_key, "Content-Type": "application/octet-stream"},
        data=tx,
    )
    if resp.status_code != 200:
        raise RuntimeError(f"{resp.status_code}: {resp.text}")
    return resp.json()["signature"]
```

**Go**

```go
import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

// tx: the signed transaction's wire bytes (solana-go: tx.MarshalBinary()).
func sendRawTransaction(apiKey string, tx []byte) (string, error) {
	req, _ := http.NewRequest("POST", "http://fra.landing.soyas.xyz/v1/sendRawTransaction", bytes.NewReader(tx))
	req.Header.Set("api-key", apiKey)
	req.Header.Set("Content-Type", "application/octet-stream")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	var out struct {
		Signature string `json:"signature"`
		Error     string `json:"error"`
	}
	if json.NewDecoder(resp.Body).Decode(&out); out.Signature == "" {
		return "", fmt.Errorf("%s: %s", resp.Status, out.Error)
	}
	return out.Signature, nil
}
```

**Rust**

```rust
use serde_json::Value;
use solana_sdk::transaction::VersionedTransaction;

async fn send_raw_transaction(
    http: &reqwest::Client,
    api_key: &str,
    tx: &VersionedTransaction,
) -> anyhow::Result<String> {
    let resp = http
        .post("http://fra.landing.soyas.xyz/v1/sendRawTransaction")
        .header("api-key", api_key)
        .header("Content-Type", "application/octet-stream")
        .body(bincode::serialize(tx)?)
        .send()
        .await?;
    let status = resp.status();
    let body: Value = resp.json().await.unwrap_or_default();
    match body["signature"].as_str() {
        Some(signature) => Ok(signature.to_string()),
        None => anyhow::bail!("{status}: {body}"),
    }
}
```

`Content-Type` 是必需的。`;` 之后的参数会被忽略，base64 请求体两端的空白会被去除。

## 应答

`200`，`Content-Type: application/json`：

| 路由 | 应答体 |
|---|---|
| `POST /v1/sendTransaction` | `{"jsonrpc":"2.0","id":1,"result":"<signature>"}` |
| `POST /v1/sendRawTransaction` | `{"signature":"<signature>"}` |

- 签名是交易的第一个签名，以 base58 表示，与你发送的字节中的一致。
- 签名表示中继接受了交易并已将其交付发送，而不是交易已上链。请在链上检查。
- 中继不验证签名，不检查 blockhash 或余额，也不做模拟。
- 中继不去重：同一笔交易发送两次会被转发两次，并在你的[速率限制](/docs/zh/tx-landing/rate-limits/)中计两次。

所有错误状态码和应答体见[错误](/docs/zh/tx-landing/errors/)。

## 限制

| 项目 | 限制 |
|---|---|
| 请求体 | 16384 字节 |
| 交易 | 1232 字节（legacy、v0），4096 字节（v1） |
| 请求头 | 16 KiB，最多 64 个请求头 |
| 请求头部、请求体 | 各 5 秒 |
| 空闲连接 | 60 秒后关闭 |

## 保持连接

对每个端点保持一个持久连接，并在其上发送所有请求。
在建立连接后 5 秒内发送 `GET /ping`（不需要密钥，不受速率限制），之后发送间隔短于 60 秒，否则中继会关闭连接。
