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

# State Machine

> The fixed dvp/v1 machine: code-defined states with a single owner per state.

Every settlement runs the **dvp/v1** machine. The machine is fixed in code - templates select it (and pin it on the settlement as `machine_version` at creation) but cannot change its states or transitions. The on-chain KeystoneSettlement contract implements the chain-owned part of the machine natively.

## One owner per state

Every state has exactly one owner - the only writer that can advance out of it:

| Owner      | States                                                               | Advanced by                                      |
| ---------- | -------------------------------------------------------------------- | ------------------------------------------------ |
| **Engine** | `INSTRUCTED`, `COMPLIANCE_CHECKING`, `COMPLIANCE_CLEARED`, `SETTLED` | KeyStone's settlement engine                     |
| **Chain**  | `AWAITING_DEPOSITS`                                                  | Observed KeystoneSettlement contract events only |
| **Admin**  | `MANUAL_REVIEW`                                                      | KeyStone operators                               |

KeyStone never sends state-transition transactions. Its only chain writes are `registerSettlement`, the compliance `attest`, and the operator `abort`. Everything in the chain-owned region - deposits, execution, timeout, refunds - happens autonomously on the contract, and the observed events drive the settlement record.

```mermaid theme={null}
%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#1a3a35', 'primaryTextColor': '#e0f2ef', 'primaryBorderColor': '#2DD4A8', 'lineColor': '#2DD4A8', 'labelColor': '#e0f2ef', 'stateBkg': '#1a3a35', 'stateBorder': '#2DD4A8', 'transitionColor': '#2DD4A8', 'compositeBackground': '#0f2420', 'compositeBorder': '#1AAF8B', 'compositeTitleBackground': '#162e2a', 'innerEndBackground': '#2DD4A8', 'specialStateColor': '#2DD4A8'}}}%%
stateDiagram-v2
    [*] --> INSTRUCTED

    state "Engine-owned" as eng {
        INSTRUCTED --> COMPLIANCE_CHECKING : engine walk
        COMPLIANCE_CHECKING --> COMPLIANCE_CLEARED : all checks pass
        COMPLIANCE_CHECKING --> REJECTED : compliance failure
        COMPLIANCE_CLEARED --> AWAITING_DEPOSITS : engine walk
    }

    state "Chain-owned" as chain {
        AWAITING_DEPOSITS --> SETTLED : SettlementExecuted event
        AWAITING_DEPOSITS --> ROLLED_BACK : SettlementAborted event
        AWAITING_DEPOSITS --> TIMED_OUT : SettlementTimedOut event
    }

    SETTLED --> FINALIZED : engine close-out

    COMPLIANCE_CLEARED --> MANUAL_REVIEW : operational failure
    AWAITING_DEPOSITS --> MANUAL_REVIEW : operator escalation
    MANUAL_REVIEW --> ROLLED_BACK : operator resolution

    FINALIZED --> [*]
    REJECTED --> [*]
    ROLLED_BACK --> [*]
    TIMED_OUT --> [*]
```

## The walk

1. **INSTRUCTED** - Settlement created from matched instructions, machine version pinned. When the contract is configured, the engine registers the settlement on-chain: recipients bound per leg, deposit keys, party hashes, timeout.
2. **COMPLIANCE\_CHECKING** - The engine screens all parties via the template's providers (LSEG entity screening, CipherOwl wallet screening). A failure routes to `REJECTED` - the terminal taxonomy for pre-deposit compliance failures.
3. **COMPLIANCE\_CLEARED** - Checks passed. The engine continues the walk.
4. **AWAITING\_DEPOSITS** - The handoff point. The engine yields; only contract events advance past here.
5. **SETTLED** - The observed `SettlementExecuted` event landed: the contract paid out every leg atomically. The engine resumes for close-out bookkeeping.
6. **FINALIZED** - Done.

## Terminal states

| State         | Meaning                                                                             |
| ------------- | ----------------------------------------------------------------------------------- |
| `FINALIZED`   | Executed on-chain and closed out                                                    |
| `REJECTED`    | Pre-deposit compliance failure - no funds ever moved                                |
| `ROLLED_BACK` | Aborted after registration (operator action); deposits reclaimable via pull refunds |
| `TIMED_OUT`   | Deadline passed; the operator or a depositor claimed the timeout on-chain           |

`MANUAL_REVIEW` is not terminal: it parks a settlement for an operator after an operational dead end (a failed post-clearance action, or a stale settlement past its deadline in an engine-owned state).

## Autonomous execution

On the last `depositLeg`, the contract checks the compliance gate (`ComplianceRegistry.areAllPartiesCleared`) and executes inline in the same transaction - every leg pays out to its recipient bound at registration, all-or-nothing. If attestations are still pending at the last deposit, the settlement stays registered and once the gate clears `execute()` can be called by the operator or any depositor: the caller only triggers the pre-committed plan, no one can steer it.

## Depositor-driven recovery

Deposits and execution are live strictly before `timeoutAt`; recovery is live at and after it - the two windows never overlap.

```mermaid theme={null}
%%{init: {'theme': 'base', 'themeVariables': {'actorBkg': '#1a3a35', 'actorBorder': '#2DD4A8', 'actorTextColor': '#e0f2ef', 'actorLineColor': '#2DD4A8', 'signalColor': '#2DD4A8', 'signalTextColor': '#e0f2ef', 'noteBkgColor': '#162e2a', 'noteTextColor': '#e0f2ef', 'noteBorderColor': '#1AAF8B', 'activationBkgColor': '#1a3a35', 'activationBorderColor': '#2DD4A8', 'labelBoxBkgColor': '#1a3a35', 'labelBoxBorderColor': '#2DD4A8', 'labelTextColor': '#e0f2ef', 'loopTextColor': '#2DD4A8'}}}%%
sequenceDiagram
    participant Depositor
    participant K as KeystoneSettlement

    Depositor->>K: claimTimeout(settlementId)
    K->>K: require(block.timestamp >= timeoutAt)
    K->>K: status = TimedOut
    Note over K: deposits stay locked until claimed
    Depositor->>K: claimRefund(settlementId, legIndex)
    K->>K: pay the recorded depositor (per leg)
```

`claimTimeout` and `claimRefund` can be called by any depositor (or the operator) and cannot be paused - funds are never locked indefinitely, even if KeyStone is down. Refunds are per-leg pull payments: one blocked depositor can never strand another leg's funds.

## Events

The contract emits a fixed event set - `SettlementRegistered`, `LegDeposited`, `SettlementExecuted`, `SettlementAborted`, `SettlementTimedOut`, `RefundClaimed`, `LegPaidOut`, `FeesCollected`. These form the complete on-chain audit trail; KeyStone's database mirrors them through a deduplicated indexer/webhook intake, mapping events to states **by name** through the settlement's pinned machine.

## Error handling

* A failed engine action routes to the machine's failure target for that state (`REJECTED` from compliance, `MANUAL_REVIEW` after clearance). If no legal failure transition exists, the settlement parks in place with a durable audit record instead of corrupting the walk.
* A settlement past `timeout_at` in an engine-owned state escalates to `MANUAL_REVIEW`. `TIMED_OUT` itself only ever comes from the contract.
* A chain event that contradicts the database state is surfaced to operators as a divergence - never silently absorbed, never retried forever.

See [KeystoneSettlement](/smart-contracts/keystone-settlement) for the full contract documentation.
