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

# 스마트 컨트랙트

배포 프로필, 컨트랙트 ID, 함수, 이벤트, 계정 상태

Hann Finance의 컨트랙트 번들은 주소와 체인, ABI, 배포 정보, 소스를 함께 보관합니다. 통합은 **배포 프로필과 컨트랙트 ID**로 대상을 찾습니다. Lending, CDP, 스테이킹, 교환은 각각의 토큰 주소와 자산·부채 관리 주소를 사용합니다.

## 배포 프로필과 ABI 조회

| 프로필          | 네트워크   | 체인 ID  | `canonical` |
| ------------ | ------ | ------ | ----------- |
| `kaia-prod`  | Kaia   | `8217` | `true`      |
| `kaia-qa`    | Kaia   | `8217` | `false`     |
| `kairos-dev` | Kairos | `1001` | `false`     |

각 프로필에는 `profile.json`, `snapshot/kaia.json`, `addresses/kaia.json`, `watch-targets/kaia.json`이 있습니다. Kairos 프로필도 파일명은 `kaia.json`을 유지하며, 메타데이터에 실제 체인 ID `1001`을 기록합니다.

`GET /api/v1/contracts/snapshot`은 API가 선택한 스냅샷을 제공합니다. `contracts[id]`에는 `address`, `chainId`, `abiRef`, `abiHash`, `source`, 배포 정보가 있습니다. `abiRef`는 `artifacts/contracts` 패키지 루트를 기준으로 해석합니다. TypeScript 레지스트리는 선택한 프로필의 `getAddress(id)`, `getAbi(id)`, `getOptionalContract(id)`를 제공합니다. 선택적 프런트엔드 기능에 활성 컨트랙트가 없으면 `active: false`, `address: null`을 반환합니다.

### Kaia 메인넷 주소

아래 컨트랙트는 아직 Kaia 메인넷에 배포되지 않았습니다. 주소는 \*\*TBA(배포 후 공개)\*\*로 표기하며, 배포가 완료되면 공개합니다.

| 컨트랙트 ID                     | 주소  |
| --------------------------- | --- |
| `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 |

Lending 자산은 `lending-core.Asset.<symbol>` 또는 선택한 시장 설정에서 찾습니다. 이 프로필의 `lending-core.Asset.BKAIA`와 `bkaia.LSTToken`, `lending-core.Asset.HNKAIA`와 `core.HNKAIA`는 각각 주소가 다릅니다. 심볼은 표시 이름이며, 호출 대상 토큰은 해당 도메인의 주소로 결정합니다.

## CDP 코어

생성된 프런트엔드 인터페이스에서 브랜치 ID는 KAIA가 `0`, HNKAIA가 `1`, EARNUSDT가 `2`입니다. 아티팩트 접두사는 각각 `core.WKAIA`, `core.HNKAIA`, `core.EARNUSDT`입니다.

| 컨트랙트 ID 또는 접미사                               | 공개 인터페이스와 상태                                                                                                                                                    |
| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `core.USDHN`                                 | 잔액·사용 승인·전송·permit: `balanceOf`, `allowance`, `approve`, `transfer`, `permit`                                                                                   |
| `core.CollateralRegistry`                    | `collateralConfig`, `getToken`, `getTroveManager`, `isCollateralActive`, 리뎀션 수수료 조회, `redeemCollateral`                                                         |
| `<branch>.BorrowerOperations`                | `openTrove`, `openTroveAndJoinInterestBatchManager`, `addColl`, `withdrawColl`, `withdrawUSDHN`, `repayUSDHN`, `adjustTrove`, `adjustZombieTrove`, `closeTrove` |
| `<branch>.TroveManager`                      | `getLatestTroveData`, `getTroveStatus`, `getCurrentICR`, `getLatestBatchData`, `batchLiquidateTroves`, `urgentRedemption`                                       |
| `<branch>.TroveNFT`                          | ERC-721의 `ownerOf`, 소유권 이전, `Transfer` 이벤트                                                                                                                      |
| `<branch>.SortedTroves`                      | 금리 정렬과 삽입 위치 힌트                                                                                                                                                 |
| `<branch>.AddressesRegistry`                 | 브랜치 컨트랙트 참조와 설정 파라미터                                                                                                                                            |
| `<branch>.PriceFeed`                         | 가격 조회, 마지막 유효 가격, 오라클 상태                                                                                                                                        |
| `<branch>.ActivePool` / `DefaultPool`        | 활성 담보·부채, 재분배 담보·부채                                                                                                                                             |
| `<branch>.CollSurplusPool` / `GasPool`       | 수령할 잉여 담보, 청산 가스 보상금                                                                                                                                            |
| `core.HintHelpers` / `core.MultiTroveGetter` | 수수료·삽입 위치 힌트 계산, 포지션 일괄 조회                                                                                                                                      |
| `core.RedemptionHelper`                      | `simulateRedemption`, `truncateRedemption`, 브랜치별 최소 수령량을 지정한 리뎀션                                                                                                |

`<branch>`는 위 세 아티팩트 접두사 중 하나입니다. Zapper의 ID는 `zappers.<symbol>.Zapper`, `zappers.<symbol>.LeverageZapper`, `zappers.<symbol>.FlashSwapper`입니다.

현재 토큰 소스 `USDHNToken.sol`은 ERC-20과 permit을 구현합니다. 교차체인 전송은 기준 체인의 잠금·해제에 `USDHNOFTAdapter`, 다른 체인의 발행·소각에 `USDHNOFT`를 사용합니다. 기록된 `kaia-prod`의 `core.USDHN` ABI에는 원본 아티팩트의 `quoteOFT`, `quoteSend`, `send`도 들어 있습니다. 이 함수들은 현재 `USDHNToken` 구현에 속하지 않습니다. OFT 통합은 배포된 어댑터나 다른 체인의 토큰, 그 대상의 ABI, peer와 endpoint 설정을 함께 사용합니다.

### 차입·금리·리뎀션 파라미터

`BorrowerOperations.openTrove`는 소유자, 소유자 인덱스, 담보량, 요청 USDHN 수량, 상·하단 힌트, 연이율, 최대 선취 수수료, 담보 추가 관리자, 담보 제거 관리자, 수령자를 받습니다. `openTroveAndJoinInterestBatchManager`의 구조체는 개별 금리 필드 대신 배치 관리자를 받습니다.

금리 제어 함수는 `adjustTroveInterestRate`, `setInterestIndividualDelegate`, `setInterestBatchManager`, `removeFromBatch`, `switchBatchManager`입니다. `addManagerOf`, `removeManagerReceiverOf`는 작업 위임과 수령자 설정을 조회합니다. 브랜치의 `BorrowerOperations`에서 `MCR`, `CCR`, `SCR`, `BCR`을 읽습니다.

일반적인 브랜치 간 리뎀션은 `CollateralRegistry.redeemCollateral(usdhnAmount, maxIterationsPerCollateral, maxFeePercentage)`로 실행합니다. 레지스트리는 활성 상태이면서 리뎀션이 가능한 브랜치를 선택하고 실제 리뎀션된 수량을 소각합니다. 반복 한도 `0`은 제한 없이 순회한다는 뜻이며 앱도 이 값을 사용합니다. 순회 횟수를 제한하면 일부 수량만 처리될 수 있습니다. 인자 다섯 개를 받는 TroveManager의 `redeemCollateral`은 레지스트리가 호출하며, 종료된 브랜치는 `urgentRedemption`을 사용합니다.

`RedemptionHelper.redeemCollateral(usdhnAmount, maxIterationsPerCollateral, maxFeePercentage, minCollRedeemed)`는 브랜치별 최소 담보 수령량을 추가로 받습니다. 도우미가 `transferFrom`으로 USDHN을 가져가므로 호출자는 도우미에 USDHN 사용 승인을 부여합니다. 최소 수령량 배열은 도우미의 브랜치 순서를 따릅니다. 한도를 충족하지 못하면 트랜잭션이 revert하며, 남은 USDHN은 환급됩니다. `simulateRedemption`, `truncateRedemption`은 가격 조회가 캐시 상태를 갱신할 수 있어 non-view 함수입니다. 사전 조회는 RPC 시뮬레이션으로 실행합니다.

### Trove 상태와 현재 부채

| 값   | 상태                    | 의미                                |
| --- | --------------------- | --------------------------------- |
| `0` | `nonExistent`         | 해당 ID에 포지션이 없음                    |
| `1` | `active`              | 정상 작업에 참여하는 열린 포지션                |
| `2` | `closedByOwner`       | 소유자가 종료한 포지션                      |
| `3` | `closedByLiquidation` | 청산으로 종료된 포지션                      |
| `4` | `zombie`              | 정상 정렬 목록에서 빠진 열린 포지션, 전용 조정 함수 사용 |

`getLatestTroveData`는 `entireDebt`, `entireColl`, 재분배 수익, 누적 이자, 저장된 부채, 연이율, 금리 가중 부채, 누적 배치 관리 수수료, 마지막 금리 조정 시간을 반환합니다. 현재 담보 상태 계산에는 `entireDebt`와 `entireColl`을 사용합니다.

TroveManager의 `TroveUpdated`, `TroveOperation`, `BatchedTroveUpdated`, `BatchUpdated`, `Liquidation`, `Redemption`, `RedemptionFeePaidToTrove`를 인덱싱합니다. 브랜치 NFT의 `Transfer`와 함께 추적해 소유권과 포지션 내역을 유지합니다.

## Earn: Stability Pool

브랜치별 `<branch>.StabilityPool`은 USDHN 예치를 받아 청산 담보와 USDHN 수익을 분배합니다.

| 작업          | 함수                                                                                  |
| ----------- | ----------------------------------------------------------------------------------- |
| 예치          | `provideToSP(uint256 amount, bool doClaim)`                                         |
| 인출          | `withdrawFromSP(uint256 amount, bool doClaim)`                                      |
| 누적 담보 수령    | `claimAllCollGains()`                                                               |
| 현재 예치 잔액    | `getCompoundedUSDHNDeposit(address depositor)`                                      |
| 담보·USDHN 수익 | `getDepositorCollGain`, `getDepositorYieldGain`, `getDepositorYieldGainWithPending` |
| 풀 계산 상태     | `getTotalUSDHNDeposits`, `P`, `currentScale`, `scaleToS`, `scaleToB`                |

`deposits()`는 저장된 초기 값을 반환하며, compounded-deposit 함수는 청산 손실을 반영합니다. `DepositUpdated`는 새 예치액과 누적 계산값 스냅샷을 기록합니다. `DepositOperation`은 작업, 예치 손실, 수량 변경, 이자, 담보 수익을 기록합니다. `P_Updated`, `S_Updated`, `B_Updated`, `ScaleUpdated`는 누적 계산값의 변경을 기록합니다. `offset`, `triggerUSDHNRewards`는 프로토콜이 호출합니다.

## Lending

`lending-core.Pool`은 시장, 담보 설정, 계정 부채를 관리합니다. 시장 설정은 기초 자산, aToken, 변동금리 부채 토큰의 주소를 제공합니다.

| 작업       | Pool 함수                                                                                                              |
| -------- | -------------------------------------------------------------------------------------------------------------------- |
| 공급       | `supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode)`                                     |
| 인출       | `withdraw(address asset, uint256 amount, address to)`                                                                |
| 차입       | `borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf)`           |
| 상환       | `repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf)`                                 |
| 담보 설정    | `setUserUseReserveAsCollateral(address asset, bool useAsCollateral)`                                                 |
| eMode 선택 | `setUserEMode(uint8 categoryId)`                                                                                     |
| 계정·시장 조회 | `getUserAccountData`, `getUserConfiguration`, `getReserveData`, `getConfiguration`, `getReservesList`                |
| 청산       | `liquidationCall(address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken)` |

앱의 차입·상환은 변동금리 모드 `2`를 사용합니다. 네이티브 KAIA 작업은 `WKaiaGateway.depositKAIA`, `withdrawKAIA`, `borrowKAIA`, `repayKAIA`를 사용합니다. 네이티브 인출은 계정의 aWKAIA 사용 승인을, 네이티브 차입은 변동금리 부채 토큰의 게이트웨이 위임을 사용합니다.

`Supply`, `Withdraw`, `Borrow`, `Repay`, `LiquidationCall`, `ReserveDataUpdated`, `ReserveUsedAsCollateralEnabled`, `ReserveUsedAsCollateralDisabled`, `UserEModeSet`을 인덱싱합니다. 시장과 역할 설정은 관리자 권한을 사용하는 `PoolConfigurator`, `ACLManager`에서 관리합니다.

## 스테이킹 토큰과 금고 함수

bKAIA 금고는 `VaultModuleRouter`로 함수 선택자를 전달합니다. **LSTVault 주소**에 `VaultDepositEntryModule`, `VaultUnstakeEntryModule`, `VaultClaimEntryModule`, `VaultViewEntryModule` 중 해당 작업의 ABI를 사용합니다.

| bKAIA 작업     | 함수                                                                           |
| ------------ | ---------------------------------------------------------------------------- |
| 네이티브 KAIA 예치 | Payable `deposit(address receiver, uint256 minShares)`                       |
| 지분·자산 사전 조회  | `previewDeposit`, `convertToShares`, `convertToAssets`                       |
| 인출 요청        | `requestUnstakeByShares(uint256 shares)` 또는 `requestUnstake(uint256 assets)` |
| 티켓 수령        | `claim(uint256 ticketId)`, `claimMany(uint256[] ticketIds)`                  |
| 취소된 요청 정산    | `settleCanceled(uint256 ticketId)`                                           |
| 티켓 조회        | `requests(uint256 ticketId)`, 금고 조회 도우미                                      |

`claimMany`는 `processed`, `totalPaid`, `totalFee`를 반환합니다. `Requested`, `RequestedBatch`, `TicketStatusUpdated`, `ClaimPayout`, `ClaimManySummary`, `ClaimRetryQueued`는 티켓의 진행 상태와 지급을 기록합니다. 일괄 실행이 성공해도 개별 티켓은 대기 상태로 남을 수 있습니다.

`core.HNKAIA`는 `supportedAssets`, `assets`, `previewDeposit`, `deposit`, `previewRedeemProRata`, `redeemProRata`, 자산별 환매 조회를 제공합니다. 지분 수량과 기초 자산 수량의 단위가 다르므로 선택한 자산의 소수점 자릿수와 해당 사전 조회를 사용합니다.

## StableSwap과 Zapper

`stableswap.UsdtUsdhnPool`은 준비금, LP 계산, 교환 수수료, 증폭 계수를 관리합니다. 조회 함수는 `getReserves`, `getDy`, `getDx`, `quoteAddLiquidity`, `quoteRemoveLiquidity`, `getVirtualPrice`입니다. `Swap`, `Mint`, `Burn`은 교환과 유동성 변경을 기록합니다.

라우터는 `getAmountsOut`, `getAmountsIn`, `swapExactTokensForTokens`, `swapTokensForExactTokens`, `addLiquidity`, `removeLiquidity`와 각 permit 변형을 제공합니다. 입력량 고정 실행은 최소 출력량을, 출력량 고정 실행은 최대 입력량을 지정합니다. 파라미터 구조체에는 경로, 수령자, 기한이 포함됩니다. `stableswap.Lens`는 상세 견적을 제공하고 `RewardStaker`는 LP 스테이킹 잔액과 미수령 보상을 관리합니다.

브랜치 Zapper는 자산을 래핑하고 Trove 작업을 실행합니다. 레버리지 Zapper는 `openLeveragedTrove`, `leverUpTrove`, `leverDownTrove`, `closeTroveByCollateral`을 제공합니다. 앞의 세 함수는 제출한 `maxDebt`를 적용합니다. 종료 구조체는 `troveId`, `profitReceiver`를 받으며 사용자 최소 수령량 필드는 없습니다. FlashSwapper 콜백은 설정된 풀과 진행 중인 작업을 확인해 플래시 스왑을 정산하고 남은 자산을 수령자에게 돌려줍니다.

## 저장소 인터페이스

* `artifacts/contracts/registry.ts`: 프로필 선택, 컨트랙트 항목, ABI 조회.
* `artifacts/contracts/frontend.ts`, `domains/*.ts`: 프런트엔드·도메인 타입과 공개 함수.
* `contracts/cdp-core/src/Interfaces`: CDP 호출, 상태 구조체, 이벤트.
* `contracts/interfaces/src/zappers`: Zapper 파라미터 구조체와 함수.
* `contracts/lending-core/src/protocol/pool`: Lending 계산과 작업.
* `contracts/bkaia/src/vault/entry`: 금고 함수 전달과 티켓 작업.
* `contracts/stableswap/src/StableSwap`: 풀, 라우터, Lens, LP 구현.

[통합 가이드](/ko/developers/integrator-kit.md)는 컨트랙트 선택, 사용 승인, 트랜잭션 구성, 이벤트 인덱싱을 설명합니다. [기술 개요](/ko/developers/technical-overview.md)는 컨트랙트와 제품 API·지갑을 연결합니다.


---

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