# Optimistic Layers & STM Drafts

> Rebaseable optimistic layers, atomic zero-flicker settle(), surgical revert(), and read-set verified STM drafts in TypeScript and Rust.

Optimistic UI is easy when only one request is in flight and nothing else changes. It breaks as soon as two optimistic actions overlap or a live server push arrives before the first request finishes.

`@zwire/core/tx` and `zwire-tx` solve this with **rebaseable optimistic layers** and **read-set verified STM drafts**, both composing with core atoms through zero-cost lazy extension slots.

## Try it live

Click **Reserve -150**, trigger a concurrent **Server Push +500**, and observe the active optimistic layer automatically rebase on top of the new authoritative value—then **Settle** atomically with zero flicker or **Revert** cleanly:

## Rebaseable optimistic layers

An `OptimisticLayer` records intent functions (`layer.update(atom, fn)`) rather than static overwritten values. When an authoritative write mutates the base atom while one or more optimistic layers are active, `zwire` replays every active layer's intent functions in creation order on top of the new committed value:

```ts
import { atom, batch, computed } from '@zwire/core';
import { createOptimisticLayer } from '@zwire/core/tx';

const balance = atom(1000);
const display = computed(() => `$${balance.get()}`);

const hold = createOptimisticLayer();
hold.update(balance, (b) => b - 150);
// UI sees $850

// Concurrent authoritative server update arrives mid-flight:
batch(() => balance.set(1500));
// Active optimistic layer auto-rebases: UI immediately sees $1350!

// Zero-flicker atomic settle: strips the layer and commits server state in one batch
hold.settle(() => balance.set(1350));
console.log(display.get()); // "$1350"
```

In Rust (`zwire-tx` / `zwire::tx`), the semantics are identical:

```rust
use zwire::prelude::*;

let scope = Scope::new();
let balance = scope.atom(1_000_i64);

let mut hold = OptimisticLayer::new(&scope);
hold.update(balance, |b| b - 150);
assert_eq!(scope.get(balance), 850);

// Concurrent authoritative update rebases the active layer
scope.set(balance, 1_500);
assert_eq!(scope.get(balance), 1_350);

// Atomic zero-flicker settle (rolls back if closure returns Err or panics)
hold.settle_with(|| scope.set(balance, 1_350));
assert_eq!(scope.get(balance), 1_350);
```

### Atomic `settle()` & surgical `revert()`

- **`layer.settle(fn)` / `try_settle(fn)`**: Snapshots committed values/versions of touched atoms, intercepts writes inside `fn`, removes the optimistic layer inside a single `batch()`, and restores every base atom atomically if `fn` throws or returns `Err`.
- **`layer.revert()`**: Removes only that single layer while keeping any other overlapping layers intact and rebased.
- **`runOptimistic(fn)`**: Scoped helper that creates a layer, runs an async mutation, settles on success, and reverts on rejection.
- **UI adapter hooks**: `@zwire/{react,vue,solid,svelte}/tx` provide `useOptimisticLayer`, `useOptimisticAction` (with `pending`, `error`, `concurrency: 'latest' | 'queue'`, and `abortOnUnmount`), and `useDraft`.

## Read-set verified STM drafts

For multi-atom transactional edits (such as editing a form or transferring funds across accounts) where you want copy-on-write isolation and conflict detection on commit, use `createDraft` / `Draft`:

```ts
import { atom, createScope } from '@zwire/core';
import { createDraft, StmConflictError } from '@zwire/core/tx';

const scope = createScope();
const checking = atom(500, { scope });
const savings = atom(1000, { scope });

const draft = createDraft(scope);
const amount = 200;
const cur = draft.get(checking); // recorded in STM read-set
draft.set(checking, cur - amount);
draft.set(savings, draft.get(savings) + amount);

// If another writer modified `checking` or `savings` before commit,
// `draft.commit()` throws `StmConflictError` instead of silently clobbering it.
draft.commit();
```
