> 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).

# Integrator guide

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

Integrations use a selected deployment profile, matching contract ABIs, wallet transactions, and the product data needed to show the result. The [Smart Contracts reference](/developers/smart-contracts.md) contains the contract IDs and public entrypoints.

## 1. Select the network and contract bundle

| Profile      | Network | Chain ID | Purpose                                              |
| ------------ | ------- | -------- | ---------------------------------------------------- |
| `kaia-prod`  | Kaia    | `8217`   | Mainnet production configuration; deployment pending |
| `kaia-qa`    | Kaia    | `8217`   | Mainnet QA configuration                             |
| `kairos-dev` | Kairos  | `1001`   | Promoted development deployment on testnet           |

Within the Hann Finance workspace, `@hann/contract-artifacts/registry` selects the profile from `HANN_CONTRACT_ARTIFACTS_PROFILE`. Browser builds use `NEXT_PUBLIC_HANN_CONTRACT_ARTIFACTS_PROFILE` with the matching `NEXT_PUBLIC_CHAIN_ID`. Set the profile before importing the package: its modules initialize contract definitions during import.

The private workspace package exports `getAddress(id)`, `getAbi(id)`, `getContractSnapshot()`, and domain modules. An external integration can load the selected profile's JSON snapshot and resolve each `abiRef` relative to `artifacts/contracts`. `GET /api/v1/contracts/snapshot` returns the API deployment's selected snapshot, including `activeProfile`, `activeChainId`, `contracts`, `aliases`, `runtime`, and source metadata. It returns ABI references rather than embedding the ABIs.

Preserve the profile, chain, contract ID, address, and ABI together. Confirm the RPC and wallet chain IDs against `activeChainId`; resolve a branch's collateral and a Lending reserve's asset from their own entries. Run-local files under `contracts/deploy/runs` and historical files under `docs/imported` are separate from the promoted runtime bundle.

### Read a USDHN balance

This TypeScript function runs within the Hann workspace and uses the selected artifact package. Select `kairos-dev` for the current testnet deployment. The caller supplies an RPC URL and a wallet address.

```ts
import { createPublicClient, http, type Address } from "viem";
import {
  getAbi,
  getAddress,
  getContractSnapshot,
} from "@hann/contract-artifacts/registry";

export async function getUsdhnBalance(rpcUrl: string, user: Address) {
  const client = createPublicClient({ transport: http(rpcUrl) });
  const snapshot = getContractSnapshot();
  const rpcChainId = await client.getChainId();
  if (rpcChainId !== snapshot.activeChainId) {
    throw new Error("RPC chain does not match the selected contract profile");
  }
  return client.readContract({
    address: getAddress("core.USDHN"),
    abi: getAbi("core.USDHN"),
    functionName: "balanceOf",
    args: [user],
  });
}
```

USDHN uses 18 decimals. Keep contract amounts as `bigint`; convert to display units at the UI boundary.

## 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                              |
| 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             | `lending-core.Pool`                                 | Underlying token allowance to the Pool                                                                   |
| Native KAIA supply or repay         | `lending-core.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 | `bkaia.LSTVault` with the matching entry-module ABI | 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                                  |

ERC-20 allowance, Permit2 signatures, and debt delegation grant different permissions. Read the existing allowance or delegation, request the amount required by the operation, and continue after its approval transaction is confirmed. A Zapper combines the protocol operation and route execution; a separate approval transaction can still precede it.

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`, as the app does.
3. Attach the entrypoint's execution bounds: StableSwap minimum output or maximum input and deadline, Zapper `maxDebt`, and the applicable upfront-fee limit.
4. Simulate the exact call with the sender, arguments, and native value. Show the resulting collateral, debt, received amount, fees, and position health before requesting the wallet signature.
5. Submit through the wallet and read the receipt. A reverted transaction changes no protocol state; a successful bKAIA batch claim can contain ticket-level failures or retries.
6. Refresh the affected product state. Keep receipt confirmation and API/indexer synchronization as separate states until the new projection is available.

For CDP health, use `getLatestTroveData().entireDebt` and `entireColl` with the branch's current price and limits. For Lending, use `getUserAccountData()` and the reserve configuration, including collateral settings and eMode. Display the liquidation condition alongside the position values; avoid applying CDP collateral-ratio rules to Lending accounts.

### 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({troveId, profitReceiver})` repays the entire live debt by selling collateral. Its ABI contains no user-supplied `minOut`. Model that exact close behavior separately from an ordinary bounded swap or debt-repayment close.

## 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`, `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 processed ticket IDs and payment events to update claims; transaction success alone does not establish that every requested ticket paid out.

## Product data and bridge execution

The app consumes generated `@hann/api-client` schemas for product data and `@hann/contract-artifacts` for wallet calls. Endpoint-supported live contract views supply transaction-critical fields during an API outage. Derived history, points, and transaction acknowledgements remain API-backed.

The Bridge API supplies supported chains, tokens, spender addresses, quotes, and the exact source-chain execution instruction. The product's Rhino route accepts supported USDT or USDC sources and delivers Kaia USDT. Submit the quoted `depositWithId` instruction with its matching approval and commitment, then track source confirmation and destination completion. A USDHN OFT `send` is a separate token interface with its own peer and fee configuration.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
