Skip to content

[Khensu] Including the contract for the Khensu Platform#9

Open
BlueJaySamurai wants to merge 2 commits into
HathorNetwork:masterfrom
BlueJaySamurai:master
Open

[Khensu] Including the contract for the Khensu Platform#9
BlueJaySamurai wants to merge 2 commits into
HathorNetwork:masterfrom
BlueJaySamurai:master

Conversation

@BlueJaySamurai

Copy link
Copy Markdown

Khensu Manager Blueprint - Token Fair-Launch Platform with Bonding Curves

This blueprint implements Khensu Manager, a contract that manages a token launchpad with bonding curve pricing for the Hathor network. Tokens are created, traded on a bonding curve, and automatically graduated to a Dozer DEX pool when they reach a target market cap.

What it does

Khensu Manager enables a pump.fun-style token launchpad where anyone can create a new token, trade it on a bonding curve with built-in price discovery, and have the token automatically migrate its liquidity to a full DEX (Dozer Pool Manager) once the bonding curve reaches its target market cap.

Main Workflow

1. Token Creation (khensu_manager.py:774-854)

  • Anyone can create a new token by depositing the network fee (0.01 HTR)
  • The contract mints the full token supply (default: 1 billion tokens) and holds it in reserve
  • Token metadata (name, symbol, image url, description, social links) stored on-chain
  • URLs validated to require https:// prefix; image links must be ≥ 32 characters
  • Token registered in symbol/name dictionaries for search, and in the LRU cache

2. Token Trading via Bonding Curve

Buy Tokens (khensu_manager.py:856-948)

  • Users deposit HTR and withdraw tokens in a single atomic transaction
  • Price calculated using a custom bonding curve formula: T = H × (a - c×Ts)² / (a×b + H×c×(a - c×Ts))
    • Where T = tokens out, H = HTR in, Ts = tokens already sold
  • Buy fee collected for the platform
  • Creator fee credited to the token creator's internal balance
  • Slippage protection: users specify desired output; excess tokens go to internal balance
  • Excess HTR returned to internal balance if purchase is capped at the graduation threshold
  • Purchase capped at 80% of total supply (remaining 20% reserved for DEX migration)
  • Curve deviation correction removes residual HTR from rounding errors
  • Automatic migration triggered when the bonding curve fills completely

Sell Tokens (khensu_manager.py:950-1001)

  • Users deposit tokens and withdraw HTR
  • HTR return calculated using inverse bonding curve: H = a×b×T / ((a - c×Ts) × (a - c×Ts + c×T))
  • Sell fee collected for the platform
  • Slippage protection: excess HTR goes to internal balance
  • Cannot sell after token migration (Transactions migrate to Dozer)

3. Automatic Migration to DEX (khensu_manager.py:716-772)

  • Triggered automatically within buy_tokens when the bonding curve reaches 80% tokens sold from the total supply
  • Validates the market cap has reached the target (default: 6,900,000 HTR)
  • Deposits HTR acquired + remaining 20% token supply into a Dozer pool
  • Creates and signs the pool on Dozer Pool Manager (Khensu contract must be an authorized signer)
  • Graduation fee and residual HTR collected as operation fees
  • Token marked as migrated; further bonding curve trading is disabled
  • After migration, trading continues on the Dozer DEX

4. User Balance System (khensu_manager.py:613-629, 1048-1069)

Internal Balance Tracking

  • Holds excess tokens/HTR from slippage on buy and sell operations
  • Holds creator fee HTR earned by token creators
  • Users withdraw via withdraw_from_balance method
  • Separate tracking per user per token

Withdraw from Balance (khensu_manager.py:1048-1069)

  • Users can withdraw any amount up to their internal balance
  • Validates sufficient balance before allowing withdrawal

5. Platform Fee Management (khensu_manager.py:1003-1046)

  • Admin can withdraw accumulated platform fees (buy fees + sell fees + operation fees)
  • Fees deducted in order: buy fees → sell fees → operation fees
  • Partial withdrawals supported

6. Administrative Controls

Fee Configuration

  • Change buy fee rate (khensu_manager.py:1071-1077) — max 10%
  • Change sell fee rate (khensu_manager.py:1079-1085) — max 10%
  • Change creator fee rate (khensu_manager.py:1087-1093) — max 10%
  • Change pool fee rate for Dozer graduation (khensu_manager.py:1095-1101) — max 10%

Bonding Curve Reconfiguration (khensu_manager.py:1103-1137)

  • Change target market cap, total supply, and graduation fee for new tokens
  • Recalculates bonding curve constants (a, b, c) from the new parameters
  • Validates constraints: 3 × target_market_cap > 5 × graduation_fee

Admin Management (khensu_manager.py:1139-1153)

  • Add new admins via add_admin
  • Remove admins via remove_admin (cannot remove the original contract creator)
  • Multi-admin support with admin set

Contract Upgrade (khensu_manager.py:1565-1601)

  • Admin can upgrade to a new blueprint version
  • Semantic versioning enforced (new version must be higher)
  • Version comparison with zero-padding for different-length versions

7. Query/View Methods

Token Information

  • get_token_info (khensu_manager.py:1214-1217) — Full token data including computed market cap and progress
  • get_pool (khensu_manager.py:1441-1449) — Get Dozer pool key for migrated tokens
  • search (khensu_manager.py:1168-1212) — Search by symbol or name with pagination

Token Listings

  • get_last_n_tokens (khensu_manager.py:1219-1239) — Most recently active tokens via LRU cache, with cursor-based pagination
  • get_newest_n_tokens (khensu_manager.py:1241-1253) — Newest created tokens (reverse chronological), offset-based pagination
  • get_oldest_n_tokens (khensu_manager.py:1255-1266) — Oldest created tokens (chronological), offset-based pagination
  • get_recently_graduated_tokens (khensu_manager.py:1268-1280) — Recently migrated tokens (reverse chronological)
  • get_tokens_created_by_user (khensu_manager.py:1282-1299) — Tokens created by a specific user

User Data

  • get_user_balance (khensu_manager.py:1301-1320) — All token balances for a user (formatted as token_hex_amount space-separated)
  • get_user_token_balance (khensu_manager.py:1322-1334) — Balance for a specific token

Price Quotes

  • quote_buy (khensu_manager.py:1336-1381) — Quote buying tokens with HTR (includes recommended amount for graduation edge case)
  • quote_sell (khensu_manager.py:1383-1408) — Quote selling tokens for HTR
  • front_quote_exact_tokens_for_tokens (khensu_manager.py:1451-1506) — Post-migration quote via Dozer reserves (exact input)
  • front_quote_tokens_for_exact_tokens (khensu_manager.py:1508-1563) — Post-migration quote via Dozer reserves (exact output)

Platform Data

  • get_platform_stats (khensu_manager.py:1410-1419) — Total tokens created/migrated and fees collected
  • get_platform_info (khensu_manager.py:1421-1439) — Full admin configuration and fee state
  • get_contract_version (khensu_manager.py:1641-1648) — Current contract version

Key Features

  • Bonding Curve Pricing: Custom curve formula with configurable constants (a, b, c) derived from target market cap, graduation fee, and total supply
  • Automatic DEX Graduation: Tokens automatically migrate to Dozer DEX when the bonding curve fills to 80% tokens sold from the total supply
  • Creator Rewards: Token creators earn a fee on every buy transaction, credited to their internal balance
  • Multi-Tier Fee System: Separate configurable fees for buying, selling, and creator rewards, all using basis points (10,000 = 100%)
  • Slippage Protection: Users specify desired output; excess tokens/HTR held in internal balance for later withdrawal
  • LRU Cache for Activity Tracking: O(1) doubly-linked list tracking most recently active tokens, with configurable capacity and eviction
  • Post-Migration Price Proxy: After graduation, Khensu proxies price quotes from the Dozer DEX pool for frontend consumption
  • Curve Deviation Correction: Automatically removes residual HTR caused by integer rounding in buy/sell calculations
  • Search & Discovery: Token lookup by symbol or name, multiple listing views (newest, oldest, most active, graduated, by creator)
  • Multi-Admin Support: Multiple admin addresses with protected original creator
  • Contract Upgradeability: Built-in upgrade mechanism with semantic version control

Technical Highlights

  • Bonding curve constants derived at initialization:
    • a = 16 × total_supply × target_market_cap
    • b = (target_market_cap + 5 × graduation_fee)²
    • c = 5 × (3 × target_market_cap − 5 × graduation_fee)
  • Market cap formula (non-migrated): MarketCap = a × b × S / (a − c × Ts)²
  • Progress calculation in basis points: Progress = 5 × b × Ts × 10000 / ((target + 5 × grad_fee) × (a − c × Ts))
  • Fee calculation uses ceiling division to prevent fee underpayment
  • Fee extraction from gross amount: fee = (amount × rate + rate + BASIS_POINTS − 1) / (rate + BASIS_POINTS)
  • LRU cache implemented as O(1) doubly-linked list with lru_prev/lru_next dicts and head/tail pointers
  • TokenData NamedTuple for efficient consolidated storage with _replace() for partial updates
  • Separate NamedTuples for internal (TokenData) and API (TokenInfo) representations — API includes computed fields like market_cap and progress
  • 80/20 split: 80% of tokens available on bonding curve, 20% reserved + proportional HTR for DEX liquidity

Contract Structure

State Variables (Core)

  • tokens: Main token data dict mapping TokenUid → TokenData (reserves, supply, volume, curve constants, migration state)
  • user_balances: Internal balances per user per token (slippage returns + creator fees)
  • user_balance_tokens: List of tokens with balance per user (for iteration)

State Variables (Registry)

  • all_tokens: Ordered list of all token UIDs (creation order)
  • symbol_dict: Symbol → list of TokenUids mapping for search
  • name_dict: Name → list of TokenUids mapping for search
  • user_creations: Creator address → list of created TokenUids
  • graduated_tokens: List of migrated token UIDs

State Variables (LRU Cache)

  • lru_prev / lru_next: Doubly-linked list pointers for O(1) cache operations
  • lru_head / lru_tail: Most/least recently used token pointers
  • lru_cache_capacity / lru_cache_size: Cache bounds
  • lru_null_token: Sentinel value (HATHOR_TOKEN_UID) representing null pointers

State Variables (Platform)

  • admin_address: Original contract creator (cannot be removed)
  • admin_set: Set of authorized admin addresses
  • collected_buy_fees / collected_sell_fees / collected_operation_fees: Accumulated platform fees
  • total_tokens_created / total_tokens_migrated: Platform-wide counters
  • contract_version: Semantic version string for upgrade control

"""Create a new token with the manager."""
initial_token_reserve = self.default_token_total_supply

token_uid = self.syscall.create_fee_token(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We must wait fee tokens activation on mainnet before this is deployed.

Comment on lines +1249 to +1251
for i in range(-1 - offset, -1 - offset - number, -1):
if -n <= i < 0:
newest_tokens.append(self.all_tokens[i].hex())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop is unbounded. Please add a limit to it.

Comment on lines +1276 to +1278
for i in range(-1 - offset, -1 - offset - number, -1):
if -n <= i < 0:
recent_graduated_tokens.append(self.graduated_tokens[i].hex())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop is unbounded. Please add a limit to it.

Comment on lines +1295 to +1297
for i in range(-1 - offset, -1 - offset - number, -1):
if -n <= i < 0:
newest_tokens.append(token_list[i].hex())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop is unbounded. Please add a limit to it.

Comment on lines +1263 to +1264
for i in range(offset, min(offset + number, n)):
oldest_tokens.append(self.all_tokens[i].hex())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop is unbounded. Please add a limit to it.

Comment on lines +1230 to +1237
for _ in range(min(number, self.lru_cache_size)):
if current == self.lru_null_token:
break
last_tokens.append(current.hex())
if current in self.lru_next:
current = self.lru_next[current]
else:
current = self.lru_null_token

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop is unbounded. Please add a limit to it.

@github-project-automation github-project-automation Bot moved this from Submitted to Review Done in Community Blueprints Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Review Done

Development

Successfully merging this pull request may close these issues.

2 participants