跳轉至

兌換交易

網路與相容性

資源 值
API 基礎 URL https://api.testnet.sera.cx/api/v1
鏈 Sepolia(chainId 11155111)
Sera 合約 0x83475A1bD98a8DC2DCd507A747e4DC85da241D6e
Vault 合約 0x3c7945840bAE0d7e7f3824Ebccef1962629250F0
SOR 合約 0x83c1368110B640A729f3810De5FBe94b99aa5668

簽名原語。 所有交易型變更都是針對 Sera domain 的 EIP-712 類型化資料簽名。走 permit 路徑的充值使用 ERC-2612 Permit 擴充功能 — USDC、EURC、EURT 以及多數現代穩定幣支援,但並非所有 ERC-20 都支援;簽名前請呼叫 GET /permit/metadata 檢查。API key 管理使用 EIP-712 ManageApiKey payload。

已驗證客戶端。 Python eth_account >= 0.10 + requests;TypeScript ethers v6(signer.signTypedData)。已驗證支援 EIP-712 類型化資料的瀏覽器錢包:MetaMask、Rabby、Frame、Coinbase Wallet、Trust、Rainbow。Safe 多簽透過 EIP-1271 支援(訊息於鏈上驗證,而非透過 ecrecover)。

地址大小寫。 讀取類端點(/balances、/orders、/fills)將 owner_address 視為大小寫敏感 — 請傳入小寫形式。EIP-712 簽名 payload 接受 EIP-55 校驗和地址。

兌換為希望立即以最佳可用價格交換代幣的交易者提供即時執行。與限價單不同,兌換是 Fill-or-Kill — 要麼全額執行,要麼被拒絕。

兌換流程

sequenceDiagram
    participant User
    participant API as Sera API
    participant Chain as Ethereum

    User->>API: POST /swap/quote
    API-->>User: Quote (uuid, route_params)
    User->>User: Sign route_params (EIP-712)
    User->>API: POST /swap (uuid + signature)
    API->>Chain: Settlement
    Chain-->>API: Confirmation
    API-->>User: Success (trade_id)

步驟一:請求報價

import time, requests

quote = requests.post(
    "https://api.testnet.sera.cx/api/v1/swap/quote",
    json={
        "from_token":    "0x965d4b...d0e",    # USDC address
        "to_token":      "0xef64d1...40f",    # EURC address
        "from_amount":   "1000000000",      # 1000 USDC(6 位小數)
        "owner_address": "0xYOUR_WALLET",
        "recipient":     "0xYOUR_WALLET",   # 接收輸出代幣的地址(可以是另一個錢包)
        "expiration":    int(time.time()) + 3600,
        "gas_mode":      "receive_less",
    },
    timeout=10,
).json()
# quote["uuid"]           — 唯一報價識別碼
# quote["route_params"]   — 需要簽名的 EIP-712 參數
# quote["fee_breakdown"]  — Gas 費用詳情(gas_cost_usd、gas_cost_from_token)
const response = await fetch("https://api.testnet.sera.cx/api/v1/swap/quote", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    from_token:    "0x965d4b...d0e",    // USDC address
    to_token:      "0xef64d1...40f",    // EURC address
    from_amount:   "1000000000",      // 1000 USDC(6 位小數)
    owner_address: "0xYOUR_WALLET",
    recipient:     "0xYOUR_WALLET",   // 接收輸出代幣的地址(可以是另一個錢包)
    expiration:    Math.floor(Date.now() / 1000) + 3600,
    gas_mode:      "receive_less",
  }),
});

const quote = await response.json();
// quote.uuid            — 唯一報價識別碼
// quote.route_params    — 需要簽名的 EIP-712 參數
// quote.fee_breakdown   — Gas 費用詳情(gas_cost_usd、gas_cost_from_token)

報價參數

參數 類型 說明
from_token address 輸入代幣的 ERC-20 地址
to_token address 輸出代幣的 ERC-20 地址
from_amount string 以原始代幣單位表示的金額(例如 "1000000000" 代表 1000 USDC)
owner_address address 您的錢包地址
recipient address 輸出代幣的接收地址;可以是任何地址——設定為其他錢包即可將兌換輸出傳送給第三方。
expiration integer Unix 時間戳截止時間
gas_mode string "receive_less" 或 "pay_more"

報價回應

回應包含:

  • uuid — 此報價的唯一識別碼(提交時使用)
  • route_params — 要簽署的 EIP-712 Intent 結構欄位
  • fee_breakdown — Gas 費用詳情:gas_cost_usd 和 gas_cost_from_token
  • expires_at — 報價到期時間(報價為一次性使用)

步驟二:簽署報價

使用錢包透過 EIP-712 類型資料簽名對 route_params 進行簽署:

from eth_account import Account
from eth_account.messages import encode_typed_data

DOMAIN = {
    "name": "Sera",
    "version": "1",
    "chainId": 11155111,                                              # Sepolia
    "verifyingContract": "0x83475A1bD98a8DC2DCd507A747e4DC85da241D6e",
}

INTENT_TYPES = {
    "Intent": [
        {"name": "taker",                "type": "address"},
        {"name": "inputToken",           "type": "address"},
        {"name": "outputToken",          "type": "address"},
        {"name": "maxInputAmount",       "type": "uint256"},
        {"name": "minOutputAmount",      "type": "uint256"},
        {"name": "recipient",            "type": "address"},
        {"name": "initialDepositAmount", "type": "uint256"},
        {"name": "uuid",                 "type": "uint256"},
        {"name": "deadline",             "type": "uint48"},
    ]
}

signable  = encode_typed_data(DOMAIN, INTENT_TYPES, quote["route_params"])
signature = Account.from_key(PRIVATE_KEY).sign_message(signable).signature.hex()
import { Wallet } from "ethers";

const DOMAIN = {
  name: "Sera",
  version: "1",
  chainId: 11155111,                                                  // Sepolia
  verifyingContract: "0x83475A1bD98a8DC2DCd507A747e4DC85da241D6e",
};

const INTENT_TYPES = {
  Intent: [
    { name: "taker",                type: "address" },
    { name: "inputToken",           type: "address" },
    { name: "outputToken",          type: "address" },
    { name: "maxInputAmount",       type: "uint256" },
    { name: "minOutputAmount",      type: "uint256" },
    { name: "recipient",            type: "address" },
    { name: "initialDepositAmount", type: "uint256" },
    { name: "uuid",                 type: "uint256" },
    { name: "deadline",             type: "uint48"  },
  ],
};

const signature = await signer.signTypedData(DOMAIN, INTENT_TYPES, quote.route_params);

步驟三:執行兌換

提交已簽署的報價:

import json
from pathlib import Path

submit_body = {"uuid": quote["uuid"], "signature": "0x" + signature.removeprefix("0x")}
permit = quote.get("permit") or {}
if permit.get("permit_required") and permit.get("permit_supported"):
    typed = permit["eip712"]
    permit_message = encode_typed_data(typed["domain"], typed["types"], typed["message"])
    permit_sig = Account.from_key(PRIVATE_KEY).sign_message(permit_message).signature.hex()
    submit_body["permit_signature"] = "0x" + permit_sig.removeprefix("0x")
    submit_body["permit_deadline"] = int(typed["message"]["deadline"])
elif permit.get("permit_required") and int(permit["current_allowance_raw"]) < int(permit["value_raw"]):
    raise RuntimeError("Approve the quoted spender, confirm the transaction, then request a fresh quote")

journal = Path("swap-requests")
journal.mkdir(mode=0o700, exist_ok=True)
# hex gives an opaque quote ID a filename without interpreting path separators.
saved_path = journal / (quote["uuid"].encode().hex() + ".json")
with saved_path.open("x", encoding="utf-8") as saved:
    json.dump(submit_body, saved)
response = requests.post("https://api.testnet.sera.cx/api/v1/swap",
                         json=submit_body, timeout=10)
response.raise_for_status()
swap = response.json()
# Accepted is not chain-confirmed: track trade_id via the authenticated order API.
import { mkdirSync, writeFileSync } from "node:fs";

const submitBody: { uuid: string; signature: string; permit_signature?: string; permit_deadline?: number } = {
  uuid: quote.uuid, signature,
};
const permit = quote.permit;
if (permit?.permit_required && permit.permit_supported) {
  const typed = permit.eip712;
  submitBody.permit_signature = await signer.signTypedData(typed.domain, typed.types, typed.message);
  submitBody.permit_deadline = Number(typed.message.deadline);
} else if (permit?.permit_required && BigInt(permit.current_allowance_raw) < BigInt(permit.value_raw)) {
  throw new Error("Approve the quoted spender, confirm the transaction, then request a fresh quote");
}
mkdirSync("swap-requests", { recursive: true, mode: 0o700 });
const savedPath = `swap-requests/${Buffer.from(quote.uuid).toString("hex")}.json`;
writeFileSync(savedPath, JSON.stringify(submitBody), { flag: "wx", mode: 0o600 });
const result = await fetch("https://api.testnet.sera.cx/api/v1/swap", {
  method: "POST", headers: { "Content-Type": "application/json" },
  body: JSON.stringify(submitBody),
});
if (!result.ok) throw new Error(`swap: ${result.status}; reconcile saved request`);
const swap = await result.json();
// Accepted is not chain-confirmed: track trade_id via the authenticated order API.

Gas 模式

Swap 執行 Gas 包含在報價中,由 relayer 發送結算交易。獨立 approve 等用戶自行發送的交易仍需網絡 Gas,詳見費用。

請求報價時,您可以選擇 Gas 費用的應用方式:

模式 行為
receive_less Gas 費用從輸出中扣除。您花費的金額恰好是 from_amount,但收到的金額略少。
pay_more Gas 費用加到輸入中。您收到完整的報價金額,但花費略多。

報價回應中的 fee_breakdown 顯示確切的 Gas 費用,不會有意外。伺服器會計算調整後的金額 — 您的前端只需按原樣簽署 route_params 即可。

多段路由

Sera 會自動為您的兌換找到最佳路徑。如果直接交易對不存在,或多跳路徑能提供更好的定價,兌換會透過中間貨幣透明地進行路由。

例如,GBP → SGD 的兌換可能執行為:

  1. GBP → USD
  2. USD → SGD

這是原子性的 — 要麼所有段都成功,要麼全部不執行。

簽名價格約束與 MEV

報價和路由在鏈下計算,簽名的 maxInputAmount、minOutputAmount、uuid 和 deadline 約束結算,不符合時回滾。這減少了開放式內存池價格發現帶來的風險,但不表示免疫排序、服務干擾或其他攻擊。請核對簽名約束並參閱安全模型。

錯誤處理

分類業務錯誤可以使用 detail.error_code,其他失敗可能返回字符串 detail 或驗證數組。Exact Output 使用獨立的 detail.code 約定,不能假定所有 4xx 形狀相同。

結果 處理
200 已接受/緩存結果;用 trade_id 查詢結算,不能僅憑 HTTP 成功確認成交
400 / 422 查看驗證、簽名和資金錯誤;更改已准入請求前先核對
409 可能是提交中、請求內容衝突、報價過舊或准入前 permit nonce 衝突;查看響應並核對原訂單
410 報價不存在/過期或保存結果已清理;不能據此證明未執行
429 有 Retry-After 時遵守
超時 / 503 保留身份和完整已簽名 body,查詢後按需重試原 body

執行示例在發送前保存請求(TypeScript 使用 Node.js),請保持文件私有。結果未知時,不要重跑報價/簽名/生成身份流程來恢復。需要 approve 時,先確認授權再取得新報價;permit 路徑除 Intent 外,還需要簽署返回的 Permit。只有解決原請求狀態後才重新報價,詳見完整錯誤和重試規則。當前報價 API 沒有客戶端 slippage 參數,不要靜默更改返回的簽名約束。