> ## Documentation Index
> Fetch the complete documentation index at: https://docs.levery.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> A deep dive into Levery’s on-chain design: permissioning, oracle-driven dynamic fees, and soulbound liquidity positions.

Levery is a permissioned on-chain market infrastructure designed for regulated institutions. Instead of relying on front-ends or off-chain middleware to enforce policy, Levery embeds compliance and operational controls directly into smart-contract execution. Every transaction path, from wallet admission to liquidity lifecycle actions and swap execution, runs deterministic checks before any state change. Non-compliant calls revert with explicit reasons; compliant actions execute normally. This gives institutions uniform enforcement, auditable outcomes, and tamper-resistant governance across all user interactions.

Levery’s on-chain architecture is organized into modular domains that work together to provide: permissioning, identity validation, pricing integrity, economic controls, governance, lifecycle enforcement, and transparent treasury operations. Institutions can tailor venue behavior through governed parameters (per pool or global) without weakening core security guarantees.

***

## Core Domains

### Permissioning and Admission Control

Levery enforces “who can do what” at the execution layer. Before swaps or liquidity actions, contracts validate that the initiating account is authorized and meets the pool’s policy requirements (e.g., role-based access, institution rules, and KYC/KYB-derived permissions). This ensures only verified actors can access pools, add/remove liquidity, or trade, while keeping the system non-custodial.

### Controlled Entry Points for Swaps and Liquidity

Levery separates transaction entry points by intent:

#### Swap

**Swap entry** is routed through a compliant execution path that ties the user identity to the call and prevents accidental or unauthorized token reception.

<div className="block dark:hidden">
  ```mermaid theme={null}
  ---
  config:
    theme: neutral
  ---
  flowchart TD
    S_A["Swap request"] --> S_B{"Admission + access checks"}
    S_B -->|Rejected| S_X["Reject swap"]

    S_B -->|Allowed| S_C["Resolve pricing context
    (market reference + pool state)"]
    S_C --> S_D["Compute fees
    (base fee + dynamic adjustment if enabled)"]
    S_D --> S_E["Execute swap + update pool state"]
    S_E --> S_F["Settle outcomes + apply service fee
    (timing: BEFORE or AFTER; charged on actual deltas)"]
    S_F --> S_G["Emit events
    (policy, fees, execution, service fee)"]
  ```
</div>

<div className="hidden dark:block">
  ```mermaid theme={null}
  ---
  config:
    theme: dark
  ---
  flowchart TD
    S_A["Swap request"] --> S_B{"Admission + access checks"}
    S_B -->|Rejected| S_X["Reject swap
    (return reason)"]

    S_B -->|Allowed| S_C["Resolve pricing context
    (market reference + pool state)"]
    S_C --> S_D["Compute fees
    (base fee + dynamic adjustment if enabled)"]
    S_D --> S_E["Execute swap + update pool state"]
    S_E --> S_F["Settle outcomes + apply service fee
    (timing: BEFORE or AFTER; charged on actual deltas)"]
    S_F --> S_G["Emit events
    (policy, fees, execution, service fee)"]
  ```
</div>

<Note>
  Service fees are always denominated in the **input token**. Collection timing depends on swap type:

  * **Exact-input swaps:** collected in `beforeSwap`(BEFORE).
  * **Exact-output swaps:** collected in `afterSwap` (AFTER).

  Fees are routed to the payment splitter vault, which allows transparent revenue-sharing between provider and institution.
</Note>

#### Liquidity

**Liquidity entry** is mediated through a position manager that performs lifecycle checks on mint, increase, decrease, and burn, so permissioning remains enforced across the entire LP journey, not just at creation time.

This structure makes policy enforcement consistent while keeping the user experience predictable and institution-friendly.

<div className="block dark:hidden">
  ```mermaid theme={null}
  ---
  config:
    theme: neutral
  ---
  flowchart TD
    L_A["Liquidity action request
    (create, add, remove, close)"] --> L_B{"Admission + pool access checks"}
    L_B -->|Rejected| L_X["Reject action"]
    L_B -->|Allowed| L_C["Validate authority
    (bind owner on create; verify owner/recipient on modify)"]

    L_C --> L_D["Compute asset deltas + validate limits
    (deadlines, min amounts, policy constraints)"]
    L_D --> L_E["Execute via liquidity lifecycle entry point"]
    L_E --> L_F["Settle assets as required
    (inputs, outputs, refunds; policy + asset rules)"]
    L_F --> L_G["Update position + pool state"]
    L_G --> L_H["Emit structured events
    (position, deltas, fees, outcomes)"]
  ```
</div>

<div className="hidden dark:block">
  ```mermaid theme={null}
  ---
  config:
    theme: dark
  ---
  flowchart TD
    L_A["Liquidity action request
    (create, add, remove, close)"] --> L_B{"Admission + pool access checks"}
    L_B -->|Rejected| L_X["Reject action
    (return reason)"]
    L_B -->|Allowed| L_C["Validate authority
    (bind owner on create; verify owner/recipient on modify)"]

    L_C --> L_D["Compute asset deltas + validate limits
    (deadlines, min amounts, policy constraints)"]
    L_D --> L_E["Execute via liquidity lifecycle entry point"]
    L_E --> L_F["Settle assets as required
    (inputs, outputs, refunds; policy + asset rules)"]
    L_F --> L_G["Update position + pool state"]
    L_G --> L_H["Emit structured events
    (position, deltas, fees, outcomes)"]
  ```
</div>

### Oracle-Guided Pricing Integrity and Dynamic Fees

Levery integrates decentralized price-feed oracles to anchor execution to external market references and to compute dynamic fees. Pools can be configured with an oracle reference and comparison rules, and the protocol adjusts fees in response to oracle-to-pool divergence to reduce toxic flow and protect liquidity providers, while maintaining competitive pricing for traders.

To preserve pricing integrity, the oracle layer includes safeguards such as:

* **On‑demand Queries:** Price feeds only invoked in swap hooks, minimizing gas overhead for liquidity ops.
* **Decimal Normalization:** Safe adjustments to align feed decimals with token decimals, preventing mispricing.
* **Zero‑price Guard:** Immediate revert on zero or stale oracle values to prevent erroneous fee calcs.

#### Price‑Feed Oracle Integration

Levery supports per‑pool oracle configuration via `setPoolOracle()`.

* **Adapters & decimals** – Each pool stores `{oracle, compareWithPrice0}`. The returned feed value is scaled to match the token decimals before comparison.
* **Deviation logic** – `beforeSwap` calculates `price0 / price1` on‑chain, fetches market price `M` and applies the formula:

$$
F_{swap}=F_{base}+\bigl|\tfrac{P_{onchain}-M}{M}\bigr|\times \texttt{deviationFeeFactor}
$$

* **Capped multiplier** – `deviationFeeFactor` (ppm) is clamped to $0,1$, guaranteeing the fee never overshoots the absolute price delta.

Let:

* $P_0$ and $P_1$ be the current prices for asset 0 and asset 1, respectively.
* $M$ be the real-time market price from the Oracle.
* $\alpha$ `deviationFeeFactor` be the liquidity provider fee multiplier.
* $F_{\text{base}}$ be the base fee for the swap.
* $F_{\text{pool}}$ be the pool-specific fee for the swap, which takes precedence over $F_{\text{base}}$ if defined.

#### Initial Swap Fee Definition

The initial swap fee $F_{\text{swap}}$ is defined as:

$$
F_{\text{swap}} =
\begin{cases}
F_{\text{pool}} & \text{if } F_{\text{pool}} \neq 0 \\
F_{\text{base}} & \text{otherwise}
\end{cases}
$$

#### Price Comparison and Fee Adjustment

If a market price oracle is defined, we adjust $F_{\text{swap}}$ based on the price comparison:

**If `compareWithPrice0` is true:**

$$
F_{\text{swap}} =
\begin{cases}
F_{\text{swap}} + \left( \frac{P_0 - M}{M} \times \alpha \right) & \text{if } P_0 > M \text{ and } \text{params.zeroForOne} \\
F_{\text{swap}} + \left( \frac{M - P_0}{M} \times \alpha \right) & \text{if } P_0 < M \text{ and not } \text{params.zeroForOne} \\
F_{\text{swap}} & \text{otherwise}
\end{cases}
$$

**Else:**

$$
F_{\text{swap}} =
\begin{cases}
F_{\text{swap}} + \left( \frac{M - P_1}{M} \times \alpha \right) & \text{if } P_1 < M \text{ and } \text{params.zeroForOne} \\
F_{\text{swap}} + \left( \frac{P_1 - M}{M} \times \alpha \right) & \text{if } P_1 > M \text{ and not } \text{params.zeroForOne} \\
F_{\text{swap}} & \text{otherwise}
\end{cases}
$$

#### Final Fee Update

The updated swap fee is used to update the dynamic LP fee:

$$
\text{poolManager.updateDynamicLPFee}(key, F_{\text{swap}})
$$

### Non-Transferable Liquidity Positions

Liquidity positions are represented as non-transferable ERC-721 tokens bound to their verified owner. This design prevents unauthorized transfers, preserves compliance status across the entire lifecycle, and simplifies compliance reporting by ensuring LP ownership remains traceable and immutable at the protocol level.

Position metadata can be generated in a standardized, auditor-friendly format, enabling transparent reviews of position state (ownership, ranges, and other relevant properties) without relying on off-chain interpretation.

### Configurable Service Fee and Transparent Treasury

Levery supports a programmable service fee that routes to an on-chain vault. The service fee can be applied predictably across swap flows and accrues transparently for accounting. Vault distribution logic is executed by contract and recorded on-chain, enabling clear treasury visibility and optional revenue-sharing models between stakeholders (e.g., provider/institution).

<div className="block dark:hidden">
  ```mermaid theme={null}
  ---
  config:
    theme: neutral
  ---
  flowchart TD
    F_A["Swap executed"] --> F_B["Compute service fee
    (based on actual swap deltas)"]
    F_B --> F_C["Transfer fee to
    Service Fee Vault
    (PaymentSplitter)"]
    F_C --> F_D["Distribute to payees
    (per configured shares)"]
  ```
</div>

<div className="hidden dark:block">
  ```mermaid theme={null}
  ---
  config:
    theme: dark
  ---
  flowchart TD
    F_A["Swap executed"] --> F_B["Compute service fee
    (based on actual swap deltas)"]
    F_B --> F_C["Transfer fee to
    Service Fee Vault
    (PaymentSplitter)"]
    F_C --> F_D["Distribute to payees
    (per configured shares)"]
  ```
</div>

### Governance, Administration, and Operational Safety

On-chain administration allows institutions to:

* update administrators and privileged roles,
* adjust fee parameters globally or per pool,
* update oracle references and pool settings,
* replace the permission manager under controlled procedures.

Levery also includes robust operational controls such as global and per-pool pausing. These controls let institutions isolate incidents, respond to risk events, and comply with procedural requests, without compromising non-custodial guarantees (the protocol restricts actions, but does not seize user funds).

### Auditability by Design

Every decision and execution step emits structured on-chain events that tie policy enforcement to the transaction lifecycle. This makes audits straightforward: institutions can reconstruct “who attempted what, under which policy, and what happened” directly from chain data. The result is a deterministic, evidence-first audit trail aligned with institutional compliance expectations.

***

## Permissioning & governance model

Permissions are represented as explicit, queryable entitlements. This keeps enforcement deterministic and makes audits easier.

### Permission lifecycle

<Steps>
  <Step title="Identity & risk assessment (off-chain)">
    The institution’s compliance stack evaluates KYC/KYB/AML and produces a decision.
  </Step>

  <Step title="Entitlement synchronization (on-chain)">
    The permission registry is updated (grant/revoke) for trade and liquidity actions.
  </Step>

  <Step title="Enforcement at execution time">Trade and liquidity calls verify entitlements before proceeding.</Step>
</Steps>

### Emergency controls

<Steps>
  <Step title="Global pause">
    A provider-level circuit breaker can halt protocol activity across markets during systemic incidents.
  </Step>

  <Step title="Per-market pause">Operators can isolate a single market (pool) without impacting others.</Step>

  <Step title="Recovery & audit trail">
    Pause/unpause actions are evented and indexed, enabling post-incident review.
  </Step>
</Steps>

***

## Why This Design

Levery is built around a simple principle: regulatory assurance should be embedded into protocol logic, not bolted on afterward. By relocating compliance controls, risk checks, pricing integrity rules, and governance into smart contracts, Levery achieves consistent enforcement, strong auditability, and operational flexibility, while keeping markets non-custodial and institution-ready.

<CardGroup cols={2}>
  <Card title="Compliance by design" icon="shield-check">
    Identity, permissions, and risk rules are enforced through an explicit permission layer plus audited operational
    controls.
  </Card>

  <Card title="Institution-grade observability" icon="building-columns">
    Event-sourced indexing, canonicalization, and deterministic snapshots power audit trails, reporting, and risk
    analytics.
  </Card>
</CardGroup>

<Card title="Non-custodial execution" icon="wallet">
  Users keep direct control of funds and keys by default, minimizing counterparty and custody risk. Policy is enforced
  at execution time (not post-trade monitoring).
</Card>

<Note>
  For institutions that require custody, Levery can also integrate HSM-based key storage and signing workflows without
  changing on-chain settlement guarantees.
</Note>

***

## Off-chain architecture: indexing, snapshots, and reporting

Levery uses an event-sourced indexing pipeline that is designed for **correctness under reorgs**, **idempotency**, and **fast UI queries**.

### Indexers

The worker layer runs multiple indexers in parallel. Key responsibilities include:

* **Protocol configuration indexer:** captures global config and per-market policy updates into a `System` and `Pool` snapshot model.
* **Permission indexer:** materializes the latest permissions per account into a `Permission` snapshot model.
* **Market activity indexer:** canonicalizes swaps and liquidity changes, attributes service fees, and writes normalized facts.
* **Price indexer:** ingests oracle feed updates and produces both *latest* and *time-slot* prices for historical valuation.
* **Balance indexers:** create daily and “current” token balance snapshots for every account.
* **Portfolio indexer:** values balances + positions + owed fees at snapshot times for reporting and analytics.
* **Metrics indexers:** compute pool and asset metrics for fast list pages (TVL, volume, APR, market cap, FDV).

<div className="block dark:hidden">
  ```mermaid theme={null}
  ---
  config:
    theme: neutral
  ---
  flowchart TB
    RPC[RPC / Chain Logs]:::box
    IDX[Indexers]:::box
    EVT[(Event Store)]:::db
    SNAP[(Snapshot Tables)]:::db
    MET[(Metrics Tables)]:::db
    API[Levery API]:::box
    UI[UI]:::box

    RPC --> IDX
    IDX --> EVT
    IDX --> SNAP
    IDX --> MET
    API -->|queries| SNAP
    API -->|queries| MET
    UI --> API
  ```
</div>

<div className="hidden dark:block">
  ```mermaid theme={null}
  ---
  config:
    theme: dark
  ---
  flowchart TB
    RPC[RPC / Chain Logs]:::box
    IDX[Indexers]:::box
    EVT[(Event Store)]:::db
    SNAP[(Snapshot Tables)]:::db
    MET[(Metrics Tables)]:::db
    API[Levery API]:::box
    UI[UI]:::box

    RPC --> IDX
    IDX --> EVT
    IDX --> SNAP
    IDX --> MET
    API -->|queries| SNAP
    API -->|queries| MET
    UI --> API
  ```
</div>

### Reorg safety & idempotency (why it matters)

To prevent “phantom activity” in regulated reporting:

* Indexers **wait for confirmations** before finalizing blocks.
* Cursors store the **last processed block** and **block hash**; mismatches trigger a bounded rollback.
* Rows are written with deterministic `uid` values (e.g., `chain:txHash:logIndex`) so retries are safe.
* In error paths (e.g., missing receipts), indexers **do not advance cursors**, avoiding silent data gaps.

### Snapshot-first data model

Rather than querying raw events at runtime, the platform materializes “latest state” objects (e.g., `Pool`, `Position`, `Permission`) plus an append-only `Event` history. This structure supports both:

* **Fast UI reads** (lists and dashboards run on precomputed snapshots).
* **Audit-grade reconstruction** (history is preserved and can be replayed or re-derived).

### Valuation correctness

Portfolio valuation aligns **prices**, **balances**, and **market state** to the same snapshot time window. This avoids mismatches such as “balance at time T valued using price at time T+Δ”.

## Extensibility and deployment topology

Levery is designed for multi-network and multi-institution deployments:

* **Per-network configuration:** deployments are described via environment configuration (e.g., contract addresses, token registry).
* **Per-market configuration:** fees, oracle bindings, role requirements, and pause state can be scoped to a market.
* **Composable integrations:** identity/risk providers and reporting systems connect through the platform API and are reflected on-chain via entitlements.

<Callout type="info">
  For regulated deployments, treat the permission registry as your **policy source of truth for execution**, and treat
  the API/indexers as your **source of truth for reporting**.
</Callout>
