> 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/developers/integrator-kit.md). Agents can also search and read this documentation through its [MCP server](https://docs.hann.finance/~gitbook/mcp).

# Integrator guide

Contract selection, wallet transactions, and indexing for Hann Finance integrations

Choose a network, use the published contract address and its verified ABI, then prepare wallet calls and index the resulting events. The [Smart Contracts reference](https://docs.hann.finance/developers/smart-contracts.md) lists addresses and public entrypoints.

## 1. Select the network, address, and ABI

| Network | Chain ID | Use                                              |
| ------- | -------- | ------------------------------------------------ |
| Kaia    | `8217`   | Mainnet; Hann Finance contracts are not deployed |
| Kairos  | `1001`   | Testnet for integration testing                  |

Select the address for the network from the [contract address table](https://docs.hann.finance/developers/smart-contracts.md). Obtain the matching ABI from that contract's verified source on the block explorer. For a proxy, call the published proxy address with the verified implementation's ABI.

Keep the chain ID, address, and ABI together. Read each CDP branch's collateral address and each Lending reserve's underlying, aToken, and debt-token addresses from their public contract getters.

Before requesting a wallet signature, confirm that the RPC and connected wallet both use the chain ID selected for the contract address.

### Read a USDHN balance

Pass the published USDHN address, chain ID, RPC URL, and wallet address. The function checks the RPC network and returns the balance in token base units.

```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 uses 18 decimals. Keep contract amounts as `bigint` and convert to display units with `formatUnits(balance, 18)`. For other assets, use that token's decimals. Native KAIA's base unit is 10⁻¹⁸ KAIA.

## 2. Resolve the operation and spender

| Operation                           | Transaction target                           | Approval or signature                                                                                    |
| ----------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| CDP borrowing                       | Branch `BorrowerOperations` or branch Zapper | Collateral allowance; the selected Zapper entrypoint determines Permit2 use                              |
| Direct CDP redemption               | `CollateralRegistry.redeemCollateral`        | The registry burns the caller's USDHN directly; no allowance is consumed                                 |
| Earn deposit                        | Branch `StabilityPool.provideToSP`           | The registered Stability Pool moves USDHN through `sendToPool`; direct deposits need no ERC-20 allowance |
| Lending supply or repay             | `Pool`                                       | Underlying token allowance to the Pool                                                                   |
| Native KAIA supply or repay         | `WKaiaGateway`                               | Native KAIA in `msg.value`                                                                               |
| Native KAIA withdrawal              | `WKaiaGateway.withdrawKAIA`                  | aWKAIA allowance to the gateway                                                                          |
| Native KAIA borrowing               | `WKaiaGateway.borrowKAIA`                    | Variable-debt-token `approveDelegation` to the gateway                                                   |
| bKAIA deposit or withdrawal request | `LSTVault`                                   | Native KAIA for deposits; owned shares for `requestUnstakeByShares`                                      |
| Swap or LP operation                | StableSwap Router or StableSwap Zapper       | Input token or LP allowance; Permit2 for the selected permit entrypoint                                  |

`approve` sets an ERC-20 allowance. A token's `permit` sets that allowance through a signature using the token's domain, nonce, spender, amount, and deadline. Permit2 has its own token-approval and signature requirements for the selected entrypoint. Variable-debt-token `approveDelegation` grants borrowing authority.

Read the existing allowance or delegation and request the amount required by the operation. Continue after the approval transaction is confirmed. A Zapper combines protocol operations and route execution; approvals completed before the route remain in place if the route reverts.

Direct `BorrowerOperations` calls expose the Trove parameters and manager settings. Zapper calls add native-token wrapping, Permit2, and routing. A position opened directly through `BorrowerOperations` needs the correct manager handover before using a leverage-managed close path.

## 3. Prepare the transaction from current state

1. Read the position, owner, branch or reserve parameters, asset decimals, and available balance.
2. Build the operation from the selected ABI. For a Trove, obtain sorted-list hints and the required upfront-fee bound. For variable-rate Lending, use interest-rate mode `2`.
3. Attach the entrypoint's execution bounds: StableSwap minimum output or maximum input and deadline, Zapper `maxDebt`, and the applicable upfront-fee limit.
4. Use `simulateContract` with the exact sender, arguments, and native value. Show the projected collateral, debt, received amount, fees, and position health before requesting the wallet signature. Simulation uses the RPC state at the simulated block; execution uses the state of the block that includes the transaction.
5. Submit through the wallet and check the receipt's status. A reverted transaction changes no protocol state and still spends gas. A successful bKAIA batch claim can contain ticket-level failures or retries.
6. Refresh the affected contract state. Track receipt confirmation separately from your indexer's synchronization until the new balances and positions are available.

For CDP health, use `getLatestTroveData(troveId).entireDebt` and `entireColl` with the branch's current price and limits. For Lending, use `getUserAccountData(walletAddress)` and the reserve configuration, including collateral settings and eMode. Display each product's liquidation condition alongside its position values.

### Flash-assisted routes

The authorized Zapper and FlashSwapper control the Trove's add manager, remove manager, and receiver during execution. The flash callback settles its swap, updates the Trove, repays the DEX pool, and restores management. Route quotes must use the configured pool and tokens. The contract checks the flash-fee cap and final-debt bound and refunds route leftovers.

`closeTroveByCollateral` takes a tuple containing `troveId` and `profitReceiver`. It sells collateral to repay the entire live debt and returns route leftovers to the receiver. Its ABI contains no user-supplied `minOut`. Show the collateral-sale result and returned assets when preparing this close operation.

## 4. Index positions and results

| Subject                      | Events and current reads                                                                                                                 |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Trove ownership              | Branch `TroveNFT.Transfer`; `ownerOf(troveId)`                                                                                           |
| Trove accounting             | `TroveUpdated`, `TroveOperation`, `BatchedTroveUpdated`, `BatchUpdated`; `getLatestTroveData`, `getTroveStatus`                          |
| Liquidations and redemptions | TroveManager `Liquidation`, `Redemption`, `RedemptionFeePaidToTrove`                                                                     |
| Earn                         | `DepositUpdated`, `DepositOperation`; compounded deposit, collateral gain, and USDHN yield getters                                       |
| Lending                      | `Supply`, `Withdraw`, `Borrow`, `Repay`, `LiquidationCall`, `ReserveDataUpdated`; reserve and account reads                              |
| StableSwap                   | Pool `Swap`, `Mint`, `Burn`; router `LiquidityAdded`, `LiquidityRemoved`, and refund events                                              |
| bKAIA                        | `Deposit`, `RequestedBatch`, `Requested`, `UnstakeShortfall`, `TicketStatusUpdated`, `ClaimPayout`, `ClaimManySummary`, and retry events |

Identify a log by chain ID, block hash, transaction hash, and log index. Store the emitting contract and branch with each Trove ID. Track NFT transfers as well as debt events so ownership changes reach the portfolio. Handle removed or replaced blocks before applying their new projections.

Events record operations at their block; current interest and prices can change without another account action. Combine event history with current reads for the displayed balance and position health. For bKAIA, use ticket status and payment events to update individual claims. `claimMany` returns `processed`, `totalPaid`, and `totalFee`; transaction success does not establish that every requested ticket paid out.

## Cross-chain transfers

Use the bridge provider's published addresses, verified ABI, and route quote. Match the source and destination chains, tokens, recipient, amount, fees, and spender before signing. Submit the quoted source-chain instruction with its required approval or signature, then track source confirmation and destination delivery separately.

USDHN cross-chain calls use a `USDHNOFTAdapter` or a remote `USDHNOFT` token with its matching ABI, peer configuration, and fees. The ERC-20 `USDHNToken` interface does not expose OFT `send`.


---

# 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/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.
