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

# Contract Methods

> Public method reference for all Stylus contracts

ouroborai deploys four Stylus (Rust) contracts compiled to WASM on Arbitrum.
All contracts use the Stylus SDK 0.10.0 patterns with `sol_storage!` for
storage and `#[public]` for exposed methods.

<AccordionGroup>
  <Accordion title="AgentRegistry">
    On-chain registry of agent instances with capabilities bitmask,
    revenue sharing, and reputation tracking.

    ### Storage Layout

    | Slot                | Type                          | Description                               |
    | ------------------- | ----------------------------- | ----------------------------------------- |
    | `next_id`           | `uint256`                     | Auto-incrementing agent ID counter        |
    | `governance`        | `address`                     | Governance address for reputation updates |
    | `owners`            | `mapping(uint256 => address)` | Agent ID to owner                         |
    | `capabilities`      | `mapping(uint256 => uint256)` | Agent ID to capability bitmask            |
    | `revenue_share_bps` | `mapping(uint256 => uint256)` | Agent ID to revenue share (basis points)  |
    | `reputation`        | `mapping(uint256 => uint256)` | Agent ID to reputation score              |
    | `active`            | `mapping(uint256 => bool)`    | Agent ID to active status                 |

    ### Capability Flags

    | Flag            | Value    | Description         |
    | --------------- | -------- | ------------------- |
    | `CAP_TRADE`     | `1 << 0` | Spot trading        |
    | `CAP_PERPS`     | `1 << 1` | Perpetual positions |
    | `CAP_LEND`      | `1 << 2` | Lending/borrowing   |
    | `CAP_YIELD`     | `1 << 3` | Yield farming       |
    | `CAP_OPTIONS`   | `1 << 4` | Options trading     |
    | `CAP_TIMEBOOST` | `1 << 5` | TimeBoost bidding   |
    | `CAP_RWA`       | `1 << 6` | RWA stock trading   |

    ### Public Methods

    **`register(capabilities: u64, revenue_share_bps: u16) -> Result<U256>`**
    Register a new agent. Caller becomes the owner. Returns the agent ID.
    Reverts if `revenue_share_bps > 10000`.

    **`update(agent_id: U256, capabilities: u64, revenue_share_bps: u16) -> Result<bool>`**
    Update an agent's capabilities and revenue share. Owner only. Returns
    `false` if caller is not the owner.

    **`deactivate(agent_id: U256) -> bool`**
    Deactivate an agent. Callable by owner or governance.

    **`update_reputation(agent_id: U256, new_score: U256) -> bool`**
    Set an agent's reputation score. Governance only.

    **`get_agent(agent_id: U256) -> (Address, U256, U256, U256, bool)`**
    Returns `(owner, capabilities, revenue_share_bps, reputation, active)`.

    **`total_agents() -> U256`**
    Returns the total number of registered agents.

    **`has_capability(agent_id: U256, cap_flag: u64) -> bool`**
    Check if an agent has a specific capability flag.

    **`set_governance(new_governance: Address) -> bool`**
    Set the governance address. Can be called by anyone if governance is
    unset (zero address), otherwise governance only.

    ### Events

    | Event               | Parameters                                             |
    | ------------------- | ------------------------------------------------------ |
    | `AgentRegistered`   | `owner` (indexed), `agentId` (indexed), `capabilities` |
    | `AgentUpdated`      | `agentId` (indexed), `capabilities`, `revenueShareBps` |
    | `AgentDeactivated`  | `agentId` (indexed)                                    |
    | `ReputationUpdated` | `agentId` (indexed), `newScore`                        |
  </Accordion>

  <Accordion title="LiquidationMonitor">
    Multi-protocol lending health scanner with dynamic protocol registry.
    Supports Aave V3 with extensible dispatch for additional lending and
    perp protocols.

    ### Storage Layout

    | Slot               | Type                          | Description                            |
    | ------------------ | ----------------------------- | -------------------------------------- |
    | `owner`            | `address`                     | Contract owner                         |
    | `tracked_accounts` | `address[]`                   | Accounts being monitored               |
    | `risk_threshold`   | `uint256`                     | Health factor threshold for alerts     |
    | `lending_count`    | `uint256`                     | Number of registered lending protocols |
    | `lending_pools`    | `mapping(uint256 => address)` | Index to pool address                  |
    | `lending_types`    | `mapping(uint256 => uint256)` | Index to protocol type                 |
    | `lending_active`   | `mapping(uint256 => bool)`    | Index to active flag                   |
    | `perp_count`       | `uint256`                     | Number of registered perp protocols    |
    | `perp_readers`     | `mapping(uint256 => address)` | Index to reader address                |
    | `perp_types`       | `mapping(uint256 => uint256)` | Index to protocol type                 |
    | `perp_active`      | `mapping(uint256 => bool)`    | Index to active flag                   |

    ### Public Methods

    **`initialize(risk_threshold: U256) -> Result<()>`**
    Initialize the contract. Sets caller as owner and configures the risk
    threshold. Can only be called once.

    **`add_lending_protocol(pool_address: Address, protocol_type: u64) -> Result<U256>`**
    Register a lending protocol. Owner only. Returns the registry index.

    **`remove_lending_protocol(index: U256) -> Result<()>`**
    Soft-delete a lending protocol by index. Owner only.

    **`lending_protocol_count() -> U256`**
    Returns the total number of registered lending protocols (including
    inactive).

    **`get_lending_protocol(index: U256) -> (Address, U256, bool)`**
    Returns `(pool_address, protocol_type, is_active)`.

    **`add_perp_protocol(reader_address: Address, protocol_type: u64) -> Result<U256>`**
    Register a perpetual protocol. Owner only.

    **`remove_perp_protocol(index: U256) -> Result<()>`**
    Soft-delete a perp protocol by index. Owner only.

    **`perp_protocol_count() -> U256`**
    Returns the total registered perp protocol count.

    **`get_health_factor(account: Address) -> Result<U256>`**
    Query the health factor for an account across all active lending
    protocols. Dispatches based on protocol type.

    ### Events

    | Event                    | Parameters                                         |
    | ------------------------ | -------------------------------------------------- |
    | `AccountAtRisk`          | `account` (indexed), `healthFactor`, `timestamp`   |
    | `AccountAdded`           | `account` (indexed)                                |
    | `AccountRemoved`         | `account` (indexed)                                |
    | `ThresholdUpdated`       | `oldThreshold`, `newThreshold`                     |
    | `LendingProtocolAdded`   | `index` (indexed), `poolAddress`, `protocolType`   |
    | `LendingProtocolRemoved` | `index` (indexed), `poolAddress`                   |
    | `PerpProtocolAdded`      | `index` (indexed), `readerAddress`, `protocolType` |
    | `PerpProtocolRemoved`    | `index` (indexed), `readerAddress`                 |
  </Accordion>

  <Accordion title="RouteOptimizer">
    Multi-DEX route comparison engine with dynamic DEX registry. Evaluates
    swap routes across registered DEXes to find the best output.

    ### Storage Layout

    | Slot             | Type                          | Description                              |
    | ---------------- | ----------------------------- | ---------------------------------------- |
    | `owner`          | `address`                     | Contract owner                           |
    | `dex_count`      | `uint256`                     | Number of registered DEXes               |
    | `dex_addresses`  | `mapping(uint256 => address)` | Index to DEX quoter address              |
    | `dex_types`      | `mapping(uint256 => uint256)` | Index to DEX type constant               |
    | `dex_active`     | `mapping(uint256 => bool)`    | Index to active flag                     |
    | `routing_tokens` | `address[]`                   | Intermediate routing tokens (WETH, USDC) |

    ### DEX Type Constants

    | Constant          | Value | Description                               |
    | ----------------- | ----- | ----------------------------------------- |
    | `DEX_TYPE_UNIV3`  | `0`   | Uniswap V3 concentrated liquidity         |
    | `DEX_TYPE_AMM_V2` | `1`   | Constant product AMM (Camelot, SushiSwap) |

    ### Public Methods

    **`initialize() -> Result<()>`**
    Initialize the contract. Sets caller as owner and seeds WETH + USDC as
    default routing tokens.

    **`add_dex(dex_address: Address, dex_type: u64) -> Result<U256>`**
    Register a DEX quoter. Owner only. Maximum 20 DEXes.

    **`remove_dex(index: U256) -> Result<()>`**
    Soft-delete a DEX by index. Owner only.

    **`dex_count() -> U256`**
    Returns the total registered DEX count.

    **`get_dex(index: U256) -> (Address, U256, bool)`**
    Returns `(dex_address, dex_type, is_active)`.

    **`add_routing_token(token: Address) -> Result<()>`**
    Add an intermediate routing token. Owner only. Maximum 50 tokens. Rejects
    duplicates.

    **`remove_routing_token(token: Address) -> Result<()>`**
    Remove a routing token (swap-and-pop). Owner only.

    **`routing_token_count() -> U256`**
    Returns the number of routing tokens.

    **`find_best_route(token_in: Address, token_out: Address, amount_in: U256) -> Result<(U256, Vec<Address>, Vec<u32>)>`**
    Query all active DEXes and return the best route as
    `(best_amount_out, token_path, fee_tiers)`.

    ### Events

    | Event        | Parameters                                 |
    | ------------ | ------------------------------------------ |
    | `DexAdded`   | `index` (indexed), `dexAddress`, `dexType` |
    | `DexRemoved` | `index` (indexed), `dexAddress`            |
  </Accordion>

  <Accordion title="TimeboostVault">
    Manages ETH/USDC funds for TimeBoost express lane bidding and handles
    payments for express lane resale.

    ### Storage Layout

    | Slot                         | Type                       | Description                                     |
    | ---------------------------- | -------------------------- | ----------------------------------------------- |
    | `owner`                      | `address`                  | Vault owner (can withdraw and configure)        |
    | `usdc`                       | `address`                  | USDC token address                              |
    | `bid_agent`                  | `address`                  | Authorized bidding agent address                |
    | `resale_price_usdc`          | `uint256`                  | Price per express lane resale slot (6 decimals) |
    | `is_express_lane_controller` | `bool`                     | Whether vault controls current round            |
    | `current_round`              | `uint256`                  | Current express lane round number               |
    | `total_resale_earnings`      | `uint256`                  | Cumulative USDC from resales                    |
    | `total_bid_cost`             | `uint256`                  | Cumulative ETH spent on bids                    |
    | `authorized_buyers`          | `mapping(address => bool)` | Current round buyer authorization               |

    ### Public Methods

    **`initialize(usdc: Address, bid_agent: Address, resale_price_usdc: U256) -> Result<()>`**
    Initialize the vault with USDC address, bidding agent, and resale price.

    **`deposit_eth() -> Result<()>`** *(payable)*
    Deposit ETH for bidding capital.

    **`deposit_usdc(amount: U256) -> Result<()>`**
    Deposit USDC via `transferFrom`.

    **`record_round_win(round: U256, bid_cost_wei: U256) -> Result<()>`**
    Record a round win. Agent or owner only. Sets controller status and
    accumulates bid costs.

    **`end_round() -> Result<()>`**
    Reset controller status at end of round. Agent or owner only.

    **`purchase_express_lane_access() -> Result<()>`**
    Buy express lane access for the current round. Transfers
    `resale_price_usdc` USDC from caller. Reverts if vault is not the
    current controller.

    **`is_authorized_buyer(buyer: Address) -> bool`**
    Check if an address has purchased access for the current round.

    **`get_stats() -> Result<(U256, U256, U256, U256, bool)>`**
    Returns `(eth_balance, usdc_balance, total_resale_earnings, total_bid_cost, is_controller)`.

    **`set_resale_price(new_price: U256) -> Result<()>`**
    Update the resale price. Owner only.

    **`withdraw_eth(amount: U256) -> Result<()>`**
    Withdraw ETH from the vault. Owner only.

    **`withdraw_usdc(amount: U256) -> Result<()>`**
    Withdraw USDC from the vault. Owner only.

    ### Events

    | Event                | Parameters                              |
    | -------------------- | --------------------------------------- |
    | `Deposited`          | `from` (indexed), `amount`, `isEth`     |
    | `Withdrawn`          | `to` (indexed), `amount`, `isEth`       |
    | `RoundWon`           | `round` (indexed), `bidCost`            |
    | `ResalePurchased`    | `buyer` (indexed), `pricePaid`, `round` |
    | `ResalePriceUpdated` | `oldPrice`, `newPrice`                  |
  </Accordion>
</AccordionGroup>
