跳至主要內容

使用 Kaia Bridge Aggregator HTTP API

任何程式語言都可以直接呼叫該 API。本指南將逐步說明如何使用 curl 進行檔案傳輸。有關每個欄位和回應的詳細資訊,請參閱 bridge-aggregator-api.kaia.io/api-docs 中的互動式參考;若您想建立客戶端,原始的 OpenAPI 文件位於 /api-docs.json。如果您使用 TypeScript 或 JavaScript 編寫程式,SDK 會自動為您完成這些步驟。

開始之前​

您需要一個 API 金鑰(kaia_…);請參閱 取得金鑰。請在每次 /api/v1 請求中,於 X-API-Key 標頭中傳送此金鑰,並將其儲存於您的伺服器上。


export BASE=https://bridge-aggregator-api.kaia.io # QA: https://bridge-aggregator-api.qa.kaia.io
export KEY=kaia_your_api_key

每通電話都須遵守以下幾項規則:

  • 金額 是以代幣最小單位表示的字串。 25 USDT(小數點後有 6 位)的數值為 "25000000"。
  • 代幣是以地址來識別的,絕非以代幣符號來識別。原生代幣(ETH、KAIA、BNB、 …)請使用 0x0000000000000000000000000000000000000000。
  • 鏈 ID:Kaia 為 8217、以太坊 1、BNB Chain 56、Polygon 137、Arbitrum 42161、Base 8453。

每個服務供應商的回應格式都相同,因此無論使用者選擇哪個服務供應商,您的程式碼都會以相同的方式簽署並傳送:

  1. 使用 /quote 取得報價。
  2. 對於橋接器,請提交所選的報價以取得其交易。 Kaia 上的這筆交換交易已準備就緒,將按報價發送。
  3. 如果存在 approval,請先核准該筆金額。接著傳送該 transaction。
  4. 請使用 swapId 和交易雜湊值來追蹤這筆轉帳。對於 Wormhole,請在目標區塊鏈上進行領取。

1. 清單鏈​


# Every chain with a route to or from Kaia
curl -s "$BASE/api/v1/chains?limit=200" -H "X-API-Key: $KEY"
# Only the chains reachable from Ethereum
curl -s "$BASE/api/v1/chains?fromChainId=1&limit=200" -H "X-API-Key: $KEY"

2. 清單代號​


# Tokens that can leave Ethereum
curl -s "$BASE/api/v1/tokens?chainId=1&limit=200" -H "X-API-Key: $KEY"
# What Ethereum USDT can become on Kaia
curl -s "$BASE/api/v1/tokens?chainId=8217&fromChainId=1&fromToken=0xdAC17F958D2ee523a2206206994597C13D831ec7" \
-H "X-API-Key: $KEY"


{
"success": true,
"chainId": 8217,
"tokens": [
{
"chainId": 8217,
"symbol": "USDT",
"address": "0xd077a400968890eacc75cdc901f0356c943e4fdb",
"decimals": 6,
"isNative": false,
"providers": ["layerswap", "rhinofi"],
"featured": true,
"official": true
}
]
}

僅列出具有有效路由的代幣,並按熱門程度由高至低排序。 official 標示的是 Kaia 的發行方所發行的代幣,因此您可以藉此將它們與符號相同的仿冒代幣區分開來。若要在金額旁顯示美元價格,可透過 GET /api/v1/prices 依代碼及代幣查詢價格("<chainId>:<address>")。

3. 查看優惠​


curl -s "$BASE/api/v1/quote" -H "X-API-Key: $KEY" -H "Content-Type: application/json" -d '{
"fromChainId": 8217,
"toChainId": 137,
"fromToken": "0xd077a400968890eacc75cdc901f0356c943e4fdb",
"toToken": "0xc2132D05D31c914a87C6611C10748AEb04B58e8F",
"amount": "25000000",
"sourceAddress": "0xUserWallet",
"receiverAddress": "0xUserWalletOnPolygon",
"slippageBps": "50"
}'

當使用者準備繼續操作時,請務必傳送 sourceAddress 和 receiverAddress:若未包含這兩項的報價僅供顯示,無法實際執行。 slippageBps 為可選參數,且為字串。


{
"success": true,
"kind": "bridge",
"from": { "chainId": 8217, "address": "0xd077a400968890eacc75cdc901f0356c943e4fdb", "symbol": "USDT", "decimals": 6 },
"to": { "chainId": 137, "address": "0xc2132d05d31c914a87c6611c10748aeb04b58e8f", "symbol": "USDT0", "decimals": 6 },
"fromAmount": "25000000",
"offers": [
{
"adaptorId": "rhinofi",
"kind": "bridge",
"toAmount": "24972490",
"feeUsd": "0.04",
"fees": [],
"durationSeconds": 2,
"needsCommit": true,
"approval": null,
"transaction": null,
"requoteAfterApproval": false,
"claim": null,
"notices": [],
"offerData": { "…": "the provider's data; send it back unchanged" }
}
]
}

優惠 列出了各供應商的優惠,並按最佳優惠優先排序。每項優惠均包含:

  • adaptorId:提供者。
  • toAmount:使用者收到的金額,以目標代幣的最小單位為單位。
  • feeUsd、fees 及 durationSeconds,用以比較報價。當提供者未提供 feeUsd 和 durationSeconds 時,這兩項值即為 null,例如 Kaia 上的互換交易。
  • needsCommit:對於橋接器,此值為 true,您必須 提交 才能取得其交易。若要在 Kaia 上進行交換,且該交易已具備 approval 和 transaction,則設定為 false;詳見 在 Kaia 上交換代幣。
  • claim:設定為「蟲洞」。使用者在 claim.chainId 上提出索賠,並需要支付該處的 gas 費用。請在優惠資訊中顯示 notices。

kind 在兩條鏈之間為 "bridge",當兩條鏈的 ID 皆為 8217 時則為 "swap"。

若要隨著各供應商陸續回覆而即時顯示報價,而非等待所有供應商回覆完畢,請將相同的請求內容傳送至 POST /api/v1/quote/stream。它會傳回伺服器發送的事件:每個報價對應一個 offer 事件({ "offer": …, "total": … }),然後使用上述完整的回應來執行 complete。

4. 提交所選的報價​

請將使用者選定的優惠方案,完全按照您收到的內容發送出去:


curl -s "$BASE/api/v1/commit" -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
-d '<the chosen offer object from offers>'

每個提供者都會傳回相同的形狀:


{
"success": true,
"adaptorId": "rhinofi",
"swapId": "6b084fe06c7256127279b7d9",
"approval": {
"token": "0xd077a400968890eacc75cdc901f0356c943e4fdb",
"spender": "0x92650ddc…",
"amount": "25000000"
},
"transaction": {
"to": "0x92650ddc…",
"data": "0x…",
"value": "0",
"chainId": 8217
},
"claim": null
}

  • approval:若存在此參數,使用者必須先授權 spender 提取 amount 單位的 token。金額總是精確到分,絕非無限額。
  • 交易:使用者在源鏈上簽署並發送的內容。 value 以 wei 為單位,且為十進制字串;對於 Chainlink CCIP 而言,此數值包含以原生代幣支付的 CCIP 手續費。當使用者發送原生代幣(ETH、KAIA、BNB、 …)時,不會有 approval,而 value 即為該筆金額。
  • swapId:透過交易的哈希值,您可藉此 追蹤 該筆轉帳。
  • 聲明:摘自要約。設定為「蟲洞」。

一個提交只能使用一次。如果使用者進行任何變更,請取得新的優惠方案。 API 會拒絕未指定接收方的報價(receiver_required)、您的金鑰不允許的路徑(route_not_allowed),以及無需確認的交換報價。

5. 簽署並寄送​

如果涉及 授權,請先傳送授權令牌。接著,使用者會使用自己的錢包簽署並發送 transaction。

這個 Node.js 腳本會針對使用者所選擇的提議執行這兩項操作:先將其提交,若權限不足則批准該代幣,接著發起轉帳並等待其被挖礦確認。設定 KAIA_BRIDGE_API_KEY、PRIVATE_KEY 以及 RPC_URL(源鏈的 RPC)。在瀏覽器應用程式中,請使用使用者的錢包而非私密金鑰,並透過後端傳送提交資料,以便 API 金鑰保留在後端。


// npm install ethers
import { Contract, JsonRpcProvider, NonceManager, Wallet } from "ethers";
const API = "https://bridge-aggregator-api.kaia.io";
const headers = { "X-API-Key": process.env.KAIA_BRIDGE_API_KEY, "Content-Type": "application/json" };
// A wallet on the source chain (Kaia in this example). NonceManager keeps the
// approval and the transfer from reusing a nonce when they're sent back to back.
const wallet = new NonceManager(new Wallet(process.env.PRIVATE_KEY, new JsonRpcProvider(process.env.RPC_URL)));
const me = await wallet.getAddress();
// offer: the object the user chose from offers in step 3.
const commit = await fetch(`${API}/api/v1/commit`, { method: "POST", headers, body: JSON.stringify(offer) }).then((r) => r.json());
if (!commit.success) throw new Error(`${commit.error.code}: ${commit.error.message}`);
const { to, data, value, chainId } = commit.transaction;
if (Number((await wallet.provider.getNetwork()).chainId) !== chainId) throw new Error(`RPC_URL must be for chain ${chainId}`);
// 1. Approve the token first, if the provider needs it and the allowance is too low.
// A native coin (ETH, KAIA, …) never needs one: approval is null and value is the amount.
if (commit.approval) {
const { token, spender, amount } = commit.approval;
const erc20 = new Contract(token, [
"function allowance(address owner, address spender) view returns (uint256)",
"function approve(address spender, uint256 amount) returns (bool)",
], wallet);
if ((await erc20.allowance(me, spender)) < BigInt(amount)) {
await (await erc20.approve(spender, amount)).wait();
}
}
// 2. Sign and send the transfer, then wait for it to be mined.
const tx = await wallet.sendTransaction({ to, data, value: BigInt(value) });
console.log("Sent", tx.hash, "swapId", commit.swapId);
const receipt = await tx.wait();
if (receipt.status !== 1) throw new Error(`Reverted: ${tx.hash}`);
console.log("Confirmed in block", receipt.blockNumber);

有些錢包永遠不會回報交易已成功挖礦。除了錢包之外,還應向您信任的 RPC 查詢源鏈,並採用第一個回覆的結果:


curl -s -X POST "$YOUR_RPC" -H 'content-type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"eth_getTransactionReceipt","params":["<txHash>"]}'
# "result": null while pending, then "status": "0x1" (success) or "0x0" (failed)

每 3 至 5 秒進行一次輪詢。如果約 10 分鐘後仍無任何確認,請向使用者顯示一個檔案總管連結,而非讓他們再次傳送。

6. 追蹤轉帳​

針對每個提供者,請使用該提交的 swapId 以及使用者所發送的交易之雜湊值:


curl -s "$BASE/api/v1/swap-status?adaptorId=<adaptorId>&swapId=<swapId>&txHash=<txHash>" -H "X-API-Key: $KEY"

status 會依序經過 user_transfer_pending → in_progress → completed 或 failed。 sourceTxHash 和 destinationTxHash 會隨著轉帳進程自動填入。每隔幾秒進行一次輪詢,直到狀態變為 completed 或 failed 為止。需要申領的轉帳(Wormhole)會停留在 ready_to_claim 狀態,直到使用者進行申領為止。

發送後,狀態可能尚未顯示。請稍等幾秒鐘,然後再試一次。

7. 領取蟲洞轉帳​

當狀態為 ready_to_claim 時,取得領取交易:


curl -s "$BASE/api/v1/claim" -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
-d '{ "adaptorId": "wormhole", "swapId": "<swapId>", "txHash": "<source transaction hash>" }'

此回應的格式與提交相同,但 approval: null。使用者將錢包切換至 transaction.chainId,接著簽署並發送 transaction,並在該處支付 gas 費用。請使用 swap-status 追蹤其狀態,直到顯示為 completed 為止。若轉帳尚未經 Wormhole 簽署,或已遭他人申領,API 將回傳 400 狀態碼。

此 Node.js 腳本會等待轉帳準備就緒,取得索賠資訊並將其傳送出去。將 SWAP_ID 設為該提交的 swapId,將 SOURCE_TX_HASH 設為步驟 5 中存款的交易雜湊值,並將 DESTINATION_RPC_URL 設為目標鏈的 RPC 位址:該索賠將發送至該處,而非來源鏈上。如果該 RPC 屬於另一條鏈,腳本會在發送前停止執行。


// npm install ethers
import { JsonRpcProvider, Wallet } from "ethers";
const API = "https://bridge-aggregator-api.kaia.io";
const headers = { "X-API-Key": process.env.KAIA_BRIDGE_API_KEY, "Content-Type": "application/json" };
const transfer = { adaptorId: "wormhole", swapId: process.env.SWAP_ID, txHash: process.env.SOURCE_TX_HASH };
// 1. Wait until Wormhole has signed the transfer (about 1 to 20 minutes).
for (;;) {
const status = await fetch(`${API}/api/v1/swap-status?${new URLSearchParams(transfer)}`, { headers }).then((r) => r.json());
if (status.success === false) throw new Error(`${status.error.code}: ${status.error.message}`);
if (status.status === "ready_to_claim") break;
if (status.status === "completed") { console.log("Already claimed"); process.exit(0); }
if (status.status === "failed") throw new Error("The transfer failed");
await new Promise((r) => setTimeout(r, 15_000));
}
// 2. Get the claim transaction for the destination chain.
const claim = await fetch(`${API}/api/v1/claim`, { method: "POST", headers, body: JSON.stringify(transfer) }).then((r) => r.json());
if (!claim.success) throw new Error(`${claim.error.code}: ${claim.error.message}`);
// 3. Send it from a wallet on the destination chain, which pays the gas there.
const { to, data, value, chainId } = claim.transaction;
const wallet = new Wallet(process.env.PRIVATE_KEY, new JsonRpcProvider(process.env.DESTINATION_RPC_URL));
if (Number((await wallet.provider.getNetwork()).chainId) !== chainId) {
throw new Error(`DESTINATION_RPC_URL must be for chain ${chainId}`);
}
const tx = await wallet.sendTransaction({ to, data, value: BigInt(value) });
console.log("Claim sent", tx.hash);
const receipt = await tx.wait();
if (receipt.status !== 1) throw new Error(`Reverted: ${tx.hash}`);
console.log("Claimed in block", receipt.blockNumber);

若要顯示仍待領取的轉帳,例如在使用者重新載入頁面或在另一台裝置上開啟您的應用程式後:


curl -s "$BASE/api/v1/claims?address=0xUserWallet&adaptorId=wormhole" -H "X-API-Key: $KEY"

claims 中的每個項目都包含 adaptorId、swapId 和 sourceTxHash。將它們作為 adaptorId、swapId 和 txHash 傳送至 /claim。

在 Kaia 上交換代幣​

當兩條鏈的 ID 皆為 8217 時,該報價的 kind 為 "swap",且無需進行提交步驟。 sourceAddress 為必填欄位。


curl -s "$BASE/api/v1/quote" -H "X-API-Key: $KEY" -H "Content-Type: application/json" -d '{
"fromChainId": 8217,
"toChainId": 8217,
"fromToken": "0x0000000000000000000000000000000000000000",
"toToken": "0xd077a400968890eacc75cdc901f0356c943e4fdb",
"amount": "1000000000000000000",
"sourceAddress": "0xUserWallet"
}'

這些出價的格式與橋牌出價相同,且 needsCommit: false。每項報價的「費用」均包含 Kaia 的費用。

  • 來自 KAIA:該要約的 交易 已準備就緒。傳送吧。
  • 來自某種代幣(例如 USDT):若配額過低,該報價將包含一個金額與配額完全相符的 approval,且 transaction: null 以及 requoteAfterApproval: true。傳送核准通知,重新報價,然後傳送新報價的 transaction。

錯誤與限制​

每項錯誤的樣式都相同:


{ "success": false, "error": { "code": "unauthorized", "message": "Invalid or revoked API key" } }

狀態常用代碼該怎麼做
400invalid_request、receiver_required、missing_swap_id修正該請求。 error.message 和 error.details 說明了問題出在哪裡。
401未經授權請檢查 X-API-Key 標頭。
403route_not_allowed、feature_not_allowed該路線或景點未包含在您的存取設定中。請凱亞幫忙換掉它們。
429請求過多:請等待 RateLimit-Reset 中指定的秒數,然後重試。
502adaptor_error服務供應商無法啟動傳輸。查看新優惠,或選擇另一項優惠。

每個回應都包含一個 X-Request-ID 標頭。當您向 ecosystem@kaia.io 回報問題時,請一併提供此資訊。

完整範例​

一個能執行整個轉帳或兌換流程的 Node.js 腳本。它會檢查路徑、列印每項報價,並選擇最佳方案(或 PROVIDER 中指定的方案)。就橋接器而言,它會確認交易提案、在必要時核准代幣、發起轉帳、追蹤轉帳直至代幣送達,若屬 Wormhole 轉帳,則會在目標區塊鏈上領取代幣。在 Kaia 上進行兌換時,系統會視需要核准代幣、重新報價,並執行兌換。預設會使用少量代幣;若要變更為其他路徑,請修改 ROUTE:將 fromToken 設為原生代幣(例如 0x0000…0000,即以太坊上的 ETH 兌換為 Kaia 上的 USDT),或同時將兩條鏈的 ID 設為 8217,以在 Kaia 上進行兌換。

顯示完整的 Node.js 腳本

// npm install ethers
// KAIA_BRIDGE_API_KEY=… PRIVATE_KEY=… SOURCE_RPC_URL=… DESTINATION_RPC_URL=… node bridge.mjs
import { Contract, JsonRpcProvider, NonceManager, Wallet } from "ethers";
const API = "https://bridge-aggregator-api.kaia.io";
const headers = { "X-API-Key": process.env.KAIA_BRIDGE_API_KEY, "Content-Type": "application/json" };
// What to send: 5 USDT from Kaia to Polygon. For another route, replace ROUTE
// with one of the examples below it.
const ROUTE = {
fromChainId: 8217, fromToken: "0xd077a400968890eacc75cdc901f0356c943e4fdb", // USDT on Kaia
toChainId: 137, toToken: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", // USDT on Polygon
amount: "5000000", // 5 USDT (6 decimals)
};
// A native coin is 0x0000…0000. It needs no approval; the transaction's value is the amount.
// const ROUTE = { // 0.02 ETH on Ethereum to USDT on Kaia
// fromChainId: 1, fromToken: "0x0000000000000000000000000000000000000000",
// toChainId: 8217, toToken: "0xd077a400968890eacc75cdc901f0356c943e4fdb", amount: "20000000000000000",
// };
// const ROUTE = { // 100 KAIA to Wormhole-wrapped KAIA on BNB Chain (claimed on BNB Chain)
// fromChainId: 8217, fromToken: "0x0000000000000000000000000000000000000000",
// toChainId: 56, toToken: "0xea970e7b7d131ea36c3051c9ca11e785462fe00c", amount: "100000000000000000000",
// };
// const ROUTE = { // swap on Kaia: 1 KAIA to USDT
// fromChainId: 8217, fromToken: "0x0000000000000000000000000000000000000000",
// toChainId: 8217, toToken: "0xd077a400968890eacc75cdc901f0356c943e4fdb", amount: "1000000000000000000",
// };
const PROVIDER = process.env.PROVIDER; // optional: use this provider's offer instead of the best one
const source = new NonceManager(new Wallet(process.env.PRIVATE_KEY, new JsonRpcProvider(process.env.SOURCE_RPC_URL)));
const me = await source.getAddress();
async function api(path, body) {
const init = body ? { method: "POST", headers, body: JSON.stringify(body) } : { headers };
const json = await fetch(`${API}${path}`, init).then((r) => r.json());
if (json.success === false) throw new Error(`${path}: ${json.error.code}: ${json.error.message}`);
return json;
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Approve exactly what the API asks for, unless the allowance already covers it.
async function approveIfNeeded(wallet, { token, spender, amount }) {
const erc20 = new Contract(token, [
"function allowance(address owner, address spender) view returns (uint256)",
"function approve(address spender, uint256 amount) returns (bool)",
], wallet);
if ((await erc20.allowance(await wallet.getAddress(), spender)) >= BigInt(amount)) return;
const tx = await erc20.approve(spender, amount);
if ((await tx.wait()).status !== 1) throw new Error(`Approval reverted: ${tx.hash}`);
}
// Send a transaction from the API ({ to, data, value, chainId }) and wait for it to be mined.
async function send(wallet, { to, data, value, chainId }) {
if (Number((await wallet.provider.getNetwork()).chainId) !== chainId) throw new Error(`Need an RPC for chain ${chainId}`);
const tx = await wallet.sendTransaction({ to, data, value: BigInt(value) });
console.log("Sent", tx.hash);
if ((await tx.wait()).status !== 1) throw new Error(`Reverted: ${tx.hash}`);
return tx.hash;
}
// 1. Check the route reaches the destination token (match by address, not symbol).
const { tokens } = await api(`/api/v1/tokens?chainId=${ROUTE.toChainId}&fromChainId=${ROUTE.fromChainId}&fromToken=${ROUTE.fromToken}&limit=200`);
if (!tokens.some((t) => t.address.toLowerCase() === ROUTE.toToken.toLowerCase())) throw new Error("No route to that token");
// 2. Get every provider's offer and pick one.
const getOffer = async () => {
const { offers } = await api("/api/v1/quote", { ...ROUTE, sourceAddress: me, receiverAddress: me });
for (const o of offers) console.log(`${o.adaptorId}: receive ${o.toAmount}${o.feeUsd ? `, fee $${o.feeUsd}` : ""}${o.durationSeconds ? `, about ${o.durationSeconds}s` : ""}`);
const offer = PROVIDER ? offers.find((o) => o.adaptorId === PROVIDER) : offers[0];
if (!offer) throw new Error(`No offer from ${PROVIDER}`);
console.log("Using", offer.adaptorId);
return offer;
};
let offer = await getOffer();
if (!offer.needsCommit) {
// 3a. Swap on Kaia: the offer is ready to send.
if (offer.approval) {
await approveIfNeeded(source, offer.approval);
if (offer.requoteAfterApproval) offer = await getOffer(); // now with the swap transaction
}
await send(source, offer.transaction);
console.log("Done: swapped on Kaia.");
} else {
// 3b. Bridge: commit, approve the token if needed, then send the transfer.
const commit = await api("/api/v1/commit", offer);
if (commit.approval) await approveIfNeeded(source, commit.approval);
const txHash = await send(source, commit.transaction);
// 4. Track the transfer: the same three values for every provider.
const transfer = { adaptorId: commit.adaptorId, swapId: commit.swapId, txHash };
let status;
for (;;) {
try {
status = await api(`/api/v1/swap-status?${new URLSearchParams(transfer)}`);
console.log("Status:", status.status);
if (["completed", "failed", "ready_to_claim"].includes(status.status)) break;
} catch (err) {
console.log("Status not available yet:", err.message); // e.g. just sent: try again shortly
}
await sleep(15_000);
}
// 5. Wormhole only: claim on the destination chain, which pays the gas there.
if (status.status === "ready_to_claim") {
const claim = await api("/api/v1/claim", transfer);
await send(new Wallet(process.env.PRIVATE_KEY, new JsonRpcProvider(process.env.DESTINATION_RPC_URL)), claim.transaction);
status.status = "completed";
}
console.log(status.status === "completed" ? "Done: the tokens have arrived." : `Transfer ${status.status}`);
}

讓這個頁面變得更好