> For the complete documentation index, see [llms.txt](https://docs.hann.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hann.finance/zh/developers/integrator-kit.md).

# 集成指南

Hann Finance 集成的合约选择、钱包交易和事件索引

选择网络，使用公开合约地址及已验证 ABI，准备钱包调用并索引事件。[智能合约参考](/zh/developers/smart-contracts.md)列出地址和公开入口。

## 1. 选择网络、地址和 ABI

| 网络     | Chain ID | 用途                     |
| ------ | -------- | ---------------------- |
| Kaia   | `8217`   | 主网；Hann Finance 合约尚未部署 |
| Kairos | `1001`   | 集成测试用测试网               |

从[合约地址表](/zh/developers/smart-contracts.md)选择对应网络地址，在区块浏览器的已验证源码中获取 ABI。代理合约使用公开代理地址配合实现合约 ABI 调用。

将 chain ID、地址和 ABI 一起保存。通过公开 getter 读取各 CDP 分支抵押代币，以及各借贷储备的底层资产、aToken 和债务代币地址。

请求钱包签名前，确认 RPC 和钱包的 chain ID 均与合约所选网络一致。

### 读取 USDHN 余额

传入公开 USDHN 地址、chain ID、RPC URL 和钱包地址。函数验证 RPC 网络并返回代币基础单位余额。

```ts
import { createPublicClient, http, type Address } from "viem";

const balanceOfAbi = [
  {
    type: "function",
    name: "balanceOf",
    stateMutability: "view",
    inputs: [{ name: "account", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

export async function getUsdhnBalance({
  contractAddress,
  chainId,
  rpcUrl,
  walletAddress,
}: {
  contractAddress: Address;
  chainId: number;
  rpcUrl: string;
  walletAddress: Address;
}): Promise<bigint> {
  const client = createPublicClient({ transport: http(rpcUrl) });
  const rpcChainId = await client.getChainId();
  if (rpcChainId !== chainId) {
    throw new Error("RPC chain ID does not match the selected network");
  }
  return client.readContract({
    address: contractAddress,
    abi: balanceOfAbi,
    functionName: "balanceOf",
    args: [walletAddress],
  });
}
```

USDHN 为 18 位精度。合约数量保留为 `bigint`，用 `formatUnits(balance, 18)` 转换显示。其他资产按自身精度处理。原生 KAIA 基础单位为 10⁻¹⁸ KAIA。

## 2. 确认操作与使用者

| 操作            | 交易目标                                  | 授权或签名                                        |
| ------------- | ------------------------------------- | -------------------------------------------- |
| CDP 借款        | 分支 `BorrowerOperations` 或 Zapper      | 抵押品额度；具体 Zapper 入口决定 Permit2 用法              |
| 直接 CDP 赎回     | `CollateralRegistry.redeemCollateral` | Registry 直接销毁调用者 USDHN，无需额度                  |
| Earn 存款       | 分支 `StabilityPool.provideToSP`        | 注册池通过 `sendToPool` 移动 USDHN，直接存入无需 ERC-20 额度 |
| 借贷供应或还款       | `Pool`                                | 向 Pool 授权底层代币                                |
| 原生 KAIA 供应或还款 | `WKaiaGateway`                        | 在 `msg.value` 提供 KAIA                        |
| 原生 KAIA 提取    | `WKaiaGateway.withdrawKAIA`           | 向 gateway 授权 aWKAIA                          |
| 原生 KAIA 借款    | `WKaiaGateway.borrowKAIA`             | 对 gateway 执行浮动债务代币 `approveDelegation`       |
| bKAIA 存款或提取申请 | `LSTVault`                            | 存款提供原生 KAIA；`requestUnstakeByShares` 使用本人份额  |
| 兑换或 LP        | StableSwap Router 或 Zapper            | 输入代币或 LP 额度；许可入口使用 Permit2                   |

`approve` 设置 ERC-20 额度。代币 `permit` 使用域、nonce、使用者、数量和期限签名设置额度。Permit2 按入口要求自己的代币授权和签名。浮动债务代币 `approveDelegation` 授予借款权限。

先读取现有额度或委托，再申请所需数量，授权确认后继续。Zapper 组合协议操作和路径执行；此前完成的授权在路径回滚后保留。

直接 `BorrowerOperations` 调用开放 Trove 参数及管理设置；Zapper 增加原生币封装、Permit2 和路由。直接开立的仓位在使用杠杆管理关闭前，需正确移交管理权限。

## 3. 按当前状态准备交易

1. 读取仓位、所有人、分支或储备参数、精度和余额。
2. 按 ABI 构造操作。Trove 获取排序提示及一次性费用上限；浮动利率借贷使用模式 `2`。
3. 附加执行边界：StableSwap 最低输出或最高输入及期限、Zapper `maxDebt`、适用一次性费用限制。
4. 用准确发送者、参数和原生 value 执行 `simulateContract`。签名前展示预计抵押品、债务、到账量、费用和健康状况。模拟使用所选区块状态，执行使用交易所在区块状态。
5. 通过钱包提交并检查回执。回滚保留原协议状态并消耗 Gas。成功的 bKAIA 批量领取中仍可能存在单票据失败或重试。
6. 刷新受影响合约状态。分别跟踪回执确认和索引同步，直到新余额与仓位可用。

CDP 健康值使用 `getLatestTroveData(troveId).entireDebt`、`entireColl` 及当前分支价格和限制。借贷使用 `getUserAccountData(walletAddress)` 和储备配置，包括抵押设置与 eMode。将各产品清算条件与仓位一起显示。

### 闪电辅助路径

授权 Zapper 和 FlashSwapper 在执行中控制 add manager、remove manager 和 receiver。回调结算兑换、更新 Trove、偿还 DEX 池并恢复管理。报价使用配置的池和代币。合约检查闪电费上限、最终债务上限并退回路径剩余量。

`closeTroveByCollateral` 接受包含 `troveId` 和 `profitReceiver` 的元组，卖抵押品偿清实时债务并返还剩余量。其 ABI 没有用户提供的 `minOut`。准备此操作时展示抵押品出售结果和预计返还资产。

## 4. 索引仓位和结果

| 对象         | 事件与当前读取                                                                                                                |
| ---------- | ---------------------------------------------------------------------------------------------------------------------- |
| Trove 所有权  | 分支 `TroveNFT.Transfer`；`ownerOf(troveId)`                                                                              |
| Trove 记账   | `TroveUpdated`、`TroveOperation`、`BatchedTroveUpdated`、`BatchUpdated`；`getLatestTroveData`、`getTroveStatus`             |
| 清算与赎回      | TroveManager 的 `Liquidation`、`Redemption`、`RedemptionFeePaidToTrove`                                                   |
| Earn       | `DepositUpdated`、`DepositOperation`；当前存款、抵押品收益及 USDHN 收益 getter                                                        |
| 借贷         | `Supply`、`Withdraw`、`Borrow`、`Repay`、`LiquidationCall`、`ReserveDataUpdated`；储备和账户读取                                    |
| StableSwap | 池 `Swap`、`Mint`、`Burn`；路由 `LiquidityAdded`、`LiquidityRemoved` 和退款事件                                                    |
| bKAIA      | `Deposit`、`RequestedBatch`、`Requested`、`UnstakeShortfall`、`TicketStatusUpdated`、`ClaimPayout`、`ClaimManySummary` 和重试事件 |

以 chain ID、区块哈希、交易哈希和日志索引标识日志。每个 Trove ID 同时保存发出日志合约和分支。跟踪 NFT 转移和债务事件以更新所有权。应用新投影前，处理移除或替换的区块。

事件记录所在区块操作；利息和价格随后持续变化。结合事件历史与当前读取显示余额及健康状况。bKAIA 按票据状态和支付事件更新领取。`claimMany` 返回 `processed`、`totalPaid`、`totalFee`，并需核对各票据支付结果。

## 跨链转账

使用跨链提供商公开地址、已验证 ABI 和报价。签名前核对发送与目标链、代币、接收者、数量、费用和使用者。按报价指令授权或签名并提交发送链交易，再分别跟踪发送确认和目标交付。

USDHN 跨链调用使用 `USDHNOFTAdapter` 或远端 `USDHNOFT`，并配套 ABI、peer 配置和费用。OFT `send` 由这些跨链接口提供；`USDHNToken` 提供 ERC-20 接口。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.hann.finance/zh/developers/integrator-kit.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
