brk_computer 0.3.0-beta.9

A Bitcoin dataset computer built on top of brk_indexer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use brk_traversable::Traversable;
use brk_types::{Bitcoin, Dollars, Height, StoredF32, Version};
use derive_more::{Deref, DerefMut};
use schemars::JsonSchema;
use vecdb::{
    DeltaChange, DeltaRate, LazyDeltaVec, LazyVecFrom1, ReadOnlyClone, ReadableCloneableVec,
    VecValue,
};

use crate::{
    indexes,
    internal::{
        AmountType, BpsType, DerivedResolutions, FiatType, LazyPerBlock, NumericValue, Percent,
        Resolutions, WindowStartVec, Windows,
    },
};

/// Generic single-slot lazy delta: a `LazyDeltaVec` + resolution views.
///
/// Used as building block for both change and rate deltas.
/// - Change: `LazyDeltaFromHeight<S, C, DeltaChange>`
/// - Rate BPS: `LazyDeltaFromHeight<S, B, DeltaRate>`
#[derive(Clone, Traversable)]
#[traversable(merge)]
pub struct LazyDeltaFromHeight<S, T, Op: 'static>
where
    S: VecValue,
    T: NumericValue + JsonSchema,
{
    pub height: LazyDeltaVec<Height, S, T, Op>,
    #[traversable(flatten)]
    pub resolutions: Box<Resolutions<T>>,
}

/// Single-slot lazy delta percent: BPS delta + lazy ratio + lazy percent views.
///
/// Mirrors `PercentPerBlock<B>` but with lazy delta for the BPS source.
#[derive(Clone, Deref, DerefMut, Traversable)]
#[traversable(transparent)]
pub struct LazyDeltaPercentFromHeight<S, B>(
    pub Percent<LazyDeltaFromHeight<S, B, DeltaRate>, LazyPerBlock<StoredF32, B>>,
)
where
    S: VecValue,
    B: BpsType;

/// Lazy rolling deltas for all 4 window durations (24h, 1w, 1m, 1y).
///
/// Tree shape: `absolute._24h/...`, `rate._24h/...` — matches old `RollingDelta`.
///
/// Replaces `RollingDelta`, `RollingDelta1m`, and `RollingDeltaExcept1m` — since
/// there is no storage cost, all 4 windows are always available.
#[derive(Clone, Traversable)]
pub struct LazyRollingDeltasFromHeight<S, C, B>
where
    S: VecValue,
    C: NumericValue + JsonSchema,
    B: BpsType,
{
    pub absolute: Windows<LazyDeltaFromHeight<S, C, DeltaChange>>,
    pub rate: Windows<LazyDeltaPercentFromHeight<S, B>>,
}

impl<S, C, B> LazyRollingDeltasFromHeight<S, C, B>
where
    S: VecValue + Into<f64>,
    C: NumericValue + JsonSchema + From<f64>,
    B: BpsType + From<f64>,
{
    pub fn new(
        name: &str,
        version: Version,
        source: &(impl ReadableCloneableVec<Height, S> + 'static),
        cached_starts: &Windows<&WindowStartVec>,
        indexes: &indexes::Vecs,
    ) -> Self {
        let src = source.read_only_boxed_clone();

        let make_slot = |suffix: &str, cached_start: &&WindowStartVec| {
            let full_name = format!("{name}_{suffix}");
            let cached = cached_start.read_only_clone();
            let starts_version = cached.version();

            // Absolute change: source[h] - source[ago] as C (via f64)
            let change_vec = LazyDeltaVec::<Height, S, C, DeltaChange>::new(
                &full_name,
                version,
                src.clone(),
                starts_version,
                {
                    let cached = cached.clone();
                    move || cached.cached()
                },
            );
            let change_resolutions =
                Resolutions::forced_import(&full_name, change_vec.clone(), version, indexes);
            let absolute = LazyDeltaFromHeight {
                height: change_vec,
                resolutions: Box::new(change_resolutions),
            };

            // Rate BPS: (source[h] - source[ago]) / source[ago] as B (via f64)
            let rate_bps_name = format!("{full_name}_rate_bps");
            let rate_vec = LazyDeltaVec::<Height, S, B, DeltaRate>::new(
                &rate_bps_name,
                version,
                src.clone(),
                starts_version,
                move || cached.cached(),
            );
            let rate_resolutions =
                Resolutions::forced_import(&rate_bps_name, rate_vec.clone(), version, indexes);
            let bps = LazyDeltaFromHeight {
                height: rate_vec,
                resolutions: Box::new(rate_resolutions),
            };

            // Ratio: bps / 10000
            let rate_ratio_name = format!("{full_name}_rate_ratio");
            let ratio = LazyPerBlock {
                height: LazyVecFrom1::transformed::<B::ToRatio>(
                    &rate_ratio_name,
                    version,
                    bps.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<B::ToRatio>(
                    &rate_ratio_name,
                    version,
                    &bps.resolutions,
                )),
            };

            // Percent: bps / 100
            let rate_name = format!("{full_name}_rate");
            let percent = LazyPerBlock {
                height: LazyVecFrom1::transformed::<B::ToPercent>(
                    &rate_name,
                    version,
                    bps.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<B::ToPercent>(
                    &rate_name,
                    version,
                    &bps.resolutions,
                )),
            };

            let rate = LazyDeltaPercentFromHeight(Percent {
                bps,
                ratio,
                percent,
            });

            (absolute, rate)
        };

        let (absolute, rate) = cached_starts.map_with_suffix(make_slot).unzip();

        Self { absolute, rate }
    }
}

// ---------------------------------------------------------------------------
// Amount delta types (sats change + lazy BTC + rate)
// ---------------------------------------------------------------------------

/// Single-slot amount delta change: sats delta + lazy BTC.
#[derive(Clone, Traversable)]
pub struct LazyDeltaAmountFromHeight<S, C>
where
    S: VecValue,
    C: AmountType,
{
    pub btc: LazyPerBlock<Bitcoin, C>,
    pub sats: LazyDeltaFromHeight<S, C, DeltaChange>,
}

/// Lazy amount rolling deltas for all 4 windows.
///
/// Tree shape: `absolute._24h.{sats,btc}/...`, `rate._24h/...` — mirrors
/// `LazyRollingDeltasFiatFromHeight` but stores sats instead of cents and
/// derives a lazy BTC view alongside (free, since sats → btc is a scalar
/// transform).
#[derive(Clone, Traversable)]
pub struct LazyRollingDeltasAmountFromHeight<S, C, B>
where
    S: VecValue,
    C: AmountType,
    B: BpsType,
{
    pub absolute: Windows<LazyDeltaAmountFromHeight<S, C>>,
    pub rate: Windows<LazyDeltaPercentFromHeight<S, B>>,
}

impl<S, C, B> LazyRollingDeltasAmountFromHeight<S, C, B>
where
    S: VecValue + Into<f64>,
    C: AmountType + From<f64>,
    B: BpsType + From<f64>,
{
    pub fn new(
        name: &str,
        version: Version,
        source: &(impl ReadableCloneableVec<Height, S> + 'static),
        cached_starts: &Windows<&WindowStartVec>,
        indexes: &indexes::Vecs,
    ) -> Self {
        let src = source.read_only_boxed_clone();

        let make_slot = |suffix: &str, cached_start: &&WindowStartVec| {
            let full_name = format!("{name}_{suffix}");
            let cached = cached_start.read_only_clone();
            let starts_version = cached.version();

            // Absolute change (sats): source[h] - source[ago] as C (via f64)
            let sats_name = format!("{full_name}_sats");
            let change_vec = LazyDeltaVec::<Height, S, C, DeltaChange>::new(
                &sats_name,
                version,
                src.clone(),
                starts_version,
                {
                    let cached = cached.clone();
                    move || cached.cached()
                },
            );
            let change_resolutions =
                Resolutions::forced_import(&sats_name, change_vec.clone(), version, indexes);
            let sats = LazyDeltaFromHeight {
                height: change_vec,
                resolutions: Box::new(change_resolutions),
            };

            // Absolute change (btc): lazy from sats delta
            let btc = LazyPerBlock {
                height: LazyVecFrom1::transformed::<C::ToBitcoin>(
                    &full_name,
                    version,
                    sats.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<C::ToBitcoin>(
                    &full_name,
                    version,
                    &sats.resolutions,
                )),
            };

            let absolute = LazyDeltaAmountFromHeight { btc, sats };

            // Rate BPS: (source[h] - source[ago]) / source[ago] as B (via f64)
            let rate_bps_name = format!("{full_name}_rate_bps");
            let rate_vec = LazyDeltaVec::<Height, S, B, DeltaRate>::new(
                &rate_bps_name,
                version,
                src.clone(),
                starts_version,
                move || cached.cached(),
            );
            let rate_resolutions =
                Resolutions::forced_import(&rate_bps_name, rate_vec.clone(), version, indexes);
            let bps = LazyDeltaFromHeight {
                height: rate_vec,
                resolutions: Box::new(rate_resolutions),
            };

            let rate_ratio_name = format!("{full_name}_rate_ratio");
            let ratio = LazyPerBlock {
                height: LazyVecFrom1::transformed::<B::ToRatio>(
                    &rate_ratio_name,
                    version,
                    bps.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<B::ToRatio>(
                    &rate_ratio_name,
                    version,
                    &bps.resolutions,
                )),
            };

            let rate_name = format!("{full_name}_rate");
            let percent = LazyPerBlock {
                height: LazyVecFrom1::transformed::<B::ToPercent>(
                    &rate_name,
                    version,
                    bps.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<B::ToPercent>(
                    &rate_name,
                    version,
                    &bps.resolutions,
                )),
            };

            let rate = LazyDeltaPercentFromHeight(Percent {
                bps,
                ratio,
                percent,
            });

            (absolute, rate)
        };

        let (absolute, rate) = cached_starts.map_with_suffix(make_slot).unzip();

        Self { absolute, rate }
    }
}

// ---------------------------------------------------------------------------
// Fiat delta types (cents change + lazy USD + rate)
// ---------------------------------------------------------------------------

/// Single-slot fiat delta change: cents delta + lazy USD.
#[derive(Clone, Traversable)]
pub struct LazyDeltaFiatFromHeight<S, C>
where
    S: VecValue,
    C: FiatType,
{
    pub usd: LazyPerBlock<Dollars, C>,
    pub cents: LazyDeltaFromHeight<S, C, DeltaChange>,
}

/// Lazy fiat rolling deltas for all 4 windows.
///
/// Tree shape: `absolute._24h.{cents,usd}/...`, `rate._24h/...` — matches old `FiatRollingDelta`.
///
/// Replaces `FiatRollingDelta`, `FiatRollingDelta1m`, and `FiatRollingDeltaExcept1m`.
#[derive(Clone, Traversable)]
pub struct LazyRollingDeltasFiatFromHeight<S, C, B>
where
    S: VecValue,
    C: FiatType,
    B: BpsType,
{
    pub absolute: Windows<LazyDeltaFiatFromHeight<S, C>>,
    pub rate: Windows<LazyDeltaPercentFromHeight<S, B>>,
}

impl<S, C, B> LazyRollingDeltasFiatFromHeight<S, C, B>
where
    S: VecValue + Into<f64>,
    C: FiatType + From<f64>,
    B: BpsType + From<f64>,
{
    pub fn new(
        name: &str,
        version: Version,
        source: &(impl ReadableCloneableVec<Height, S> + 'static),
        cached_starts: &Windows<&WindowStartVec>,
        indexes: &indexes::Vecs,
    ) -> Self {
        let src = source.read_only_boxed_clone();

        let make_slot = |suffix: &str, cached_start: &&WindowStartVec| {
            let full_name = format!("{name}_{suffix}");
            let cached = cached_start.read_only_clone();
            let starts_version = cached.version();

            // Absolute change (cents): source[h] - source[ago] as C (via f64)
            let cents_name = format!("{full_name}_cents");
            let change_vec = LazyDeltaVec::<Height, S, C, DeltaChange>::new(
                &cents_name,
                version,
                src.clone(),
                starts_version,
                {
                    let cached = cached.clone();
                    move || cached.cached()
                },
            );
            let change_resolutions =
                Resolutions::forced_import(&cents_name, change_vec.clone(), version, indexes);
            let cents = LazyDeltaFromHeight {
                height: change_vec,
                resolutions: Box::new(change_resolutions),
            };

            // Absolute change (usd): lazy from cents delta
            let usd = LazyPerBlock {
                height: LazyVecFrom1::transformed::<C::ToDollars>(
                    &full_name,
                    version,
                    cents.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<C::ToDollars>(
                    &full_name,
                    version,
                    &cents.resolutions,
                )),
            };

            let absolute = LazyDeltaFiatFromHeight { usd, cents };

            // Rate BPS: (source[h] - source[ago]) / source[ago] as B (via f64)
            let rate_bps_name = format!("{full_name}_rate_bps");
            let rate_vec = LazyDeltaVec::<Height, S, B, DeltaRate>::new(
                &rate_bps_name,
                version,
                src.clone(),
                starts_version,
                move || cached.cached(),
            );
            let rate_resolutions =
                Resolutions::forced_import(&rate_bps_name, rate_vec.clone(), version, indexes);
            let bps = LazyDeltaFromHeight {
                height: rate_vec,
                resolutions: Box::new(rate_resolutions),
            };

            let rate_ratio_name = format!("{full_name}_rate_ratio");
            let ratio = LazyPerBlock {
                height: LazyVecFrom1::transformed::<B::ToRatio>(
                    &rate_ratio_name,
                    version,
                    bps.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<B::ToRatio>(
                    &rate_ratio_name,
                    version,
                    &bps.resolutions,
                )),
            };

            let rate_name = format!("{full_name}_rate");
            let percent = LazyPerBlock {
                height: LazyVecFrom1::transformed::<B::ToPercent>(
                    &rate_name,
                    version,
                    bps.height.read_only_boxed_clone(),
                ),
                resolutions: Box::new(DerivedResolutions::from_derived_computed::<B::ToPercent>(
                    &rate_name,
                    version,
                    &bps.resolutions,
                )),
            };

            let rate = LazyDeltaPercentFromHeight(Percent {
                bps,
                ratio,
                percent,
            });

            (absolute, rate)
        };

        let (absolute, rate) = cached_starts.map_with_suffix(make_slot).unzip();

        Self { absolute, rate }
    }
}