Sử dụng API HTTP của Kaia Bridge Aggregator
Bất kỳ ngôn ngữ lập trình nào cũng có thể gọi API trực tiếp. Hướng dẫn này sẽ hướng dẫn bạn thực hiện quá trình chuyển dữ liệu bằng curl. Để biết thông tin chi tiết về từng trường và phản hồi, hãy tham khảo tài liệu tham khảo tương tác tại bridge-aggregator-api.kaia.io/api-docs; tài liệu OpenAPI gốc nằm tại /api-docs.json nếu bạn muốn tạo một client. Nếu bạn viết mã bằng TypeScript hoặc JavaScript, SDK sẽ thực hiện các bước này giúp bạn.
Trước khi bắt đầu
Bạn cần một khóa API (kaia_…); xem Lấy khóa. Hãy gửi khóa này trong tiêu đề X-API-Key trong mỗi yêu cầu /api/v1 và lưu trữ nó trên máy chủ của bạn.
export BASE=https://bridge-aggregator-api.kaia.io # QA: https://bridge-aggregator-api.qa.kaia.ioexport KEY=kaia_your_api_key
Mỗi cuộc gọi đều phải tuân thủ một số quy tắc sau:
- Số tiền là các chuỗi ký tự được biểu thị bằng đơn vị nhỏ nhất của token. 25 USDT, có 6 chữ số thập phân, là
"25000000". - Token được xác định bằng địa chỉ, chứ không bao giờ bằng ký hiệu. Các token gốc (ETH, KAIA, BNB, …) Sử dụng
0x0000000000000000000000000000000000000000. - ID chuỗi: Kaia là
8217, Ethereum là1, BNB Chain là56, Polygon là137, Arbitrum là42161, Base là8453.
Tất cả các nhà cung cấp đều trả lời theo cùng một định dạng, do đó mã của bạn sẽ ký và gửi theo cùng một cách bất kể người dùng chọn nhà cung cấp nào:
- Nhận báo giá bằng lệnh
/quote. - Đối với một cầu nối, hãy xác nhận đề nghị đã chọn để nhận giao dịch tương ứng. Một giao dịch hoán đổi trên Kaia đã sẵn sàng để thực hiện theo báo giá.
- Nếu có mục
approval, hãy phê duyệt số tiền đó trước. Sau đó, hãy gửigiao dịch. - Theo dõi giao dịch chuyển nhượng bằng
swapIdvà mã băm giao dịch. Đối với Wormhole, hãy thực hiện việc nhận thưởng trên chuỗi đích.
1. Danh sách chuỗi
# Every chain with a route to or from Kaiacurl -s "$BASE/api/v1/chains?limit=200" -H "X-API-Key: $KEY"# Only the chains reachable from Ethereumcurl -s "$BASE/api/v1/chains?fromChainId=1&limit=200" -H "X-API-Key: $KEY"
2. Danh sách các token
# Tokens that can leave Ethereumcurl -s "$BASE/api/v1/tokens?chainId=1&limit=200" -H "X-API-Key: $KEY"# What Ethereum USDT can become on Kaiacurl -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 } ]}
Chỉ những token có tuyến đường đang hoạt động mới được liệt kê, với các token phổ biến được xếp ở đầu danh sách. official là ký hiệu dành cho các token do Kaia phát hành và được niêm yết, nhờ đó bạn có thể phân biệt chúng với các token trông giống hệt nhưng có cùng ký hiệu. Để hiển thị giá bằng USD bên cạnh các số tiền, phương thức GET /api/v1/prices trả về giá theo mã chứng khoán và theo mã token ("<chainId>:<address>").
3. Xem các ưu đãi
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"}'
Luôn gửi sourceAddress và receiverAddress khi người dùng quyết định tiếp tục: một báo giá không có hai thông tin này chỉ mang tính chất hiển thị và không thể được xác nhận. slippageBps là tham số tùy chọn và là một chuỗi ký tự.
{ "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" } } ]}
offers liệt kê các ưu đãi của từng nhà cung cấp, sắp xếp theo thứ tự từ tốt nhất trở đi. Mỗi ưu đãi bao gồm:
adaptorId: nhà cung cấp.toAmount: số tiền người dùng nhận được, tính theo đơn vị nhỏ nhất của token đích.feeUsd,feesvàdurationSeconds, để so sánh các đề xuất.feeUsdvàdurationSecondscó giá trịnullkhi nhà cung cấp không cung cấp các thông tin này, như trong trường hợp các giao dịch hoán đổi trên Kaia.needsCommit:trueđối với một cầu nối, mà bạn phải xác nhận để lấy giao dịch của nó.falseđối với giao dịch hoán đổi trên Kaia, nơi đã có sẵn các thông tinapprovalvàtransaction; xem Hoán đổi token trên Kaia.claim: dành cho Wormhole. Người dùng thực hiện yêu cầu trênclaim.chainIdvà cần gas cho thao tác đó. Hiển thị cácthông báokèm theo ưu đãi.
kind là "bridge" khi kết nối giữa hai chuỗi và là "swap" khi cả hai ID chuỗi đều là 8217.
Để hiển thị các báo giá ngay khi từng nhà cung cấp trả lời thay vì phải đợi tất cả họ trả lời xong, hãy gửi cùng một nội dung yêu cầu đến POST /api/v1/quote/stream. Nó trả về các sự kiện do máy chủ gửi: một sự kiện offer cho mỗi đề nghị ({ "offer": …, "total": … }), sau đó complete với toàn bộ phản hồi ở trên.
4. Xác nhận ưu đãi đã chọn
Hãy gửi đề nghị mà người dùng đã chọn, y hệt như bạn đã nhận được:
curl -s "$BASE/api/v1/commit" -H "X-API-Key: $KEY" -H "Content-Type: application/json" \ -d '<the chosen offer object from offers>'
Mỗi nhà cung cấp đều trả về cùng một cấu trúc:
{ "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: nếu có, người dùng phải trước tiên cho phépspenderrútamounttoken. Số tiền luôn chính xác, không bao giờ là không giới hạn.giao dịch: nội dung mà người dùng ký và gửi trên chuỗi nguồn.valueđược tính bằng wei, dưới dạng chuỗi số thập phân; đối với Chainlink CCIP, giá trị này đã bao gồm phí CCIP, được thanh toán bằng token gốc. Khi người dùng gửi một loại tiền điện tử gốc (ETH, KAIA, BNB, …), sẽ không có bướcapprovalvàvaluechính là số lượng.swapId: cùng với mã băm của giao dịch, đây là cách bạn theo dõi giao dịch chuyển tiền.claim: sao chép từ đề nghị. Cài đặt cho Wormhole.
Một commit chỉ có thể được sử dụng một lần. Nếu người dùng thay đổi bất kỳ thông tin nào, hãy lấy các ưu đãi mới. API sẽ từ chối các đề nghị được đưa ra mà không có bên nhận (receiver_required), các tuyến đường mà khóa của bạn không cho phép (route_not_allowed) và các đề nghị hoán đổi, vốn không cần cam kết.
5. Ký và gửi
Nếu có approval, hãy gửi token approval trước. Sau đó, người dùng ký và gửi giao dịch bằng ví của mình.
Tập lệnh Node.js này thực hiện cả hai thao tác đối với đề nghị mà người dùng đã chọn: nó xác nhận đề nghị đó, phê duyệt token nếu hạn mức quá thấp, sau đó gửi giao dịch và chờ cho đến khi giao dịch được xác nhận. Đặt các biến KAIA_BRIDGE_API_KEY, PRIVATE_KEY và RPC_URL (một địa chỉ RPC cho chuỗi nguồn). Trong ứng dụng trình duyệt, hãy sử dụng ví của người dùng thay vì khóa riêng tư, và gửi lệnh commit qua hệ thống backend của bạn để khóa API được lưu trữ tại đó.
- ethers v6
- viem
// npm install ethersimport { 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);
// npm install viemimport { createPublicClient, createWalletClient, erc20Abi, http } from "viem";import { privateKeyToAccount } from "viem/accounts";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).const account = privateKeyToAccount(process.env.PRIVATE_KEY);const publicClient = createPublicClient({ transport: http(process.env.RPC_URL) });const walletClient = createWalletClient({ account, transport: http(process.env.RPC_URL) });// 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 ((await publicClient.getChainId()) !== 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 allowance = await publicClient.readContract({ address: token, abi: erc20Abi, functionName: "allowance", args: [account.address, spender], }); if (allowance < BigInt(amount)) { const approveHash = await walletClient.writeContract({ chain: null, address: token, abi: erc20Abi, functionName: "approve", args: [spender, BigInt(amount)], }); await publicClient.waitForTransactionReceipt({ hash: approveHash }); }}// 2. Sign and send the transfer, then wait for it to be mined.const hash = await walletClient.sendTransaction({ chain: null, to, data, value: BigInt(value) });console.log("Sent", hash, "swapId", commit.swapId);const receipt = await publicClient.waitForTransactionReceipt({ hash });if (receipt.status !== "success") throw new Error(`Reverted: ${hash}`);console.log("Confirmed in block", receipt.blockNumber);
Một số ví không bao giờ thông báo rằng một giao dịch đã được khai thác. Ngoài ví ra, hãy gửi yêu cầu đến một máy chủ RPC mà bạn tin tưởng để xác định chuỗi nguồn, và sử dụng kết quả trả về trước tiên:
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)
Kiểm tra mỗi 3 đến 5 giây. Nếu sau khoảng 10 phút vẫn không có phản hồi nào, hãy hiển thị cho người dùng một liên kết trình duyệt thay vì để họ gửi lại.
6. Theo dõi giao dịch
Đối với mỗi nhà cung cấp, hãy sử dụng swapId của commit và giá trị băm của giao dịch mà người dùng đã gửi:
curl -s "$BASE/api/v1/swap-status?adaptorId=<adaptorId>&swapId=<swapId>&txHash=<txHash>" -H "X-API-Key: $KEY"
status thay đổi theo thứ tự user_transfer_pending → in_progress → completed hoặc failed. sourceTxHash và destinationTxHash sẽ được điền tự động khi giao dịch diễn ra. Kiểm tra cứ sau vài giây cho đến khi trạng thái là completed hoặc failed. Một giao dịch chuyển tiền cần được xác nhận (Wormhole) sẽ ở trạng thái ready_to_claim cho đến khi người dùng xác nhận giao dịch đó.
Ngay sau khi gửi, trạng thái có thể chưa hiển thị. Hãy đợi vài giây rồi thử lại.
7. Yêu cầu chuyển khoản qua Wormhole
Khi trạng thái là ready_to_claim, hãy lấy giao dịch yêu cầu thanh toán:
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>" }'
Phản hồi có cấu trúc giống như một commit, với approval: null. Người dùng chuyển ví của mình sang transaction.chainId, sau đó ký và gửi transaction, đồng thời thanh toán phí gas tại đó. Hãy theo dõi trạng thái của nó bằng lệnh swap-status cho đến khi nó chuyển sang trạng thái completed. API sẽ trả về mã trạng thái 400 nếu giao dịch chưa được Wormhole ký xác nhận hoặc đã được xác nhận.
Tập lệnh Node.js này sẽ chờ cho đến khi quá trình chuyển khoản sẵn sàng, lấy thông tin yêu cầu và gửi đi. Đặt SWAP_ID thành giá trị swapId của commit, SOURCE_TX_HASH thành mã băm giao dịch nạp tiền từ bước 5, và DESTINATION_RPC_URL thành địa chỉ RPC của chuỗi đích: yêu cầu nhận tiền sẽ được gửi đến đó, chứ không phải trên chuỗi nguồn. Nếu lệnh RPC đó dành cho một chuỗi khối khác, skript sẽ dừng lại trước khi gửi.
- ethers v6
- viem
// npm install ethersimport { 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);
// npm install viemimport { createPublicClient, createWalletClient, http } from "viem";import { privateKeyToAccount } from "viem/accounts";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 transport = http(process.env.DESTINATION_RPC_URL);const publicClient = createPublicClient({ transport });const walletClient = createWalletClient({ account: privateKeyToAccount(process.env.PRIVATE_KEY), transport });if ((await publicClient.getChainId()) !== chainId) { throw new Error(`DESTINATION_RPC_URL must be for chain ${chainId}`);}const hash = await walletClient.sendTransaction({ chain: null, to, data, value: BigInt(value) });console.log("Claim sent", hash);const receipt = await publicClient.waitForTransactionReceipt({ hash });if (receipt.status !== "success") throw new Error(`Reverted: ${hash}`);console.log("Claimed in block", receipt.blockNumber);
Để hiển thị các giao dịch chuyển khoản vẫn đang chờ người dùng xác nhận, ví dụ như sau khi người dùng làm mới trang hoặc mở ứng dụng của bạn trên một thiết bị khác:
curl -s "$BASE/api/v1/claims?address=0xUserWallet&adaptorId=wormhole" -H "X-API-Key: $KEY"
Mỗi mục trong claims đều có các trường adaptorId, swapId và sourceTxHash. Gửi các giá trị này đến /claim dưới dạng adaptorId, swapId và txHash.
Trao đổi token trên Kaia
Khi cả hai ID chuỗi đều là 8217, thuộc tính kind của báo giá là "swap" và không có bước cam kết. sourceAddress là trường bắt buộc.
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"}'
Các đề nghị này có cấu trúc tương tự như các đề nghị cầu nối, với needsCommit: false. Phí của mỗi ưu đãi đã bao gồm phí của Kaia.
- Từ KAIA:
giao dịchtrong đề nghị này đã sẵn sàng. Gửi đi. - Từ một token như USDT: nếu hạn mức quá thấp, đề nghị sẽ có
approvalcho chính xác số tiền đó,transaction: nullvàrequoteAfterApproval: true. Gửi văn bản phê duyệt, lập lại báo giá, sau đó gửigiao dịchcủa đề nghị mới.
Lỗi và giới hạn
Mọi lỗi đều có cùng một dạng:
{ "success": false, "error": { "code": "unauthorized", "message": "Invalid or revoked API key" } }
| Trạng thái | Các mã thông dụng | Phải làm gì |
|---|---|---|
| 400 | yêu_cầu_không_hợp_lệ, cần_người_nhận, thiếu_mã_hoán_đổi | Hãy sửa lại yêu cầu. error.message và error.details cho biết lỗi là gì. |
| 401 | không được phép | Kiểm tra tiêu đề X-API-Key. |
| 403 | route_not_allowed, feature_not_allowed | Tuyến đường hoặc tính năng này không có trong cài đặt quyền truy cập của bạn. Hãy nhờ Kaia thay chúng đi. |
| 429 | Quá nhiều yêu cầu: hãy đợi trong số giây được chỉ định trong RateLimit-Reset, sau đó thử lại. | |
| 502 | lỗi bộ chuyển đổi | Nhà cung cấp không thể bắt đầu quá trình chuyển dữ liệu. Xem các ưu đãi mới hoặc chọn một ưu đãi khác. |
Mỗi phản hồi đều có tiêu đề X-Request-ID. Hãy đính kèm thông tin này khi bạn báo cáo sự cố tới ecosystem@kaia.io.
Ví dụ đầy đủ
Một tập lệnh Node.js thực hiện toàn bộ quá trình chuyển nhượng hoặc hoán đổi. Nó kiểm tra lộ trình, in ra tất cả các đề xuất và chọn đề xuất tốt nhất (hoặc đề xuất được chỉ định trong PROVIDER). Đối với một cầu nối, nó sẽ xác nhận đề nghị, phê duyệt token nếu cần thiết, thực hiện chuyển khoản, theo dõi giao dịch cho đến khi nó đến nơi và nhận token trên chuỗi đích nếu đó là giao dịch Wormhole. Đối với giao dịch hoán đổi trên Kaia, hệ thống sẽ xác nhận token nếu cần thiết, đưa ra báo giá lại và thực hiện giao dịch hoán đổi. Theo mặc định, hệ thống sẽ sử dụng một lượng nhỏ; hãy thay đổi ROUTE để chọn một lộ trình khác: sử dụng một loại tiền điện tử gốc làm fromToken (ví dụ: 0x0000…0000, tương ứng với việc hoán đổi từ ETH trên Ethereum sang USDT trên Kaia), hoặc cả hai ID chuỗi 8217 để thực hiện giao dịch hoán đổi trên Kaia.
Hiển thị toàn bộ đoạn mã Node.js
- ethers v6
- viem
// npm install ethers// KAIA_BRIDGE_API_KEY=… PRIVATE_KEY=… SOURCE_RPC_URL=… DESTINATION_RPC_URL=… node bridge.mjsimport { 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 oneconst 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}`);}
// npm install viem// KAIA_BRIDGE_API_KEY=… PRIVATE_KEY=… SOURCE_RPC_URL=… DESTINATION_RPC_URL=… node bridge.mjsimport { createPublicClient, createWalletClient, erc20Abi, http } from "viem";import { privateKeyToAccount } from "viem/accounts";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 oneconst account = privateKeyToAccount(process.env.PRIVATE_KEY);const clients = (url) => ({ read: createPublicClient({ transport: http(url) }), write: createWalletClient({ account, transport: http(url) }),});const source = clients(process.env.SOURCE_RPC_URL);const me = account.address;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(c, { token, spender, amount }) { const allowance = await c.read.readContract({ address: token, abi: erc20Abi, functionName: "allowance", args: [me, spender] }); if (allowance >= BigInt(amount)) return; const hash = await c.write.writeContract({ chain: null, address: token, abi: erc20Abi, functionName: "approve", args: [spender, BigInt(amount)] }); if ((await c.read.waitForTransactionReceipt({ hash })).status !== "success") throw new Error(`Approval reverted: ${hash}`);}// Send a transaction from the API ({ to, data, value, chainId }) and wait for it to be mined.async function send(c, { to, data, value, chainId }) { if ((await c.read.getChainId()) !== chainId) throw new Error(`Need an RPC for chain ${chainId}`); const hash = await c.write.sendTransaction({ chain: null, to, data, value: BigInt(value) }); console.log("Sent", hash); if ((await c.read.waitForTransactionReceipt({ hash })).status !== "success") throw new Error(`Reverted: ${hash}`); return 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(clients(process.env.DESTINATION_RPC_URL), claim.transaction); status.status = "completed"; } console.log(status.status === "completed" ? "Done: the tokens have arrived." : `Transfer ${status.status}`);}