跳至主要内容

使用 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。金额总是精确到分,绝非无限额。
  • transaction:用户在源链上签名并发送的内容。 value 以 wei 为单位,表示为十进制字符串;对于 Chainlink CCIP,该值包含以原生代币支付的 CCIP 手续费。当用户发送原生代币(ETH、KAIA、BNB、 …)时,无需进行 approval 操作,且 value 即为金额。
  • swapId:通过交易的哈希值,您可以追踪这笔转账。
  • claim:摘自报价。设置为“虫洞”。

一个提交只能使用一次。如果用户进行了任何更改,请获取新的报价。 API 会拒绝未指定接收方的报价(receiver_required)、您的密钥不允许的路线(route_not_allowed),以及无需确认的交换报价。

5. 签名并发送​

如果存在 approval,请先发送令牌授权请求。然后,用户使用自己的钱包对 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}`);
}

让这个页面变得更好