orderbook_optimistic/
orderbook_optimistic.rs1use core::cell::Cell;
6use std::rc::Rc;
7
8use zwire::prelude::*;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11struct Bid {
12 id: u64,
13 price_cents: i64,
14 qty: u32,
15 active: bool,
16}
17
18fn main() {
19 let scope = Scope::new();
20
21 let bids = ReactiveCollection::with_filter(
23 &scope,
24 |b: &Bid| b.id,
25 |a, b| b.price_cents.cmp(&a.price_cents),
26 |b| b.active && b.qty > 0,
27 );
28
29 bids.upsert_many((1..=10_000u64).map(|id| Bid {
30 id,
31 price_cents: i64::try_from(id).unwrap() * 10,
32 qty: 5,
33 active: true,
34 }));
35
36 let top5 = bids.top_k_signal(5);
37 let best_bid =
38 scope.computed(move |cx| cx.with(top5, |rows| rows.first().map_or(0, |b| b.price_cents)));
39
40 let renders = Rc::new(Cell::new(0usize));
41 let renders_c = Rc::clone(&renders);
42 let _sub = scope.subscribe(best_bid, move |price| {
43 renders_c.set(renders_c.get() + 1);
44 println!(
45 "[book] best bid updated -> ${}.{:02}",
46 price / 100,
47 price.abs() % 100
48 );
49 });
50
51 let init_price = scope.get(best_bid);
52 println!(
53 "Initial best bid across {} active bids: ${}.{:02}",
54 bids.indexed_len(),
55 init_price / 100,
56 init_price.abs() % 100
57 );
58
59 for id in 1..=100u64 {
61 bids.mutate(&id, |b| b.price_cents += 1);
62 }
63 assert_eq!(renders.get(), 0);
64 println!(
65 "After 100 off-top updates: {} UI renders (O(1) pruned)",
66 renders.get()
67 );
68
69 bids.upsert(Bid {
71 id: 99_999,
72 price_cents: 105_000,
73 qty: 12,
74 active: true,
75 });
76 assert_eq!(renders.get(), 1);
77
78 let available_usd = scope.atom(10_000i64);
80
81 let mut order_a = OptimisticLayer::new(&scope);
82 order_a.update(available_usd, |bal| bal - 1_200); let mut order_b = OptimisticLayer::new(&scope);
85 order_b.update(available_usd, |bal| bal - 800); println!(
87 "After 2 optimistic orders -> displayed balance: ${}",
88 scope.get(available_usd)
89 );
90
91 scope.set(available_usd, 15_000);
93 assert_eq!(scope.get(available_usd), 13_000);
94 println!(
95 "After concurrent +$5,000 deposit -> auto-rebased balance: ${}",
96 scope.get(available_usd)
97 );
98
99 order_a.revert();
101 assert_eq!(scope.get(available_usd), 14_200);
102 println!(
103 "After Order A rejected -> balance: ${}",
104 scope.get(available_usd)
105 );
106
107 order_b.settle_with(|| scope.set(available_usd, 14_200));
109 assert_eq!(scope.get(available_usd), 14_200);
110 println!(
111 "After Order B settled -> final committed balance: ${}",
112 scope.get(available_usd)
113 );
114}