> For the complete documentation index, see [llms.txt](https://docs.trilobyte.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.trilobyte.finance/technical-documentation/globals-contract.md).

# Globals Contract

Protocol-wide settings, role management, fee configuration, pool-manager collateral, manager credit/delinquency tracking, and the Factory + vault registry.

**Source:** `contracts/globals/`

## Source Modules

| File           | Purpose                                                                                               |
| -------------- | ----------------------------------------------------------------------------------------------------- |
| `contract.rs`  | All public entry points — settings, roles, collateral, delinquency/credit, Factory/vault registration |
| `storage.rs`   | Data types (`GlobalSettings`, `Manager`, `ManagerCollateral`), storage keys, getters/setters          |
| `constants.rs` | Default values (`PROTOCOL_FEE = 50_000` = 0.5% in 7-decimal)                                          |
| `errors.rs`    | `#[contracterror]` enum                                                                               |
| `events.rs`    | `#[contractevent]` structs                                                                            |
| `test.rs`      | 29 tests (core settings + collateral + delinquency/credit)                                            |

## Roles & Authorisation

Roles use OpenZeppelin Access Control. The **admin** is the `governor` set at construction (later transferred to the Timelock). `sec_adm` and `ops_adm` are granted at construction.

| Role           | Key         | Who                 | Can Do                                                                                                                                                        |
| -------------- | ----------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Admin          | (OZ admin)  | Governor / Timelock | `whitelist_asset`, `remove_asset`, `set_treasury_address`, `set_factory`, `register_vault`\*, `upgrade`, two-step admin transfer                              |
| Security Admin | `"sec_adm"` | Security team       | `pause` / `unpause`                                                                                                                                           |
| Ops Admin      | `"ops_adm"` | Operations team     | `approve_pool_manager`, `remove_pool_manager`, `set_protocol_fee`, `update_settings`, `set_manager_inactive`, `set_manager_credit_limit`, `clear_delinquency` |

\* `register_vault` is admin-defined but additionally requires the call to come from the registered **Factory** (it re-checks `factory.require_auth()`).

{% hint style="info" %}
`whitelist_asset` / `remove_asset` / `set_treasury_address` / `set_factory` use the `#[only_admin]` macro. The pool-manager, fee, settings, and delinquency functions use `#[only_role(caller, "ops_adm")]`. `pause` / `unpause` use `#[only_role(caller, "sec_adm")]`.
{% endhint %}

## GlobalSettings

The settings struct has **21 fields** (no addresses or paused state — those live in OZ storage):

```rust
GlobalSettings {
    protocol_fee: i128,             // Fee (7-decimal, 50_000 = 0.5%)
    min_interest_rate: u32,         // Min annual rate, basis points
    max_interest_rate: u32,         // Max annual rate, basis points
    min_loan_term: u32,             // Min loan term, months
    max_loan_term: u32,             // Max loan term, months
    default_grace_period: u32,      // Default grace period (days)
    default_risk_tolerance: u32,    // Default-after % missed payments
    default_collateral_ratio: u32,  // Manager collateral as % of principal
    min_collateral_value: i128,     // Min collateral value (7-decimal)
    one_day: u64,                   // Seconds in a day
    one_year: u64,                  // Seconds in a 360-day year
    days_in_year_30_360: u32,       // 360
    days_in_month_30_360: u32,      // 30
    monthly_emi_interval: u64,      // EMI interval (seconds)
    default_penalty_rate_bps: u32,  // Penalty rate (1800 = 18% p.a.)
    min_emi_tolerance: u32,         // Min % of EMI to avoid penalty
    token_decimals: u32,            // 7
    min_loan_amount: i128,          // Minimum loan amount (7-decimal)
    max_loan_amount: i128,          // Maximum loan amount (7-decimal)
    default_timelock_delay: u64,    // Default timelock delay (ledgers)
    default_timelock_duration: u64, // Default timelock duration (ledgers)
}
```

{% hint style="warning" %}
The min/max loan bounds are named `min_loan_amount` / `max_loan_amount` (not `min_principal` / `max_principal`). Timelock delay/duration are measured in **ledgers** (\~5 s/ledger), not seconds.
{% endhint %}

## Functions

### Admin-only (`#[only_admin]`)

| Function                             | Description                                                             |
| ------------------------------------ | ----------------------------------------------------------------------- |
| `set_treasury_address(new_treasury)` | Update the treasury address (the new treasury must also `require_auth`) |
| `whitelist_asset(asset)`             | Whitelist a lending/collateral token                                    |
| `remove_asset(asset)`                | Remove a token from the whitelist                                       |
| `set_factory(factory)`               | Register the Factory address (required before vault creation works)     |
| `register_vault(vault)`              | Mark a vault as trusted (Factory-gated)                                 |
| `upgrade(new_wasm_hash, operator)`   | Upgrade the contract (auth via stored admin)                            |

### Two-step admin transfer (OZ Access Control)

| Function                                                                                                                                                                                            | Description                                                            |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `transfer_admin_role(new_admin, live_until_ledger)`                                                                                                                                                 | Initiate admin transfer; pending until accepted or `live_until_ledger` |
| `accept_admin_transfer()`                                                                                                                                                                           | New admin accepts the pending transfer                                 |
| `renounce_admin()`                                                                                                                                                                                  | Current admin renounces                                                |
| Plus OZ role functions: `grant_role`, `revoke_role`, `renounce_role`, `has_role`, `get_role_admin`, `set_role_admin`, `get_role_member`, `get_role_member_count`, `get_admin`, `get_existing_roles` |                                                                        |

### Security Admin (`#[only_role(caller, "sec_adm")]`)

| Function          | Description                              |
| ----------------- | ---------------------------------------- |
| `pause(caller)`   | Pause all `#[when_not_paused]` functions |
| `unpause(caller)` | Resume normal operation                  |

### Operations Admin (`#[only_role(caller, "ops_adm")]`)

| Function                                                | Description                                                   |
| ------------------------------------------------------- | ------------------------------------------------------------- |
| `approve_pool_manager(manager, caller, max_credit)`     | Approve a manager with a credit limit (returns the `Manager`) |
| `remove_pool_manager(manager_address, caller)`          | Remove a manager                                              |
| `set_protocol_fee(fee, caller)`                         | Update the protocol fee                                       |
| `update_settings(settings, caller)`                     | Replace the full `GlobalSettings` struct                      |
| `set_manager_inactive(manager_address, caller)`         | Deactivate a manager                                          |
| `set_manager_credit_limit(manager, max_credit, caller)` | Update a manager's credit limit                               |
| `clear_delinquency(manager, caller)`                    | Clear a manager's delinquency record after review             |

### Collateral (manager / cross-contract, `#[when_not_paused]`)

| Function                                               | Auth             | Description                                                                            |
| ------------------------------------------------------ | ---------------- | -------------------------------------------------------------------------------------- |
| `deposit_collateral(manager, token, amount)`           | Manager          | Stake collateral (manager must be active, token whitelisted, single token per manager) |
| `withdraw_collateral(manager, amount)`                 | Manager          | Withdraw unlocked collateral (`staked − locked`)                                       |
| `lock_collateral(manager, amount)`                     | Factory          | Lock collateral on vault creation                                                      |
| `release_collateral(caller, manager, amount)`          | Registered Vault | Release on full repayment / cancellation                                               |
| `slash_collateral(caller, manager, amount, recipient)` | Registered Vault | Slash on default, transfer to `recipient`                                              |
| `get_manager_collateral(manager)`                      | Any              | View `{ token, staked, locked }`                                                       |
| `get_available_collateral(manager)`                    | Any              | View `staked − locked`                                                                 |

### Manager credit & delinquency tracking (cross-contract)

| Function                                         | Called By | Description                                       |
| ------------------------------------------------ | --------- | ------------------------------------------------- |
| `mark_delinquent(caller, manager)`               | Vault     | Increment delinquency count on default            |
| `clear_delinquency(manager, caller)`             | Ops Admin | Reset delinquency count                           |
| `increment_outstanding(manager, amount)`         | Factory   | Track new vault principal against credit          |
| `decrement_outstanding(caller, manager, amount)` | Vault     | Release principal on repayment / default / expiry |
| `is_delinquent(manager)`                         | Any       | Whether the manager has any uncleared default     |
| `get_manager(manager)`                           | Any       | Full `Manager` record (`Option`)                  |

### Public Queries

| Function                 | Returns                |
| ------------------------ | ---------------------- |
| `get_global_settings()`  | `GlobalSettings`       |
| `get_treasury_address()` | Treasury address       |
| `get_supported_assets()` | Whitelisted token list |
| `list_pool_managers()`   | `Vec<Manager>`         |
| `paused()`               | `bool`                 |

## Events

| Event                       | Key Fields                                   | When                                     |
| --------------------------- | -------------------------------------------- | ---------------------------------------- |
| `RoleUpdated`               | `role`, `new_address`                        | Treasury (or other role address) updated |
| `ProtocolPaused`            | `paused`                                     | Paused / unpaused                        |
| `ManagerApproved`           | `manager`                                    | Manager approved                         |
| `ManagerRemoved`            | `manager`                                    | Manager removed                          |
| `AssetWhitelisted`          | `asset`                                      | Asset added                              |
| `AssetRemoved`              | `asset`                                      | Asset removed                            |
| `FeeUpdated`                | `new_fee`                                    | Protocol fee updated                     |
| `CollateralDeposited`       | `manager`, `token`, `amount`, `total_staked` | Manager stakes collateral                |
| `CollateralWithdrawn`       | `manager`, `amount`, `total_staked`          | Manager withdraws collateral             |
| `CollateralLocked`          | `manager`, `amount`, `total_locked`          | Collateral locked for a vault            |
| `CollateralReleased`        | `manager`, `amount`, `total_locked`          | Collateral released                      |
| `CollateralSlashed`         | `manager`, `amount`, `remaining_staked`      | Collateral slashed on default            |
| `ManagerMarkedDelinquent`   | `manager`, `delinquency_count`               | Vault defaulted                          |
| `ManagerDelinquencyCleared` | `manager`                                    | Delinquency cleared                      |
| `ManagerCreditLimitSet`     | `manager`, `max_credit`                      | Credit limit set/updated                 |
| `ManagerOutstandingUpdated` | `manager`, `outstanding_principal`           | Outstanding principal changed            |

## Storage Design

`GlobalSettings`, treasury, the Factory address, supported assets, pool managers, and per-manager collateral are stored in **instance storage** with TTL extension (\~30-day threshold, \~31-day bump). Registered vaults are stored in **persistent storage** keyed by vault address, with a TTL clamped to the network maximum (`max_ttl()`).
