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.ioexport KEY=kaia_your_api_key
すべての通話には、いくつかのルールが適用されます:
- 金額は、トークンの最小単位で表された文字列です。小数点以下6桁の25 USDTは、
"25000000"となります。 - トークンはアドレスによって識別され、シンボルによって識別されることはありません。ネイティブトークン(ETH、KAIA、BNB、 …)
0x0000000000000000000000000000000000000000を使用してください。 - チェーンID:Kaiaは
8217、Ethereumは1、BNB Chainは56、Polygonは137、Arbitrumは42161、Baseは8453です。
どのプロバイダーも同様の形式で応答するため、ユーザーがどのプロバイダーを選んでも、コードの署名と送信方法は同じになります:
/quoteを使って見積もりを取得してください。- ブリッジの場合、選択したオファーを確定させて、そのトランザクションを取得してください。カイアでの交換品は、お見積りの通り発送の準備が整っております。
- 「承認」がある場合は、まずその金額を承認してください。その後、
transactionを送信してください。 swapIdとトランザクションハッシュを使用して、送金を追跡してください。 Wormholeの場合は、宛先チェーンで受け取り手続きを行ってください。
1. リストチェーン
# 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. トークンの一覧
# 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 } ]}
稼働中のルートを持つトークンのみが表示され、人気の高いものから順に並んでいます。 official は、カイアの発行元が上場しているトークンを示すため、同じシンボルを持つ類似のトークンと見分けることができます。金額の横に米ドル(USD)の価格を表示するには、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" } } ]}
offers には、各プロバイダーのオファーが、最も条件の良いものから順に一覧表示されます。各オファーには以下の内容が含まれています:
adaptorId:プロバイダーです。toAmount:ユーザーが受け取る金額を、宛先トークンの最小単位で表したものです。feeUsd、fees、およびdurationSecondsを使用して、オファーを比較します。 Kaiaでのスワップと同様に、プロバイダーがfeeUsdおよびdurationSecondsを指定しない場合、これらはnullとなります。needsCommit:ブリッジの場合はtrueとなります。トランザクションを取得するには、コミット を行う必要があります。 Kaiaでのスワップについては、すでにapprovalとtransactionが設定されているため、falseとします。詳しくは、Kaiaでのトークンスワップをご覧ください。claim:Wormhole用に設定されています。ユーザーはclaim.chainIdでクレームを行い、その際にガスが必要です。オファーと一緒に「通知」を表示してください。
kindは、2つのチェーン間では"bridge"となり、両方のチェーンIDが8217の場合は"swap"となります。
すべてのプロバイダーからの回答を待つのではなく、各プロバイダーが回答するたびにオファーを表示するには、同じ本文を POST /api/v1/quote/stream に送信してください。サーバーから送信されたイベントが返されます。オファーごとに1つの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がtokenをamountだけ取得することを許可する必要があります。常に正確な金額で、無制限になることはありません。transaction:ユーザーがソースチェーン上で署名して送信するものです。valueは wei 単位の10進数文字列です。Chainlink CCIP の場合、これにはネイティブトークンで支払われる CCIP 手数料が含まれます。ユーザーがネイティブコイン(ETH、KAIA、BNB、 …)を送金する場合、approvalは不要で、valueには送金金額が指定されます。swapId:トランザクションのハッシュを使用して、送金をどのように追跡するか。claim:オファーから転記しました。「ワームホール」に設定します。
コミットは1回のみ使用できます。ユーザーが何かを変更した場合は、新しいオファーを取得してください。 APIは、受信者が指定されていないオファー(receiver_required)、キーで許可されていないルート(route_not_allowed)、およびコミットを必要としないスワップオファーを拒否します。
5. 署名して送信する
「承認」がある場合は、まずトークンの承認を送信してください。その後、ユーザーは自身のウォレットで transaction に署名し、送信します。
この Node.js スクリプトは、ユーザーが選択したオファーに対して、コミットを行い、割り当て額が不足している場合はトークンを承認し、その後、送金を実行してマイニングが完了するのを待ちます。 KAIA_BRIDGE_API_KEY、PRIVATE_KEY、および RPC_URL(ソースチェーン用のRPC)を設定してください。ブラウザアプリでは、秘密鍵の代わりにユーザーのウォレットを使用し、コミットをバックエンド経由で送信することで、APIキーをバックエンドに保持するようにしてください。
- 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);
一部のウォレットでは、取引がマイニングされたことを報告しないことがあります。ウォレットのほかに、ソースチェーンについて信頼できる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 となるまで、数秒おきにポーリングを行ってください。請求が必要な送金(ワームホール)は、ユーザーが請求を行うまで 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 に署名して送信し、そこでガス代を支払います。 swap-status を使って、completed になるまで追跡してください。転送がまだWormholeによって署名されていない場合、またはすでに請求済みの場合は、APIは400を返します。
この Node.js スクリプトは、転送の準備が整うのを待ち、クレームを取得して送信します。 SWAP_ID をコミットの swapId に、SOURCE_TX_HASH を手順 5 で取得したデポジットのトランザクションハッシュに、DESTINATION_RPC_URL を宛先チェーンの RPC に設定してください。クレームはソースチェーン上ではなく、その宛先チェーンに送信されます。そのRPCが別のチェーン向けである場合、スクリプトは送信を行う前に停止します。
- 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);
ユーザーがページを再読み込みしたり、別のデバイスでアプリを開いたりした後など、まだ受け取り待ちの送金を表示するには:
curl -s "$BASE/api/v1/claims?address=0xUserWallet&adaptorId=wormhole" -H "X-API-Key: $KEY"
claims の各項目には、adaptorId、swapId、および sourceTxHash が含まれています。これらを /claim に、adaptorId、swapId、txHash として送信してください。
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が含まれます。承認を送信し、再度見積もりを提示した後、新しいオファーの「トランザクション」を送信してください。
エラーと制限
どのエラーも、同じ形をしています:
{ "success": false, "error": { "code": "unauthorized", "message": "Invalid or revoked API key" } }
| ステータス | 一般的なコード | どうすればよいでしょうか |
|---|---|---|
| 400 | invalid_request、receiver_required、missing_swap_id | リクエストを修正してください。 error.message と error.details には、何が問題なのかが記載されています。 |
| 401 | 無許可 | X-API-Key ヘッダーをご確認ください。 |
| 403 | route_not_allowed、feature_not_allowed | そのルートまたは機能は、お客様のアクセス設定に含まれていません。カイアさんに、それを変えてもらうようお願いしてください。 |
| 429 | リクエストが多すぎます:RateLimit-Reset に指定された秒数待機してから、再試行してください。 | |
| 502 | adaptor_error | プロバイダーは転送を開始できませんでした。新しいオファーをご覧になるか、別のオファーをお選びください。 |
すべてのレスポンスには、X-Request-ID ヘッダーが含まれています。 ecosystem@kaia.io に問題を報告する際は、その情報を併せてご記載ください。
完全な例
転送またはスワップ全体を実行する1つのNode.jsスクリプトです。ルートを確認し、すべてのオファーを出力した上で、最適なオファー(またはPROVIDERで指定されたオファー)を選択します。ブリッジの場合、オファーを実行し、必要に応じてトークンを承認し、転送を送信し、到着するまで追跡し、ワームホール転送の場合は宛先チェーン上で受け取ります。 Kaiaでのスワップの場合、必要に応じてトークンの承認を行い、再度価格を提示した上で、スワップを実行します。デフォルトでは少量のトークンが使用されます。別のルートに変更するには、ROUTE を変更してください。fromToken としてネイティブコイン(例:イーサリアムの ETH から Kaia の USDT へのスワップの場合、0x0000…0000)を指定するか、Kaia でのスワップの場合は両方のチェーン ID 8217 を指定してください。
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}`);}