본문으로 건너뛰기

Kaia Bridge 애그리게이터 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

모든 전화 통화에는 몇 가지 규칙이 적용됩니다:

  • 금액은 토큰의 최소 단위로 표시된 문자열입니다. 소수점 이하 6자리를 갖는 25 USDT는 "25000000"입니다.
  • 토큰은 심볼이 아닌 주소로 식별됩니다. 네이티브 토큰 (ETH, KAIA, BNB, …) 0x0000000000000000000000000000000000000000을 사용하십시오.
  • 체인 ID: 카이아(Kaia)는 8217, 이더리움(Ethereum)은 1, BNB 체인은 56, 폴리곤(Polygon)은 137, 아비트럼(Arbitrum)은 42161, 베이즈(Base)는 8453입니다.

모든 제공업체가 동일한 형식으로 응답하므로, 사용자가 어떤 제공업체를 선택하든 코드는 동일한 방식으로 서명하고 전송합니다:

  1. /quote를 통해 견적을 받아보세요.
  2. 브리지의 경우, 선택한 오퍼를 확정하여 해당 트랜잭션을 획득합니다. Kaia의 스왑 상품은 제시된 대로 발송 준비가 완료되었습니다.
  3. 승인 항목이 있다면, 해당 금액을 먼저 승인하십시오. 그런 다음 transaction을 전송합니다.
  4. swapId와 트랜잭션 해시를 사용하여 이체를 추적하세요. 웜홀의 경우, 목적지 체인에서 청구하십시오.

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은 카이아의 발행사가 상장한 토큰을 나타내므로, 동일한 심볼을 가진 유사 토큰과 구별할 수 있습니다. 금액 옆에 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이며, 해당 브리지의 트랜잭션을 얻으려면 커밋해야 합니다. 이미 approval과 transaction이 설정된 Kaia의 스왑에 대해서는 false를 입력하세요. 자세한 내용은 Kaia에서 토큰 스왑하기를 참조하세요.
  • claim: Wormhole용으로 설정됨. 사용자는 claim.chainId에 대해 클레임을 제기하며, 이때 가스가 필요합니다. 제안과 함께 공지사항을 표시하세요.

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가 token의 amount를 인출할 수 있도록 승인해야 합니다. 항상 정확한 금액만 지급되며, 무제한으로 제공되는 일은 절대 없습니다.
  • 트랜잭션: 사용자가 소스 체인에서 서명하고 전송하는 내용. value는 위(wei) 단위의 십진수 문자열로 표시됩니다. 체인링크 CCIP의 경우, 여기에는 네이티브 토큰으로 지불되는 CCIP 수수료가 포함됩니다. 사용자가 네이티브 코인(ETH, KAIA, BNB, …)을 전송할 때는 approval이 필요하지 않으며, value는 전송 금액을 나타냅니다.
  • swapId: 거래 해시를 통해 이체를 추적하는 방법입니다.
  • claim: 제안서에서 복사함. 웜홀로 설정.

커밋은 한 번만 사용할 수 있습니다. 사용자가 내용을 변경하면 새로운 제안을 받아보세요. API는 수신자가 명시되지 않은 오퍼(receiver_required), 키에서 허용하지 않는 경로(route_not_allowed), 그리고 커밋이 필요 없는 스왑 오퍼를 거부합니다.

5. 서명하고 보내기​

승인이 있는 경우, 먼저 토큰 승인 요청을 전송하십시오. 그런 다음 사용자는 자신의 지갑을 통해 트랜잭션에 서명하고 전송합니다.

이 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 상태가 될 때까지 몇 초마다 폴링을 수행합니다. 청구가 필요한 전송(웜홀)은 사용자가 청구할 때까지 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에 서명하고 전송하며, 이때 가스 비용을 지불합니다. completed 상태가 될 때까지 swap-status를 통해 진행 상황을 확인하세요. 이전 작업이 아직 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에서: 해당 오퍼의 트랜잭션이 준비되었습니다. 보내주세요.
  • 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에 명시된 제안)을 선택합니다. 브리지의 경우, 오퍼를 확정하고, 필요한 경우 토큰을 승인한 뒤, 전송을 수행하며, 토큰이 도착할 때까지 추적하고, 웜홀 전송인 경우 대상 체인에서 토큰을 수령합니다. Kaia에서 스왑을 진행할 경우, 필요한 경우 토큰을 승인하고, 다시 호가를 확인한 뒤 스왑을 실행합니다. 기본적으로 소량이 사용됩니다. 다른 경로를 사용하려면 ROUTE를 변경하세요: fromToken으로 네이티브 코인(예: 이더리움의 ETH를 카이아의 USDT로 전환할 경우 0x0000…0000)을 지정하거나, 카이아에서 스왑을 수행할 경우 두 체인 ID 모두 8217을 지정하세요.

전체 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}`);
}

페이지를 개선해 주세요