# Technical Architecture

Kana Labs' perpetual DEX leverages the Aptos blockchain and integrates **Econia** on-chain orderbook. Built with scalability, composability, and security in mind, the system is designed to be modular, decentralized, permissionless, and optimized for high-throughput trading.

***

## Core Components

### 1. Trade Profiles

Trade profiles are [Aptos objects](https://aptos.dev/en/build/smart-contracts/objects) that represent an individual user’s trading state on Kana Perps. These objects serve as the foundational identity for interaction with the trading protocol.

* When a user interacts with the platform for the first time (e.g., deposits funds), a **trade profile is automatically created** if it does not already exist.
* This profile is essential for:
  * Holding trading balances
  * Managing open positions
  * Storing collateral
  * Interfacing with order placement and settlement mechanisms

Because of Aptos's object model, each trade profile is uniquely tied to the user and ensures strong state isolation across traders.

***

### 2. Market Creation

Kana enables permissionless market creation for any asset with a reliable price feed available on **Pyth Network**. Markets are created and owned by a **market creator**, who is responsible for parameter management and liquidity provisioning.

**2.1 Market Creator Responsibilities**

Upon creating a market, the creator becomes:

* **Maintainer**: Controls market state and configuration.
* **Fee Recipient**: Receives all trading fees generated by the market.
* **Market Maker Whitelister**: Has authority to whitelist addresses as market makers.

#### 2.2 Initialization Parameters

| Parameter            | Description                                  |
| -------------------- | -------------------------------------------- |
| `creator`            | Signer reference for the market creator      |
| `fee_wallet`         | Address that collects market fees            |
| `base_name`          | Identifier for the base asset                |
| `lot_size`           | Minimum tradable unit size                   |
| `tick_size`          | Minimum price increment                      |
| `min_lots`           | Minimum order size in lots                   |
| `max_lots`           | Maximum order size in lots                   |
| `max_position_value` | Maximum position value allowed               |
| `maintenance_margin` | Required margin to prevent liquidation       |
| `max_leverage`       | Maximum leverage allowed on the market       |
| `quote_precision`    | Decimal precision for quote asset            |
| `base_decimals`      | Decimal precision for base asset             |
| `quote_decimals`     | Decimal precision for quote pricing          |
| `pyth_price_feed_id` | Vector identifier for Pyth oracle price feed |

#### 2.3 Mutable Parameters

| Mode            | Code | Description                                                       |
| --------------- | ---- | ----------------------------------------------------------------- |
| Active          | 1    | Market is fully operational for all users                         |
| Inactive        | 2    | Market is temporarily disabled                                    |
| Deprecated      | 3    | Market is permanently disabled (irreversible)                     |
| Settlement Only | 4    | Only position settlement is allowed, no new orders (irreversible) |
| MM Only         | 5    | Only whitelisted market makers can place orders                   |

#### 2.4 Market Modes

Kana Perps defines several operational modes for markets, each representing a different trading state. These modes are critical for lifecycle management and operational flexibility:

1. <mark style="color:green;">**Active**</mark>: The market is live and open to all traders. Orders can be placed, canceled, and matched freely.
2. <mark style="color:yellow;">**Inactive**</mark>: The market is temporarily paused.
3. <mark style="color:red;">**Deprecated**</mark>: The market is permanently closed. No further trading or changes are allowed, and the market can never be reactivated.
4. <mark style="color:orange;">**Settlement-Only**</mark>: Only order settlement (e.g., closing positions) is allowed. New order placements are disallowed. Like deprecated mode, this state is irreversible.
5. <mark style="color:blue;">**Market Maker Only (MM Only)**</mark>: Only addresses that have been whitelisted as market makers can place orders. This mode is typically used during initial market setup to allow liquidity provisioning before opening the market to the public.

By default, all newly created markets begin in <mark style="color:blue;">**Market Maker Only**</mark> mode, giving the creator an opportunity to whitelist professional liquidity providers and bootstrap depth on the orderbook before transitioning to a publicly tradable state.

> <mark style="color:red;">**Note:**</mark> <mark style="color:red;"></mark><mark style="color:red;">Once a market enters</mark> <mark style="color:red;"></mark><mark style="color:red;">`SETTLEMENTONLY`</mark> <mark style="color:red;"></mark><mark style="color:red;">or</mark> <mark style="color:red;"></mark><mark style="color:red;">`DEPRECATED`</mark><mark style="color:red;">, it cannot be reactivated. This enforces immutability guarantees for deprecated markets.</mark>

**2.5 Market Maker Whitelisting**

Market creators can whitelist specific addresses as **market makers**, enabling them to:

* Exceed standard position limits (`max_position_value`)
* Trade during restricted phases such as `MM_ONLY` mode
* Participate in liquidity provisioning.

***

### 3. Asset Management

Econia markets require two assets: a **base asset** and a **quote asset**.

**3.1 Base Asset**

* The base asset is not required to be an Aptos `Coin` type.
* It is **custom-managed** by **the market underwriter** internally.

**3.2 Quote Asset: KanaUSDT**

Kana Perps standardizes all quote currencies via an internal stablecoin abstraction called `KanaUSDT`:

* **Pegged 1:1 to USDT**
* **Internally minted/burned** during trade flows
* **Non-transferable and inaccessible externally**

This design ensures:

* Unified accounting across all markets
* Economic isolation from external protocols
* Guaranteed encapsulation of Econia orderbook access — **only Kana modules can interact with these markets**

> This design effectively “locks” the Econia markets created via Kana, preventing unauthorized access by third-party contracts or traders.

***

## Order Lifecycle

#### 4. Order Placement

When a user places an order, the system performs a sequence of operations to manage risk and settlement preparation.

**4.1 Collateral Calculation**

1. The total order value is computed from size and price.
2. The **required collateral** is calculated based on the user’s selected leverage.
3. Collateral is withdrawn from the user’s trading profile and stored in a **collateral vault** specific to the order.

**4.2 Execution Flow**

* **Long Positions**:
  * Kana calculates the quote contribution:\
    `KanaContribution = TotalPositionValue - UserCollateral`
  * Internal minting of `KanaUSDT` equal to `TotalPositionValue`
  * Funds are deposited into the corresponding Econia market account
  * The order is placed on the **Econia orderbook**
* **Short Positions**:
  * The base asset is deposited directly using the underwriter capability
  * `KanaUSDT` equal to user collateral is minted and deposited alongside the base asset

#### 5. Order Cancellation

If a user cancels an order:

* It is removed from the Econia orderbook
* Associated collateral is unlocked and refunded to the user’s trading profile

***

## Funding Rate Mechanism

Funding rates incentivize price convergence between perpetual markets and the oracle spot price. Kana implements a dynamic funding system using the **Pyth oracle** and **impact pricing**.

#### 6.1 Calculation

* Every minute, a temporary funding rate is derived using:

  ```
  impact_quote = 500 * 10^6 * market_leverage
  ```
* `impact_bid` and `impact_ask` are calculated to simulate slippage
* A rolling hourly average is computed from 60 one-minute snapshots

#### 6.2 Application

* The hourly average is applied to all open positions, credited or debited based on long/short exposure
* A **1% per-minute cap** is enforced to prevent abusive funding events:
  * If any minute's funding exceeds this threshold, it is clamped to 0

***

## Liquidation Logic

Kana’s liquidation process ensures robust solvency guarantees and minimizes risk propagation.

#### 7.1 Trigger Conditions

* Liquidation is triggered when the **oracle price** from Pyth breaches a position’s liquidation threshold
* External actors (e.g., bots) call the `liquidate` function

#### 7.2 Execution and Distribution

If the user’s collateral **covers the loss**:

* Position is closed
* Remaining collateral is distributed as:
  * **30%** to the liquidator
  * **20%** to the insurance fund
  * **50%** refunded to the user

If the loss **exceeds the collateral**:

* Insurance fund is used to cover the shortfall
* **No reward** is given to the liquidator

This ensures:

* Risk is socialized responsibly
* Liquidator incentives align with solvency maintenance

##

***


---

# Agent Instructions: 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:

```
GET https://docs.kanalabs.io/perpetual-futures/kana-perps/technical-architecture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
