> 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/smart-contracts.md).

# Smart contracts

Deployment profiles, contract IDs, functions, events, and account state

Hann Finance's generated contract bundle pairs each contract address with its chain, ABI, deployment metadata, and source. Integrations resolve contracts by **profile and contract ID**. Lending, CDP, staking, and swaps each retain their own token and accounting addresses.

## Deployment profiles and ABI lookup

| Profile      | Network | Chain ID | `canonical` |
| ------------ | ------- | -------- | ----------- |
| `kaia-prod`  | Kaia    | `8217`   | `true`      |
| `kaia-qa`    | Kaia    | `8217`   | `false`     |
| `kairos-dev` | Kairos  | `1001`   | `false`     |

Each profile contains `profile.json`, `snapshot/kaia.json`, `addresses/kaia.json`, and `watch-targets/kaia.json`. The filename `kaia.json` is retained in the Kairos profile; the metadata specifies its actual chain `1001`.

`GET /api/v1/contracts/snapshot` serves the API's selected snapshot. Its `contracts[id]` entry contains `address`, `chainId`, `abiRef`, `abiHash`, `source`, and deployment metadata. Resolve `abiRef` from the `artifacts/contracts` package root. The TypeScript registry exposes `getAddress(id)`, `getAbi(id)`, and `getOptionalContract(id)` for the selected profile. Optional frontend contracts return `active: false` and `address: null` when that capability has no active contract.

### Kaia mainnet addresses

The following contracts have not been deployed on Kaia mainnet. Addresses are **TBA (to be announced)** and will be published after deployment.

| Contract ID                 | Address |
| --------------------------- | ------- |
| `core.USDHN`                | TBA     |
| `core.CollateralRegistry`   | TBA     |
| `core.HNKAIA`               | TBA     |
| `lending-core.Pool`         | TBA     |
| `lending-core.WKaiaGateway` | TBA     |
| `bkaia.LSTVault`            | TBA     |
| `bkaia.LSTToken`            | TBA     |
| `stableswap.Router`         | TBA     |
| `stableswap.UsdtUsdhnPool`  | TBA     |

Resolve Lending assets from `lending-core.Asset.<symbol>` or the selected reserve configuration. For example, this profile's `lending-core.Asset.BKAIA` differs from `bkaia.LSTToken`; `lending-core.Asset.HNKAIA` differs from `core.HNKAIA`. The symbol is a display name, so the selected domain's address determines which token the call uses.

## CDP core

Branch IDs in the generated frontend interface are `0` for KAIA, `1` for HNKAIA, and `2` for EARNUSDT. Their artifact prefixes are `core.WKAIA`, `core.HNKAIA`, and `core.EARNUSDT`.

| Contract ID or suffix                        | Public interface and state                                                                                                                                          |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `core.USDHN`                                 | Token balance, allowance, transfers, and permit: `balanceOf`, `allowance`, `approve`, `transfer`, `permit`                                                          |
| `core.CollateralRegistry`                    | `collateralConfig`, `getToken`, `getTroveManager`, `isCollateralActive`, redemption fee getters, and `redeemCollateral`                                             |
| `<branch>.BorrowerOperations`                | `openTrove`, `openTroveAndJoinInterestBatchManager`, `addColl`, `withdrawColl`, `withdrawUSDHN`, `repayUSDHN`, `adjustTrove`, `adjustZombieTrove`, and `closeTrove` |
| `<branch>.TroveManager`                      | `getLatestTroveData`, `getTroveStatus`, `getCurrentICR`, `getLatestBatchData`, `batchLiquidateTroves`, and `urgentRedemption`                                       |
| `<branch>.TroveNFT`                          | ERC-721 `ownerOf`, ownership transfers, and `Transfer` events                                                                                                       |
| `<branch>.SortedTroves`                      | Interest-rate ordering and insertion hints                                                                                                                          |
| `<branch>.AddressesRegistry`                 | Branch contract references and configured parameters                                                                                                                |
| `<branch>.PriceFeed`                         | Price fetching, last-good price, and oracle state                                                                                                                   |
| `<branch>.ActivePool` / `DefaultPool`        | Active collateral and debt; redistributed collateral and debt                                                                                                       |
| `<branch>.CollSurplusPool` / `GasPool`       | Claimable collateral surplus and liquidation gas compensation                                                                                                       |
| `core.HintHelpers` / `core.MultiTroveGetter` | Fee and insertion-hint calculations; batch position reads                                                                                                           |
| `core.RedemptionHelper`                      | `simulateRedemption`, `truncateRedemption`, and redemption with per-branch minimum outputs                                                                          |

`<branch>` means one of the three complete artifact prefixes above. Zappers use `zappers.<symbol>.Zapper`, `zappers.<symbol>.LeverageZapper`, and `zappers.<symbol>.FlashSwapper`.

The current token source, `USDHNToken.sol`, implements ERC-20 and permit. Cross-chain transfers use `USDHNOFTAdapter` for canonical-chain lock/unlock and `USDHNOFT` for remote-chain mint/burn. The recorded `kaia-prod` ABI for `core.USDHN` also contains `quoteOFT`, `quoteSend`, and `send` from its source artifact. Those entries do not belong to the current `USDHNToken` implementation. An OFT integration must use the deployed adapter or remote token, its matching ABI, and its peer and endpoint configuration.

### Borrowing, interest, and redemption parameters

`BorrowerOperations.openTrove` takes the owner, owner index, collateral amount, requested USDHN amount, upper and lower hints, annual interest rate, maximum upfront fee, add manager, remove manager, and receiver. `openTroveAndJoinInterestBatchManager` replaces the individual interest-rate field with a batch manager in its parameter struct.

Interest control uses `adjustTroveInterestRate`, `setInterestIndividualDelegate`, `setInterestBatchManager`, `removeFromBatch`, and `switchBatchManager`. `addManagerOf` and `removeManagerReceiverOf` expose delegated operation and receiver settings. Read `MCR`, `CCR`, `SCR`, and `BCR` from the branch's BorrowerOperations.

Ordinary cross-branch redemption enters through `CollateralRegistry.redeemCollateral(usdhnAmount, maxIterationsPerCollateral, maxFeePercentage)`. The registry selects active, redeemable branches and burns the amount actually redeemed. An iteration limit of `0` means unlimited traversal, as used by the app; a bounded traversal can produce a partial redemption. TroveManager's five-argument `redeemCollateral` is called by the registry; shutdown redemption uses `urgentRedemption`.

`RedemptionHelper.redeemCollateral(usdhnAmount, maxIterationsPerCollateral, maxFeePercentage, minCollRedeemed)` adds minimum collateral outputs for each branch. This helper pulls USDHN with `transferFrom`, so its caller grants USDHN allowance to the helper. The minimum-output array follows the helper's branch order; unmet bounds revert the transaction, and remaining USDHN is refunded. `simulateRedemption` and `truncateRedemption` are non-view functions because price reads can update cached state; use RPC simulation to obtain their previews.

### Trove status and latest debt

| Value | Status                | Meaning                                                                              |
| ----- | --------------------- | ------------------------------------------------------------------------------------ |
| `0`   | `nonExistent`         | No position exists for the ID                                                        |
| `1`   | `active`              | Open position participating in normal operations                                     |
| `2`   | `closedByOwner`       | Position closed by its owner                                                         |
| `3`   | `closedByLiquidation` | Position closed through liquidation                                                  |
| `4`   | `zombie`              | Open position removed from normal sorted ordering; use its dedicated adjustment path |

`getLatestTroveData` returns `entireDebt`, `entireColl`, redistribution gains, accrued interest, recorded debt, annual interest rate, weighted recorded debt, accrued batch-management fee, and the last rate-adjustment time. `entireDebt` and `entireColl` are the position values used for current health calculations.

Index TroveManager's `TroveUpdated`, `TroveOperation`, `BatchedTroveUpdated`, `BatchUpdated`, `Liquidation`, `Redemption`, and `RedemptionFeePaidToTrove`. Couple them with the branch NFT's `Transfer` events to maintain ownership and position history.

## Earn: Stability Pool

Each branch's `<branch>.StabilityPool` accepts USDHN deposits and distributes liquidation collateral and USDHN yield.

| Operation                    | Function                                                                            |
| ---------------------------- | ----------------------------------------------------------------------------------- |
| Deposit                      | `provideToSP(uint256 amount, bool doClaim)`                                         |
| Withdraw                     | `withdrawFromSP(uint256 amount, bool doClaim)`                                      |
| Claim accumulated collateral | `claimAllCollGains()`                                                               |
| Read remaining deposit       | `getCompoundedUSDHNDeposit(address depositor)`                                      |
| Read collateral and yield    | `getDepositorCollGain`, `getDepositorYieldGain`, `getDepositorYieldGainWithPending` |
| Read pool accounting         | `getTotalUSDHNDeposits`, `P`, `currentScale`, `scaleToS`, `scaleToB`                |

`deposits()` is the stored initial value; the compounded-deposit getter accounts for liquidation losses. `DepositUpdated` records the new deposit and accumulator snapshot. `DepositOperation` records the action, deposit loss, amount change, yield, and collateral gains. `P_Updated`, `S_Updated`, `B_Updated`, and `ScaleUpdated` expose accumulator changes. `offset` and `triggerUSDHNRewards` are protocol-controlled calls.

## Lending

`lending-core.Pool` manages reserves, collateral settings, and account debt. Reserve configuration supplies the underlying asset, aToken, and variable debt token addresses.

| Action                    | Pool function                                                                                                        |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| Supply                    | `supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode)`                                     |
| Withdraw                  | `withdraw(address asset, uint256 amount, address to)`                                                                |
| Borrow                    | `borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf)`           |
| Repay                     | `repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf)`                                 |
| Toggle collateral         | `setUserUseReserveAsCollateral(address asset, bool useAsCollateral)`                                                 |
| Select eMode              | `setUserEMode(uint8 categoryId)`                                                                                     |
| Account and reserve reads | `getUserAccountData`, `getUserConfiguration`, `getReserveData`, `getConfiguration`, `getReservesList`                |
| Liquidate                 | `liquidationCall(address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken)` |

The app's borrow and repay paths use variable-rate mode `2`. Native KAIA operations use `WKaiaGateway.depositKAIA`, `withdrawKAIA`, `borrowKAIA`, and `repayKAIA`. Native withdrawals spend the account's aWKAIA allowance; native borrowing uses variable debt token delegation to the gateway.

Index `Supply`, `Withdraw`, `Borrow`, `Repay`, `LiquidationCall`, `ReserveDataUpdated`, `ReserveUsedAsCollateralEnabled`, `ReserveUsedAsCollateralDisabled`, and `UserEModeSet`. `PoolConfigurator` and `ACLManager` expose administrator-controlled reserve and role settings.

## Staking tokens and vault entrypoints

The bKAIA vault dispatches entrypoint selectors through `VaultModuleRouter`. Calls use the **LSTVault address** with the ABI from `VaultDepositEntryModule`, `VaultUnstakeEntryModule`, `VaultClaimEntryModule`, or `VaultViewEntryModule`.

| bKAIA operation           | Entrypoint                                                                   |
| ------------------------- | ---------------------------------------------------------------------------- |
| Deposit native KAIA       | Payable `deposit(address receiver, uint256 minShares)`                       |
| Preview shares and assets | `previewDeposit`, `convertToShares`, `convertToAssets`                       |
| Request withdrawal        | `requestUnstakeByShares(uint256 shares)` or `requestUnstake(uint256 assets)` |
| Claim tickets             | `claim(uint256 ticketId)` and `claimMany(uint256[] ticketIds)`               |
| Resolve canceled request  | `settleCanceled(uint256 ticketId)`                                           |
| Read ticket               | `requests(uint256 ticketId)` and the vault view helpers                      |

`claimMany` returns `processed`, `totalPaid`, and `totalFee`. The events `Requested`, `RequestedBatch`, `TicketStatusUpdated`, `ClaimPayout`, `ClaimManySummary`, and `ClaimRetryQueued` describe ticket progress and payouts. A batch can succeed while leaving individual tickets pending.

`core.HNKAIA` exposes `supportedAssets`, `assets`, `previewDeposit`, `deposit`, `previewRedeemProRata`, `redeemProRata`, and per-asset redemption reads. Its share and underlying-asset amounts have different units; use the selected asset's decimals and the matching preview.

## StableSwap and Zappers

`stableswap.UsdtUsdhnPool` owns reserves, LP accounting, swap fees, and amplification. Read `getReserves`, `getDy`, `getDx`, `quoteAddLiquidity`, `quoteRemoveLiquidity`, and `getVirtualPrice`. Its `Swap`, `Mint`, and `Burn` events record trades and liquidity changes.

The router exposes `getAmountsOut`, `getAmountsIn`, `swapExactTokensForTokens`, `swapTokensForExactTokens`, `addLiquidity`, `removeLiquidity`, and their permit variants. Exact-input execution sets a minimum output; exact-output execution sets a maximum input. Parameter structs include the route, recipient, and deadline. `stableswap.Lens` adds detailed quotes, and `RewardStaker` accounts for staked LP balances and pending rewards.

Branch Zappers wrap assets and execute Trove operations. Leverage Zappers expose `openLeveragedTrove`, `leverUpTrove`, `leverDownTrove`, and `closeTroveByCollateral`. The first three enforce submitted `maxDebt`. The close struct contains `troveId` and `profitReceiver` and supplies no user minimum-output field. FlashSwapper callbacks accept the configured pool and active operation, settle the flash swap, and return route leftovers to the receiver.

## Repository interfaces

* `artifacts/contracts/registry.ts`: profile selection, contract entries, and ABI lookup.
* `artifacts/contracts/frontend.ts` and `domains/*.ts`: typed frontend and domain exports.
* `contracts/cdp-core/src/Interfaces`: CDP calls, state structs, and events.
* `contracts/interfaces/src/zappers`: Zapper parameter structs and calls.
* `contracts/lending-core/src/protocol/pool`: Lending accounting and operations.
* `contracts/bkaia/src/vault/entry`: vault entrypoint dispatch and ticket operations.
* `contracts/stableswap/src/StableSwap`: pool, router, lens, and LP implementation.

The [Integrator Guide](/developers/integrator-kit.md) describes contract selection, approvals, transaction preparation, and event indexing. The [Technical Overview](/developers/technical-overview.md) connects these contracts to the product API and wallet.


---

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