# Factory Contract

Deploys and registers vault contracts. Validates all parameters against the Globals contract before deployment.

**Source:** `contracts/factory/`

## Source Modules

| File          | Purpose                                                                             |
| ------------- | ----------------------------------------------------------------------------------- |
| `contract.rs` | Constructor, `set_vault_wasm_hash`, `create_vault`, queries, inline `GlobalsClient` |
| `storage.rs`  | Data keys (globals, wasm\_hash, 3-index vault registry), getters/setters            |
| `errors.rs`   | `#[contracterror]` enum (11 variants)                                               |
| `events.rs`   | `VaultDeployed`, `WasmHashUpdated` events                                           |
| `test.rs`     | 3 tests                                                                             |

## How It Works

1. Governor deploys the Factory with a Globals address and an initial vault WASM hash
2. When a Pool Manager calls `create_vault(params, salt)`, the factory:
   * Validates the manager is approved and active (via `GlobalsClient`)
   * Checks the manager is **not delinquent** (`is_delinquent` — blocked if any vault defaulted)
   * Checks the manager's **credit limit** (`outstanding + principal ≤ max_credit`)
   * Validates the lending token is whitelisted
   * Validates interest rate, loan term, principal, and split ratio against global settings
   * **Locks manager collateral** via `GlobalsClient::lock_collateral`
   * **Increments outstanding principal** via `GlobalsClient::increment_outstanding`
   * Deploys a new vault contract using `e.deployer().with_current_contract(salt).deploy_v2(wasm_hash, (globals, params))`
   * Registers the vault in three indexes: all vaults, per-manager, per-borrower
3. The governor can update the vault WASM hash via `set_vault_wasm_hash` (for future vault template upgrades)

## Functions

### Constructor

```
__constructor(governor, globals, wasm_hash)
```

Initialise factory with admin, globals reference, and vault template hash.

### Admin Actions

| Function                                | Description                    |
| --------------------------------------- | ------------------------------ |
| `set_vault_wasm_hash(caller, new_hash)` | Update the vault WASM template |

### Vault Creation

| Function                                  | Description                             |
| ----------------------------------------- | --------------------------------------- |
| `create_vault(params: VaultParams, salt)` | Deploy a new vault with full validation |

**VaultParams:**

```rust
VaultParams {
    manager: Address,
    borrower: Address,
    lent_token: Address,
    principal: i128,
    interest_rate: u32,
    loan_term: u32,
    split_ratio: u32,
    permissioned: bool,
    grace_period: u64,
    funding_deadline: u64,
    approval_deadline: u64,
}
```

### Queries

| Function                        | Returns                              |
| ------------------------------- | ------------------------------------ |
| `get_globals()`                 | Globals contract address             |
| `get_vault_wasm_hash()`         | Current vault template hash          |
| `get_vault_count()`             | Total deployed vaults                |
| `get_all_vaults()`              | List of all vault addresses          |
| `get_manager_vaults(manager)`   | Vaults created by a specific manager |
| `get_borrower_vaults(borrower)` | Vaults for a specific borrower       |

## Validation Checks

The Factory performs extensive validation before deploying a vault:

| Check             | Error Code                   | Description                                   |
| ----------------- | ---------------------------- | --------------------------------------------- |
| Manager approved  | `ManagerNotApproved (3)`     | Manager must be active in Globals             |
| Not delinquent    | `ManagerDelinquent (10)`     | Manager must have no uncleared defaults       |
| Credit limit      | `CreditLimitExceeded (11)`   | `outstanding + principal ≤ max_credit`        |
| Asset whitelisted | `AssetNotSupported (4)`      | Token must be whitelisted in Globals          |
| Interest rate     | `InvalidRate (5)`            | Must exceed global minimum                    |
| Loan term         | `InvalidTerm (6)`            | Must be within global min/max                 |
| Principal         | `InvalidPrincipal (7)`       | Must be within global min/max                 |
| Split ratio       | `InvalidSplitRatio (8)`      | Must be 1–99                                  |
| Collateral        | `InsufficientCollateral (9)` | Manager must have enough available collateral |

## Events

| Event             | Key Fields                                  | When             |
| ----------------- | ------------------------------------------- | ---------------- |
| `VaultDeployed`   | vault address, manager, borrower, principal | Vault created    |
| `WasmHashUpdated` | new hash                                    | Template updated |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.trilobyte.finance/technical-documentation/factory-contract.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
