Lichen Contracts Reference

Complete documentation of all 29 production smart contracts

29
Contracts
19,395
Lines of Rust
227
Public Functions (All Contracts)
6
LichenID Integrations

Contract Architecture

Lichen's 29 contracts span eight categories — DeFi, DEX, NFTs, Identity, Infrastructure & Governance — all compiled to WASM and deployable on-chain.

DeFi
LichenCoin, LichenSwap, ThallLend, SporePump, SporePay, SporeVault
DEX
DEX Core, DEX AMM, DEX Router, DEX Margin, DEX Governance, DEX Rewards, DEX Analytics
NFT
LichenPunks, LichenMarket, LichenAuction
Identity
LichenID (.lichen names, reputation, vouching)
Infrastructure
LichenOracle, LichenBridge, BountyBoard, Compute Market, Moss Storage, Shielded Pool
Governance
LichenDAO (proposals, voting, treasury)

WASM ABI Calling Convention

Lichen contracts compile to WASM and follow a unified ABI for argument passing. The runtime supports three modes — agents should use JSON mode for simplicity or Layout Descriptor mode for full control.

Argument Passing Modes
Mode Trigger Best For
JSON Auto-Encode Args start with [ (JSON array) CLI calls, agents — no manual encoding needed
Layout Descriptor Args start with 0xAB SDKs, binary callers — full stride control per param
Default (Legacy) Neither of above All-pointer functions (pubkeys only, no integers)
JSON Auto-Encode Mode

When argument bytes start with [, the runtime parses them as a JSON array and converts each element to binary with a 0xAB layout descriptor:

JSON Type WASM Param Encoding Stride
String (valid base58) I32 32-byte public key 32
String (non-base58) I32 UTF-8 bytes, zero-padded to next 32-byte boundary (max 224B) padded length
Number ≤ 255 I32 1 byte 1
Number 256–65535 I32 2 bytes LE 2
Number > 65535 I32 4 bytes LE 4
Boolean I32 1 byte (0 or 1) 1
Number / any I64 8 bytes LE 8

Example — molt call <addr> register_identity '["8nRM2Fk...", 1, "agent-demo", 10]'

The runtime detects the JSON array, encodes: 0xAB 20 01 20 01 + [32B pubkey][1B: 1][32B: "agent-demo\0…"][1B: 10]

Layout Descriptor Mode (0xAB)

Binary callers construct 0xAB + N stride bytes + data. Each stride byte controls how the runtime interprets the corresponding parameter:

Stride Meaning
32 (0x20) Pointer — 32 bytes at that offset, WASM receives memory address
4 (0x04) u32/i32 — 4 LE bytes, WASM receives raw I32 value
2 (0x02) u16/i16 — 2 LE bytes, WASM receives raw I32 value
1 (0x01) u8/bool — 1 byte, WASM receives raw I32 value
8 (0x08) I64 — 8 LE bytes, WASM receives raw I64 value
Default Mode (Legacy)

Without JSON or 0xAB prefix: every I32 param advances 32 bytes (treated as a pointer). Every I64 param advances 8 bytes. This mode works for all-pointer functions (e.g., transfer(from, to, amount)) but silently breaks functions with mixed pointer/integer I32 params.

Contract ABI Patterns
Pattern Contracts Notes
Named exports (standard) LichenCoin, LichenSwap, ThallLend, SporePump, SporePay, SporeVault, LichenID, LichenDAO, LichenPunks, LichenMarket, LichenAuction, LichenOracle, LichenBridge, BountyBoard, Compute Market, Moss Storage, lUSD, wETH, wSOL Each function is a #[no_mangle] pub extern "C" fn — callable by name with JSON args
Opcode dispatcher (call()) DEX Core, DEX AMM, DEX Router, DEX Governance, DEX Rewards, DEX Margin, DEX Analytics, Prediction Market Single call() export; internal ops dispatched via opcode byte in get_args() buffer. Use SDK for these.

Which pattern should I use?

Named exports (recommended for new contracts): Each public function is a separate WASM export (#[no_mangle] pub extern "C" fn). The runtime calls the function by name with JSON-encoded arguments. This is simpler to develop, test, and audit — each function is independently callable and discoverable.

Opcode dispatch (legacy DEX pattern): A single call() export reads a leading opcode byte from get_args() and dispatches internally via match opcode { ... }. This pattern was used for the 7 DEX contracts and the Prediction Market for historical reasons (batched operations, shared initialization). New contracts should use named exports.

Rationale: Named exports provide better tooling support (function discovery via WASM introspection), clearer error messages (unknown function vs. unknown opcode), and simpler SDK integration. The opcode pattern will be migrated to named exports in a future release with a backward-compatible shim.

Dispatcher Opcode Table
Contract Entry Export Opcode Source Dispatch Style
DEX Core call() args[0] from get_args() match opcode { ... } in contract dispatcher
DEX AMM call() args[0] from get_args() match opcode { ... } in contract dispatcher
DEX Router call() args[0] from get_args() match opcode { ... } in contract dispatcher
DEX Governance call() args[0] from get_args() match opcode { ... } in contract dispatcher
DEX Rewards call() args[0] from get_args() match opcode { ... } in contract dispatcher
DEX Margin call() args[0] from get_args() match opcode { ... } in contract dispatcher
DEX Analytics call() args[0] from get_args() match opcode { ... } in contract dispatcher
Prediction Market call() args[0] from get_args() match opcode { ... } in contract dispatcher

Use the SDK builders for opcode-dispatch contracts. They encode the leading opcode byte and argument layout correctly for each operation.

Return Code Conventions

Not all contracts agree on return codes. The runtime records the WASM return value in return_code for informational purposes but does NOT use it to determine success/failure — only a WASM trap constitutes failure.

Convention Contracts
0 = success, non-zero = error LichenID (0/20/100/200), lusd_token, weth_token, wsol_token, Moss Storage, LichenBridge, Compute Market, BountyBoard, SporePay
1 = success, 0 = error LichenOracle (queries), LichenPunks (mutations), LichenSwap (get_pool_info)
i64 return value (amount/balance) LichenSwap (swaps, add_liquidity), SporePump (buy/sell), all token contracts (balance_of)
void (no return) LichenSwap/LichenPunks (initialize), LichenDAO init variants

Contracts

LichenCoin

MT-20 Fungible Token Standard
498 lines8 fns5.2 KB

The native fungible token contract for Lichen. Implements the MT-20 standard with minting, burning, transfers, and approvals. Serves as the reference token used across the entire DeFi stack — LichenSwap liquidity pools quote in LICN, ThallLend accepts LICN deposits, and DAO governance is weighted by LICN holdings.

Configuration
Constant Value
NAME "LichenCoin"
SYMBOL "LICN"
DECIMALS 9
INITIAL_SUPPLY 500,000,000 LICN (500,000,000,000,000,000 spores)
Functions
initializebalance_oftransfermintburnapprovetransfer_fromtotal_supply
DeFi

LichenSwap

Automated Market Maker DEX
1,764 lines32 fns5.4 KB

Full-featured decentralized exchange using the constant-product (x·y=k) AMM model. Supports liquidity pool creation, token swaps, flash loans (0.09% fee), and LichenID reputation-based fee discounts. SporePump tokens graduate to LichenSwap pools once they hit the market cap threshold.

Key Features
  • Add / remove liquidity with LP token accounting
  • Swap in both directions with minimum output slippage protection
  • Flash loans (borrow → use → repay in same transaction)
  • LichenID integration for identity-gated fee discounts
  • Reentrancy guard on all state-changing operations
Functions
initializeadd_liquidityremove_liquidityswap_a_for_bswap_b_for_aswap_a_for_b_with_deadlineswap_b_for_a_with_deadlineget_quoteget_reservesget_liquidity_balanceget_total_liquidityflash_loan_borrowflash_loan_repayflash_loan_abortget_flash_loan_feeget_twap_cumulativesget_twap_snapshot_countset_protocol_feeget_protocol_feesset_identity_adminset_lichenid_addressset_reputation_discountms_pausems_unpausecreate_poolswapget_pool_infoget_pool_countset_platform_feeget_swap_countget_total_volumeget_swap_stats
DeFiLichenID

ThallLend

Decentralized Lending Protocol
2,068 lines21 fns12.2 KB

Collateralized lending and borrowing with automated liquidations. Depositors earn interest; borrowers pledge collateral up to the collateral factor. Uses a kinked interest rate model — low rates below 80% utilization, steeply increasing above. Liquidators receive a 5% bonus for keeping the protocol solvent.

Configuration
Constant Value
COLLATERAL_FACTOR 75% — max borrow relative to deposit
LIQUIDATION_THRESHOLD 85% — positions liquidated above this
LIQUIDATION_BONUS 5% — incentive for liquidators
UTILIZATION_KINK 80% — rate model inflection point
BASE_RATE ~2% APR (254 / 10B per slot)
Functions
initializedepositwithdrawborrowrepayliquidateget_account_infoget_protocol_statsflash_borrowflash_repaypauseunpauseset_deposit_capset_reserve_factorwithdraw_reservesset_lichencoin_addressget_interest_rateget_deposit_countget_borrow_countget_liquidation_countget_platform_stats
DeFi

SporePump

Token Launchpad with Bonding Curves
1,996 lines20 fns16.5 KB

Fair-launch platform for new tokens. Anyone can create a token by paying a small fee; the price follows a linear bonding curve (price = base + slope × supply). When a token's market cap hits the graduation threshold, it automatically migrates liquidity to a LichenSwap pool — no rugs, no presales.

Configuration
Constant Value
CREATION_FEE 10 LICN per token launch
GRADUATION_MCAP 100,000 LICN
BASE_PRICE 1,000 spores (0.000001 LICN)
SLOPE 1 (linear curve)
PLATFORM_FEE 1% on each trade
Functions
initializecreate_tokenbuysellget_token_infoget_buy_quoteget_token_countget_platform_statspauseunpausefreeze_tokenunfreeze_tokenset_buy_cooldownset_sell_cooldownset_max_buyset_creator_royaltywithdraw_feesset_licn_tokenset_dex_addressesget_graduation_info
DeFi

SporePay

Streaming Payments
2,114 lines18 fns17.4 KB

Sablier-style payment streaming for real-time payroll, subscriptions, and vesting. A sender locks LICN and sets a time window; the recipient can withdraw proportionally as slots pass. Senders can cancel at any time — unstreamed funds return automatically. Supports LichenID identity gating so streams can require a minimum reputation score.

How It Works
  • create_stream — sender locks total amount with start/end slot window
  • withdraw_from_stream — recipient claims accrued amount
  • cancel_stream — sender reclaims remaining unstreamed balance
  • Identity gate: admin can set a LichenID reputation threshold
Functions
create_streamwithdraw_from_streamcancel_streamget_streamget_withdrawablecreate_stream_with_clifftransfer_streaminitialize_cp_adminset_token_addressset_self_addresspauseunpauseget_stream_infoset_identity_adminset_lichenid_addressset_identity_gateget_stream_countget_platform_stats
DeFiLichenID

SporeVault

Auto-Compounding Yield Aggregator
1,698 lines19 fns17.0 KB

ERC-4626-style vault that optimizes yield across Lichen DeFi protocols. Depositors receive shares; the vault routes capital to up to 5 strategies (ThallLend lending, LichenSwap LP, staking). harvest() compounds returns and takes a 10% performance fee. Minimum locked shares prevent the ERC-4626 inflation attack (T5.9).

Configuration
Constant Value
PERFORMANCE_FEE 10% of harvested yield
MANAGEMENT_FEE ~2% annual (25 BPS/slot)
MAX_STRATEGIES 5 active strategies
MIN_LOCKED_SHARES 1,000 (anti-inflation attack)
Strategy Types
ID Strategy
1 Lending (ThallLend deposits)
2 LP Provision (LichenSwap liquidity)
3 Staking
Functions
initializeadd_strategydepositwithdrawset_protocol_addressesharvestget_vault_statsget_user_positionget_strategy_infocv_pausecv_unpauseset_deposit_feeset_withdrawal_feeset_deposit_capset_risk_tierremove_strategywithdraw_protocol_feesupdate_strategy_allocationset_licn_token
DeFi

LichenID

Agent Identity & Reputation System
6,688 lines59 fns43.0 KB

The largest and most critical contract in Lichen. LichenID is the on-chain identity layer for AI agents. Register your agent, build reputation through actions and vouches, claim a .lichen domain name, earn skill attestations, and carry your identity across the entire ecosystem. Six other contracts integrate LichenID for gating and verification.

Core Systems
  • Identity Registration — name, agent type (trading, dev, analyst, etc.), starting reputation
  • Reputation — earned through actions and vouches; starts at 100, ceiling 100K
  • .LICN Naming — DNS-like agent names; 3-char = 500 LICN, 4-char = 100 LICN, 5+ = 20 LICN; annual renewal
  • Vouching — agents vouch for each other; costs rep to vouch, rewards the vouchee
  • Skills & Attestations — register up to 16 skills; other agents attest abilities
  • Achievements — contribution badges awarded by admin
  • Agent Profiles — metadata, endpoint URL, availability status, rate
  • Trust Tiers — computed from reputation score
Reputation Constants
Constant Value
INITIAL_REPUTATION 100 — starting score on registration
MAX_REPUTATION 100,000 — reputation ceiling
VOUCH_COST 5 — deducted from voucher
VOUCH_REWARD 10 — granted to vouchee
MIN_REPUTATION 0 — floor
.lichen Name Pricing
Name Length Cost (spores)
3 characters 500,000,000,000 (500 LICN)
4 characters 100,000,000,000 (100 LICN)
5+ characters 20,000,000,000 (20 LICN)
Agent Types
ID Type
0 Unknown
1 Trading
2 Development
3 Analysis
4 Creative
5 Infrastructure
6 Governance
7 Oracle
8 Storage
9 General
10 Personal
Functions (59)
initializeregister_identityget_identityupdate_reputationupdate_reputation_typedadd_skilladd_skill_asget_skillsvouchset_recovery_guardiansapprove_recoveryexecute_recoveryget_reputationdeactivate_identityget_identity_countupdate_agent_typeget_vouchesaward_contribution_achievementget_achievementsattest_skillget_attestationsrevoke_attestationregister_nameresolve_namereverse_resolvecreate_name_auctionbid_name_auctionfinalize_name_auctionget_name_auctiontransfer_namerenew_namerelease_nametransfer_name_asrenew_name_asrelease_name_asset_endpointget_endpointset_metadataget_metadataset_availabilityget_availabilityset_rateget_rateset_delegaterevoke_delegateget_delegateset_endpoint_asset_metadata_asset_availability_asset_rate_asupdate_agent_type_asget_agent_profileget_trust_tiermid_pausemid_unpausetransfer_adminadmin_register_reserved_nameset_mid_token_addressset_mid_self_address
Identity

LichenDAO

Decentralized Governance
1,840 lines26 fns18.5 KB

On-chain governance with token-weighted voting, tiered proposal types, treasury management, and veto power. Proposals stake 10,000 LICN; a 20% veto threshold can block contentious changes. Supports reputation-weighted voting via LichenID.

Proposal Types
Type Voting Approval Quorum Time-lock
Fast Track 24 hours 60% None 1 hour
Standard 7 days 50% 10% 7 days
Constitutional 30 days 75% 30% 7 days
Functions (26)
initialize_daocreate_proposalcreate_proposal_typedvotevote_with_reputationexecute_proposalveto_proposalcancel_proposaltreasury_transferget_treasury_balanceget_proposalget_dao_statsget_active_proposalsinitializecast_votefinalize_proposalget_proposal_countget_voteget_vote_countget_total_supplyset_quorumset_voting_periodset_timelock_delaydao_pausedao_unpauseset_lichenid_address
Governance

LichenPunks

MT-721 NFT Standard
748 lines21 fns8.9 KB

Reference NFT implementation following the MT-721 standard. Supports minting with arbitrary metadata, ownership transfer, approval delegation, transfer-from (marketplace compatibility), burning, and balance/supply queries. The blueprint all Lichen NFT collections are built on.

Functions (21)
initializeminttransferowner_ofbalance_ofapprovetransfer_fromburntotal_mintedmint_punktransfer_punkget_owner_ofget_total_supplyget_punk_metadataget_punks_by_ownerset_base_uriset_max_supplyset_royaltymp_pausemp_unpauseget_collection_stats
NFT

LichenMarket

NFT Marketplace
2,053 lines26 fns8.5 KB

Fixed-price NFT marketplace demonstrating Lichen's cross-contract composability. Sellers list NFTs with a price; buyers pay in any token. The marketplace takes a 2.5% fee, executes the NFT transfer via call_nft_transfer, and routes payment via call_token_transfer — all in one atomic transaction.

Configuration
Constant Value
DEFAULT_FEE_BPS 250 (2.5%)
Functions (26)
initializelist_nftbuy_nftcancel_listingget_listingset_marketplace_feelist_nft_with_royaltymake_offercancel_offeraccept_offerget_marketplace_statsset_nft_attributesget_nft_attributesget_offer_countupdate_listing_pricecreate_auctionplace_bidsettle_auctioncancel_auctionget_auctionmake_collection_offeraccept_collection_offercancel_collection_offermake_offer_with_expirymm_pausemm_unpause
NFT

LichenAuction

English Auctions & Offers
1,469 lines16 fns35.5 KB

Advanced NFT auction house supporting English auctions (ascending bid), direct offers, creator royalties, and per-collection statistics. Auctions run for a configurable duration (default 24h) with a minimum bid increment (default 5%). When finalized, royalties are paid, the marketplace fee is deducted, and the NFT transfers atomically.

Configuration
Constant Value
AUCTION_DURATION 86,400 seconds (24 hours)
MIN_BID_INCREMENT 5% above previous bid
AUCTION_SIZE 169 bytes per auction record
Functions (16)
initializecreate_auctionplace_bidfinalize_auctionmake_offeraccept_offerset_royaltyupdate_collection_statsget_collection_statsset_reserve_pricecancel_auctioninitialize_ma_adminma_pausema_unpauseget_auction_infoget_auction_stats
NFT

LichenOracle

Price Feeds, VRF & Attestations
1,341 lines24 fns16.4 KB

Oracle contract providing three services: price feeds (owner-authorized feeders submit prices per asset, max 1h staleness), verifiable random function (VRF) (commit-reveal scheme for provably fair randomness), and data attestations (arbitrary signed data with on-chain verification). It complements, rather than replaces, the native validator oracle used for consensus price surfaces.

Configuration
Constant Value
MAX_STALENESS 3,600 seconds (1 hour)
PRICE_FEED_SIZE 49 bytes (price + timestamp + decimals + feeder)
Functions (24)
initialize_oracleadd_price_feederset_authorized_attestersubmit_priceget_pricecommit_randomnessreveal_randomnessrequest_randomnessget_randomnesssubmit_attestationverify_attestationget_attestation_dataquery_oracleget_aggregated_priceget_oracle_statsinitializeregister_feedget_feed_countget_feed_listadd_reporterremove_reporterset_update_intervalmo_pausemo_unpause
Infrastructure

LichenBridge

Cross-Chain Lock-and-Mint Bridge
2,653 lines21 fns16.2 KB

Cross-chain bridge using the lock-and-mint pattern. Lock LICN on Lichen → bridge validators confirm → mint wrapped tokens on the destination chain. Burn wrapped tokens externally → validators confirm → unlock on Lichen. Requires 2 validator confirmations. Integrates LichenID identity gating.

Configuration
Constant Value
REQUIRED_CONFIRMATIONS 2 validators
BRIDGE_TX_SIZE 115 bytes per transaction record
Transaction States
PENDING Awaiting validator confirmations
COMPLETED Fully confirmed and executed
CANCELLED Cancelled / refunded
Functions
initializeadd_bridge_validatorremove_bridge_validatorset_required_confirmationsset_request_timeoutlock_tokenssubmit_mintconfirm_mintsubmit_unlockconfirm_unlockcancel_expired_requestget_bridge_statushas_confirmed_minthas_confirmed_unlockis_source_tx_usedis_burn_proof_usedset_lichenid_addressset_identity_gatemb_pausemb_unpauseset_token_address
InfrastructureLichenID

BountyBoard

On-Chain Bounty & Task Management
1,389 lines16 fns16.0 KB

Decentralized task marketplace where creators post bounties with LICN rewards and deadlines, workers submit proof of completion, and creators approve to release payment. Supports LichenID identity gating so bounties can require a minimum reputation.

How It Works
  • create_bounty — lock reward LICN and set deadline
  • submit_work — worker submits proof hash
  • approve_work — creator approves, worker gets paid + reputation boost
  • cancel_bounty — creator cancels open bounty for refund
Functions (16)
create_bountysubmit_workapprove_workcancel_bountyget_bountyset_identity_adminset_lichenid_addressset_identity_gateset_token_addressinitializeapprove_submissionget_bounty_countset_platform_feebb_pausebb_unpauseget_platform_stats
InfrastructureLichenID

Compute Market

Decentralized Compute Marketplace
2,323 lines34 fns16.9 KB

On-chain marketplace for decentralized compute resources. Providers register CPU/GPU/memory; requesters submit jobs with a code hash and payment; providers claim and complete jobs. Built-in dispute mechanism for invalid results. LichenID ensures only reputable providers participate.

Job States
PENDING Open, awaiting provider claim
CLAIMED Provider working on it
COMPLETED Provider submitted result, payment released
DISPUTED Requester challenged the result
Functions (34)
register_providersubmit_jobclaim_jobcomplete_jobdispute_jobget_jobset_identity_adminset_lichenid_addressset_identity_gateinitializeset_claim_timeoutset_complete_timeoutset_challenge_periodadd_arbitratorremove_arbitratorcancel_jobrelease_paymentresolve_disputedeactivate_providerreactivate_providerupdate_providerget_escrowcreate_jobaccept_jobsubmit_resultconfirm_resultget_job_infoget_job_countget_provider_infoset_platform_feecm_pausecm_unpauseget_platform_statsset_token_address
InfrastructureLichenID

Moss Storage

Decentralized Storage Layer
1,694 lines17 fns14.7 KB

On-chain coordination layer for decentralized data storage. Data owners submit storage requests with a data hash, desired replication factor, and payment. Storage providers register capacity and confirm storage. Providers earn rewards proportional to duration × data size. Up to 10× replication across 16 providers.

Configuration
Constant Value
MAX_REPLICATION 10 copies
MIN_STORAGE_DURATION 1,000 slots
MAX_PROVIDERS 16 per storage entry
REWARD_PER_SLOT_PER_BYTE 10 spores
Functions (17)
store_dataconfirm_storageget_storage_inforegister_providerclaim_storage_rewardsinitializeset_challenge_windowset_slash_percentstake_collateralset_storage_priceget_storage_priceget_provider_stakeissue_challengerespond_challengeslash_providerget_platform_statsset_licn_token
Infrastructure

DEX Core

Central Limit Order Book & Matching Engine
3,873 lines29 fns56 KB

The heart of Lichen DEX. A full central limit order book (CLOB) with price-time priority matching, self-trade prevention, and stop-limit activation. Supports pair creation, order lifecycle (place/cancel/modify), and real-time order book queries. Fee structure: -1 BPS maker rebate, 5 BPS taker fee. Revenue split: 60% protocol, 20% LP rewards, 20% stakers.

Storage Layout
Structure Size
Order 128 bytes (trader, pair_id, side, type, price, qty, filled, status, slots, order_id)
Trading Pair 112 bytes (tokens, pair_id, tick/lot size, fees, volume)
Functions (29)
initializeset_preferred_quoteadd_allowed_quotecreate_pairupdate_pair_feespause_pairunpause_pairplace_ordercancel_ordercancel_all_ordersmodify_orderset_analytics_addressset_margin_addressemergency_pauseemergency_unpauseget_orderget_best_bidget_best_askget_spreadget_pair_infoget_trade_countget_pair_countcheck_triggers

Reduce-only orders: Set order_type | 0x80 to flag reduce-only. Cross-validates against dex-margin open positions. Returns code 12 on rejection. set_margin_address (opcode 30): admin-only, links to dex-margin contract for validation.

DEX

DEX AMM

Concentrated Liquidity Pools
1,850 lines17 fns41 KB

Uniswap V3-style concentrated liquidity AMM with Q64.64 fixed-point math. LPs provide liquidity within custom tick ranges for capital-efficient market making. Four fee tiers (1/5/30/100 bps) with dynamic tick spacing. Integrates with DEX Router for hybrid CLOB+AMM order filling.

Fee Tiers
Tier Fee Tick Spacing Use Case
0 1 bps 1 Stablecoins
1 5 bps 10 Correlated pairs
2 30 bps 60 Standard pairs
3 100 bps 200 Exotic / volatile
Functions (17)
create_pooladd_liquidityremove_liquiditycollect_feesswap_exact_inget_pool_infoquote_swapset_fee_tierget_fee_tieramm_pauseamm_unpauseget_pool_countget_tvlget_swap_countget_pool_fee_infoset_core_addressset_rewards_address
DEX

DEX Router

Smart Order Routing Engine
1,193 lines12 fns28 KB

Aggregates liquidity across CLOB, concentrated AMM, and legacy LichenSwap pools for optimal execution. Supports direct fills, split CLOB+AMM orders, multi-hop routing (A→B→C through intermediaries), and cross-pool sequencing. Finds the best price path automatically.

Route Types
  • Direct CLOB — single order book fill
  • Direct AMM — single pool swap
  • Split CLOB+AMM — partial fill from each venue
  • Multi-hop — A→B→C through intermediary tokens
  • Cross-pool — multiple AMM pools in sequence
Functions (12)
initializeset_addressesregister_routeset_route_enabledswapmulti_hop_swapget_best_routeemergency_pauseemergency_unpauseget_route_countget_swap_countget_route_info
DEX

DEX Governance

Pair Listing & Fee Voting
1,779 lines18 fns22 KB

Decentralized governance for DEX operations. Community proposes and votes on new trading pair listings and fee schedule changes. Listing requirements: minimum 10K LICN liquidity, 10 holders, LichenID reputation ≥ 500. 48-hour voting window, 66% approval threshold. Admin can emergency delist pairs. execute_proposal now performs real cross-contract dispatch: NEW_PAIR calls dex_core::create_pair, FEE_CHANGE calls dex_core::update_pair_fees, DELIST calls dex_core::pause_pair. All executions write audit trail to gov_exec_* storage keys.

Functions (18)
propose_new_pairvoteexecute_proposalpropose_fee_changefinalize_proposalemergency_delistset_listing_requirementsemergency_pauseemergency_unpauseset_lichenid_addressget_proposal_countget_proposal_infoset_preferred_quoteadd_allowed_quoteremove_allowed_quoteget_allowed_quote_countget_preferred_quote
DEXLichenID

DEX Rewards

Trading Incentives & Referrals
1,326 lines19 fns18 KB

Tiered trading rewards with volume-based multipliers, LP incentives, and a referral programme. Referrers earn 10% of referee fees (15% with LichenID verification). Referees get 5% fee discount for 30 days. Monthly epoch cap: 100K LICN/month (resets after 2,592,000 slots). Trades after budget exhaustion receive 0 reward until next epoch.

Trading Tiers
Tier Volume Multiplier
Bronze < $10K 1x
Silver $10K – $100K 1.5x
Gold $100K – $1M 2x
Diamond > $1M 3x
Functions (19)
claim_trading_rewardsclaim_lp_rewardsget_pending_rewardsset_reward_rateregister_referralget_trading_tierrecord_trade_volumerecord_lp_actionset_boosted_pairsset_epoch_durationget_epoch_infoset_core_addressset_amm_addressset_lichenid_addressdr_pausedr_unpauseget_referral_countget_trader_volumeget_total_distributed
DEXLichenID

DEX Margin

Leveraged Trading & Liquidation Engine
3,176 lines32 fns27 KB

Isolated and cross-margin leverage trading up to 100x (isolated) / 3x (cross). Automated liquidation engine triggers when health drops below 10%. Liquidation penalty split 50/50 between liquidator bonus and insurance fund. Socialized loss if insurance fund is depleted. Funding rate settlements every 8 hours. Oracle safety: close_position, partial_close, and remove_margin now reject (codes 5/7) when oracle price is unavailable — prevents zero-PnL exits during outages.

Configuration
Parameter Value
Max Leverage (Isolated) 100x (tiered 2x–100x)
Max Leverage (Cross) 3x
Initial Margin 1% (100x) to 50% (2x)
Maintenance Margin 10%
Liquidation Penalty 5%
Insurance Fund Share 50% of penalties
Funding Rate Every 8 hours
Functions (32)
open_positionopen_position_with_modeclose_positionclose_position_limitpartial_closepartial_close_limitadd_marginremove_marginliquidateset_mark_priceset_index_priceapply_fundingenable_margin_pairdisable_margin_pairis_margin_enabledset_max_leverageset_maintenance_marginget_tier_infoget_maintenance_margin_overrideget_position_countget_insurance_fundget_position_infoget_margin_ratioquery_user_open_positionset_position_sl_tpwithdraw_insuranceset_lichencoin_addressemergency_pauseemergency_unpause
DEX

DEX Analytics

On-Chain OHLCV, Stats & Leaderboards
1,279 lines11 fns21 KB

On-chain analytics engine recording every trade as OHLCV candles across nine time intervals (1m, 5m, 15m, 1H, 4H, 1D, 1W, 1M, 1Y). Provides 24h pair stats, per-trader stats, and volume leaderboards. Feeds DEX TWAP prices to LichenOracle for use by ThallLend collateral valuation and SporeVault pricing.

Candle Configuration
Interval Rolling Window Size
1 minute 1,440 candles (24h) 48 bytes each
5 minutes 288 candles (24h) 48 bytes each
15 minutes 96 candles (24h) 48 bytes each
1 hour 168 candles (7d) 48 bytes each
4 hours 180 candles (30d) 48 bytes each
1 day 365 candles (1y) 48 bytes each
1 week 104 candles (2y) 48 bytes each
1 month 60 candles (5y) 48 bytes each
1 year 10 candles (10y) 48 bytes each
Functions (11)
record_traderecord_pnlget_ohlcvget_24h_statsget_trader_statsget_last_priceget_record_countemergency_pauseemergency_unpauseset_authorized_caller
DEX

Prediction Market

Binary Outcome Markets
5,144 lines37 fns38 KB

Full prediction market with AMM pricing, liquidity pools, oracle-based resolution, DAO arbitration, and share redemption. Opcode-dispatch ABI. Multi-outcome sell uses binary search over total_a_for_sets() for exact computation. Return values from create_market, buy_shares, sell_shares, add_liquidity, withdraw_liquidity write full u64 to set_return_data() to avoid u32 truncation.

Opcodes (24)
Opcode Function Description
0 create_market Create binary outcome market
1 buy_shares Buy outcome shares via AMM
2 sell_shares Sell shares back to AMM
3 add_liquidity Provide AMM liquidity
4 add_initial_liquidity Bootstrap new market pool
5 mint_complete_set Mint all outcome tokens
6 redeem_complete_set Redeem matched outcomes
7 get_market Query market state
8 submit_resolution Submit resolution oracle
9 challenge_resolution Challenge pending resolution
10 finalize_resolution Finalize after challenge period
11 dao_resolve DAO override resolution
12 dao_void DAO void market
13 redeem_shares Redeem winning shares
14 reclaim_collateral Reclaim from voided market
15 withdraw_liquidity LP withdraw
22 close_market Close expired market
DeFiPrediction

lUSD Stablecoin

Treasury-Backed Stablecoin
1,178 lines20 fns23.5 KB

Treasury-backed stablecoin contract with mint/burn mechanics, reserve attestation, epoch rate-limiting, and circuit breaker protection. Implements the MT-20 interface for seamless integration with the Lichen DeFi stack.

Configuration
Constant Value
EPOCH_RATE_LIMIT 100,000 lUSD/epoch
CIRCUIT_BREAKER_THRESHOLD 50,000 lUSD
Functions (20)
initializemintburntransferapprovetransfer_fromattest_reservesbalance_ofallowancetotal_supplytotal_mintedtotal_burnedget_reserve_ratioget_last_attestation_slotget_attestation_countget_epoch_remainingget_transfer_countemergency_pauseemergency_unpausetransfer_admin
DeFiStablecoin

Wrapped ETH

Wrapped ETH Bridge Token
853 lines20 fns23.5 KB

Wrapped ETH bridge token with epoch rate-limited minting, reserve attestation, and circuit breaker protection. Used as the canonical ETH representation on Lichen for cross-chain DeFi.

Configuration
Constant Value
EPOCH_RATE_LIMIT 500 ETH/epoch
CIRCUIT_BREAKER_THRESHOLD Configurable
Functions (20)
initializemintburntransferapprovetransfer_fromattest_reservesbalance_ofallowancetotal_supplytotal_mintedtotal_burnedget_reserve_ratioget_last_attestation_slotget_attestation_countget_epoch_remainingget_transfer_countemergency_pauseemergency_unpausetransfer_admin
BridgeToken

Wrapped SOL

Wrapped SOL Bridge Token
853 lines20 fns23.5 KB

Wrapped SOL bridge token with epoch rate-limited minting, reserve attestation, and circuit breaker protection. Used as the canonical SOL representation on Lichen for cross-chain DeFi.

Configuration
Constant Value
EPOCH_RATE_LIMIT 50,000 SOL/epoch
CIRCUIT_BREAKER_THRESHOLD Configurable
Functions (20)
initializemintburntransferapprovetransfer_fromattest_reservesbalance_ofallowancetotal_supplytotal_mintedtotal_burnedget_reserve_ratioget_last_attestation_slotget_attestation_countget_epoch_remainingget_transfer_countemergency_pauseemergency_unpausetransfer_admin
BridgeToken

Wrapped BNB

Wrapped BNB Bridge Token
854 lines20 fns23.5 KB

Wrapped BNB bridge token with epoch rate-limited minting, reserve attestation, and circuit breaker protection. Used as the canonical BNB representation on Lichen for cross-chain DeFi.

Configuration
Constant Value
EPOCH_RATE_LIMIT 5,000 BNB/epoch
CIRCUIT_BREAKER_THRESHOLD Configurable
Functions (20)
initializemintburntransferapprovetransfer_fromattest_reservesbalance_ofallowancetotal_supplytotal_mintedtotal_burnedget_reserve_ratioget_last_attestation_slotget_attestation_countget_epoch_remainingget_transfer_countemergency_pauseemergency_unpausetransfer_admin
BridgeToken

Shielded Pool

ZK-Private Transaction Pool
924 lines10 fns18 KB

On-chain contract managing the shielded transaction pool for ZK-private transfers. Stores the commitment Merkle tree root, spent nullifier set, and verification keys. Verifies Groth16/BN254 ZK proofs (128-byte) and updates state. Three core operations: shield (deposit into pool), unshield (withdraw from pool), and transfer (private transfer within pool). Uses reentrancy guard and admin pause control.

Functions (10)
initializeshieldunshieldtransferpauseunpauseget_pool_statsget_merkle_rootcheck_nullifierget_commitments
InfrastructurePrivacy

Authoritative Live Export Matrix (Source-Derived)

This matrix is generated from real contract source exports (contracts/*/src/lib.rs, #[no_mangle] pub extern "C" fn ...) and is the authoritative surface. Some per-card function chips above are legacy summaries; use this section for strict agent/runtime compatibility.

Contract Exported Functions (source of truth)
lichencoin initialize, balance_of, transfer, mint, burn, approve, total_supply, transfer_from
lichenswap initialize, add_liquidity, remove_liquidity, swap_a_for_b, swap_b_for_a, swap_a_for_b_with_deadline, swap_b_for_a_with_deadline, get_quote, get_reserves, get_liquidity_balance, get_total_liquidity, flash_loan_borrow, flash_loan_repay, flash_loan_abort, get_flash_loan_fee, get_twap_cumulatives, get_twap_snapshot_count, set_protocol_fee, get_protocol_fees, set_identity_admin, set_lichenid_address, set_reputation_discount, ms_pause, ms_unpause, create_pool, swap, get_pool_info, get_pool_count, set_platform_fee, get_swap_count, get_total_volume, get_swap_stats
thalllend initialize, deposit, withdraw, borrow, repay, liquidate, get_account_info, get_protocol_stats, flash_borrow, flash_repay, pause, unpause, set_deposit_cap, set_reserve_factor, withdraw_reserves, get_interest_rate, get_deposit_count, get_borrow_count, get_liquidation_count, get_platform_stats, set_lichencoin_address
sporepump initialize, create_token, buy, sell, get_token_info, get_buy_quote, get_token_count, get_platform_stats, pause, unpause, freeze_token, unfreeze_token, set_buy_cooldown, set_sell_cooldown, set_max_buy, set_creator_royalty, withdraw_fees, set_dex_addresses, get_graduation_info, set_licn_token
sporepay create_stream, withdraw_from_stream, cancel_stream, get_stream, get_withdrawable, create_stream_with_cliff, transfer_stream, initialize_cp_admin, pause, unpause, get_stream_info, set_identity_admin, set_lichenid_address, set_identity_gate, get_stream_count, get_platform_stats, set_token_address, set_self_address
sporevault initialize, add_strategy, deposit, withdraw, set_protocol_addresses, harvest, get_vault_stats, get_user_position, get_strategy_info, cv_pause, cv_unpause, set_deposit_fee, set_withdrawal_fee, set_deposit_cap, set_risk_tier, remove_strategy, withdraw_protocol_fees, update_strategy_allocation, set_licn_token
lichenid initialize, register_identity, get_identity, update_reputation_typed, update_reputation, add_skill, add_skill_as, get_skills, vouch, set_recovery_guardians, approve_recovery, execute_recovery, get_reputation, deactivate_identity, get_identity_count, update_agent_type, get_vouches, award_contribution_achievement, get_achievements, attest_skill, get_attestations, revoke_attestation, register_name, resolve_name, reverse_resolve, create_name_auction, bid_name_auction, finalize_name_auction, get_name_auction, transfer_name, renew_name, release_name, transfer_name_as, renew_name_as, release_name_as, set_endpoint, get_endpoint, set_metadata, get_metadata, set_availability, get_availability, set_rate, get_rate, set_delegate, revoke_delegate, get_delegate, set_endpoint_as, set_metadata_as, set_availability_as, set_rate_as, update_agent_type_as, get_agent_profile, get_trust_tier, mid_pause, mid_unpause, transfer_admin, admin_register_reserved_name, set_mid_token_address, set_mid_self_address
lichendao initialize_dao, create_proposal, create_proposal_typed, vote, vote_with_reputation, execute_proposal, veto_proposal, cancel_proposal, treasury_transfer, get_treasury_balance, get_proposal, get_dao_stats, get_active_proposals, initialize, cast_vote, finalize_proposal, get_proposal_count, get_vote, get_vote_count, get_total_supply, set_quorum, set_voting_period, set_timelock_delay, dao_pause, dao_unpause, set_lichenid_address
lichenpunks initialize, mint, transfer, owner_of, balance_of, approve, transfer_from, burn, total_minted, mint_punk, transfer_punk, get_owner_of, get_total_supply, get_punk_metadata, get_punks_by_owner, set_base_uri, set_max_supply, set_royalty, mp_pause, mp_unpause, get_collection_stats
lichenmarket initialize, list_nft, buy_nft, cancel_listing, get_listing, set_marketplace_fee, list_nft_with_royalty, make_offer, cancel_offer, accept_offer, get_marketplace_stats, set_nft_attributes, get_nft_attributes, get_offer_count, update_listing_price, create_auction, place_bid, settle_auction, cancel_auction, get_auction, make_collection_offer, accept_collection_offer, cancel_collection_offer, make_offer_with_expiry, mm_pause, mm_unpause
lichenauction create_auction, place_bid, finalize_auction, make_offer, accept_offer, set_royalty, update_collection_stats, get_collection_stats, initialize, set_reserve_price, cancel_auction, initialize_ma_admin, ma_pause, ma_unpause, get_auction_info, get_auction_stats
lichenoracle initialize_oracle, add_price_feeder, set_authorized_attester, submit_price, get_price, commit_randomness, reveal_randomness, request_randomness, get_randomness, submit_attestation, verify_attestation, get_attestation_data, query_oracle, get_aggregated_price, get_oracle_stats, initialize, register_feed, get_feed_count, get_feed_list, add_reporter, remove_reporter, set_update_interval, mo_pause, mo_unpause
lichenbridge initialize, add_bridge_validator, remove_bridge_validator, set_required_confirmations, set_request_timeout, lock_tokens, submit_mint, confirm_mint, submit_unlock, confirm_unlock, cancel_expired_request, get_bridge_status, has_confirmed_mint, has_confirmed_unlock, is_source_tx_used, is_burn_proof_used, set_lichenid_address, set_identity_gate, mb_pause, mb_unpause, set_token_address
bountyboard create_bounty, submit_work, approve_work, cancel_bounty, get_bounty, set_identity_admin, set_lichenid_address, set_identity_gate, set_token_address, initialize, approve_submission, get_bounty_count, set_platform_fee, bb_pause, bb_unpause, get_platform_stats
compute_market register_provider, submit_job, claim_job, complete_job, dispute_job, get_job, initialize, set_claim_timeout, set_complete_timeout, set_challenge_period, add_arbitrator, remove_arbitrator, cancel_job, release_payment, resolve_dispute, deactivate_provider, reactivate_provider, update_provider, get_escrow, set_identity_admin, set_lichenid_address, set_identity_gate, create_job, accept_job, submit_result, confirm_result, get_job_info, get_job_count, get_provider_info, set_platform_fee, cm_pause, cm_unpause, get_platform_stats, set_token_address
moss_storage store_data, confirm_storage, get_storage_info, register_provider, claim_storage_rewards, initialize, set_challenge_window, set_slash_percent, stake_collateral, set_storage_price, get_storage_price, get_provider_stake, issue_challenge, respond_challenge, slash_provider, get_platform_stats, set_licn_token
dex_core initialize, call
dex_amm initialize, call
dex_router call
dex_governance initialize, call
dex_rewards initialize, call
dex_margin call
dex_analytics initialize, call
prediction_market initialize, call
lusd_token initialize, mint, burn, transfer, approve, transfer_from, attest_reserves, balance_of, allowance, total_supply, total_minted, total_burned, get_reserve_ratio, get_last_attestation_slot, get_attestation_count, get_epoch_remaining, get_transfer_count, emergency_pause, emergency_unpause, transfer_admin
weth_token initialize, mint, burn, transfer, approve, transfer_from, attest_reserves, balance_of, allowance, total_supply, total_minted, total_burned, get_reserve_ratio, get_last_attestation_slot, get_attestation_count, get_epoch_remaining, get_transfer_count, emergency_pause, emergency_unpause, transfer_admin
wsol_token initialize, mint, burn, transfer, approve, transfer_from, attest_reserves, balance_of, allowance, total_supply, total_minted, total_burned, get_reserve_ratio, get_last_attestation_slot, get_attestation_count, get_epoch_remaining, get_transfer_count, emergency_pause, emergency_unpause, transfer_admin
shielded_pool initialize, shield, unshield, transfer, pause, unpause, get_pool_stats, get_merkle_root, check_nullifier, get_commitments
wbnb_token initialize, mint, burn, transfer, approve, transfer_from, attest_reserves, balance_of, allowance, total_supply, total_minted, total_burned, get_reserve_ratio, get_last_attestation_slot, get_attestation_count, get_epoch_remaining, get_transfer_count, emergency_pause, emergency_unpause, transfer_admin

Cross-Contract Integration Map

LichenID is the identity backbone — 6 contracts integrate it for reputation gating, fee discounts, and identity verification. DEX contracts cross-reference each other and the core DeFi stack.

Contract LichenID Integration Purpose
LichenSwap set_lichenid_address, set_reputation_discount Fee discounts based on reputation tier
SporePay set_lichenid_address, set_identity_gate Require minimum rep to create streams
LichenBridge set_lichenid_address, set_identity_gate Require verified identity to bridge
BountyBoard set_lichenid_address, set_identity_gate Reputation bounty gating + rep rewards
Compute Market set_lichenid_address, set_identity_gate Only reputable providers can register
LichenDAO vote_with_reputation Reputation-weighted governance voting

DEX Cross-Contract Dependencies

Contract Dependencies Purpose
DEX Router DEX Core, DEX AMM, LichenSwap Aggregate liquidity across all venues
DEX Margin DEX Core, LichenOracle Leveraged orders + oracle price feeds
DEX Analytics DEX Core, LichenOracle TWAP price feeds from trades to oracle
DEX Governance LichenID, LichenCoin Rep-gated pair proposals, LICN voting
DEX Rewards LichenID, LichenCoin LichenID-boosted referrals, LICN distribution

Security Patterns

Pattern Contracts
Reentrancy guard LichenSwap, ThallLend, SporePump, DEX Core, DEX AMM
Admin-only initialization All 29 contracts
Overflow-safe arithmetic All DeFi + DEX contracts
T5.9 inflation attack prevention SporeVault (MIN_LOCKED_SHARES)
T5.10 caller verification LichenOracle
Self-trade prevention DEX Core
Liquidation health checks DEX Margin, ThallLend
Insurance fund backstop DEX Margin (socialized loss)