From 6f45ec13f3a9e84728abdaed03e8c5432df5ffa3 Mon Sep 17 00:00:00 2001 From: nym21 Date: Sat, 10 Jan 2026 18:43:18 +0100 Subject: [PATCH] global: snapshot --- Cargo.lock | 6 - Cargo.toml | 4 +- crates/brk_bindgen/src/analysis/patterns.rs | 92 +- crates/brk_bindgen/src/analysis/tree.rs | 8 +- crates/brk_bindgen/src/generate/fields.rs | 6 + crates/brk_bindgen/src/types/schema.rs | 9 - crates/brk_client/src/lib.rs | 1844 +++++++--------- crates/brk_computer/src/blocks/compute.rs | 11 +- .../brk_computer/src/blocks/count/compute.rs | 4 +- .../brk_computer/src/blocks/count/import.rs | 14 +- crates/brk_computer/src/blocks/count/vecs.rs | 14 +- .../src/blocks/difficulty/compute.rs | 46 +- .../src/blocks/difficulty/import.rs | 30 +- .../src/blocks/difficulty/vecs.rs | 18 +- .../brk_computer/src/blocks/halving/import.rs | 8 +- .../brk_computer/src/blocks/halving/vecs.rs | 8 +- crates/brk_computer/src/blocks/import.rs | 7 +- .../src/blocks/interval/import.rs | 4 +- .../brk_computer/src/blocks/interval/vecs.rs | 4 +- .../brk_computer/src/blocks/mining/compute.rs | 37 +- .../brk_computer/src/blocks/mining/import.rs | 56 +- crates/brk_computer/src/blocks/mining/vecs.rs | 40 +- crates/brk_computer/src/blocks/mod.rs | 2 + .../src/blocks/rewards/compute.rs | 10 +- .../brk_computer/src/blocks/rewards/import.rs | 31 +- .../brk_computer/src/blocks/rewards/vecs.rs | 12 +- crates/brk_computer/src/blocks/size/import.rs | 6 +- crates/brk_computer/src/blocks/size/vecs.rs | 6 +- crates/brk_computer/src/blocks/time/import.rs | 4 +- crates/brk_computer/src/blocks/time/vecs.rs | 4 +- .../brk_computer/src/blocks/weight/import.rs | 6 +- crates/brk_computer/src/blocks/weight/vecs.rs | 6 +- .../src/cointime/activity/import.rs | 12 +- .../src/cointime/activity/vecs.rs | 12 +- .../src/cointime/adjusted/import.rs | 8 +- .../src/cointime/adjusted/vecs.rs | 8 +- .../brk_computer/src/cointime/cap/import.rs | 12 +- crates/brk_computer/src/cointime/cap/vecs.rs | 12 +- crates/brk_computer/src/cointime/compute.rs | 1 - crates/brk_computer/src/cointime/import.rs | 3 +- .../src/cointime/pricing/import.rs | 6 +- .../brk_computer/src/cointime/pricing/vecs.rs | 18 +- .../src/cointime/supply/compute.rs | 7 +- .../src/cointime/supply/import.rs | 12 +- .../brk_computer/src/cointime/supply/vecs.rs | 6 +- .../brk_computer/src/cointime/value/import.rs | 8 +- .../brk_computer/src/cointime/value/vecs.rs | 8 +- .../src/distribution/address/address_count.rs | 16 +- .../src/distribution/address/indexes/any.rs | 133 +- .../address/type_map/index_map.rs | 5 + .../block/cohort/address_updates.rs | 43 +- .../src/distribution/cohorts/address/vecs.rs | 6 +- .../src/distribution/compute/write.rs | 9 +- .../src/distribution/metrics/activity.rs | 14 +- .../src/distribution/metrics/cost_basis.rs | 10 +- .../src/distribution/metrics/mod.rs | 2 +- .../src/distribution/metrics/outputs.rs | 6 +- .../src/distribution/metrics/realized.rs | 94 +- .../src/distribution/metrics/relative.rs | 92 +- .../src/distribution/metrics/supply.rs | 21 +- .../src/distribution/metrics/unrealized.rs | 32 +- crates/brk_computer/src/distribution/vecs.rs | 12 +- .../brk_computer/src/inputs/count/import.rs | 4 +- crates/brk_computer/src/inputs/count/vecs.rs | 4 +- crates/brk_computer/src/internal/compute.rs | 146 +- .../{derived_date => date_derived}/average.rs | 4 +- .../distribution.rs | 4 +- .../{derived_date => date_derived}/first.rs | 4 +- .../{derived_date => date_derived}/full.rs | 4 +- .../{derived_date => date_derived}/last.rs | 4 +- .../{derived_date => date_derived}/max.rs | 30 +- .../{derived_date => date_derived}/min.rs | 30 +- .../{derived_date => date_derived}/mod.rs | 2 - .../{derived_date => date_derived}/sum.rs | 4 +- .../{derived_date => date_derived}/sum_cum.rs | 4 +- .../multi/{date => from_date}/average.rs | 12 +- .../multi/{date => from_date}/binary_last.rs | 222 +- .../multi/{date => from_date}/binary_sum.rs | 10 +- .../{date => from_date}/binary_sum_cum.rs | 38 +- .../multi/{date => from_date}/first.rs | 10 +- .../multi/{date => from_date}/last.rs | 10 +- .../multi/{derived_date => from_date}/lazy.rs | 4 +- .../multi/{date => from_date}/lazy_full.rs | 8 +- .../multi/{date => from_date}/lazy_last.rs | 16 +- .../multi/{date => from_date}/lazy_sum.rs | 8 +- .../multi/{date => from_date}/lazy_sum_cum.rs | 8 +- .../internal/multi/{date => from_date}/max.rs | 45 +- .../internal/multi/{date => from_date}/min.rs | 45 +- .../internal/multi/{date => from_date}/mod.rs | 14 + .../{specialized => from_date}/percentiles.rs | 8 +- .../multi/{specialized => from_date}/ratio.rs | 61 +- .../{specialized => from_date}/stddev.rs | 68 +- .../value_derived_last.rs} | 20 +- .../date/last.rs => from_date/value_last.rs} | 12 +- .../value_lazy_last.rs} | 34 +- .../{height => from_height}/binary_full.rs | 16 +- .../{height => from_height}/binary_last.rs | 166 +- .../{height => from_height}/binary_sum.rs | 20 +- .../{height => from_height}/binary_sum_cum.rs | 62 +- .../multi/{height => from_height}/full.rs | 14 +- .../{height/sum.rs => from_height/last.rs} | 12 +- .../from_height/lazy_binary_computed_full.rs | 70 + .../from_height/lazy_binary_computed_last.rs | 70 + .../from_height/lazy_binary_computed_sum.rs | 70 + .../lazy_binary_computed_sum_cum.rs | 71 + .../lazy_computed_full.rs} | 14 +- .../lazy_computed_sum_cum.rs} | 12 +- .../lazy_distribution.rs | 14 +- .../{height => from_height}/lazy_full.rs | 18 +- .../{height => from_height}/lazy_last.rs | 42 +- .../multi/{height => from_height}/lazy_sum.rs | 16 +- .../{height => from_height}/lazy_sum_cum.rs | 19 +- .../lazy_value.rs} | 10 +- .../src/internal/multi/from_height/mod.rs | 59 + .../{height/last.rs => from_height/sum.rs} | 12 +- .../multi/{height => from_height}/sum_cum.rs | 28 +- .../binary.rs => from_height/value_binary.rs} | 56 +- .../internal/multi/from_height/value_full.rs | 94 + .../internal/multi/from_height/value_last.rs | 110 + .../value_lazy_binary_last.rs} | 20 +- .../value_lazy_computed_sum_cum.rs} | 18 +- .../value_lazy_last.rs} | 21 +- .../value_lazy_sum_cum.rs} | 18 +- .../internal/multi/from_height/value_sum.rs | 93 + .../multi/from_height/value_sum_cum.rs | 131 ++ .../binary_last.rs} | 22 +- .../computed_ohlc.rs} | 22 +- .../constant.rs | 11 +- .../first.rs} | 12 +- .../last.rs} | 12 +- .../lazy_ohlc.rs} | 3 +- .../max.rs} | 57 +- .../min.rs} | 57 +- .../multi/from_height_and_date/mod.rs | 19 + .../value_last.rs} | 19 +- .../lazy_distribution.rs | 12 +- .../src/internal/multi/from_tx/mod.rs | 7 + .../internal/multi/from_tx/value_dollars.rs | 202 ++ .../tx/full.rs => from_tx/value_full.rs} | 38 +- .../src/internal/multi/height/mod.rs | 43 - .../bytes.rs} | 6 +- .../src/internal/multi/height_and_date/mod.rs | 5 + .../internal/multi/height_and_date/ohlc.rs | 21 + .../binary_last.rs | 40 +- .../binary_sum.rs | 14 +- .../binary_sum_cum.rs | 54 +- .../distribution.rs | 18 +- .../first.rs | 12 +- .../full.rs | 24 +- .../last.rs | 12 +- .../lazy_full.rs | 16 +- .../lazy_last.rs | 28 +- .../lazy_sum.rs | 18 +- .../lazy_sum_cum.rs | 16 +- .../{derived_height => height_derived}/mod.rs | 2 + .../{derived_height => height_derived}/sum.rs | 12 +- .../sum_cum.rs | 18 +- .../value_sum_cum.rs} | 18 +- crates/brk_computer/src/internal/multi/mod.rs | 30 +- .../src/internal/multi/specialized/mod.rs | 11 - .../internal/multi/specialized/ohlc/mod.rs | 7 - .../distribution.rs | 44 +- .../multi/{derived_tx => tx_derived}/full.rs | 52 +- .../{derived_tx => tx_derived}/lazy_full.rs | 20 +- .../multi/{derived_tx => tx_derived}/mod.rs | 4 +- .../value_full.rs} | 46 +- .../src/internal/multi/value/date/mod.rs | 9 - .../multi/value/derived_height/mod.rs | 3 - .../src/internal/multi/value/height/full.rs | 86 - .../src/internal/multi/value/height/last.rs | 107 - .../src/internal/multi/value/height/mod.rs | 27 - .../src/internal/multi/value/height/sum.rs | 86 - .../internal/multi/value/height/sum_cum.rs | 125 -- .../src/internal/multi/value/mod.rs | 9 - .../src/internal/multi/value/tx/dollars.rs | 136 -- .../src/internal/multi/value/tx/mod.rs | 7 - .../difficultyepoch/lazy_value.rs} | 51 +- .../internal/single/difficultyepoch/mod.rs | 3 + .../src/internal/single/group/distribution.rs | 68 +- .../src/internal/single/group/full.rs | 83 +- .../internal/single/group/min_max_average.rs | 27 +- .../src/internal/single/group/percentiles.rs | 23 +- .../src/internal/single/group/stats.rs | 68 +- .../src/internal/single/group/sum_cum.rs | 12 +- .../height/derived_values.rs} | 4 +- .../height/lazy_value.rs} | 8 +- .../src/internal/single/height/mod.rs | 7 + .../{value/height.rs => height/value.rs} | 4 +- .../src/internal/single/lazy/max.rs | 21 +- .../src/internal/single/lazy/min.rs | 21 +- .../single/lazy_transform/binary_full.rs | 101 + .../lazy_transform/binary_percentiles.rs | 71 + .../single/lazy_transform/binary_sum.rs | 6 +- .../single/lazy_transform/binary_sum_cum.rs | 32 +- .../internal/single/lazy_transform/full.rs | 13 +- .../internal/single/lazy_transform/last.rs | 2 +- .../src/internal/single/lazy_transform/mod.rs | 4 + .../single/lazy_transform/percentiles.rs | 12 +- .../src/internal/single/lazy_transform/sum.rs | 4 +- .../internal/single/lazy_transform/sum_cum.rs | 10 +- .../brk_computer/src/internal/single/mod.rs | 6 +- .../src/internal/single/transform/mod.rs | 4 + .../ohlc/lazy.rs => single/transform/ohlc.rs} | 15 +- .../transform/sats_times_close_price.rs | 14 + .../src/internal/single/tx/distribution.rs | 36 +- .../src/internal/single/value/mod.rs | 3 - .../src/internal/single/vec/average.rs | 6 +- .../src/internal/single/vec/cumulative.rs | 6 +- .../src/internal/single/vec/first.rs | 8 +- .../src/internal/single/vec/last.rs | 6 +- .../src/internal/single/vec/max.rs | 6 +- .../src/internal/single/vec/min.rs | 6 +- .../src/internal/single/vec/percentiles.rs | 6 +- .../src/internal/single/vec/sum.rs | 6 +- crates/brk_computer/src/lib.rs | 12 +- crates/brk_computer/src/market/ath/import.rs | 14 +- crates/brk_computer/src/market/ath/vecs.rs | 14 +- crates/brk_computer/src/market/dca/import.rs | 18 +- crates/brk_computer/src/market/dca/vecs.rs | 18 +- .../src/market/indicators/import.rs | 14 +- .../src/market/indicators/vecs.rs | 6 +- .../src/market/lookback/import.rs | 4 +- .../brk_computer/src/market/lookback/vecs.rs | 4 +- .../src/market/moving_average/import.rs | 72 +- .../src/market/moving_average/vecs.rs | 72 +- .../brk_computer/src/market/range/compute.rs | 8 +- .../brk_computer/src/market/range/import.rs | 28 +- crates/brk_computer/src/market/range/vecs.rs | 24 +- .../brk_computer/src/market/returns/import.rs | 18 +- .../brk_computer/src/market/returns/vecs.rs | 18 +- .../src/market/volatility/import.rs | 32 +- .../src/market/volatility/vecs.rs | 8 +- .../brk_computer/src/outputs/count/import.rs | 6 +- crates/brk_computer/src/outputs/count/vecs.rs | 6 +- crates/brk_computer/src/pools/vecs.rs | 62 +- crates/brk_computer/src/price/cents/import.rs | 8 +- crates/brk_computer/src/price/cents/vecs.rs | 6 +- crates/brk_computer/src/price/sats/import.rs | 6 +- crates/brk_computer/src/price/sats/vecs.rs | 6 +- crates/brk_computer/src/price/usd/import.rs | 6 +- crates/brk_computer/src/price/usd/vecs.rs | 6 +- crates/brk_computer/src/scripts/compute.rs | 5 +- .../brk_computer/src/scripts/count/import.rs | 32 +- crates/brk_computer/src/scripts/count/vecs.rs | 32 +- crates/brk_computer/src/scripts/import.rs | 3 +- .../brk_computer/src/scripts/value/compute.rs | 5 +- .../brk_computer/src/scripts/value/import.rs | 8 +- crates/brk_computer/src/scripts/value/vecs.rs | 4 +- .../brk_computer/src/supply/burned/compute.rs | 7 +- .../brk_computer/src/supply/burned/import.rs | 12 +- crates/brk_computer/src/supply/burned/vecs.rs | 6 +- .../src/supply/circulating/import.rs | 4 +- .../src/supply/circulating/vecs.rs | 4 +- crates/brk_computer/src/supply/compute.rs | 5 +- crates/brk_computer/src/supply/import.rs | 2 +- .../src/supply/inflation/import.rs | 4 +- .../brk_computer/src/supply/inflation/vecs.rs | 4 +- .../src/supply/market_cap/import.rs | 4 +- .../src/supply/market_cap/vecs.rs | 4 +- .../src/supply/velocity/import.rs | 6 +- .../brk_computer/src/supply/velocity/vecs.rs | 6 +- crates/brk_computer/src/traits/pricing.rs | 2 +- .../brk_computer/src/transactions/compute.rs | 4 +- .../src/transactions/count/import.rs | 4 +- .../src/transactions/count/vecs.rs | 4 +- .../src/transactions/fees/compute.rs | 6 +- .../src/transactions/fees/import.rs | 10 +- .../src/transactions/fees/vecs.rs | 6 +- .../brk_computer/src/transactions/import.rs | 3 +- .../src/transactions/size/import.rs | 6 +- .../src/transactions/size/vecs.rs | 6 +- .../src/transactions/versions/compute.rs | 4 +- .../src/transactions/versions/import.rs | 8 +- .../src/transactions/versions/vecs.rs | 8 +- .../src/transactions/volume/compute.rs | 5 +- .../src/transactions/volume/import.rs | 17 +- .../src/transactions/volume/vecs.rs | 12 +- crates/brk_indexer/src/vecs/blocks.rs | 2 + .../brk_query/src/impl/mining/block_fees.rs | 3 +- .../src/impl/mining/block_rewards.rs | 3 +- .../brk_query/src/impl/mining/block_sizes.rs | 6 +- crates/brk_query/src/impl/mining/epochs.rs | 2 +- crates/brk_query/src/vecs.rs | 2 - crates/brk_traversable/tests/derive_tests.rs | 874 -------- .../tests/traversable/common.rs | 162 -- .../tests/traversable/computed_types.rs | 224 -- .../tests/traversable/derived_date.rs | 172 -- .../tests/traversable/group_types.rs | 239 --- .../tests/traversable/lazy_aggregation.rs | 176 -- .../brk_traversable/tests/traversable/main.rs | 12 - crates/brk_types/src/ohlc.rs | 4 + crates/brk_types/src/treenode.rs | 80 +- modules/brk-client/index.js | 1890 ++++++++--------- .../modern-screenshot/4.6.6/dist/index.d.ts | 1 + .../modern-screenshot/4.6.6/dist/index.mjs | 1 + packages/brk_client/brk_client/__init__.py | 1077 +++++----- websites/bitview/index.html | 52 +- websites/bitview/scripts/chart/index.js | 7 +- websites/bitview/scripts/entry.js | 8 +- websites/bitview/scripts/lazy.js | 2 +- websites/bitview/scripts/options/chain.js | 580 +---- .../scripts/options/cohorts/address.js | 6 +- .../bitview/scripts/options/cohorts/shared.js | 24 +- .../bitview/scripts/options/cohorts/utxo.js | 32 +- websites/bitview/scripts/options/cointime.js | 22 +- websites/bitview/scripts/options/constants.js | 6 +- websites/bitview/scripts/options/context.js | 28 +- .../bitview/scripts/options/market/index.js | 5 +- websites/bitview/scripts/options/series.js | 381 +++- websites/bitview/scripts/options/types.js | 11 +- websites/bitview/scripts/panes/chart/index.js | 8 +- 311 files changed, 6916 insertions(+), 7664 deletions(-) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/average.rs (96%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/distribution.rs (96%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/first.rs (96%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/full.rs (97%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/last.rs (96%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/max.rs (62%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/min.rs (62%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/mod.rs (90%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/sum.rs (96%) rename crates/brk_computer/src/internal/multi/{derived_date => date_derived}/sum_cum.rs (96%) rename crates/brk_computer/src/internal/multi/{date => from_date}/average.rs (80%) rename crates/brk_computer/src/internal/multi/{date => from_date}/binary_last.rs (71%) rename crates/brk_computer/src/internal/multi/{date => from_date}/binary_sum.rs (86%) rename crates/brk_computer/src/internal/multi/{date => from_date}/binary_sum_cum.rs (89%) rename crates/brk_computer/src/internal/multi/{date => from_date}/first.rs (86%) rename crates/brk_computer/src/internal/multi/{date => from_date}/last.rs (88%) rename crates/brk_computer/src/internal/multi/{derived_date => from_date}/lazy.rs (96%) rename crates/brk_computer/src/internal/multi/{date => from_date}/lazy_full.rs (89%) rename crates/brk_computer/src/internal/multi/{date => from_date}/lazy_last.rs (85%) rename crates/brk_computer/src/internal/multi/{date => from_date}/lazy_sum.rs (89%) rename crates/brk_computer/src/internal/multi/{date => from_date}/lazy_sum_cum.rs (89%) rename crates/brk_computer/src/internal/multi/{date => from_date}/max.rs (57%) rename crates/brk_computer/src/internal/multi/{date => from_date}/min.rs (57%) rename crates/brk_computer/src/internal/multi/{date => from_date}/mod.rs (60%) rename crates/brk_computer/src/internal/multi/{specialized => from_date}/percentiles.rs (93%) rename crates/brk_computer/src/internal/multi/{specialized => from_date}/ratio.rs (83%) rename crates/brk_computer/src/internal/multi/{specialized => from_date}/stddev.rs (83%) rename crates/brk_computer/src/internal/multi/{value/date/derived_last.rs => from_date/value_derived_last.rs} (74%) rename crates/brk_computer/src/internal/multi/{value/date/last.rs => from_date/value_last.rs} (87%) rename crates/brk_computer/src/internal/multi/{value/date/lazy_last.rs => from_date/value_lazy_last.rs} (67%) rename crates/brk_computer/src/internal/multi/{height => from_height}/binary_full.rs (74%) rename crates/brk_computer/src/internal/multi/{height => from_height}/binary_last.rs (55%) rename crates/brk_computer/src/internal/multi/{height => from_height}/binary_sum.rs (71%) rename crates/brk_computer/src/internal/multi/{height => from_height}/binary_sum_cum.rs (73%) rename crates/brk_computer/src/internal/multi/{height => from_height}/full.rs (80%) rename crates/brk_computer/src/internal/multi/{height/sum.rs => from_height/last.rs} (82%) create mode 100644 crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_full.rs create mode 100644 crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_last.rs create mode 100644 crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum.rs create mode 100644 crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum_cum.rs rename crates/brk_computer/src/internal/multi/{height/lazy_height_full.rs => from_height/lazy_computed_full.rs} (79%) rename crates/brk_computer/src/internal/multi/{height/lazy_height_sum_cum.rs => from_height/lazy_computed_sum_cum.rs} (82%) rename crates/brk_computer/src/internal/multi/{height => from_height}/lazy_distribution.rs (82%) rename crates/brk_computer/src/internal/multi/{height => from_height}/lazy_full.rs (75%) rename crates/brk_computer/src/internal/multi/{height => from_height}/lazy_last.rs (55%) rename crates/brk_computer/src/internal/multi/{height => from_height}/lazy_sum.rs (76%) rename crates/brk_computer/src/internal/multi/{height => from_height}/lazy_sum_cum.rs (74%) rename crates/brk_computer/src/internal/multi/{value/height/lazy_block_value.rs => from_height/lazy_value.rs} (87%) create mode 100644 crates/brk_computer/src/internal/multi/from_height/mod.rs rename crates/brk_computer/src/internal/multi/{height/last.rs => from_height/sum.rs} (85%) rename crates/brk_computer/src/internal/multi/{height => from_height}/sum_cum.rs (79%) rename crates/brk_computer/src/internal/multi/{value/height/binary.rs => from_height/value_binary.rs} (69%) create mode 100644 crates/brk_computer/src/internal/multi/from_height/value_full.rs create mode 100644 crates/brk_computer/src/internal/multi/from_height/value_last.rs rename crates/brk_computer/src/internal/multi/{value/height/lazy_binary_last.rs => from_height/value_lazy_binary_last.rs} (77%) rename crates/brk_computer/src/internal/multi/{value/height/lazy_computed_sum_cum.rs => from_height/value_lazy_computed_sum_cum.rs} (79%) rename crates/brk_computer/src/internal/multi/{value/height/lazy_last.rs => from_height/value_lazy_last.rs} (57%) rename crates/brk_computer/src/internal/multi/{value/height/lazy_sum_cum.rs => from_height/value_lazy_sum_cum.rs} (80%) create mode 100644 crates/brk_computer/src/internal/multi/from_height/value_sum.rs create mode 100644 crates/brk_computer/src/internal/multi/from_height/value_sum_cum.rs rename crates/brk_computer/src/internal/multi/{height/binary_height_date_last.rs => from_height_and_date/binary_last.rs} (67%) rename crates/brk_computer/src/internal/multi/{specialized/ohlc/computed.rs => from_height_and_date/computed_ohlc.rs} (68%) rename crates/brk_computer/src/internal/multi/{specialized => from_height_and_date}/constant.rs (87%) rename crates/brk_computer/src/internal/multi/{height/height_date_first.rs => from_height_and_date/first.rs} (82%) rename crates/brk_computer/src/internal/multi/{height/height_date_last.rs => from_height_and_date/last.rs} (83%) rename crates/brk_computer/src/internal/multi/{specialized/ohlc/period.rs => from_height_and_date/lazy_ohlc.rs} (94%) rename crates/brk_computer/src/internal/multi/{height/height_date_max.rs => from_height_and_date/max.rs} (51%) rename crates/brk_computer/src/internal/multi/{height/height_date_min.rs => from_height_and_date/min.rs} (51%) create mode 100644 crates/brk_computer/src/internal/multi/from_height_and_date/mod.rs rename crates/brk_computer/src/internal/multi/{value/date/height_date_last.rs => from_height_and_date/value_last.rs} (78%) rename crates/brk_computer/src/internal/multi/{derived_tx => from_tx}/lazy_distribution.rs (81%) create mode 100644 crates/brk_computer/src/internal/multi/from_tx/mod.rs create mode 100644 crates/brk_computer/src/internal/multi/from_tx/value_dollars.rs rename crates/brk_computer/src/internal/multi/{value/tx/full.rs => from_tx/value_full.rs} (52%) delete mode 100644 crates/brk_computer/src/internal/multi/height/mod.rs rename crates/brk_computer/src/internal/multi/{height/height_date_bytes.rs => height_and_date/bytes.rs} (86%) create mode 100644 crates/brk_computer/src/internal/multi/height_and_date/mod.rs create mode 100644 crates/brk_computer/src/internal/multi/height_and_date/ohlc.rs rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/binary_last.rs (71%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/binary_sum.rs (71%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/binary_sum_cum.rs (77%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/distribution.rs (78%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/first.rs (82%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/full.rs (78%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/last.rs (81%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/lazy_full.rs (81%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/lazy_last.rs (73%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/lazy_sum.rs (76%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/lazy_sum_cum.rs (77%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/mod.rs (91%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/sum.rs (88%) rename crates/brk_computer/src/internal/multi/{derived_height => height_derived}/sum_cum.rs (89%) rename crates/brk_computer/src/internal/multi/{value/derived_height/sum_cum.rs => height_derived/value_sum_cum.rs} (79%) delete mode 100644 crates/brk_computer/src/internal/multi/specialized/mod.rs delete mode 100644 crates/brk_computer/src/internal/multi/specialized/ohlc/mod.rs rename crates/brk_computer/src/internal/multi/{derived_tx => tx_derived}/distribution.rs (65%) rename crates/brk_computer/src/internal/multi/{derived_tx => tx_derived}/full.rs (62%) rename crates/brk_computer/src/internal/multi/{derived_tx => tx_derived}/lazy_full.rs (80%) rename crates/brk_computer/src/internal/multi/{derived_tx => tx_derived}/mod.rs (67%) rename crates/brk_computer/src/internal/multi/{value/tx/derived_full.rs => tx_derived/value_full.rs} (57%) delete mode 100644 crates/brk_computer/src/internal/multi/value/date/mod.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/derived_height/mod.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/height/full.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/height/last.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/height/mod.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/height/sum.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/height/sum_cum.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/mod.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/tx/dollars.rs delete mode 100644 crates/brk_computer/src/internal/multi/value/tx/mod.rs rename crates/brk_computer/src/internal/{multi/value/height/lazy_difficultyepoch.rs => single/difficultyepoch/lazy_value.rs} (79%) create mode 100644 crates/brk_computer/src/internal/single/difficultyepoch/mod.rs rename crates/brk_computer/src/internal/{multi/value/height/lazy_derived.rs => single/height/derived_values.rs} (94%) rename crates/brk_computer/src/internal/{multi/value/height/lazy_height.rs => single/height/lazy_value.rs} (90%) create mode 100644 crates/brk_computer/src/internal/single/height/mod.rs rename crates/brk_computer/src/internal/single/{value/height.rs => height/value.rs} (96%) create mode 100644 crates/brk_computer/src/internal/single/lazy_transform/binary_full.rs create mode 100644 crates/brk_computer/src/internal/single/lazy_transform/binary_percentiles.rs rename crates/brk_computer/src/internal/{multi/specialized/ohlc/lazy.rs => single/transform/ohlc.rs} (58%) create mode 100644 crates/brk_computer/src/internal/single/transform/sats_times_close_price.rs delete mode 100644 crates/brk_computer/src/internal/single/value/mod.rs delete mode 100644 crates/brk_traversable/tests/derive_tests.rs delete mode 100644 crates/brk_traversable/tests/traversable/common.rs delete mode 100644 crates/brk_traversable/tests/traversable/computed_types.rs delete mode 100644 crates/brk_traversable/tests/traversable/derived_date.rs delete mode 100644 crates/brk_traversable/tests/traversable/group_types.rs delete mode 100644 crates/brk_traversable/tests/traversable/lazy_aggregation.rs delete mode 100644 crates/brk_traversable/tests/traversable/main.rs diff --git a/Cargo.lock b/Cargo.lock index f2e916dcd..dcc738ae3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2762,8 +2762,6 @@ dependencies = [ [[package]] name = "rawdb" version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a5e6777f8192d5ccaafddad97373ffa60e08f3251afa9365e2a161c69fd9dc" dependencies = [ "libc", "log", @@ -3705,8 +3703,6 @@ checksum = "8f54a172d0620933a27a4360d3db3e2ae0dd6cceae9730751a036bbf182c4b23" [[package]] name = "vecdb" version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "650b943316db7a11c54684ab0390a787aed7fdb306f2e0c1f7cbdf8b2440644a" dependencies = [ "ctrlc", "log", @@ -3726,8 +3722,6 @@ dependencies = [ [[package]] name = "vecdb_derive" version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b71f12e3bfb96b62f18d6293029870102764565895effc4e25922002ad1db6" dependencies = [ "quote", "syn", diff --git a/Cargo.toml b/Cargo.toml index fcae36f0f..643a26a93 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,8 +79,8 @@ serde_json = { version = "1.0.149", features = ["float_roundtrip"] } smallvec = "1.15.1" tokio = { version = "1.49.0", features = ["rt-multi-thread"] } tracing = { version = "0.1", default-features = false, features = ["std"] } -vecdb = { version = "0.5.7", features = ["derive", "serde_json", "pco", "schemars"] } -# vecdb = { path = "../anydb/crates/vecdb", features = ["derive", "serde_json", "pco", "schemars"] } +# vecdb = { version = "0.5.7", features = ["derive", "serde_json", "pco", "schemars"] } +vecdb = { path = "../anydb/crates/vecdb", features = ["derive", "serde_json", "pco", "schemars"] } # vecdb = { git = "https://github.com/anydb-rs/anydb", features = ["derive", "serde_json", "pco"] } [workspace.metadata.release] diff --git a/crates/brk_bindgen/src/analysis/patterns.rs b/crates/brk_bindgen/src/analysis/patterns.rs index 96cfd8678..b7bbec731 100644 --- a/crates/brk_bindgen/src/analysis/patterns.rs +++ b/crates/brk_bindgen/src/analysis/patterns.rs @@ -5,10 +5,10 @@ use std::collections::{BTreeSet, HashMap}; -use brk_types::TreeNode; +use brk_types::{TreeNode, extract_json_type}; use super::analyze_all_field_positions; -use crate::{PatternField, StructuralPattern, schema_to_json_type, to_pascal_case}; +use crate::{PatternField, StructuralPattern, to_pascal_case}; /// Context for pattern detection, holding all intermediate state. struct PatternContext { @@ -147,6 +147,11 @@ fn detect_generic_patterns( } /// Normalize fields by replacing concrete value types with "T". +/// +/// Handles two cases: +/// 1. All leaves have identical types (e.g., all `Sats`) -> normalize to `T` +/// 2. All leaves have wrapper types with the same inner type (e.g., `Open`, `High`) +/// -> normalize to `Open`, `High`, etc. fn normalize_fields_for_generic(fields: &[PatternField]) -> Option<(Vec, String)> { let leaf_types: Vec<&str> = fields .iter() @@ -159,28 +164,75 @@ fn normalize_fields_for_generic(fields: &[PatternField]) -> Option<(Vec, High, Low, Close all have inner type Sats + let inner_types: Vec = leaf_types .iter() - .map(|f| { - if f.is_branch() { - f.clone() - } else { - PatternField { - name: f.name.clone(), - rust_type: "T".to_string(), - json_type: "T".to_string(), - indexes: f.indexes.clone(), - type_param: None, - } - } - }) + .map(|t| crate::extract_inner_type(t)) .collect(); - Some((normalized, crate::extract_inner_type(first_type))) + let first_inner = &inner_types[0]; + + // Only proceed if inner types differ from originals (meaning they had wrappers) + // and all inner types are the same + if inner_types.iter().all(|t| t == first_inner) + && inner_types.iter().zip(leaf_types.iter()).any(|(inner, orig)| inner != *orig) + { + let normalized = fields + .iter() + .map(|f| { + if f.is_branch() { + f.clone() + } else { + PatternField { + name: f.name.clone(), + rust_type: replace_inner_type(&f.rust_type, "T"), + json_type: replace_inner_type(&f.json_type, "T"), + indexes: f.indexes.clone(), + type_param: None, + } + } + }) + .collect(); + return Some((normalized, first_inner.clone())); + } + + None +} + +/// Replace the inner type of a wrapper generic with a new type. +/// e.g., `Open` with replacement `T` -> `Open` +fn replace_inner_type(type_str: &str, replacement: &str) -> String { + if let Some(start) = type_str.find('<') + && let Some(end) = type_str.rfind('>') + && start < end + { + format!("{}<{}>", &type_str[..start], replacement) + } else { + replacement.to_string() + } } /// Recursively resolve branch patterns bottom-up. @@ -200,7 +252,7 @@ fn resolve_branch_patterns( let (rust_type, json_type, indexes, child_fields) = match child_node { TreeNode::Leaf(leaf) => ( leaf.kind().to_string(), - schema_to_json_type(&leaf.schema), + extract_json_type(&leaf.schema), leaf.indexes().clone(), Vec::new(), ), diff --git a/crates/brk_bindgen/src/analysis/tree.rs b/crates/brk_bindgen/src/analysis/tree.rs index f6889e98c..1fc990bd0 100644 --- a/crates/brk_bindgen/src/analysis/tree.rs +++ b/crates/brk_bindgen/src/analysis/tree.rs @@ -5,9 +5,9 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; -use brk_types::{Index, TreeNode}; +use brk_types::{Index, TreeNode, extract_json_type}; -use crate::{IndexSetPattern, PatternField, child_type_name, schema_to_json_type}; +use crate::{IndexSetPattern, PatternField, child_type_name}; /// Get the first leaf name from a tree node. pub fn get_first_leaf_name(node: &TreeNode) -> Option { @@ -36,7 +36,7 @@ pub fn get_node_fields( let (rust_type, json_type, indexes) = match node { TreeNode::Leaf(leaf) => ( leaf.kind().to_string(), - schema_to_json_type(&leaf.schema), + extract_json_type(&leaf.schema), leaf.indexes().clone(), ), TreeNode::Branch(grandchildren) => { @@ -229,7 +229,7 @@ pub fn get_fields_with_child_info( let (rust_type, json_type, indexes, child_fields) = match node { TreeNode::Leaf(leaf) => ( leaf.kind().to_string(), - schema_to_json_type(&leaf.schema), + extract_json_type(&leaf.schema), leaf.indexes().clone(), None, ), diff --git a/crates/brk_bindgen/src/generate/fields.rs b/crates/brk_bindgen/src/generate/fields.rs index e3db9103d..b69a9187d 100644 --- a/crates/brk_bindgen/src/generate/fields.rs +++ b/crates/brk_bindgen/src/generate/fields.rs @@ -43,6 +43,9 @@ pub fn generate_parameterized_field( syntax.constructor(&field.rust_type, &path_expr) } else if let Some(accessor) = metadata.find_index_set_pattern(&field.indexes) { syntax.constructor(&accessor.name, &path_expr) + } else if field.is_branch() { + // Non-pattern branch - instantiate the nested struct + syntax.constructor(&field.rust_type, &path_expr) } else { panic!( "Field '{}' has no matching pattern or index accessor. All metrics must be indexed.", @@ -72,6 +75,9 @@ pub fn generate_tree_path_field( syntax.constructor(&field.rust_type, &path_expr) } else if let Some(accessor) = metadata.find_index_set_pattern(&field.indexes) { syntax.constructor(&accessor.name, &path_expr) + } else if field.is_branch() { + // Non-pattern branch - instantiate the nested struct + syntax.constructor(&field.rust_type, &path_expr) } else { panic!( "Field '{}' has no matching pattern or index accessor. All metrics must be indexed.", diff --git a/crates/brk_bindgen/src/types/schema.rs b/crates/brk_bindgen/src/types/schema.rs index ec64a5253..98ce7b6f9 100644 --- a/crates/brk_bindgen/src/types/schema.rs +++ b/crates/brk_bindgen/src/types/schema.rs @@ -28,15 +28,6 @@ pub fn extract_inner_type(type_str: &str) -> String { type_str.to_string() } -/// Extract JSON type from a schema ("integer", "number", "string", etc). -pub fn schema_to_json_type(schema: &Value) -> String { - schema - .get("type") - .and_then(|v| v.as_str()) - .unwrap_or("object") - .to_string() -} - /// Extract type name from a JSON Schema $ref path. /// E.g., "#/definitions/MyType" -> "MyType", "#/$defs/Foo" -> "Foo" pub fn ref_to_type_name(ref_path: &str) -> Option<&str> { diff --git a/crates/brk_client/src/lib.rs b/crates/brk_client/src/lib.rs index 77945f6b8..bf1881bde 100644 --- a/crates/brk_client/src/lib.rs +++ b/crates/brk_client/src/lib.rs @@ -552,27 +552,15 @@ pub struct MetricPattern5By { } impl MetricPattern5By { - pub fn by_decadeindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::DecadeIndex) + pub fn by_dateindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::DateIndex) } - pub fn by_monthindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::MonthIndex) - } - pub fn by_quarterindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::QuarterIndex) - } - pub fn by_semesterindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::SemesterIndex) - } - pub fn by_weekindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::WeekIndex) - } - pub fn by_yearindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::YearIndex) + pub fn by_height(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::Height) } } -/// Index accessor for metrics with 6 indexes. +/// Index accessor for metrics with 2 indexes. pub struct MetricPattern5 { client: Arc, name: Arc, @@ -606,12 +594,8 @@ impl AnyMetricPattern for MetricPattern5 { fn indexes(&self) -> &'static [Index] { &[ - Index::DecadeIndex, - Index::MonthIndex, - Index::QuarterIndex, - Index::SemesterIndex, - Index::WeekIndex, - Index::YearIndex, + Index::DateIndex, + Index::Height, ] } } @@ -619,12 +603,8 @@ impl AnyMetricPattern for MetricPattern5 { impl MetricPattern for MetricPattern5 { fn get(&self, index: Index) -> Option> { match index { - Index::DecadeIndex => Some(self.by.by_decadeindex()), - Index::MonthIndex => Some(self.by.by_monthindex()), - Index::QuarterIndex => Some(self.by.by_quarterindex()), - Index::SemesterIndex => Some(self.by.by_semesterindex()), - Index::WeekIndex => Some(self.by.by_weekindex()), - Index::YearIndex => Some(self.by.by_yearindex()), + Index::DateIndex => Some(self.by.by_dateindex()), + Index::Height => Some(self.by.by_height()), _ => None, } } @@ -641,12 +621,9 @@ impl MetricPattern6By { pub fn by_dateindex(&self) -> Endpoint { Endpoint::new(self.client.clone(), self.name.clone(), Index::DateIndex) } - pub fn by_height(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::Height) - } } -/// Index accessor for metrics with 2 indexes. +/// Index accessor for metrics with 1 indexes. pub struct MetricPattern6 { client: Arc, name: Arc, @@ -681,7 +658,6 @@ impl AnyMetricPattern for MetricPattern6 { fn indexes(&self) -> &'static [Index] { &[ Index::DateIndex, - Index::Height, ] } } @@ -690,7 +666,6 @@ impl MetricPattern for MetricPattern6 { fn get(&self, index: Index) -> Option> { match index { Index::DateIndex => Some(self.by.by_dateindex()), - Index::Height => Some(self.by.by_height()), _ => None, } } @@ -704,8 +679,8 @@ pub struct MetricPattern7By { } impl MetricPattern7By { - pub fn by_dateindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::DateIndex) + pub fn by_decadeindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::DecadeIndex) } } @@ -743,7 +718,7 @@ impl AnyMetricPattern for MetricPattern7 { fn indexes(&self) -> &'static [Index] { &[ - Index::DateIndex, + Index::DecadeIndex, ] } } @@ -751,7 +726,7 @@ impl AnyMetricPattern for MetricPattern7 { impl MetricPattern for MetricPattern7 { fn get(&self, index: Index) -> Option> { match index { - Index::DateIndex => Some(self.by.by_dateindex()), + Index::DecadeIndex => Some(self.by.by_decadeindex()), _ => None, } } @@ -765,8 +740,8 @@ pub struct MetricPattern8By { } impl MetricPattern8By { - pub fn by_decadeindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::DecadeIndex) + pub fn by_difficultyepoch(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::DifficultyEpoch) } } @@ -804,7 +779,7 @@ impl AnyMetricPattern for MetricPattern8 { fn indexes(&self) -> &'static [Index] { &[ - Index::DecadeIndex, + Index::DifficultyEpoch, ] } } @@ -812,7 +787,7 @@ impl AnyMetricPattern for MetricPattern8 { impl MetricPattern for MetricPattern8 { fn get(&self, index: Index) -> Option> { match index { - Index::DecadeIndex => Some(self.by.by_decadeindex()), + Index::DifficultyEpoch => Some(self.by.by_difficultyepoch()), _ => None, } } @@ -826,8 +801,8 @@ pub struct MetricPattern9By { } impl MetricPattern9By { - pub fn by_difficultyepoch(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::DifficultyEpoch) + pub fn by_emptyoutputindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::EmptyOutputIndex) } } @@ -865,7 +840,7 @@ impl AnyMetricPattern for MetricPattern9 { fn indexes(&self) -> &'static [Index] { &[ - Index::DifficultyEpoch, + Index::EmptyOutputIndex, ] } } @@ -873,7 +848,7 @@ impl AnyMetricPattern for MetricPattern9 { impl MetricPattern for MetricPattern9 { fn get(&self, index: Index) -> Option> { match index { - Index::DifficultyEpoch => Some(self.by.by_difficultyepoch()), + Index::EmptyOutputIndex => Some(self.by.by_emptyoutputindex()), _ => None, } } @@ -887,8 +862,8 @@ pub struct MetricPattern10By { } impl MetricPattern10By { - pub fn by_emptyoutputindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::EmptyOutputIndex) + pub fn by_halvingepoch(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::HalvingEpoch) } } @@ -926,7 +901,7 @@ impl AnyMetricPattern for MetricPattern10 { fn indexes(&self) -> &'static [Index] { &[ - Index::EmptyOutputIndex, + Index::HalvingEpoch, ] } } @@ -934,7 +909,7 @@ impl AnyMetricPattern for MetricPattern10 { impl MetricPattern for MetricPattern10 { fn get(&self, index: Index) -> Option> { match index { - Index::EmptyOutputIndex => Some(self.by.by_emptyoutputindex()), + Index::HalvingEpoch => Some(self.by.by_halvingepoch()), _ => None, } } @@ -948,8 +923,8 @@ pub struct MetricPattern11By { } impl MetricPattern11By { - pub fn by_halvingepoch(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::HalvingEpoch) + pub fn by_height(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::Height) } } @@ -987,7 +962,7 @@ impl AnyMetricPattern for MetricPattern11 { fn indexes(&self) -> &'static [Index] { &[ - Index::HalvingEpoch, + Index::Height, ] } } @@ -995,7 +970,7 @@ impl AnyMetricPattern for MetricPattern11 { impl MetricPattern for MetricPattern11 { fn get(&self, index: Index) -> Option> { match index { - Index::HalvingEpoch => Some(self.by.by_halvingepoch()), + Index::Height => Some(self.by.by_height()), _ => None, } } @@ -1009,8 +984,8 @@ pub struct MetricPattern12By { } impl MetricPattern12By { - pub fn by_height(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::Height) + pub fn by_txinindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::TxInIndex) } } @@ -1048,7 +1023,7 @@ impl AnyMetricPattern for MetricPattern12 { fn indexes(&self) -> &'static [Index] { &[ - Index::Height, + Index::TxInIndex, ] } } @@ -1056,7 +1031,7 @@ impl AnyMetricPattern for MetricPattern12 { impl MetricPattern for MetricPattern12 { fn get(&self, index: Index) -> Option> { match index { - Index::Height => Some(self.by.by_height()), + Index::TxInIndex => Some(self.by.by_txinindex()), _ => None, } } @@ -1070,8 +1045,8 @@ pub struct MetricPattern13By { } impl MetricPattern13By { - pub fn by_txinindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::TxInIndex) + pub fn by_monthindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::MonthIndex) } } @@ -1109,7 +1084,7 @@ impl AnyMetricPattern for MetricPattern13 { fn indexes(&self) -> &'static [Index] { &[ - Index::TxInIndex, + Index::MonthIndex, ] } } @@ -1117,7 +1092,7 @@ impl AnyMetricPattern for MetricPattern13 { impl MetricPattern for MetricPattern13 { fn get(&self, index: Index) -> Option> { match index { - Index::TxInIndex => Some(self.by.by_txinindex()), + Index::MonthIndex => Some(self.by.by_monthindex()), _ => None, } } @@ -1131,8 +1106,8 @@ pub struct MetricPattern14By { } impl MetricPattern14By { - pub fn by_monthindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::MonthIndex) + pub fn by_opreturnindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::OpReturnIndex) } } @@ -1170,7 +1145,7 @@ impl AnyMetricPattern for MetricPattern14 { fn indexes(&self) -> &'static [Index] { &[ - Index::MonthIndex, + Index::OpReturnIndex, ] } } @@ -1178,7 +1153,7 @@ impl AnyMetricPattern for MetricPattern14 { impl MetricPattern for MetricPattern14 { fn get(&self, index: Index) -> Option> { match index { - Index::MonthIndex => Some(self.by.by_monthindex()), + Index::OpReturnIndex => Some(self.by.by_opreturnindex()), _ => None, } } @@ -1192,8 +1167,8 @@ pub struct MetricPattern15By { } impl MetricPattern15By { - pub fn by_opreturnindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::OpReturnIndex) + pub fn by_txoutindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::TxOutIndex) } } @@ -1231,7 +1206,7 @@ impl AnyMetricPattern for MetricPattern15 { fn indexes(&self) -> &'static [Index] { &[ - Index::OpReturnIndex, + Index::TxOutIndex, ] } } @@ -1239,7 +1214,7 @@ impl AnyMetricPattern for MetricPattern15 { impl MetricPattern for MetricPattern15 { fn get(&self, index: Index) -> Option> { match index { - Index::OpReturnIndex => Some(self.by.by_opreturnindex()), + Index::TxOutIndex => Some(self.by.by_txoutindex()), _ => None, } } @@ -1253,8 +1228,8 @@ pub struct MetricPattern16By { } impl MetricPattern16By { - pub fn by_txoutindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::TxOutIndex) + pub fn by_p2aaddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2AAddressIndex) } } @@ -1292,7 +1267,7 @@ impl AnyMetricPattern for MetricPattern16 { fn indexes(&self) -> &'static [Index] { &[ - Index::TxOutIndex, + Index::P2AAddressIndex, ] } } @@ -1300,7 +1275,7 @@ impl AnyMetricPattern for MetricPattern16 { impl MetricPattern for MetricPattern16 { fn get(&self, index: Index) -> Option> { match index { - Index::TxOutIndex => Some(self.by.by_txoutindex()), + Index::P2AAddressIndex => Some(self.by.by_p2aaddressindex()), _ => None, } } @@ -1314,8 +1289,8 @@ pub struct MetricPattern17By { } impl MetricPattern17By { - pub fn by_p2aaddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2AAddressIndex) + pub fn by_p2msoutputindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2MSOutputIndex) } } @@ -1353,7 +1328,7 @@ impl AnyMetricPattern for MetricPattern17 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2AAddressIndex, + Index::P2MSOutputIndex, ] } } @@ -1361,7 +1336,7 @@ impl AnyMetricPattern for MetricPattern17 { impl MetricPattern for MetricPattern17 { fn get(&self, index: Index) -> Option> { match index { - Index::P2AAddressIndex => Some(self.by.by_p2aaddressindex()), + Index::P2MSOutputIndex => Some(self.by.by_p2msoutputindex()), _ => None, } } @@ -1375,8 +1350,8 @@ pub struct MetricPattern18By { } impl MetricPattern18By { - pub fn by_p2msoutputindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2MSOutputIndex) + pub fn by_p2pk33addressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2PK33AddressIndex) } } @@ -1414,7 +1389,7 @@ impl AnyMetricPattern for MetricPattern18 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2MSOutputIndex, + Index::P2PK33AddressIndex, ] } } @@ -1422,7 +1397,7 @@ impl AnyMetricPattern for MetricPattern18 { impl MetricPattern for MetricPattern18 { fn get(&self, index: Index) -> Option> { match index { - Index::P2MSOutputIndex => Some(self.by.by_p2msoutputindex()), + Index::P2PK33AddressIndex => Some(self.by.by_p2pk33addressindex()), _ => None, } } @@ -1436,8 +1411,8 @@ pub struct MetricPattern19By { } impl MetricPattern19By { - pub fn by_p2pk33addressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2PK33AddressIndex) + pub fn by_p2pk65addressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2PK65AddressIndex) } } @@ -1475,7 +1450,7 @@ impl AnyMetricPattern for MetricPattern19 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2PK33AddressIndex, + Index::P2PK65AddressIndex, ] } } @@ -1483,7 +1458,7 @@ impl AnyMetricPattern for MetricPattern19 { impl MetricPattern for MetricPattern19 { fn get(&self, index: Index) -> Option> { match index { - Index::P2PK33AddressIndex => Some(self.by.by_p2pk33addressindex()), + Index::P2PK65AddressIndex => Some(self.by.by_p2pk65addressindex()), _ => None, } } @@ -1497,8 +1472,8 @@ pub struct MetricPattern20By { } impl MetricPattern20By { - pub fn by_p2pk65addressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2PK65AddressIndex) + pub fn by_p2pkhaddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2PKHAddressIndex) } } @@ -1536,7 +1511,7 @@ impl AnyMetricPattern for MetricPattern20 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2PK65AddressIndex, + Index::P2PKHAddressIndex, ] } } @@ -1544,7 +1519,7 @@ impl AnyMetricPattern for MetricPattern20 { impl MetricPattern for MetricPattern20 { fn get(&self, index: Index) -> Option> { match index { - Index::P2PK65AddressIndex => Some(self.by.by_p2pk65addressindex()), + Index::P2PKHAddressIndex => Some(self.by.by_p2pkhaddressindex()), _ => None, } } @@ -1558,8 +1533,8 @@ pub struct MetricPattern21By { } impl MetricPattern21By { - pub fn by_p2pkhaddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2PKHAddressIndex) + pub fn by_p2shaddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2SHAddressIndex) } } @@ -1597,7 +1572,7 @@ impl AnyMetricPattern for MetricPattern21 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2PKHAddressIndex, + Index::P2SHAddressIndex, ] } } @@ -1605,7 +1580,7 @@ impl AnyMetricPattern for MetricPattern21 { impl MetricPattern for MetricPattern21 { fn get(&self, index: Index) -> Option> { match index { - Index::P2PKHAddressIndex => Some(self.by.by_p2pkhaddressindex()), + Index::P2SHAddressIndex => Some(self.by.by_p2shaddressindex()), _ => None, } } @@ -1619,8 +1594,8 @@ pub struct MetricPattern22By { } impl MetricPattern22By { - pub fn by_p2shaddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2SHAddressIndex) + pub fn by_p2traddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2TRAddressIndex) } } @@ -1658,7 +1633,7 @@ impl AnyMetricPattern for MetricPattern22 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2SHAddressIndex, + Index::P2TRAddressIndex, ] } } @@ -1666,7 +1641,7 @@ impl AnyMetricPattern for MetricPattern22 { impl MetricPattern for MetricPattern22 { fn get(&self, index: Index) -> Option> { match index { - Index::P2SHAddressIndex => Some(self.by.by_p2shaddressindex()), + Index::P2TRAddressIndex => Some(self.by.by_p2traddressindex()), _ => None, } } @@ -1680,8 +1655,8 @@ pub struct MetricPattern23By { } impl MetricPattern23By { - pub fn by_p2traddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2TRAddressIndex) + pub fn by_p2wpkhaddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2WPKHAddressIndex) } } @@ -1719,7 +1694,7 @@ impl AnyMetricPattern for MetricPattern23 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2TRAddressIndex, + Index::P2WPKHAddressIndex, ] } } @@ -1727,7 +1702,7 @@ impl AnyMetricPattern for MetricPattern23 { impl MetricPattern for MetricPattern23 { fn get(&self, index: Index) -> Option> { match index { - Index::P2TRAddressIndex => Some(self.by.by_p2traddressindex()), + Index::P2WPKHAddressIndex => Some(self.by.by_p2wpkhaddressindex()), _ => None, } } @@ -1741,8 +1716,8 @@ pub struct MetricPattern24By { } impl MetricPattern24By { - pub fn by_p2wpkhaddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2WPKHAddressIndex) + pub fn by_p2wshaddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::P2WSHAddressIndex) } } @@ -1780,7 +1755,7 @@ impl AnyMetricPattern for MetricPattern24 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2WPKHAddressIndex, + Index::P2WSHAddressIndex, ] } } @@ -1788,7 +1763,7 @@ impl AnyMetricPattern for MetricPattern24 { impl MetricPattern for MetricPattern24 { fn get(&self, index: Index) -> Option> { match index { - Index::P2WPKHAddressIndex => Some(self.by.by_p2wpkhaddressindex()), + Index::P2WSHAddressIndex => Some(self.by.by_p2wshaddressindex()), _ => None, } } @@ -1802,8 +1777,8 @@ pub struct MetricPattern25By { } impl MetricPattern25By { - pub fn by_p2wshaddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::P2WSHAddressIndex) + pub fn by_quarterindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::QuarterIndex) } } @@ -1841,7 +1816,7 @@ impl AnyMetricPattern for MetricPattern25 { fn indexes(&self) -> &'static [Index] { &[ - Index::P2WSHAddressIndex, + Index::QuarterIndex, ] } } @@ -1849,7 +1824,7 @@ impl AnyMetricPattern for MetricPattern25 { impl MetricPattern for MetricPattern25 { fn get(&self, index: Index) -> Option> { match index { - Index::P2WSHAddressIndex => Some(self.by.by_p2wshaddressindex()), + Index::QuarterIndex => Some(self.by.by_quarterindex()), _ => None, } } @@ -1863,8 +1838,8 @@ pub struct MetricPattern26By { } impl MetricPattern26By { - pub fn by_quarterindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::QuarterIndex) + pub fn by_semesterindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::SemesterIndex) } } @@ -1902,7 +1877,7 @@ impl AnyMetricPattern for MetricPattern26 { fn indexes(&self) -> &'static [Index] { &[ - Index::QuarterIndex, + Index::SemesterIndex, ] } } @@ -1910,7 +1885,7 @@ impl AnyMetricPattern for MetricPattern26 { impl MetricPattern for MetricPattern26 { fn get(&self, index: Index) -> Option> { match index { - Index::QuarterIndex => Some(self.by.by_quarterindex()), + Index::SemesterIndex => Some(self.by.by_semesterindex()), _ => None, } } @@ -1924,8 +1899,8 @@ pub struct MetricPattern27By { } impl MetricPattern27By { - pub fn by_semesterindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::SemesterIndex) + pub fn by_txindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::TxIndex) } } @@ -1963,7 +1938,7 @@ impl AnyMetricPattern for MetricPattern27 { fn indexes(&self) -> &'static [Index] { &[ - Index::SemesterIndex, + Index::TxIndex, ] } } @@ -1971,7 +1946,7 @@ impl AnyMetricPattern for MetricPattern27 { impl MetricPattern for MetricPattern27 { fn get(&self, index: Index) -> Option> { match index { - Index::SemesterIndex => Some(self.by.by_semesterindex()), + Index::TxIndex => Some(self.by.by_txindex()), _ => None, } } @@ -1985,8 +1960,8 @@ pub struct MetricPattern28By { } impl MetricPattern28By { - pub fn by_txindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::TxIndex) + pub fn by_unknownoutputindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::UnknownOutputIndex) } } @@ -2024,7 +1999,7 @@ impl AnyMetricPattern for MetricPattern28 { fn indexes(&self) -> &'static [Index] { &[ - Index::TxIndex, + Index::UnknownOutputIndex, ] } } @@ -2032,7 +2007,7 @@ impl AnyMetricPattern for MetricPattern28 { impl MetricPattern for MetricPattern28 { fn get(&self, index: Index) -> Option> { match index { - Index::TxIndex => Some(self.by.by_txindex()), + Index::UnknownOutputIndex => Some(self.by.by_unknownoutputindex()), _ => None, } } @@ -2046,8 +2021,8 @@ pub struct MetricPattern29By { } impl MetricPattern29By { - pub fn by_unknownoutputindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::UnknownOutputIndex) + pub fn by_weekindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::WeekIndex) } } @@ -2085,7 +2060,7 @@ impl AnyMetricPattern for MetricPattern29 { fn indexes(&self) -> &'static [Index] { &[ - Index::UnknownOutputIndex, + Index::WeekIndex, ] } } @@ -2093,7 +2068,7 @@ impl AnyMetricPattern for MetricPattern29 { impl MetricPattern for MetricPattern29 { fn get(&self, index: Index) -> Option> { match index { - Index::UnknownOutputIndex => Some(self.by.by_unknownoutputindex()), + Index::WeekIndex => Some(self.by.by_weekindex()), _ => None, } } @@ -2107,8 +2082,8 @@ pub struct MetricPattern30By { } impl MetricPattern30By { - pub fn by_weekindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::WeekIndex) + pub fn by_yearindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::YearIndex) } } @@ -2146,7 +2121,7 @@ impl AnyMetricPattern for MetricPattern30 { fn indexes(&self) -> &'static [Index] { &[ - Index::WeekIndex, + Index::YearIndex, ] } } @@ -2154,7 +2129,7 @@ impl AnyMetricPattern for MetricPattern30 { impl MetricPattern for MetricPattern30 { fn get(&self, index: Index) -> Option> { match index { - Index::WeekIndex => Some(self.by.by_weekindex()), + Index::YearIndex => Some(self.by.by_yearindex()), _ => None, } } @@ -2168,8 +2143,8 @@ pub struct MetricPattern31By { } impl MetricPattern31By { - pub fn by_yearindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::YearIndex) + pub fn by_loadedaddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::LoadedAddressIndex) } } @@ -2207,7 +2182,7 @@ impl AnyMetricPattern for MetricPattern31 { fn indexes(&self) -> &'static [Index] { &[ - Index::YearIndex, + Index::LoadedAddressIndex, ] } } @@ -2215,7 +2190,7 @@ impl AnyMetricPattern for MetricPattern31 { impl MetricPattern for MetricPattern31 { fn get(&self, index: Index) -> Option> { match index { - Index::YearIndex => Some(self.by.by_yearindex()), + Index::LoadedAddressIndex => Some(self.by.by_loadedaddressindex()), _ => None, } } @@ -2229,8 +2204,8 @@ pub struct MetricPattern32By { } impl MetricPattern32By { - pub fn by_loadedaddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::LoadedAddressIndex) + pub fn by_emptyaddressindex(&self) -> Endpoint { + Endpoint::new(self.client.clone(), self.name.clone(), Index::EmptyAddressIndex) } } @@ -2266,67 +2241,6 @@ impl AnyMetricPattern for MetricPattern32 { &self.name } - fn indexes(&self) -> &'static [Index] { - &[ - Index::LoadedAddressIndex, - ] - } -} - -impl MetricPattern for MetricPattern32 { - fn get(&self, index: Index) -> Option> { - match index { - Index::LoadedAddressIndex => Some(self.by.by_loadedaddressindex()), - _ => None, - } - } -} - -/// Container for index endpoint methods. -pub struct MetricPattern33By { - client: Arc, - name: Arc, - _marker: std::marker::PhantomData, -} - -impl MetricPattern33By { - pub fn by_emptyaddressindex(&self) -> Endpoint { - Endpoint::new(self.client.clone(), self.name.clone(), Index::EmptyAddressIndex) - } -} - -/// Index accessor for metrics with 1 indexes. -pub struct MetricPattern33 { - client: Arc, - name: Arc, - pub by: MetricPattern33By, -} - -impl MetricPattern33 { - pub fn new(client: Arc, name: String) -> Self { - let name: Arc = name.into(); - Self { - client: client.clone(), - name: name.clone(), - by: MetricPattern33By { - client, - name, - _marker: std::marker::PhantomData, - } - } - } - - /// Get the metric name. - pub fn name(&self) -> &str { - &self.name - } -} - -impl AnyMetricPattern for MetricPattern33 { - fn name(&self) -> &str { - &self.name - } - fn indexes(&self) -> &'static [Index] { &[ Index::EmptyAddressIndex, @@ -2334,7 +2248,7 @@ impl AnyMetricPattern for MetricPattern33 { } } -impl MetricPattern for MetricPattern33 { +impl MetricPattern for MetricPattern32 { fn get(&self, index: Index) -> Option> { match index { Index::EmptyAddressIndex => Some(self.by.by_emptyaddressindex()), @@ -2347,9 +2261,9 @@ impl MetricPattern for MetricPattern33 { /// Pattern struct for repeated tree structure. pub struct RealizedPattern3 { - pub adjusted_sopr: MetricPattern7, - pub adjusted_sopr_30d_ema: MetricPattern7, - pub adjusted_sopr_7d_ema: MetricPattern7, + pub adjusted_sopr: MetricPattern6, + pub adjusted_sopr_30d_ema: MetricPattern6, + pub adjusted_sopr_7d_ema: MetricPattern6, pub adjusted_value_created: MetricPattern1, pub adjusted_value_destroyed: MetricPattern1, pub mvrv: MetricPattern4, @@ -2368,14 +2282,14 @@ pub struct RealizedPattern3 { pub realized_price_extra: ActivePriceRatioPattern, pub realized_profit: BlockCountPattern, pub realized_profit_rel_to_realized_cap: BlockCountPattern, - pub realized_profit_to_loss_ratio: MetricPattern7, + pub realized_profit_to_loss_ratio: MetricPattern6, pub realized_value: MetricPattern1, - pub sell_side_risk_ratio: MetricPattern7, - pub sell_side_risk_ratio_30d_ema: MetricPattern7, - pub sell_side_risk_ratio_7d_ema: MetricPattern7, - pub sopr: MetricPattern7, - pub sopr_30d_ema: MetricPattern7, - pub sopr_7d_ema: MetricPattern7, + pub sell_side_risk_ratio: MetricPattern6, + pub sell_side_risk_ratio_30d_ema: MetricPattern6, + pub sell_side_risk_ratio_7d_ema: MetricPattern6, + pub sopr: MetricPattern6, + pub sopr_30d_ema: MetricPattern6, + pub sopr_7d_ema: MetricPattern6, pub total_realized_pnl: MetricPattern1, pub value_created: MetricPattern1, pub value_destroyed: MetricPattern1, @@ -2385,9 +2299,9 @@ impl RealizedPattern3 { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - adjusted_sopr: MetricPattern7::new(client.clone(), _m(&acc, "adjusted_sopr")), - adjusted_sopr_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "adjusted_sopr_30d_ema")), - adjusted_sopr_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "adjusted_sopr_7d_ema")), + adjusted_sopr: MetricPattern6::new(client.clone(), _m(&acc, "adjusted_sopr")), + adjusted_sopr_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "adjusted_sopr_30d_ema")), + adjusted_sopr_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "adjusted_sopr_7d_ema")), adjusted_value_created: MetricPattern1::new(client.clone(), _m(&acc, "adjusted_value_created")), adjusted_value_destroyed: MetricPattern1::new(client.clone(), _m(&acc, "adjusted_value_destroyed")), mvrv: MetricPattern4::new(client.clone(), _m(&acc, "mvrv")), @@ -2406,14 +2320,14 @@ impl RealizedPattern3 { realized_price_extra: ActivePriceRatioPattern::new(client.clone(), _m(&acc, "realized_price_ratio")), realized_profit: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit")), realized_profit_rel_to_realized_cap: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit_rel_to_realized_cap")), - realized_profit_to_loss_ratio: MetricPattern7::new(client.clone(), _m(&acc, "realized_profit_to_loss_ratio")), + realized_profit_to_loss_ratio: MetricPattern6::new(client.clone(), _m(&acc, "realized_profit_to_loss_ratio")), realized_value: MetricPattern1::new(client.clone(), _m(&acc, "realized_value")), - sell_side_risk_ratio: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), - sell_side_risk_ratio_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), - sell_side_risk_ratio_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), - sopr: MetricPattern7::new(client.clone(), _m(&acc, "sopr")), - sopr_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_30d_ema")), - sopr_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_7d_ema")), + sell_side_risk_ratio: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), + sell_side_risk_ratio_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), + sell_side_risk_ratio_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), + sopr: MetricPattern6::new(client.clone(), _m(&acc, "sopr")), + sopr_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_30d_ema")), + sopr_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_7d_ema")), total_realized_pnl: MetricPattern1::new(client.clone(), _m(&acc, "total_realized_pnl")), value_created: MetricPattern1::new(client.clone(), _m(&acc, "value_created")), value_destroyed: MetricPattern1::new(client.clone(), _m(&acc, "value_destroyed")), @@ -2423,9 +2337,9 @@ impl RealizedPattern3 { /// Pattern struct for repeated tree structure. pub struct RealizedPattern4 { - pub adjusted_sopr: MetricPattern7, - pub adjusted_sopr_30d_ema: MetricPattern7, - pub adjusted_sopr_7d_ema: MetricPattern7, + pub adjusted_sopr: MetricPattern6, + pub adjusted_sopr_30d_ema: MetricPattern6, + pub adjusted_sopr_7d_ema: MetricPattern6, pub adjusted_value_created: MetricPattern1, pub adjusted_value_destroyed: MetricPattern1, pub mvrv: MetricPattern4, @@ -2444,12 +2358,12 @@ pub struct RealizedPattern4 { pub realized_profit: BlockCountPattern, pub realized_profit_rel_to_realized_cap: BlockCountPattern, pub realized_value: MetricPattern1, - pub sell_side_risk_ratio: MetricPattern7, - pub sell_side_risk_ratio_30d_ema: MetricPattern7, - pub sell_side_risk_ratio_7d_ema: MetricPattern7, - pub sopr: MetricPattern7, - pub sopr_30d_ema: MetricPattern7, - pub sopr_7d_ema: MetricPattern7, + pub sell_side_risk_ratio: MetricPattern6, + pub sell_side_risk_ratio_30d_ema: MetricPattern6, + pub sell_side_risk_ratio_7d_ema: MetricPattern6, + pub sopr: MetricPattern6, + pub sopr_30d_ema: MetricPattern6, + pub sopr_7d_ema: MetricPattern6, pub total_realized_pnl: MetricPattern1, pub value_created: MetricPattern1, pub value_destroyed: MetricPattern1, @@ -2459,9 +2373,9 @@ impl RealizedPattern4 { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - adjusted_sopr: MetricPattern7::new(client.clone(), _m(&acc, "adjusted_sopr")), - adjusted_sopr_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "adjusted_sopr_30d_ema")), - adjusted_sopr_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "adjusted_sopr_7d_ema")), + adjusted_sopr: MetricPattern6::new(client.clone(), _m(&acc, "adjusted_sopr")), + adjusted_sopr_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "adjusted_sopr_30d_ema")), + adjusted_sopr_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "adjusted_sopr_7d_ema")), adjusted_value_created: MetricPattern1::new(client.clone(), _m(&acc, "adjusted_value_created")), adjusted_value_destroyed: MetricPattern1::new(client.clone(), _m(&acc, "adjusted_value_destroyed")), mvrv: MetricPattern4::new(client.clone(), _m(&acc, "mvrv")), @@ -2480,12 +2394,12 @@ impl RealizedPattern4 { realized_profit: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit")), realized_profit_rel_to_realized_cap: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit_rel_to_realized_cap")), realized_value: MetricPattern1::new(client.clone(), _m(&acc, "realized_value")), - sell_side_risk_ratio: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), - sell_side_risk_ratio_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), - sell_side_risk_ratio_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), - sopr: MetricPattern7::new(client.clone(), _m(&acc, "sopr")), - sopr_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_30d_ema")), - sopr_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_7d_ema")), + sell_side_risk_ratio: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), + sell_side_risk_ratio_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), + sell_side_risk_ratio_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), + sopr: MetricPattern6::new(client.clone(), _m(&acc, "sopr")), + sopr_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_30d_ema")), + sopr_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_7d_ema")), total_realized_pnl: MetricPattern1::new(client.clone(), _m(&acc, "total_realized_pnl")), value_created: MetricPattern1::new(client.clone(), _m(&acc, "value_created")), value_destroyed: MetricPattern1::new(client.clone(), _m(&acc, "value_destroyed")), @@ -2579,14 +2493,14 @@ pub struct RealizedPattern2 { pub realized_price_extra: ActivePriceRatioPattern, pub realized_profit: BlockCountPattern, pub realized_profit_rel_to_realized_cap: BlockCountPattern, - pub realized_profit_to_loss_ratio: MetricPattern7, + pub realized_profit_to_loss_ratio: MetricPattern6, pub realized_value: MetricPattern1, - pub sell_side_risk_ratio: MetricPattern7, - pub sell_side_risk_ratio_30d_ema: MetricPattern7, - pub sell_side_risk_ratio_7d_ema: MetricPattern7, - pub sopr: MetricPattern7, - pub sopr_30d_ema: MetricPattern7, - pub sopr_7d_ema: MetricPattern7, + pub sell_side_risk_ratio: MetricPattern6, + pub sell_side_risk_ratio_30d_ema: MetricPattern6, + pub sell_side_risk_ratio_7d_ema: MetricPattern6, + pub sopr: MetricPattern6, + pub sopr_30d_ema: MetricPattern6, + pub sopr_7d_ema: MetricPattern6, pub total_realized_pnl: MetricPattern1, pub value_created: MetricPattern1, pub value_destroyed: MetricPattern1, @@ -2612,14 +2526,14 @@ impl RealizedPattern2 { realized_price_extra: ActivePriceRatioPattern::new(client.clone(), _m(&acc, "realized_price_ratio")), realized_profit: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit")), realized_profit_rel_to_realized_cap: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit_rel_to_realized_cap")), - realized_profit_to_loss_ratio: MetricPattern7::new(client.clone(), _m(&acc, "realized_profit_to_loss_ratio")), + realized_profit_to_loss_ratio: MetricPattern6::new(client.clone(), _m(&acc, "realized_profit_to_loss_ratio")), realized_value: MetricPattern1::new(client.clone(), _m(&acc, "realized_value")), - sell_side_risk_ratio: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), - sell_side_risk_ratio_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), - sell_side_risk_ratio_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), - sopr: MetricPattern7::new(client.clone(), _m(&acc, "sopr")), - sopr_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_30d_ema")), - sopr_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_7d_ema")), + sell_side_risk_ratio: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), + sell_side_risk_ratio_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), + sell_side_risk_ratio_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), + sopr: MetricPattern6::new(client.clone(), _m(&acc, "sopr")), + sopr_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_30d_ema")), + sopr_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_7d_ema")), total_realized_pnl: MetricPattern1::new(client.clone(), _m(&acc, "total_realized_pnl")), value_created: MetricPattern1::new(client.clone(), _m(&acc, "value_created")), value_destroyed: MetricPattern1::new(client.clone(), _m(&acc, "value_destroyed")), @@ -2645,12 +2559,12 @@ pub struct RealizedPattern { pub realized_profit: BlockCountPattern, pub realized_profit_rel_to_realized_cap: BlockCountPattern, pub realized_value: MetricPattern1, - pub sell_side_risk_ratio: MetricPattern7, - pub sell_side_risk_ratio_30d_ema: MetricPattern7, - pub sell_side_risk_ratio_7d_ema: MetricPattern7, - pub sopr: MetricPattern7, - pub sopr_30d_ema: MetricPattern7, - pub sopr_7d_ema: MetricPattern7, + pub sell_side_risk_ratio: MetricPattern6, + pub sell_side_risk_ratio_30d_ema: MetricPattern6, + pub sell_side_risk_ratio_7d_ema: MetricPattern6, + pub sopr: MetricPattern6, + pub sopr_30d_ema: MetricPattern6, + pub sopr_7d_ema: MetricPattern6, pub total_realized_pnl: MetricPattern1, pub value_created: MetricPattern1, pub value_destroyed: MetricPattern1, @@ -2676,12 +2590,12 @@ impl RealizedPattern { realized_profit: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit")), realized_profit_rel_to_realized_cap: BlockCountPattern::new(client.clone(), _m(&acc, "realized_profit_rel_to_realized_cap")), realized_value: MetricPattern1::new(client.clone(), _m(&acc, "realized_value")), - sell_side_risk_ratio: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), - sell_side_risk_ratio_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), - sell_side_risk_ratio_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), - sopr: MetricPattern7::new(client.clone(), _m(&acc, "sopr")), - sopr_30d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_30d_ema")), - sopr_7d_ema: MetricPattern7::new(client.clone(), _m(&acc, "sopr_7d_ema")), + sell_side_risk_ratio: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio")), + sell_side_risk_ratio_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_30d_ema")), + sell_side_risk_ratio_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sell_side_risk_ratio_7d_ema")), + sopr: MetricPattern6::new(client.clone(), _m(&acc, "sopr")), + sopr_30d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_30d_ema")), + sopr_7d_ema: MetricPattern6::new(client.clone(), _m(&acc, "sopr_7d_ema")), total_realized_pnl: MetricPattern1::new(client.clone(), _m(&acc, "total_realized_pnl")), value_created: MetricPattern1::new(client.clone(), _m(&acc, "value_created")), value_destroyed: MetricPattern1::new(client.clone(), _m(&acc, "value_destroyed")), @@ -2742,7 +2656,7 @@ impl Price111dSmaPattern { } /// Pattern struct for repeated tree structure. -pub struct PercentilesPattern2 { +pub struct PercentilesPattern { pub cost_basis_pct05: MetricPattern4, pub cost_basis_pct10: MetricPattern4, pub cost_basis_pct15: MetricPattern4, @@ -2764,7 +2678,7 @@ pub struct PercentilesPattern2 { pub cost_basis_pct95: MetricPattern4, } -impl PercentilesPattern2 { +impl PercentilesPattern { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { @@ -3073,6 +2987,40 @@ impl ClassAveragePricePattern { } } +/// Pattern struct for repeated tree structure. +pub struct FullnessPattern { + pub average: MetricPattern2, + pub base: MetricPattern11, + pub cumulative: MetricPattern1, + pub max: MetricPattern2, + pub median: MetricPattern6, + pub min: MetricPattern2, + pub pct10: MetricPattern6, + pub pct25: MetricPattern6, + pub pct75: MetricPattern6, + pub pct90: MetricPattern6, + pub sum: MetricPattern2, +} + +impl FullnessPattern { + /// Create a new pattern node with accumulated metric name. + pub fn new(client: Arc, acc: String) -> Self { + Self { + average: MetricPattern2::new(client.clone(), _m(&acc, "average")), + base: MetricPattern11::new(client.clone(), acc.clone()), + cumulative: MetricPattern1::new(client.clone(), _m(&acc, "cumulative")), + max: MetricPattern2::new(client.clone(), _m(&acc, "max")), + median: MetricPattern6::new(client.clone(), _m(&acc, "median")), + min: MetricPattern2::new(client.clone(), _m(&acc, "min")), + pct10: MetricPattern6::new(client.clone(), _m(&acc, "pct10")), + pct25: MetricPattern6::new(client.clone(), _m(&acc, "pct25")), + pct75: MetricPattern6::new(client.clone(), _m(&acc, "pct75")), + pct90: MetricPattern6::new(client.clone(), _m(&acc, "pct90")), + sum: MetricPattern2::new(client.clone(), _m(&acc, "sum")), + } + } +} + /// Pattern struct for repeated tree structure. pub struct RelativePattern { pub neg_unrealized_loss_rel_to_market_cap: MetricPattern1, @@ -3137,6 +3085,38 @@ impl RelativePattern2 { } } +/// Pattern struct for repeated tree structure. +pub struct SizePattern { + pub average: MetricPattern1, + pub cumulative: MetricPattern1, + pub max: MetricPattern1, + pub median: MetricPattern11, + pub min: MetricPattern1, + pub pct10: MetricPattern11, + pub pct25: MetricPattern11, + pub pct75: MetricPattern11, + pub pct90: MetricPattern11, + pub sum: MetricPattern1, +} + +impl SizePattern { + /// Create a new pattern node with accumulated metric name. + pub fn new(client: Arc, acc: String) -> Self { + Self { + average: MetricPattern1::new(client.clone(), _m(&acc, "average")), + cumulative: MetricPattern1::new(client.clone(), _m(&acc, "cumulative")), + max: MetricPattern1::new(client.clone(), _m(&acc, "max")), + median: MetricPattern11::new(client.clone(), _m(&acc, "median")), + min: MetricPattern1::new(client.clone(), _m(&acc, "min")), + pct10: MetricPattern11::new(client.clone(), _m(&acc, "pct10")), + pct25: MetricPattern11::new(client.clone(), _m(&acc, "pct25")), + pct75: MetricPattern11::new(client.clone(), _m(&acc, "pct75")), + pct90: MetricPattern11::new(client.clone(), _m(&acc, "pct90")), + sum: MetricPattern1::new(client.clone(), _m(&acc, "sum")), + } + } +} + /// Pattern struct for repeated tree structure. pub struct AddrCountPattern { pub all: MetricPattern1, @@ -3167,47 +3147,17 @@ impl AddrCountPattern { } } -/// Pattern struct for repeated tree structure. -pub struct OhlcPattern { - pub dateindex: MetricPattern7, - pub decade: MetricPattern8, - pub difficultyepoch: MetricPattern9, - pub height: MetricPattern12, - pub month: MetricPattern14, - pub quarter: MetricPattern26, - pub semester: MetricPattern27, - pub week: MetricPattern30, - pub year: MetricPattern31, -} - -impl OhlcPattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - dateindex: MetricPattern7::new(client.clone(), acc.clone()), - decade: MetricPattern8::new(client.clone(), acc.clone()), - difficultyepoch: MetricPattern9::new(client.clone(), acc.clone()), - height: MetricPattern12::new(client.clone(), acc.clone()), - month: MetricPattern14::new(client.clone(), acc.clone()), - quarter: MetricPattern26::new(client.clone(), acc.clone()), - semester: MetricPattern27::new(client.clone(), acc.clone()), - week: MetricPattern30::new(client.clone(), acc.clone()), - year: MetricPattern31::new(client.clone(), acc.clone()), - } - } -} - /// Pattern struct for repeated tree structure. pub struct FeeRatePattern { pub average: MetricPattern1, pub max: MetricPattern1, - pub median: MetricPattern12, + pub median: MetricPattern11, pub min: MetricPattern1, - pub pct10: MetricPattern12, - pub pct25: MetricPattern12, - pub pct75: MetricPattern12, - pub pct90: MetricPattern12, - pub txindex: MetricPattern28, + pub pct10: MetricPattern11, + pub pct25: MetricPattern11, + pub pct75: MetricPattern11, + pub pct90: MetricPattern11, + pub txindex: MetricPattern27, } impl FeeRatePattern { @@ -3216,13 +3166,13 @@ impl FeeRatePattern { Self { average: MetricPattern1::new(client.clone(), _m(&acc, "average")), max: MetricPattern1::new(client.clone(), _m(&acc, "max")), - median: MetricPattern12::new(client.clone(), _m(&acc, "median")), + median: MetricPattern11::new(client.clone(), _m(&acc, "median")), min: MetricPattern1::new(client.clone(), _m(&acc, "min")), - pct10: MetricPattern12::new(client.clone(), _m(&acc, "pct10")), - pct25: MetricPattern12::new(client.clone(), _m(&acc, "pct25")), - pct75: MetricPattern12::new(client.clone(), _m(&acc, "pct75")), - pct90: MetricPattern12::new(client.clone(), _m(&acc, "pct90")), - txindex: MetricPattern28::new(client.clone(), acc.clone()), + pct10: MetricPattern11::new(client.clone(), _m(&acc, "pct10")), + pct25: MetricPattern11::new(client.clone(), _m(&acc, "pct25")), + pct75: MetricPattern11::new(client.clone(), _m(&acc, "pct75")), + pct90: MetricPattern11::new(client.clone(), _m(&acc, "pct90")), + txindex: MetricPattern27::new(client.clone(), acc.clone()), } } } @@ -3256,25 +3206,25 @@ impl _0satsPattern { } /// Pattern struct for repeated tree structure. -pub struct _10yPattern { +pub struct _0satsPattern2 { pub activity: ActivityPattern2, pub cost_basis: CostBasisPattern, pub outputs: OutputsPattern, - pub realized: RealizedPattern4, - pub relative: RelativePattern, + pub realized: RealizedPattern, + pub relative: RelativePattern4, pub supply: SupplyPattern2, pub unrealized: UnrealizedPattern, } -impl _10yPattern { +impl _0satsPattern2 { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { activity: ActivityPattern2::new(client.clone(), acc.clone()), cost_basis: CostBasisPattern::new(client.clone(), acc.clone()), outputs: OutputsPattern::new(client.clone(), acc.clone()), - realized: RealizedPattern4::new(client.clone(), acc.clone()), - relative: RelativePattern::new(client.clone(), acc.clone()), + realized: RealizedPattern::new(client.clone(), acc.clone()), + relative: RelativePattern4::new(client.clone(), _m(&acc, "supply_in")), supply: SupplyPattern2::new(client.clone(), _m(&acc, "supply")), unrealized: UnrealizedPattern::new(client.clone(), acc.clone()), } @@ -3308,25 +3258,25 @@ impl _10yTo12yPattern { } /// Pattern struct for repeated tree structure. -pub struct _0satsPattern2 { +pub struct _10yPattern { pub activity: ActivityPattern2, pub cost_basis: CostBasisPattern, pub outputs: OutputsPattern, - pub realized: RealizedPattern, - pub relative: RelativePattern4, + pub realized: RealizedPattern4, + pub relative: RelativePattern, pub supply: SupplyPattern2, pub unrealized: UnrealizedPattern, } -impl _0satsPattern2 { +impl _10yPattern { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { activity: ActivityPattern2::new(client.clone(), acc.clone()), cost_basis: CostBasisPattern::new(client.clone(), acc.clone()), outputs: OutputsPattern::new(client.clone(), acc.clone()), - realized: RealizedPattern::new(client.clone(), acc.clone()), - relative: RelativePattern4::new(client.clone(), _m(&acc, "supply_in")), + realized: RealizedPattern4::new(client.clone(), acc.clone()), + relative: RelativePattern::new(client.clone(), acc.clone()), supply: SupplyPattern2::new(client.clone(), _m(&acc, "supply")), unrealized: UnrealizedPattern::new(client.clone(), acc.clone()), } @@ -3411,62 +3361,12 @@ impl PeriodCagrPattern { } } -/// Pattern struct for repeated tree structure. -pub struct BitcoinPattern { - pub average: MetricPattern2, - pub cumulative: MetricPattern1, - pub height: MetricPattern12, - pub max: MetricPattern2, - pub min: MetricPattern2, - pub percentiles: PercentilesPattern, - pub sum: MetricPattern2, -} - -impl BitcoinPattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - average: MetricPattern2::new(client.clone(), _m(&acc, "average")), - cumulative: MetricPattern1::new(client.clone(), _m(&acc, "cumulative")), - height: MetricPattern12::new(client.clone(), acc.clone()), - max: MetricPattern2::new(client.clone(), _m(&acc, "max")), - min: MetricPattern2::new(client.clone(), _m(&acc, "min")), - percentiles: PercentilesPattern::new(client.clone(), acc.clone()), - sum: MetricPattern2::new(client.clone(), _m(&acc, "sum")), - } - } -} - -/// Pattern struct for repeated tree structure. -pub struct SizePattern { - pub average: MetricPattern1, - pub cumulative: MetricPattern1, - pub max: MetricPattern1, - pub min: MetricPattern1, - pub percentiles: PercentilesPattern, - pub sum: MetricPattern1, -} - -impl SizePattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - average: MetricPattern1::new(client.clone(), _m(&acc, "average")), - cumulative: MetricPattern1::new(client.clone(), _m(&acc, "cumulative")), - max: MetricPattern1::new(client.clone(), _m(&acc, "max")), - min: MetricPattern1::new(client.clone(), _m(&acc, "min")), - percentiles: PercentilesPattern::new(client.clone(), acc.clone()), - sum: MetricPattern1::new(client.clone(), _m(&acc, "sum")), - } - } -} - /// Pattern struct for repeated tree structure. pub struct ActivityPattern2 { pub coinblocks_destroyed: BlockCountPattern, pub coindays_destroyed: BlockCountPattern, - pub satblocks_destroyed: MetricPattern12, - pub satdays_destroyed: MetricPattern12, + pub satblocks_destroyed: MetricPattern11, + pub satdays_destroyed: MetricPattern11, pub sent: UnclaimedRewardsPattern, } @@ -3476,127 +3376,101 @@ impl ActivityPattern2 { Self { coinblocks_destroyed: BlockCountPattern::new(client.clone(), _m(&acc, "coinblocks_destroyed")), coindays_destroyed: BlockCountPattern::new(client.clone(), _m(&acc, "coindays_destroyed")), - satblocks_destroyed: MetricPattern12::new(client.clone(), _m(&acc, "satblocks_destroyed")), - satdays_destroyed: MetricPattern12::new(client.clone(), _m(&acc, "satdays_destroyed")), + satblocks_destroyed: MetricPattern11::new(client.clone(), _m(&acc, "satblocks_destroyed")), + satdays_destroyed: MetricPattern11::new(client.clone(), _m(&acc, "satdays_destroyed")), sent: UnclaimedRewardsPattern::new(client.clone(), _m(&acc, "sent")), } } } /// Pattern struct for repeated tree structure. -pub struct PercentilesPattern { - pub median: MetricPattern7, - pub pct10: MetricPattern7, - pub pct25: MetricPattern7, - pub pct75: MetricPattern7, - pub pct90: MetricPattern7, +pub struct SplitPattern { + pub close: MetricPattern5, + pub high: MetricPattern5, + pub low: MetricPattern5, + pub open: MetricPattern5, } -impl PercentilesPattern { +impl SplitPattern { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - median: MetricPattern7::new(client.clone(), _m(&acc, "median")), - pct10: MetricPattern7::new(client.clone(), _m(&acc, "pct10")), - pct25: MetricPattern7::new(client.clone(), _m(&acc, "pct25")), - pct75: MetricPattern7::new(client.clone(), _m(&acc, "pct75")), - pct90: MetricPattern7::new(client.clone(), _m(&acc, "pct90")), - } - } -} - -/// Pattern struct for repeated tree structure. -pub struct DateindexPattern2 { - pub close: MetricPattern7, - pub high: MetricPattern7, - pub low: MetricPattern7, - pub open: MetricPattern7, -} - -impl DateindexPattern2 { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - close: MetricPattern7::new(client.clone(), _m(&acc, "close_cents")), - high: MetricPattern7::new(client.clone(), _m(&acc, "high_cents")), - low: MetricPattern7::new(client.clone(), _m(&acc, "low_cents")), - open: MetricPattern7::new(client.clone(), _m(&acc, "open_cents")), - } - } -} - -/// Pattern struct for repeated tree structure. -pub struct HighPattern { - pub dateindex: MetricPattern7, - pub difficultyepoch: MetricPattern9, - pub height: MetricPattern12, - pub rest: MetricPattern5, -} - -impl HighPattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - dateindex: MetricPattern7::new(client.clone(), acc.clone()), - difficultyepoch: MetricPattern9::new(client.clone(), _m(&acc, "max")), - height: MetricPattern12::new(client.clone(), acc.clone()), - rest: MetricPattern5::new(client.clone(), _m(&acc, "max")), - } - } -} - -/// Pattern struct for repeated tree structure. -pub struct SplitPattern2 { - pub close: MetricPattern1, - pub high: HighPattern, - pub low: HighPattern, - pub open: MetricPattern1, -} - -impl SplitPattern2 { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - close: MetricPattern1::new(client.clone(), _m(&acc, "close")), - high: HighPattern::new(client.clone(), _m(&acc, "high")), - low: HighPattern::new(client.clone(), _m(&acc, "low")), - open: MetricPattern1::new(client.clone(), _m(&acc, "open")), - } - } -} - -/// Pattern struct for repeated tree structure. -pub struct _24hCoinbaseSumPattern { - pub bitcoin: MetricPattern12, - pub dollars: MetricPattern12, - pub sats: MetricPattern12, -} - -impl _24hCoinbaseSumPattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - bitcoin: MetricPattern12::new(client.clone(), _m(&acc, "btc")), - dollars: MetricPattern12::new(client.clone(), _m(&acc, "usd")), - sats: MetricPattern12::new(client.clone(), acc.clone()), + close: MetricPattern5::new(client.clone(), _m(&acc, "close_cents")), + high: MetricPattern5::new(client.clone(), _m(&acc, "high_cents")), + low: MetricPattern5::new(client.clone(), _m(&acc, "low_cents")), + open: MetricPattern5::new(client.clone(), _m(&acc, "open_cents")), } } } /// Pattern struct for repeated tree structure. pub struct CoinbasePattern { - pub bitcoin: BitcoinPattern, - pub dollars: BitcoinPattern, - pub sats: BitcoinPattern, + pub bitcoin: FullnessPattern, + pub dollars: FullnessPattern, + pub sats: FullnessPattern, } impl CoinbasePattern { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - bitcoin: BitcoinPattern::new(client.clone(), _m(&acc, "btc")), - dollars: BitcoinPattern::new(client.clone(), _m(&acc, "usd")), - sats: BitcoinPattern::new(client.clone(), acc.clone()), + bitcoin: FullnessPattern::new(client.clone(), _m(&acc, "btc")), + dollars: FullnessPattern::new(client.clone(), _m(&acc, "usd")), + sats: FullnessPattern::new(client.clone(), acc.clone()), + } + } +} + +/// Pattern struct for repeated tree structure. +pub struct SegwitAdoptionPattern { + pub base: MetricPattern11, + pub cumulative: MetricPattern2, + pub sum: MetricPattern2, +} + +impl SegwitAdoptionPattern { + /// Create a new pattern node with accumulated metric name. + pub fn new(client: Arc, acc: String) -> Self { + Self { + base: MetricPattern11::new(client.clone(), acc.clone()), + cumulative: MetricPattern2::new(client.clone(), _m(&acc, "cumulative")), + sum: MetricPattern2::new(client.clone(), _m(&acc, "sum")), + } + } +} + +/// Pattern struct for repeated tree structure. +pub struct _24hCoinbaseSumPattern { + pub bitcoin: MetricPattern11, + pub dollars: MetricPattern11, + pub sats: MetricPattern11, +} + +impl _24hCoinbaseSumPattern { + /// Create a new pattern node with accumulated metric name. + pub fn new(client: Arc, acc: String) -> Self { + Self { + bitcoin: MetricPattern11::new(client.clone(), _m(&acc, "btc")), + dollars: MetricPattern11::new(client.clone(), _m(&acc, "usd")), + sats: MetricPattern11::new(client.clone(), acc.clone()), + } + } +} + +/// Pattern struct for repeated tree structure. +pub struct CostBasisPattern2 { + pub max: MetricPattern1, + pub min: MetricPattern1, + pub percentiles: PercentilesPattern, +} + +impl CostBasisPattern2 { + /// Create a new pattern node with accumulated metric name. + pub fn new(client: Arc, acc: String) -> Self { + Self { + max: MetricPattern1::new(client.clone(), _m(&acc, "max_cost_basis")), + min: MetricPattern1::new(client.clone(), _m(&acc, "min_cost_basis")), + percentiles: PercentilesPattern::new(client.clone(), _m(&acc, "cost_basis")), } } } @@ -3620,53 +3494,17 @@ impl UnclaimedRewardsPattern { } /// Pattern struct for repeated tree structure. -pub struct CostBasisPattern2 { - pub max: MetricPattern1, - pub min: MetricPattern1, - pub percentiles: PercentilesPattern2, +pub struct RelativePattern4 { + pub supply_in_loss_rel_to_own_supply: MetricPattern1, + pub supply_in_profit_rel_to_own_supply: MetricPattern1, } -impl CostBasisPattern2 { +impl RelativePattern4 { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - max: MetricPattern1::new(client.clone(), _m(&acc, "max_cost_basis")), - min: MetricPattern1::new(client.clone(), _m(&acc, "min_cost_basis")), - percentiles: PercentilesPattern2::new(client.clone(), _m(&acc, "cost_basis")), - } - } -} - -/// Pattern struct for repeated tree structure. -pub struct SegwitAdoptionPattern { - pub cumulative: MetricPattern2, - pub height: MetricPattern12, - pub sum: MetricPattern2, -} - -impl SegwitAdoptionPattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - cumulative: MetricPattern2::new(client.clone(), _m(&acc, "cumulative")), - height: MetricPattern12::new(client.clone(), acc.clone()), - sum: MetricPattern2::new(client.clone(), _m(&acc, "sum")), - } - } -} - -/// Pattern struct for repeated tree structure. -pub struct SatsPattern { - pub ohlc: OhlcPattern, - pub split: SplitPattern2, -} - -impl SatsPattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - ohlc: OhlcPattern::new(client.clone(), _m(&acc, "ohlc_sats")), - split: SplitPattern2::new(client.clone(), _m(&acc, "sats")), + supply_in_loss_rel_to_own_supply: MetricPattern1::new(client.clone(), _m(&acc, "loss_rel_to_own_supply")), + supply_in_profit_rel_to_own_supply: MetricPattern1::new(client.clone(), _m(&acc, "profit_rel_to_own_supply")), } } } @@ -3687,22 +3525,6 @@ impl CostBasisPattern { } } -/// Pattern struct for repeated tree structure. -pub struct _1dReturns1mSdPattern { - pub sd: MetricPattern4, - pub sma: MetricPattern4, -} - -impl _1dReturns1mSdPattern { - /// Create a new pattern node with accumulated metric name. - pub fn new(client: Arc, acc: String) -> Self { - Self { - sd: MetricPattern4::new(client.clone(), _m(&acc, "sd")), - sma: MetricPattern4::new(client.clone(), _m(&acc, "sma")), - } - } -} - /// Pattern struct for repeated tree structure. pub struct SupplyPattern2 { pub halved: _24hCoinbaseSumPattern, @@ -3720,24 +3542,40 @@ impl SupplyPattern2 { } /// Pattern struct for repeated tree structure. -pub struct RelativePattern4 { - pub supply_in_loss_rel_to_own_supply: MetricPattern1, - pub supply_in_profit_rel_to_own_supply: MetricPattern1, +pub struct _1dReturns1mSdPattern { + pub sd: MetricPattern4, + pub sma: MetricPattern4, } -impl RelativePattern4 { +impl _1dReturns1mSdPattern { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - supply_in_loss_rel_to_own_supply: MetricPattern1::new(client.clone(), _m(&acc, "loss_rel_to_own_supply")), - supply_in_profit_rel_to_own_supply: MetricPattern1::new(client.clone(), _m(&acc, "profit_rel_to_own_supply")), + sd: MetricPattern4::new(client.clone(), _m(&acc, "sd")), + sma: MetricPattern4::new(client.clone(), _m(&acc, "sma")), + } + } +} + +/// Pattern struct for repeated tree structure. +pub struct CentsPattern { + pub ohlc: MetricPattern5, + pub split: SplitPattern, +} + +impl CentsPattern { + /// Create a new pattern node with accumulated metric name. + pub fn new(client: Arc, acc: String) -> Self { + Self { + ohlc: MetricPattern5::new(client.clone(), _m(&acc, "ohlc_sats")), + split: SplitPattern::new(client.clone(), _m(&acc, "sats")), } } } /// Pattern struct for repeated tree structure. pub struct BlockCountPattern { - pub cumulative: MetricPattern2, + pub cumulative: MetricPattern1, pub sum: MetricPattern1, } @@ -3745,7 +3583,7 @@ impl BlockCountPattern { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - cumulative: MetricPattern2::new(client.clone(), _m(&acc, "cumulative")), + cumulative: MetricPattern1::new(client.clone(), _m(&acc, "cumulative")), sum: MetricPattern1::new(client.clone(), acc.clone()), } } @@ -3781,14 +3619,14 @@ impl OutputsPattern { /// Pattern struct for repeated tree structure. pub struct EmptyPattern { - pub identity: MetricPattern25, + pub identity: MetricPattern23, } impl EmptyPattern { /// Create a new pattern node with accumulated metric name. pub fn new(client: Arc, acc: String) -> Self { Self { - identity: MetricPattern25::new(client.clone(), acc.clone()), + identity: MetricPattern23::new(client.clone(), acc.clone()), } } } @@ -3838,78 +3676,80 @@ impl CatalogTree { /// Catalog tree node. pub struct CatalogTree_Addresses { - pub first_p2aaddressindex: MetricPattern12, - pub first_p2pk33addressindex: MetricPattern12, - pub first_p2pk65addressindex: MetricPattern12, - pub first_p2pkhaddressindex: MetricPattern12, - pub first_p2shaddressindex: MetricPattern12, - pub first_p2traddressindex: MetricPattern12, - pub first_p2wpkhaddressindex: MetricPattern12, - pub first_p2wshaddressindex: MetricPattern12, - pub p2abytes: MetricPattern17, - pub p2pk33bytes: MetricPattern19, - pub p2pk65bytes: MetricPattern20, - pub p2pkhbytes: MetricPattern21, - pub p2shbytes: MetricPattern22, - pub p2trbytes: MetricPattern23, - pub p2wpkhbytes: MetricPattern24, - pub p2wshbytes: MetricPattern25, + pub first_p2aaddressindex: MetricPattern11, + pub first_p2pk33addressindex: MetricPattern11, + pub first_p2pk65addressindex: MetricPattern11, + pub first_p2pkhaddressindex: MetricPattern11, + pub first_p2shaddressindex: MetricPattern11, + pub first_p2traddressindex: MetricPattern11, + pub first_p2wpkhaddressindex: MetricPattern11, + pub first_p2wshaddressindex: MetricPattern11, + pub p2abytes: MetricPattern16, + pub p2pk33bytes: MetricPattern18, + pub p2pk65bytes: MetricPattern19, + pub p2pkhbytes: MetricPattern20, + pub p2shbytes: MetricPattern21, + pub p2trbytes: MetricPattern22, + pub p2wpkhbytes: MetricPattern23, + pub p2wshbytes: MetricPattern24, } impl CatalogTree_Addresses { pub fn new(client: Arc, base_path: String) -> Self { Self { - first_p2aaddressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2aaddressindex")), - first_p2pk33addressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2pk33addressindex")), - first_p2pk65addressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2pk65addressindex")), - first_p2pkhaddressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2pkhaddressindex")), - first_p2shaddressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2shaddressindex")), - first_p2traddressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2traddressindex")), - first_p2wpkhaddressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2wpkhaddressindex")), - first_p2wshaddressindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2wshaddressindex")), - p2abytes: MetricPattern17::new(client.clone(), format!("{base_path}_p2abytes")), - p2pk33bytes: MetricPattern19::new(client.clone(), format!("{base_path}_p2pk33bytes")), - p2pk65bytes: MetricPattern20::new(client.clone(), format!("{base_path}_p2pk65bytes")), - p2pkhbytes: MetricPattern21::new(client.clone(), format!("{base_path}_p2pkhbytes")), - p2shbytes: MetricPattern22::new(client.clone(), format!("{base_path}_p2shbytes")), - p2trbytes: MetricPattern23::new(client.clone(), format!("{base_path}_p2trbytes")), - p2wpkhbytes: MetricPattern24::new(client.clone(), format!("{base_path}_p2wpkhbytes")), - p2wshbytes: MetricPattern25::new(client.clone(), format!("{base_path}_p2wshbytes")), + first_p2aaddressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2aaddressindex")), + first_p2pk33addressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2pk33addressindex")), + first_p2pk65addressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2pk65addressindex")), + first_p2pkhaddressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2pkhaddressindex")), + first_p2shaddressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2shaddressindex")), + first_p2traddressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2traddressindex")), + first_p2wpkhaddressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2wpkhaddressindex")), + first_p2wshaddressindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2wshaddressindex")), + p2abytes: MetricPattern16::new(client.clone(), format!("{base_path}_p2abytes")), + p2pk33bytes: MetricPattern18::new(client.clone(), format!("{base_path}_p2pk33bytes")), + p2pk65bytes: MetricPattern19::new(client.clone(), format!("{base_path}_p2pk65bytes")), + p2pkhbytes: MetricPattern20::new(client.clone(), format!("{base_path}_p2pkhbytes")), + p2shbytes: MetricPattern21::new(client.clone(), format!("{base_path}_p2shbytes")), + p2trbytes: MetricPattern22::new(client.clone(), format!("{base_path}_p2trbytes")), + p2wpkhbytes: MetricPattern23::new(client.clone(), format!("{base_path}_p2wpkhbytes")), + p2wshbytes: MetricPattern24::new(client.clone(), format!("{base_path}_p2wshbytes")), } } } /// Catalog tree node. pub struct CatalogTree_Blocks { - pub blockhash: MetricPattern12, + pub blockhash: MetricPattern11, pub count: CatalogTree_Blocks_Count, pub difficulty: CatalogTree_Blocks_Difficulty, + pub fullness: FullnessPattern, pub halving: CatalogTree_Blocks_Halving, pub interval: CatalogTree_Blocks_Interval, pub mining: CatalogTree_Blocks_Mining, pub rewards: CatalogTree_Blocks_Rewards, - pub size: CatalogTree_Blocks_Size, + pub size: SizePattern, pub time: CatalogTree_Blocks_Time, - pub timestamp: MetricPattern12, - pub total_size: MetricPattern12, - pub weight: CatalogTree_Blocks_Weight, + pub total_size: MetricPattern11, + pub vbytes: FullnessPattern, + pub weight: FullnessPattern, } impl CatalogTree_Blocks { pub fn new(client: Arc, base_path: String) -> Self { Self { - blockhash: MetricPattern12::new(client.clone(), format!("{base_path}_blockhash")), + blockhash: MetricPattern11::new(client.clone(), format!("{base_path}_blockhash")), count: CatalogTree_Blocks_Count::new(client.clone(), format!("{base_path}_count")), difficulty: CatalogTree_Blocks_Difficulty::new(client.clone(), format!("{base_path}_difficulty")), + fullness: FullnessPattern::new(client.clone(), "block_fullness".to_string()), halving: CatalogTree_Blocks_Halving::new(client.clone(), format!("{base_path}_halving")), interval: CatalogTree_Blocks_Interval::new(client.clone(), format!("{base_path}_interval")), mining: CatalogTree_Blocks_Mining::new(client.clone(), format!("{base_path}_mining")), rewards: CatalogTree_Blocks_Rewards::new(client.clone(), format!("{base_path}_rewards")), - size: CatalogTree_Blocks_Size::new(client.clone(), format!("{base_path}_size")), + size: SizePattern::new(client.clone(), "block_size".to_string()), time: CatalogTree_Blocks_Time::new(client.clone(), format!("{base_path}_time")), - timestamp: MetricPattern12::new(client.clone(), format!("{base_path}_timestamp")), - total_size: MetricPattern12::new(client.clone(), format!("{base_path}_total_size")), - weight: CatalogTree_Blocks_Weight::new(client.clone(), format!("{base_path}_weight")), + total_size: MetricPattern11::new(client.clone(), format!("{base_path}_total_size")), + vbytes: FullnessPattern::new(client.clone(), "block_vbytes".to_string()), + weight: FullnessPattern::new(client.clone(), "".to_string()), } } } @@ -3917,13 +3757,13 @@ impl CatalogTree_Blocks { /// Catalog tree node. pub struct CatalogTree_Blocks_Count { pub _1m_block_count: MetricPattern1, - pub _1m_start: MetricPattern12, + pub _1m_start: MetricPattern11, pub _1w_block_count: MetricPattern1, - pub _1w_start: MetricPattern12, + pub _1w_start: MetricPattern11, pub _1y_block_count: MetricPattern1, - pub _1y_start: MetricPattern12, + pub _1y_start: MetricPattern11, pub _24h_block_count: MetricPattern1, - pub _24h_start: MetricPattern12, + pub _24h_start: MetricPattern11, pub block_count: BlockCountPattern, pub block_count_target: MetricPattern4, } @@ -3932,13 +3772,13 @@ impl CatalogTree_Blocks_Count { pub fn new(client: Arc, base_path: String) -> Self { Self { _1m_block_count: MetricPattern1::new(client.clone(), format!("{base_path}_1m_block_count")), - _1m_start: MetricPattern12::new(client.clone(), format!("{base_path}_1m_start")), + _1m_start: MetricPattern11::new(client.clone(), format!("{base_path}_1m_start")), _1w_block_count: MetricPattern1::new(client.clone(), format!("{base_path}_1w_block_count")), - _1w_start: MetricPattern12::new(client.clone(), format!("{base_path}_1w_start")), + _1w_start: MetricPattern11::new(client.clone(), format!("{base_path}_1w_start")), _1y_block_count: MetricPattern1::new(client.clone(), format!("{base_path}_1y_block_count")), - _1y_start: MetricPattern12::new(client.clone(), format!("{base_path}_1y_start")), + _1y_start: MetricPattern11::new(client.clone(), format!("{base_path}_1y_start")), _24h_block_count: MetricPattern1::new(client.clone(), format!("{base_path}_24h_block_count")), - _24h_start: MetricPattern12::new(client.clone(), format!("{base_path}_24h_start")), + _24h_start: MetricPattern11::new(client.clone(), format!("{base_path}_24h_start")), block_count: BlockCountPattern::new(client.clone(), "block_count".to_string()), block_count_target: MetricPattern4::new(client.clone(), format!("{base_path}_block_count_target")), } @@ -3947,19 +3787,23 @@ impl CatalogTree_Blocks_Count { /// Catalog tree node. pub struct CatalogTree_Blocks_Difficulty { - pub base: MetricPattern12, - pub blocks_before_next_difficulty_adjustment: MetricPattern1, - pub days_before_next_difficulty_adjustment: MetricPattern1, + pub adjustment: MetricPattern1, + pub as_hash: MetricPattern1, + pub blocks_before_next_adjustment: MetricPattern1, + pub days_before_next_adjustment: MetricPattern1, pub epoch: MetricPattern4, + pub raw: MetricPattern1, } impl CatalogTree_Blocks_Difficulty { pub fn new(client: Arc, base_path: String) -> Self { Self { - base: MetricPattern12::new(client.clone(), format!("{base_path}_base")), - blocks_before_next_difficulty_adjustment: MetricPattern1::new(client.clone(), format!("{base_path}_blocks_before_next_difficulty_adjustment")), - days_before_next_difficulty_adjustment: MetricPattern1::new(client.clone(), format!("{base_path}_days_before_next_difficulty_adjustment")), + adjustment: MetricPattern1::new(client.clone(), format!("{base_path}_adjustment")), + as_hash: MetricPattern1::new(client.clone(), format!("{base_path}_as_hash")), + blocks_before_next_adjustment: MetricPattern1::new(client.clone(), format!("{base_path}_blocks_before_next_adjustment")), + days_before_next_adjustment: MetricPattern1::new(client.clone(), format!("{base_path}_days_before_next_adjustment")), epoch: MetricPattern4::new(client.clone(), format!("{base_path}_epoch")), + raw: MetricPattern1::new(client.clone(), format!("{base_path}_raw")), } } } @@ -3984,37 +3828,34 @@ impl CatalogTree_Blocks_Halving { /// Catalog tree node. pub struct CatalogTree_Blocks_Interval { pub average: MetricPattern2, - pub base: MetricPattern12, + pub base: MetricPattern11, pub max: MetricPattern2, - pub median: MetricPattern7, + pub median: MetricPattern6, pub min: MetricPattern2, - pub pct10: MetricPattern7, - pub pct25: MetricPattern7, - pub pct75: MetricPattern7, - pub pct90: MetricPattern7, + pub pct10: MetricPattern6, + pub pct25: MetricPattern6, + pub pct75: MetricPattern6, + pub pct90: MetricPattern6, } impl CatalogTree_Blocks_Interval { pub fn new(client: Arc, base_path: String) -> Self { Self { average: MetricPattern2::new(client.clone(), format!("{base_path}_average")), - base: MetricPattern12::new(client.clone(), format!("{base_path}_base")), + base: MetricPattern11::new(client.clone(), format!("{base_path}_base")), max: MetricPattern2::new(client.clone(), format!("{base_path}_max")), - median: MetricPattern7::new(client.clone(), format!("{base_path}_median")), + median: MetricPattern6::new(client.clone(), format!("{base_path}_median")), min: MetricPattern2::new(client.clone(), format!("{base_path}_min")), - pct10: MetricPattern7::new(client.clone(), format!("{base_path}_pct10")), - pct25: MetricPattern7::new(client.clone(), format!("{base_path}_pct25")), - pct75: MetricPattern7::new(client.clone(), format!("{base_path}_pct75")), - pct90: MetricPattern7::new(client.clone(), format!("{base_path}_pct90")), + pct10: MetricPattern6::new(client.clone(), format!("{base_path}_pct10")), + pct25: MetricPattern6::new(client.clone(), format!("{base_path}_pct25")), + pct75: MetricPattern6::new(client.clone(), format!("{base_path}_pct75")), + pct90: MetricPattern6::new(client.clone(), format!("{base_path}_pct90")), } } } /// Catalog tree node. pub struct CatalogTree_Blocks_Mining { - pub difficulty: MetricPattern2, - pub difficulty_adjustment: MetricPattern1, - pub difficulty_as_hash: MetricPattern1, pub hash_price_phs: MetricPattern1, pub hash_price_phs_min: MetricPattern1, pub hash_price_rebound: MetricPattern1, @@ -4035,9 +3876,6 @@ pub struct CatalogTree_Blocks_Mining { impl CatalogTree_Blocks_Mining { pub fn new(client: Arc, base_path: String) -> Self { Self { - difficulty: MetricPattern2::new(client.clone(), format!("{base_path}_difficulty")), - difficulty_adjustment: MetricPattern1::new(client.clone(), format!("{base_path}_difficulty_adjustment")), - difficulty_as_hash: MetricPattern1::new(client.clone(), format!("{base_path}_difficulty_as_hash")), hash_price_phs: MetricPattern1::new(client.clone(), format!("{base_path}_hash_price_phs")), hash_price_phs_min: MetricPattern1::new(client.clone(), format!("{base_path}_hash_price_phs_min")), hash_price_rebound: MetricPattern1::new(client.clone(), format!("{base_path}_hash_price_rebound")), @@ -4061,9 +3899,9 @@ impl CatalogTree_Blocks_Mining { pub struct CatalogTree_Blocks_Rewards { pub _24h_coinbase_sum: _24hCoinbaseSumPattern, pub coinbase: CoinbasePattern, - pub fee_dominance: MetricPattern7, + pub fee_dominance: MetricPattern6, pub subsidy: CoinbasePattern, - pub subsidy_dominance: MetricPattern7, + pub subsidy_dominance: MetricPattern6, pub subsidy_usd_1y_sma: MetricPattern4, pub unclaimed_rewards: UnclaimedRewardsPattern, } @@ -4073,87 +3911,30 @@ impl CatalogTree_Blocks_Rewards { Self { _24h_coinbase_sum: _24hCoinbaseSumPattern::new(client.clone(), "24h_coinbase_sum".to_string()), coinbase: CoinbasePattern::new(client.clone(), "coinbase".to_string()), - fee_dominance: MetricPattern7::new(client.clone(), format!("{base_path}_fee_dominance")), + fee_dominance: MetricPattern6::new(client.clone(), format!("{base_path}_fee_dominance")), subsidy: CoinbasePattern::new(client.clone(), "subsidy".to_string()), - subsidy_dominance: MetricPattern7::new(client.clone(), format!("{base_path}_subsidy_dominance")), + subsidy_dominance: MetricPattern6::new(client.clone(), format!("{base_path}_subsidy_dominance")), subsidy_usd_1y_sma: MetricPattern4::new(client.clone(), format!("{base_path}_subsidy_usd_1y_sma")), unclaimed_rewards: UnclaimedRewardsPattern::new(client.clone(), "unclaimed_rewards".to_string()), } } } -/// Catalog tree node. -pub struct CatalogTree_Blocks_Size { - pub size: SizePattern, - pub vbytes: CatalogTree_Blocks_Size_Vbytes, -} - -impl CatalogTree_Blocks_Size { - pub fn new(client: Arc, base_path: String) -> Self { - Self { - size: SizePattern::new(client.clone(), "block_size".to_string()), - vbytes: CatalogTree_Blocks_Size_Vbytes::new(client.clone(), format!("{base_path}_vbytes")), - } - } -} - -/// Catalog tree node. -pub struct CatalogTree_Blocks_Size_Vbytes { - pub average: MetricPattern2, - pub base: MetricPattern12, - pub cumulative: MetricPattern1, - pub max: MetricPattern2, - pub min: MetricPattern2, - pub percentiles: PercentilesPattern, - pub sum: MetricPattern2, -} - -impl CatalogTree_Blocks_Size_Vbytes { - pub fn new(client: Arc, base_path: String) -> Self { - Self { - average: MetricPattern2::new(client.clone(), format!("{base_path}_average")), - base: MetricPattern12::new(client.clone(), format!("{base_path}_base")), - cumulative: MetricPattern1::new(client.clone(), format!("{base_path}_cumulative")), - max: MetricPattern2::new(client.clone(), format!("{base_path}_max")), - min: MetricPattern2::new(client.clone(), format!("{base_path}_min")), - percentiles: PercentilesPattern::new(client.clone(), "block_vbytes".to_string()), - sum: MetricPattern2::new(client.clone(), format!("{base_path}_sum")), - } - } -} - /// Catalog tree node. pub struct CatalogTree_Blocks_Time { - pub date: MetricPattern12, - pub date_fixed: MetricPattern12, - pub timestamp: MetricPattern2, - pub timestamp_fixed: MetricPattern12, + pub date: MetricPattern11, + pub date_fixed: MetricPattern11, + pub timestamp: MetricPattern1, + pub timestamp_fixed: MetricPattern11, } impl CatalogTree_Blocks_Time { pub fn new(client: Arc, base_path: String) -> Self { Self { - date: MetricPattern12::new(client.clone(), format!("{base_path}_date")), - date_fixed: MetricPattern12::new(client.clone(), format!("{base_path}_date_fixed")), - timestamp: MetricPattern2::new(client.clone(), format!("{base_path}_timestamp")), - timestamp_fixed: MetricPattern12::new(client.clone(), format!("{base_path}_timestamp_fixed")), - } - } -} - -/// Catalog tree node. -pub struct CatalogTree_Blocks_Weight { - pub base: MetricPattern12, - pub fullness: BitcoinPattern, - pub weight: SizePattern, -} - -impl CatalogTree_Blocks_Weight { - pub fn new(client: Arc, base_path: String) -> Self { - Self { - base: MetricPattern12::new(client.clone(), format!("{base_path}_base")), - fullness: BitcoinPattern::new(client.clone(), "block_fullness".to_string()), - weight: SizePattern::new(client.clone(), "block_weight".to_string()), + date: MetricPattern11::new(client.clone(), format!("{base_path}_date")), + date_fixed: MetricPattern11::new(client.clone(), format!("{base_path}_date_fixed")), + timestamp: MetricPattern1::new(client.clone(), format!("{base_path}_timestamp")), + timestamp_fixed: MetricPattern11::new(client.clone(), format!("{base_path}_timestamp_fixed")), } } } @@ -4301,47 +4082,47 @@ impl CatalogTree_Cointime_Value { /// Catalog tree node. pub struct CatalogTree_Constants { - pub constant_0: MetricPattern3, - pub constant_1: MetricPattern3, - pub constant_100: MetricPattern3, - pub constant_2: MetricPattern3, - pub constant_20: MetricPattern3, - pub constant_3: MetricPattern3, - pub constant_30: MetricPattern3, - pub constant_38_2: MetricPattern3, - pub constant_4: MetricPattern3, - pub constant_50: MetricPattern3, - pub constant_600: MetricPattern3, - pub constant_61_8: MetricPattern3, - pub constant_70: MetricPattern3, - pub constant_80: MetricPattern3, - pub constant_minus_1: MetricPattern3, - pub constant_minus_2: MetricPattern3, - pub constant_minus_3: MetricPattern3, - pub constant_minus_4: MetricPattern3, + pub constant_0: MetricPattern1, + pub constant_1: MetricPattern1, + pub constant_100: MetricPattern1, + pub constant_2: MetricPattern1, + pub constant_20: MetricPattern1, + pub constant_3: MetricPattern1, + pub constant_30: MetricPattern1, + pub constant_38_2: MetricPattern1, + pub constant_4: MetricPattern1, + pub constant_50: MetricPattern1, + pub constant_600: MetricPattern1, + pub constant_61_8: MetricPattern1, + pub constant_70: MetricPattern1, + pub constant_80: MetricPattern1, + pub constant_minus_1: MetricPattern1, + pub constant_minus_2: MetricPattern1, + pub constant_minus_3: MetricPattern1, + pub constant_minus_4: MetricPattern1, } impl CatalogTree_Constants { pub fn new(client: Arc, base_path: String) -> Self { Self { - constant_0: MetricPattern3::new(client.clone(), format!("{base_path}_constant_0")), - constant_1: MetricPattern3::new(client.clone(), format!("{base_path}_constant_1")), - constant_100: MetricPattern3::new(client.clone(), format!("{base_path}_constant_100")), - constant_2: MetricPattern3::new(client.clone(), format!("{base_path}_constant_2")), - constant_20: MetricPattern3::new(client.clone(), format!("{base_path}_constant_20")), - constant_3: MetricPattern3::new(client.clone(), format!("{base_path}_constant_3")), - constant_30: MetricPattern3::new(client.clone(), format!("{base_path}_constant_30")), - constant_38_2: MetricPattern3::new(client.clone(), format!("{base_path}_constant_38_2")), - constant_4: MetricPattern3::new(client.clone(), format!("{base_path}_constant_4")), - constant_50: MetricPattern3::new(client.clone(), format!("{base_path}_constant_50")), - constant_600: MetricPattern3::new(client.clone(), format!("{base_path}_constant_600")), - constant_61_8: MetricPattern3::new(client.clone(), format!("{base_path}_constant_61_8")), - constant_70: MetricPattern3::new(client.clone(), format!("{base_path}_constant_70")), - constant_80: MetricPattern3::new(client.clone(), format!("{base_path}_constant_80")), - constant_minus_1: MetricPattern3::new(client.clone(), format!("{base_path}_constant_minus_1")), - constant_minus_2: MetricPattern3::new(client.clone(), format!("{base_path}_constant_minus_2")), - constant_minus_3: MetricPattern3::new(client.clone(), format!("{base_path}_constant_minus_3")), - constant_minus_4: MetricPattern3::new(client.clone(), format!("{base_path}_constant_minus_4")), + constant_0: MetricPattern1::new(client.clone(), format!("{base_path}_constant_0")), + constant_1: MetricPattern1::new(client.clone(), format!("{base_path}_constant_1")), + constant_100: MetricPattern1::new(client.clone(), format!("{base_path}_constant_100")), + constant_2: MetricPattern1::new(client.clone(), format!("{base_path}_constant_2")), + constant_20: MetricPattern1::new(client.clone(), format!("{base_path}_constant_20")), + constant_3: MetricPattern1::new(client.clone(), format!("{base_path}_constant_3")), + constant_30: MetricPattern1::new(client.clone(), format!("{base_path}_constant_30")), + constant_38_2: MetricPattern1::new(client.clone(), format!("{base_path}_constant_38_2")), + constant_4: MetricPattern1::new(client.clone(), format!("{base_path}_constant_4")), + constant_50: MetricPattern1::new(client.clone(), format!("{base_path}_constant_50")), + constant_600: MetricPattern1::new(client.clone(), format!("{base_path}_constant_600")), + constant_61_8: MetricPattern1::new(client.clone(), format!("{base_path}_constant_61_8")), + constant_70: MetricPattern1::new(client.clone(), format!("{base_path}_constant_70")), + constant_80: MetricPattern1::new(client.clone(), format!("{base_path}_constant_80")), + constant_minus_1: MetricPattern1::new(client.clone(), format!("{base_path}_constant_minus_1")), + constant_minus_2: MetricPattern1::new(client.clone(), format!("{base_path}_constant_minus_2")), + constant_minus_3: MetricPattern1::new(client.clone(), format!("{base_path}_constant_minus_3")), + constant_minus_4: MetricPattern1::new(client.clone(), format!("{base_path}_constant_minus_4")), } } } @@ -4352,10 +4133,10 @@ pub struct CatalogTree_Distribution { pub address_cohorts: CatalogTree_Distribution_AddressCohorts, pub addresses_data: CatalogTree_Distribution_AddressesData, pub any_address_indexes: CatalogTree_Distribution_AnyAddressIndexes, - pub chain_state: MetricPattern12, + pub chain_state: MetricPattern11, pub empty_addr_count: AddrCountPattern, - pub emptyaddressindex: MetricPattern33, - pub loadedaddressindex: MetricPattern32, + pub emptyaddressindex: MetricPattern32, + pub loadedaddressindex: MetricPattern31, pub utxo_cohorts: CatalogTree_Distribution_UtxoCohorts, } @@ -4366,10 +4147,10 @@ impl CatalogTree_Distribution { address_cohorts: CatalogTree_Distribution_AddressCohorts::new(client.clone(), format!("{base_path}_address_cohorts")), addresses_data: CatalogTree_Distribution_AddressesData::new(client.clone(), format!("{base_path}_addresses_data")), any_address_indexes: CatalogTree_Distribution_AnyAddressIndexes::new(client.clone(), format!("{base_path}_any_address_indexes")), - chain_state: MetricPattern12::new(client.clone(), format!("{base_path}_chain_state")), + chain_state: MetricPattern11::new(client.clone(), format!("{base_path}_chain_state")), empty_addr_count: AddrCountPattern::new(client.clone(), "empty_addr_count".to_string()), - emptyaddressindex: MetricPattern33::new(client.clone(), format!("{base_path}_emptyaddressindex")), - loadedaddressindex: MetricPattern32::new(client.clone(), format!("{base_path}_loadedaddressindex")), + emptyaddressindex: MetricPattern32::new(client.clone(), format!("{base_path}_emptyaddressindex")), + loadedaddressindex: MetricPattern31::new(client.clone(), format!("{base_path}_loadedaddressindex")), utxo_cohorts: CatalogTree_Distribution_UtxoCohorts::new(client.clone(), format!("{base_path}_utxo_cohorts")), } } @@ -4509,42 +4290,42 @@ impl CatalogTree_Distribution_AddressCohorts_LtAmount { /// Catalog tree node. pub struct CatalogTree_Distribution_AddressesData { - pub empty: MetricPattern33, - pub loaded: MetricPattern32, + pub empty: MetricPattern32, + pub loaded: MetricPattern31, } impl CatalogTree_Distribution_AddressesData { pub fn new(client: Arc, base_path: String) -> Self { Self { - empty: MetricPattern33::new(client.clone(), format!("{base_path}_empty")), - loaded: MetricPattern32::new(client.clone(), format!("{base_path}_loaded")), + empty: MetricPattern32::new(client.clone(), format!("{base_path}_empty")), + loaded: MetricPattern31::new(client.clone(), format!("{base_path}_loaded")), } } } /// Catalog tree node. pub struct CatalogTree_Distribution_AnyAddressIndexes { - pub p2a: MetricPattern17, - pub p2pk33: MetricPattern19, - pub p2pk65: MetricPattern20, - pub p2pkh: MetricPattern21, - pub p2sh: MetricPattern22, - pub p2tr: MetricPattern23, - pub p2wpkh: MetricPattern24, - pub p2wsh: MetricPattern25, + pub p2a: MetricPattern16, + pub p2pk33: MetricPattern18, + pub p2pk65: MetricPattern19, + pub p2pkh: MetricPattern20, + pub p2sh: MetricPattern21, + pub p2tr: MetricPattern22, + pub p2wpkh: MetricPattern23, + pub p2wsh: MetricPattern24, } impl CatalogTree_Distribution_AnyAddressIndexes { pub fn new(client: Arc, base_path: String) -> Self { Self { - p2a: MetricPattern17::new(client.clone(), format!("{base_path}_p2a")), - p2pk33: MetricPattern19::new(client.clone(), format!("{base_path}_p2pk33")), - p2pk65: MetricPattern20::new(client.clone(), format!("{base_path}_p2pk65")), - p2pkh: MetricPattern21::new(client.clone(), format!("{base_path}_p2pkh")), - p2sh: MetricPattern22::new(client.clone(), format!("{base_path}_p2sh")), - p2tr: MetricPattern23::new(client.clone(), format!("{base_path}_p2tr")), - p2wpkh: MetricPattern24::new(client.clone(), format!("{base_path}_p2wpkh")), - p2wsh: MetricPattern25::new(client.clone(), format!("{base_path}_p2wsh")), + p2a: MetricPattern16::new(client.clone(), format!("{base_path}_p2a")), + p2pk33: MetricPattern18::new(client.clone(), format!("{base_path}_p2pk33")), + p2pk65: MetricPattern19::new(client.clone(), format!("{base_path}_p2pk65")), + p2pkh: MetricPattern20::new(client.clone(), format!("{base_path}_p2pkh")), + p2sh: MetricPattern21::new(client.clone(), format!("{base_path}_p2sh")), + p2tr: MetricPattern22::new(client.clone(), format!("{base_path}_p2tr")), + p2wpkh: MetricPattern23::new(client.clone(), format!("{base_path}_p2wpkh")), + p2wsh: MetricPattern24::new(client.clone(), format!("{base_path}_p2wsh")), } } } @@ -5134,128 +4915,145 @@ impl CatalogTree_Indexes_Address { /// Catalog tree node. pub struct CatalogTree_Indexes_Dateindex { - pub date: MetricPattern7, - pub first_height: MetricPattern7, - pub height_count: MetricPattern7, - pub identity: MetricPattern7, - pub monthindex: MetricPattern7, - pub weekindex: MetricPattern7, + pub date: MetricPattern6, + pub first_height: MetricPattern6, + pub height_count: MetricPattern6, + pub identity: MetricPattern6, + pub monthindex: MetricPattern6, + pub weekindex: MetricPattern6, } impl CatalogTree_Indexes_Dateindex { pub fn new(client: Arc, base_path: String) -> Self { Self { - date: MetricPattern7::new(client.clone(), format!("{base_path}_date")), - first_height: MetricPattern7::new(client.clone(), format!("{base_path}_first_height")), - height_count: MetricPattern7::new(client.clone(), format!("{base_path}_height_count")), - identity: MetricPattern7::new(client.clone(), format!("{base_path}_identity")), - monthindex: MetricPattern7::new(client.clone(), format!("{base_path}_monthindex")), - weekindex: MetricPattern7::new(client.clone(), format!("{base_path}_weekindex")), + date: MetricPattern6::new(client.clone(), format!("{base_path}_date")), + first_height: MetricPattern6::new(client.clone(), format!("{base_path}_first_height")), + height_count: MetricPattern6::new(client.clone(), format!("{base_path}_height_count")), + identity: MetricPattern6::new(client.clone(), format!("{base_path}_identity")), + monthindex: MetricPattern6::new(client.clone(), format!("{base_path}_monthindex")), + weekindex: MetricPattern6::new(client.clone(), format!("{base_path}_weekindex")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Decadeindex { - pub first_yearindex: MetricPattern8, - pub identity: MetricPattern8, - pub yearindex_count: MetricPattern8, + pub first_yearindex: MetricPattern7, + pub identity: MetricPattern7, + pub yearindex_count: MetricPattern7, } impl CatalogTree_Indexes_Decadeindex { pub fn new(client: Arc, base_path: String) -> Self { Self { - first_yearindex: MetricPattern8::new(client.clone(), format!("{base_path}_first_yearindex")), - identity: MetricPattern8::new(client.clone(), format!("{base_path}_identity")), - yearindex_count: MetricPattern8::new(client.clone(), format!("{base_path}_yearindex_count")), + first_yearindex: MetricPattern7::new(client.clone(), format!("{base_path}_first_yearindex")), + identity: MetricPattern7::new(client.clone(), format!("{base_path}_identity")), + yearindex_count: MetricPattern7::new(client.clone(), format!("{base_path}_yearindex_count")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Difficultyepoch { - pub first_height: MetricPattern9, - pub height_count: MetricPattern9, - pub identity: MetricPattern9, + pub first_height: MetricPattern8, + pub height_count: MetricPattern8, + pub identity: MetricPattern8, } impl CatalogTree_Indexes_Difficultyepoch { pub fn new(client: Arc, base_path: String) -> Self { Self { - first_height: MetricPattern9::new(client.clone(), format!("{base_path}_first_height")), - height_count: MetricPattern9::new(client.clone(), format!("{base_path}_height_count")), - identity: MetricPattern9::new(client.clone(), format!("{base_path}_identity")), + first_height: MetricPattern8::new(client.clone(), format!("{base_path}_first_height")), + height_count: MetricPattern8::new(client.clone(), format!("{base_path}_height_count")), + identity: MetricPattern8::new(client.clone(), format!("{base_path}_identity")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Halvingepoch { - pub first_height: MetricPattern11, - pub identity: MetricPattern11, + pub first_height: MetricPattern10, + pub identity: MetricPattern10, } impl CatalogTree_Indexes_Halvingepoch { pub fn new(client: Arc, base_path: String) -> Self { Self { - first_height: MetricPattern11::new(client.clone(), format!("{base_path}_first_height")), - identity: MetricPattern11::new(client.clone(), format!("{base_path}_identity")), + first_height: MetricPattern10::new(client.clone(), format!("{base_path}_first_height")), + identity: MetricPattern10::new(client.clone(), format!("{base_path}_identity")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Height { - pub dateindex: MetricPattern12, - pub difficultyepoch: MetricPattern12, - pub halvingepoch: MetricPattern12, - pub identity: MetricPattern12, - pub txindex_count: MetricPattern12, + pub dateindex: MetricPattern11, + pub difficultyepoch: MetricPattern11, + pub halvingepoch: MetricPattern11, + pub identity: MetricPattern11, + pub txindex_count: MetricPattern11, } impl CatalogTree_Indexes_Height { pub fn new(client: Arc, base_path: String) -> Self { Self { - dateindex: MetricPattern12::new(client.clone(), format!("{base_path}_dateindex")), - difficultyepoch: MetricPattern12::new(client.clone(), format!("{base_path}_difficultyepoch")), - halvingepoch: MetricPattern12::new(client.clone(), format!("{base_path}_halvingepoch")), - identity: MetricPattern12::new(client.clone(), format!("{base_path}_identity")), - txindex_count: MetricPattern12::new(client.clone(), format!("{base_path}_txindex_count")), + dateindex: MetricPattern11::new(client.clone(), format!("{base_path}_dateindex")), + difficultyepoch: MetricPattern11::new(client.clone(), format!("{base_path}_difficultyepoch")), + halvingepoch: MetricPattern11::new(client.clone(), format!("{base_path}_halvingepoch")), + identity: MetricPattern11::new(client.clone(), format!("{base_path}_identity")), + txindex_count: MetricPattern11::new(client.clone(), format!("{base_path}_txindex_count")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Monthindex { - pub dateindex_count: MetricPattern14, - pub first_dateindex: MetricPattern14, - pub identity: MetricPattern14, - pub quarterindex: MetricPattern14, - pub semesterindex: MetricPattern14, - pub yearindex: MetricPattern14, + pub dateindex_count: MetricPattern13, + pub first_dateindex: MetricPattern13, + pub identity: MetricPattern13, + pub quarterindex: MetricPattern13, + pub semesterindex: MetricPattern13, + pub yearindex: MetricPattern13, } impl CatalogTree_Indexes_Monthindex { pub fn new(client: Arc, base_path: String) -> Self { Self { - dateindex_count: MetricPattern14::new(client.clone(), format!("{base_path}_dateindex_count")), - first_dateindex: MetricPattern14::new(client.clone(), format!("{base_path}_first_dateindex")), - identity: MetricPattern14::new(client.clone(), format!("{base_path}_identity")), - quarterindex: MetricPattern14::new(client.clone(), format!("{base_path}_quarterindex")), - semesterindex: MetricPattern14::new(client.clone(), format!("{base_path}_semesterindex")), - yearindex: MetricPattern14::new(client.clone(), format!("{base_path}_yearindex")), + dateindex_count: MetricPattern13::new(client.clone(), format!("{base_path}_dateindex_count")), + first_dateindex: MetricPattern13::new(client.clone(), format!("{base_path}_first_dateindex")), + identity: MetricPattern13::new(client.clone(), format!("{base_path}_identity")), + quarterindex: MetricPattern13::new(client.clone(), format!("{base_path}_quarterindex")), + semesterindex: MetricPattern13::new(client.clone(), format!("{base_path}_semesterindex")), + yearindex: MetricPattern13::new(client.clone(), format!("{base_path}_yearindex")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Quarterindex { - pub first_monthindex: MetricPattern26, - pub identity: MetricPattern26, - pub monthindex_count: MetricPattern26, + pub first_monthindex: MetricPattern25, + pub identity: MetricPattern25, + pub monthindex_count: MetricPattern25, } impl CatalogTree_Indexes_Quarterindex { + pub fn new(client: Arc, base_path: String) -> Self { + Self { + first_monthindex: MetricPattern25::new(client.clone(), format!("{base_path}_first_monthindex")), + identity: MetricPattern25::new(client.clone(), format!("{base_path}_identity")), + monthindex_count: MetricPattern25::new(client.clone(), format!("{base_path}_monthindex_count")), + } + } +} + +/// Catalog tree node. +pub struct CatalogTree_Indexes_Semesterindex { + pub first_monthindex: MetricPattern26, + pub identity: MetricPattern26, + pub monthindex_count: MetricPattern26, +} + +impl CatalogTree_Indexes_Semesterindex { pub fn new(client: Arc, base_path: String) -> Self { Self { first_monthindex: MetricPattern26::new(client.clone(), format!("{base_path}_first_monthindex")), @@ -5265,72 +5063,55 @@ impl CatalogTree_Indexes_Quarterindex { } } -/// Catalog tree node. -pub struct CatalogTree_Indexes_Semesterindex { - pub first_monthindex: MetricPattern27, - pub identity: MetricPattern27, - pub monthindex_count: MetricPattern27, -} - -impl CatalogTree_Indexes_Semesterindex { - pub fn new(client: Arc, base_path: String) -> Self { - Self { - first_monthindex: MetricPattern27::new(client.clone(), format!("{base_path}_first_monthindex")), - identity: MetricPattern27::new(client.clone(), format!("{base_path}_identity")), - monthindex_count: MetricPattern27::new(client.clone(), format!("{base_path}_monthindex_count")), - } - } -} - /// Catalog tree node. pub struct CatalogTree_Indexes_Txindex { - pub identity: MetricPattern28, - pub input_count: MetricPattern28, - pub output_count: MetricPattern28, + pub identity: MetricPattern27, + pub input_count: MetricPattern27, + pub output_count: MetricPattern27, } impl CatalogTree_Indexes_Txindex { pub fn new(client: Arc, base_path: String) -> Self { Self { - identity: MetricPattern28::new(client.clone(), format!("{base_path}_identity")), - input_count: MetricPattern28::new(client.clone(), format!("{base_path}_input_count")), - output_count: MetricPattern28::new(client.clone(), format!("{base_path}_output_count")), + identity: MetricPattern27::new(client.clone(), format!("{base_path}_identity")), + input_count: MetricPattern27::new(client.clone(), format!("{base_path}_input_count")), + output_count: MetricPattern27::new(client.clone(), format!("{base_path}_output_count")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Weekindex { - pub dateindex_count: MetricPattern30, - pub first_dateindex: MetricPattern30, - pub identity: MetricPattern30, + pub dateindex_count: MetricPattern29, + pub first_dateindex: MetricPattern29, + pub identity: MetricPattern29, } impl CatalogTree_Indexes_Weekindex { pub fn new(client: Arc, base_path: String) -> Self { Self { - dateindex_count: MetricPattern30::new(client.clone(), format!("{base_path}_dateindex_count")), - first_dateindex: MetricPattern30::new(client.clone(), format!("{base_path}_first_dateindex")), - identity: MetricPattern30::new(client.clone(), format!("{base_path}_identity")), + dateindex_count: MetricPattern29::new(client.clone(), format!("{base_path}_dateindex_count")), + first_dateindex: MetricPattern29::new(client.clone(), format!("{base_path}_first_dateindex")), + identity: MetricPattern29::new(client.clone(), format!("{base_path}_identity")), } } } /// Catalog tree node. pub struct CatalogTree_Indexes_Yearindex { - pub decadeindex: MetricPattern31, - pub first_monthindex: MetricPattern31, - pub identity: MetricPattern31, - pub monthindex_count: MetricPattern31, + pub decadeindex: MetricPattern30, + pub first_monthindex: MetricPattern30, + pub identity: MetricPattern30, + pub monthindex_count: MetricPattern30, } impl CatalogTree_Indexes_Yearindex { pub fn new(client: Arc, base_path: String) -> Self { Self { - decadeindex: MetricPattern31::new(client.clone(), format!("{base_path}_decadeindex")), - first_monthindex: MetricPattern31::new(client.clone(), format!("{base_path}_first_monthindex")), - identity: MetricPattern31::new(client.clone(), format!("{base_path}_identity")), - monthindex_count: MetricPattern31::new(client.clone(), format!("{base_path}_monthindex_count")), + decadeindex: MetricPattern30::new(client.clone(), format!("{base_path}_decadeindex")), + first_monthindex: MetricPattern30::new(client.clone(), format!("{base_path}_first_monthindex")), + identity: MetricPattern30::new(client.clone(), format!("{base_path}_identity")), + monthindex_count: MetricPattern30::new(client.clone(), format!("{base_path}_monthindex_count")), } } } @@ -5338,41 +5119,41 @@ impl CatalogTree_Indexes_Yearindex { /// Catalog tree node. pub struct CatalogTree_Inputs { pub count: SizePattern, - pub first_txinindex: MetricPattern12, - pub outpoint: MetricPattern13, - pub outputtype: MetricPattern13, + pub first_txinindex: MetricPattern11, + pub outpoint: MetricPattern12, + pub outputtype: MetricPattern12, pub spent: CatalogTree_Inputs_Spent, - pub txindex: MetricPattern13, - pub typeindex: MetricPattern13, - pub witness_size: MetricPattern13, + pub txindex: MetricPattern12, + pub typeindex: MetricPattern12, + pub witness_size: MetricPattern12, } impl CatalogTree_Inputs { pub fn new(client: Arc, base_path: String) -> Self { Self { count: SizePattern::new(client.clone(), "input_count".to_string()), - first_txinindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_txinindex")), - outpoint: MetricPattern13::new(client.clone(), format!("{base_path}_outpoint")), - outputtype: MetricPattern13::new(client.clone(), format!("{base_path}_outputtype")), + first_txinindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_txinindex")), + outpoint: MetricPattern12::new(client.clone(), format!("{base_path}_outpoint")), + outputtype: MetricPattern12::new(client.clone(), format!("{base_path}_outputtype")), spent: CatalogTree_Inputs_Spent::new(client.clone(), format!("{base_path}_spent")), - txindex: MetricPattern13::new(client.clone(), format!("{base_path}_txindex")), - typeindex: MetricPattern13::new(client.clone(), format!("{base_path}_typeindex")), - witness_size: MetricPattern13::new(client.clone(), format!("{base_path}_witness_size")), + txindex: MetricPattern12::new(client.clone(), format!("{base_path}_txindex")), + typeindex: MetricPattern12::new(client.clone(), format!("{base_path}_typeindex")), + witness_size: MetricPattern12::new(client.clone(), format!("{base_path}_witness_size")), } } } /// Catalog tree node. pub struct CatalogTree_Inputs_Spent { - pub txoutindex: MetricPattern13, - pub value: MetricPattern13, + pub txoutindex: MetricPattern12, + pub value: MetricPattern12, } impl CatalogTree_Inputs_Spent { pub fn new(client: Arc, base_path: String) -> Self { Self { - txoutindex: MetricPattern13::new(client.clone(), format!("{base_path}_txoutindex")), - value: MetricPattern13::new(client.clone(), format!("{base_path}_value")), + txoutindex: MetricPattern12::new(client.clone(), format!("{base_path}_txoutindex")), + value: MetricPattern12::new(client.clone(), format!("{base_path}_value")), } } } @@ -5489,49 +5270,49 @@ impl CatalogTree_Market_Dca_ClassStack { /// Catalog tree node. pub struct CatalogTree_Market_Indicators { - pub gini: MetricPattern7, - pub macd_histogram: MetricPattern7, - pub macd_line: MetricPattern7, - pub macd_signal: MetricPattern7, + pub gini: MetricPattern6, + pub macd_histogram: MetricPattern6, + pub macd_line: MetricPattern6, + pub macd_signal: MetricPattern6, pub nvt: MetricPattern4, - pub pi_cycle: MetricPattern7, + pub pi_cycle: MetricPattern6, pub puell_multiple: MetricPattern4, - pub rsi_14d: MetricPattern7, - pub rsi_14d_max: MetricPattern7, - pub rsi_14d_min: MetricPattern7, - pub rsi_average_gain_14d: MetricPattern7, - pub rsi_average_loss_14d: MetricPattern7, - pub rsi_gains: MetricPattern7, - pub rsi_losses: MetricPattern7, - pub stoch_d: MetricPattern7, - pub stoch_k: MetricPattern7, - pub stoch_rsi: MetricPattern7, - pub stoch_rsi_d: MetricPattern7, - pub stoch_rsi_k: MetricPattern7, + pub rsi_14d: MetricPattern6, + pub rsi_14d_max: MetricPattern6, + pub rsi_14d_min: MetricPattern6, + pub rsi_average_gain_14d: MetricPattern6, + pub rsi_average_loss_14d: MetricPattern6, + pub rsi_gains: MetricPattern6, + pub rsi_losses: MetricPattern6, + pub stoch_d: MetricPattern6, + pub stoch_k: MetricPattern6, + pub stoch_rsi: MetricPattern6, + pub stoch_rsi_d: MetricPattern6, + pub stoch_rsi_k: MetricPattern6, } impl CatalogTree_Market_Indicators { pub fn new(client: Arc, base_path: String) -> Self { Self { - gini: MetricPattern7::new(client.clone(), format!("{base_path}_gini")), - macd_histogram: MetricPattern7::new(client.clone(), format!("{base_path}_macd_histogram")), - macd_line: MetricPattern7::new(client.clone(), format!("{base_path}_macd_line")), - macd_signal: MetricPattern7::new(client.clone(), format!("{base_path}_macd_signal")), + gini: MetricPattern6::new(client.clone(), format!("{base_path}_gini")), + macd_histogram: MetricPattern6::new(client.clone(), format!("{base_path}_macd_histogram")), + macd_line: MetricPattern6::new(client.clone(), format!("{base_path}_macd_line")), + macd_signal: MetricPattern6::new(client.clone(), format!("{base_path}_macd_signal")), nvt: MetricPattern4::new(client.clone(), format!("{base_path}_nvt")), - pi_cycle: MetricPattern7::new(client.clone(), format!("{base_path}_pi_cycle")), + pi_cycle: MetricPattern6::new(client.clone(), format!("{base_path}_pi_cycle")), puell_multiple: MetricPattern4::new(client.clone(), format!("{base_path}_puell_multiple")), - rsi_14d: MetricPattern7::new(client.clone(), format!("{base_path}_rsi_14d")), - rsi_14d_max: MetricPattern7::new(client.clone(), format!("{base_path}_rsi_14d_max")), - rsi_14d_min: MetricPattern7::new(client.clone(), format!("{base_path}_rsi_14d_min")), - rsi_average_gain_14d: MetricPattern7::new(client.clone(), format!("{base_path}_rsi_average_gain_14d")), - rsi_average_loss_14d: MetricPattern7::new(client.clone(), format!("{base_path}_rsi_average_loss_14d")), - rsi_gains: MetricPattern7::new(client.clone(), format!("{base_path}_rsi_gains")), - rsi_losses: MetricPattern7::new(client.clone(), format!("{base_path}_rsi_losses")), - stoch_d: MetricPattern7::new(client.clone(), format!("{base_path}_stoch_d")), - stoch_k: MetricPattern7::new(client.clone(), format!("{base_path}_stoch_k")), - stoch_rsi: MetricPattern7::new(client.clone(), format!("{base_path}_stoch_rsi")), - stoch_rsi_d: MetricPattern7::new(client.clone(), format!("{base_path}_stoch_rsi_d")), - stoch_rsi_k: MetricPattern7::new(client.clone(), format!("{base_path}_stoch_rsi_k")), + rsi_14d: MetricPattern6::new(client.clone(), format!("{base_path}_rsi_14d")), + rsi_14d_max: MetricPattern6::new(client.clone(), format!("{base_path}_rsi_14d_max")), + rsi_14d_min: MetricPattern6::new(client.clone(), format!("{base_path}_rsi_14d_min")), + rsi_average_gain_14d: MetricPattern6::new(client.clone(), format!("{base_path}_rsi_average_gain_14d")), + rsi_average_loss_14d: MetricPattern6::new(client.clone(), format!("{base_path}_rsi_average_loss_14d")), + rsi_gains: MetricPattern6::new(client.clone(), format!("{base_path}_rsi_gains")), + rsi_losses: MetricPattern6::new(client.clone(), format!("{base_path}_rsi_losses")), + stoch_d: MetricPattern6::new(client.clone(), format!("{base_path}_stoch_d")), + stoch_k: MetricPattern6::new(client.clone(), format!("{base_path}_stoch_k")), + stoch_rsi: MetricPattern6::new(client.clone(), format!("{base_path}_stoch_rsi")), + stoch_rsi_d: MetricPattern6::new(client.clone(), format!("{base_path}_stoch_rsi_d")), + stoch_rsi_k: MetricPattern6::new(client.clone(), format!("{base_path}_stoch_rsi_k")), } } } @@ -5641,8 +5422,8 @@ pub struct CatalogTree_Market_Range { pub price_2w_choppiness_index: MetricPattern4, pub price_2w_max: MetricPattern4, pub price_2w_min: MetricPattern4, - pub price_true_range: MetricPattern7, - pub price_true_range_2w_sum: MetricPattern7, + pub price_true_range: MetricPattern6, + pub price_true_range_2w_sum: MetricPattern6, } impl CatalogTree_Market_Range { @@ -5657,8 +5438,8 @@ impl CatalogTree_Market_Range { price_2w_choppiness_index: MetricPattern4::new(client.clone(), format!("{base_path}_price_2w_choppiness_index")), price_2w_max: MetricPattern4::new(client.clone(), format!("{base_path}_price_2w_max")), price_2w_min: MetricPattern4::new(client.clone(), format!("{base_path}_price_2w_min")), - price_true_range: MetricPattern7::new(client.clone(), format!("{base_path}_price_true_range")), - price_true_range_2w_sum: MetricPattern7::new(client.clone(), format!("{base_path}_price_true_range_2w_sum")), + price_true_range: MetricPattern6::new(client.clone(), format!("{base_path}_price_true_range")), + price_true_range_2w_sum: MetricPattern6::new(client.clone(), format!("{base_path}_price_true_range_2w_sum")), } } } @@ -5672,7 +5453,7 @@ pub struct CatalogTree_Market_Returns { pub downside_1m_sd: _1dReturns1mSdPattern, pub downside_1w_sd: _1dReturns1mSdPattern, pub downside_1y_sd: _1dReturns1mSdPattern, - pub downside_returns: MetricPattern7, + pub downside_returns: MetricPattern6, pub price_returns: PriceAgoPattern, } @@ -5686,7 +5467,7 @@ impl CatalogTree_Market_Returns { downside_1m_sd: _1dReturns1mSdPattern::new(client.clone(), "downside_1m_sd".to_string()), downside_1w_sd: _1dReturns1mSdPattern::new(client.clone(), "downside_1w_sd".to_string()), downside_1y_sd: _1dReturns1mSdPattern::new(client.clone(), "downside_1y_sd".to_string()), - downside_returns: MetricPattern7::new(client.clone(), format!("{base_path}_downside_returns")), + downside_returns: MetricPattern6::new(client.clone(), format!("{base_path}_downside_returns")), price_returns: PriceAgoPattern::new(client.clone(), "price_returns".to_string()), } } @@ -5697,12 +5478,12 @@ pub struct CatalogTree_Market_Volatility { pub price_1m_volatility: MetricPattern4, pub price_1w_volatility: MetricPattern4, pub price_1y_volatility: MetricPattern4, - pub sharpe_1m: MetricPattern7, - pub sharpe_1w: MetricPattern7, - pub sharpe_1y: MetricPattern7, - pub sortino_1m: MetricPattern7, - pub sortino_1w: MetricPattern7, - pub sortino_1y: MetricPattern7, + pub sharpe_1m: MetricPattern6, + pub sharpe_1w: MetricPattern6, + pub sharpe_1y: MetricPattern6, + pub sortino_1m: MetricPattern6, + pub sortino_1w: MetricPattern6, + pub sortino_1y: MetricPattern6, } impl CatalogTree_Market_Volatility { @@ -5711,12 +5492,12 @@ impl CatalogTree_Market_Volatility { price_1m_volatility: MetricPattern4::new(client.clone(), format!("{base_path}_price_1m_volatility")), price_1w_volatility: MetricPattern4::new(client.clone(), format!("{base_path}_price_1w_volatility")), price_1y_volatility: MetricPattern4::new(client.clone(), format!("{base_path}_price_1y_volatility")), - sharpe_1m: MetricPattern7::new(client.clone(), format!("{base_path}_sharpe_1m")), - sharpe_1w: MetricPattern7::new(client.clone(), format!("{base_path}_sharpe_1w")), - sharpe_1y: MetricPattern7::new(client.clone(), format!("{base_path}_sharpe_1y")), - sortino_1m: MetricPattern7::new(client.clone(), format!("{base_path}_sortino_1m")), - sortino_1w: MetricPattern7::new(client.clone(), format!("{base_path}_sortino_1w")), - sortino_1y: MetricPattern7::new(client.clone(), format!("{base_path}_sortino_1y")), + sharpe_1m: MetricPattern6::new(client.clone(), format!("{base_path}_sharpe_1m")), + sharpe_1w: MetricPattern6::new(client.clone(), format!("{base_path}_sharpe_1w")), + sharpe_1y: MetricPattern6::new(client.clone(), format!("{base_path}_sharpe_1y")), + sortino_1m: MetricPattern6::new(client.clone(), format!("{base_path}_sortino_1m")), + sortino_1w: MetricPattern6::new(client.clone(), format!("{base_path}_sortino_1w")), + sortino_1y: MetricPattern6::new(client.clone(), format!("{base_path}_sortino_1y")), } } } @@ -5724,24 +5505,24 @@ impl CatalogTree_Market_Volatility { /// Catalog tree node. pub struct CatalogTree_Outputs { pub count: CatalogTree_Outputs_Count, - pub first_txoutindex: MetricPattern12, - pub outputtype: MetricPattern16, + pub first_txoutindex: MetricPattern11, + pub outputtype: MetricPattern15, pub spent: CatalogTree_Outputs_Spent, - pub txindex: MetricPattern16, - pub typeindex: MetricPattern16, - pub value: MetricPattern16, + pub txindex: MetricPattern15, + pub typeindex: MetricPattern15, + pub value: MetricPattern15, } impl CatalogTree_Outputs { pub fn new(client: Arc, base_path: String) -> Self { Self { count: CatalogTree_Outputs_Count::new(client.clone(), format!("{base_path}_count")), - first_txoutindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_txoutindex")), - outputtype: MetricPattern16::new(client.clone(), format!("{base_path}_outputtype")), + first_txoutindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_txoutindex")), + outputtype: MetricPattern15::new(client.clone(), format!("{base_path}_outputtype")), spent: CatalogTree_Outputs_Spent::new(client.clone(), format!("{base_path}_spent")), - txindex: MetricPattern16::new(client.clone(), format!("{base_path}_txindex")), - typeindex: MetricPattern16::new(client.clone(), format!("{base_path}_typeindex")), - value: MetricPattern16::new(client.clone(), format!("{base_path}_value")), + txindex: MetricPattern15::new(client.clone(), format!("{base_path}_txindex")), + typeindex: MetricPattern15::new(client.clone(), format!("{base_path}_typeindex")), + value: MetricPattern15::new(client.clone(), format!("{base_path}_value")), } } } @@ -5749,41 +5530,41 @@ impl CatalogTree_Outputs { /// Catalog tree node. pub struct CatalogTree_Outputs_Count { pub total_count: SizePattern, - pub utxo_count: BitcoinPattern, + pub utxo_count: FullnessPattern, } impl CatalogTree_Outputs_Count { pub fn new(client: Arc, base_path: String) -> Self { Self { total_count: SizePattern::new(client.clone(), "output_count".to_string()), - utxo_count: BitcoinPattern::new(client.clone(), "exact_utxo_count".to_string()), + utxo_count: FullnessPattern::new(client.clone(), "exact_utxo_count".to_string()), } } } /// Catalog tree node. pub struct CatalogTree_Outputs_Spent { - pub txinindex: MetricPattern16, + pub txinindex: MetricPattern15, } impl CatalogTree_Outputs_Spent { pub fn new(client: Arc, base_path: String) -> Self { Self { - txinindex: MetricPattern16::new(client.clone(), format!("{base_path}_txinindex")), + txinindex: MetricPattern15::new(client.clone(), format!("{base_path}_txinindex")), } } } /// Catalog tree node. pub struct CatalogTree_Pools { - pub pool: MetricPattern12, + pub height_to_pool: MetricPattern11, pub vecs: CatalogTree_Pools_Vecs, } impl CatalogTree_Pools { pub fn new(client: Arc, base_path: String) -> Self { Self { - pool: MetricPattern12::new(client.clone(), format!("{base_path}_pool")), + height_to_pool: MetricPattern11::new(client.clone(), format!("{base_path}_height_to_pool")), vecs: CatalogTree_Pools_Vecs::new(client.clone(), format!("{base_path}_vecs")), } } @@ -6118,62 +5899,32 @@ impl CatalogTree_Pools_Vecs { /// Catalog tree node. pub struct CatalogTree_Positions { - pub block_position: MetricPattern12, - pub tx_position: MetricPattern28, + pub block_position: MetricPattern11, + pub tx_position: MetricPattern27, } impl CatalogTree_Positions { pub fn new(client: Arc, base_path: String) -> Self { Self { - block_position: MetricPattern12::new(client.clone(), format!("{base_path}_block_position")), - tx_position: MetricPattern28::new(client.clone(), format!("{base_path}_tx_position")), + block_position: MetricPattern11::new(client.clone(), format!("{base_path}_block_position")), + tx_position: MetricPattern27::new(client.clone(), format!("{base_path}_tx_position")), } } } /// Catalog tree node. pub struct CatalogTree_Price { - pub cents: CatalogTree_Price_Cents, - pub sats: SatsPattern, - pub usd: SatsPattern, + pub cents: CentsPattern, + pub sats: CentsPattern, + pub usd: CentsPattern, } impl CatalogTree_Price { pub fn new(client: Arc, base_path: String) -> Self { Self { - cents: CatalogTree_Price_Cents::new(client.clone(), format!("{base_path}_cents")), - sats: SatsPattern::new(client.clone(), "price".to_string()), - usd: SatsPattern::new(client.clone(), "price".to_string()), - } - } -} - -/// Catalog tree node. -pub struct CatalogTree_Price_Cents { - pub ohlc: MetricPattern6, - pub split: CatalogTree_Price_Cents_Split, -} - -impl CatalogTree_Price_Cents { - pub fn new(client: Arc, base_path: String) -> Self { - Self { - ohlc: MetricPattern6::new(client.clone(), format!("{base_path}_ohlc")), - split: CatalogTree_Price_Cents_Split::new(client.clone(), format!("{base_path}_split")), - } - } -} - -/// Catalog tree node. -pub struct CatalogTree_Price_Cents_Split { - pub dateindex: DateindexPattern2, - pub height: DateindexPattern2, -} - -impl CatalogTree_Price_Cents_Split { - pub fn new(client: Arc, base_path: String) -> Self { - Self { - dateindex: DateindexPattern2::new(client.clone(), "price".to_string()), - height: DateindexPattern2::new(client.clone(), "price".to_string()), + cents: CentsPattern::new(client.clone(), "cents".to_string()), + sats: CentsPattern::new(client.clone(), "price".to_string()), + usd: CentsPattern::new(client.clone(), "price".to_string()), } } } @@ -6181,14 +5932,14 @@ impl CatalogTree_Price_Cents_Split { /// Catalog tree node. pub struct CatalogTree_Scripts { pub count: CatalogTree_Scripts_Count, - pub empty_to_txindex: MetricPattern10, - pub first_emptyoutputindex: MetricPattern12, - pub first_opreturnindex: MetricPattern12, - pub first_p2msoutputindex: MetricPattern12, - pub first_unknownoutputindex: MetricPattern12, - pub opreturn_to_txindex: MetricPattern15, - pub p2ms_to_txindex: MetricPattern18, - pub unknown_to_txindex: MetricPattern29, + pub empty_to_txindex: MetricPattern9, + pub first_emptyoutputindex: MetricPattern11, + pub first_opreturnindex: MetricPattern11, + pub first_p2msoutputindex: MetricPattern11, + pub first_unknownoutputindex: MetricPattern11, + pub opreturn_to_txindex: MetricPattern14, + pub p2ms_to_txindex: MetricPattern17, + pub unknown_to_txindex: MetricPattern28, pub value: CatalogTree_Scripts_Value, } @@ -6196,14 +5947,14 @@ impl CatalogTree_Scripts { pub fn new(client: Arc, base_path: String) -> Self { Self { count: CatalogTree_Scripts_Count::new(client.clone(), format!("{base_path}_count")), - empty_to_txindex: MetricPattern10::new(client.clone(), format!("{base_path}_empty_to_txindex")), - first_emptyoutputindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_emptyoutputindex")), - first_opreturnindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_opreturnindex")), - first_p2msoutputindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_p2msoutputindex")), - first_unknownoutputindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_unknownoutputindex")), - opreturn_to_txindex: MetricPattern15::new(client.clone(), format!("{base_path}_opreturn_to_txindex")), - p2ms_to_txindex: MetricPattern18::new(client.clone(), format!("{base_path}_p2ms_to_txindex")), - unknown_to_txindex: MetricPattern29::new(client.clone(), format!("{base_path}_unknown_to_txindex")), + empty_to_txindex: MetricPattern9::new(client.clone(), format!("{base_path}_empty_to_txindex")), + first_emptyoutputindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_emptyoutputindex")), + first_opreturnindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_opreturnindex")), + first_p2msoutputindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_p2msoutputindex")), + first_unknownoutputindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_unknownoutputindex")), + opreturn_to_txindex: MetricPattern14::new(client.clone(), format!("{base_path}_opreturn_to_txindex")), + p2ms_to_txindex: MetricPattern17::new(client.clone(), format!("{base_path}_p2ms_to_txindex")), + unknown_to_txindex: MetricPattern28::new(client.clone(), format!("{base_path}_unknown_to_txindex")), value: CatalogTree_Scripts_Value::new(client.clone(), format!("{base_path}_value")), } } @@ -6211,41 +5962,41 @@ impl CatalogTree_Scripts { /// Catalog tree node. pub struct CatalogTree_Scripts_Count { - pub emptyoutput: BitcoinPattern, - pub opreturn: BitcoinPattern, - pub p2a: BitcoinPattern, - pub p2ms: BitcoinPattern, - pub p2pk33: BitcoinPattern, - pub p2pk65: BitcoinPattern, - pub p2pkh: BitcoinPattern, - pub p2sh: BitcoinPattern, - pub p2tr: BitcoinPattern, - pub p2wpkh: BitcoinPattern, - pub p2wsh: BitcoinPattern, - pub segwit: BitcoinPattern, + pub emptyoutput: FullnessPattern, + pub opreturn: FullnessPattern, + pub p2a: FullnessPattern, + pub p2ms: FullnessPattern, + pub p2pk33: FullnessPattern, + pub p2pk65: FullnessPattern, + pub p2pkh: FullnessPattern, + pub p2sh: FullnessPattern, + pub p2tr: FullnessPattern, + pub p2wpkh: FullnessPattern, + pub p2wsh: FullnessPattern, + pub segwit: FullnessPattern, pub segwit_adoption: SegwitAdoptionPattern, pub taproot_adoption: SegwitAdoptionPattern, - pub unknownoutput: BitcoinPattern, + pub unknownoutput: FullnessPattern, } impl CatalogTree_Scripts_Count { pub fn new(client: Arc, base_path: String) -> Self { Self { - emptyoutput: BitcoinPattern::new(client.clone(), "emptyoutput_count".to_string()), - opreturn: BitcoinPattern::new(client.clone(), "opreturn_count".to_string()), - p2a: BitcoinPattern::new(client.clone(), "p2a_count".to_string()), - p2ms: BitcoinPattern::new(client.clone(), "p2ms_count".to_string()), - p2pk33: BitcoinPattern::new(client.clone(), "p2pk33_count".to_string()), - p2pk65: BitcoinPattern::new(client.clone(), "p2pk65_count".to_string()), - p2pkh: BitcoinPattern::new(client.clone(), "p2pkh_count".to_string()), - p2sh: BitcoinPattern::new(client.clone(), "p2sh_count".to_string()), - p2tr: BitcoinPattern::new(client.clone(), "p2tr_count".to_string()), - p2wpkh: BitcoinPattern::new(client.clone(), "p2wpkh_count".to_string()), - p2wsh: BitcoinPattern::new(client.clone(), "p2wsh_count".to_string()), - segwit: BitcoinPattern::new(client.clone(), "segwit_count".to_string()), + emptyoutput: FullnessPattern::new(client.clone(), "emptyoutput_count".to_string()), + opreturn: FullnessPattern::new(client.clone(), "opreturn_count".to_string()), + p2a: FullnessPattern::new(client.clone(), "p2a_count".to_string()), + p2ms: FullnessPattern::new(client.clone(), "p2ms_count".to_string()), + p2pk33: FullnessPattern::new(client.clone(), "p2pk33_count".to_string()), + p2pk65: FullnessPattern::new(client.clone(), "p2pk65_count".to_string()), + p2pkh: FullnessPattern::new(client.clone(), "p2pkh_count".to_string()), + p2sh: FullnessPattern::new(client.clone(), "p2sh_count".to_string()), + p2tr: FullnessPattern::new(client.clone(), "p2tr_count".to_string()), + p2wpkh: FullnessPattern::new(client.clone(), "p2wpkh_count".to_string()), + p2wsh: FullnessPattern::new(client.clone(), "p2wsh_count".to_string()), + segwit: FullnessPattern::new(client.clone(), "segwit_count".to_string()), segwit_adoption: SegwitAdoptionPattern::new(client.clone(), "segwit_adoption".to_string()), taproot_adoption: SegwitAdoptionPattern::new(client.clone(), "taproot_adoption".to_string()), - unknownoutput: BitcoinPattern::new(client.clone(), "unknownoutput_count".to_string()), + unknownoutput: FullnessPattern::new(client.clone(), "unknownoutput_count".to_string()), } } } @@ -6316,19 +6067,19 @@ impl CatalogTree_Supply_Velocity { /// Catalog tree node. pub struct CatalogTree_Transactions { - pub base_size: MetricPattern28, + pub base_size: MetricPattern27, pub count: CatalogTree_Transactions_Count, pub fees: CatalogTree_Transactions_Fees, - pub first_txindex: MetricPattern12, - pub first_txinindex: MetricPattern28, - pub first_txoutindex: MetricPattern28, - pub height: MetricPattern28, - pub is_explicitly_rbf: MetricPattern28, - pub rawlocktime: MetricPattern28, + pub first_txindex: MetricPattern11, + pub first_txinindex: MetricPattern27, + pub first_txoutindex: MetricPattern27, + pub height: MetricPattern27, + pub is_explicitly_rbf: MetricPattern27, + pub rawlocktime: MetricPattern27, pub size: CatalogTree_Transactions_Size, - pub total_size: MetricPattern28, - pub txid: MetricPattern28, - pub txversion: MetricPattern28, + pub total_size: MetricPattern27, + pub txid: MetricPattern27, + pub txversion: MetricPattern27, pub versions: CatalogTree_Transactions_Versions, pub volume: CatalogTree_Transactions_Volume, } @@ -6336,19 +6087,19 @@ pub struct CatalogTree_Transactions { impl CatalogTree_Transactions { pub fn new(client: Arc, base_path: String) -> Self { Self { - base_size: MetricPattern28::new(client.clone(), format!("{base_path}_base_size")), + base_size: MetricPattern27::new(client.clone(), format!("{base_path}_base_size")), count: CatalogTree_Transactions_Count::new(client.clone(), format!("{base_path}_count")), fees: CatalogTree_Transactions_Fees::new(client.clone(), format!("{base_path}_fees")), - first_txindex: MetricPattern12::new(client.clone(), format!("{base_path}_first_txindex")), - first_txinindex: MetricPattern28::new(client.clone(), format!("{base_path}_first_txinindex")), - first_txoutindex: MetricPattern28::new(client.clone(), format!("{base_path}_first_txoutindex")), - height: MetricPattern28::new(client.clone(), format!("{base_path}_height")), - is_explicitly_rbf: MetricPattern28::new(client.clone(), format!("{base_path}_is_explicitly_rbf")), - rawlocktime: MetricPattern28::new(client.clone(), format!("{base_path}_rawlocktime")), + first_txindex: MetricPattern11::new(client.clone(), format!("{base_path}_first_txindex")), + first_txinindex: MetricPattern27::new(client.clone(), format!("{base_path}_first_txinindex")), + first_txoutindex: MetricPattern27::new(client.clone(), format!("{base_path}_first_txoutindex")), + height: MetricPattern27::new(client.clone(), format!("{base_path}_height")), + is_explicitly_rbf: MetricPattern27::new(client.clone(), format!("{base_path}_is_explicitly_rbf")), + rawlocktime: MetricPattern27::new(client.clone(), format!("{base_path}_rawlocktime")), size: CatalogTree_Transactions_Size::new(client.clone(), format!("{base_path}_size")), - total_size: MetricPattern28::new(client.clone(), format!("{base_path}_total_size")), - txid: MetricPattern28::new(client.clone(), format!("{base_path}_txid")), - txversion: MetricPattern28::new(client.clone(), format!("{base_path}_txversion")), + total_size: MetricPattern27::new(client.clone(), format!("{base_path}_total_size")), + txid: MetricPattern27::new(client.clone(), format!("{base_path}_txid")), + txversion: MetricPattern27::new(client.clone(), format!("{base_path}_txversion")), versions: CatalogTree_Transactions_Versions::new(client.clone(), format!("{base_path}_versions")), volume: CatalogTree_Transactions_Volume::new(client.clone(), format!("{base_path}_volume")), } @@ -6357,15 +6108,15 @@ impl CatalogTree_Transactions { /// Catalog tree node. pub struct CatalogTree_Transactions_Count { - pub is_coinbase: MetricPattern28, - pub tx_count: BitcoinPattern, + pub is_coinbase: MetricPattern27, + pub tx_count: FullnessPattern, } impl CatalogTree_Transactions_Count { pub fn new(client: Arc, base_path: String) -> Self { Self { - is_coinbase: MetricPattern28::new(client.clone(), format!("{base_path}_is_coinbase")), - tx_count: BitcoinPattern::new(client.clone(), "tx_count".to_string()), + is_coinbase: MetricPattern27::new(client.clone(), format!("{base_path}_is_coinbase")), + tx_count: FullnessPattern::new(client.clone(), "tx_count".to_string()), } } } @@ -6374,8 +6125,8 @@ impl CatalogTree_Transactions_Count { pub struct CatalogTree_Transactions_Fees { pub fee: CatalogTree_Transactions_Fees_Fee, pub fee_rate: FeeRatePattern, - pub input_value: MetricPattern28, - pub output_value: MetricPattern28, + pub input_value: MetricPattern27, + pub output_value: MetricPattern27, } impl CatalogTree_Transactions_Fees { @@ -6383,8 +6134,8 @@ impl CatalogTree_Transactions_Fees { Self { fee: CatalogTree_Transactions_Fees_Fee::new(client.clone(), format!("{base_path}_fee")), fee_rate: FeeRatePattern::new(client.clone(), "fee_rate".to_string()), - input_value: MetricPattern28::new(client.clone(), format!("{base_path}_input_value")), - output_value: MetricPattern28::new(client.clone(), format!("{base_path}_output_value")), + input_value: MetricPattern27::new(client.clone(), format!("{base_path}_input_value")), + output_value: MetricPattern27::new(client.clone(), format!("{base_path}_output_value")), } } } @@ -6392,18 +6143,51 @@ impl CatalogTree_Transactions_Fees { /// Catalog tree node. pub struct CatalogTree_Transactions_Fees_Fee { pub bitcoin: SizePattern, - pub dollars: SizePattern, + pub dollars: CatalogTree_Transactions_Fees_Fee_Dollars, pub sats: SizePattern, - pub txindex: MetricPattern28, + pub txindex: MetricPattern27, } impl CatalogTree_Transactions_Fees_Fee { pub fn new(client: Arc, base_path: String) -> Self { Self { bitcoin: SizePattern::new(client.clone(), "fee_btc".to_string()), - dollars: SizePattern::new(client.clone(), "fee_usd".to_string()), + dollars: CatalogTree_Transactions_Fees_Fee_Dollars::new(client.clone(), format!("{base_path}_dollars")), sats: SizePattern::new(client.clone(), "fee".to_string()), - txindex: MetricPattern28::new(client.clone(), format!("{base_path}_txindex")), + txindex: MetricPattern27::new(client.clone(), format!("{base_path}_txindex")), + } + } +} + +/// Catalog tree node. +pub struct CatalogTree_Transactions_Fees_Fee_Dollars { + pub average: MetricPattern1, + pub cumulative: MetricPattern2, + pub height_cumulative: MetricPattern11, + pub max: MetricPattern1, + pub median: MetricPattern11, + pub min: MetricPattern1, + pub pct10: MetricPattern11, + pub pct25: MetricPattern11, + pub pct75: MetricPattern11, + pub pct90: MetricPattern11, + pub sum: MetricPattern1, +} + +impl CatalogTree_Transactions_Fees_Fee_Dollars { + pub fn new(client: Arc, base_path: String) -> Self { + Self { + average: MetricPattern1::new(client.clone(), format!("{base_path}_average")), + cumulative: MetricPattern2::new(client.clone(), format!("{base_path}_cumulative")), + height_cumulative: MetricPattern11::new(client.clone(), format!("{base_path}_height_cumulative")), + max: MetricPattern1::new(client.clone(), format!("{base_path}_max")), + median: MetricPattern11::new(client.clone(), format!("{base_path}_median")), + min: MetricPattern1::new(client.clone(), format!("{base_path}_min")), + pct10: MetricPattern11::new(client.clone(), format!("{base_path}_pct10")), + pct25: MetricPattern11::new(client.clone(), format!("{base_path}_pct25")), + pct75: MetricPattern11::new(client.clone(), format!("{base_path}_pct75")), + pct90: MetricPattern11::new(client.clone(), format!("{base_path}_pct90")), + sum: MetricPattern1::new(client.clone(), format!("{base_path}_sum")), } } } diff --git a/crates/brk_computer/src/blocks/compute.rs b/crates/brk_computer/src/blocks/compute.rs index 62fb63781..87301909f 100644 --- a/crates/brk_computer/src/blocks/compute.rs +++ b/crates/brk_computer/src/blocks/compute.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_indexer::Indexer; use vecdb::Exit; -use crate::{ComputeIndexes, indexes, price, transactions}; +use crate::{ComputeIndexes, indexes, transactions}; use super::Vecs; @@ -13,7 +13,6 @@ impl Vecs { indexes: &indexes::Vecs, transactions: &transactions::Vecs, starting_indexes: &ComputeIndexes, - price: Option<&price::Vecs>, exit: &Exit, ) -> Result<()> { // Core block metrics @@ -29,7 +28,8 @@ impl Vecs { self.time.compute(indexes, starting_indexes, exit)?; // Epoch metrics - self.difficulty.compute(indexes, starting_indexes, exit)?; + self.difficulty + .compute(indexer, indexes, starting_indexes, exit)?; self.halving.compute(indexes, starting_indexes, exit)?; // Rewards depends on count and transactions fees @@ -39,15 +39,14 @@ impl Vecs { &self.count, &transactions.fees, starting_indexes, - price, exit, )?; - // Mining depends on count and rewards + // Mining depends on count, difficulty, and rewards self.mining.compute( - indexer, indexes, &self.count, + &self.difficulty, &self.rewards, starting_indexes, exit, diff --git a/crates/brk_computer/src/blocks/count/compute.rs b/crates/brk_computer/src/blocks/count/compute.rs index ece1d52db..a37d8fdf1 100644 --- a/crates/brk_computer/src/blocks/count/compute.rs +++ b/crates/brk_computer/src/blocks/count/compute.rs @@ -5,7 +5,7 @@ use vecdb::{EagerVec, Exit, PcoVec, TypedVecIterator}; use super::super::time; use super::Vecs; -use crate::{ComputeIndexes, indexes, internal::ComputedBlockLast}; +use crate::{ComputeIndexes, indexes, internal::ComputedFromHeightLast}; impl Vecs { pub fn compute( @@ -104,7 +104,7 @@ impl Vecs { get_field: F, ) -> Result<()> where - F: FnOnce(&mut Self) -> &mut ComputedBlockLast, + F: FnOnce(&mut Self) -> &mut ComputedFromHeightLast, { get_field(self).compute_all(indexes, starting_indexes, exit, |v| { v.compute_transform( diff --git a/crates/brk_computer/src/blocks/count/import.rs b/crates/brk_computer/src/blocks/count/import.rs index ca181b457..2b0720b45 100644 --- a/crates/brk_computer/src/blocks/count/import.rs +++ b/crates/brk_computer/src/blocks/count/import.rs @@ -10,13 +10,13 @@ use crate::{ TARGET_BLOCKS_PER_YEAR, }, indexes, - internal::{ComputedBlockLast, ComputedBlockSumCum, LazyPeriodVecs}, + internal::{ComputedFromHeightLast, ComputedFromHeightSumCum, LazyFromDate}, }; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - block_count_target: LazyPeriodVecs::new( + block_count_target: LazyFromDate::new( "block_count_target", version, indexes, @@ -28,30 +28,30 @@ impl Vecs { |_, _| Some(StoredU64::from(TARGET_BLOCKS_PER_YEAR)), |_, _| Some(StoredU64::from(TARGET_BLOCKS_PER_DECADE)), ), - block_count: ComputedBlockSumCum::forced_import(db, "block_count", version, indexes)?, + block_count: ComputedFromHeightSumCum::forced_import(db, "block_count", version, indexes)?, _24h_start: ImportableVec::forced_import(db, "24h_start", version)?, _1w_start: ImportableVec::forced_import(db, "1w_start", version)?, _1m_start: ImportableVec::forced_import(db, "1m_start", version)?, _1y_start: ImportableVec::forced_import(db, "1y_start", version)?, - _24h_block_count: ComputedBlockLast::forced_import( + _24h_block_count: ComputedFromHeightLast::forced_import( db, "24h_block_count", version, indexes, )?, - _1w_block_count: ComputedBlockLast::forced_import( + _1w_block_count: ComputedFromHeightLast::forced_import( db, "1w_block_count", version, indexes, )?, - _1m_block_count: ComputedBlockLast::forced_import( + _1m_block_count: ComputedFromHeightLast::forced_import( db, "1m_block_count", version, indexes, )?, - _1y_block_count: ComputedBlockLast::forced_import( + _1y_block_count: ComputedFromHeightLast::forced_import( db, "1y_block_count", version, diff --git a/crates/brk_computer/src/blocks/count/vecs.rs b/crates/brk_computer/src/blocks/count/vecs.rs index 31c268093..93b24920c 100644 --- a/crates/brk_computer/src/blocks/count/vecs.rs +++ b/crates/brk_computer/src/blocks/count/vecs.rs @@ -2,20 +2,20 @@ use brk_traversable::Traversable; use brk_types::{Height, StoredU32, StoredU64}; use vecdb::{EagerVec, PcoVec}; -use crate::internal::{ComputedBlockLast, ComputedBlockSumCum, LazyPeriodVecs}; +use crate::internal::{ComputedFromHeightLast, ComputedFromHeightSumCum, LazyFromDate}; #[derive(Clone, Traversable)] pub struct Vecs { - pub block_count_target: LazyPeriodVecs, - pub block_count: ComputedBlockSumCum, + pub block_count_target: LazyFromDate, + pub block_count: ComputedFromHeightSumCum, // Rolling window starts (height-indexed only, no date aggregation needed) pub _24h_start: EagerVec>, pub _1w_start: EagerVec>, pub _1m_start: EagerVec>, pub _1y_start: EagerVec>, // Rolling window block counts - pub _24h_block_count: ComputedBlockLast, - pub _1w_block_count: ComputedBlockLast, - pub _1m_block_count: ComputedBlockLast, - pub _1y_block_count: ComputedBlockLast, + pub _24h_block_count: ComputedFromHeightLast, + pub _1w_block_count: ComputedFromHeightLast, + pub _1m_block_count: ComputedFromHeightLast, + pub _1y_block_count: ComputedFromHeightLast, } diff --git a/crates/brk_computer/src/blocks/difficulty/compute.rs b/crates/brk_computer/src/blocks/difficulty/compute.rs index cf49f3a22..490b3b29a 100644 --- a/crates/brk_computer/src/blocks/difficulty/compute.rs +++ b/crates/brk_computer/src/blocks/difficulty/compute.rs @@ -1,5 +1,6 @@ use brk_error::Result; -use brk_types::StoredU32; +use brk_indexer::Indexer; +use brk_types::{StoredF32, StoredU32}; use vecdb::{Exit, TypedVecIterator}; use super::super::TARGET_BLOCKS_PER_DAY_F32; @@ -9,10 +10,45 @@ use crate::{ComputeIndexes, indexes}; impl Vecs { pub fn compute( &mut self, + indexer: &Indexer, indexes: &indexes::Vecs, starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { + // Derive dateindex/period stats from raw difficulty + self.raw.derive_from( + indexes, + starting_indexes, + &indexer.vecs.blocks.difficulty, + exit, + )?; + + // Compute difficulty as hash rate equivalent + self.as_hash + .compute_all(indexes, starting_indexes, exit, |v| { + let multiplier = 2.0_f64.powi(32) / 600.0; + v.compute_transform( + starting_indexes.height, + &indexer.vecs.blocks.difficulty, + |(i, v, ..)| (i, StoredF32::from(*v * multiplier)), + exit, + )?; + Ok(()) + })?; + + // Compute difficulty adjustment percentage + self.adjustment + .compute_all(indexes, starting_indexes, exit, |v| { + v.compute_percentage_change( + starting_indexes.height, + &indexer.vecs.blocks.difficulty, + 1, + exit, + )?; + Ok(()) + })?; + + // Compute epoch by dateindex let mut height_to_difficultyepoch_iter = indexes.height.difficultyepoch.into_iter(); self.epoch.compute_all(starting_indexes, exit, |vec| { let mut height_count_iter = indexes.dateindex.height_count.into_iter(); @@ -31,7 +67,8 @@ impl Vecs { Ok(()) })?; - self.blocks_before_next_difficulty_adjustment.compute_all( + // Compute blocks before next adjustment + self.blocks_before_next_adjustment.compute_all( indexes, starting_indexes, exit, @@ -46,14 +83,15 @@ impl Vecs { }, )?; - self.days_before_next_difficulty_adjustment.compute_all( + // Compute days before next adjustment + self.days_before_next_adjustment.compute_all( indexes, starting_indexes, exit, |v| { v.compute_transform( starting_indexes.height, - &self.blocks_before_next_difficulty_adjustment.height, + &self.blocks_before_next_adjustment.height, |(h, blocks, ..)| (h, (*blocks as f32 / TARGET_BLOCKS_PER_DAY_F32).into()), exit, )?; diff --git a/crates/brk_computer/src/blocks/difficulty/import.rs b/crates/brk_computer/src/blocks/difficulty/import.rs index 35f6ddd00..48d4b32d9 100644 --- a/crates/brk_computer/src/blocks/difficulty/import.rs +++ b/crates/brk_computer/src/blocks/difficulty/import.rs @@ -1,26 +1,44 @@ use brk_error::Result; +use brk_indexer::Indexer; use brk_types::Version; -use vecdb::Database; +use vecdb::{Database, IterableCloneableVec}; use super::Vecs; use crate::{ indexes, - internal::{ComputedBlockLast, ComputedDateLast}, + internal::{ + ComputedFromHeightLast, ComputedFromHeightSum, ComputedFromDateLast, + ComputedHeightDerivedLast, + }, }; impl Vecs { - pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { + pub fn forced_import( + db: &Database, + version: Version, + indexer: &Indexer, + indexes: &indexes::Vecs, + ) -> Result { let v2 = Version::TWO; Ok(Self { - epoch: ComputedDateLast::forced_import(db, "difficultyepoch", version, indexes)?, - blocks_before_next_difficulty_adjustment: ComputedBlockLast::forced_import( + raw: ComputedHeightDerivedLast::forced_import( + db, + "difficulty", + indexer.vecs.blocks.difficulty.boxed_clone(), + version, + indexes, + )?, + as_hash: ComputedFromHeightLast::forced_import(db, "difficulty_as_hash", version, indexes)?, + adjustment: ComputedFromHeightSum::forced_import(db, "difficulty_adjustment", version, indexes)?, + epoch: ComputedFromDateLast::forced_import(db, "difficultyepoch", version, indexes)?, + blocks_before_next_adjustment: ComputedFromHeightLast::forced_import( db, "blocks_before_next_difficulty_adjustment", version + v2, indexes, )?, - days_before_next_difficulty_adjustment: ComputedBlockLast::forced_import( + days_before_next_adjustment: ComputedFromHeightLast::forced_import( db, "days_before_next_difficulty_adjustment", version + v2, diff --git a/crates/brk_computer/src/blocks/difficulty/vecs.rs b/crates/brk_computer/src/blocks/difficulty/vecs.rs index ea407c6dd..583bf0378 100644 --- a/crates/brk_computer/src/blocks/difficulty/vecs.rs +++ b/crates/brk_computer/src/blocks/difficulty/vecs.rs @@ -1,12 +1,18 @@ use brk_traversable::Traversable; -use brk_types::{DifficultyEpoch, StoredF32, StoredU32}; +use brk_types::{DifficultyEpoch, StoredF32, StoredF64, StoredU32}; -use crate::internal::{ComputedBlockLast, ComputedDateLast}; +use crate::internal::{ + ComputedFromHeightLast, ComputedFromHeightSum, ComputedFromDateLast, ComputedHeightDerivedLast, +}; -/// Difficulty epoch metrics and countdown +/// Difficulty metrics: raw difficulty, derived stats, adjustment, and countdown #[derive(Clone, Traversable)] pub struct Vecs { - pub epoch: ComputedDateLast, - pub blocks_before_next_difficulty_adjustment: ComputedBlockLast, - pub days_before_next_difficulty_adjustment: ComputedBlockLast, + /// Raw difficulty with dateindex/period stats - merges with indexer's raw + pub raw: ComputedHeightDerivedLast, + pub as_hash: ComputedFromHeightLast, + pub adjustment: ComputedFromHeightSum, + pub epoch: ComputedFromDateLast, + pub blocks_before_next_adjustment: ComputedFromHeightLast, + pub days_before_next_adjustment: ComputedFromHeightLast, } diff --git a/crates/brk_computer/src/blocks/halving/import.rs b/crates/brk_computer/src/blocks/halving/import.rs index 5db47715d..d21adf77a 100644 --- a/crates/brk_computer/src/blocks/halving/import.rs +++ b/crates/brk_computer/src/blocks/halving/import.rs @@ -5,7 +5,7 @@ use vecdb::Database; use super::Vecs; use crate::{ indexes, - internal::{ComputedBlockLast, ComputedDateLast}, + internal::{ComputedFromHeightLast, ComputedFromDateLast}, }; impl Vecs { @@ -13,14 +13,14 @@ impl Vecs { let v2 = Version::TWO; Ok(Self { - epoch: ComputedDateLast::forced_import(db, "halvingepoch", version, indexes)?, - blocks_before_next_halving: ComputedBlockLast::forced_import( + epoch: ComputedFromDateLast::forced_import(db, "halvingepoch", version, indexes)?, + blocks_before_next_halving: ComputedFromHeightLast::forced_import( db, "blocks_before_next_halving", version + v2, indexes, )?, - days_before_next_halving: ComputedBlockLast::forced_import( + days_before_next_halving: ComputedFromHeightLast::forced_import( db, "days_before_next_halving", version + v2, diff --git a/crates/brk_computer/src/blocks/halving/vecs.rs b/crates/brk_computer/src/blocks/halving/vecs.rs index a1b0c3f36..60ec1f434 100644 --- a/crates/brk_computer/src/blocks/halving/vecs.rs +++ b/crates/brk_computer/src/blocks/halving/vecs.rs @@ -1,12 +1,12 @@ use brk_traversable::Traversable; use brk_types::{HalvingEpoch, StoredF32, StoredU32}; -use crate::internal::{ComputedBlockLast, ComputedDateLast}; +use crate::internal::{ComputedFromHeightLast, ComputedFromDateLast}; /// Halving epoch metrics and countdown #[derive(Clone, Traversable)] pub struct Vecs { - pub epoch: ComputedDateLast, - pub blocks_before_next_halving: ComputedBlockLast, - pub days_before_next_halving: ComputedBlockLast, + pub epoch: ComputedFromDateLast, + pub blocks_before_next_halving: ComputedFromHeightLast, + pub days_before_next_halving: ComputedFromHeightLast, } diff --git a/crates/brk_computer/src/blocks/import.rs b/crates/brk_computer/src/blocks/import.rs index bfa032a4b..54311e306 100644 --- a/crates/brk_computer/src/blocks/import.rs +++ b/crates/brk_computer/src/blocks/import.rs @@ -25,16 +25,15 @@ impl Vecs { db.set_min_len(PAGE_SIZE * 50_000_000)?; let version = parent_version; - let compute_dollars = price.is_some(); let count = CountVecs::forced_import(&db, version, indexes)?; let interval = IntervalVecs::forced_import(&db, version, indexer, indexes)?; let size = SizeVecs::forced_import(&db, version, indexer, indexes)?; let weight = WeightVecs::forced_import(&db, version, indexer, indexes)?; let time = TimeVecs::forced_import(&db, version, indexer, indexes)?; - let mining = MiningVecs::forced_import(&db, version, indexer, indexes)?; - let rewards = RewardsVecs::forced_import(&db, version, indexes, compute_dollars)?; - let difficulty = DifficultyVecs::forced_import(&db, version, indexes)?; + let mining = MiningVecs::forced_import(&db, version, indexes)?; + let rewards = RewardsVecs::forced_import(&db, version, indexes, price)?; + let difficulty = DifficultyVecs::forced_import(&db, version, indexer, indexes)?; let halving = HalvingVecs::forced_import(&db, version, indexes)?; let this = Self { diff --git a/crates/brk_computer/src/blocks/interval/import.rs b/crates/brk_computer/src/blocks/interval/import.rs index 82f195384..5c4fed49e 100644 --- a/crates/brk_computer/src/blocks/interval/import.rs +++ b/crates/brk_computer/src/blocks/interval/import.rs @@ -4,7 +4,7 @@ use brk_types::{CheckedSub, Height, Timestamp, Version}; use vecdb::{Database, VecIndex}; use super::Vecs; -use crate::{indexes, internal::LazyBlockDistribution}; +use crate::{indexes, internal::LazyFromHeightDistribution}; impl Vecs { pub fn forced_import( @@ -13,7 +13,7 @@ impl Vecs { indexer: &Indexer, indexes: &indexes::Vecs, ) -> Result { - let interval = LazyBlockDistribution::forced_import_with_init( + let interval = LazyFromHeightDistribution::forced_import_with_init( db, "block_interval", version, diff --git a/crates/brk_computer/src/blocks/interval/vecs.rs b/crates/brk_computer/src/blocks/interval/vecs.rs index 6014dba17..e96c42880 100644 --- a/crates/brk_computer/src/blocks/interval/vecs.rs +++ b/crates/brk_computer/src/blocks/interval/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::Timestamp; -use crate::internal::LazyBlockDistribution; +use crate::internal::LazyFromHeightDistribution; #[derive(Clone, Traversable)] pub struct Vecs { #[traversable(flatten)] - pub interval: LazyBlockDistribution, + pub interval: LazyFromHeightDistribution, } diff --git a/crates/brk_computer/src/blocks/mining/compute.rs b/crates/brk_computer/src/blocks/mining/compute.rs index 6e78a06ae..4daa06795 100644 --- a/crates/brk_computer/src/blocks/mining/compute.rs +++ b/crates/brk_computer/src/blocks/mining/compute.rs @@ -1,47 +1,27 @@ use brk_error::Result; -use brk_indexer::Indexer; use brk_types::{StoredF32, StoredF64}; use vecdb::Exit; -use super::super::{ONE_TERA_HASH, TARGET_BLOCKS_PER_DAY_F64, count, rewards}; +use super::super::{ONE_TERA_HASH, TARGET_BLOCKS_PER_DAY_F64, count, difficulty, rewards}; use super::Vecs; use crate::{ComputeIndexes, indexes}; impl Vecs { pub fn compute( &mut self, - indexer: &Indexer, indexes: &indexes::Vecs, count_vecs: &count::Vecs, + difficulty_vecs: &difficulty::Vecs, rewards_vecs: &rewards::Vecs, starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { - self.difficulty.derive_from( - indexes, - starting_indexes, - &indexer.vecs.blocks.difficulty, - exit, - )?; - - self.difficulty_as_hash - .compute_all(indexes, starting_indexes, exit, |v| { - let multiplier = 2.0_f64.powi(32) / 600.0; - v.compute_transform( - starting_indexes.height, - &indexer.vecs.blocks.difficulty, - |(i, v, ..)| (i, StoredF32::from(*v * multiplier)), - exit, - )?; - Ok(()) - })?; - self.hash_rate .compute_all(indexes, starting_indexes, exit, |v| { v.compute_transform2( starting_indexes.height, &count_vecs._24h_block_count.height, - &self.difficulty_as_hash.height, + &difficulty_vecs.as_hash.height, |(i, block_count_sum, difficulty_as_hash, ..)| { ( i, @@ -100,17 +80,6 @@ impl Vecs { Ok(()) })?; - self.difficulty_adjustment - .compute_all(indexes, starting_indexes, exit, |v| { - v.compute_percentage_change( - starting_indexes.height, - &indexer.vecs.blocks.difficulty, - 1, - exit, - )?; - Ok(()) - })?; - self.hash_price_ths .compute_all(indexes, starting_indexes, exit, |v| { v.compute_transform2( diff --git a/crates/brk_computer/src/blocks/mining/import.rs b/crates/brk_computer/src/blocks/mining/import.rs index e58cacf9c..42da92198 100644 --- a/crates/brk_computer/src/blocks/mining/import.rs +++ b/crates/brk_computer/src/blocks/mining/import.rs @@ -1,130 +1,108 @@ use brk_error::Result; -use brk_indexer::Indexer; use brk_types::Version; -use vecdb::{Database, IterableCloneableVec}; +use vecdb::Database; use super::Vecs; use crate::{ indexes, - internal::{ComputedBlockLast, ComputedBlockSum, ComputedDateLast, ComputedDerivedBlockLast}, + internal::{ComputedFromHeightLast, ComputedFromDateLast}, }; impl Vecs { pub fn forced_import( db: &Database, version: Version, - indexer: &Indexer, indexes: &indexes::Vecs, ) -> Result { let v4 = Version::new(4); let v5 = Version::new(5); Ok(Self { - hash_rate: ComputedBlockLast::forced_import(db, "hash_rate", version + v5, indexes)?, - hash_rate_1w_sma: ComputedDateLast::forced_import( + hash_rate: ComputedFromHeightLast::forced_import(db, "hash_rate", version + v5, indexes)?, + hash_rate_1w_sma: ComputedFromDateLast::forced_import( db, "hash_rate_1w_sma", version, indexes, )?, - hash_rate_1m_sma: ComputedDateLast::forced_import( + hash_rate_1m_sma: ComputedFromDateLast::forced_import( db, "hash_rate_1m_sma", version, indexes, )?, - hash_rate_2m_sma: ComputedDateLast::forced_import( + hash_rate_2m_sma: ComputedFromDateLast::forced_import( db, "hash_rate_2m_sma", version, indexes, )?, - hash_rate_1y_sma: ComputedDateLast::forced_import( + hash_rate_1y_sma: ComputedFromDateLast::forced_import( db, "hash_rate_1y_sma", version, indexes, )?, - hash_price_ths: ComputedBlockLast::forced_import( + hash_price_ths: ComputedFromHeightLast::forced_import( db, "hash_price_ths", version + v4, indexes, )?, - hash_price_ths_min: ComputedBlockLast::forced_import( + hash_price_ths_min: ComputedFromHeightLast::forced_import( db, "hash_price_ths_min", version + v4, indexes, )?, - hash_price_phs: ComputedBlockLast::forced_import( + hash_price_phs: ComputedFromHeightLast::forced_import( db, "hash_price_phs", version + v4, indexes, )?, - hash_price_phs_min: ComputedBlockLast::forced_import( + hash_price_phs_min: ComputedFromHeightLast::forced_import( db, "hash_price_phs_min", version + v4, indexes, )?, - hash_price_rebound: ComputedBlockLast::forced_import( + hash_price_rebound: ComputedFromHeightLast::forced_import( db, "hash_price_rebound", version + v4, indexes, )?, - hash_value_ths: ComputedBlockLast::forced_import( + hash_value_ths: ComputedFromHeightLast::forced_import( db, "hash_value_ths", version + v4, indexes, )?, - hash_value_ths_min: ComputedBlockLast::forced_import( + hash_value_ths_min: ComputedFromHeightLast::forced_import( db, "hash_value_ths_min", version + v4, indexes, )?, - hash_value_phs: ComputedBlockLast::forced_import( + hash_value_phs: ComputedFromHeightLast::forced_import( db, "hash_value_phs", version + v4, indexes, )?, - hash_value_phs_min: ComputedBlockLast::forced_import( + hash_value_phs_min: ComputedFromHeightLast::forced_import( db, "hash_value_phs_min", version + v4, indexes, )?, - hash_value_rebound: ComputedBlockLast::forced_import( + hash_value_rebound: ComputedFromHeightLast::forced_import( db, "hash_value_rebound", version + v4, indexes, )?, - // Derived from external indexer data - no height storage needed - difficulty: ComputedDerivedBlockLast::forced_import( - db, - "difficulty", - indexer.vecs.blocks.difficulty.boxed_clone(), - version, - indexes, - )?, - difficulty_as_hash: ComputedBlockLast::forced_import( - db, - "difficulty_as_hash", - version, - indexes, - )?, - difficulty_adjustment: ComputedBlockSum::forced_import( - db, - "difficulty_adjustment", - version, - indexes, - )?, }) } } diff --git a/crates/brk_computer/src/blocks/mining/vecs.rs b/crates/brk_computer/src/blocks/mining/vecs.rs index 6b45470db..258a618d0 100644 --- a/crates/brk_computer/src/blocks/mining/vecs.rs +++ b/crates/brk_computer/src/blocks/mining/vecs.rs @@ -1,30 +1,24 @@ use brk_traversable::Traversable; use brk_types::{StoredF32, StoredF64}; -use crate::internal::{ - ComputedBlockLast, ComputedBlockSum, ComputedDateLast, ComputedDerivedBlockLast, -}; +use crate::internal::{ComputedFromHeightLast, ComputedFromDateLast}; -/// Mining-related metrics: hash rate, hash price, hash value, difficulty +/// Mining-related metrics: hash rate, hash price, hash value #[derive(Clone, Traversable)] pub struct Vecs { - pub hash_rate: ComputedBlockLast, - pub hash_rate_1w_sma: ComputedDateLast, - pub hash_rate_1m_sma: ComputedDateLast, - pub hash_rate_2m_sma: ComputedDateLast, - pub hash_rate_1y_sma: ComputedDateLast, - pub hash_price_ths: ComputedBlockLast, - pub hash_price_ths_min: ComputedBlockLast, - pub hash_price_phs: ComputedBlockLast, - pub hash_price_phs_min: ComputedBlockLast, - pub hash_price_rebound: ComputedBlockLast, - pub hash_value_ths: ComputedBlockLast, - pub hash_value_ths_min: ComputedBlockLast, - pub hash_value_phs: ComputedBlockLast, - pub hash_value_phs_min: ComputedBlockLast, - pub hash_value_rebound: ComputedBlockLast, - /// Derived from indexer - no height storage needed - pub difficulty: ComputedDerivedBlockLast, - pub difficulty_as_hash: ComputedBlockLast, - pub difficulty_adjustment: ComputedBlockSum, + pub hash_rate: ComputedFromHeightLast, + pub hash_rate_1w_sma: ComputedFromDateLast, + pub hash_rate_1m_sma: ComputedFromDateLast, + pub hash_rate_2m_sma: ComputedFromDateLast, + pub hash_rate_1y_sma: ComputedFromDateLast, + pub hash_price_ths: ComputedFromHeightLast, + pub hash_price_ths_min: ComputedFromHeightLast, + pub hash_price_phs: ComputedFromHeightLast, + pub hash_price_phs_min: ComputedFromHeightLast, + pub hash_price_rebound: ComputedFromHeightLast, + pub hash_value_ths: ComputedFromHeightLast, + pub hash_value_ths_min: ComputedFromHeightLast, + pub hash_value_phs: ComputedFromHeightLast, + pub hash_value_phs_min: ComputedFromHeightLast, + pub hash_value_rebound: ComputedFromHeightLast, } diff --git a/crates/brk_computer/src/blocks/mod.rs b/crates/brk_computer/src/blocks/mod.rs index 420a80754..a5a852126 100644 --- a/crates/brk_computer/src/blocks/mod.rs +++ b/crates/brk_computer/src/blocks/mod.rs @@ -44,7 +44,9 @@ pub struct Vecs { pub count: CountVecs, pub interval: IntervalVecs, + #[traversable(flatten)] pub size: SizeVecs, + #[traversable(flatten)] pub weight: WeightVecs, pub time: TimeVecs, pub mining: MiningVecs, diff --git a/crates/brk_computer/src/blocks/rewards/compute.rs b/crates/brk_computer/src/blocks/rewards/compute.rs index b4a13d021..ebf871d40 100644 --- a/crates/brk_computer/src/blocks/rewards/compute.rs +++ b/crates/brk_computer/src/blocks/rewards/compute.rs @@ -5,10 +5,9 @@ use vecdb::{Exit, IterableVec, TypedVecIterator, VecIndex}; use super::super::count; use super::Vecs; -use crate::{ComputeIndexes, indexes, price, transactions}; +use crate::{ComputeIndexes, indexes, transactions}; impl Vecs { - #[allow(clippy::too_many_arguments)] pub fn compute( &mut self, indexer: &Indexer, @@ -16,11 +15,10 @@ impl Vecs { count_vecs: &count::Vecs, transactions_fees: &transactions::FeesVecs, starting_indexes: &ComputeIndexes, - price: Option<&price::Vecs>, exit: &Exit, ) -> Result<()> { self.coinbase - .compute_all(indexes, price, starting_indexes, exit, |vec| { + .compute_all(indexes, starting_indexes, exit, |vec| { let mut txindex_to_first_txoutindex_iter = indexer.vecs.transactions.first_txoutindex.iter()?; let mut txindex_to_output_count_iter = @@ -84,7 +82,7 @@ impl Vecs { } self.subsidy - .compute_all(indexes, price, starting_indexes, exit, |vec| { + .compute_all(indexes, starting_indexes, exit, |vec| { vec.compute_transform2( starting_indexes.height, &self.coinbase.sats.height, @@ -104,7 +102,7 @@ impl Vecs { })?; self.unclaimed_rewards - .compute_all(indexes, price, starting_indexes, exit, |vec| { + .compute_all(indexes, starting_indexes, exit, |vec| { vec.compute_transform( starting_indexes.height, &self.subsidy.sats.height, diff --git a/crates/brk_computer/src/blocks/rewards/import.rs b/crates/brk_computer/src/blocks/rewards/import.rs index e0bb0286d..48ac51563 100644 --- a/crates/brk_computer/src/blocks/rewards/import.rs +++ b/crates/brk_computer/src/blocks/rewards/import.rs @@ -5,7 +5,8 @@ use vecdb::{Database, EagerVec, ImportableVec}; use super::Vecs; use crate::{ indexes, - internal::{ComputedDateLast, ValueBlockFull, ValueBlockHeight, ValueBlockSumCum}, + internal::{ComputedFromDateLast, ValueFromHeightFull, ValueHeight, ValueFromHeightSumCum}, + price, }; impl Vecs { @@ -13,41 +14,31 @@ impl Vecs { db: &Database, version: Version, indexes: &indexes::Vecs, - compute_dollars: bool, + price: Option<&price::Vecs>, ) -> Result { + let compute_dollars = price.is_some(); + Ok(Self { - _24h_coinbase_sum: ValueBlockHeight::forced_import( + _24h_coinbase_sum: ValueHeight::forced_import( db, "24h_coinbase_sum", version, compute_dollars, )?, - coinbase: ValueBlockFull::forced_import( - db, - "coinbase", - version, - indexes, - compute_dollars, - )?, - subsidy: ValueBlockFull::forced_import( - db, - "subsidy", - version, - indexes, - compute_dollars, - )?, - unclaimed_rewards: ValueBlockSumCum::forced_import( + coinbase: ValueFromHeightFull::forced_import(db, "coinbase", version, indexes, price)?, + subsidy: ValueFromHeightFull::forced_import(db, "subsidy", version, indexes, price)?, + unclaimed_rewards: ValueFromHeightSumCum::forced_import( db, "unclaimed_rewards", version, indexes, - compute_dollars, + price, )?, fee_dominance: EagerVec::forced_import(db, "fee_dominance", version)?, subsidy_dominance: EagerVec::forced_import(db, "subsidy_dominance", version)?, subsidy_usd_1y_sma: compute_dollars .then(|| { - ComputedDateLast::forced_import(db, "subsidy_usd_1y_sma", version, indexes) + ComputedFromDateLast::forced_import(db, "subsidy_usd_1y_sma", version, indexes) }) .transpose()?, }) diff --git a/crates/brk_computer/src/blocks/rewards/vecs.rs b/crates/brk_computer/src/blocks/rewards/vecs.rs index 9b48b6570..dc8075cfc 100644 --- a/crates/brk_computer/src/blocks/rewards/vecs.rs +++ b/crates/brk_computer/src/blocks/rewards/vecs.rs @@ -2,16 +2,16 @@ use brk_traversable::Traversable; use brk_types::{DateIndex, Dollars, StoredF32}; use vecdb::{EagerVec, PcoVec}; -use crate::internal::{ComputedDateLast, ValueBlockFull, ValueBlockHeight, ValueBlockSumCum}; +use crate::internal::{ComputedFromDateLast, ValueFromHeightFull, ValueHeight, ValueFromHeightSumCum}; /// Coinbase/subsidy/rewards metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub _24h_coinbase_sum: ValueBlockHeight, - pub coinbase: ValueBlockFull, - pub subsidy: ValueBlockFull, - pub unclaimed_rewards: ValueBlockSumCum, + pub _24h_coinbase_sum: ValueHeight, + pub coinbase: ValueFromHeightFull, + pub subsidy: ValueFromHeightFull, + pub unclaimed_rewards: ValueFromHeightSumCum, pub fee_dominance: EagerVec>, pub subsidy_dominance: EagerVec>, - pub subsidy_usd_1y_sma: Option>, + pub subsidy_usd_1y_sma: Option>, } diff --git a/crates/brk_computer/src/blocks/size/import.rs b/crates/brk_computer/src/blocks/size/import.rs index 2d134a2ff..2815a91d0 100644 --- a/crates/brk_computer/src/blocks/size/import.rs +++ b/crates/brk_computer/src/blocks/size/import.rs @@ -4,7 +4,7 @@ use brk_types::{Height, StoredU64, Version}; use vecdb::{Database, IterableCloneableVec, VecIndex}; use super::Vecs; -use crate::{indexes, internal::{ComputedDerivedBlockFull, LazyBlockFullHeight}}; +use crate::{indexes, internal::{ComputedHeightDerivedFull, LazyComputedFromHeightFull}}; impl Vecs { pub fn forced_import( @@ -14,7 +14,7 @@ impl Vecs { indexes: &indexes::Vecs, ) -> Result { Ok(Self { - vbytes: LazyBlockFullHeight::forced_import_with_init( + vbytes: LazyComputedFromHeightFull::forced_import_with_init( db, "block_vbytes", version, @@ -26,7 +26,7 @@ impl Vecs { .map(|w| StoredU64::from(w.to_vbytes_floor())) }, )?, - size: ComputedDerivedBlockFull::forced_import( + size: ComputedHeightDerivedFull::forced_import( db, "block_size", indexer.vecs.blocks.total_size.boxed_clone(), diff --git a/crates/brk_computer/src/blocks/size/vecs.rs b/crates/brk_computer/src/blocks/size/vecs.rs index c1d3239a1..32396bafb 100644 --- a/crates/brk_computer/src/blocks/size/vecs.rs +++ b/crates/brk_computer/src/blocks/size/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::{StoredU64, Weight}; -use crate::internal::{ComputedDerivedBlockFull, LazyBlockFullHeight}; +use crate::internal::{ComputedHeightDerivedFull, LazyComputedFromHeightFull}; #[derive(Clone, Traversable)] pub struct Vecs { - pub vbytes: LazyBlockFullHeight, - pub size: ComputedDerivedBlockFull, + pub vbytes: LazyComputedFromHeightFull, + pub size: ComputedHeightDerivedFull, } diff --git a/crates/brk_computer/src/blocks/time/import.rs b/crates/brk_computer/src/blocks/time/import.rs index 3481e2d85..4188e696a 100644 --- a/crates/brk_computer/src/blocks/time/import.rs +++ b/crates/brk_computer/src/blocks/time/import.rs @@ -4,7 +4,7 @@ use brk_types::{Date, Height, Version}; use vecdb::{Database, EagerVec, ImportableVec, IterableCloneableVec, LazyVecFrom1, VecIndex}; use super::Vecs; -use crate::{indexes, internal::ComputedDerivedBlockFirst}; +use crate::{indexes, internal::ComputedHeightDerivedFirst}; impl Vecs { pub fn forced_import( @@ -31,7 +31,7 @@ impl Vecs { |height: Height, timestamp_iter| timestamp_iter.get(height).map(Date::from), ), timestamp_fixed: height_to_timestamp_fixed, - timestamp: ComputedDerivedBlockFirst::forced_import( + timestamp: ComputedHeightDerivedFirst::forced_import( db, "timestamp", indexer.vecs.blocks.timestamp.boxed_clone(), diff --git a/crates/brk_computer/src/blocks/time/vecs.rs b/crates/brk_computer/src/blocks/time/vecs.rs index 7516cdf8c..1f060e794 100644 --- a/crates/brk_computer/src/blocks/time/vecs.rs +++ b/crates/brk_computer/src/blocks/time/vecs.rs @@ -2,7 +2,7 @@ use brk_traversable::Traversable; use brk_types::{Date, Height, Timestamp}; use vecdb::{EagerVec, LazyVecFrom1, PcoVec}; -use crate::internal::ComputedDerivedBlockFirst; +use crate::internal::ComputedHeightDerivedFirst; /// Timestamp and date metrics for blocks #[derive(Clone, Traversable)] @@ -10,5 +10,5 @@ pub struct Vecs { pub date: LazyVecFrom1, pub date_fixed: LazyVecFrom1, pub timestamp_fixed: EagerVec>, - pub timestamp: ComputedDerivedBlockFirst, + pub timestamp: ComputedHeightDerivedFirst, } diff --git a/crates/brk_computer/src/blocks/weight/import.rs b/crates/brk_computer/src/blocks/weight/import.rs index c03ac577e..9e677f35f 100644 --- a/crates/brk_computer/src/blocks/weight/import.rs +++ b/crates/brk_computer/src/blocks/weight/import.rs @@ -6,7 +6,7 @@ use vecdb::{Database, IterableCloneableVec}; use super::Vecs; use crate::{ indexes, - internal::{ComputedDerivedBlockFull, LazyBlockFull, WeightToFullness}, + internal::{ComputedHeightDerivedFull, LazyFromHeightFull, WeightToFullness}, }; impl Vecs { @@ -16,7 +16,7 @@ impl Vecs { indexer: &Indexer, indexes: &indexes::Vecs, ) -> Result { - let weight = ComputedDerivedBlockFull::forced_import( + let weight = ComputedHeightDerivedFull::forced_import( db, "block_weight", indexer.vecs.blocks.weight.boxed_clone(), @@ -24,7 +24,7 @@ impl Vecs { indexes, )?; - let fullness = LazyBlockFull::from_derived::( + let fullness = LazyFromHeightFull::from_derived::( "block_fullness", version, indexer.vecs.blocks.weight.boxed_clone(), diff --git a/crates/brk_computer/src/blocks/weight/vecs.rs b/crates/brk_computer/src/blocks/weight/vecs.rs index 7277675d2..2979de93e 100644 --- a/crates/brk_computer/src/blocks/weight/vecs.rs +++ b/crates/brk_computer/src/blocks/weight/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::{StoredF32, Weight}; -use crate::internal::{ComputedDerivedBlockFull, LazyBlockFull}; +use crate::internal::{ComputedHeightDerivedFull, LazyFromHeightFull}; #[derive(Clone, Traversable)] pub struct Vecs { - pub weight: ComputedDerivedBlockFull, - pub fullness: LazyBlockFull, + pub weight: ComputedHeightDerivedFull, + pub fullness: LazyFromHeightFull, } diff --git a/crates/brk_computer/src/cointime/activity/import.rs b/crates/brk_computer/src/cointime/activity/import.rs index 0517ebb25..ef21138bd 100644 --- a/crates/brk_computer/src/cointime/activity/import.rs +++ b/crates/brk_computer/src/cointime/activity/import.rs @@ -5,27 +5,27 @@ use vecdb::Database; use super::Vecs; use crate::{ indexes, - internal::{ComputedBlockLast, ComputedBlockSumCum}, + internal::{ComputedFromHeightLast, ComputedFromHeightSumCum}, }; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - coinblocks_created: ComputedBlockSumCum::forced_import( + coinblocks_created: ComputedFromHeightSumCum::forced_import( db, "coinblocks_created", version, indexes, )?, - coinblocks_stored: ComputedBlockSumCum::forced_import( + coinblocks_stored: ComputedFromHeightSumCum::forced_import( db, "coinblocks_stored", version, indexes, )?, - liveliness: ComputedBlockLast::forced_import(db, "liveliness", version, indexes)?, - vaultedness: ComputedBlockLast::forced_import(db, "vaultedness", version, indexes)?, - activity_to_vaultedness_ratio: ComputedBlockLast::forced_import( + liveliness: ComputedFromHeightLast::forced_import(db, "liveliness", version, indexes)?, + vaultedness: ComputedFromHeightLast::forced_import(db, "vaultedness", version, indexes)?, + activity_to_vaultedness_ratio: ComputedFromHeightLast::forced_import( db, "activity_to_vaultedness_ratio", version, diff --git a/crates/brk_computer/src/cointime/activity/vecs.rs b/crates/brk_computer/src/cointime/activity/vecs.rs index a3bdc7c33..99295c230 100644 --- a/crates/brk_computer/src/cointime/activity/vecs.rs +++ b/crates/brk_computer/src/cointime/activity/vecs.rs @@ -1,13 +1,13 @@ use brk_traversable::Traversable; use brk_types::StoredF64; -use crate::internal::{ComputedBlockLast, ComputedBlockSumCum}; +use crate::internal::{ComputedFromHeightLast, ComputedFromHeightSumCum}; #[derive(Clone, Traversable)] pub struct Vecs { - pub coinblocks_created: ComputedBlockSumCum, - pub coinblocks_stored: ComputedBlockSumCum, - pub liveliness: ComputedBlockLast, - pub vaultedness: ComputedBlockLast, - pub activity_to_vaultedness_ratio: ComputedBlockLast, + pub coinblocks_created: ComputedFromHeightSumCum, + pub coinblocks_stored: ComputedFromHeightSumCum, + pub liveliness: ComputedFromHeightLast, + pub vaultedness: ComputedFromHeightLast, + pub activity_to_vaultedness_ratio: ComputedFromHeightLast, } diff --git a/crates/brk_computer/src/cointime/adjusted/import.rs b/crates/brk_computer/src/cointime/adjusted/import.rs index dfe97fe4c..b8629b928 100644 --- a/crates/brk_computer/src/cointime/adjusted/import.rs +++ b/crates/brk_computer/src/cointime/adjusted/import.rs @@ -3,24 +3,24 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ComputedDateLast}; +use crate::{indexes, internal::ComputedFromDateLast}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - cointime_adj_inflation_rate: ComputedDateLast::forced_import( + cointime_adj_inflation_rate: ComputedFromDateLast::forced_import( db, "cointime_adj_inflation_rate", version, indexes, )?, - cointime_adj_tx_btc_velocity: ComputedDateLast::forced_import( + cointime_adj_tx_btc_velocity: ComputedFromDateLast::forced_import( db, "cointime_adj_tx_btc_velocity", version, indexes, )?, - cointime_adj_tx_usd_velocity: ComputedDateLast::forced_import( + cointime_adj_tx_usd_velocity: ComputedFromDateLast::forced_import( db, "cointime_adj_tx_usd_velocity", version, diff --git a/crates/brk_computer/src/cointime/adjusted/vecs.rs b/crates/brk_computer/src/cointime/adjusted/vecs.rs index cbf55d774..c36a02a19 100644 --- a/crates/brk_computer/src/cointime/adjusted/vecs.rs +++ b/crates/brk_computer/src/cointime/adjusted/vecs.rs @@ -1,11 +1,11 @@ use brk_traversable::Traversable; use brk_types::{StoredF32, StoredF64}; -use crate::internal::ComputedDateLast; +use crate::internal::ComputedFromDateLast; #[derive(Clone, Traversable)] pub struct Vecs { - pub cointime_adj_inflation_rate: ComputedDateLast, - pub cointime_adj_tx_btc_velocity: ComputedDateLast, - pub cointime_adj_tx_usd_velocity: ComputedDateLast, + pub cointime_adj_inflation_rate: ComputedFromDateLast, + pub cointime_adj_tx_btc_velocity: ComputedFromDateLast, + pub cointime_adj_tx_usd_velocity: ComputedFromDateLast, } diff --git a/crates/brk_computer/src/cointime/cap/import.rs b/crates/brk_computer/src/cointime/cap/import.rs index 4a6345072..310cab508 100644 --- a/crates/brk_computer/src/cointime/cap/import.rs +++ b/crates/brk_computer/src/cointime/cap/import.rs @@ -3,16 +3,16 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ComputedBlockLast}; +use crate::{indexes, internal::ComputedFromHeightLast}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - thermo_cap: ComputedBlockLast::forced_import(db, "thermo_cap", version, indexes)?, - investor_cap: ComputedBlockLast::forced_import(db, "investor_cap", version, indexes)?, - vaulted_cap: ComputedBlockLast::forced_import(db, "vaulted_cap", version, indexes)?, - active_cap: ComputedBlockLast::forced_import(db, "active_cap", version, indexes)?, - cointime_cap: ComputedBlockLast::forced_import(db, "cointime_cap", version, indexes)?, + thermo_cap: ComputedFromHeightLast::forced_import(db, "thermo_cap", version, indexes)?, + investor_cap: ComputedFromHeightLast::forced_import(db, "investor_cap", version, indexes)?, + vaulted_cap: ComputedFromHeightLast::forced_import(db, "vaulted_cap", version, indexes)?, + active_cap: ComputedFromHeightLast::forced_import(db, "active_cap", version, indexes)?, + cointime_cap: ComputedFromHeightLast::forced_import(db, "cointime_cap", version, indexes)?, }) } } diff --git a/crates/brk_computer/src/cointime/cap/vecs.rs b/crates/brk_computer/src/cointime/cap/vecs.rs index 00e3a7bcf..994503b33 100644 --- a/crates/brk_computer/src/cointime/cap/vecs.rs +++ b/crates/brk_computer/src/cointime/cap/vecs.rs @@ -1,13 +1,13 @@ use brk_traversable::Traversable; use brk_types::Dollars; -use crate::internal::ComputedBlockLast; +use crate::internal::ComputedFromHeightLast; #[derive(Clone, Traversable)] pub struct Vecs { - pub thermo_cap: ComputedBlockLast, - pub investor_cap: ComputedBlockLast, - pub vaulted_cap: ComputedBlockLast, - pub active_cap: ComputedBlockLast, - pub cointime_cap: ComputedBlockLast, + pub thermo_cap: ComputedFromHeightLast, + pub investor_cap: ComputedFromHeightLast, + pub vaulted_cap: ComputedFromHeightLast, + pub active_cap: ComputedFromHeightLast, + pub cointime_cap: ComputedFromHeightLast, } diff --git a/crates/brk_computer/src/cointime/compute.rs b/crates/brk_computer/src/cointime/compute.rs index 6e4970852..2e662cb2f 100644 --- a/crates/brk_computer/src/cointime/compute.rs +++ b/crates/brk_computer/src/cointime/compute.rs @@ -24,7 +24,6 @@ impl Vecs { self.supply.compute( indexes, starting_indexes, - price, distribution, &self.activity, exit, diff --git a/crates/brk_computer/src/cointime/import.rs b/crates/brk_computer/src/cointime/import.rs index e89ab5e5c..5a9a76754 100644 --- a/crates/brk_computer/src/cointime/import.rs +++ b/crates/brk_computer/src/cointime/import.rs @@ -20,12 +20,11 @@ impl Vecs { let db = Database::open(&parent_path.join(DB_NAME))?; db.set_min_len(PAGE_SIZE * 1_000_000)?; - let compute_dollars = price.is_some(); let version = parent_version + VERSION; let v1 = version + Version::ONE; let activity = ActivityVecs::forced_import(&db, version, indexes)?; - let supply = SupplyVecs::forced_import(&db, v1, indexes, compute_dollars)?; + let supply = SupplyVecs::forced_import(&db, v1, indexes, price)?; let value = ValueVecs::forced_import(&db, v1, indexes)?; let cap = CapVecs::forced_import(&db, v1, indexes)?; let pricing = PricingVecs::forced_import(&db, version, indexes, price)?; diff --git a/crates/brk_computer/src/cointime/pricing/import.rs b/crates/brk_computer/src/cointime/pricing/import.rs index 75e378eaa..adf645ad1 100644 --- a/crates/brk_computer/src/cointime/pricing/import.rs +++ b/crates/brk_computer/src/cointime/pricing/import.rs @@ -5,7 +5,7 @@ use vecdb::Database; use super::Vecs; use crate::{ indexes, - internal::{ComputedBlockLast, ComputedRatioVecsDate}, + internal::{ComputedFromHeightLast, ComputedFromDateRatio}, price, }; @@ -18,7 +18,7 @@ impl Vecs { ) -> Result { macro_rules! computed_h { ($name:expr) => { - ComputedBlockLast::forced_import(db, $name, version, indexes)? + ComputedFromHeightLast::forced_import(db, $name, version, indexes)? }; } @@ -30,7 +30,7 @@ impl Vecs { macro_rules! ratio_di { ($name:expr, $source:expr) => { - ComputedRatioVecsDate::forced_import( + ComputedFromDateRatio::forced_import( db, $name, Some($source), diff --git a/crates/brk_computer/src/cointime/pricing/vecs.rs b/crates/brk_computer/src/cointime/pricing/vecs.rs index b1b951e74..145cd0de6 100644 --- a/crates/brk_computer/src/cointime/pricing/vecs.rs +++ b/crates/brk_computer/src/cointime/pricing/vecs.rs @@ -1,16 +1,16 @@ use brk_traversable::Traversable; use brk_types::Dollars; -use crate::internal::{ComputedBlockLast, ComputedRatioVecsDate}; +use crate::internal::{ComputedFromHeightLast, ComputedFromDateRatio}; #[derive(Clone, Traversable)] pub struct Vecs { - pub vaulted_price: ComputedBlockLast, - pub vaulted_price_ratio: ComputedRatioVecsDate, - pub active_price: ComputedBlockLast, - pub active_price_ratio: ComputedRatioVecsDate, - pub true_market_mean: ComputedBlockLast, - pub true_market_mean_ratio: ComputedRatioVecsDate, - pub cointime_price: ComputedBlockLast, - pub cointime_price_ratio: ComputedRatioVecsDate, + pub vaulted_price: ComputedFromHeightLast, + pub vaulted_price_ratio: ComputedFromDateRatio, + pub active_price: ComputedFromHeightLast, + pub active_price_ratio: ComputedFromDateRatio, + pub true_market_mean: ComputedFromHeightLast, + pub true_market_mean_ratio: ComputedFromDateRatio, + pub cointime_price: ComputedFromHeightLast, + pub cointime_price_ratio: ComputedFromDateRatio, } diff --git a/crates/brk_computer/src/cointime/supply/compute.rs b/crates/brk_computer/src/cointime/supply/compute.rs index ae5b05584..858a5454a 100644 --- a/crates/brk_computer/src/cointime/supply/compute.rs +++ b/crates/brk_computer/src/cointime/supply/compute.rs @@ -3,14 +3,13 @@ use vecdb::Exit; use super::super::activity; use super::Vecs; -use crate::{ComputeIndexes, distribution, indexes, price}; +use crate::{ComputeIndexes, distribution, indexes}; impl Vecs { pub fn compute( &mut self, indexes: &indexes::Vecs, starting_indexes: &ComputeIndexes, - price: Option<&price::Vecs>, distribution: &distribution::Vecs, activity: &activity::Vecs, exit: &Exit, @@ -25,7 +24,7 @@ impl Vecs { .height; self.vaulted_supply - .compute_all(indexes, price, starting_indexes, exit, |vec| { + .compute_all(indexes, starting_indexes, exit, |vec| { vec.compute_multiply( starting_indexes.height, circulating_supply, @@ -36,7 +35,7 @@ impl Vecs { })?; self.active_supply - .compute_all(indexes, price, starting_indexes, exit, |vec| { + .compute_all(indexes, starting_indexes, exit, |vec| { vec.compute_multiply( starting_indexes.height, circulating_supply, diff --git a/crates/brk_computer/src/cointime/supply/import.rs b/crates/brk_computer/src/cointime/supply/import.rs index a5335380c..32d34a88f 100644 --- a/crates/brk_computer/src/cointime/supply/import.rs +++ b/crates/brk_computer/src/cointime/supply/import.rs @@ -3,29 +3,29 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ValueBlockLast}; +use crate::{indexes, internal::ValueFromHeightLast, price}; impl Vecs { pub fn forced_import( db: &Database, version: Version, indexes: &indexes::Vecs, - compute_dollars: bool, + price: Option<&price::Vecs>, ) -> Result { Ok(Self { - vaulted_supply: ValueBlockLast::forced_import( + vaulted_supply: ValueFromHeightLast::forced_import( db, "vaulted_supply", version, indexes, - compute_dollars, + price, )?, - active_supply: ValueBlockLast::forced_import( + active_supply: ValueFromHeightLast::forced_import( db, "active_supply", version, indexes, - compute_dollars, + price, )?, }) } diff --git a/crates/brk_computer/src/cointime/supply/vecs.rs b/crates/brk_computer/src/cointime/supply/vecs.rs index 9b9f9ee49..027794af1 100644 --- a/crates/brk_computer/src/cointime/supply/vecs.rs +++ b/crates/brk_computer/src/cointime/supply/vecs.rs @@ -1,9 +1,9 @@ use brk_traversable::Traversable; -use crate::internal::ValueBlockLast; +use crate::internal::ValueFromHeightLast; #[derive(Clone, Traversable)] pub struct Vecs { - pub vaulted_supply: ValueBlockLast, - pub active_supply: ValueBlockLast, + pub vaulted_supply: ValueFromHeightLast, + pub active_supply: ValueFromHeightLast, } diff --git a/crates/brk_computer/src/cointime/value/import.rs b/crates/brk_computer/src/cointime/value/import.rs index 0fc99be94..62b76496b 100644 --- a/crates/brk_computer/src/cointime/value/import.rs +++ b/crates/brk_computer/src/cointime/value/import.rs @@ -3,24 +3,24 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ComputedBlockSumCum}; +use crate::{indexes, internal::ComputedFromHeightSumCum}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - cointime_value_destroyed: ComputedBlockSumCum::forced_import( + cointime_value_destroyed: ComputedFromHeightSumCum::forced_import( db, "cointime_value_destroyed", version, indexes, )?, - cointime_value_created: ComputedBlockSumCum::forced_import( + cointime_value_created: ComputedFromHeightSumCum::forced_import( db, "cointime_value_created", version, indexes, )?, - cointime_value_stored: ComputedBlockSumCum::forced_import( + cointime_value_stored: ComputedFromHeightSumCum::forced_import( db, "cointime_value_stored", version, diff --git a/crates/brk_computer/src/cointime/value/vecs.rs b/crates/brk_computer/src/cointime/value/vecs.rs index 51fba2db7..6767b3066 100644 --- a/crates/brk_computer/src/cointime/value/vecs.rs +++ b/crates/brk_computer/src/cointime/value/vecs.rs @@ -1,11 +1,11 @@ use brk_traversable::Traversable; use brk_types::StoredF64; -use crate::internal::ComputedBlockSumCum; +use crate::internal::ComputedFromHeightSumCum; #[derive(Clone, Traversable)] pub struct Vecs { - pub cointime_value_destroyed: ComputedBlockSumCum, - pub cointime_value_created: ComputedBlockSumCum, - pub cointime_value_stored: ComputedBlockSumCum, + pub cointime_value_destroyed: ComputedFromHeightSumCum, + pub cointime_value_created: ComputedFromHeightSumCum, + pub cointime_value_stored: ComputedFromHeightSumCum, } diff --git a/crates/brk_computer/src/distribution/address/address_count.rs b/crates/brk_computer/src/distribution/address/address_count.rs index 25cc1740e..463084752 100644 --- a/crates/brk_computer/src/distribution/address/address_count.rs +++ b/crates/brk_computer/src/distribution/address/address_count.rs @@ -8,7 +8,7 @@ use vecdb::{ AnyStoredVec, AnyVec, Database, EagerVec, Exit, GenericStoredVec, PcoVec, TypedVecIterator, }; -use crate::{ComputeIndexes, indexes, internal::ComputedBlockLast}; +use crate::{ComputeIndexes, indexes, internal::ComputedFromHeightLast}; /// Address count per address type (runtime state). #[derive(Debug, Default, Deref, DerefMut)] @@ -78,11 +78,11 @@ impl From<(&AddressTypeToAddrCountVecs, Height)> for AddressTypeToAddressCount { /// Address count per address type, with height + derived indexes. #[derive(Clone, Deref, DerefMut, Traversable)] -pub struct AddressTypeToAddrCountVecs(ByAddressType>); +pub struct AddressTypeToAddrCountVecs(ByAddressType>); -impl From>> for AddressTypeToAddrCountVecs { +impl From>> for AddressTypeToAddrCountVecs { #[inline] - fn from(value: ByAddressType>) -> Self { + fn from(value: ByAddressType>) -> Self { Self(value) } } @@ -95,8 +95,8 @@ impl AddressTypeToAddrCountVecs { indexes: &indexes::Vecs, ) -> Result { Ok(Self::from( - ByAddressType::>::new_with_name(|type_name| { - ComputedBlockLast::forced_import( + ByAddressType::>::new_with_name(|type_name| { + ComputedFromHeightLast::forced_import( db, &format!("{type_name}_{name}"), version, @@ -224,7 +224,7 @@ impl AddressTypeToAddrCountVecs { #[derive(Clone, Traversable)] pub struct AddrCountVecs { - pub all: ComputedBlockLast, + pub all: ComputedFromHeightLast, #[traversable(flatten)] pub by_addresstype: AddressTypeToAddrCountVecs, } @@ -237,7 +237,7 @@ impl AddrCountVecs { indexes: &indexes::Vecs, ) -> Result { Ok(Self { - all: ComputedBlockLast::forced_import(db, name, version, indexes)?, + all: ComputedFromHeightLast::forced_import(db, name, version, indexes)?, by_addresstype: AddressTypeToAddrCountVecs::forced_import(db, name, version, indexes)?, }) } diff --git a/crates/brk_computer/src/distribution/address/indexes/any.rs b/crates/brk_computer/src/distribution/address/indexes/any.rs index eb74532f6..2221c60a6 100644 --- a/crates/brk_computer/src/distribution/address/indexes/any.rs +++ b/crates/brk_computer/src/distribution/address/indexes/any.rs @@ -1,3 +1,6 @@ +use std::thread; + +use brk_cohort::ByAddressType; use brk_error::{Error, Result}; use brk_traversable::Traversable; use brk_types::{ @@ -6,10 +9,14 @@ use brk_types::{ TypeIndex, Version, }; use rayon::prelude::*; +use rustc_hash::FxHashMap; use vecdb::{ - AnyStoredVec, BytesVec, Database, GenericStoredVec, ImportOptions, ImportableVec, Reader, Stamp, + AnyStoredVec, AnyVec, BytesVec, Database, GenericStoredVec, ImportOptions, ImportableVec, + Reader, Stamp, }; +use super::super::AddressTypeToTypeIndexMap; + const SAVED_STAMPED_CHANGES: u16 = 10; /// Macro to define AnyAddressIndexesVecs and its methods. @@ -75,6 +82,31 @@ macro_rules! define_any_address_indexes_vecs { Ok(()) } + /// Get length for a given address type. + pub fn len_of(&self, address_type: OutputType) -> usize { + match address_type { + $(OutputType::$variant => self.$field.len(),)* + _ => unreachable!("Invalid address type: {:?}", address_type), + } + } + + /// Update existing entry (must be within bounds). + pub fn update(&mut self, address_type: OutputType, typeindex: TypeIndex, index: AnyAddressIndex) -> Result<()> { + match address_type { + $(OutputType::$variant => self.$field.update(typeindex.into(), index)?,)* + _ => unreachable!("Invalid address type: {:?}", address_type), + } + Ok(()) + } + + /// Push new entry (must be at exactly len position). + pub fn push(&mut self, address_type: OutputType, index: AnyAddressIndex) { + match address_type { + $(OutputType::$variant => self.$field.push(index),)* + _ => unreachable!("Invalid address type: {:?}", address_type), + } + } + /// Write all address types with stamp. pub fn write(&mut self, stamp: Stamp, with_changes: bool) -> Result<()> { $(self.$field.stamped_write_maybe_with_changes(stamp, with_changes)?;)* @@ -100,3 +132,102 @@ define_any_address_indexes_vecs!( (p2wpkh, P2WPKH, P2WPKHAddressIndex), (p2wsh, P2WSH, P2WSHAddressIndex), ); + +impl AnyAddressIndexesVecs { + /// Process index updates in parallel by address type. + /// Accepts two maps (e.g. from empty and loaded processing) and merges per-thread. + /// Updates existing entries and pushes new ones (sorted). + /// Returns (update_count, push_count). + pub fn par_batch_update( + &mut self, + updates1: AddressTypeToTypeIndexMap, + updates2: AddressTypeToTypeIndexMap, + ) -> Result<(usize, usize)> { + let ByAddressType { + p2a: u1_p2a, + p2pk33: u1_p2pk33, + p2pk65: u1_p2pk65, + p2pkh: u1_p2pkh, + p2sh: u1_p2sh, + p2tr: u1_p2tr, + p2wpkh: u1_p2wpkh, + p2wsh: u1_p2wsh, + } = updates1.into_inner(); + + let ByAddressType { + p2a: u2_p2a, + p2pk33: u2_p2pk33, + p2pk65: u2_p2pk65, + p2pkh: u2_p2pkh, + p2sh: u2_p2sh, + p2tr: u2_p2tr, + p2wpkh: u2_p2wpkh, + p2wsh: u2_p2wsh, + } = updates2.into_inner(); + + let Self { + p2a, + p2pk33, + p2pk65, + p2pkh, + p2sh, + p2tr, + p2wpkh, + p2wsh, + } = self; + + thread::scope(|s| { + let h_p2a = s.spawn(|| process_single_type_merged(p2a, u1_p2a, u2_p2a)); + let h_p2pk33 = s.spawn(|| process_single_type_merged(p2pk33, u1_p2pk33, u2_p2pk33)); + let h_p2pk65 = s.spawn(|| process_single_type_merged(p2pk65, u1_p2pk65, u2_p2pk65)); + let h_p2pkh = s.spawn(|| process_single_type_merged(p2pkh, u1_p2pkh, u2_p2pkh)); + let h_p2sh = s.spawn(|| process_single_type_merged(p2sh, u1_p2sh, u2_p2sh)); + let h_p2tr = s.spawn(|| process_single_type_merged(p2tr, u1_p2tr, u2_p2tr)); + let h_p2wpkh = s.spawn(|| process_single_type_merged(p2wpkh, u1_p2wpkh, u2_p2wpkh)); + let h_p2wsh = s.spawn(|| process_single_type_merged(p2wsh, u1_p2wsh, u2_p2wsh)); + + let mut total_updates = 0usize; + let mut total_pushes = 0usize; + + for h in [ + h_p2a, h_p2pk33, h_p2pk65, h_p2pkh, h_p2sh, h_p2tr, h_p2wpkh, h_p2wsh, + ] { + let (updates, pushes) = h.join().unwrap()?; + total_updates += updates; + total_pushes += pushes; + } + + Ok((total_updates, total_pushes)) + }) + } +} + +/// Process updates for a single address type's BytesVec, merging two maps. +fn process_single_type_merged( + vec: &mut BytesVec, + map1: FxHashMap, + map2: FxHashMap, +) -> Result<(usize, usize)> { + let current_len = vec.len(); + let mut pushes = Vec::with_capacity(map1.len() + map2.len()); + let mut update_count = 0usize; + + for (typeindex, any_index) in map1.into_iter().chain(map2) { + if usize::from(typeindex) < current_len { + vec.update(I::from(usize::from(typeindex)), any_index)?; + update_count += 1; + } else { + pushes.push((typeindex, any_index)); + } + } + + let push_count = pushes.len(); + if !pushes.is_empty() { + pushes.sort_unstable_by_key(|(typeindex, _)| *typeindex); + for (_, any_index) in pushes { + vec.push(any_index); + } + } + + Ok((update_count, push_count)) +} diff --git a/crates/brk_computer/src/distribution/address/type_map/index_map.rs b/crates/brk_computer/src/distribution/address/type_map/index_map.rs index d88dab378..eeeb8195d 100644 --- a/crates/brk_computer/src/distribution/address/type_map/index_map.rs +++ b/crates/brk_computer/src/distribution/address/type_map/index_map.rs @@ -92,6 +92,11 @@ impl AddressTypeToTypeIndexMap { self.0.into_iter() } + /// Consume and return the inner ByAddressType. + pub fn into_inner(self) -> ByAddressType> { + self.0 + } + /// Iterate mutably over entries by address type. pub fn iter_mut(&mut self) -> impl Iterator)> { self.0.iter_mut() diff --git a/crates/brk_computer/src/distribution/block/cohort/address_updates.rs b/crates/brk_computer/src/distribution/block/cohort/address_updates.rs index 7b289eb36..3b36f8647 100644 --- a/crates/brk_computer/src/distribution/block/cohort/address_updates.rs +++ b/crates/brk_computer/src/distribution/block/cohort/address_updates.rs @@ -3,6 +3,7 @@ use brk_types::{ AnyAddressIndex, EmptyAddressData, EmptyAddressIndex, LoadedAddressData, LoadedAddressIndex, OutputType, TypeIndex, }; +use vecdb::AnyVec; use crate::distribution::{AddressTypeToTypeIndexMap, AddressesDataVecs}; @@ -51,9 +52,12 @@ pub fn process_loaded_addresses( addresses_data.loaded.update(index, data)?; } - // Phase 3: Pushes (fills holes, then grows) - let mut result = AddressTypeToTypeIndexMap::default(); - for (address_type, typeindex, data) in pushes { + // Phase 3: Pushes (fill holes first, then pure pushes) + let mut result = AddressTypeToTypeIndexMap::with_capacity(pushes.len() / 4); + let holes_count = addresses_data.loaded.holes().len(); + let mut pushes_iter = pushes.into_iter(); + + for (address_type, typeindex, data) in pushes_iter.by_ref().take(holes_count) { let index = addresses_data.loaded.fill_first_hole_or_push(data)?; result .get_mut(address_type) @@ -61,6 +65,18 @@ pub fn process_loaded_addresses( .insert(typeindex, AnyAddressIndex::from(index)); } + // Pure pushes - no holes remain + addresses_data.loaded.reserve_pushed(pushes_iter.len()); + let mut next_index = addresses_data.loaded.len(); + for (address_type, typeindex, data) in pushes_iter { + addresses_data.loaded.push(data); + result + .get_mut(address_type) + .unwrap() + .insert(typeindex, AnyAddressIndex::from(LoadedAddressIndex::from(next_index))); + next_index += 1; + } + Ok(result) } @@ -107,9 +123,12 @@ pub fn process_empty_addresses( addresses_data.empty.update(index, data)?; } - // Phase 3: Pushes (fills holes, then grows) - let mut result = AddressTypeToTypeIndexMap::default(); - for (address_type, typeindex, data) in pushes { + // Phase 3: Pushes (fill holes first, then pure pushes) + let mut result = AddressTypeToTypeIndexMap::with_capacity(pushes.len() / 4); + let holes_count = addresses_data.empty.holes().len(); + let mut pushes_iter = pushes.into_iter(); + + for (address_type, typeindex, data) in pushes_iter.by_ref().take(holes_count) { let index = addresses_data.empty.fill_first_hole_or_push(data)?; result .get_mut(address_type) @@ -117,5 +136,17 @@ pub fn process_empty_addresses( .insert(typeindex, AnyAddressIndex::from(index)); } + // Pure pushes - no holes remain + addresses_data.empty.reserve_pushed(pushes_iter.len()); + let mut next_index = addresses_data.empty.len(); + for (address_type, typeindex, data) in pushes_iter { + addresses_data.empty.push(data); + result + .get_mut(address_type) + .unwrap() + .insert(typeindex, AnyAddressIndex::from(EmptyAddressIndex::from(next_index))); + next_index += 1; + } + Ok(result) } diff --git a/crates/brk_computer/src/distribution/cohorts/address/vecs.rs b/crates/brk_computer/src/distribution/cohorts/address/vecs.rs index 813a2435d..51c73a3af 100644 --- a/crates/brk_computer/src/distribution/cohorts/address/vecs.rs +++ b/crates/brk_computer/src/distribution/cohorts/address/vecs.rs @@ -8,7 +8,7 @@ use rayon::prelude::*; use vecdb::{AnyStoredVec, AnyVec, Database, Exit, GenericStoredVec, IterableVec}; use crate::{ - ComputeIndexes, distribution::state::AddressCohortState, indexes, internal::ComputedBlockLast, + ComputeIndexes, distribution::state::AddressCohortState, indexes, internal::ComputedFromHeightLast, price, }; @@ -32,7 +32,7 @@ pub struct AddressCohortVecs { #[traversable(flatten)] pub metrics: CohortMetrics, - pub addr_count: ComputedBlockLast, + pub addr_count: ComputedFromHeightLast, } impl AddressCohortVecs { @@ -73,7 +73,7 @@ impl AddressCohortVecs { metrics: CohortMetrics::forced_import(&cfg, all_supply)?, - addr_count: ComputedBlockLast::forced_import( + addr_count: ComputedFromHeightLast::forced_import( db, &cfg.name("addr_count"), version + VERSION, diff --git a/crates/brk_computer/src/distribution/compute/write.rs b/crates/brk_computer/src/distribution/compute/write.rs index 5d7bc2d28..615204da6 100644 --- a/crates/brk_computer/src/distribution/compute/write.rs +++ b/crates/brk_computer/src/distribution/compute/write.rs @@ -33,15 +33,12 @@ pub fn process_address_updates( ) -> Result<()> { info!("Processing address updates..."); + let i = Instant::now(); let empty_result = process_empty_addresses(addresses_data, empty_updates)?; let loaded_result = process_loaded_addresses(addresses_data, loaded_updates)?; - let all_updates = empty_result.merge(loaded_result); + address_indexes.par_batch_update(empty_result, loaded_result)?; - for (address_type, sorted) in all_updates.into_sorted_iter() { - for (typeindex, any_index) in sorted { - address_indexes.update_or_push(address_type, typeindex, any_index)?; - } - } + info!("Processed address updates in {:?}", i.elapsed()); Ok(()) } diff --git a/crates/brk_computer/src/distribution/metrics/activity.rs b/crates/brk_computer/src/distribution/metrics/activity.rs index 841315558..cd93dd3e6 100644 --- a/crates/brk_computer/src/distribution/metrics/activity.rs +++ b/crates/brk_computer/src/distribution/metrics/activity.rs @@ -6,7 +6,7 @@ use vecdb::{AnyStoredVec, AnyVec, EagerVec, Exit, GenericStoredVec, ImportableVe use crate::{ ComputeIndexes, indexes, - internal::{ComputedBlockSumCum, LazyComputedValueBlockSumCum}, + internal::{ComputedFromHeightSumCum, LazyComputedValueFromHeightSumCum}, }; use super::ImportConfig; @@ -15,7 +15,7 @@ use super::ImportConfig; #[derive(Clone, Traversable)] pub struct ActivityMetrics { /// Total satoshis sent at each height + derived indexes - pub sent: LazyComputedValueBlockSumCum, + pub sent: LazyComputedValueFromHeightSumCum, /// Satoshi-blocks destroyed (supply * blocks_old when spent) pub satblocks_destroyed: EagerVec>, @@ -24,17 +24,17 @@ pub struct ActivityMetrics { pub satdays_destroyed: EagerVec>, /// Coin-blocks destroyed (in BTC rather than sats) - pub coinblocks_destroyed: ComputedBlockSumCum, + pub coinblocks_destroyed: ComputedFromHeightSumCum, /// Coin-days destroyed (in BTC rather than sats) - pub coindays_destroyed: ComputedBlockSumCum, + pub coindays_destroyed: ComputedFromHeightSumCum, } impl ActivityMetrics { /// Import activity metrics from database. pub fn forced_import(cfg: &ImportConfig) -> Result { Ok(Self { - sent: LazyComputedValueBlockSumCum::forced_import( + sent: LazyComputedValueFromHeightSumCum::forced_import( cfg.db, &cfg.name("sent"), cfg.version, @@ -54,14 +54,14 @@ impl ActivityMetrics { cfg.version, )?, - coinblocks_destroyed: ComputedBlockSumCum::forced_import( + coinblocks_destroyed: ComputedFromHeightSumCum::forced_import( cfg.db, &cfg.name("coinblocks_destroyed"), cfg.version, cfg.indexes, )?, - coindays_destroyed: ComputedBlockSumCum::forced_import( + coindays_destroyed: ComputedFromHeightSumCum::forced_import( cfg.db, &cfg.name("coindays_destroyed"), cfg.version, diff --git a/crates/brk_computer/src/distribution/metrics/cost_basis.rs b/crates/brk_computer/src/distribution/metrics/cost_basis.rs index f6bdcea9a..25fe0bca6 100644 --- a/crates/brk_computer/src/distribution/metrics/cost_basis.rs +++ b/crates/brk_computer/src/distribution/metrics/cost_basis.rs @@ -8,7 +8,7 @@ use crate::{ ComputeIndexes, distribution::state::CohortState, indexes, - internal::{ComputedBlockLast, CostBasisPercentiles}, + internal::{ComputedFromHeightLast, CostBasisPercentiles}, }; use super::ImportConfig; @@ -17,10 +17,10 @@ use super::ImportConfig; #[derive(Clone, Traversable)] pub struct CostBasisMetrics { /// Minimum cost basis for any UTXO at this height - pub min: ComputedBlockLast, + pub min: ComputedFromHeightLast, /// Maximum cost basis for any UTXO at this height - pub max: ComputedBlockLast, + pub max: ComputedFromHeightLast, /// Cost basis distribution percentiles (median, quartiles, etc.) pub percentiles: Option, @@ -32,13 +32,13 @@ impl CostBasisMetrics { let extended = cfg.extended(); Ok(Self { - min: ComputedBlockLast::forced_import( + min: ComputedFromHeightLast::forced_import( cfg.db, &cfg.name("min_cost_basis"), cfg.version, cfg.indexes, )?, - max: ComputedBlockLast::forced_import( + max: ComputedFromHeightLast::forced_import( cfg.db, &cfg.name("max_cost_basis"), cfg.version, diff --git a/crates/brk_computer/src/distribution/metrics/mod.rs b/crates/brk_computer/src/distribution/metrics/mod.rs index c0c03f61f..0ce788c3f 100644 --- a/crates/brk_computer/src/distribution/metrics/mod.rs +++ b/crates/brk_computer/src/distribution/metrics/mod.rs @@ -313,7 +313,7 @@ impl CohortMetrics { exit: &Exit, ) -> Result<()> { self.supply - .compute_rest_part1(indexes, price, starting_indexes, exit)?; + .compute_rest_part1(indexes, starting_indexes, exit)?; self.outputs.compute_rest(indexes, starting_indexes, exit)?; self.activity .compute_rest_part1(indexes, starting_indexes, exit)?; diff --git a/crates/brk_computer/src/distribution/metrics/outputs.rs b/crates/brk_computer/src/distribution/metrics/outputs.rs index c3031c018..6723060d9 100644 --- a/crates/brk_computer/src/distribution/metrics/outputs.rs +++ b/crates/brk_computer/src/distribution/metrics/outputs.rs @@ -4,21 +4,21 @@ use brk_types::{Height, StoredU64}; use rayon::prelude::*; use vecdb::{AnyStoredVec, AnyVec, Exit, GenericStoredVec}; -use crate::{ComputeIndexes, indexes, internal::ComputedBlockLast}; +use crate::{ComputeIndexes, indexes, internal::ComputedFromHeightLast}; use super::ImportConfig; /// Output metrics for a cohort. #[derive(Clone, Traversable)] pub struct OutputsMetrics { - pub utxo_count: ComputedBlockLast, + pub utxo_count: ComputedFromHeightLast, } impl OutputsMetrics { /// Import output metrics from database. pub fn forced_import(cfg: &ImportConfig) -> Result { Ok(Self { - utxo_count: ComputedBlockLast::forced_import( + utxo_count: ComputedFromHeightLast::forced_import( cfg.db, &cfg.name("utxo_count"), cfg.version, diff --git a/crates/brk_computer/src/distribution/metrics/realized.rs b/crates/brk_computer/src/distribution/metrics/realized.rs index f1461ef8f..cae98efb2 100644 --- a/crates/brk_computer/src/distribution/metrics/realized.rs +++ b/crates/brk_computer/src/distribution/metrics/realized.rs @@ -12,9 +12,9 @@ use crate::{ distribution::state::RealizedState, indexes, internal::{ - ComputedBlockLast, ComputedBlockSum, ComputedBlockSumCum, ComputedDateLast, - ComputedRatioVecsDate, DollarsMinus, LazyBinaryBlockSum, LazyBinaryBlockSumCum, - LazyBlockSum, LazyBlockSumCum, LazyDateLast, PercentageDollarsF32, StoredF32Identity, + ComputedFromHeightLast, ComputedFromHeightSum, ComputedFromHeightSumCum, ComputedFromDateLast, + ComputedFromDateRatio, DollarsMinus, LazyBinaryFromHeightSum, LazyBinaryFromHeightSumCum, + LazyFromHeightSum, LazyFromHeightSumCum, LazyFromDateLast, PercentageDollarsF32, StoredF32Identity, }, price, }; @@ -25,39 +25,39 @@ use super::ImportConfig; #[derive(Clone, Traversable)] pub struct RealizedMetrics { // === Realized Cap === - pub realized_cap: ComputedBlockLast, - pub realized_price: ComputedBlockLast, - pub realized_price_extra: ComputedRatioVecsDate, - pub realized_cap_rel_to_own_market_cap: Option>, - pub realized_cap_30d_delta: ComputedDateLast, + pub realized_cap: ComputedFromHeightLast, + pub realized_price: ComputedFromHeightLast, + pub realized_price_extra: ComputedFromDateRatio, + pub realized_cap_rel_to_own_market_cap: Option>, + pub realized_cap_30d_delta: ComputedFromDateLast, // === MVRV (Market Value to Realized Value) === // Proxy for realized_price_extra.ratio (close / realized_price = market_cap / realized_cap) - pub mvrv: LazyDateLast, + pub mvrv: LazyFromDateLast, // === Realized Profit/Loss === - pub realized_profit: ComputedBlockSumCum, - pub realized_loss: ComputedBlockSumCum, - pub neg_realized_loss: LazyBlockSumCum, - pub net_realized_pnl: ComputedBlockSumCum, - pub realized_value: ComputedBlockSum, + pub realized_profit: ComputedFromHeightSumCum, + pub realized_loss: ComputedFromHeightSumCum, + pub neg_realized_loss: LazyFromHeightSumCum, + pub net_realized_pnl: ComputedFromHeightSumCum, + pub realized_value: ComputedFromHeightSum, // === Realized vs Realized Cap Ratios (lazy) === - pub realized_profit_rel_to_realized_cap: LazyBinaryBlockSumCum, - pub realized_loss_rel_to_realized_cap: LazyBinaryBlockSumCum, - pub net_realized_pnl_rel_to_realized_cap: LazyBinaryBlockSumCum, + pub realized_profit_rel_to_realized_cap: LazyBinaryFromHeightSumCum, + pub realized_loss_rel_to_realized_cap: LazyBinaryFromHeightSumCum, + pub net_realized_pnl_rel_to_realized_cap: LazyBinaryFromHeightSumCum, // === Total Realized PnL === - pub total_realized_pnl: LazyBlockSum, + pub total_realized_pnl: LazyFromHeightSum, pub realized_profit_to_loss_ratio: Option>>, // === Value Created/Destroyed === - pub value_created: ComputedBlockSum, - pub value_destroyed: ComputedBlockSum, + pub value_created: ComputedFromHeightSum, + pub value_destroyed: ComputedFromHeightSum, // === Adjusted Value (lazy: cohort - up_to_1h) === - pub adjusted_value_created: Option>, - pub adjusted_value_destroyed: Option>, + pub adjusted_value_created: Option>, + pub adjusted_value_destroyed: Option>, // === SOPR (Spent Output Profit Ratio) === pub sopr: EagerVec>, @@ -73,9 +73,9 @@ pub struct RealizedMetrics { pub sell_side_risk_ratio_30d_ema: EagerVec>, // === Net Realized PnL Deltas === - pub net_realized_pnl_cumulative_30d_delta: ComputedDateLast, - pub net_realized_pnl_cumulative_30d_delta_rel_to_realized_cap: ComputedDateLast, - pub net_realized_pnl_cumulative_30d_delta_rel_to_market_cap: ComputedDateLast, + pub net_realized_pnl_cumulative_30d_delta: ComputedFromDateLast, + pub net_realized_pnl_cumulative_30d_delta_rel_to_realized_cap: ComputedFromDateLast, + pub net_realized_pnl_cumulative_30d_delta_rel_to_market_cap: ComputedFromDateLast, } impl RealizedMetrics { @@ -87,35 +87,35 @@ impl RealizedMetrics { let compute_adjusted = cfg.compute_adjusted(); // Import combined types using forced_import which handles height + derived - let realized_cap = ComputedBlockLast::forced_import( + let realized_cap = ComputedFromHeightLast::forced_import( cfg.db, &cfg.name("realized_cap"), cfg.version, cfg.indexes, )?; - let realized_profit = ComputedBlockSumCum::forced_import( + let realized_profit = ComputedFromHeightSumCum::forced_import( cfg.db, &cfg.name("realized_profit"), cfg.version, cfg.indexes, )?; - let realized_loss = ComputedBlockSumCum::forced_import( + let realized_loss = ComputedFromHeightSumCum::forced_import( cfg.db, &cfg.name("realized_loss"), cfg.version, cfg.indexes, )?; - let neg_realized_loss = LazyBlockSumCum::from_computed::( + let neg_realized_loss = LazyFromHeightSumCum::from_computed::( &cfg.name("neg_realized_loss"), cfg.version + v1, realized_loss.height.boxed_clone(), &realized_loss, ); - let net_realized_pnl = ComputedBlockSumCum::forced_import( + let net_realized_pnl = ComputedFromHeightSumCum::forced_import( cfg.db, &cfg.name("net_realized_pnl"), cfg.version, @@ -123,7 +123,7 @@ impl RealizedMetrics { )?; // realized_value is the source for total_realized_pnl (they're identical) - let realized_value = ComputedBlockSum::forced_import( + let realized_value = ComputedFromHeightSum::forced_import( cfg.db, &cfg.name("realized_value"), cfg.version, @@ -131,7 +131,7 @@ impl RealizedMetrics { )?; // total_realized_pnl is a lazy alias to realized_value - let total_realized_pnl = LazyBlockSum::from_computed::( + let total_realized_pnl = LazyFromHeightSum::from_computed::( &cfg.name("total_realized_pnl"), cfg.version + v1, realized_value.height.boxed_clone(), @@ -140,7 +140,7 @@ impl RealizedMetrics { // Construct lazy ratio vecs let realized_profit_rel_to_realized_cap = - LazyBinaryBlockSumCum::from_computed_last::( + LazyBinaryFromHeightSumCum::from_computed_last::( &cfg.name("realized_profit_rel_to_realized_cap"), cfg.version + v1, realized_profit.height.boxed_clone(), @@ -150,7 +150,7 @@ impl RealizedMetrics { ); let realized_loss_rel_to_realized_cap = - LazyBinaryBlockSumCum::from_computed_last::( + LazyBinaryFromHeightSumCum::from_computed_last::( &cfg.name("realized_loss_rel_to_realized_cap"), cfg.version + v1, realized_loss.height.boxed_clone(), @@ -160,7 +160,7 @@ impl RealizedMetrics { ); let net_realized_pnl_rel_to_realized_cap = - LazyBinaryBlockSumCum::from_computed_last::( + LazyBinaryFromHeightSumCum::from_computed_last::( &cfg.name("net_realized_pnl_rel_to_realized_cap"), cfg.version + v1, net_realized_pnl.height.boxed_clone(), @@ -169,21 +169,21 @@ impl RealizedMetrics { &realized_cap, ); - let realized_price = ComputedBlockLast::forced_import( + let realized_price = ComputedFromHeightLast::forced_import( cfg.db, &cfg.name("realized_price"), cfg.version + v1, cfg.indexes, )?; - let value_created = ComputedBlockSum::forced_import( + let value_created = ComputedFromHeightSum::forced_import( cfg.db, &cfg.name("value_created"), cfg.version, cfg.indexes, )?; - let value_destroyed = ComputedBlockSum::forced_import( + let value_destroyed = ComputedFromHeightSum::forced_import( cfg.db, &cfg.name("value_destroyed"), cfg.version, @@ -194,7 +194,7 @@ impl RealizedMetrics { let adjusted_value_created = (compute_adjusted && cfg.up_to_1h_realized.is_some()).then(|| { let up_to_1h = cfg.up_to_1h_realized.unwrap(); - LazyBinaryBlockSum::from_computed::( + LazyBinaryFromHeightSum::from_computed::( &cfg.name("adjusted_value_created"), cfg.version, &value_created, @@ -204,7 +204,7 @@ impl RealizedMetrics { let adjusted_value_destroyed = (compute_adjusted && cfg.up_to_1h_realized.is_some()).then(|| { let up_to_1h = cfg.up_to_1h_realized.unwrap(); - LazyBinaryBlockSum::from_computed::( + LazyBinaryFromHeightSum::from_computed::( &cfg.name("adjusted_value_destroyed"), cfg.version, &value_destroyed, @@ -213,7 +213,7 @@ impl RealizedMetrics { }); // Create realized_price_extra first so we can reference its ratio for MVRV proxy - let realized_price_extra = ComputedRatioVecsDate::forced_import( + let realized_price_extra = ComputedFromDateRatio::forced_import( cfg.db, &cfg.name("realized_price"), Some(&realized_price), @@ -225,7 +225,7 @@ impl RealizedMetrics { // MVRV is a lazy proxy for realized_price_extra.ratio // ratio = close / realized_price = market_cap / realized_cap = MVRV - let mvrv = LazyDateLast::from_source::( + let mvrv = LazyFromDateLast::from_source::( &cfg.name("mvrv"), cfg.version, &realized_price_extra.ratio, @@ -238,7 +238,7 @@ impl RealizedMetrics { realized_price_extra, realized_cap_rel_to_own_market_cap: extended .then(|| { - ComputedBlockLast::forced_import( + ComputedFromHeightLast::forced_import( cfg.db, &cfg.name("realized_cap_rel_to_own_market_cap"), cfg.version, @@ -246,7 +246,7 @@ impl RealizedMetrics { ) }) .transpose()?, - realized_cap_30d_delta: ComputedDateLast::forced_import( + realized_cap_30d_delta: ComputedFromDateLast::forced_import( cfg.db, &cfg.name("realized_cap_30d_delta"), cfg.version, @@ -338,21 +338,21 @@ impl RealizedMetrics { )?, // === Net Realized PnL Deltas === - net_realized_pnl_cumulative_30d_delta: ComputedDateLast::forced_import( + net_realized_pnl_cumulative_30d_delta: ComputedFromDateLast::forced_import( cfg.db, &cfg.name("net_realized_pnl_cumulative_30d_delta"), cfg.version + v3, cfg.indexes, )?, net_realized_pnl_cumulative_30d_delta_rel_to_realized_cap: - ComputedDateLast::forced_import( + ComputedFromDateLast::forced_import( cfg.db, &cfg.name("net_realized_pnl_cumulative_30d_delta_rel_to_realized_cap"), cfg.version + v3, cfg.indexes, )?, net_realized_pnl_cumulative_30d_delta_rel_to_market_cap: - ComputedDateLast::forced_import( + ComputedFromDateLast::forced_import( cfg.db, &cfg.name("net_realized_pnl_cumulative_30d_delta_rel_to_market_cap"), cfg.version + v3, diff --git a/crates/brk_computer/src/distribution/metrics/relative.rs b/crates/brk_computer/src/distribution/metrics/relative.rs index ecce33bf5..b624b614b 100644 --- a/crates/brk_computer/src/distribution/metrics/relative.rs +++ b/crates/brk_computer/src/distribution/metrics/relative.rs @@ -4,7 +4,7 @@ use brk_types::{Dollars, Sats, StoredF32, StoredF64, Version}; use vecdb::IterableCloneableVec; use crate::internal::{ - LazyBinaryBlockLast, LazyBinaryDateLast, NegPercentageDollarsF32, NegRatio32, + LazyBinaryFromHeightLast, LazyBinaryFromDateLast, NegPercentageDollarsF32, NegRatio32, PercentageDollarsF32, PercentageSatsF64, Ratio32, }; @@ -15,49 +15,49 @@ use super::{ImportConfig, SupplyMetrics, UnrealizedMetrics}; #[derive(Clone, Traversable)] pub struct RelativeMetrics { // === Supply Relative to Circulating Supply (lazy from global supply) === - pub supply_rel_to_circulating_supply: Option>, + pub supply_rel_to_circulating_supply: Option>, // === Supply in Profit/Loss Relative to Own Supply (lazy) === - pub supply_in_profit_rel_to_own_supply: LazyBinaryBlockLast, - pub supply_in_loss_rel_to_own_supply: LazyBinaryBlockLast, + pub supply_in_profit_rel_to_own_supply: LazyBinaryFromHeightLast, + pub supply_in_loss_rel_to_own_supply: LazyBinaryFromHeightLast, // === Supply in Profit/Loss Relative to Circulating Supply (lazy from global supply) === pub supply_in_profit_rel_to_circulating_supply: - Option>, + Option>, pub supply_in_loss_rel_to_circulating_supply: - Option>, + Option>, // === Unrealized vs Market Cap (lazy from global market cap) === pub unrealized_profit_rel_to_market_cap: - Option>, - pub unrealized_loss_rel_to_market_cap: Option>, + Option>, + pub unrealized_loss_rel_to_market_cap: Option>, pub neg_unrealized_loss_rel_to_market_cap: - Option>, + Option>, pub net_unrealized_pnl_rel_to_market_cap: - Option>, + Option>, // === NUPL (Net Unrealized Profit/Loss) === - pub nupl: Option>, + pub nupl: Option>, // === Unrealized vs Own Market Cap (lazy) === pub unrealized_profit_rel_to_own_market_cap: - Option>, + Option>, pub unrealized_loss_rel_to_own_market_cap: - Option>, + Option>, pub neg_unrealized_loss_rel_to_own_market_cap: - Option>, + Option>, pub net_unrealized_pnl_rel_to_own_market_cap: - Option>, + Option>, // === Unrealized vs Own Total Unrealized PnL (lazy) === pub unrealized_profit_rel_to_own_total_unrealized_pnl: - Option>, + Option>, pub unrealized_loss_rel_to_own_total_unrealized_pnl: - Option>, + Option>, pub neg_unrealized_loss_rel_to_own_total_unrealized_pnl: - Option>, + Option>, pub net_unrealized_pnl_rel_to_own_total_unrealized_pnl: - Option>, + Option>, } impl RelativeMetrics { @@ -91,7 +91,7 @@ impl RelativeMetrics { supply_rel_to_circulating_supply: (compute_rel_to_all && global_supply_sats_dates.is_some()) .then(|| { - LazyBinaryDateLast::from_both_derived_last::( + LazyBinaryFromDateLast::from_both_derived_last::( &cfg.name("supply_rel_to_circulating_supply"), cfg.version + v1, supply.total.sats.rest.dateindex.boxed_clone(), @@ -103,7 +103,7 @@ impl RelativeMetrics { // === Supply in Profit/Loss Relative to Own Supply (lazy) === supply_in_profit_rel_to_own_supply: - LazyBinaryBlockLast::from_height_difficultyepoch_dates::( + LazyBinaryFromHeightLast::from_height_difficultyepoch_dates::( &cfg.name("supply_in_profit_rel_to_own_supply"), cfg.version + v1, unrealized.supply_in_profit.height.boxed_clone(), @@ -120,7 +120,7 @@ impl RelativeMetrics { &supply.total.sats.rest.dates, ), supply_in_loss_rel_to_own_supply: - LazyBinaryBlockLast::from_height_difficultyepoch_dates::( + LazyBinaryFromHeightLast::from_height_difficultyepoch_dates::( &cfg.name("supply_in_loss_rel_to_own_supply"), cfg.version + v1, unrealized.supply_in_loss.height.boxed_clone(), @@ -141,7 +141,7 @@ impl RelativeMetrics { supply_in_profit_rel_to_circulating_supply: (compute_rel_to_all && global_supply_sats_height.is_some()) .then(|| { - LazyBinaryBlockLast::from_height_difficultyepoch_dates::( + LazyBinaryFromHeightLast::from_height_difficultyepoch_dates::( &cfg.name("supply_in_profit_rel_to_circulating_supply"), cfg.version + v1, unrealized.supply_in_profit.height.boxed_clone(), @@ -161,7 +161,7 @@ impl RelativeMetrics { supply_in_loss_rel_to_circulating_supply: (compute_rel_to_all && global_supply_sats_height.is_some()) .then(|| { - LazyBinaryBlockLast::from_height_difficultyepoch_dates::( + LazyBinaryFromHeightLast::from_height_difficultyepoch_dates::( &cfg.name("supply_in_loss_rel_to_circulating_supply"), cfg.version + v1, unrealized.supply_in_loss.height.boxed_clone(), @@ -182,8 +182,10 @@ impl RelativeMetrics { // === Unrealized vs Market Cap (lazy from global market cap) === unrealized_profit_rel_to_market_cap: global_market_cap.map(|mc| { - LazyBinaryBlockLast::from_computed_height_date_and_block_last::< + LazyBinaryFromHeightLast::from_computed_height_date_and_lazy_binary_block_last::< PercentageDollarsF32, + _, + _, >( &cfg.name("unrealized_profit_rel_to_market_cap"), cfg.version + v2, @@ -193,8 +195,10 @@ impl RelativeMetrics { }), unrealized_loss_rel_to_market_cap: global_market_cap.map(|mc| { - LazyBinaryBlockLast::from_computed_height_date_and_block_last::< + LazyBinaryFromHeightLast::from_computed_height_date_and_lazy_binary_block_last::< PercentageDollarsF32, + _, + _, >( &cfg.name("unrealized_loss_rel_to_market_cap"), cfg.version + v2, @@ -203,8 +207,10 @@ impl RelativeMetrics { ) }), neg_unrealized_loss_rel_to_market_cap: global_market_cap.map(|mc| { - LazyBinaryBlockLast::from_computed_height_date_and_block_last::< + LazyBinaryFromHeightLast::from_computed_height_date_and_lazy_binary_block_last::< NegPercentageDollarsF32, + _, + _, >( &cfg.name("neg_unrealized_loss_rel_to_market_cap"), cfg.version + v2, @@ -213,10 +219,12 @@ impl RelativeMetrics { ) }), net_unrealized_pnl_rel_to_market_cap: global_market_cap.map(|mc| { - LazyBinaryBlockLast::from_binary_block_and_computed_block_last::< + LazyBinaryFromHeightLast::from_binary_block_and_lazy_binary_block_last::< PercentageDollarsF32, _, _, + _, + _, >( &cfg.name("net_unrealized_pnl_rel_to_market_cap"), cfg.version + v2, @@ -227,10 +235,12 @@ impl RelativeMetrics { // NUPL is a proxy for net_unrealized_pnl_rel_to_market_cap nupl: global_market_cap.map(|mc| { - LazyBinaryBlockLast::from_binary_block_and_computed_block_last::< + LazyBinaryFromHeightLast::from_binary_block_and_lazy_binary_block_last::< PercentageDollarsF32, _, _, + _, + _, >( &cfg.name("nupl"), cfg.version + v2, @@ -243,8 +253,10 @@ impl RelativeMetrics { unrealized_profit_rel_to_own_market_cap: (extended && compute_rel_to_all) .then(|| { own_market_cap.map(|mc| { - LazyBinaryBlockLast::from_computed_height_date_and_block_last::< + LazyBinaryFromHeightLast::from_computed_height_date_and_lazy_binary_block_last::< PercentageDollarsF32, + _, + _, >( &cfg.name("unrealized_profit_rel_to_own_market_cap"), cfg.version + v2, @@ -257,8 +269,10 @@ impl RelativeMetrics { unrealized_loss_rel_to_own_market_cap: (extended && compute_rel_to_all) .then(|| { own_market_cap.map(|mc| { - LazyBinaryBlockLast::from_computed_height_date_and_block_last::< + LazyBinaryFromHeightLast::from_computed_height_date_and_lazy_binary_block_last::< PercentageDollarsF32, + _, + _, >( &cfg.name("unrealized_loss_rel_to_own_market_cap"), cfg.version + v2, @@ -271,8 +285,10 @@ impl RelativeMetrics { neg_unrealized_loss_rel_to_own_market_cap: (extended && compute_rel_to_all) .then(|| { own_market_cap.map(|mc| { - LazyBinaryBlockLast::from_computed_height_date_and_block_last::< + LazyBinaryFromHeightLast::from_computed_height_date_and_lazy_binary_block_last::< NegPercentageDollarsF32, + _, + _, >( &cfg.name("neg_unrealized_loss_rel_to_own_market_cap"), cfg.version + v2, @@ -285,10 +301,12 @@ impl RelativeMetrics { net_unrealized_pnl_rel_to_own_market_cap: (extended && compute_rel_to_all) .then(|| { own_market_cap.map(|mc| { - LazyBinaryBlockLast::from_binary_block_and_computed_block_last::< + LazyBinaryFromHeightLast::from_binary_block_and_lazy_binary_block_last::< PercentageDollarsF32, _, _, + _, + _, >( &cfg.name("net_unrealized_pnl_rel_to_own_market_cap"), cfg.version + v2, @@ -301,7 +319,7 @@ impl RelativeMetrics { // === Unrealized vs Own Total Unrealized PnL (lazy, optional) === unrealized_profit_rel_to_own_total_unrealized_pnl: extended.then(|| { - LazyBinaryBlockLast::from_computed_height_date_and_binary_block::( + LazyBinaryFromHeightLast::from_computed_height_date_and_binary_block::( &cfg.name("unrealized_profit_rel_to_own_total_unrealized_pnl"), cfg.version, &unrealized.unrealized_profit, @@ -309,7 +327,7 @@ impl RelativeMetrics { ) }), unrealized_loss_rel_to_own_total_unrealized_pnl: extended.then(|| { - LazyBinaryBlockLast::from_computed_height_date_and_binary_block::( + LazyBinaryFromHeightLast::from_computed_height_date_and_binary_block::( &cfg.name("unrealized_loss_rel_to_own_total_unrealized_pnl"), cfg.version, &unrealized.unrealized_loss, @@ -317,7 +335,7 @@ impl RelativeMetrics { ) }), neg_unrealized_loss_rel_to_own_total_unrealized_pnl: extended.then(|| { - LazyBinaryBlockLast::from_computed_height_date_and_binary_block::( + LazyBinaryFromHeightLast::from_computed_height_date_and_binary_block::( &cfg.name("neg_unrealized_loss_rel_to_own_total_unrealized_pnl"), cfg.version, &unrealized.unrealized_loss, @@ -325,7 +343,7 @@ impl RelativeMetrics { ) }), net_unrealized_pnl_rel_to_own_total_unrealized_pnl: extended.then(|| { - LazyBinaryBlockLast::from_both_binary_block::( + LazyBinaryFromHeightLast::from_both_binary_block::( &cfg.name("net_unrealized_pnl_rel_to_own_total_unrealized_pnl"), cfg.version + v1, &unrealized.net_unrealized_pnl, diff --git a/crates/brk_computer/src/distribution/metrics/supply.rs b/crates/brk_computer/src/distribution/metrics/supply.rs index 28fe50037..36452b91d 100644 --- a/crates/brk_computer/src/distribution/metrics/supply.rs +++ b/crates/brk_computer/src/distribution/metrics/supply.rs @@ -9,10 +9,9 @@ use vecdb::{AnyStoredVec, AnyVec, Exit, GenericStoredVec}; use crate::{ indexes, internal::{ - HalfClosePriceTimesSats, HalveDollars, HalveSats, HalveSatsToBitcoin, LazyBinaryValueBlockLast, - ValueBlockLast, + HalfClosePriceTimesSats, HalveDollars, HalveSats, HalveSatsToBitcoin, LazyBinaryValueFromHeightLast, + ValueFromHeightLast, }, - price, }; use super::ImportConfig; @@ -20,24 +19,22 @@ use super::ImportConfig; /// Supply metrics for a cohort. #[derive(Clone, Traversable)] pub struct SupplyMetrics { - pub total: ValueBlockLast, - pub halved: LazyBinaryValueBlockLast, + pub total: ValueFromHeightLast, + pub halved: LazyBinaryValueFromHeightLast, } impl SupplyMetrics { /// Import supply metrics from database. pub fn forced_import(cfg: &ImportConfig) -> Result { - let compute_dollars = cfg.compute_dollars(); - - let supply = ValueBlockLast::forced_import( + let supply = ValueFromHeightLast::forced_import( cfg.db, &cfg.name("supply"), cfg.version, cfg.indexes, - compute_dollars, + cfg.price, )?; - let supply_half = LazyBinaryValueBlockLast::from_block_source::< + let supply_half = LazyBinaryValueFromHeightLast::from_block_source::< HalveSats, HalveSatsToBitcoin, HalfClosePriceTimesSats, @@ -100,11 +97,9 @@ impl SupplyMetrics { pub fn compute_rest_part1( &mut self, indexes: &indexes::Vecs, - price: Option<&price::Vecs>, starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { - self.total - .compute_rest(indexes, price, starting_indexes, exit) + self.total.compute_rest(indexes, starting_indexes, exit) } } diff --git a/crates/brk_computer/src/distribution/metrics/unrealized.rs b/crates/brk_computer/src/distribution/metrics/unrealized.rs index 8b0a71acf..ea129ebb0 100644 --- a/crates/brk_computer/src/distribution/metrics/unrealized.rs +++ b/crates/brk_computer/src/distribution/metrics/unrealized.rs @@ -8,8 +8,8 @@ use crate::{ ComputeIndexes, distribution::state::UnrealizedState, internal::{ - ComputedHeightDateLast, DollarsMinus, DollarsPlus, LazyBinaryBlockLast, LazyBlockLast, - ValueHeightDateLast, + ComputedFromHeightAndDateLast, DollarsMinus, DollarsPlus, LazyBinaryFromHeightLast, LazyFromHeightLast, + ValueFromHeightAndDateLast, }, }; @@ -19,19 +19,19 @@ use super::ImportConfig; #[derive(Clone, Traversable)] pub struct UnrealizedMetrics { // === Supply in Profit/Loss === - pub supply_in_profit: ValueHeightDateLast, - pub supply_in_loss: ValueHeightDateLast, + pub supply_in_profit: ValueFromHeightAndDateLast, + pub supply_in_loss: ValueFromHeightAndDateLast, // === Unrealized Profit/Loss === - pub unrealized_profit: ComputedHeightDateLast, - pub unrealized_loss: ComputedHeightDateLast, + pub unrealized_profit: ComputedFromHeightAndDateLast, + pub unrealized_loss: ComputedFromHeightAndDateLast, // === Negated === - pub neg_unrealized_loss: LazyBlockLast, + pub neg_unrealized_loss: LazyFromHeightLast, // === Net and Total === - pub net_unrealized_pnl: LazyBinaryBlockLast, - pub total_unrealized_pnl: LazyBinaryBlockLast, + pub net_unrealized_pnl: LazyBinaryFromHeightLast, + pub total_unrealized_pnl: LazyBinaryFromHeightLast, } impl UnrealizedMetrics { @@ -40,7 +40,7 @@ impl UnrealizedMetrics { let compute_dollars = cfg.compute_dollars(); // === Supply in Profit/Loss === - let supply_in_profit = ValueHeightDateLast::forced_import( + let supply_in_profit = ValueFromHeightAndDateLast::forced_import( cfg.db, &cfg.name("supply_in_profit"), cfg.version, @@ -48,7 +48,7 @@ impl UnrealizedMetrics { cfg.indexes, cfg.price, )?; - let supply_in_loss = ValueHeightDateLast::forced_import( + let supply_in_loss = ValueFromHeightAndDateLast::forced_import( cfg.db, &cfg.name("supply_in_loss"), cfg.version, @@ -58,13 +58,13 @@ impl UnrealizedMetrics { )?; // === Unrealized Profit/Loss === - let unrealized_profit = ComputedHeightDateLast::forced_import( + let unrealized_profit = ComputedFromHeightAndDateLast::forced_import( cfg.db, &cfg.name("unrealized_profit"), cfg.version, cfg.indexes, )?; - let unrealized_loss = ComputedHeightDateLast::forced_import( + let unrealized_loss = ComputedFromHeightAndDateLast::forced_import( cfg.db, &cfg.name("unrealized_loss"), cfg.version, @@ -72,20 +72,20 @@ impl UnrealizedMetrics { )?; // === Negated === - let neg_unrealized_loss = LazyBlockLast::from_computed_height_date::( + let neg_unrealized_loss = LazyFromHeightLast::from_computed_height_date::( &cfg.name("neg_unrealized_loss"), cfg.version, &unrealized_loss, ); // === Net and Total === - let net_unrealized_pnl = LazyBinaryBlockLast::from_computed_height_date_last::( + let net_unrealized_pnl = LazyBinaryFromHeightLast::from_computed_height_date_last::( &cfg.name("net_unrealized_pnl"), cfg.version, &unrealized_profit, &unrealized_loss, ); - let total_unrealized_pnl = LazyBinaryBlockLast::from_computed_height_date_last::( + let total_unrealized_pnl = LazyBinaryFromHeightLast::from_computed_height_date_last::( &cfg.name("total_unrealized_pnl"), cfg.version, &unrealized_profit, diff --git a/crates/brk_computer/src/distribution/vecs.rs b/crates/brk_computer/src/distribution/vecs.rs index f7c93da3a..c80595d7e 100644 --- a/crates/brk_computer/src/distribution/vecs.rs +++ b/crates/brk_computer/src/distribution/vecs.rs @@ -43,9 +43,9 @@ pub struct Vecs { pub addr_count: AddrCountVecs, pub empty_addr_count: AddrCountVecs, - pub loadedaddressindex_to_loadedaddressindex: + pub loadedaddressindex: LazyVecFrom1, - pub emptyaddressindex_to_emptyaddressindex: + pub emptyaddressindex: LazyVecFrom1, } @@ -90,13 +90,13 @@ impl Vecs { )?; // Identity mappings for traversable - let loadedaddressindex_to_loadedaddressindex = LazyVecFrom1::init( + let loadedaddressindex = LazyVecFrom1::init( "loadedaddressindex", version, loadedaddressindex_to_loadedaddressdata.boxed_clone(), |index, _| Some(index), ); - let emptyaddressindex_to_emptyaddressindex = LazyVecFrom1::init( + let emptyaddressindex = LazyVecFrom1::init( "emptyaddressindex", version, emptyaddressindex_to_emptyaddressdata.boxed_clone(), @@ -125,8 +125,8 @@ impl Vecs { loaded: loadedaddressindex_to_loadedaddressdata, empty: emptyaddressindex_to_emptyaddressdata, }, - loadedaddressindex_to_loadedaddressindex, - emptyaddressindex_to_emptyaddressindex, + loadedaddressindex, + emptyaddressindex, db, }; diff --git a/crates/brk_computer/src/inputs/count/import.rs b/crates/brk_computer/src/inputs/count/import.rs index de3d38af4..cfc4ab1a4 100644 --- a/crates/brk_computer/src/inputs/count/import.rs +++ b/crates/brk_computer/src/inputs/count/import.rs @@ -3,11 +3,11 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::DerivedTxFull}; +use crate::{indexes, internal::TxDerivedFull}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { - Ok(Self(DerivedTxFull::forced_import( + Ok(Self(TxDerivedFull::forced_import( db, "input_count", version, diff --git a/crates/brk_computer/src/inputs/count/vecs.rs b/crates/brk_computer/src/inputs/count/vecs.rs index 13cc020e8..238616ae3 100644 --- a/crates/brk_computer/src/inputs/count/vecs.rs +++ b/crates/brk_computer/src/inputs/count/vecs.rs @@ -2,7 +2,7 @@ use brk_traversable::Traversable; use brk_types::StoredU64; use derive_more::{Deref, DerefMut}; -use crate::internal::DerivedTxFull; +use crate::internal::TxDerivedFull; #[derive(Clone, Deref, DerefMut, Traversable)] -pub struct Vecs(pub DerivedTxFull); +pub struct Vecs(pub TxDerivedFull); diff --git a/crates/brk_computer/src/internal/compute.rs b/crates/brk_computer/src/internal/compute.rs index a673466d4..2237d76b1 100644 --- a/crates/brk_computer/src/internal/compute.rs +++ b/crates/brk_computer/src/internal/compute.rs @@ -3,7 +3,7 @@ //! These functions replace the Option-based compute logic in flexible builders. //! Each function takes optional mutable references and computes only for Some() vecs. -use brk_error::{Error, Result}; +use brk_error::Result; use brk_types::{CheckedSub, StoredU64}; use schemars::JsonSchema; use vecdb::{ @@ -28,6 +28,10 @@ fn validate_and_start( /// /// This function computes all requested aggregations in a single pass when possible, /// optimizing for the common case where multiple aggregations are needed. +/// +/// The `skip_count` parameter allows skipping the first N items from ALL calculations. +/// This is useful for excluding coinbase transactions (which have 0 fee) from +/// fee/feerate aggregations. #[allow(clippy::too_many_arguments)] pub fn compute_aggregations( max_from: I, @@ -35,6 +39,7 @@ pub fn compute_aggregations( first_indexes: &impl IterableVec, count_indexes: &impl IterableVec, exit: &Exit, + skip_count: usize, mut first: Option<&mut EagerVec>>, mut last: Option<&mut EagerVec>>, mut min: Option<&mut EagerVec>>, @@ -105,29 +110,37 @@ where let count_index = count_indexes_iter.next().unwrap(); let count = *count_index as usize; + // Effective count after skipping (e.g., skip coinbase for fee calculations) + let effective_count = count.saturating_sub(skip_count); + let effective_first_index = first_index + skip_count.min(count); + if let Some(ref mut first_vec) = first { - let f = source_iter - .get(first_index) - .unwrap_or_else(|| T::from(0_usize)); + let f = if effective_count > 0 { + source_iter.get_unwrap(effective_first_index) + } else { + T::from(0_usize) + }; first_vec.truncate_push_at(idx, f)?; } if let Some(ref mut last_vec) = last { - if count == 0 { - panic!("should not compute last if count can be 0"); + if effective_count == 0 { + // If all items skipped, use zero + last_vec.truncate_push_at(idx, T::from(0_usize))?; + } else { + let last_index = first_index + (count - 1); + let v = source_iter.get_unwrap(last_index); + last_vec.truncate_push_at(idx, v)?; } - let last_index = first_index + (count - 1); - let v = source_iter.get_unwrap(last_index); - last_vec.truncate_push_at(idx, v)?; } // Fast path: only min/max needed, no sorting or allocation required if needs_minmax && !needs_percentiles && !needs_aggregates { - source_iter.set_position(first_index); + source_iter.set_position(effective_first_index); let mut min_val: Option = None; let mut max_val: Option = None; - for val in (&mut source_iter).take(count) { + for val in (&mut source_iter).take(effective_count) { if needs_min { min_val = Some(min_val.map_or(val, |m| if val < m { val } else { m })); } @@ -137,43 +150,94 @@ where } if let Some(ref mut min_vec) = min { - min_vec.truncate_push_at(idx, min_val.unwrap())?; + let v = min_val.or(max_val).unwrap_or_else(|| T::from(0_usize)); + min_vec.truncate_push_at(idx, v)?; } if let Some(ref mut max_vec) = max { - max_vec.truncate_push_at(idx, max_val.unwrap())?; + let v = max_val.or(min_val).unwrap_or_else(|| T::from(0_usize)); + max_vec.truncate_push_at(idx, v)?; } } else if needs_percentiles || needs_aggregates || needs_minmax { - source_iter.set_position(first_index); - let mut values: Vec = (&mut source_iter).take(count).collect(); - - if needs_percentiles { - values.sort_unstable(); + source_iter.set_position(effective_first_index); + let values: Vec = (&mut source_iter).take(effective_count).collect(); + if values.is_empty() { + // Handle edge case where all items were skipped if let Some(ref mut max_vec) = max { - max_vec.truncate_push_at( - idx, - *values - .last() - .ok_or(Error::Internal("Empty values for percentiles"))?, - )?; + max_vec.truncate_push_at(idx, T::from(0_usize))?; } if let Some(ref mut pct90_vec) = pct90 { - pct90_vec.truncate_push_at(idx, get_percentile(&values, 0.90))?; + pct90_vec.truncate_push_at(idx, T::from(0_usize))?; } if let Some(ref mut pct75_vec) = pct75 { - pct75_vec.truncate_push_at(idx, get_percentile(&values, 0.75))?; + pct75_vec.truncate_push_at(idx, T::from(0_usize))?; } if let Some(ref mut median_vec) = median { - median_vec.truncate_push_at(idx, get_percentile(&values, 0.50))?; + median_vec.truncate_push_at(idx, T::from(0_usize))?; } if let Some(ref mut pct25_vec) = pct25 { - pct25_vec.truncate_push_at(idx, get_percentile(&values, 0.25))?; + pct25_vec.truncate_push_at(idx, T::from(0_usize))?; } if let Some(ref mut pct10_vec) = pct10 { - pct10_vec.truncate_push_at(idx, get_percentile(&values, 0.10))?; + pct10_vec.truncate_push_at(idx, T::from(0_usize))?; } if let Some(ref mut min_vec) = min { - min_vec.truncate_push_at(idx, *values.first().unwrap())?; + min_vec.truncate_push_at(idx, T::from(0_usize))?; + } + if let Some(ref mut average_vec) = average { + average_vec.truncate_push_at(idx, T::from(0_usize))?; + } + if let Some(ref mut sum_vec) = sum { + sum_vec.truncate_push_at(idx, T::from(0_usize))?; + } + if let Some(ref mut cumulative_vec) = cumulative { + let t = cumulative_val.unwrap(); + cumulative_vec.truncate_push_at(idx, t)?; + } + } else if needs_percentiles { + let mut sorted_values = values.clone(); + sorted_values.sort_unstable(); + + if let Some(ref mut max_vec) = max { + max_vec.truncate_push_at(idx, *sorted_values.last().unwrap())?; + } + if let Some(ref mut pct90_vec) = pct90 { + pct90_vec.truncate_push_at(idx, get_percentile(&sorted_values, 0.90))?; + } + if let Some(ref mut pct75_vec) = pct75 { + pct75_vec.truncate_push_at(idx, get_percentile(&sorted_values, 0.75))?; + } + if let Some(ref mut median_vec) = median { + median_vec.truncate_push_at(idx, get_percentile(&sorted_values, 0.50))?; + } + if let Some(ref mut pct25_vec) = pct25 { + pct25_vec.truncate_push_at(idx, get_percentile(&sorted_values, 0.25))?; + } + if let Some(ref mut pct10_vec) = pct10 { + pct10_vec.truncate_push_at(idx, get_percentile(&sorted_values, 0.10))?; + } + if let Some(ref mut min_vec) = min { + min_vec.truncate_push_at(idx, *sorted_values.first().unwrap())?; + } + + if needs_aggregates { + let len = values.len(); + let sum_val = values.into_iter().fold(T::from(0), |a, b| a + b); + + if let Some(ref mut average_vec) = average { + average_vec.truncate_push_at(idx, sum_val / len)?; + } + + if needs_sum_or_cumulative { + if let Some(ref mut sum_vec) = sum { + sum_vec.truncate_push_at(idx, sum_val)?; + } + if let Some(ref mut cumulative_vec) = cumulative { + let t = cumulative_val.unwrap() + sum_val; + cumulative_val.replace(t); + cumulative_vec.truncate_push_at(idx, t)?; + } + } } } else if needs_minmax { if let Some(ref mut min_vec) = min { @@ -182,9 +246,27 @@ where if let Some(ref mut max_vec) = max { max_vec.truncate_push_at(idx, *values.iter().max().unwrap())?; } - } - if needs_aggregates { + if needs_aggregates { + let len = values.len(); + let sum_val = values.into_iter().fold(T::from(0), |a, b| a + b); + + if let Some(ref mut average_vec) = average { + average_vec.truncate_push_at(idx, sum_val / len)?; + } + + if needs_sum_or_cumulative { + if let Some(ref mut sum_vec) = sum { + sum_vec.truncate_push_at(idx, sum_val)?; + } + if let Some(ref mut cumulative_vec) = cumulative { + let t = cumulative_val.unwrap() + sum_val; + cumulative_val.replace(t); + cumulative_vec.truncate_push_at(idx, t)?; + } + } + } + } else if needs_aggregates { let len = values.len(); let sum_val = values.into_iter().fold(T::from(0), |a, b| a + b); diff --git a/crates/brk_computer/src/internal/multi/derived_date/average.rs b/crates/brk_computer/src/internal/multi/date_derived/average.rs similarity index 96% rename from crates/brk_computer/src/internal/multi/derived_date/average.rs rename to crates/brk_computer/src/internal/multi/date_derived/average.rs index 12e4316ad..fe7705f05 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/average.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/average.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsAverage +pub struct LazyDateDerivedAverage where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsAverage +impl LazyDateDerivedAverage where T: ComputedVecValue + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/derived_date/distribution.rs b/crates/brk_computer/src/internal/multi/date_derived/distribution.rs similarity index 96% rename from crates/brk_computer/src/internal/multi/derived_date/distribution.rs rename to crates/brk_computer/src/internal/multi/date_derived/distribution.rs index 1488c1328..2a0887246 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/distribution.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/distribution.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsDistribution +pub struct LazyDateDerivedDistribution where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsDistribution +impl LazyDateDerivedDistribution where T: ComputedVecValue + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/derived_date/first.rs b/crates/brk_computer/src/internal/multi/date_derived/first.rs similarity index 96% rename from crates/brk_computer/src/internal/multi/derived_date/first.rs rename to crates/brk_computer/src/internal/multi/date_derived/first.rs index 1c72f4da0..d47be80a2 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/first.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/first.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsFirst +pub struct LazyDateDerivedFirst where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsFirst +impl LazyDateDerivedFirst where T: ComputedVecValue + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/derived_date/full.rs b/crates/brk_computer/src/internal/multi/date_derived/full.rs similarity index 97% rename from crates/brk_computer/src/internal/multi/derived_date/full.rs rename to crates/brk_computer/src/internal/multi/date_derived/full.rs index 62641b57b..8d01b6a1e 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/full.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/full.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsFull +pub struct LazyDateDerivedFull where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsFull +impl LazyDateDerivedFull where T: ComputedVecValue + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/derived_date/last.rs b/crates/brk_computer/src/internal/multi/date_derived/last.rs similarity index 96% rename from crates/brk_computer/src/internal/multi/derived_date/last.rs rename to crates/brk_computer/src/internal/multi/date_derived/last.rs index 1816a2958..06fa893fe 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/last.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/last.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsLast +pub struct LazyDateDerivedLast where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsLast +impl LazyDateDerivedLast where T: ComputedVecValue + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/derived_date/max.rs b/crates/brk_computer/src/internal/multi/date_derived/max.rs similarity index 62% rename from crates/brk_computer/src/internal/multi/derived_date/max.rs rename to crates/brk_computer/src/internal/multi/date_derived/max.rs index 7340eeb69..bc54745d7 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/max.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/max.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsMax +pub struct LazyDateDerivedMax where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsMax +impl LazyDateDerivedMax where T: ComputedVecValue + JsonSchema + 'static, { @@ -37,12 +37,36 @@ where version: Version, dateindex_source: IterableBoxedVec, indexes: &indexes::Vecs, + ) -> Self { + Self::from_source_inner(name, version, dateindex_source, indexes, false) + } + + /// Create from an external dateindex source without adding _max suffix. + pub fn from_source_raw( + name: &str, + version: Version, + dateindex_source: IterableBoxedVec, + indexes: &indexes::Vecs, + ) -> Self { + Self::from_source_inner(name, version, dateindex_source, indexes, true) + } + + fn from_source_inner( + name: &str, + version: Version, + dateindex_source: IterableBoxedVec, + indexes: &indexes::Vecs, + raw: bool, ) -> Self { let v = version + VERSION; macro_rules! period { ($idx:ident) => { - LazyMax::from_source(name, v, dateindex_source.clone(), indexes.$idx.identity.boxed_clone()) + if raw { + LazyMax::from_source_raw(name, v, dateindex_source.clone(), indexes.$idx.identity.boxed_clone()) + } else { + LazyMax::from_source(name, v, dateindex_source.clone(), indexes.$idx.identity.boxed_clone()) + } }; } diff --git a/crates/brk_computer/src/internal/multi/derived_date/min.rs b/crates/brk_computer/src/internal/multi/date_derived/min.rs similarity index 62% rename from crates/brk_computer/src/internal/multi/derived_date/min.rs rename to crates/brk_computer/src/internal/multi/date_derived/min.rs index 63bb275c8..461186866 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/min.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/min.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsMin +pub struct LazyDateDerivedMin where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsMin +impl LazyDateDerivedMin where T: ComputedVecValue + JsonSchema + 'static, { @@ -37,12 +37,36 @@ where version: Version, dateindex_source: IterableBoxedVec, indexes: &indexes::Vecs, + ) -> Self { + Self::from_source_inner(name, version, dateindex_source, indexes, false) + } + + /// Create from an external dateindex source without adding _min suffix. + pub fn from_source_raw( + name: &str, + version: Version, + dateindex_source: IterableBoxedVec, + indexes: &indexes::Vecs, + ) -> Self { + Self::from_source_inner(name, version, dateindex_source, indexes, true) + } + + fn from_source_inner( + name: &str, + version: Version, + dateindex_source: IterableBoxedVec, + indexes: &indexes::Vecs, + raw: bool, ) -> Self { let v = version + VERSION; macro_rules! period { ($idx:ident) => { - LazyMin::from_source(name, v, dateindex_source.clone(), indexes.$idx.identity.boxed_clone()) + if raw { + LazyMin::from_source_raw(name, v, dateindex_source.clone(), indexes.$idx.identity.boxed_clone()) + } else { + LazyMin::from_source(name, v, dateindex_source.clone(), indexes.$idx.identity.boxed_clone()) + } }; } diff --git a/crates/brk_computer/src/internal/multi/derived_date/mod.rs b/crates/brk_computer/src/internal/multi/date_derived/mod.rs similarity index 90% rename from crates/brk_computer/src/internal/multi/derived_date/mod.rs rename to crates/brk_computer/src/internal/multi/date_derived/mod.rs index c2340e54d..2061797f6 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/mod.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/mod.rs @@ -3,7 +3,6 @@ mod distribution; mod first; mod full; mod last; -mod lazy; mod max; mod min; mod sum; @@ -14,7 +13,6 @@ pub use distribution::*; pub use first::*; pub use full::*; pub use last::*; -pub use lazy::*; pub use max::*; pub use min::*; pub use sum::*; diff --git a/crates/brk_computer/src/internal/multi/derived_date/sum.rs b/crates/brk_computer/src/internal/multi/date_derived/sum.rs similarity index 96% rename from crates/brk_computer/src/internal/multi/derived_date/sum.rs rename to crates/brk_computer/src/internal/multi/date_derived/sum.rs index 5bbcb382a..c911c0833 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/sum.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/sum.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsSum +pub struct LazyDateDerivedSum where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsSum +impl LazyDateDerivedSum where T: ComputedVecValue + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/derived_date/sum_cum.rs b/crates/brk_computer/src/internal/multi/date_derived/sum_cum.rs similarity index 96% rename from crates/brk_computer/src/internal/multi/derived_date/sum_cum.rs rename to crates/brk_computer/src/internal/multi/date_derived/sum_cum.rs index 7f4fed887..c265fa186 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/date_derived/sum_cum.rs @@ -13,7 +13,7 @@ use crate::internal::ComputedVecValue; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodsSumCum +pub struct LazyDateDerivedSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,7 +27,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyPeriodsSumCum +impl LazyDateDerivedSumCum where T: ComputedVecValue + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/date/average.rs b/crates/brk_computer/src/internal/multi/from_date/average.rs similarity index 80% rename from crates/brk_computer/src/internal/multi/date/average.rs rename to crates/brk_computer/src/internal/multi/from_date/average.rs index 378457ae7..fdd8583d8 100644 --- a/crates/brk_computer/src/internal/multi/date/average.rs +++ b/crates/brk_computer/src/internal/multi/from_date/average.rs @@ -1,4 +1,4 @@ -//! ComputedDateAverage - dateindex storage + lazy periods for average-value aggregation. +//! ComputedFromDateAverage - dateindex storage + lazy periods for average-value aggregation. use brk_error::Result; use brk_traversable::Traversable; @@ -9,11 +9,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, LazyPeriodsAverage}; +use crate::internal::{ComputedVecValue, LazyDateDerivedAverage}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDateAverage +pub struct ComputedFromDateAverage where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -21,12 +21,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: LazyPeriodsAverage, + pub rest: LazyDateDerivedAverage, } const VERSION: Version = Version::ZERO; -impl ComputedDateAverage +impl ComputedFromDateAverage where T: ComputedVecValue + JsonSchema + 'static, { @@ -39,7 +39,7 @@ where let dateindex = EagerVec::forced_import(db, name, version + VERSION)?; Ok(Self { - rest: LazyPeriodsAverage::from_source( + rest: LazyDateDerivedAverage::from_source( name, version + VERSION, dateindex.boxed_clone(), diff --git a/crates/brk_computer/src/internal/multi/date/binary_last.rs b/crates/brk_computer/src/internal/multi/from_date/binary_last.rs similarity index 71% rename from crates/brk_computer/src/internal/multi/date/binary_last.rs rename to crates/brk_computer/src/internal/multi/from_date/binary_last.rs index 728cb534c..f640ac8be 100644 --- a/crates/brk_computer/src/internal/multi/date/binary_last.rs +++ b/crates/brk_computer/src/internal/multi/from_date/binary_last.rs @@ -8,15 +8,16 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; use crate::internal::{ - ComputedBlockLast, ComputedBlockSum, ComputedDateLast, ComputedVecValue, LazyBinaryTransformLast, - LazyPeriodsLast, LazyPeriodsSumCum, NumericValue, + ComputedFromHeightLast, ComputedFromHeightSum, ComputedFromDateLast, ComputedVecValue, + LazyBinaryComputedFromHeightLast, LazyBinaryComputedFromHeightSum, LazyBinaryTransformLast, + LazyDateDerivedLast, LazyDateDerivedSumCum, NumericValue, }; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyBinaryDateLast +pub struct LazyBinaryFromDateLast where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -31,7 +32,7 @@ where pub decadeindex: LazyBinaryTransformLast, } -impl LazyBinaryDateLast +impl LazyBinaryFromDateLast where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -40,8 +41,8 @@ where pub fn from_computed_both_last>( name: &str, version: Version, - source1: &ComputedDateLast, - source2: &ComputedDateLast, + source1: &ComputedFromDateLast, + source2: &ComputedFromDateLast, ) -> Self { let v = version + VERSION; @@ -76,8 +77,8 @@ where name: &str, version: Version, dateindex_source1: IterableBoxedVec, - source1: &LazyPeriodsLast, - source2: &ComputedDateLast, + source1: &LazyDateDerivedLast, + source2: &ComputedFromDateLast, ) -> Self { let v = version + VERSION; @@ -112,8 +113,8 @@ where name: &str, version: Version, dateindex_source1: IterableBoxedVec, - source1: &LazyPeriodsLast, - source2: &ComputedBlockLast, + source1: &LazyDateDerivedLast, + source2: &ComputedFromHeightLast, ) -> Self where S2T: NumericValue, @@ -136,7 +137,7 @@ where name, v, dateindex_source1, - source2.dateindex.0.boxed_clone(), + source2.dateindex.boxed_clone(), ), weekindex: period!(weekindex), monthindex: period!(monthindex), @@ -151,9 +152,9 @@ where name: &str, version: Version, dateindex_source1: IterableBoxedVec, - source1: &LazyPeriodsLast, + source1: &LazyDateDerivedLast, dateindex_source2: IterableBoxedVec, - source2: &LazyPeriodsLast, + source2: &LazyDateDerivedLast, ) -> Self { let v = version + VERSION; @@ -187,8 +188,8 @@ where pub fn from_height_and_dateindex_last>( name: &str, version: Version, - source1: &ComputedBlockLast, - source2: &ComputedDateLast, + source1: &ComputedFromHeightLast, + source2: &ComputedFromDateLast, ) -> Self where S1T: NumericValue, @@ -210,7 +211,7 @@ where dateindex: LazyVecFrom2::transformed::( name, v, - source1.dateindex.0.boxed_clone(), + source1.dateindex.boxed_clone(), source2.dateindex.boxed_clone(), ), weekindex: period!(weekindex), @@ -225,8 +226,8 @@ where pub fn from_dateindex_and_height_last>( name: &str, version: Version, - source1: &ComputedDateLast, - source2: &ComputedBlockLast, + source1: &ComputedFromDateLast, + source2: &ComputedFromHeightLast, ) -> Self where S2T: NumericValue, @@ -249,7 +250,7 @@ where name, v, source1.dateindex.boxed_clone(), - source2.dateindex.0.boxed_clone(), + source2.dateindex.boxed_clone(), ), weekindex: period!(weekindex), monthindex: period!(monthindex), @@ -263,8 +264,8 @@ where pub fn from_both_block_last>( name: &str, version: Version, - source1: &ComputedBlockLast, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightLast, + source2: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -287,8 +288,8 @@ where dateindex: LazyVecFrom2::transformed::( name, v, - source1.dateindex.0.boxed_clone(), - source2.dateindex.0.boxed_clone(), + source1.dateindex.boxed_clone(), + source2.dateindex.boxed_clone(), ), weekindex: period!(weekindex), monthindex: period!(monthindex), @@ -302,8 +303,8 @@ where pub fn from_dateindex_last_and_height_sum>( name: &str, version: Version, - source1: &ComputedDateLast, - source2: &ComputedBlockSum, + source1: &ComputedFromDateLast, + source2: &ComputedFromHeightSum, ) -> Self where S2T: NumericValue, @@ -326,7 +327,7 @@ where name, v, source1.dateindex.boxed_clone(), - source2.dateindex.0.boxed_clone(), + source2.dateindex.boxed_clone(), ), weekindex: period!(weekindex), monthindex: period!(monthindex), @@ -340,8 +341,8 @@ where pub fn from_block_last_and_height_sum>( name: &str, version: Version, - source1: &ComputedBlockLast, - source2: &ComputedBlockSum, + source1: &ComputedFromHeightLast, + source2: &ComputedFromHeightSum, ) -> Self where S1T: NumericValue, @@ -364,8 +365,8 @@ where dateindex: LazyVecFrom2::transformed::( name, v, - source1.dateindex.0.boxed_clone(), - source2.dateindex.0.boxed_clone(), + source1.dateindex.boxed_clone(), + source2.dateindex.boxed_clone(), ), weekindex: period!(weekindex), monthindex: period!(monthindex), @@ -380,9 +381,9 @@ where name: &str, version: Version, dateindex_source1: IterableBoxedVec, - dates1: &LazyPeriodsSumCum, + dates1: &LazyDateDerivedSumCum, dateindex_source2: IterableBoxedVec, - dates2: &LazyPeriodsSumCum, + dates2: &LazyDateDerivedSumCum, ) -> Self where S1T: PartialOrd, @@ -417,13 +418,13 @@ where } } - /// Create from a LazyPeriodsLast source and a BinaryDateLast source. + /// Create from a LazyDateDerivedLast source and a BinaryDateLast source. pub fn from_derived_last_and_binary_last( name: &str, version: Version, dateindex_source1: IterableBoxedVec, - source1: &LazyPeriodsLast, - source2: &LazyBinaryDateLast, + source1: &LazyDateDerivedLast, + source2: &LazyBinaryFromDateLast, ) -> Self where F: BinaryTransform, @@ -459,12 +460,12 @@ where } } - /// Create from a BinaryDateLast source and a ComputedDateLast source. + /// Create from a BinaryDateLast source and a ComputedFromDateLast source. pub fn from_binary_and_computed_last( name: &str, version: Version, - source1: &LazyBinaryDateLast, - source2: &ComputedDateLast, + source1: &LazyBinaryFromDateLast, + source2: &ComputedFromDateLast, ) -> Self where F: BinaryTransform, @@ -500,12 +501,12 @@ where } } - /// Create from a BinaryDateLast source and a ComputedBlockLast source. + /// Create from a BinaryDateLast source and a ComputedFromHeightLast source. pub fn from_binary_and_block_last( name: &str, version: Version, - source1: &LazyBinaryDateLast, - source2: &ComputedBlockLast, + source1: &LazyBinaryFromDateLast, + source2: &ComputedFromHeightLast, ) -> Self where F: BinaryTransform, @@ -531,7 +532,7 @@ where name, v, source1.dateindex.boxed_clone(), - source2.dateindex.0.boxed_clone(), + source2.dateindex.boxed_clone(), ), weekindex: period!(weekindex), monthindex: period!(monthindex), @@ -542,12 +543,12 @@ where } } - /// Create from a ComputedDateLast source and a BinaryDateLast source. + /// Create from a ComputedFromDateLast source and a BinaryDateLast source. pub fn from_computed_and_binary_last( name: &str, version: Version, - source1: &ComputedDateLast, - source2: &LazyBinaryDateLast, + source1: &ComputedFromDateLast, + source2: &LazyBinaryFromDateLast, ) -> Self where F: BinaryTransform, @@ -587,8 +588,8 @@ where pub fn from_both_binary_last( name: &str, version: Version, - source1: &LazyBinaryDateLast, - source2: &LazyBinaryDateLast, + source1: &LazyBinaryFromDateLast, + source2: &LazyBinaryFromDateLast, ) -> Self where F: BinaryTransform, @@ -625,4 +626,131 @@ where decadeindex: period!(decadeindex), } } + + /// Create from a BinaryDateLast source and a LazyDateDerivedLast source. + pub fn from_binary_and_derived_last( + name: &str, + version: Version, + source1: &LazyBinaryFromDateLast, + dateindex_source2: IterableBoxedVec, + source2: &LazyDateDerivedLast, + ) -> Self + where + F: BinaryTransform, + S1aT: ComputedVecValue + JsonSchema, + S1bT: ComputedVecValue + JsonSchema, + { + let v = version + VERSION; + + macro_rules! period { + ($p:ident) => { + LazyBinaryTransformLast::from_vecs::( + name, + v, + source1.$p.boxed_clone(), + source2.$p.boxed_clone(), + ) + }; + } + + Self { + dateindex: LazyVecFrom2::transformed::( + name, + v, + source1.dateindex.boxed_clone(), + dateindex_source2, + ), + weekindex: period!(weekindex), + monthindex: period!(monthindex), + quarterindex: period!(quarterindex), + semesterindex: period!(semesterindex), + yearindex: period!(yearindex), + decadeindex: period!(decadeindex), + } + } + + /// Create from a LazyBinaryComputedFromHeightLast and a ComputedFromHeightSum. + pub fn from_lazy_binary_block_last_and_height_sum( + name: &str, + version: Version, + source1: &LazyBinaryComputedFromHeightLast, + source2: &ComputedFromHeightSum, + ) -> Self + where + F: BinaryTransform, + S1aT: ComputedVecValue + JsonSchema, + S1bT: ComputedVecValue + JsonSchema, + S2T: NumericValue, + { + let v = version + VERSION; + + macro_rules! period { + ($p:ident) => { + LazyBinaryTransformLast::from_vecs::( + name, + v, + source1.rest.dates.$p.boxed_clone(), + source2.$p.boxed_clone(), + ) + }; + } + + Self { + dateindex: LazyVecFrom2::transformed::( + name, + v, + source1.rest.dateindex.boxed_clone(), + source2.dateindex.boxed_clone(), + ), + weekindex: period!(weekindex), + monthindex: period!(monthindex), + quarterindex: period!(quarterindex), + semesterindex: period!(semesterindex), + yearindex: period!(yearindex), + decadeindex: period!(decadeindex), + } + } + + /// Create from a LazyBinaryComputedFromHeightLast and a LazyBinaryComputedFromHeightSum. + pub fn from_lazy_binary_block_last_and_lazy_binary_sum( + name: &str, + version: Version, + source1: &LazyBinaryComputedFromHeightLast, + source2: &LazyBinaryComputedFromHeightSum, + ) -> Self + where + F: BinaryTransform, + S1aT: ComputedVecValue + JsonSchema, + S1bT: ComputedVecValue + JsonSchema, + S2aT: ComputedVecValue + JsonSchema, + S2bT: ComputedVecValue + JsonSchema, + { + let v = version + VERSION; + + macro_rules! period { + ($p:ident) => { + LazyBinaryTransformLast::from_vecs::( + name, + v, + source1.rest.dates.$p.boxed_clone(), + source2.rest.dates.$p.boxed_clone(), + ) + }; + } + + Self { + dateindex: LazyVecFrom2::transformed::( + name, + v, + source1.rest.dateindex.boxed_clone(), + source2.rest.dateindex.boxed_clone(), + ), + weekindex: period!(weekindex), + monthindex: period!(monthindex), + quarterindex: period!(quarterindex), + semesterindex: period!(semesterindex), + yearindex: period!(yearindex), + decadeindex: period!(decadeindex), + } + } } diff --git a/crates/brk_computer/src/internal/multi/date/binary_sum.rs b/crates/brk_computer/src/internal/multi/from_date/binary_sum.rs similarity index 86% rename from crates/brk_computer/src/internal/multi/date/binary_sum.rs rename to crates/brk_computer/src/internal/multi/from_date/binary_sum.rs index bcdda9d16..24e9da216 100644 --- a/crates/brk_computer/src/internal/multi/date/binary_sum.rs +++ b/crates/brk_computer/src/internal/multi/from_date/binary_sum.rs @@ -7,13 +7,13 @@ use brk_types::{ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableCloneableVec}; -use crate::internal::{ComputedVecValue, ComputedDerivedBlockSum, LazyBinaryTransformSum, NumericValue}; +use crate::internal::{ComputedVecValue, ComputedHeightDerivedSum, LazyBinaryTransformSum, NumericValue}; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyBinaryDateSum +pub struct LazyBinaryFromDateSum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -28,7 +28,7 @@ where pub decadeindex: LazyBinaryTransformSum, } -impl LazyBinaryDateSum +impl LazyBinaryFromDateSum where T: ComputedVecValue + JsonSchema + 'static, S1T: NumericValue + JsonSchema, @@ -37,8 +37,8 @@ where pub fn from_derived>( name: &str, version: Version, - source1: &ComputedDerivedBlockSum, - source2: &ComputedDerivedBlockSum, + source1: &ComputedHeightDerivedSum, + source2: &ComputedHeightDerivedSum, ) -> Self { let v = version + VERSION; diff --git a/crates/brk_computer/src/internal/multi/date/binary_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_date/binary_sum_cum.rs similarity index 89% rename from crates/brk_computer/src/internal/multi/date/binary_sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_date/binary_sum_cum.rs index 0f0eb33cc..293f64302 100644 --- a/crates/brk_computer/src/internal/multi/date/binary_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_date/binary_sum_cum.rs @@ -8,16 +8,16 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableCloneableVec}; use crate::internal::{ - ComputedBlockLast, ComputedBlockSumCum, ComputedDerivedBlockLast, - ComputedDerivedBlockSumCum, ComputedVecValue, LazyBinaryTransformSumCum, LazyPeriodsFull, - LazyPeriodsSumCum, NumericValue, SumCum, + ComputedFromHeightLast, ComputedFromHeightSumCum, ComputedHeightDerivedLast, + ComputedHeightDerivedSumCum, ComputedVecValue, LazyBinaryTransformSumCum, LazyDateDerivedFull, + LazyDateDerivedSumCum, NumericValue, SumCum, }; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyBinaryDateSumCum +pub struct LazyBinaryFromDateSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -32,7 +32,7 @@ where pub decadeindex: LazyBinaryTransformSumCum, } -impl LazyBinaryDateSumCum +impl LazyBinaryFromDateSumCum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -43,9 +43,9 @@ where name: &str, version: Version, dateindex1: &SumCum, - periods1: &LazyPeriodsSumCum, + periods1: &LazyDateDerivedSumCum, dateindex2: &SumCum, - periods2: &LazyPeriodsSumCum, + periods2: &LazyDateDerivedSumCum, ) -> Self { let v = version + VERSION; @@ -74,9 +74,9 @@ where name: &str, version: Version, dateindex1: &SumCum, - dates1: &LazyPeriodsFull, + dates1: &LazyDateDerivedFull, dateindex2: &SumCum, - dates2: &LazyPeriodsFull, + dates2: &LazyDateDerivedFull, ) -> Self { let v = version + VERSION; @@ -106,9 +106,9 @@ where name: &str, version: Version, dateindex1: &SumCum, - periods1: &LazyPeriodsSumCum, + periods1: &LazyDateDerivedSumCum, dateindex2: &SumCum, - periods2: &LazyPeriodsSumCum, + periods2: &LazyDateDerivedSumCum, ) -> Self { let v = version + VERSION; @@ -138,8 +138,8 @@ where pub fn from_computed_last>( name: &str, version: Version, - source1: &ComputedBlockSumCum, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightSumCum, + source2: &ComputedFromHeightLast, ) -> Self where S1T: PartialOrd, @@ -174,8 +174,8 @@ where pub fn from_derived_computed_last>( name: &str, version: Version, - source1: &ComputedDerivedBlockSumCum, - source2: &ComputedBlockLast, + source1: &ComputedHeightDerivedSumCum, + source2: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -210,8 +210,8 @@ where pub fn from_computed_derived_last>( name: &str, version: Version, - source1: &ComputedBlockSumCum, - source2: &ComputedDerivedBlockLast, + source1: &ComputedFromHeightSumCum, + source2: &ComputedHeightDerivedLast, ) -> Self where S1T: PartialOrd, @@ -246,8 +246,8 @@ where pub fn from_derived_last>( name: &str, version: Version, - source1: &ComputedDerivedBlockSumCum, - source2: &ComputedDerivedBlockLast, + source1: &ComputedHeightDerivedSumCum, + source2: &ComputedHeightDerivedLast, ) -> Self where S1T: NumericValue, diff --git a/crates/brk_computer/src/internal/multi/date/first.rs b/crates/brk_computer/src/internal/multi/from_date/first.rs similarity index 86% rename from crates/brk_computer/src/internal/multi/date/first.rs rename to crates/brk_computer/src/internal/multi/from_date/first.rs index f5a75f4d3..7d683b58b 100644 --- a/crates/brk_computer/src/internal/multi/date/first.rs +++ b/crates/brk_computer/src/internal/multi/from_date/first.rs @@ -9,11 +9,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, LazyPeriodsFirst}; +use crate::internal::{ComputedVecValue, LazyDateDerivedFirst}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDateFirst +pub struct ComputedFromDateFirst where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -21,12 +21,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: LazyPeriodsFirst, + pub rest: LazyDateDerivedFirst, } const VERSION: Version = Version::ZERO; -impl ComputedDateFirst +impl ComputedFromDateFirst where T: ComputedVecValue + JsonSchema + 'static, { @@ -39,7 +39,7 @@ where let dateindex = EagerVec::forced_import(db, name, version + VERSION)?; Ok(Self { - rest: LazyPeriodsFirst::from_source( + rest: LazyDateDerivedFirst::from_source( name, version + VERSION, dateindex.boxed_clone(), diff --git a/crates/brk_computer/src/internal/multi/date/last.rs b/crates/brk_computer/src/internal/multi/from_date/last.rs similarity index 88% rename from crates/brk_computer/src/internal/multi/date/last.rs rename to crates/brk_computer/src/internal/multi/from_date/last.rs index 403ce181a..3df16e800 100644 --- a/crates/brk_computer/src/internal/multi/date/last.rs +++ b/crates/brk_computer/src/internal/multi/from_date/last.rs @@ -9,11 +9,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, Itera use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, LazyPeriodsLast}; +use crate::internal::{ComputedVecValue, LazyDateDerivedLast}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDateLast +pub struct ComputedFromDateLast where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -21,12 +21,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: LazyPeriodsLast, + pub rest: LazyDateDerivedLast, } const VERSION: Version = Version::ZERO; -impl ComputedDateLast +impl ComputedFromDateLast where T: ComputedVecValue + JsonSchema + 'static, { @@ -39,7 +39,7 @@ where let dateindex = EagerVec::forced_import(db, name, version + VERSION)?; Ok(Self { - rest: LazyPeriodsLast::from_source( + rest: LazyDateDerivedLast::from_source( name, version + VERSION, dateindex.boxed_clone(), diff --git a/crates/brk_computer/src/internal/multi/derived_date/lazy.rs b/crates/brk_computer/src/internal/multi/from_date/lazy.rs similarity index 96% rename from crates/brk_computer/src/internal/multi/derived_date/lazy.rs rename to crates/brk_computer/src/internal/multi/from_date/lazy.rs index a0fbd6c73..0fd5bb51f 100644 --- a/crates/brk_computer/src/internal/multi/derived_date/lazy.rs +++ b/crates/brk_computer/src/internal/multi/from_date/lazy.rs @@ -13,7 +13,7 @@ use crate::indexes; /// Lazy vecs for all time period indexes (no height). #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyPeriodVecs +pub struct LazyFromDate where T: VecValue + Formattable + Serialize + JsonSchema, { @@ -26,7 +26,7 @@ where pub decadeindex: LazyVecFrom1, } -impl LazyPeriodVecs { +impl LazyFromDate { #[allow(clippy::too_many_arguments)] pub fn new( name: &str, diff --git a/crates/brk_computer/src/internal/multi/date/lazy_full.rs b/crates/brk_computer/src/internal/multi/from_date/lazy_full.rs similarity index 89% rename from crates/brk_computer/src/internal/multi/date/lazy_full.rs rename to crates/brk_computer/src/internal/multi/from_date/lazy_full.rs index deac7117c..67f3c7984 100644 --- a/crates/brk_computer/src/internal/multi/date/lazy_full.rs +++ b/crates/brk_computer/src/internal/multi/from_date/lazy_full.rs @@ -5,13 +5,13 @@ use brk_types::{DateIndex, DecadeIndex, MonthIndex, QuarterIndex, SemesterIndex, use schemars::JsonSchema; use vecdb::{IterableCloneableVec, UnaryTransform}; -use crate::internal::{ComputedVecValue, Full, LazyPeriodsFull, LazyTransformFull, LazyTransformStats}; +use crate::internal::{ComputedVecValue, Full, LazyDateDerivedFull, LazyTransformFull, LazyTransformStats}; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyDateFull +pub struct LazyFromDateFull where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -25,7 +25,7 @@ where pub decadeindex: LazyTransformStats, } -impl LazyDateFull +impl LazyFromDateFull where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -34,7 +34,7 @@ where name: &str, version: Version, dateindex: &Full, - source: &LazyPeriodsFull, + source: &LazyDateDerivedFull, ) -> Self { let v = version + VERSION; diff --git a/crates/brk_computer/src/internal/multi/date/lazy_last.rs b/crates/brk_computer/src/internal/multi/from_date/lazy_last.rs similarity index 85% rename from crates/brk_computer/src/internal/multi/date/lazy_last.rs rename to crates/brk_computer/src/internal/multi/from_date/lazy_last.rs index 01073c6c6..56727ff46 100644 --- a/crates/brk_computer/src/internal/multi/date/lazy_last.rs +++ b/crates/brk_computer/src/internal/multi/from_date/lazy_last.rs @@ -7,13 +7,13 @@ use brk_types::{ use schemars::JsonSchema; use vecdb::{IterableBoxedVec, IterableCloneableVec, UnaryTransform}; -use crate::internal::{ComputedBlockLast, ComputedDateLast, ComputedVecValue, LazyPeriodsLast, LazyTransformLast, NumericValue}; +use crate::internal::{ComputedFromHeightLast, ComputedFromDateLast, ComputedVecValue, LazyDateDerivedLast, LazyTransformLast, NumericValue}; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyDateLast +pub struct LazyFromDateLast where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -27,7 +27,7 @@ where pub decadeindex: LazyTransformLast, } -impl LazyDateLast +impl LazyFromDateLast where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -35,7 +35,7 @@ where pub fn from_source>( name: &str, version: Version, - source: &ComputedDateLast, + source: &ComputedFromDateLast, ) -> Self { Self::from_computed::(name, version, source.dateindex.boxed_clone(), source) } @@ -44,7 +44,7 @@ where name: &str, version: Version, dateindex_source: IterableBoxedVec, - source: &ComputedDateLast, + source: &ComputedFromDateLast, ) -> Self { Self::from_derived::(name, version, dateindex_source, &source.rest) } @@ -53,7 +53,7 @@ where name: &str, version: Version, dateindex_source: IterableBoxedVec, - source: &LazyPeriodsLast, + source: &LazyDateDerivedLast, ) -> Self { let v = version + VERSION; @@ -77,11 +77,11 @@ where pub fn from_block_source>( name: &str, version: Version, - source: &ComputedBlockLast, + source: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, { - Self::from_derived::(name, version, source.dateindex.0.boxed_clone(), &source.dates) + Self::from_derived::(name, version, source.dateindex.boxed_clone(), &source.dates) } } diff --git a/crates/brk_computer/src/internal/multi/date/lazy_sum.rs b/crates/brk_computer/src/internal/multi/from_date/lazy_sum.rs similarity index 89% rename from crates/brk_computer/src/internal/multi/date/lazy_sum.rs rename to crates/brk_computer/src/internal/multi/from_date/lazy_sum.rs index e2b1eae63..7b5dc401c 100644 --- a/crates/brk_computer/src/internal/multi/date/lazy_sum.rs +++ b/crates/brk_computer/src/internal/multi/from_date/lazy_sum.rs @@ -5,13 +5,13 @@ use brk_types::{DateIndex, DecadeIndex, MonthIndex, QuarterIndex, SemesterIndex, use schemars::JsonSchema; use vecdb::{IterableBoxedVec, IterableCloneableVec, UnaryTransform}; -use crate::internal::{ComputedVecValue, LazyPeriodsSum, LazyTransformSum}; +use crate::internal::{ComputedVecValue, LazyDateDerivedSum, LazyTransformSum}; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyDateSum +pub struct LazyFromDateSum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -25,7 +25,7 @@ where pub decadeindex: LazyTransformSum, } -impl LazyDateSum +impl LazyFromDateSum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -34,7 +34,7 @@ where name: &str, version: Version, dateindex_source: IterableBoxedVec, - source: &LazyPeriodsSum, + source: &LazyDateDerivedSum, ) -> Self { let v = version + VERSION; diff --git a/crates/brk_computer/src/internal/multi/date/lazy_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_date/lazy_sum_cum.rs similarity index 89% rename from crates/brk_computer/src/internal/multi/date/lazy_sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_date/lazy_sum_cum.rs index d733f2032..d32d5764e 100644 --- a/crates/brk_computer/src/internal/multi/date/lazy_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_date/lazy_sum_cum.rs @@ -5,13 +5,13 @@ use brk_types::{DateIndex, DecadeIndex, MonthIndex, QuarterIndex, SemesterIndex, use schemars::JsonSchema; use vecdb::{IterableCloneableVec, UnaryTransform}; -use crate::internal::{ComputedVecValue, LazyPeriodsSumCum, LazyTransformSumCum, SumCum}; +use crate::internal::{ComputedVecValue, LazyDateDerivedSumCum, LazyTransformSumCum, SumCum}; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyDateSumCum +pub struct LazyFromDateSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -25,7 +25,7 @@ where pub decadeindex: LazyTransformSumCum, } -impl LazyDateSumCum +impl LazyFromDateSumCum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -34,7 +34,7 @@ where name: &str, version: Version, dateindex: &SumCum, - source: &LazyPeriodsSumCum, + source: &LazyDateDerivedSumCum, ) -> Self { let v = version + VERSION; diff --git a/crates/brk_computer/src/internal/multi/date/max.rs b/crates/brk_computer/src/internal/multi/from_date/max.rs similarity index 57% rename from crates/brk_computer/src/internal/multi/date/max.rs rename to crates/brk_computer/src/internal/multi/from_date/max.rs index ad8871fe4..d39f9921f 100644 --- a/crates/brk_computer/src/internal/multi/date/max.rs +++ b/crates/brk_computer/src/internal/multi/from_date/max.rs @@ -9,11 +9,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, LazyPeriodsMax}; +use crate::internal::{ComputedVecValue, LazyDateDerivedMax}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDateMax +pub struct ComputedFromDateMax where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -21,12 +21,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: LazyPeriodsMax, + pub rest: LazyDateDerivedMax, } const VERSION: Version = Version::ZERO; -impl ComputedDateMax +impl ComputedFromDateMax where T: ComputedVecValue + JsonSchema + 'static, { @@ -35,16 +35,47 @@ where name: &str, version: Version, indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, false) + } + + /// Import without adding _max suffix to lazy vecs. + pub fn forced_import_raw( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, true) + } + + fn forced_import_inner( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + raw: bool, ) -> Result { let dateindex = EagerVec::forced_import(db, name, version + VERSION)?; - Ok(Self { - rest: LazyPeriodsMax::from_source( + let rest = if raw { + LazyDateDerivedMax::from_source_raw( name, version + VERSION, dateindex.boxed_clone(), indexes, - ), + ) + } else { + LazyDateDerivedMax::from_source( + name, + version + VERSION, + dateindex.boxed_clone(), + indexes, + ) + }; + + Ok(Self { + rest, dateindex, }) } diff --git a/crates/brk_computer/src/internal/multi/date/min.rs b/crates/brk_computer/src/internal/multi/from_date/min.rs similarity index 57% rename from crates/brk_computer/src/internal/multi/date/min.rs rename to crates/brk_computer/src/internal/multi/from_date/min.rs index dc1be9762..44268f1d7 100644 --- a/crates/brk_computer/src/internal/multi/date/min.rs +++ b/crates/brk_computer/src/internal/multi/from_date/min.rs @@ -9,11 +9,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, LazyPeriodsMin}; +use crate::internal::{ComputedVecValue, LazyDateDerivedMin}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDateMin +pub struct ComputedFromDateMin where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -21,12 +21,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: LazyPeriodsMin, + pub rest: LazyDateDerivedMin, } const VERSION: Version = Version::ZERO; -impl ComputedDateMin +impl ComputedFromDateMin where T: ComputedVecValue + JsonSchema + 'static, { @@ -35,16 +35,47 @@ where name: &str, version: Version, indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, false) + } + + /// Import without adding _min suffix to lazy vecs. + pub fn forced_import_raw( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, true) + } + + fn forced_import_inner( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + raw: bool, ) -> Result { let dateindex = EagerVec::forced_import(db, name, version + VERSION)?; - Ok(Self { - rest: LazyPeriodsMin::from_source( + let rest = if raw { + LazyDateDerivedMin::from_source_raw( name, version + VERSION, dateindex.boxed_clone(), indexes, - ), + ) + } else { + LazyDateDerivedMin::from_source( + name, + version + VERSION, + dateindex.boxed_clone(), + indexes, + ) + }; + + Ok(Self { + rest, dateindex, }) } diff --git a/crates/brk_computer/src/internal/multi/date/mod.rs b/crates/brk_computer/src/internal/multi/from_date/mod.rs similarity index 60% rename from crates/brk_computer/src/internal/multi/date/mod.rs rename to crates/brk_computer/src/internal/multi/from_date/mod.rs index c83a41740..886bf6d53 100644 --- a/crates/brk_computer/src/internal/multi/date/mod.rs +++ b/crates/brk_computer/src/internal/multi/from_date/mod.rs @@ -4,12 +4,19 @@ mod binary_sum; mod binary_sum_cum; mod first; mod last; +mod lazy; mod lazy_full; mod lazy_last; mod lazy_sum; mod lazy_sum_cum; mod max; mod min; +mod percentiles; +mod ratio; +mod stddev; +mod value_derived_last; +mod value_last; +mod value_lazy_last; pub use average::*; pub use binary_last::*; @@ -17,9 +24,16 @@ pub use binary_sum::*; pub use binary_sum_cum::*; pub use first::*; pub use last::*; +pub use lazy::*; pub use lazy_full::*; pub use lazy_last::*; pub use lazy_sum::*; pub use lazy_sum_cum::*; pub use max::*; pub use min::*; +pub use percentiles::*; +pub use ratio::*; +pub use stddev::*; +pub use value_derived_last::*; +pub use value_last::*; +pub use value_lazy_last::*; diff --git a/crates/brk_computer/src/internal/multi/specialized/percentiles.rs b/crates/brk_computer/src/internal/multi/from_date/percentiles.rs similarity index 93% rename from crates/brk_computer/src/internal/multi/specialized/percentiles.rs rename to crates/brk_computer/src/internal/multi/from_date/percentiles.rs index 751026597..83e01dcc4 100644 --- a/crates/brk_computer/src/internal/multi/specialized/percentiles.rs +++ b/crates/brk_computer/src/internal/multi/from_date/percentiles.rs @@ -8,7 +8,7 @@ use vecdb::{ use crate::{ComputeIndexes, indexes}; -use super::super::ComputedDateLast; +use super::ComputedFromDateLast; pub const PERCENTILES: [u8; 19] = [ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, @@ -17,7 +17,7 @@ pub const PERCENTILES_LEN: usize = PERCENTILES.len(); #[derive(Clone)] pub struct CostBasisPercentiles { - pub vecs: [Option>; PERCENTILES_LEN], + pub vecs: [Option>; PERCENTILES_LEN], } const VERSION: Version = Version::ZERO; @@ -37,7 +37,7 @@ impl CostBasisPercentiles { } else { format!("{name}_cost_basis_pct{p:02}") }; - ComputedDateLast::forced_import(db, &metric_name, version + VERSION, indexes) + ComputedFromDateLast::forced_import(db, &metric_name, version + VERSION, indexes) .unwrap() }) }); @@ -81,7 +81,7 @@ impl CostBasisPercentiles { Ok(()) } - pub fn get(&self, percentile: u8) -> Option<&ComputedDateLast> { + pub fn get(&self, percentile: u8) -> Option<&ComputedFromDateLast> { PERCENTILES .iter() .position(|&p| p == percentile) diff --git a/crates/brk_computer/src/internal/multi/specialized/ratio.rs b/crates/brk_computer/src/internal/multi/from_date/ratio.rs similarity index 83% rename from crates/brk_computer/src/internal/multi/specialized/ratio.rs rename to crates/brk_computer/src/internal/multi/from_date/ratio.rs index 17ba1c94c..e484fadb1 100644 --- a/crates/brk_computer/src/internal/multi/specialized/ratio.rs +++ b/crates/brk_computer/src/internal/multi/from_date/ratio.rs @@ -9,49 +9,50 @@ use vecdb::{ use crate::{ ComputeIndexes, indexes, internal::{ - ComputedStandardDeviationVecsDate, LazyBinaryDateLast, PriceTimesRatio, + ComputedFromDateStdDev, LazyBinaryFromDateLast, PriceTimesRatio, StandardDeviationVecsOptions, }, price, utils::get_percentile, }; -use super::super::{ComputedBlockLast, ComputedDateLast}; +use super::ComputedFromDateLast; +use crate::internal::ComputedFromHeightLast; #[derive(Clone, Traversable)] -pub struct ComputedRatioVecsDate { - pub price: Option>, +pub struct ComputedFromDateRatio { + pub price: Option>, - pub ratio: ComputedDateLast, - pub ratio_1w_sma: Option>, - pub ratio_1m_sma: Option>, - pub ratio_pct99: Option>, - pub ratio_pct98: Option>, - pub ratio_pct95: Option>, - pub ratio_pct5: Option>, - pub ratio_pct2: Option>, - pub ratio_pct1: Option>, - pub ratio_pct99_usd: Option>, - pub ratio_pct98_usd: Option>, - pub ratio_pct95_usd: Option>, - pub ratio_pct5_usd: Option>, - pub ratio_pct2_usd: Option>, - pub ratio_pct1_usd: Option>, + pub ratio: ComputedFromDateLast, + pub ratio_1w_sma: Option>, + pub ratio_1m_sma: Option>, + pub ratio_pct99: Option>, + pub ratio_pct98: Option>, + pub ratio_pct95: Option>, + pub ratio_pct5: Option>, + pub ratio_pct2: Option>, + pub ratio_pct1: Option>, + pub ratio_pct99_usd: Option>, + pub ratio_pct98_usd: Option>, + pub ratio_pct95_usd: Option>, + pub ratio_pct5_usd: Option>, + pub ratio_pct2_usd: Option>, + pub ratio_pct1_usd: Option>, - pub ratio_sd: Option, - pub ratio_4y_sd: Option, - pub ratio_2y_sd: Option, - pub ratio_1y_sd: Option, + pub ratio_sd: Option, + pub ratio_4y_sd: Option, + pub ratio_2y_sd: Option, + pub ratio_1y_sd: Option, } const VERSION: Version = Version::TWO; -impl ComputedRatioVecsDate { +impl ComputedFromDateRatio { #[allow(clippy::too_many_arguments)] pub fn forced_import( db: &Database, name: &str, - metric_price: Option<&ComputedBlockLast>, + metric_price: Option<&ComputedFromHeightLast>, version: Version, indexes: &indexes::Vecs, extended: bool, @@ -61,7 +62,7 @@ impl ComputedRatioVecsDate { macro_rules! import { ($suffix:expr) => { - ComputedDateLast::forced_import(db, &format!("{name}_{}", $suffix), v, indexes) + ComputedFromDateLast::forced_import(db, &format!("{name}_{}", $suffix), v, indexes) .unwrap() }; } @@ -69,11 +70,11 @@ impl ComputedRatioVecsDate { // Only compute internally when metric_price is None let price = metric_price .is_none() - .then(|| ComputedDateLast::forced_import(db, name, v, indexes).unwrap()); + .then(|| ComputedFromDateLast::forced_import(db, name, v, indexes).unwrap()); macro_rules! import_sd { ($suffix:expr, $days:expr) => { - ComputedStandardDeviationVecsDate::forced_import( + ComputedFromDateStdDev::forced_import( db, &format!("{name}_{}", $suffix), $days, @@ -97,7 +98,7 @@ impl ComputedRatioVecsDate { ($ratio:expr, $suffix:expr) => { if let Some(mp) = metric_price { $ratio.as_ref().map(|r| { - LazyBinaryDateLast::from_height_and_dateindex_last::( + LazyBinaryFromDateLast::from_height_and_dateindex_last::( &format!("{name}_{}", $suffix), v, mp, @@ -106,7 +107,7 @@ impl ComputedRatioVecsDate { }) } else { price.as_ref().zip($ratio.as_ref()).map(|(p, r)| { - LazyBinaryDateLast::from_computed_both_last::( + LazyBinaryFromDateLast::from_computed_both_last::( &format!("{name}_{}", $suffix), v, p, diff --git a/crates/brk_computer/src/internal/multi/specialized/stddev.rs b/crates/brk_computer/src/internal/multi/from_date/stddev.rs similarity index 83% rename from crates/brk_computer/src/internal/multi/specialized/stddev.rs rename to crates/brk_computer/src/internal/multi/from_date/stddev.rs index f029e348c..d2a699349 100644 --- a/crates/brk_computer/src/internal/multi/specialized/stddev.rs +++ b/crates/brk_computer/src/internal/multi/from_date/stddev.rs @@ -10,44 +10,44 @@ use vecdb::{ use crate::{ComputeIndexes, indexes, price}; -use crate::internal::{ClosePriceTimesRatio, ComputedDateLast, LazyBinaryDateLast}; +use crate::internal::{ClosePriceTimesRatio, ComputedFromDateLast, LazyBinaryFromDateLast}; #[derive(Clone, Traversable)] -pub struct ComputedStandardDeviationVecsDate { +pub struct ComputedFromDateStdDev { days: usize, - pub sma: Option>, + pub sma: Option>, - pub sd: ComputedDateLast, + pub sd: ComputedFromDateLast, - pub zscore: Option>, + pub zscore: Option>, - pub p0_5sd: Option>, - pub p1sd: Option>, - pub p1_5sd: Option>, - pub p2sd: Option>, - pub p2_5sd: Option>, - pub p3sd: Option>, - pub m0_5sd: Option>, - pub m1sd: Option>, - pub m1_5sd: Option>, - pub m2sd: Option>, - pub m2_5sd: Option>, - pub m3sd: Option>, + pub p0_5sd: Option>, + pub p1sd: Option>, + pub p1_5sd: Option>, + pub p2sd: Option>, + pub p2_5sd: Option>, + pub p3sd: Option>, + pub m0_5sd: Option>, + pub m1sd: Option>, + pub m1_5sd: Option>, + pub m2sd: Option>, + pub m2_5sd: Option>, + pub m3sd: Option>, - pub _0sd_usd: Option, StoredF32>>, - pub p0_5sd_usd: Option, StoredF32>>, - pub p1sd_usd: Option, StoredF32>>, - pub p1_5sd_usd: Option, StoredF32>>, - pub p2sd_usd: Option, StoredF32>>, - pub p2_5sd_usd: Option, StoredF32>>, - pub p3sd_usd: Option, StoredF32>>, - pub m0_5sd_usd: Option, StoredF32>>, - pub m1sd_usd: Option, StoredF32>>, - pub m1_5sd_usd: Option, StoredF32>>, - pub m2sd_usd: Option, StoredF32>>, - pub m2_5sd_usd: Option, StoredF32>>, - pub m3sd_usd: Option, StoredF32>>, + pub _0sd_usd: Option, StoredF32>>, + pub p0_5sd_usd: Option, StoredF32>>, + pub p1sd_usd: Option, StoredF32>>, + pub p1_5sd_usd: Option, StoredF32>>, + pub p2sd_usd: Option, StoredF32>>, + pub p2_5sd_usd: Option, StoredF32>>, + pub p3sd_usd: Option, StoredF32>>, + pub m0_5sd_usd: Option, StoredF32>>, + pub m1sd_usd: Option, StoredF32>>, + pub m1_5sd_usd: Option, StoredF32>>, + pub m2sd_usd: Option, StoredF32>>, + pub m2_5sd_usd: Option, StoredF32>>, + pub m3sd_usd: Option, StoredF32>>, } #[derive(Debug, Default)] @@ -94,7 +94,7 @@ impl StandardDeviationVecsOptions { } } -impl ComputedStandardDeviationVecsDate { +impl ComputedFromDateStdDev { #[allow(clippy::too_many_arguments)] pub fn forced_import( db: &Database, @@ -109,7 +109,7 @@ impl ComputedStandardDeviationVecsDate { macro_rules! import { ($suffix:expr) => { - ComputedDateLast::forced_import( + ComputedFromDateLast::forced_import( db, &format!("{name}_{}", $suffix), version, @@ -140,7 +140,7 @@ impl ComputedStandardDeviationVecsDate { .zip($band.as_ref()) .filter(|_| options.price_bands()) .map(|(p, b)| { - LazyBinaryDateLast::from_computed_both_last::( + LazyBinaryFromDateLast::from_computed_both_last::( &format!("{name}_{}", $suffix), version, p, @@ -370,7 +370,7 @@ impl ComputedStandardDeviationVecsDate { Ok(()) } - fn mut_stateful_computed(&mut self) -> impl Iterator> { + fn mut_stateful_computed(&mut self) -> impl Iterator> { [ Some(&mut self.sd), self.p0_5sd.as_mut(), diff --git a/crates/brk_computer/src/internal/multi/value/date/derived_last.rs b/crates/brk_computer/src/internal/multi/from_date/value_derived_last.rs similarity index 74% rename from crates/brk_computer/src/internal/multi/value/date/derived_last.rs rename to crates/brk_computer/src/internal/multi/from_date/value_derived_last.rs index c47131764..ec949cb3f 100644 --- a/crates/brk_computer/src/internal/multi/value/date/derived_last.rs +++ b/crates/brk_computer/src/internal/multi/from_date/value_derived_last.rs @@ -7,22 +7,22 @@ use vecdb::{Database, Exit, IterableBoxedVec}; use crate::{ ComputeIndexes, indexes, - internal::{ComputedDateLast, LazyPeriodsLast, LazyDateLast, SatsToBitcoin}, + internal::{ComputedFromDateLast, LazyDateDerivedLast, LazyFromDateLast, SatsToBitcoin}, price, traits::ComputeFromBitcoin, utils::OptionExt, }; #[derive(Clone, Traversable)] -pub struct ValueLazyPeriodsLast { - pub sats: LazyPeriodsLast, - pub bitcoin: LazyDateLast, - pub dollars: Option>, +pub struct LazyValueDateDerivedLast { + pub sats: LazyDateDerivedLast, + pub bitcoin: LazyFromDateLast, + pub dollars: Option>, } const VERSION: Version = Version::ZERO; -impl ValueLazyPeriodsLast { +impl LazyValueDateDerivedLast { pub fn from_source( db: &Database, name: &str, @@ -31,9 +31,9 @@ impl ValueLazyPeriodsLast { compute_dollars: bool, indexes: &indexes::Vecs, ) -> Result { - let sats = LazyPeriodsLast::from_source(name, version + VERSION, source.clone(), indexes); + let sats = LazyDateDerivedLast::from_source(name, version + VERSION, source.clone(), indexes); - let bitcoin = LazyDateLast::from_derived::( + let bitcoin = LazyFromDateLast::from_derived::( &format!("{name}_btc"), version + VERSION, source, @@ -41,7 +41,7 @@ impl ValueLazyPeriodsLast { ); let dollars = compute_dollars.then(|| { - ComputedDateLast::forced_import(db, &format!("{name}_usd"), version + VERSION, indexes) + ComputedFromDateLast::forced_import(db, &format!("{name}_usd"), version + VERSION, indexes) .unwrap() }); @@ -54,7 +54,7 @@ impl ValueLazyPeriodsLast { pub fn compute_dollars(&mut self, mut compute: F) -> Result<()> where - F: FnMut(&mut ComputedDateLast) -> Result<()>, + F: FnMut(&mut ComputedFromDateLast) -> Result<()>, { if let Some(dollars) = self.dollars.as_mut() { compute(dollars)?; diff --git a/crates/brk_computer/src/internal/multi/value/date/last.rs b/crates/brk_computer/src/internal/multi/from_date/value_last.rs similarity index 87% rename from crates/brk_computer/src/internal/multi/value/date/last.rs rename to crates/brk_computer/src/internal/multi/from_date/value_last.rs index 2e55eadfe..17c609ffa 100644 --- a/crates/brk_computer/src/internal/multi/value/date/last.rs +++ b/crates/brk_computer/src/internal/multi/from_date/value_last.rs @@ -8,21 +8,21 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes, price}; -use super::ValueLazyPeriodsLast; +use super::LazyValueDateDerivedLast; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ValueDateLast { +pub struct ValueFromDateLast { #[traversable(rename = "sats")] pub sats_dateindex: EagerVec>, #[deref] #[deref_mut] - pub rest: ValueLazyPeriodsLast, + pub rest: LazyValueDateDerivedLast, } const VERSION: Version = Version::ZERO; -impl ValueDateLast { +impl ValueFromDateLast { pub fn forced_import( db: &Database, name: &str, @@ -32,7 +32,7 @@ impl ValueDateLast { ) -> Result { let sats_dateindex = EagerVec::forced_import(db, name, version + VERSION)?; - let rest = ValueLazyPeriodsLast::from_source( + let rest = LazyValueDateDerivedLast::from_source( db, name, sats_dateindex.boxed_clone(), @@ -70,7 +70,7 @@ impl ValueDateLast { pub fn compute_dollars(&mut self, compute: F) -> Result<()> where - F: FnMut(&mut crate::internal::ComputedDateLast) -> Result<()>, + F: FnMut(&mut crate::internal::ComputedFromDateLast) -> Result<()>, { self.rest.compute_dollars(compute) } diff --git a/crates/brk_computer/src/internal/multi/value/date/lazy_last.rs b/crates/brk_computer/src/internal/multi/from_date/value_lazy_last.rs similarity index 67% rename from crates/brk_computer/src/internal/multi/value/date/lazy_last.rs rename to crates/brk_computer/src/internal/multi/from_date/value_lazy_last.rs index f610fcd01..c0aaaaee7 100644 --- a/crates/brk_computer/src/internal/multi/value/date/lazy_last.rs +++ b/crates/brk_computer/src/internal/multi/from_date/value_lazy_last.rs @@ -4,21 +4,21 @@ use brk_traversable::Traversable; use brk_types::{Bitcoin, Dollars, Sats, Version}; use vecdb::{IterableCloneableVec, UnaryTransform}; -use crate::internal::{LazyDateLast, ValueBlockLast, ValueDateLast}; +use crate::internal::{LazyFromDateLast, ValueFromHeightLast, ValueFromDateLast}; const VERSION: Version = Version::ZERO; #[derive(Clone, Traversable)] -pub struct LazyValueDateLast { - pub sats: LazyDateLast, - pub bitcoin: LazyDateLast, - pub dollars: Option>, +pub struct LazyValueFromDateLast { + pub sats: LazyFromDateLast, + pub bitcoin: LazyFromDateLast, + pub dollars: Option>, } -impl LazyValueDateLast { +impl LazyValueFromDateLast { pub fn from_source( name: &str, - source: &ValueDateLast, + source: &ValueFromDateLast, version: Version, ) -> Self where @@ -28,14 +28,14 @@ impl LazyValueDateLast { { let v = version + VERSION; - let sats = LazyDateLast::from_derived::( + let sats = LazyFromDateLast::from_derived::( name, v, source.sats_dateindex.boxed_clone(), &source.sats, ); - let bitcoin = LazyDateLast::from_derived::( + let bitcoin = LazyFromDateLast::from_derived::( &format!("{name}_btc"), v, source.sats_dateindex.boxed_clone(), @@ -43,7 +43,7 @@ impl LazyValueDateLast { ); let dollars = source.dollars.as_ref().map(|dollars_source| { - LazyDateLast::from_computed::( + LazyFromDateLast::from_computed::( &format!("{name}_usd"), v, dollars_source.dateindex.boxed_clone(), @@ -56,7 +56,7 @@ impl LazyValueDateLast { pub fn from_block_source( name: &str, - source: &ValueBlockLast, + source: &ValueFromHeightLast, version: Version, ) -> Self where @@ -66,25 +66,25 @@ impl LazyValueDateLast { { let v = version + VERSION; - let sats = LazyDateLast::from_derived::( + let sats = LazyFromDateLast::from_derived::( name, v, - source.sats.rest.dateindex.0.boxed_clone(), + source.sats.rest.dateindex.boxed_clone(), &source.sats.rest.dates, ); - let bitcoin = LazyDateLast::from_derived::( + let bitcoin = LazyFromDateLast::from_derived::( &format!("{name}_btc"), v, - source.sats.rest.dateindex.0.boxed_clone(), + source.sats.rest.dateindex.boxed_clone(), &source.sats.rest.dates, ); let dollars = source.dollars.as_ref().map(|dollars_source| { - LazyDateLast::from_derived::( + LazyFromDateLast::from_derived::( &format!("{name}_usd"), v, - dollars_source.rest.dateindex.0.boxed_clone(), + dollars_source.rest.dateindex.boxed_clone(), &dollars_source.rest.dates, ) }); diff --git a/crates/brk_computer/src/internal/multi/height/binary_full.rs b/crates/brk_computer/src/internal/multi/from_height/binary_full.rs similarity index 74% rename from crates/brk_computer/src/internal/multi/height/binary_full.rs rename to crates/brk_computer/src/internal/multi/from_height/binary_full.rs index 704cf4d21..3d344e8e4 100644 --- a/crates/brk_computer/src/internal/multi/height/binary_full.rs +++ b/crates/brk_computer/src/internal/multi/from_height/binary_full.rs @@ -7,27 +7,27 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableBoxedVec, LazyVecFrom2}; use crate::internal::{ - ComputedBlockFull, ComputedVecValue, DerivedTxFull, LazyBinaryDerivedBlockSumCum, NumericValue, + ComputedFromHeightFull, ComputedVecValue, TxDerivedFull, LazyBinaryHeightDerivedSumCum, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryBlockFull +pub struct LazyBinaryFromHeightFull where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, S2T: ComputedVecValue, { - #[traversable(wrap = "base")] + #[traversable(rename = "base")] pub height: LazyVecFrom2, #[deref] #[deref_mut] - pub rest: LazyBinaryDerivedBlockSumCum, + pub rest: LazyBinaryHeightDerivedSumCum, } const VERSION: Version = Version::ZERO; -impl LazyBinaryBlockFull +impl LazyBinaryFromHeightFull where T: ComputedVecValue + JsonSchema + 'static, S1T: NumericValue + JsonSchema, @@ -38,14 +38,14 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedBlockFull, - source2: &DerivedTxFull, + source1: &ComputedFromHeightFull, + source2: &TxDerivedFull, ) -> Self { let v = version + VERSION; Self { height: LazyVecFrom2::transformed::(name, v, height_source1, height_source2), - rest: LazyBinaryDerivedBlockSumCum::from_derived_full::( + rest: LazyBinaryHeightDerivedSumCum::from_derived_full::( name, v, &source1.dateindex.sum_cum, diff --git a/crates/brk_computer/src/internal/multi/height/binary_last.rs b/crates/brk_computer/src/internal/multi/from_height/binary_last.rs similarity index 55% rename from crates/brk_computer/src/internal/multi/height/binary_last.rs rename to crates/brk_computer/src/internal/multi/from_height/binary_last.rs index b75360666..3b8ed6e28 100644 --- a/crates/brk_computer/src/internal/multi/height/binary_last.rs +++ b/crates/brk_computer/src/internal/multi/from_height/binary_last.rs @@ -7,14 +7,14 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; use crate::internal::{ - ComputedBlockLast, ComputedBlockSumCum, ComputedHeightDateLast, ComputedVecValue, - LazyBinaryDateLast, LazyBinaryDerivedBlockLast, LazyBinaryTransformLast, LazyPeriodsLast, - NumericValue, + ComputedFromHeightLast, ComputedFromHeightSumCum, ComputedFromHeightAndDateLast, ComputedVecValue, + LazyBinaryComputedFromHeightLast, LazyBinaryFromDateLast, LazyBinaryHeightDerivedLast, + LazyBinaryTransformLast, LazyDateDerivedLast, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryBlockLast +pub struct LazyBinaryFromHeightLast where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -23,12 +23,12 @@ where pub height: LazyVecFrom2, #[deref] #[deref_mut] - pub rest: LazyBinaryDerivedBlockLast, + pub rest: LazyBinaryHeightDerivedLast, } const VERSION: Version = Version::ZERO; -impl LazyBinaryBlockLast +impl LazyBinaryFromHeightLast where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -37,8 +37,8 @@ where pub fn from_computed_sum_cum>( name: &str, version: Version, - source1: &ComputedBlockSumCum, - source2: &ComputedBlockSumCum, + source1: &ComputedFromHeightSumCum, + source2: &ComputedFromHeightSumCum, ) -> Self where S1T: PartialOrd, @@ -50,18 +50,18 @@ where height: LazyVecFrom2::transformed::( name, v, - source1.height_cumulative.0.boxed_clone(), - source2.height_cumulative.0.boxed_clone(), + source1.height_cumulative.boxed_clone(), + source2.height_cumulative.boxed_clone(), ), - rest: LazyBinaryDerivedBlockLast::from_computed_sum_cum::(name, v, source1, source2), + rest: LazyBinaryHeightDerivedLast::from_computed_sum_cum::(name, v, source1, source2), } } pub fn from_computed_last>( name: &str, version: Version, - source1: &ComputedBlockLast, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightLast, + source2: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -76,15 +76,15 @@ where source1.height.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockLast::from_computed_last::(name, v, source1, source2), + rest: LazyBinaryHeightDerivedLast::from_computed_last::(name, v, source1, source2), } } pub fn from_computed_height_date_last>( name: &str, version: Version, - source1: &ComputedHeightDateLast, - source2: &ComputedHeightDateLast, + source1: &ComputedFromHeightAndDateLast, + source2: &ComputedFromHeightAndDateLast, ) -> Self where S1T: PartialOrd, @@ -99,18 +99,18 @@ where source1.height.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockLast::from_computed_height_date_last::( + rest: LazyBinaryHeightDerivedLast::from_computed_height_date_last::( name, v, source1, source2, ), } } - /// Create from a ComputedHeightDateLast and a LazyBinaryBlockLast. + /// Create from a ComputedFromHeightAndDateLast and a LazyBinaryFromHeightLast. pub fn from_computed_height_date_and_binary_block( name: &str, version: Version, - source1: &ComputedHeightDateLast, - source2: &LazyBinaryBlockLast, + source1: &ComputedFromHeightAndDateLast, + source2: &LazyBinaryFromHeightLast, ) -> Self where F: BinaryTransform, @@ -127,8 +127,8 @@ where source1.height.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockLast { - dates: LazyBinaryDateLast::from_computed_and_binary_last::( + rest: LazyBinaryHeightDerivedLast { + dates: LazyBinaryFromDateLast::from_computed_and_binary_last::( name, v, &source1.rest, @@ -137,19 +137,19 @@ where difficultyepoch: LazyBinaryTransformLast::from_vecs::( name, v, - source1.difficultyepoch.0.boxed_clone(), + source1.difficultyepoch.boxed_clone(), source2.rest.difficultyepoch.boxed_clone(), ), }, } } - /// Create from a ComputedHeightDateLast and a ComputedBlockLast. + /// Create from a ComputedFromHeightAndDateLast and a ComputedFromHeightLast. pub fn from_computed_height_date_and_block_last>( name: &str, version: Version, - source1: &ComputedHeightDateLast, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightAndDateLast, + source2: &ComputedFromHeightLast, ) -> Self where S1T: PartialOrd, @@ -164,18 +164,18 @@ where source1.height.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockLast::from_computed_height_date_and_block_last::( + rest: LazyBinaryHeightDerivedLast::from_computed_height_date_and_block_last::( name, v, source1, source2, ), } } - /// Create from a LazyBinaryBlockLast and a ComputedBlockLast. + /// Create from a LazyBinaryFromHeightLast and a ComputedFromHeightLast. pub fn from_binary_block_and_computed_block_last( name: &str, version: Version, - source1: &LazyBinaryBlockLast, - source2: &ComputedBlockLast, + source1: &LazyBinaryFromHeightLast, + source2: &ComputedFromHeightLast, ) -> Self where F: BinaryTransform, @@ -192,8 +192,8 @@ where source1.height.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockLast { - dates: LazyBinaryDateLast::from_binary_and_block_last::( + rest: LazyBinaryHeightDerivedLast { + dates: LazyBinaryFromDateLast::from_binary_and_block_last::( name, v, &source1.rest.dates, @@ -209,12 +209,12 @@ where } } - /// Create from two LazyBinaryBlockLast sources. + /// Create from two LazyBinaryFromHeightLast sources. pub fn from_both_binary_block( name: &str, version: Version, - source1: &LazyBinaryBlockLast, - source2: &LazyBinaryBlockLast, + source1: &LazyBinaryFromHeightLast, + source2: &LazyBinaryFromHeightLast, ) -> Self where F: BinaryTransform, @@ -232,8 +232,8 @@ where source1.height.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockLast { - dates: LazyBinaryDateLast::from_both_binary_last::( + rest: LazyBinaryHeightDerivedLast { + dates: LazyBinaryFromDateLast::from_both_binary_last::( name, v, &source1.rest.dates, @@ -251,7 +251,7 @@ where /// Create from separate height, difficultyepoch, and date sources. /// - /// Use when sources are split across different types (e.g., ValueHeightDateLast + ComputedBlockLast). + /// Use when sources are split across different types (e.g., ValueFromHeightAndDateLast + ComputedFromHeightLast). #[allow(clippy::too_many_arguments)] pub fn from_height_difficultyepoch_dates>( name: &str, @@ -261,16 +261,16 @@ where difficultyepoch_source1: IterableBoxedVec, difficultyepoch_source2: IterableBoxedVec, dateindex_source1: IterableBoxedVec, - dates_source1: &LazyPeriodsLast, + dates_source1: &LazyDateDerivedLast, dateindex_source2: IterableBoxedVec, - dates_source2: &LazyPeriodsLast, + dates_source2: &LazyDateDerivedLast, ) -> Self { let v = version + VERSION; Self { height: LazyVecFrom2::transformed::(name, v, height_source1, height_source2), - rest: LazyBinaryDerivedBlockLast { - dates: LazyBinaryDateLast::from_both_derived_last::( + rest: LazyBinaryHeightDerivedLast { + dates: LazyBinaryFromDateLast::from_both_derived_last::( name, v, dateindex_source1, @@ -287,4 +287,86 @@ where }, } } + + /// Create from a ComputedFromHeightAndDateLast and a LazyBinaryComputedFromHeightLast. + pub fn from_computed_height_date_and_lazy_binary_block_last( + name: &str, + version: Version, + source1: &ComputedFromHeightAndDateLast, + source2: &LazyBinaryComputedFromHeightLast, + ) -> Self + where + F: BinaryTransform, + S1T: PartialOrd, + S2aT: ComputedVecValue + JsonSchema, + S2bT: ComputedVecValue + JsonSchema, + { + let v = version + VERSION; + + Self { + height: LazyVecFrom2::transformed::( + name, + v, + source1.height.boxed_clone(), + source2.height.boxed_clone(), + ), + rest: LazyBinaryHeightDerivedLast { + dates: LazyBinaryFromDateLast::from_both_derived_last::( + name, + v, + source1.rest.dateindex.boxed_clone(), + &source1.rest.rest, + source2.rest.dateindex.boxed_clone(), + &source2.rest.dates, + ), + difficultyepoch: LazyBinaryTransformLast::from_vecs::( + name, + v, + source1.difficultyepoch.boxed_clone(), + source2.rest.difficultyepoch.boxed_clone(), + ), + }, + } + } + + /// Create from a LazyBinaryFromHeightLast and a LazyBinaryComputedFromHeightLast. + pub fn from_binary_block_and_lazy_binary_block_last( + name: &str, + version: Version, + source1: &LazyBinaryFromHeightLast, + source2: &LazyBinaryComputedFromHeightLast, + ) -> Self + where + F: BinaryTransform, + S1aT: ComputedVecValue + JsonSchema, + S1bT: ComputedVecValue + JsonSchema, + S2aT: ComputedVecValue + JsonSchema, + S2bT: ComputedVecValue + JsonSchema, + { + let v = version + VERSION; + + Self { + height: LazyVecFrom2::transformed::( + name, + v, + source1.height.boxed_clone(), + source2.height.boxed_clone(), + ), + rest: LazyBinaryHeightDerivedLast { + dates: LazyBinaryFromDateLast::from_binary_and_derived_last::( + name, + v, + &source1.rest.dates, + source2.rest.dateindex.boxed_clone(), + &source2.rest.dates, + ), + difficultyepoch: LazyBinaryTransformLast::from_vecs::( + name, + v, + source1.rest.difficultyepoch.boxed_clone(), + source2.rest.difficultyepoch.boxed_clone(), + ), + }, + } + } } diff --git a/crates/brk_computer/src/internal/multi/height/binary_sum.rs b/crates/brk_computer/src/internal/multi/from_height/binary_sum.rs similarity index 71% rename from crates/brk_computer/src/internal/multi/height/binary_sum.rs rename to crates/brk_computer/src/internal/multi/from_height/binary_sum.rs index 94f504ce7..7997eb9d3 100644 --- a/crates/brk_computer/src/internal/multi/height/binary_sum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/binary_sum.rs @@ -7,7 +7,7 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; use crate::internal::{ - ComputedBlockSum, ComputedDerivedBlockSum, ComputedVecValue, LazyBinaryDerivedBlockSum, + ComputedFromHeightSum, ComputedHeightDerivedSum, ComputedVecValue, LazyBinaryHeightDerivedSum, NumericValue, }; @@ -15,7 +15,7 @@ const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryBlockSum +pub struct LazyBinaryFromHeightSum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -25,10 +25,10 @@ where pub height: LazyVecFrom2, #[deref] #[deref_mut] - pub rest: LazyBinaryDerivedBlockSum, + pub rest: LazyBinaryHeightDerivedSum, } -impl LazyBinaryBlockSum +impl LazyBinaryFromHeightSum where T: ComputedVecValue + JsonSchema + 'static, S1T: NumericValue + JsonSchema, @@ -39,22 +39,22 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedDerivedBlockSum, - source2: &ComputedDerivedBlockSum, + source1: &ComputedHeightDerivedSum, + source2: &ComputedHeightDerivedSum, ) -> Self { let v = version + VERSION; Self { height: LazyVecFrom2::transformed::(name, v, height_source1, height_source2), - rest: LazyBinaryDerivedBlockSum::from_derived::(name, v, source1, source2), + rest: LazyBinaryHeightDerivedSum::from_derived::(name, v, source1, source2), } } pub fn from_computed>( name: &str, version: Version, - source1: &ComputedBlockSum, - source2: &ComputedBlockSum, + source1: &ComputedFromHeightSum, + source2: &ComputedFromHeightSum, ) -> Self { let v = version + VERSION; @@ -65,7 +65,7 @@ where source1.height.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockSum::from_derived::(name, v, &source1.rest, &source2.rest), + rest: LazyBinaryHeightDerivedSum::from_derived::(name, v, &source1.rest, &source2.rest), } } } diff --git a/crates/brk_computer/src/internal/multi/height/binary_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/binary_sum_cum.rs similarity index 73% rename from crates/brk_computer/src/internal/multi/height/binary_sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_height/binary_sum_cum.rs index 61a686e9e..7d9cb507c 100644 --- a/crates/brk_computer/src/internal/multi/height/binary_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/binary_sum_cum.rs @@ -7,13 +7,13 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; use crate::internal::{ - ComputedBlockLast, ComputedBlockSumCum, ComputedDerivedBlockLast, ComputedDerivedBlockSumCum, - ComputedVecValue, LazyBinaryDerivedBlockSumCum, NumericValue, + ComputedFromHeightLast, ComputedFromHeightSumCum, ComputedHeightDerivedLast, ComputedHeightDerivedSumCum, + ComputedVecValue, LazyBinaryHeightDerivedSumCum, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryBlockSumCum +pub struct LazyBinaryFromHeightSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -25,12 +25,12 @@ where pub height_cumulative: LazyVecFrom2, #[deref] #[deref_mut] - pub rest: LazyBinaryDerivedBlockSumCum, + pub rest: LazyBinaryHeightDerivedSumCum, } const VERSION: Version = Version::ZERO; -impl LazyBinaryBlockSumCum +impl LazyBinaryFromHeightSumCum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -41,8 +41,8 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedBlockSumCum, - source2: &ComputedBlockSumCum, + source1: &ComputedFromHeightSumCum, + source2: &ComputedFromHeightSumCum, ) -> Self where S1T: PartialOrd, @@ -55,10 +55,10 @@ where height_cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), v, - source1.height_cumulative.0.boxed_clone(), - source2.height_cumulative.0.boxed_clone(), + source1.height_cumulative.boxed_clone(), + source2.height_cumulative.boxed_clone(), ), - rest: LazyBinaryDerivedBlockSumCum::from_computed_sum_raw::( + rest: LazyBinaryHeightDerivedSumCum::from_computed_sum_raw::( name, v, &source1.dateindex, @@ -76,8 +76,8 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedDerivedBlockSumCum, - source2: &ComputedDerivedBlockSumCum, + source1: &ComputedHeightDerivedSumCum, + source2: &ComputedHeightDerivedSumCum, ) -> Self where S1T: PartialOrd, @@ -90,10 +90,10 @@ where height_cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), v, - source1.height_cumulative.0.boxed_clone(), - source2.height_cumulative.0.boxed_clone(), + source1.height_cumulative.boxed_clone(), + source2.height_cumulative.boxed_clone(), ), - rest: LazyBinaryDerivedBlockSumCum::from_computed_sum_raw::( + rest: LazyBinaryHeightDerivedSumCum::from_computed_sum_raw::( name, v, &source1.dateindex, @@ -113,8 +113,8 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedBlockSumCum, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightSumCum, + source2: &ComputedFromHeightLast, ) -> Self where S1T: PartialOrd, @@ -126,10 +126,10 @@ where height_cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), v, - source1.height_cumulative.0.boxed_clone(), + source1.height_cumulative.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockSumCum::from_computed_last::(name, v, source1, source2), + rest: LazyBinaryHeightDerivedSumCum::from_computed_last::(name, v, source1, source2), } } @@ -138,8 +138,8 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedDerivedBlockSumCum, - source2: &ComputedBlockLast, + source1: &ComputedHeightDerivedSumCum, + source2: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -151,10 +151,10 @@ where height_cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), v, - source1.height_cumulative.0.boxed_clone(), + source1.height_cumulative.boxed_clone(), source2.height.boxed_clone(), ), - rest: LazyBinaryDerivedBlockSumCum::from_derived_computed_last::(name, v, source1, source2), + rest: LazyBinaryHeightDerivedSumCum::from_derived_computed_last::(name, v, source1, source2), } } @@ -163,8 +163,8 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedDerivedBlockSumCum, - source2: &ComputedDerivedBlockLast, + source1: &ComputedHeightDerivedSumCum, + source2: &ComputedHeightDerivedLast, ) -> Self where S1T: NumericValue, @@ -176,10 +176,10 @@ where height_cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), v, - source1.height_cumulative.0.boxed_clone(), + source1.height_cumulative.boxed_clone(), height_source2, ), - rest: LazyBinaryDerivedBlockSumCum::from_derived_last::(name, v, source1, source2), + rest: LazyBinaryHeightDerivedSumCum::from_derived_last::(name, v, source1, source2), } } @@ -188,8 +188,8 @@ where version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ComputedBlockSumCum, - source2: &ComputedDerivedBlockLast, + source1: &ComputedFromHeightSumCum, + source2: &ComputedHeightDerivedLast, ) -> Self where S1T: PartialOrd, @@ -201,10 +201,10 @@ where height_cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), v, - source1.height_cumulative.0.boxed_clone(), + source1.height_cumulative.boxed_clone(), height_source2, ), - rest: LazyBinaryDerivedBlockSumCum::from_computed_derived_last::(name, v, source1, source2), + rest: LazyBinaryHeightDerivedSumCum::from_computed_derived_last::(name, v, source1, source2), } } } diff --git a/crates/brk_computer/src/internal/multi/height/full.rs b/crates/brk_computer/src/internal/multi/from_height/full.rs similarity index 80% rename from crates/brk_computer/src/internal/multi/height/full.rs rename to crates/brk_computer/src/internal/multi/from_height/full.rs index daaf133f2..6c15b7b14 100644 --- a/crates/brk_computer/src/internal/multi/height/full.rs +++ b/crates/brk_computer/src/internal/multi/from_height/full.rs @@ -1,4 +1,4 @@ -//! ComputedBlock with full stats aggregation. +//! ComputedFromHeight with full stats aggregation. use brk_error::Result; @@ -10,24 +10,24 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, ComputedDerivedBlockFull, NumericValue}; +use crate::internal::{ComputedVecValue, ComputedHeightDerivedFull, NumericValue}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedBlockFull +pub struct ComputedFromHeightFull where T: ComputedVecValue + PartialOrd + JsonSchema, { - #[traversable(wrap = "base")] + #[traversable(rename = "base")] pub height: EagerVec>, #[deref] #[deref_mut] - pub rest: ComputedDerivedBlockFull, + pub rest: ComputedHeightDerivedFull, } const VERSION: Version = Version::ZERO; -impl ComputedBlockFull +impl ComputedFromHeightFull where T: NumericValue + JsonSchema, { @@ -41,7 +41,7 @@ where let height: EagerVec> = EagerVec::forced_import(db, name, v)?; - let rest = ComputedDerivedBlockFull::forced_import( + let rest = ComputedHeightDerivedFull::forced_import( db, name, height.boxed_clone(), diff --git a/crates/brk_computer/src/internal/multi/height/sum.rs b/crates/brk_computer/src/internal/multi/from_height/last.rs similarity index 82% rename from crates/brk_computer/src/internal/multi/height/sum.rs rename to crates/brk_computer/src/internal/multi/from_height/last.rs index ba2dbdd2d..be54a280b 100644 --- a/crates/brk_computer/src/internal/multi/height/sum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/last.rs @@ -1,4 +1,4 @@ -//! ComputedBlock using Sum-only aggregation. +//! ComputedFromHeight using only LastVec aggregation. use brk_error::Result; @@ -10,11 +10,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, ComputedDerivedBlockSum, NumericValue}; +use crate::internal::{ComputedVecValue, ComputedHeightDerivedLast, NumericValue}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedBlockSum +pub struct ComputedFromHeightLast where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -22,12 +22,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: ComputedDerivedBlockSum, + pub rest: ComputedHeightDerivedLast, } const VERSION: Version = Version::ZERO; -impl ComputedBlockSum +impl ComputedFromHeightLast where T: NumericValue + JsonSchema, { @@ -42,7 +42,7 @@ where let height: EagerVec> = EagerVec::forced_import(db, name, v)?; let rest = - ComputedDerivedBlockSum::forced_import(db, name, height.boxed_clone(), v, indexes)?; + ComputedHeightDerivedLast::forced_import(db, name, height.boxed_clone(), v, indexes)?; Ok(Self { height, rest }) } diff --git a/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_full.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_full.rs new file mode 100644 index 000000000..6fe0d3771 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_full.rs @@ -0,0 +1,70 @@ +//! LazyBinaryComputedFromHeightFull - block full with lazy binary transform at height level. +//! +//! Height-level values are lazy: `transform(source1[h], source2[h])`. +//! Cumulative, dateindex stats, and difficultyepoch are stored since they +//! require aggregation across heights. + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Height, Version}; +use derive_more::{Deref, DerefMut}; +use schemars::JsonSchema; +use vecdb::{BinaryTransform, Database, Exit, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ComputedHeightDerivedFull, ComputedVecValue, NumericValue}, +}; + +const VERSION: Version = Version::ZERO; + +/// Block full aggregation with lazy binary transform at height + computed derived indexes. +#[derive(Clone, Deref, DerefMut, Traversable)] +#[traversable(merge)] +pub struct LazyBinaryComputedFromHeightFull +where + T: ComputedVecValue + PartialOrd + JsonSchema, + S1T: ComputedVecValue, + S2T: ComputedVecValue, +{ + #[traversable(rename = "base")] + pub height: LazyVecFrom2, + #[deref] + #[deref_mut] + pub rest: ComputedHeightDerivedFull, +} + +impl LazyBinaryComputedFromHeightFull +where + T: NumericValue + JsonSchema, + S1T: ComputedVecValue + JsonSchema, + S2T: ComputedVecValue + JsonSchema, +{ + pub fn forced_import>( + db: &Database, + name: &str, + version: Version, + source1: IterableBoxedVec, + source2: IterableBoxedVec, + indexes: &indexes::Vecs, + ) -> Result { + let v = version + VERSION; + + let height = LazyVecFrom2::transformed::(name, v, source1, source2); + + let rest = + ComputedHeightDerivedFull::forced_import(db, name, height.boxed_clone(), v, indexes)?; + + Ok(Self { height, rest }) + } + + pub fn derive_from( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + ) -> Result<()> { + self.rest + .derive_from(indexes, starting_indexes, &self.height, exit) + } +} diff --git a/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_last.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_last.rs new file mode 100644 index 000000000..b0d564ad9 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_last.rs @@ -0,0 +1,70 @@ +//! LazyBinaryComputedFromHeightLast - block last with lazy binary transform at height level. +//! +//! Height-level value is lazy: `transform(source1[h], source2[h])`. +//! DateIndex last is stored since it requires finding the last value within each date +//! (which may span multiple heights with varying prices). + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Height, Version}; +use derive_more::{Deref, DerefMut}; +use schemars::JsonSchema; +use vecdb::{BinaryTransform, Database, Exit, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ComputedHeightDerivedLast, ComputedVecValue, NumericValue}, +}; + +const VERSION: Version = Version::ZERO; + +/// Block last aggregation with lazy binary transform at height + computed derived indexes. +#[derive(Clone, Deref, DerefMut, Traversable)] +#[traversable(merge)] +pub struct LazyBinaryComputedFromHeightLast +where + T: ComputedVecValue + PartialOrd + JsonSchema, + S1T: ComputedVecValue, + S2T: ComputedVecValue, +{ + pub height: LazyVecFrom2, + #[deref] + #[deref_mut] + #[traversable(flatten)] + pub rest: ComputedHeightDerivedLast, +} + +impl LazyBinaryComputedFromHeightLast +where + T: NumericValue + JsonSchema, + S1T: ComputedVecValue + JsonSchema, + S2T: ComputedVecValue + JsonSchema, +{ + pub fn forced_import>( + db: &Database, + name: &str, + version: Version, + source1: IterableBoxedVec, + source2: IterableBoxedVec, + indexes: &indexes::Vecs, + ) -> Result { + let v = version + VERSION; + + let height = LazyVecFrom2::transformed::(name, v, source1, source2); + + let rest = + ComputedHeightDerivedLast::forced_import(db, name, height.boxed_clone(), v, indexes)?; + + Ok(Self { height, rest }) + } + + pub fn derive_from( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + ) -> Result<()> { + self.rest + .derive_from(indexes, starting_indexes, &self.height, exit) + } +} diff --git a/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum.rs new file mode 100644 index 000000000..7508fdcd8 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum.rs @@ -0,0 +1,70 @@ +//! LazyBinaryComputedFromHeightSum - block sum with lazy binary transform at height level. +//! +//! Height-level sum is lazy: `transform(source1[h], source2[h])`. +//! DateIndex stats are stored since they require aggregation across heights. + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Height, Version}; +use derive_more::{Deref, DerefMut}; +use schemars::JsonSchema; +use vecdb::{BinaryTransform, Database, Exit, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ComputedHeightDerivedSum, ComputedVecValue, NumericValue}, +}; + +const VERSION: Version = Version::ZERO; + +/// Block sum aggregation with lazy binary transform at height + computed derived indexes. +#[derive(Clone, Deref, DerefMut, Traversable)] +#[traversable(merge)] +pub struct LazyBinaryComputedFromHeightSum +where + T: ComputedVecValue + PartialOrd + JsonSchema, + S1T: ComputedVecValue, + S2T: ComputedVecValue, +{ + #[traversable(rename = "sum")] + pub height: LazyVecFrom2, + #[deref] + #[deref_mut] + #[traversable(flatten)] + pub rest: ComputedHeightDerivedSum, +} + +impl LazyBinaryComputedFromHeightSum +where + T: NumericValue + JsonSchema, + S1T: ComputedVecValue + JsonSchema, + S2T: ComputedVecValue + JsonSchema, +{ + pub fn forced_import>( + db: &Database, + name: &str, + version: Version, + source1: IterableBoxedVec, + source2: IterableBoxedVec, + indexes: &indexes::Vecs, + ) -> Result { + let v = version + VERSION; + + let height = LazyVecFrom2::transformed::(name, v, source1, source2); + + let rest = + ComputedHeightDerivedSum::forced_import(db, name, height.boxed_clone(), v, indexes)?; + + Ok(Self { height, rest }) + } + + pub fn derive_from( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + ) -> Result<()> { + self.rest + .derive_from(indexes, starting_indexes, &self.height, exit) + } +} diff --git a/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum_cum.rs new file mode 100644 index 000000000..d0bc35a56 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_binary_computed_sum_cum.rs @@ -0,0 +1,71 @@ +//! LazyBinaryComputedFromHeightSumCum - block sum_cum with lazy binary transform at height level. +//! +//! Height-level sum is lazy: `transform(source1[h], source2[h])`. +//! Cumulative and dateindex stats are stored since they require aggregation +//! across heights. + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Height, Version}; +use derive_more::{Deref, DerefMut}; +use schemars::JsonSchema; +use vecdb::{BinaryTransform, Database, Exit, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ComputedHeightDerivedSumCum, ComputedVecValue, NumericValue}, +}; + +const VERSION: Version = Version::ZERO; + +/// Block sum_cum aggregation with lazy binary transform at height + computed derived indexes. +#[derive(Clone, Deref, DerefMut, Traversable)] +#[traversable(merge)] +pub struct LazyBinaryComputedFromHeightSumCum +where + T: ComputedVecValue + PartialOrd + JsonSchema, + S1T: ComputedVecValue, + S2T: ComputedVecValue, +{ + #[traversable(rename = "sum")] + pub height: LazyVecFrom2, + #[deref] + #[deref_mut] + #[traversable(flatten)] + pub rest: ComputedHeightDerivedSumCum, +} + +impl LazyBinaryComputedFromHeightSumCum +where + T: NumericValue + JsonSchema, + S1T: ComputedVecValue + JsonSchema, + S2T: ComputedVecValue + JsonSchema, +{ + pub fn forced_import>( + db: &Database, + name: &str, + version: Version, + source1: IterableBoxedVec, + source2: IterableBoxedVec, + indexes: &indexes::Vecs, + ) -> Result { + let v = version + VERSION; + + let height = LazyVecFrom2::transformed::(name, v, source1, source2); + + let rest = + ComputedHeightDerivedSumCum::forced_import(db, name, height.boxed_clone(), v, indexes)?; + + Ok(Self { height, rest }) + } + + pub fn derive_from( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + ) -> Result<()> { + self.rest + .derive_from(indexes, starting_indexes, &self.height, exit) + } +} diff --git a/crates/brk_computer/src/internal/multi/height/lazy_height_full.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_computed_full.rs similarity index 79% rename from crates/brk_computer/src/internal/multi/height/lazy_height_full.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_computed_full.rs index 9d70e8cce..1c5c26333 100644 --- a/crates/brk_computer/src/internal/multi/height/lazy_height_full.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_computed_full.rs @@ -1,4 +1,4 @@ -//! LazyBlockFullHeight - block full with lazy height transform. +//! LazyComputedFromHeightFull - block full with lazy height transform. use brk_error::Result; use brk_traversable::Traversable; @@ -9,7 +9,7 @@ use vecdb::{Database, Exit, IterableCloneableVec, LazyVecFrom1, UnaryTransform}; use crate::{ ComputeIndexes, indexes, - internal::{ComputedVecValue, ComputedDerivedBlockFull, NumericValue}, + internal::{ComputedVecValue, ComputedHeightDerivedFull, NumericValue}, }; const VERSION: Version = Version::ZERO; @@ -17,7 +17,7 @@ const VERSION: Version = Version::ZERO; /// Block full aggregation with lazy height transform + computed derived indexes. #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockFullHeight +pub struct LazyComputedFromHeightFull where T: ComputedVecValue + PartialOrd + JsonSchema, S: ComputedVecValue, @@ -26,10 +26,10 @@ where pub height: LazyVecFrom1, #[deref] #[deref_mut] - pub rest: ComputedDerivedBlockFull, + pub rest: ComputedHeightDerivedFull, } -impl LazyBlockFullHeight +impl LazyComputedFromHeightFull where T: NumericValue + JsonSchema, S: ComputedVecValue + JsonSchema, @@ -46,7 +46,7 @@ where let height = LazyVecFrom1::transformed::(name, v, source.boxed_clone()); let rest = - ComputedDerivedBlockFull::forced_import(db, name, height.boxed_clone(), v, indexes)?; + ComputedHeightDerivedFull::forced_import(db, name, height.boxed_clone(), v, indexes)?; Ok(Self { height, rest }) } @@ -64,7 +64,7 @@ where let height = LazyVecFrom1::init(name, v, source.boxed_clone(), init_fn); let rest = - ComputedDerivedBlockFull::forced_import(db, name, height.boxed_clone(), v, indexes)?; + ComputedHeightDerivedFull::forced_import(db, name, height.boxed_clone(), v, indexes)?; Ok(Self { height, rest }) } diff --git a/crates/brk_computer/src/internal/multi/height/lazy_height_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_computed_sum_cum.rs similarity index 82% rename from crates/brk_computer/src/internal/multi/height/lazy_height_sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_computed_sum_cum.rs index 50e99ed2b..a30351b43 100644 --- a/crates/brk_computer/src/internal/multi/height/lazy_height_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_computed_sum_cum.rs @@ -1,4 +1,4 @@ -//! LazyBlockSumCumHeight - block sum+cumulative with lazy height transform. +//! LazyComputedFromHeightSumCum - block sum+cumulative with lazy height transform. //! //! Use this when you need: //! - Lazy height (binary transform from two sources) @@ -14,7 +14,7 @@ use vecdb::{Database, Exit, IterableCloneableVec, LazyVecFrom2}; use crate::{indexes, ComputeIndexes}; -use crate::internal::{ComputedVecValue, ComputedDerivedBlockSumCum, NumericValue}; +use crate::internal::{ComputedVecValue, ComputedHeightDerivedSumCum, NumericValue}; /// Block sum+cumulative with lazy binary height transform + computed derived indexes. /// @@ -23,7 +23,7 @@ use crate::internal::{ComputedVecValue, ComputedDerivedBlockSumCum, NumericValue /// Coarser periods are lazy lookups. #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockSumCumHeight +pub struct LazyComputedFromHeightSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -33,12 +33,12 @@ where pub height: LazyVecFrom2, #[deref] #[deref_mut] - pub rest: ComputedDerivedBlockSumCum, + pub rest: ComputedHeightDerivedSumCum, } const VERSION: Version = Version::ZERO; -impl LazyBlockSumCumHeight +impl LazyComputedFromHeightSumCum where T: NumericValue + JsonSchema, S1T: ComputedVecValue + JsonSchema, @@ -53,7 +53,7 @@ where ) -> Result { let v = version + VERSION; - let rest = ComputedDerivedBlockSumCum::forced_import( + let rest = ComputedHeightDerivedSumCum::forced_import( db, name, height.boxed_clone(), diff --git a/crates/brk_computer/src/internal/multi/height/lazy_distribution.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_distribution.rs similarity index 82% rename from crates/brk_computer/src/internal/multi/height/lazy_distribution.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_distribution.rs index ee7287c40..e9b74d1a3 100644 --- a/crates/brk_computer/src/internal/multi/height/lazy_distribution.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_distribution.rs @@ -1,4 +1,4 @@ -//! LazyBlockDistribution - lazy height + derived distribution (avg/min/max) for indexes. +//! LazyFromHeightDistribution - lazy height + derived distribution (avg/min/max) for indexes. use brk_error::Result; use brk_traversable::Traversable; @@ -9,7 +9,7 @@ use vecdb::{ComputeFrom1, Database, Exit, IterableCloneableVec, LazyVecFrom1, Un use crate::{ ComputeIndexes, indexes, - internal::{ComputedVecValue, ComputedDerivedBlockDistribution, NumericValue}, + internal::{ComputedVecValue, ComputedHeightDerivedDistribution, NumericValue}, }; const VERSION: Version = Version::ZERO; @@ -20,7 +20,7 @@ const VERSION: Version = Version::ZERO; /// Indexes (dateindex + periods + difficultyepoch) store distribution stats (avg/min/max). #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockDistribution +pub struct LazyFromHeightDistribution where T: ComputedVecValue + PartialOrd + JsonSchema, S: ComputedVecValue, @@ -30,10 +30,10 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: ComputedDerivedBlockDistribution, + pub rest: ComputedHeightDerivedDistribution, } -impl LazyBlockDistribution +impl LazyFromHeightDistribution where T: NumericValue + JsonSchema, S: ComputedVecValue + JsonSchema, @@ -49,7 +49,7 @@ where let height = LazyVecFrom1::transformed::(name, v, source.boxed_clone()); - let rest = ComputedDerivedBlockDistribution::forced_import( + let rest = ComputedHeightDerivedDistribution::forced_import( db, name, height.boxed_clone(), @@ -72,7 +72,7 @@ where let height = LazyVecFrom1::init(name, v, source.boxed_clone(), init_fn); - let rest = ComputedDerivedBlockDistribution::forced_import( + let rest = ComputedHeightDerivedDistribution::forced_import( db, name, height.boxed_clone(), diff --git a/crates/brk_computer/src/internal/multi/height/lazy_full.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_full.rs similarity index 75% rename from crates/brk_computer/src/internal/multi/height/lazy_full.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_full.rs index a21f0da6e..ca180a6a1 100644 --- a/crates/brk_computer/src/internal/multi/height/lazy_full.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_full.rs @@ -7,26 +7,26 @@ use schemars::JsonSchema; use vecdb::{IterableBoxedVec, LazyVecFrom1, UnaryTransform}; use crate::internal::{ - ComputedBlockFull, ComputedDerivedBlockFull, ComputedVecValue, LazyDerivedBlockFull, + ComputedFromHeightFull, ComputedHeightDerivedFull, ComputedVecValue, LazyHeightDerivedFull, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockFull +pub struct LazyFromHeightFull where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, { - #[traversable(wrap = "base")] + #[traversable(rename = "base")] pub height: LazyVecFrom1, #[deref] #[deref_mut] - pub rest: LazyDerivedBlockFull, + pub rest: LazyHeightDerivedFull, } const VERSION: Version = Version::ZERO; -impl LazyBlockFull +impl LazyFromHeightFull where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -35,12 +35,12 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedBlockFull, + source: &ComputedFromHeightFull, ) -> Self { let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockFull::from_computed::( + rest: LazyHeightDerivedFull::from_computed::( name, v, &source.dateindex, @@ -54,7 +54,7 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedDerivedBlockFull, + source: &ComputedHeightDerivedFull, ) -> Self where S1T: NumericValue, @@ -62,7 +62,7 @@ where let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockFull::from_derived_computed::(name, v, source), + rest: LazyHeightDerivedFull::from_derived_computed::(name, v, source), } } } diff --git a/crates/brk_computer/src/internal/multi/height/lazy_last.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_last.rs similarity index 55% rename from crates/brk_computer/src/internal/multi/height/lazy_last.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_last.rs index 9edcc31c4..58f92d85f 100644 --- a/crates/brk_computer/src/internal/multi/height/lazy_last.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_last.rs @@ -7,12 +7,12 @@ use schemars::JsonSchema; use vecdb::{IterableBoxedVec, IterableCloneableVec, LazyVecFrom1, UnaryTransform}; use crate::internal::{ - ComputedBlockLast, ComputedDerivedBlockLast, ComputedHeightDateLast, ComputedVecValue, - LazyDerivedBlockLast, NumericValue, + ComputedFromHeightAndDateLast, ComputedFromHeightLast, ComputedHeightDerivedLast, + ComputedVecValue, LazyBinaryComputedFromHeightLast, LazyHeightDerivedLast, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockLast +pub struct LazyFromHeightLast where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -20,12 +20,13 @@ where pub height: LazyVecFrom1, #[deref] #[deref_mut] - pub rest: LazyDerivedBlockLast, + #[traversable(flatten)] + pub rest: LazyHeightDerivedLast, } const VERSION: Version = Version::ZERO; -impl LazyBlockLast +impl LazyFromHeightLast where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -34,7 +35,7 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedBlockLast, + source: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -42,7 +43,7 @@ where let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockLast::from_computed::(name, v, source), + rest: LazyHeightDerivedLast::from_computed::(name, v, source), } } @@ -50,7 +51,7 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedDerivedBlockLast, + source: &ComputedHeightDerivedLast, ) -> Self where S1T: NumericValue, @@ -58,14 +59,14 @@ where let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockLast::from_derived_computed::(name, v, source), + rest: LazyHeightDerivedLast::from_derived_computed::(name, v, source), } } pub fn from_computed_height_date>( name: &str, version: Version, - source: &ComputedHeightDateLast, + source: &ComputedFromHeightAndDateLast, ) -> Self where S1T: PartialOrd, @@ -73,7 +74,26 @@ where let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, source.height.boxed_clone()), - rest: LazyDerivedBlockLast::from_computed_height_date::(name, v, source), + rest: LazyHeightDerivedLast::from_computed_height_date::(name, v, source), + } + } + + pub fn from_lazy_binary_computed( + name: &str, + version: Version, + height_source: IterableBoxedVec, + source: &LazyBinaryComputedFromHeightLast, + ) -> Self + where + F: UnaryTransform, + S1T: NumericValue, + S1aT: ComputedVecValue + JsonSchema, + S1bT: ComputedVecValue + JsonSchema, + { + let v = version + VERSION; + Self { + height: LazyVecFrom1::transformed::(name, v, height_source), + rest: LazyHeightDerivedLast::from_derived_computed::(name, v, &source.rest), } } } diff --git a/crates/brk_computer/src/internal/multi/height/lazy_sum.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_sum.rs similarity index 76% rename from crates/brk_computer/src/internal/multi/height/lazy_sum.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_sum.rs index 77b5e141c..1372edaec 100644 --- a/crates/brk_computer/src/internal/multi/height/lazy_sum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_sum.rs @@ -7,11 +7,11 @@ use schemars::JsonSchema; use vecdb::{IterableBoxedVec, LazyVecFrom1, UnaryTransform}; use crate::internal::{ - ComputedBlockSum, ComputedDerivedBlockSum, ComputedVecValue, LazyDerivedBlockSum, NumericValue, + ComputedFromHeightSum, ComputedHeightDerivedSum, ComputedVecValue, LazyHeightDerivedSum, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockSum +pub struct LazyFromHeightSum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -20,12 +20,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: LazyDerivedBlockSum, + pub rest: LazyHeightDerivedSum, } const VERSION: Version = Version::ZERO; -impl LazyBlockSum +impl LazyFromHeightSum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -34,12 +34,12 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedBlockSum, + source: &ComputedFromHeightSum, ) -> Self { let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockSum::from_computed::( + rest: LazyHeightDerivedSum::from_computed::( name, v, &source.dateindex, @@ -53,7 +53,7 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedDerivedBlockSum, + source: &ComputedHeightDerivedSum, ) -> Self where S1T: NumericValue, @@ -61,7 +61,7 @@ where let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockSum::from_derived_computed::(name, v, source), + rest: LazyHeightDerivedSum::from_derived_computed::(name, v, source), } } } diff --git a/crates/brk_computer/src/internal/multi/height/lazy_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_sum_cum.rs similarity index 74% rename from crates/brk_computer/src/internal/multi/height/lazy_sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_sum_cum.rs index fed0e5d13..215eda718 100644 --- a/crates/brk_computer/src/internal/multi/height/lazy_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_sum_cum.rs @@ -7,12 +7,12 @@ use schemars::JsonSchema; use vecdb::{IterableBoxedVec, LazyVecFrom1, UnaryTransform}; use crate::internal::{ - ComputedBlockSumCum, ComputedDerivedBlockSumCum, ComputedVecValue, LazyDerivedBlockSumCum, - NumericValue, + ComputedFromHeightSumCum, ComputedHeightDerivedSumCum, ComputedVecValue, + LazyHeightDerivedSumCum, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockSumCum +pub struct LazyFromHeightSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -21,12 +21,13 @@ where pub height: LazyVecFrom1, #[deref] #[deref_mut] - pub rest: LazyDerivedBlockSumCum, + #[traversable(flatten)] + pub rest: LazyHeightDerivedSumCum, } const VERSION: Version = Version::ZERO; -impl LazyBlockSumCum +impl LazyFromHeightSumCum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -35,12 +36,12 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedBlockSumCum, + source: &ComputedFromHeightSumCum, ) -> Self { let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockSumCum::from_computed::( + rest: LazyHeightDerivedSumCum::from_computed::( name, v, &source.dateindex, @@ -54,7 +55,7 @@ where name: &str, version: Version, height_source: IterableBoxedVec, - source: &ComputedDerivedBlockSumCum, + source: &ComputedHeightDerivedSumCum, ) -> Self where S1T: NumericValue, @@ -62,7 +63,7 @@ where let v = version + VERSION; Self { height: LazyVecFrom1::transformed::(name, v, height_source), - rest: LazyDerivedBlockSumCum::from_derived_computed::(name, v, source), + rest: LazyHeightDerivedSumCum::from_derived_computed::(name, v, source), } } } diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_block_value.rs b/crates/brk_computer/src/internal/multi/from_height/lazy_value.rs similarity index 87% rename from crates/brk_computer/src/internal/multi/value/height/lazy_block_value.rs rename to crates/brk_computer/src/internal/multi/from_height/lazy_value.rs index d15f26ca4..d0cd1ed19 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_block_value.rs +++ b/crates/brk_computer/src/internal/multi/from_height/lazy_value.rs @@ -3,21 +3,21 @@ use brk_types::{Bitcoin, Close, Dollars, Height, Sats, Version}; use derive_more::{Deref, DerefMut}; use vecdb::{BinaryTransform, IterableBoxedVec, LazyVecFrom1, LazyVecFrom2, UnaryTransform}; -use super::LazyDerivedBlockValue; +use crate::internal::LazyDerivedValuesHeight; const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBlockValue { +pub struct LazyFromHeightValue { #[traversable(rename = "sats")] pub sats: LazyVecFrom1, #[deref] #[deref_mut] - pub rest: LazyDerivedBlockValue, + pub rest: LazyDerivedValuesHeight, } -impl LazyBlockValue { +impl LazyFromHeightValue { pub fn from_sources( name: &str, sats_source: IterableBoxedVec, @@ -50,7 +50,7 @@ impl LazyBlockValue { Self { sats, - rest: LazyDerivedBlockValue { bitcoin, dollars }, + rest: LazyDerivedValuesHeight { bitcoin, dollars }, } } } diff --git a/crates/brk_computer/src/internal/multi/from_height/mod.rs b/crates/brk_computer/src/internal/multi/from_height/mod.rs new file mode 100644 index 000000000..909a820cc --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/mod.rs @@ -0,0 +1,59 @@ +mod binary_full; +mod binary_last; +mod binary_sum; +mod binary_sum_cum; +mod full; +mod last; +mod lazy_distribution; +mod lazy_full; +mod lazy_binary_computed_full; +mod lazy_binary_computed_last; +mod lazy_binary_computed_sum; +mod lazy_binary_computed_sum_cum; +mod lazy_computed_full; +mod lazy_computed_sum_cum; +mod lazy_last; +mod lazy_sum; +mod lazy_sum_cum; +mod sum; +mod sum_cum; +mod value_binary; +mod value_full; +mod value_last; +mod value_lazy_binary_last; +mod lazy_value; +mod value_lazy_computed_sum_cum; +mod value_lazy_last; +mod value_lazy_sum_cum; +mod value_sum; +mod value_sum_cum; + +pub use binary_full::*; +pub use binary_last::*; +pub use binary_sum::*; +pub use binary_sum_cum::*; +pub use full::*; +pub use last::*; +pub use lazy_distribution::*; +pub use lazy_full::*; +pub use lazy_binary_computed_full::*; +pub use lazy_binary_computed_last::*; +pub use lazy_binary_computed_sum::*; +pub use lazy_binary_computed_sum_cum::*; +pub use lazy_computed_full::*; +pub use lazy_computed_sum_cum::*; +pub use lazy_last::*; +pub use lazy_sum::*; +pub use lazy_sum_cum::*; +pub use sum::*; +pub use sum_cum::*; +pub use value_binary::*; +pub use value_full::*; +pub use value_last::*; +pub use value_lazy_binary_last::*; +pub use lazy_value::*; +pub use value_lazy_computed_sum_cum::*; +pub use value_lazy_last::*; +pub use value_lazy_sum_cum::*; +pub use value_sum::*; +pub use value_sum_cum::*; diff --git a/crates/brk_computer/src/internal/multi/height/last.rs b/crates/brk_computer/src/internal/multi/from_height/sum.rs similarity index 85% rename from crates/brk_computer/src/internal/multi/height/last.rs rename to crates/brk_computer/src/internal/multi/from_height/sum.rs index 685c48199..059aea8b5 100644 --- a/crates/brk_computer/src/internal/multi/height/last.rs +++ b/crates/brk_computer/src/internal/multi/from_height/sum.rs @@ -1,4 +1,4 @@ -//! ComputedBlock using only LastVec aggregation. +//! ComputedFromHeight using Sum-only aggregation. use brk_error::Result; @@ -10,11 +10,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, ComputedDerivedBlockLast, NumericValue}; +use crate::internal::{ComputedVecValue, ComputedHeightDerivedSum, NumericValue}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedBlockLast +pub struct ComputedFromHeightSum where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -22,12 +22,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: ComputedDerivedBlockLast, + pub rest: ComputedHeightDerivedSum, } const VERSION: Version = Version::ZERO; -impl ComputedBlockLast +impl ComputedFromHeightSum where T: NumericValue + JsonSchema, { @@ -42,7 +42,7 @@ where let height: EagerVec> = EagerVec::forced_import(db, name, v)?; let rest = - ComputedDerivedBlockLast::forced_import(db, name, height.boxed_clone(), v, indexes)?; + ComputedHeightDerivedSum::forced_import(db, name, height.boxed_clone(), v, indexes)?; Ok(Self { height, rest }) } diff --git a/crates/brk_computer/src/internal/multi/height/sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/sum_cum.rs similarity index 79% rename from crates/brk_computer/src/internal/multi/height/sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_height/sum_cum.rs index 3739d4223..a2dd5bfac 100644 --- a/crates/brk_computer/src/internal/multi/height/sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/sum_cum.rs @@ -1,4 +1,4 @@ -//! ComputedBlock using SumCum aggregation. +//! ComputedFromHeight using SumCum aggregation. use brk_error::Result; @@ -11,13 +11,13 @@ use vecdb::{ IterableCloneableVec, IterableVec, PcoVec, VecIndex, }; -use crate::{indexes, ComputeIndexes}; +use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedVecValue, ComputedDerivedBlockSumCum, NumericValue}; +use crate::internal::{ComputedHeightDerivedSumCum, ComputedVecValue, NumericValue}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedBlockSumCum +pub struct ComputedFromHeightSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -25,12 +25,13 @@ where pub height: EagerVec>, #[deref] #[deref_mut] - pub rest: ComputedDerivedBlockSumCum, + #[traversable(flatten)] + pub rest: ComputedHeightDerivedSumCum, } const VERSION: Version = Version::ZERO; -impl ComputedBlockSumCum +impl ComputedFromHeightSumCum where T: NumericValue + JsonSchema, { @@ -44,13 +45,8 @@ where let height: EagerVec> = EagerVec::forced_import(db, name, v)?; - let rest = ComputedDerivedBlockSumCum::forced_import( - db, - name, - height.boxed_clone(), - v, - indexes, - )?; + let rest = + ComputedHeightDerivedSumCum::forced_import(db, name, height.boxed_clone(), v, indexes)?; Ok(Self { height, rest }) } @@ -76,7 +72,8 @@ where starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { - self.rest.derive_from(indexes, starting_indexes, &self.height, exit) + self.rest + .derive_from(indexes, starting_indexes, &self.height, exit) } /// Derive from an external height source (e.g., a LazyVec). @@ -101,6 +98,7 @@ where } self.height.write()?; - self.rest.derive_from(indexes, starting_indexes, &self.height, exit) + self.rest + .derive_from(indexes, starting_indexes, &self.height, exit) } } diff --git a/crates/brk_computer/src/internal/multi/value/height/binary.rs b/crates/brk_computer/src/internal/multi/from_height/value_binary.rs similarity index 69% rename from crates/brk_computer/src/internal/multi/value/height/binary.rs rename to crates/brk_computer/src/internal/multi/from_height/value_binary.rs index 4cce4d0bc..3684c7b19 100644 --- a/crates/brk_computer/src/internal/multi/value/height/binary.rs +++ b/crates/brk_computer/src/internal/multi/from_height/value_binary.rs @@ -4,34 +4,34 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec}; use crate::internal::{ - ComputedVecValue, ValueDerivedBlockSumCum, LazyBinaryBlockSumCum, LazyValueBlockSumCum, - ValueBlockSumCum, + ComputedVecValue, ValueHeightDerivedSumCum, LazyBinaryFromHeightSumCum, LazyValueFromHeightSumCum, + ValueFromHeightSumCum, }; -/// Lazy value vecs computed from two ValueBlockSumCum sources via binary transforms. +/// Lazy value vecs computed from two ValueFromHeightSumCum sources via binary transforms. /// Used for computing coinbase = subsidy + fee. #[derive(Clone, Traversable)] -pub struct ValueBinaryBlock { - pub sats: LazyBinaryBlockSumCum, - pub bitcoin: LazyBinaryBlockSumCum, - pub dollars: Option>, +pub struct ValueBinaryFromHeight { + pub sats: LazyBinaryFromHeightSumCum, + pub bitcoin: LazyBinaryFromHeightSumCum, + pub dollars: Option>, } -impl ValueBinaryBlock { +impl ValueBinaryFromHeight { pub fn from_computed( name: &str, version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ValueBlockSumCum, - source2: &ValueBlockSumCum, + source1: &ValueFromHeightSumCum, + source2: &ValueFromHeightSumCum, ) -> Self where SatsF: BinaryTransform, BitcoinF: BinaryTransform, DollarsF: BinaryTransform, { - let sats = LazyBinaryBlockSumCum::from_computed::( + let sats = LazyBinaryFromHeightSumCum::from_computed::( name, version, height_source1.boxed_clone(), @@ -40,7 +40,7 @@ impl ValueBinaryBlock { &source2.sats, ); - let bitcoin = LazyBinaryBlockSumCum::from_computed::( + let bitcoin = LazyBinaryFromHeightSumCum::from_computed::( &format!("{name}_btc"), version, height_source1, @@ -49,18 +49,20 @@ impl ValueBinaryBlock { &source2.sats, ); + // For dollars: use from_derived since the height is now lazy (LazyVecFrom2) + // The rest (cumulative, dateindex) is still ComputedHeightDerivedSumCum let dollars = source1 .dollars .as_ref() .zip(source2.dollars.as_ref()) .map(|(d1, d2)| { - LazyBinaryBlockSumCum::from_computed::( + LazyBinaryFromHeightSumCum::from_derived::( &format!("{name}_usd"), version, d1.height.boxed_clone(), d2.height.boxed_clone(), - d1, - d2, + &d1.rest, + &d2.rest, ) }); @@ -76,15 +78,15 @@ impl ValueBinaryBlock { version: Version, height_source1: IterableBoxedVec, height_source2: IterableBoxedVec, - source1: &ValueDerivedBlockSumCum, - source2: &ValueDerivedBlockSumCum, + source1: &ValueHeightDerivedSumCum, + source2: &ValueHeightDerivedSumCum, ) -> Self where SatsF: BinaryTransform, BitcoinF: BinaryTransform, DollarsF: BinaryTransform, { - let sats = LazyBinaryBlockSumCum::from_derived::( + let sats = LazyBinaryFromHeightSumCum::from_derived::( name, version, height_source1.boxed_clone(), @@ -93,7 +95,7 @@ impl ValueBinaryBlock { &source2.sats, ); - let bitcoin = LazyBinaryBlockSumCum::from_derived::( + let bitcoin = LazyBinaryFromHeightSumCum::from_derived::( &format!("{name}_btc"), version, height_source1, @@ -107,11 +109,11 @@ impl ValueBinaryBlock { .as_ref() .zip(source2.dollars.as_ref()) .map(|(d1, d2)| { - LazyBinaryBlockSumCum::from_derived::( + LazyBinaryFromHeightSumCum::from_derived::( &format!("{name}_usd"), version, - d1.height_cumulative.0.boxed_clone(), - d2.height_cumulative.0.boxed_clone(), + d1.height_cumulative.boxed_clone(), + d2.height_cumulative.boxed_clone(), d1, d2, ) @@ -127,8 +129,8 @@ impl ValueBinaryBlock { pub fn from_lazy( name: &str, version: Version, - source1: &LazyValueBlockSumCum, - source2: &LazyValueBlockSumCum, + source1: &LazyValueFromHeightSumCum, + source2: &LazyValueFromHeightSumCum, ) -> Self where SatsF: BinaryTransform, @@ -137,7 +139,7 @@ impl ValueBinaryBlock { S1T: ComputedVecValue + JsonSchema, S2T: ComputedVecValue + JsonSchema, { - let sats = LazyBinaryBlockSumCum::from_derived::( + let sats = LazyBinaryFromHeightSumCum::from_derived::( name, version, source1.sats.height.boxed_clone(), @@ -146,7 +148,7 @@ impl ValueBinaryBlock { &source2.sats.rest, ); - let bitcoin = LazyBinaryBlockSumCum::from_derived::( + let bitcoin = LazyBinaryFromHeightSumCum::from_derived::( &format!("{name}_btc"), version, source1.sats.height.boxed_clone(), @@ -160,7 +162,7 @@ impl ValueBinaryBlock { .as_ref() .zip(source2.dollars.as_ref()) .map(|(d1, d2)| { - LazyBinaryBlockSumCum::from_derived::( + LazyBinaryFromHeightSumCum::from_derived::( &format!("{name}_usd"), version, d1.height.boxed_clone(), diff --git a/crates/brk_computer/src/internal/multi/from_height/value_full.rs b/crates/brk_computer/src/internal/multi/from_height/value_full.rs new file mode 100644 index 000000000..d74a63600 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/value_full.rs @@ -0,0 +1,94 @@ +//! Value type for Full pattern from Height. +//! +//! Height-level USD stats are lazy: `sats * price`. +//! Cumulative and dateindex stats are stored since they require aggregation +//! across heights with varying prices. + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Bitcoin, Close, Dollars, Height, Sats, Version}; +use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, PcoVec}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ + ComputedFromHeightFull, LazyBinaryComputedFromHeightFull, LazyFromHeightFull, + SatsTimesClosePrice, SatsToBitcoin, + }, + price, +}; + +/// Lazy dollars type: `sats[h] * price[h]` at height level, stored derived. +pub type LazyDollarsFromHeightFull = + LazyBinaryComputedFromHeightFull>; + +#[derive(Clone, Traversable)] +pub struct ValueFromHeightFull { + pub sats: ComputedFromHeightFull, + pub bitcoin: LazyFromHeightFull, + pub dollars: Option, +} + +const VERSION: Version = Version::ONE; // Bumped for lazy height dollars + +impl ValueFromHeightFull { + pub fn forced_import( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + price: Option<&price::Vecs>, + ) -> Result { + let v = version + VERSION; + + let sats = ComputedFromHeightFull::forced_import(db, name, v, indexes)?; + + let bitcoin = LazyFromHeightFull::from_computed::( + &format!("{name}_btc"), + v, + sats.height.boxed_clone(), + &sats, + ); + + let dollars = price + .map(|price| { + LazyBinaryComputedFromHeightFull::forced_import::( + db, + &format!("{name}_usd"), + v, + sats.height.boxed_clone(), + price.usd.split.close.height.boxed_clone(), + indexes, + ) + }) + .transpose()?; + + Ok(Self { + sats, + bitcoin, + dollars, + }) + } + + pub fn compute_all( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + mut compute: F, + ) -> Result<()> + where + F: FnMut(&mut EagerVec>) -> Result<()>, + { + // Compute sats + self.sats + .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; + + // Derive dollars (height is lazy, just compute cumulative and dateindex) + if let Some(dollars) = self.dollars.as_mut() { + dollars.derive_from(indexes, starting_indexes, exit)?; + } + + Ok(()) + } +} diff --git a/crates/brk_computer/src/internal/multi/from_height/value_last.rs b/crates/brk_computer/src/internal/multi/from_height/value_last.rs new file mode 100644 index 000000000..55f2d4e44 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/value_last.rs @@ -0,0 +1,110 @@ +//! Value type for Last pattern from Height. +//! +//! Height-level USD value is lazy: `sats * price`. +//! DateIndex last is stored since it requires finding the last value within each date. + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Bitcoin, Close, Dollars, Height, Sats, Version}; +use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, PcoVec}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ + ComputedFromHeightLast, LazyBinaryComputedFromHeightLast, LazyFromHeightLast, + SatsTimesClosePrice, SatsToBitcoin, + }, + price, +}; + +/// Lazy dollars type: `sats[h] * price[h]` at height level, stored derived. +pub type LazyDollarsFromHeightLast = + LazyBinaryComputedFromHeightLast>; + +#[derive(Clone, Traversable)] +pub struct ValueFromHeightLast { + pub sats: ComputedFromHeightLast, + pub bitcoin: LazyFromHeightLast, + pub dollars: Option, +} + +const VERSION: Version = Version::ONE; // Bumped for lazy height dollars + +impl ValueFromHeightLast { + pub fn forced_import( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + price: Option<&price::Vecs>, + ) -> Result { + let v = version + VERSION; + + let sats = ComputedFromHeightLast::forced_import(db, name, v, indexes)?; + + let bitcoin = LazyFromHeightLast::from_computed::( + &format!("{name}_btc"), + v, + sats.height.boxed_clone(), + &sats, + ); + + let dollars = price + .map(|price| { + LazyBinaryComputedFromHeightLast::forced_import::( + db, + &format!("{name}_usd"), + v, + sats.height.boxed_clone(), + price.usd.split.close.height.boxed_clone(), + indexes, + ) + }) + .transpose()?; + + Ok(Self { + sats, + bitcoin, + dollars, + }) + } + + pub fn compute_all( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + mut compute: F, + ) -> Result<()> + where + F: FnMut(&mut EagerVec>) -> Result<()>, + { + // Compute sats (closure receives &mut height vec) + self.sats + .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; + + // Derive dollars (height is lazy, just compute dateindex last) + if let Some(dollars) = self.dollars.as_mut() { + dollars.derive_from(indexes, starting_indexes, exit)?; + } + + Ok(()) + } + + /// Compute derived vecs from existing height data. + pub fn compute_rest( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + ) -> Result<()> { + self.sats.compute_rest(indexes, starting_indexes, exit)?; + + // Derive dollars (height is lazy, just compute dateindex last) + if let Some(dollars) = self.dollars.as_mut() { + dollars.derive_from(indexes, starting_indexes, exit)?; + } + + Ok(()) + } +} diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_binary_last.rs b/crates/brk_computer/src/internal/multi/from_height/value_lazy_binary_last.rs similarity index 77% rename from crates/brk_computer/src/internal/multi/value/height/lazy_binary_last.rs rename to crates/brk_computer/src/internal/multi/from_height/value_lazy_binary_last.rs index ab978da71..3e481e73a 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_binary_last.rs +++ b/crates/brk_computer/src/internal/multi/from_height/value_lazy_binary_last.rs @@ -5,9 +5,9 @@ use brk_types::{Bitcoin, Close, Dollars, Sats, Version}; use derive_more::{Deref, DerefMut}; use vecdb::{BinaryTransform, IterableCloneableVec, UnaryTransform}; -use super::{LazyBlockValue, LazyTransformedValueDifficultyEpoch}; -use crate::internal::LazyValueDateLast; -use crate::{internal::ValueBlockLast, price}; +use super::LazyFromHeightValue; +use crate::internal::{LazyTransformedValueDifficultyEpoch, LazyValueFromDateLast}; +use crate::{internal::ValueFromHeightLast, price}; const VERSION: Version = Version::ZERO; @@ -19,21 +19,21 @@ const VERSION: Version = Version::ZERO; /// No merge at this level - denominations (sats, bitcoin, dollars) stay as separate branches. /// Each inner field has merge which combines indexes within each denomination. #[derive(Clone, Deref, DerefMut, Traversable)] -pub struct LazyBinaryValueBlockLast { +pub struct LazyBinaryValueFromHeightLast { #[traversable(flatten)] - pub height: LazyBlockValue, + pub height: LazyFromHeightValue, #[traversable(flatten)] pub difficultyepoch: LazyTransformedValueDifficultyEpoch, #[deref] #[deref_mut] #[traversable(flatten)] - pub dates: LazyValueDateLast, + pub dates: LazyValueFromDateLast, } -impl LazyBinaryValueBlockLast { +impl LazyBinaryValueFromHeightLast { pub fn from_block_source( name: &str, - source: &ValueBlockLast, + source: &ValueFromHeightLast, price: Option<&price::Vecs>, version: Version, ) -> Self @@ -47,7 +47,7 @@ impl LazyBinaryValueBlockLast { let price_source = price.map(|p| p.usd.split.close.height.boxed_clone()); - let height = LazyBlockValue::from_sources::( + let height = LazyFromHeightValue::from_sources::( name, source.sats.height.boxed_clone(), price_source, @@ -60,7 +60,7 @@ impl LazyBinaryValueBlockLast { HeightDollarsTransform, >(name, source, price, v); - let dates = LazyValueDateLast::from_block_source::( + let dates = LazyValueFromDateLast::from_block_source::( name, source, v, ); diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_computed_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/value_lazy_computed_sum_cum.rs similarity index 79% rename from crates/brk_computer/src/internal/multi/value/height/lazy_computed_sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_height/value_lazy_computed_sum_cum.rs index a26bbeadf..c79fdc97f 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_computed_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/value_lazy_computed_sum_cum.rs @@ -14,7 +14,7 @@ use vecdb::{Database, Exit, IterableCloneableVec, LazyVecFrom2}; use crate::{ ComputeIndexes, indexes, internal::{ - ClosePriceTimesSats, ComputedBlockSumCum, LazyBlockSumCum, LazyBlockSumCumHeight, + ClosePriceTimesSats, ComputedFromHeightSumCum, LazyFromHeightSumCum, LazyComputedFromHeightSumCum, SatsToBitcoin, }, price, @@ -26,15 +26,15 @@ use crate::{ /// Dollars height is lazy (price × sats). /// Cumulative and dateindex aggregates are stored for both. #[derive(Clone, Traversable)] -pub struct LazyComputedValueBlockSumCum { - pub sats: ComputedBlockSumCum, - pub bitcoin: LazyBlockSumCum, - pub dollars: Option, Sats>>, +pub struct LazyComputedValueFromHeightSumCum { + pub sats: ComputedFromHeightSumCum, + pub bitcoin: LazyFromHeightSumCum, + pub dollars: Option, Sats>>, } const VERSION: Version = Version::ZERO; -impl LazyComputedValueBlockSumCum { +impl LazyComputedValueFromHeightSumCum { pub fn forced_import( db: &Database, name: &str, @@ -44,9 +44,9 @@ impl LazyComputedValueBlockSumCum { ) -> Result { let v = version + VERSION; - let sats = ComputedBlockSumCum::forced_import(db, name, v, indexes)?; + let sats = ComputedFromHeightSumCum::forced_import(db, name, v, indexes)?; - let bitcoin = LazyBlockSumCum::from_computed::( + let bitcoin = LazyFromHeightSumCum::from_computed::( &format!("{name}_btc"), v, sats.height.boxed_clone(), @@ -61,7 +61,7 @@ impl LazyComputedValueBlockSumCum { sats.height.boxed_clone(), ); - Some(LazyBlockSumCumHeight::forced_import( + Some(LazyComputedFromHeightSumCum::forced_import( db, &format!("{name}_usd"), v, diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_last.rs b/crates/brk_computer/src/internal/multi/from_height/value_lazy_last.rs similarity index 57% rename from crates/brk_computer/src/internal/multi/value/height/lazy_last.rs rename to crates/brk_computer/src/internal/multi/from_height/value_lazy_last.rs index be56e017c..73357cd7a 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_last.rs +++ b/crates/brk_computer/src/internal/multi/from_height/value_lazy_last.rs @@ -1,31 +1,30 @@ -//! Lazy value wrapper for ValueBlockLast - all transforms are lazy. +//! Lazy value wrapper for ValueFromHeightLast - all transforms are lazy. use brk_traversable::Traversable; use brk_types::{Dollars, Sats, Version}; use derive_more::{Deref, DerefMut}; use vecdb::UnaryTransform; -use super::LazyValueBlockHeight; -use crate::internal::{LazyValueDateLast, SatsToBitcoin, ValueBlockLast}; +use crate::internal::{LazyValueFromDateLast, LazyValueHeight, SatsToBitcoin, ValueFromHeightLast}; const VERSION: Version = Version::ZERO; -/// Lazy value wrapper with height + date last transforms from ValueBlockLast. +/// Lazy value wrapper with height + date last transforms from ValueFromHeightLast. #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyValueBlockLast { +pub struct LazyValueFromHeightLast { #[traversable(flatten)] - pub height: LazyValueBlockHeight, + pub height: LazyValueHeight, #[deref] #[deref_mut] #[traversable(flatten)] - pub dates: LazyValueDateLast, + pub dates: LazyValueFromDateLast, } -impl LazyValueBlockLast { +impl LazyValueFromHeightLast { pub fn from_block_source( name: &str, - source: &ValueBlockLast, + source: &ValueFromHeightLast, version: Version, ) -> Self where @@ -35,9 +34,9 @@ impl LazyValueBlockLast { let v = version + VERSION; let height = - LazyValueBlockHeight::from_block_source::(name, source, v); + LazyValueHeight::from_block_source::(name, source, v); - let dates = LazyValueDateLast::from_block_source::( + let dates = LazyValueFromDateLast::from_block_source::( name, source, v, ); diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/value_lazy_sum_cum.rs similarity index 80% rename from crates/brk_computer/src/internal/multi/value/height/lazy_sum_cum.rs rename to crates/brk_computer/src/internal/multi/from_height/value_lazy_sum_cum.rs index 02ef1142f..2f4017953 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/from_height/value_lazy_sum_cum.rs @@ -13,7 +13,7 @@ use vecdb::{ use crate::{ ComputeIndexes, indexes, internal::{ - ClosePriceTimesSats, ComputedVecValue, LazyBlockSumCum, LazyBlockSumCumHeight, + ClosePriceTimesSats, ComputedVecValue, LazyFromHeightSumCum, LazyComputedFromHeightSumCum, SatsToBitcoin, }, price, @@ -25,19 +25,19 @@ use crate::{ /// Dollars height is also lazy (price × sats). /// Cumulative and dateindex are stored. #[derive(Clone, Traversable)] -pub struct LazyValueBlockSumCum +pub struct LazyValueFromHeightSumCum where S1T: ComputedVecValue + JsonSchema, S2T: ComputedVecValue + JsonSchema, { - pub sats: LazyBlockSumCumHeight, - pub bitcoin: LazyBlockSumCum, - pub dollars: Option, Sats>>, + pub sats: LazyComputedFromHeightSumCum, + pub bitcoin: LazyFromHeightSumCum, + pub dollars: Option, Sats>>, } const VERSION: Version = Version::ZERO; -impl LazyValueBlockSumCum +impl LazyValueFromHeightSumCum where S1T: ComputedVecValue + JsonSchema, S2T: ComputedVecValue + JsonSchema, @@ -57,9 +57,9 @@ where let v = version + VERSION; let sats_height = LazyVecFrom2::transformed::(name, v, source1, source2); - let sats = LazyBlockSumCumHeight::forced_import(db, name, v, indexes, sats_height)?; + let sats = LazyComputedFromHeightSumCum::forced_import(db, name, v, indexes, sats_height)?; - let bitcoin = LazyBlockSumCum::from_derived::( + let bitcoin = LazyFromHeightSumCum::from_derived::( &format!("{name}_btc"), v, sats.height.boxed_clone(), @@ -74,7 +74,7 @@ where sats.height.boxed_clone(), ); - Some(LazyBlockSumCumHeight::forced_import( + Some(LazyComputedFromHeightSumCum::forced_import( db, &format!("{name}_usd"), v, diff --git a/crates/brk_computer/src/internal/multi/from_height/value_sum.rs b/crates/brk_computer/src/internal/multi/from_height/value_sum.rs new file mode 100644 index 000000000..5bf4eb65d --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/value_sum.rs @@ -0,0 +1,93 @@ +//! Value type for Sum pattern from Height. +//! +//! Height-level USD value is lazy: `sats * price`. +//! DateIndex sum is stored since it requires aggregation across heights with varying prices. + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Bitcoin, Close, Dollars, Height, Sats, Version}; +use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, PcoVec}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ + ComputedFromHeightSum, LazyBinaryComputedFromHeightSum, LazyFromHeightSum, + SatsTimesClosePrice, SatsToBitcoin, + }, + price, +}; + +/// Lazy dollars type: `sats[h] * price[h]` at height level, stored derived. +pub type LazyDollarsFromHeightSum = + LazyBinaryComputedFromHeightSum>; + +#[derive(Clone, Traversable)] +pub struct ValueFromHeightSum { + pub sats: ComputedFromHeightSum, + pub bitcoin: LazyFromHeightSum, + pub dollars: Option, +} + +const VERSION: Version = Version::ONE; // Bumped for lazy height dollars + +impl ValueFromHeightSum { + pub fn forced_import( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + price: Option<&price::Vecs>, + ) -> Result { + let v = version + VERSION; + + let sats = ComputedFromHeightSum::forced_import(db, name, v, indexes)?; + + let bitcoin = LazyFromHeightSum::from_computed::( + &format!("{name}_btc"), + v, + sats.height.boxed_clone(), + &sats, + ); + + let dollars = price + .map(|price| { + LazyBinaryComputedFromHeightSum::forced_import::( + db, + &format!("{name}_usd"), + v, + sats.height.boxed_clone(), + price.usd.split.close.height.boxed_clone(), + indexes, + ) + }) + .transpose()?; + + Ok(Self { + sats, + bitcoin, + dollars, + }) + } + + pub fn compute_all( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + mut compute: F, + ) -> Result<()> + where + F: FnMut(&mut EagerVec>) -> Result<()>, + { + // Compute sats (closure receives &mut height vec) + self.sats + .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; + + // Derive dollars (height is lazy, just compute dateindex sum) + if let Some(dollars) = self.dollars.as_mut() { + dollars.derive_from(indexes, starting_indexes, exit)?; + } + + Ok(()) + } +} diff --git a/crates/brk_computer/src/internal/multi/from_height/value_sum_cum.rs b/crates/brk_computer/src/internal/multi/from_height/value_sum_cum.rs new file mode 100644 index 000000000..c9e0054b8 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height/value_sum_cum.rs @@ -0,0 +1,131 @@ +//! Value type for SumCum pattern from Height. +//! +//! Height-level USD sum is lazy: `sats * price`. +//! Cumulative and dateindex stats are stored since they require aggregation +//! across heights with varying prices. + +use brk_error::Result; +use brk_traversable::Traversable; +use brk_types::{Bitcoin, Close, Dollars, Height, Sats, Version}; +use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, IterableVec, PcoVec}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ + ComputedFromHeightSumCum, LazyBinaryComputedFromHeightSumCum, LazyFromHeightSumCum, + SatsTimesClosePrice, SatsToBitcoin, + }, + price, +}; + +/// Lazy dollars type: `sats[h] * price[h]` at height level, stored derived. +pub type LazyDollarsFromHeightSumCum = + LazyBinaryComputedFromHeightSumCum>; + +#[derive(Clone, Traversable)] +pub struct ValueFromHeightSumCum { + pub sats: ComputedFromHeightSumCum, + pub bitcoin: LazyFromHeightSumCum, + pub dollars: Option, +} + +const VERSION: Version = Version::ONE; // Bumped for lazy height dollars + +impl ValueFromHeightSumCum { + pub fn forced_import( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + price: Option<&price::Vecs>, + ) -> Result { + let v = version + VERSION; + + let sats = ComputedFromHeightSumCum::forced_import(db, name, v, indexes)?; + + let bitcoin = LazyFromHeightSumCum::from_computed::( + &format!("{name}_btc"), + v, + sats.height.boxed_clone(), + &sats, + ); + + let dollars = price + .map(|price| { + LazyBinaryComputedFromHeightSumCum::forced_import::( + db, + &format!("{name}_usd"), + v, + sats.height.boxed_clone(), + price.usd.split.close.height.boxed_clone(), + indexes, + ) + }) + .transpose()?; + + Ok(Self { + sats, + bitcoin, + dollars, + }) + } + + pub fn compute_all( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + mut compute: F, + ) -> Result<()> + where + F: FnMut(&mut EagerVec>) -> Result<()>, + { + // Compute sats (closure receives &mut height vec) + self.sats + .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; + + // Derive dollars (height is lazy, just compute cumulative and dateindex) + if let Some(dollars) = self.dollars.as_mut() { + dollars.derive_from(indexes, starting_indexes, exit)?; + } + + Ok(()) + } + + /// Derive from an external height source (e.g., a LazyVec). + pub fn derive_from( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + source: &impl IterableVec, + exit: &Exit, + ) -> Result<()> { + // Derive sats from source + self.sats + .derive_from(indexes, starting_indexes, source, exit)?; + + // Derive dollars (height is lazy, just compute cumulative and dateindex) + if let Some(dollars) = self.dollars.as_mut() { + dollars.derive_from(indexes, starting_indexes, exit)?; + } + + Ok(()) + } + + /// Compute rest (derived indexes) from already-computed height. + pub fn compute_rest( + &mut self, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + ) -> Result<()> { + self.sats.compute_rest(indexes, starting_indexes, exit)?; + + // Derive dollars (height is lazy, just compute cumulative and dateindex) + if let Some(dollars) = self.dollars.as_mut() { + dollars.derive_from(indexes, starting_indexes, exit)?; + } + + Ok(()) + } +} diff --git a/crates/brk_computer/src/internal/multi/height/binary_height_date_last.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/binary_last.rs similarity index 67% rename from crates/brk_computer/src/internal/multi/height/binary_height_date_last.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/binary_last.rs index fba0ab0d0..741c05289 100644 --- a/crates/brk_computer/src/internal/multi/height/binary_height_date_last.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/binary_last.rs @@ -1,4 +1,4 @@ -//! LazyBinaryHeightDateLast - height storage + binary transform lazy date periods. +//! LazyBinaryFromHeightAndDateLast - height storage + binary transform lazy date periods. //! //! Use this when height is stored as EagerVec and date periods are lazy binary transforms. @@ -9,14 +9,14 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, EagerVec, PcoVec}; use crate::internal::{ - ComputedDateLast, ComputedHeightDateLast, ComputedVecValue, LazyBinaryDateLast, + ComputedFromDateLast, ComputedFromHeightAndDateLast, ComputedVecValue, LazyBinaryFromDateLast, }; const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryHeightDateLast +pub struct LazyBinaryFromHeightAndDateLast where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -26,10 +26,10 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: LazyBinaryDateLast, + pub rest: LazyBinaryFromDateLast, } -impl LazyBinaryHeightDateLast +impl LazyBinaryFromHeightAndDateLast where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -39,14 +39,14 @@ where name: &str, version: Version, height: EagerVec>, - source1: &ComputedDateLast, - source2: &ComputedDateLast, + source1: &ComputedFromDateLast, + source2: &ComputedFromDateLast, ) -> Self { let v = version + VERSION; Self { height, - rest: LazyBinaryDateLast::from_computed_both_last::(name, v, source1, source2), + rest: LazyBinaryFromDateLast::from_computed_both_last::(name, v, source1, source2), } } @@ -54,8 +54,8 @@ where name: &str, version: Version, height: EagerVec>, - source1: &ComputedHeightDateLast, - source2: &ComputedHeightDateLast, + source1: &ComputedFromHeightAndDateLast, + source2: &ComputedFromHeightAndDateLast, ) -> Self where S1T: JsonSchema + 'static, @@ -65,7 +65,7 @@ where Self { height, - rest: LazyBinaryDateLast::from_computed_both_last::( + rest: LazyBinaryFromDateLast::from_computed_both_last::( name, v, &source1.rest, diff --git a/crates/brk_computer/src/internal/multi/specialized/ohlc/computed.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/computed_ohlc.rs similarity index 68% rename from crates/brk_computer/src/internal/multi/specialized/ohlc/computed.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/computed_ohlc.rs index f27f28b18..0904f0c45 100644 --- a/crates/brk_computer/src/internal/multi/specialized/ohlc/computed.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/computed_ohlc.rs @@ -8,7 +8,7 @@ use vecdb::Database; use crate::indexes; use crate::internal::{ - ComputedHeightDateFirst, ComputedHeightDateLast, ComputedHeightDateMax, ComputedHeightDateMin, + ComputedFromHeightAndDateFirst, ComputedFromHeightAndDateLast, ComputedFromHeightAndDateMax, ComputedFromHeightAndDateMin, ComputedVecValue, }; @@ -16,18 +16,18 @@ use crate::internal::{ /// /// Access pattern: `ohlc.{open,high,low,close}.{height,dateindex,weekindex,...,difficultyepoch}` #[derive(Clone, Traversable)] -pub struct OHLCComputedVecs +pub struct ComputedOHLC where T: ComputedVecValue + PartialOrd + JsonSchema + From, f64: From, { - pub open: ComputedHeightDateFirst>, - pub high: ComputedHeightDateMax>, - pub low: ComputedHeightDateMin>, - pub close: ComputedHeightDateLast>, + pub open: ComputedFromHeightAndDateFirst>, + pub high: ComputedFromHeightAndDateMax>, + pub low: ComputedFromHeightAndDateMin>, + pub close: ComputedFromHeightAndDateLast>, } -impl OHLCComputedVecs +impl ComputedOHLC where T: ComputedVecValue + PartialOrd + JsonSchema + From + 'static, f64: From, @@ -39,25 +39,25 @@ where indexes: &indexes::Vecs, ) -> Result { Ok(Self { - open: ComputedHeightDateFirst::forced_import( + open: ComputedFromHeightAndDateFirst::forced_import( db, &format!("{name}_open"), version, indexes, )?, - high: ComputedHeightDateMax::forced_import( + high: ComputedFromHeightAndDateMax::forced_import_raw( db, &format!("{name}_high"), version, indexes, )?, - low: ComputedHeightDateMin::forced_import( + low: ComputedFromHeightAndDateMin::forced_import_raw( db, &format!("{name}_low"), version, indexes, )?, - close: ComputedHeightDateLast::forced_import( + close: ComputedFromHeightAndDateLast::forced_import( db, &format!("{name}_close"), version, diff --git a/crates/brk_computer/src/internal/multi/specialized/constant.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/constant.rs similarity index 87% rename from crates/brk_computer/src/internal/multi/specialized/constant.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/constant.rs index 7e9938020..326863b18 100644 --- a/crates/brk_computer/src/internal/multi/specialized/constant.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/constant.rs @@ -1,7 +1,7 @@ use brk_traversable::Traversable; use brk_types::{ - DateIndex, DecadeIndex, Height, MonthIndex, QuarterIndex, SemesterIndex, Version, WeekIndex, - YearIndex, + DateIndex, DecadeIndex, DifficultyEpoch, Height, MonthIndex, QuarterIndex, SemesterIndex, + Version, WeekIndex, YearIndex, }; use schemars::JsonSchema; use serde::Serialize; @@ -18,6 +18,7 @@ where T: VecValue + Formattable + Serialize + JsonSchema, { pub height: LazyVecFrom1, + pub difficultyepoch: LazyVecFrom1, pub dateindex: LazyVecFrom1, pub weekindex: LazyVecFrom1, pub monthindex: LazyVecFrom1, @@ -32,6 +33,7 @@ impl ConstantVecs { pub fn new(name: &str, version: Version, indexes: &indexes::Vecs) -> Self where F: UnaryTransform + + UnaryTransform + UnaryTransform + UnaryTransform + UnaryTransform @@ -46,6 +48,11 @@ impl ConstantVecs { version, indexes.height.identity.boxed_clone(), ), + difficultyepoch: LazyVecFrom1::transformed::( + name, + version, + indexes.difficultyepoch.identity.boxed_clone(), + ), dateindex: LazyVecFrom1::transformed::( name, version, diff --git a/crates/brk_computer/src/internal/multi/height/height_date_first.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/first.rs similarity index 82% rename from crates/brk_computer/src/internal/multi/height/height_date_first.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/first.rs index c871c460e..d1c59b5bd 100644 --- a/crates/brk_computer/src/internal/multi/height/height_date_first.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/first.rs @@ -1,4 +1,4 @@ -//! ComputedHeightDateFirst - height storage + dateindex storage + lazy periods. +//! ComputedFromHeightAndDateFirst - height storage + dateindex storage + lazy periods. //! //! Use this when both height and dateindex are stored EagerVecs with first-value aggregation. @@ -11,11 +11,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedDateFirst, ComputedVecValue, LazyFirst}; +use crate::internal::{ComputedFromDateFirst, ComputedVecValue, LazyFirst}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedHeightDateFirst +pub struct ComputedFromHeightAndDateFirst where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -23,13 +23,13 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: ComputedDateFirst, + pub rest: ComputedFromDateFirst, pub difficultyepoch: LazyFirst, } const VERSION: Version = Version::ZERO; -impl ComputedHeightDateFirst +impl ComputedFromHeightAndDateFirst where T: ComputedVecValue + JsonSchema + 'static, { @@ -42,7 +42,7 @@ where let v = version + VERSION; let height: EagerVec> = EagerVec::forced_import(db, name, v)?; - let rest = ComputedDateFirst::forced_import(db, name, v, indexes)?; + let rest = ComputedFromDateFirst::forced_import(db, name, v, indexes)?; let difficultyepoch = LazyFirst::from_source( name, v, diff --git a/crates/brk_computer/src/internal/multi/height/height_date_last.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/last.rs similarity index 83% rename from crates/brk_computer/src/internal/multi/height/height_date_last.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/last.rs index d14af0b00..744f34c32 100644 --- a/crates/brk_computer/src/internal/multi/height/height_date_last.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/last.rs @@ -1,4 +1,4 @@ -//! ComputedHeightDateLast - height storage + dateindex storage + lazy periods. +//! ComputedFromHeightAndDateLast - height storage + dateindex storage + lazy periods. //! //! Use this when both height and dateindex are stored EagerVecs with last-value aggregation. @@ -9,13 +9,13 @@ use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVec}; -use crate::{indexes, internal::ComputedDateLast, ComputeIndexes}; +use crate::{indexes, internal::ComputedFromDateLast, ComputeIndexes}; use crate::internal::{ComputedVecValue, LazyLast}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedHeightDateLast +pub struct ComputedFromHeightAndDateLast where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -23,13 +23,13 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: ComputedDateLast, + pub rest: ComputedFromDateLast, pub difficultyepoch: LazyLast, } const VERSION: Version = Version::ZERO; -impl ComputedHeightDateLast +impl ComputedFromHeightAndDateLast where T: ComputedVecValue + JsonSchema + 'static, { @@ -42,7 +42,7 @@ where let v = version + VERSION; let height: EagerVec> = EagerVec::forced_import(db, name, v)?; - let rest = ComputedDateLast::forced_import(db, name, v, indexes)?; + let rest = ComputedFromDateLast::forced_import(db, name, v, indexes)?; let difficultyepoch = LazyLast::from_source( name, v, diff --git a/crates/brk_computer/src/internal/multi/specialized/ohlc/period.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/lazy_ohlc.rs similarity index 94% rename from crates/brk_computer/src/internal/multi/specialized/ohlc/period.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/lazy_ohlc.rs index 74537b66a..d2a0c0496 100644 --- a/crates/brk_computer/src/internal/multi/specialized/ohlc/period.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/lazy_ohlc.rs @@ -11,7 +11,8 @@ use vecdb::{BytesVec, BytesVecValue, EagerVec, Formattable}; /// Bundled OHLC vecs for all periods (time + chain based). #[derive(Clone, Traversable)] -pub struct OHLCPeriodVecs +#[traversable(merge)] +pub struct LazyFromHeightAndDateOHLC where T: BytesVecValue + Formattable + Serialize + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/height/height_date_max.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/max.rs similarity index 51% rename from crates/brk_computer/src/internal/multi/height/height_date_max.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/max.rs index fb97dc352..1e9039f03 100644 --- a/crates/brk_computer/src/internal/multi/height/height_date_max.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/max.rs @@ -1,4 +1,4 @@ -//! ComputedHeightDateMax - height storage + dateindex storage + lazy periods. +//! ComputedFromHeightAndDateMax - height storage + dateindex storage + lazy periods. //! //! Use this when both height and dateindex are stored EagerVecs with max-value aggregation. @@ -11,11 +11,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedDateMax, ComputedVecValue, LazyMax}; +use crate::internal::{ComputedFromDateMax, ComputedVecValue, LazyMax}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedHeightDateMax +pub struct ComputedFromHeightAndDateMax where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -23,13 +23,13 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: ComputedDateMax, + pub rest: ComputedFromDateMax, pub difficultyepoch: LazyMax, } const VERSION: Version = Version::ZERO; -impl ComputedHeightDateMax +impl ComputedFromHeightAndDateMax where T: ComputedVecValue + JsonSchema + 'static, { @@ -38,17 +38,50 @@ where name: &str, version: Version, indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, false) + } + + /// Import without adding _max suffix to lazy vecs. + pub fn forced_import_raw( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, true) + } + + fn forced_import_inner( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + raw: bool, ) -> Result { let v = version + VERSION; let height: EagerVec> = EagerVec::forced_import(db, name, v)?; - let rest = ComputedDateMax::forced_import(db, name, v, indexes)?; - let difficultyepoch = LazyMax::from_source( - name, - v, - height.boxed_clone(), - indexes.difficultyepoch.identity.boxed_clone(), - ); + let rest = if raw { + ComputedFromDateMax::forced_import_raw(db, name, v, indexes)? + } else { + ComputedFromDateMax::forced_import(db, name, v, indexes)? + }; + let difficultyepoch = if raw { + LazyMax::from_source_raw( + name, + v, + height.boxed_clone(), + indexes.difficultyepoch.identity.boxed_clone(), + ) + } else { + LazyMax::from_source( + name, + v, + height.boxed_clone(), + indexes.difficultyepoch.identity.boxed_clone(), + ) + }; Ok(Self { height, diff --git a/crates/brk_computer/src/internal/multi/height/height_date_min.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/min.rs similarity index 51% rename from crates/brk_computer/src/internal/multi/height/height_date_min.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/min.rs index bc3e4b7d9..196de7fc0 100644 --- a/crates/brk_computer/src/internal/multi/height/height_date_min.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/min.rs @@ -1,4 +1,4 @@ -//! ComputedHeightDateMin - height storage + dateindex storage + lazy periods. +//! ComputedFromHeightAndDateMin - height storage + dateindex storage + lazy periods. //! //! Use this when both height and dateindex are stored EagerVecs with min-value aggregation. @@ -11,11 +11,11 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes}; -use crate::internal::{ComputedDateMin, ComputedVecValue, LazyMin}; +use crate::internal::{ComputedFromDateMin, ComputedVecValue, LazyMin}; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedHeightDateMin +pub struct ComputedFromHeightAndDateMin where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -23,13 +23,13 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub rest: ComputedDateMin, + pub rest: ComputedFromDateMin, pub difficultyepoch: LazyMin, } const VERSION: Version = Version::ZERO; -impl ComputedHeightDateMin +impl ComputedFromHeightAndDateMin where T: ComputedVecValue + JsonSchema + 'static, { @@ -38,17 +38,50 @@ where name: &str, version: Version, indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, false) + } + + /// Import without adding _min suffix to lazy vecs. + pub fn forced_import_raw( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + ) -> Result { + Self::forced_import_inner(db, name, version, indexes, true) + } + + fn forced_import_inner( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + raw: bool, ) -> Result { let v = version + VERSION; let height: EagerVec> = EagerVec::forced_import(db, name, v)?; - let rest = ComputedDateMin::forced_import(db, name, v, indexes)?; - let difficultyepoch = LazyMin::from_source( - name, - v, - height.boxed_clone(), - indexes.difficultyepoch.identity.boxed_clone(), - ); + let rest = if raw { + ComputedFromDateMin::forced_import_raw(db, name, v, indexes)? + } else { + ComputedFromDateMin::forced_import(db, name, v, indexes)? + }; + let difficultyepoch = if raw { + LazyMin::from_source_raw( + name, + v, + height.boxed_clone(), + indexes.difficultyepoch.identity.boxed_clone(), + ) + } else { + LazyMin::from_source( + name, + v, + height.boxed_clone(), + indexes.difficultyepoch.identity.boxed_clone(), + ) + }; Ok(Self { height, diff --git a/crates/brk_computer/src/internal/multi/from_height_and_date/mod.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/mod.rs new file mode 100644 index 000000000..4ac3aafd2 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/mod.rs @@ -0,0 +1,19 @@ +mod binary_last; +mod computed_ohlc; +mod constant; +mod first; +mod last; +mod lazy_ohlc; +mod max; +mod min; +mod value_last; + +pub use binary_last::*; +pub use computed_ohlc::*; +pub use constant::*; +pub use first::*; +pub use last::*; +pub use lazy_ohlc::*; +pub use max::*; +pub use min::*; +pub use value_last::*; diff --git a/crates/brk_computer/src/internal/multi/value/date/height_date_last.rs b/crates/brk_computer/src/internal/multi/from_height_and_date/value_last.rs similarity index 78% rename from crates/brk_computer/src/internal/multi/value/date/height_date_last.rs rename to crates/brk_computer/src/internal/multi/from_height_and_date/value_last.rs index 43e7bc70a..91327951b 100644 --- a/crates/brk_computer/src/internal/multi/value/date/height_date_last.rs +++ b/crates/brk_computer/src/internal/multi/from_height_and_date/value_last.rs @@ -11,29 +11,28 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, IterableCloneableVec, PcoVe use crate::{ComputeIndexes, indexes, price}; -use crate::internal::{LazyDerivedBlockValue, LazyValueDifficultyEpochFromHeight}; -use super::ValueDateLast; +use crate::internal::{LazyDerivedValuesHeight, LazyValueDifficultyEpoch, ValueFromDateLast}; /// Value type where both height and dateindex are stored independently. /// Dateindex values cannot be derived from height (e.g., unrealized P&L). #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ValueHeightDateLast { +pub struct ValueFromHeightAndDateLast { #[traversable(rename = "sats")] pub height: EagerVec>, #[traversable(flatten)] - pub height_value: LazyDerivedBlockValue, + pub height_value: LazyDerivedValuesHeight, #[traversable(flatten)] - pub difficultyepoch: LazyValueDifficultyEpochFromHeight, + pub difficultyepoch: LazyValueDifficultyEpoch, #[deref] #[deref_mut] #[traversable(flatten)] - pub indexes: ValueDateLast, + pub indexes: ValueFromDateLast, } const VERSION: Version = Version::ZERO; -impl ValueHeightDateLast { +impl ValueFromHeightAndDateLast { pub fn forced_import( db: &Database, name: &str, @@ -49,9 +48,9 @@ impl ValueHeightDateLast { let price_source = price.map(|p| p.usd.split.close.height.boxed_clone()); let height_value = - LazyDerivedBlockValue::from_source(name, height.boxed_clone(), v, price_source); + LazyDerivedValuesHeight::from_source(name, height.boxed_clone(), v, price_source); - let difficultyepoch = LazyValueDifficultyEpochFromHeight::from_height_source( + let difficultyepoch = LazyValueDifficultyEpoch::from_height_source( name, height.boxed_clone(), indexes.difficultyepoch.identity.boxed_clone(), @@ -59,7 +58,7 @@ impl ValueHeightDateLast { v, ); - let indexes = ValueDateLast::forced_import(db, name, v, compute_dollars, indexes)?; + let indexes = ValueFromDateLast::forced_import(db, name, v, compute_dollars, indexes)?; Ok(Self { height, diff --git a/crates/brk_computer/src/internal/multi/derived_tx/lazy_distribution.rs b/crates/brk_computer/src/internal/multi/from_tx/lazy_distribution.rs similarity index 81% rename from crates/brk_computer/src/internal/multi/derived_tx/lazy_distribution.rs rename to crates/brk_computer/src/internal/multi/from_tx/lazy_distribution.rs index 3fcc7b2c3..5c6f7e785 100644 --- a/crates/brk_computer/src/internal/multi/derived_tx/lazy_distribution.rs +++ b/crates/brk_computer/src/internal/multi/from_tx/lazy_distribution.rs @@ -1,4 +1,4 @@ -//! LazyTxDistribution - lazy txindex source + computed distribution. +//! LazyFromTxDistribution - lazy txindex source + computed distribution. use brk_error::Result; use brk_indexer::Indexer; @@ -10,14 +10,14 @@ use vecdb::{CollectableVec, Database, Exit, LazyVecFrom2}; use crate::{ ComputeIndexes, indexes, - internal::{ComputedVecValue, DerivedTxDistribution, NumericValue}, + internal::{ComputedVecValue, TxDerivedDistribution, NumericValue}, }; const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyTxDistribution +pub struct LazyFromTxDistribution where T: ComputedVecValue + PartialOrd + JsonSchema, S1: ComputedVecValue, @@ -27,10 +27,10 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub distribution: DerivedTxDistribution, + pub distribution: TxDerivedDistribution, } -impl LazyTxDistribution +impl LazyFromTxDistribution where T: NumericValue + JsonSchema, S1: ComputedVecValue + JsonSchema, @@ -44,7 +44,7 @@ where indexes: &indexes::Vecs, ) -> Result { let v = version + VERSION; - let distribution = DerivedTxDistribution::forced_import(db, name, v, indexes)?; + let distribution = TxDerivedDistribution::forced_import(db, name, v, indexes)?; Ok(Self { txindex, distribution, diff --git a/crates/brk_computer/src/internal/multi/from_tx/mod.rs b/crates/brk_computer/src/internal/multi/from_tx/mod.rs new file mode 100644 index 000000000..c8faef681 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_tx/mod.rs @@ -0,0 +1,7 @@ +mod lazy_distribution; +mod value_dollars; +mod value_full; + +pub use lazy_distribution::*; +pub use value_dollars::*; +pub use value_full::*; diff --git a/crates/brk_computer/src/internal/multi/from_tx/value_dollars.rs b/crates/brk_computer/src/internal/multi/from_tx/value_dollars.rs new file mode 100644 index 000000000..7a057d89f --- /dev/null +++ b/crates/brk_computer/src/internal/multi/from_tx/value_dollars.rs @@ -0,0 +1,202 @@ +//! Dollars from TxIndex with lazy height stats and stored dateindex. +//! +//! Height-level USD stats (min/max/avg/sum/percentiles) are lazy: `sats_stat * price`. +//! Height cumulative and dateindex stats are stored since they require aggregation +//! across heights with varying prices. + +use brk_error::Result; +use brk_indexer::Indexer; +use brk_traversable::Traversable; +use brk_types::{ + Bitcoin, Close, DateIndex, DifficultyEpoch, Dollars, Height, Sats, TxIndex, Version, +}; +use derive_more::{Deref, DerefMut}; +use vecdb::{ + AnyStoredVec, AnyVec, Database, EagerVec, Exit, GenericStoredVec, ImportableVec, + IterableBoxedVec, IterableCloneableVec, IterableVec, LazyVecFrom3, +}; + +use crate::{ + ComputeIndexes, indexes, + internal::{ + CumulativeVec, Full, LazyBinaryTransformFull, LazyDateDerivedFull, LazyFull, + SatsTimesClosePrice, Stats, + }, +}; + +/// Lazy dollars at TxIndex: `sats * price[height]` +pub type LazyDollarsTxIndex = + LazyVecFrom3>; + +/// Lazy dollars height stats: `sats_height_stat * price` +pub type LazyDollarsHeightFull = LazyBinaryTransformFull>; + +/// Dollars with lazy txindex and height fields, stored dateindex. +/// +/// Height-level stats (except cumulative) are lazy: `sats * price[height]`. +/// Cumulative at height level is stored since it requires summing historical values. +/// DateIndex stats are stored since they aggregate across heights with varying prices. +#[derive(Clone, Deref, DerefMut, Traversable)] +#[traversable(merge)] +pub struct ValueDollarsFromTxFull { + #[traversable(skip)] + pub txindex: LazyDollarsTxIndex, + #[traversable(flatten)] + pub height: LazyDollarsHeightFull, + pub height_cumulative: CumulativeVec, + pub difficultyepoch: LazyFull, + pub dateindex: Stats, + #[deref] + #[deref_mut] + pub dates: LazyDateDerivedFull, +} + +const VERSION: Version = Version::ONE; // Bumped for lazy height change + +impl ValueDollarsFromTxFull { + #[allow(clippy::too_many_arguments)] + pub fn forced_import( + db: &Database, + name: &str, + version: Version, + indexes: &indexes::Vecs, + sats_height: &Full, + height_to_price: IterableBoxedVec>, + sats_txindex: IterableBoxedVec, + txindex_to_height: IterableBoxedVec, + ) -> Result { + let v = version + VERSION; + + let txindex = create_lazy_txindex( + name, + v, + sats_txindex, + txindex_to_height, + height_to_price.clone(), + ); + + // Lazy height stats: sats_stat * price + let height = LazyBinaryTransformFull::from_full_and_source::( + name, + v, + sats_height, + height_to_price.clone(), + ); + + // Stored cumulative - must be computed by summing historical sum*price + let height_cumulative = CumulativeVec(EagerVec::forced_import( + db, + &format!("{name}_cumulative"), + v, + )?); + + let dateindex = Stats::forced_import(db, name, v)?; + + let difficultyepoch = + LazyFull::::from_stats_aggregate( + name, + v, + height.boxed_average(), + height.boxed_min(), + height.boxed_max(), + height.boxed_sum(), + height_cumulative.0.boxed_clone(), + indexes.difficultyepoch.identity.boxed_clone(), + ); + + let dates = LazyDateDerivedFull::from_sources( + name, + v, + dateindex.boxed_average(), + dateindex.boxed_min(), + dateindex.boxed_max(), + dateindex.boxed_sum(), + dateindex.boxed_cumulative(), + indexes, + ); + + Ok(Self { + txindex, + height, + height_cumulative, + difficultyepoch, + dateindex, + dates, + }) + } + + /// Compute stored fields (cumulative and dateindex) from lazy height stats. + /// + /// This is MUCH faster than the old approach since it only iterates heights, + /// not all transactions per block. + pub fn derive_from( + &mut self, + _indexer: &Indexer, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + ) -> Result<()> { + // Compute height cumulative by summing lazy height.sum values + self.compute_height_cumulative(starting_indexes.height, exit)?; + + // Compute dateindex stats by aggregating lazy height stats + self.dateindex.compute( + starting_indexes.dateindex, + &self.height.average, + &indexes.dateindex.first_height, + &indexes.dateindex.height_count, + exit, + )?; + + Ok(()) + } + + /// Compute cumulative USD by summing `sum_sats[h] * price[h]` for all heights. + fn compute_height_cumulative(&mut self, max_from: Height, exit: &Exit) -> Result<()> { + let starting_height = max_from.min(Height::from(self.height_cumulative.0.len())); + + let mut cumulative = starting_height.decremented().map_or(Dollars::ZERO, |h| { + self.height_cumulative.0.iter().get_unwrap(h) + }); + + let mut sum_iter = self.height.sum.iter(); + let start_idx = *starting_height as usize; + let end_idx = sum_iter.len(); + + for h in start_idx..end_idx { + let sum_usd = sum_iter.get_unwrap(Height::from(h)); + cumulative += sum_usd; + self.height_cumulative.0.truncate_push_at(h, cumulative)?; + } + + let _lock = exit.lock(); + self.height_cumulative.0.write()?; + + Ok(()) + } +} + +fn create_lazy_txindex( + name: &str, + version: Version, + sats_txindex: IterableBoxedVec, + txindex_to_height: IterableBoxedVec, + height_to_price: IterableBoxedVec>, +) -> LazyDollarsTxIndex { + LazyVecFrom3::init( + &format!("{name}_txindex"), + version, + sats_txindex, + txindex_to_height, + height_to_price, + |txindex, sats_iter, height_iter, price_iter| { + sats_iter.get(txindex).and_then(|sats| { + height_iter.get(txindex).and_then(|height| { + price_iter + .get(height) + .map(|close| *close * Bitcoin::from(sats)) + }) + }) + }, + ) +} diff --git a/crates/brk_computer/src/internal/multi/value/tx/full.rs b/crates/brk_computer/src/internal/multi/from_tx/value_full.rs similarity index 52% rename from crates/brk_computer/src/internal/multi/value/tx/full.rs rename to crates/brk_computer/src/internal/multi/from_tx/value_full.rs index bfc6e25b2..20a310b4a 100644 --- a/crates/brk_computer/src/internal/multi/value/tx/full.rs +++ b/crates/brk_computer/src/internal/multi/from_tx/value_full.rs @@ -1,4 +1,4 @@ -//! ValueTxFull - eager txindex Sats source + ValueDerivedTxFull (sats/bitcoin/dollars). +//! ValueFromTxFull - eager txindex Sats source + ValueTxDerivedFull (sats/bitcoin/dollars). use brk_error::Result; use brk_indexer::Indexer; @@ -7,23 +7,21 @@ use brk_types::{Sats, TxIndex, Version}; use derive_more::{Deref, DerefMut}; use vecdb::{Database, EagerVec, Exit, ImportableVec, PcoVec}; -use crate::{ComputeIndexes, indexes, price}; - -use super::ValueDerivedTxFull; +use crate::{ComputeIndexes, indexes, internal::ValueTxDerivedFull, price}; const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] -pub struct ValueTxFull { +pub struct ValueFromTxFull { #[traversable(rename = "txindex")] pub base: EagerVec>, #[deref] #[deref_mut] #[traversable(flatten)] - pub indexes: ValueDerivedTxFull, + pub indexes: ValueTxDerivedFull, } -impl ValueTxFull { +impl ValueFromTxFull { pub fn forced_import( db: &Database, name: &str, @@ -35,7 +33,7 @@ impl ValueTxFull { let v = version + VERSION; let txindex = EagerVec::forced_import(db, name, v)?; let derived = - ValueDerivedTxFull::forced_import(db, name, v, indexes, indexer, price, &txindex)?; + ValueTxDerivedFull::forced_import(db, name, v, indexes, indexer, price, &txindex)?; Ok(Self { base: txindex, indexes: derived, @@ -49,7 +47,27 @@ impl ValueTxFull { starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { - self.indexes - .derive_from(indexer, indexes, starting_indexes, &self.base, exit) + self.derive_from_with_skip(indexer, indexes, starting_indexes, exit, 0) + } + + /// Derive from source, skipping first N transactions per block from all calculations. + /// + /// Use `skip_count: 1` to exclude coinbase transactions from fee/feerate stats. + pub fn derive_from_with_skip( + &mut self, + indexer: &Indexer, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + skip_count: usize, + ) -> Result<()> { + self.indexes.derive_from_with_skip( + indexer, + indexes, + starting_indexes, + &self.base, + exit, + skip_count, + ) } } diff --git a/crates/brk_computer/src/internal/multi/height/mod.rs b/crates/brk_computer/src/internal/multi/height/mod.rs deleted file mode 100644 index 3718c0d37..000000000 --- a/crates/brk_computer/src/internal/multi/height/mod.rs +++ /dev/null @@ -1,43 +0,0 @@ -mod binary_full; -mod binary_height_date_last; -mod binary_last; -mod binary_sum; -mod binary_sum_cum; -mod full; -mod height_date_bytes; -mod height_date_first; -mod height_date_last; -mod height_date_max; -mod height_date_min; -mod last; -mod lazy_distribution; -mod lazy_full; -mod lazy_height_full; -mod lazy_height_sum_cum; -mod lazy_last; -mod lazy_sum; -mod lazy_sum_cum; -mod sum; -mod sum_cum; - -pub use binary_full::*; -pub use binary_height_date_last::*; -pub use binary_last::*; -pub use binary_sum::*; -pub use binary_sum_cum::*; -pub use full::*; -pub use height_date_bytes::*; -pub use height_date_first::*; -pub use height_date_last::*; -pub use height_date_max::*; -pub use height_date_min::*; -pub use last::*; -pub use lazy_distribution::*; -pub use lazy_full::*; -pub use lazy_height_full::*; -pub use lazy_height_sum_cum::*; -pub use lazy_last::*; -pub use lazy_sum::*; -pub use lazy_sum_cum::*; -pub use sum::*; -pub use sum_cum::*; diff --git a/crates/brk_computer/src/internal/multi/height/height_date_bytes.rs b/crates/brk_computer/src/internal/multi/height_and_date/bytes.rs similarity index 86% rename from crates/brk_computer/src/internal/multi/height/height_date_bytes.rs rename to crates/brk_computer/src/internal/multi/height_and_date/bytes.rs index 7caa6929d..e1a8cc986 100644 --- a/crates/brk_computer/src/internal/multi/height/height_date_bytes.rs +++ b/crates/brk_computer/src/internal/multi/height_and_date/bytes.rs @@ -1,4 +1,4 @@ -//! ComputedHeightDateBytes - height + dateindex BytesVec storage. +//! ComputedHeightAndDateBytes - height + dateindex BytesVec storage. //! //! Use this for simple cases where both height and dateindex are stored BytesVecs //! without any lazy derivations. For OHLC-type data. @@ -12,7 +12,7 @@ use vecdb::{BytesVec, BytesVecValue, Database, Formattable, ImportableVec}; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct ComputedHeightDateBytes +pub struct ComputedHeightAndDateBytes where T: BytesVecValue + Formattable + Serialize + JsonSchema, { @@ -22,7 +22,7 @@ where const VERSION: Version = Version::ZERO; -impl ComputedHeightDateBytes +impl ComputedHeightAndDateBytes where T: BytesVecValue + Formattable + Serialize + JsonSchema + 'static, { diff --git a/crates/brk_computer/src/internal/multi/height_and_date/mod.rs b/crates/brk_computer/src/internal/multi/height_and_date/mod.rs new file mode 100644 index 000000000..ed1a31441 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/height_and_date/mod.rs @@ -0,0 +1,5 @@ +mod bytes; +mod ohlc; + +pub use bytes::*; +pub use ohlc::*; diff --git a/crates/brk_computer/src/internal/multi/height_and_date/ohlc.rs b/crates/brk_computer/src/internal/multi/height_and_date/ohlc.rs new file mode 100644 index 000000000..1a69d3013 --- /dev/null +++ b/crates/brk_computer/src/internal/multi/height_and_date/ohlc.rs @@ -0,0 +1,21 @@ +//! Lazy OHLC component extractors for height + dateindex only. + +use brk_traversable::Traversable; +use brk_types::{DateIndex, Height}; +use schemars::JsonSchema; +use serde::Serialize; +use vecdb::{BytesVecValue, Formattable}; + +use crate::internal::LazyOHLC; + +/// Lazy OHLC component extractors for height + dateindex. +#[derive(Clone, Traversable)] +#[traversable(merge)] +pub struct LazyHeightAndDateOHLC +where + T: BytesVecValue + Formattable + Serialize + JsonSchema + 'static, + SourceT: BytesVecValue + Formattable + Serialize + JsonSchema + 'static, +{ + pub height: LazyOHLC, + pub dateindex: LazyOHLC, +} diff --git a/crates/brk_computer/src/internal/multi/derived_height/binary_last.rs b/crates/brk_computer/src/internal/multi/height_derived/binary_last.rs similarity index 71% rename from crates/brk_computer/src/internal/multi/derived_height/binary_last.rs rename to crates/brk_computer/src/internal/multi/height_derived/binary_last.rs index 8ad523175..ce2fa0f17 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/binary_last.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/binary_last.rs @@ -7,13 +7,13 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableCloneableVec}; use crate::internal::{ - ComputedBlockLast, ComputedBlockSumCum, ComputedHeightDateLast, ComputedVecValue, - LazyBinaryDateLast, LazyBinaryTransformLast, NumericValue, + ComputedFromHeightLast, ComputedFromHeightSumCum, ComputedFromHeightAndDateLast, ComputedVecValue, + LazyBinaryFromDateLast, LazyBinaryTransformLast, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryDerivedBlockLast +pub struct LazyBinaryHeightDerivedLast where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -21,13 +21,13 @@ where { #[deref] #[deref_mut] - pub dates: LazyBinaryDateLast, + pub dates: LazyBinaryFromDateLast, pub difficultyepoch: LazyBinaryTransformLast, } const VERSION: Version = Version::ZERO; -impl LazyBinaryDerivedBlockLast +impl LazyBinaryHeightDerivedLast where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -36,8 +36,8 @@ where pub fn from_computed_sum_cum>( name: &str, version: Version, - source1: &ComputedBlockSumCum, - source2: &ComputedBlockSumCum, + source1: &ComputedFromHeightSumCum, + source2: &ComputedFromHeightSumCum, ) -> Self where S1T: PartialOrd, @@ -46,7 +46,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateLast::from_both_sum_cum_cumulatives::( + dates: LazyBinaryFromDateLast::from_both_sum_cum_cumulatives::( name, v, source1.dateindex.cumulative.boxed_clone(), @@ -66,8 +66,8 @@ where pub fn from_computed_last>( name: &str, version: Version, - source1: &ComputedBlockLast, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightLast, + source2: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -76,7 +76,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateLast::from_both_block_last::(name, v, source1, source2), + dates: LazyBinaryFromDateLast::from_both_block_last::(name, v, source1, source2), difficultyepoch: LazyBinaryTransformLast::from_vecs::( name, v, @@ -89,8 +89,8 @@ where pub fn from_computed_height_date_last>( name: &str, version: Version, - source1: &ComputedHeightDateLast, - source2: &ComputedHeightDateLast, + source1: &ComputedFromHeightAndDateLast, + source2: &ComputedFromHeightAndDateLast, ) -> Self where S1T: PartialOrd, @@ -99,7 +99,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateLast::from_computed_both_last::( + dates: LazyBinaryFromDateLast::from_computed_both_last::( name, v, &source1.rest, @@ -108,8 +108,8 @@ where difficultyepoch: LazyBinaryTransformLast::from_vecs::( name, v, - source1.difficultyepoch.0.boxed_clone(), - source2.difficultyepoch.0.boxed_clone(), + source1.difficultyepoch.boxed_clone(), + source2.difficultyepoch.boxed_clone(), ), } } @@ -117,8 +117,8 @@ where pub fn from_computed_height_date_and_block_last>( name: &str, version: Version, - source1: &ComputedHeightDateLast, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightAndDateLast, + source2: &ComputedFromHeightLast, ) -> Self where S1T: PartialOrd, @@ -127,7 +127,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateLast::from_dateindex_and_height_last::( + dates: LazyBinaryFromDateLast::from_dateindex_and_height_last::( name, v, &source1.rest, @@ -136,7 +136,7 @@ where difficultyepoch: LazyBinaryTransformLast::from_vecs::( name, v, - source1.difficultyepoch.0.boxed_clone(), + source1.difficultyepoch.boxed_clone(), source2.difficultyepoch.boxed_clone(), ), } diff --git a/crates/brk_computer/src/internal/multi/derived_height/binary_sum.rs b/crates/brk_computer/src/internal/multi/height_derived/binary_sum.rs similarity index 71% rename from crates/brk_computer/src/internal/multi/derived_height/binary_sum.rs rename to crates/brk_computer/src/internal/multi/height_derived/binary_sum.rs index 3374c1e48..fe12500a5 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/binary_sum.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/binary_sum.rs @@ -6,13 +6,13 @@ use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableCloneableVec}; -use crate::internal::{ComputedVecValue, ComputedDerivedBlockSum, LazyBinaryDateSum, LazyBinaryTransformSum, NumericValue}; +use crate::internal::{ComputedVecValue, ComputedHeightDerivedSum, LazyBinaryFromDateSum, LazyBinaryTransformSum, NumericValue}; const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryDerivedBlockSum +pub struct LazyBinaryHeightDerivedSum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -20,11 +20,11 @@ where { #[deref] #[deref_mut] - pub dates: LazyBinaryDateSum, + pub dates: LazyBinaryFromDateSum, pub difficultyepoch: LazyBinaryTransformSum, } -impl LazyBinaryDerivedBlockSum +impl LazyBinaryHeightDerivedSum where T: ComputedVecValue + JsonSchema + 'static, S1T: NumericValue + JsonSchema, @@ -33,13 +33,13 @@ where pub fn from_derived>( name: &str, version: Version, - source1: &ComputedDerivedBlockSum, - source2: &ComputedDerivedBlockSum, + source1: &ComputedHeightDerivedSum, + source2: &ComputedHeightDerivedSum, ) -> Self { let v = version + VERSION; Self { - dates: LazyBinaryDateSum::from_derived::(name, v, source1, source2), + dates: LazyBinaryFromDateSum::from_derived::(name, v, source1, source2), difficultyepoch: LazyBinaryTransformSum::from_boxed::( name, v, diff --git a/crates/brk_computer/src/internal/multi/derived_height/binary_sum_cum.rs b/crates/brk_computer/src/internal/multi/height_derived/binary_sum_cum.rs similarity index 77% rename from crates/brk_computer/src/internal/multi/derived_height/binary_sum_cum.rs rename to crates/brk_computer/src/internal/multi/height_derived/binary_sum_cum.rs index ae009ffa0..6a690274e 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/binary_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/binary_sum_cum.rs @@ -7,16 +7,16 @@ use schemars::JsonSchema; use vecdb::{BinaryTransform, IterableCloneableVec}; use crate::internal::{ - ComputedBlockLast, ComputedBlockSumCum, ComputedDerivedBlockLast, ComputedDerivedBlockSumCum, - ComputedVecValue, LazyBinaryDateSumCum, LazyBinaryTransformSumCum, LazyFull, LazyPeriodsFull, - LazyPeriodsSumCum, LazySumCum, NumericValue, SumCum, + ComputedFromHeightLast, ComputedFromHeightSumCum, ComputedHeightDerivedLast, ComputedHeightDerivedSumCum, + ComputedVecValue, LazyBinaryFromDateSumCum, LazyBinaryTransformSumCum, LazyFull, LazyDateDerivedFull, + LazyDateDerivedSumCum, LazySumCum, NumericValue, SumCum, }; const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyBinaryDerivedBlockSumCum +pub struct LazyBinaryHeightDerivedSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -24,11 +24,11 @@ where { #[deref] #[deref_mut] - pub dates: LazyBinaryDateSumCum, + pub dates: LazyBinaryFromDateSumCum, pub difficultyepoch: LazyBinaryTransformSumCum, } -impl LazyBinaryDerivedBlockSumCum +impl LazyBinaryHeightDerivedSumCum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -39,16 +39,16 @@ where name: &str, version: Version, dateindex1: &SumCum, - periods1: &LazyPeriodsSumCum, + periods1: &LazyDateDerivedSumCum, difficultyepoch1: &LazySumCum, dateindex2: &SumCum, - periods2: &LazyPeriodsSumCum, + periods2: &LazyDateDerivedSumCum, difficultyepoch2: &LazySumCum, ) -> Self { let v = version + VERSION; Self { - dates: LazyBinaryDateSumCum::from_computed::( + dates: LazyBinaryFromDateSumCum::from_computed::( name, v, dateindex1, periods1, dateindex2, periods2, ), difficultyepoch: LazyBinaryTransformSumCum::from_sources::( @@ -67,10 +67,10 @@ where name: &str, version: Version, dateindex1: &SumCum, - dates1: &LazyPeriodsFull, + dates1: &LazyDateDerivedFull, difficultyepoch1: &LazyFull, dateindex2: &SumCum, - dates2: &LazyPeriodsFull, + dates2: &LazyDateDerivedFull, difficultyepoch2: &LazyFull, ) -> Self where @@ -83,7 +83,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateSumCum::from_derived_full::( + dates: LazyBinaryFromDateSumCum::from_derived_full::( name, v, dateindex1, dates1, dateindex2, dates2, ), difficultyepoch: LazyBinaryTransformSumCum::from_lazy_stats_aggregate::( @@ -101,16 +101,16 @@ where name: &str, version: Version, dateindex1: &SumCum, - periods1: &LazyPeriodsSumCum, + periods1: &LazyDateDerivedSumCum, difficultyepoch1: &LazySumCum, dateindex2: &SumCum, - periods2: &LazyPeriodsSumCum, + periods2: &LazyDateDerivedSumCum, difficultyepoch2: &LazySumCum, ) -> Self { let v = version + VERSION; Self { - dates: LazyBinaryDateSumCum::from_computed_sum_raw::( + dates: LazyBinaryFromDateSumCum::from_computed_sum_raw::( name, v, dateindex1, periods1, dateindex2, periods2, ), difficultyepoch: LazyBinaryTransformSumCum::from_sources_sum_raw::( @@ -129,8 +129,8 @@ where pub fn from_computed_last>( name: &str, version: Version, - source1: &ComputedBlockSumCum, - source2: &ComputedBlockLast, + source1: &ComputedFromHeightSumCum, + source2: &ComputedFromHeightLast, ) -> Self where S1T: PartialOrd, @@ -139,7 +139,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateSumCum::from_computed_last::(name, v, source1, source2), + dates: LazyBinaryFromDateSumCum::from_computed_last::(name, v, source1, source2), difficultyepoch: LazyBinaryTransformSumCum::from_sources_last_sum_raw::( name, v, @@ -153,8 +153,8 @@ where pub fn from_derived_computed_last>( name: &str, version: Version, - source1: &ComputedDerivedBlockSumCum, - source2: &ComputedBlockLast, + source1: &ComputedHeightDerivedSumCum, + source2: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -163,7 +163,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateSumCum::from_derived_computed_last::(name, v, source1, source2), + dates: LazyBinaryFromDateSumCum::from_derived_computed_last::(name, v, source1, source2), difficultyepoch: LazyBinaryTransformSumCum::from_sources_last_sum_raw::( name, v, @@ -177,8 +177,8 @@ where pub fn from_computed_derived_last>( name: &str, version: Version, - source1: &ComputedBlockSumCum, - source2: &ComputedDerivedBlockLast, + source1: &ComputedFromHeightSumCum, + source2: &ComputedHeightDerivedLast, ) -> Self where S1T: PartialOrd, @@ -187,7 +187,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateSumCum::from_computed_derived_last::(name, v, source1, source2), + dates: LazyBinaryFromDateSumCum::from_computed_derived_last::(name, v, source1, source2), difficultyepoch: LazyBinaryTransformSumCum::from_sources_last_sum_raw::( name, v, @@ -201,8 +201,8 @@ where pub fn from_derived_last>( name: &str, version: Version, - source1: &ComputedDerivedBlockSumCum, - source2: &ComputedDerivedBlockLast, + source1: &ComputedHeightDerivedSumCum, + source2: &ComputedHeightDerivedLast, ) -> Self where S1T: NumericValue, @@ -211,7 +211,7 @@ where let v = version + VERSION; Self { - dates: LazyBinaryDateSumCum::from_derived_last::(name, v, source1, source2), + dates: LazyBinaryFromDateSumCum::from_derived_last::(name, v, source1, source2), difficultyepoch: LazyBinaryTransformSumCum::from_sources_last_sum_raw::( name, v, diff --git a/crates/brk_computer/src/internal/multi/derived_height/distribution.rs b/crates/brk_computer/src/internal/multi/height_derived/distribution.rs similarity index 78% rename from crates/brk_computer/src/internal/multi/derived_height/distribution.rs rename to crates/brk_computer/src/internal/multi/height_derived/distribution.rs index 61adc1f4c..554d21021 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/distribution.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/distribution.rs @@ -1,4 +1,4 @@ -//! ComputedDerivedBlockDistribution - dateindex storage + lazy time periods + difficultyepoch. +//! ComputedHeightDerivedDistribution - dateindex storage + lazy time periods + difficultyepoch. use brk_error::Result; @@ -11,26 +11,26 @@ use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec} use crate::{ ComputeIndexes, indexes, internal::{ - ComputedVecValue, LazyPeriodsDistribution, Distribution, LazyDistribution, NumericValue, + ComputedVecValue, LazyDateDerivedDistribution, Distribution, LazyDistribution, NumericValue, }, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDerivedBlockDistribution +pub struct ComputedHeightDerivedDistribution where T: ComputedVecValue + PartialOrd + JsonSchema, { pub dateindex: Distribution, #[deref] #[deref_mut] - pub dates: LazyPeriodsDistribution, + pub dates: LazyDateDerivedDistribution, pub difficultyepoch: LazyDistribution, } const VERSION: Version = Version::ZERO; -impl ComputedDerivedBlockDistribution +impl ComputedHeightDerivedDistribution where T: NumericValue + JsonSchema, { @@ -44,12 +44,12 @@ where let dateindex = Distribution::forced_import(db, name, version + VERSION)?; let v = version + VERSION; - let dates = LazyPeriodsDistribution::from_sources( + let dates = LazyDateDerivedDistribution::from_sources( name, v, - dateindex.average.0.boxed_clone(), - dateindex.minmax.min.0.boxed_clone(), - dateindex.minmax.max.0.boxed_clone(), + dateindex.boxed_average(), + dateindex.boxed_min(), + dateindex.boxed_max(), indexes, ); diff --git a/crates/brk_computer/src/internal/multi/derived_height/first.rs b/crates/brk_computer/src/internal/multi/height_derived/first.rs similarity index 82% rename from crates/brk_computer/src/internal/multi/derived_height/first.rs rename to crates/brk_computer/src/internal/multi/height_derived/first.rs index 1fd8e4e3e..2d4298b54 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/first.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/first.rs @@ -1,4 +1,4 @@ -//! ComputedDerivedBlockFirst - dateindex storage + difficultyepoch + lazy time periods (first value). +//! ComputedHeightDerivedFirst - dateindex storage + difficultyepoch + lazy time periods (first value). use brk_error::Result; @@ -10,12 +10,12 @@ use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec} use crate::{ ComputeIndexes, indexes, - internal::{ComputedVecValue, LazyPeriodsFirst, FirstVec, LazyFirst, NumericValue}, + internal::{ComputedVecValue, LazyDateDerivedFirst, FirstVec, LazyFirst, NumericValue}, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDerivedBlockFirst +pub struct ComputedHeightDerivedFirst where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -23,13 +23,13 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub dates: LazyPeriodsFirst, + pub dates: LazyDateDerivedFirst, pub difficultyepoch: LazyFirst, } const VERSION: Version = Version::ZERO; -impl ComputedDerivedBlockFirst +impl ComputedHeightDerivedFirst where T: NumericValue + JsonSchema, { @@ -44,7 +44,7 @@ where let v = version + VERSION; Ok(Self { - dates: LazyPeriodsFirst::from_source(name, v, dateindex.0.boxed_clone(), indexes), + dates: LazyDateDerivedFirst::from_source(name, v, dateindex.boxed_clone(), indexes), difficultyepoch: LazyFirst::from_source( name, v, diff --git a/crates/brk_computer/src/internal/multi/derived_height/full.rs b/crates/brk_computer/src/internal/multi/height_derived/full.rs similarity index 78% rename from crates/brk_computer/src/internal/multi/derived_height/full.rs rename to crates/brk_computer/src/internal/multi/height_derived/full.rs index 4c7d51abc..42f62f0e2 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/full.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/full.rs @@ -1,4 +1,4 @@ -//! ComputedDerivedBlockFull - height_cumulative + dateindex storage + difficultyepoch + lazy time periods. +//! ComputedHeightDerivedFull - height_cumulative + dateindex storage + difficultyepoch + lazy time periods. use brk_error::Result; @@ -11,14 +11,14 @@ use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec} use crate::{ ComputeIndexes, indexes, internal::{ - ComputedVecValue, CumulativeVec, LazyPeriodsFull, Full, LazyFull, NumericValue, + ComputedVecValue, CumulativeVec, LazyDateDerivedFull, Full, LazyFull, NumericValue, compute_cumulative_extend, }, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDerivedBlockFull +pub struct ComputedHeightDerivedFull where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,13 +27,13 @@ where pub dateindex: Full, #[deref] #[deref_mut] - pub dates: LazyPeriodsFull, + pub dates: LazyDateDerivedFull, pub difficultyepoch: LazyFull, } const VERSION: Version = Version::ZERO; -impl ComputedDerivedBlockFull +impl ComputedHeightDerivedFull where T: NumericValue + JsonSchema, { @@ -49,14 +49,14 @@ where let dateindex = Full::forced_import(db, name, v)?; Ok(Self { - dates: LazyPeriodsFull::from_sources( + dates: LazyDateDerivedFull::from_sources( name, v, - dateindex.distribution.average.0.boxed_clone(), - dateindex.distribution.minmax.min.0.boxed_clone(), - dateindex.distribution.minmax.max.0.boxed_clone(), - dateindex.sum_cum.sum.0.boxed_clone(), - dateindex.sum_cum.cumulative.0.boxed_clone(), + dateindex.boxed_average(), + dateindex.boxed_min(), + dateindex.boxed_max(), + dateindex.boxed_sum(), + dateindex.boxed_cumulative(), indexes, ), difficultyepoch: LazyFull::from_stats_aggregate( @@ -66,7 +66,7 @@ where height_source.boxed_clone(), height_source.boxed_clone(), height_source.boxed_clone(), - height_cumulative.0.boxed_clone(), + height_cumulative.boxed_clone(), indexes.difficultyepoch.identity.boxed_clone(), ), height_cumulative, diff --git a/crates/brk_computer/src/internal/multi/derived_height/last.rs b/crates/brk_computer/src/internal/multi/height_derived/last.rs similarity index 81% rename from crates/brk_computer/src/internal/multi/derived_height/last.rs rename to crates/brk_computer/src/internal/multi/height_derived/last.rs index 4169338d6..ea507372f 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/last.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/last.rs @@ -1,4 +1,4 @@ -//! ComputedDerivedBlockLast - dateindex storage + difficultyepoch + lazy time periods. +//! ComputedHeightDerivedLast - dateindex storage + difficultyepoch + lazy time periods. use brk_error::Result; @@ -10,12 +10,12 @@ use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec} use crate::{ ComputeIndexes, indexes, - internal::{ComputedVecValue, LazyPeriodsLast, LastVec, LazyLast, NumericValue}, + internal::{ComputedVecValue, LazyDateDerivedLast, LastVec, LazyLast, NumericValue}, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDerivedBlockLast +pub struct ComputedHeightDerivedLast where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -23,13 +23,13 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub dates: LazyPeriodsLast, + pub dates: LazyDateDerivedLast, pub difficultyepoch: LazyLast, } const VERSION: Version = Version::ZERO; -impl ComputedDerivedBlockLast +impl ComputedHeightDerivedLast where T: NumericValue + JsonSchema, { @@ -44,7 +44,7 @@ where let v = version + VERSION; Ok(Self { - dates: LazyPeriodsLast::from_source(name, v, dateindex.0.boxed_clone(), indexes), + dates: LazyDateDerivedLast::from_source(name, v, dateindex.boxed_clone(), indexes), difficultyepoch: LazyLast::from_source( name, v, diff --git a/crates/brk_computer/src/internal/multi/derived_height/lazy_full.rs b/crates/brk_computer/src/internal/multi/height_derived/lazy_full.rs similarity index 81% rename from crates/brk_computer/src/internal/multi/derived_height/lazy_full.rs rename to crates/brk_computer/src/internal/multi/height_derived/lazy_full.rs index 966117867..bcb54070b 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/lazy_full.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/lazy_full.rs @@ -7,26 +7,26 @@ use schemars::JsonSchema; use vecdb::{IterableCloneableVec, UnaryTransform}; use crate::internal::{ - ComputedDerivedBlockFull, ComputedVecValue, Full, LazyDateFull, LazyPeriodsFull, + ComputedHeightDerivedFull, ComputedVecValue, Full, LazyFromDateFull, LazyDateDerivedFull, LazyTransformStats, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyDerivedBlockFull +pub struct LazyHeightDerivedFull where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, { #[deref] #[deref_mut] - pub dates: LazyDateFull, + pub dates: LazyFromDateFull, pub difficultyepoch: LazyTransformStats, } const VERSION: Version = Version::ZERO; -impl LazyDerivedBlockFull +impl LazyHeightDerivedFull where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -35,7 +35,7 @@ where name: &str, version: Version, dateindex: &Full, - periods: &LazyPeriodsFull, + periods: &LazyDateDerivedFull, difficultyepoch: &crate::internal::LazyFull< DifficultyEpoch, S1T, @@ -46,7 +46,7 @@ where let v = version + VERSION; Self { - dates: LazyDateFull::from_full::(name, v, dateindex, periods), + dates: LazyFromDateFull::from_full::(name, v, dateindex, periods), difficultyepoch: LazyTransformStats::from_boxed::( name, v, @@ -62,7 +62,7 @@ where pub fn from_derived_computed>( name: &str, version: Version, - source: &ComputedDerivedBlockFull, + source: &ComputedHeightDerivedFull, ) -> Self where S1T: NumericValue, @@ -70,7 +70,7 @@ where let v = version + VERSION; Self { - dates: LazyDateFull::from_full::(name, v, &source.dateindex, &source.dates), + dates: LazyFromDateFull::from_full::(name, v, &source.dateindex, &source.dates), difficultyepoch: LazyTransformStats::from_boxed::( name, v, diff --git a/crates/brk_computer/src/internal/multi/derived_height/lazy_last.rs b/crates/brk_computer/src/internal/multi/height_derived/lazy_last.rs similarity index 73% rename from crates/brk_computer/src/internal/multi/derived_height/lazy_last.rs rename to crates/brk_computer/src/internal/multi/height_derived/lazy_last.rs index e732dbf8e..901477dce 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/lazy_last.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/lazy_last.rs @@ -7,26 +7,26 @@ use schemars::JsonSchema; use vecdb::{IterableCloneableVec, UnaryTransform}; use crate::internal::{ - ComputedBlockLast, ComputedDerivedBlockLast, ComputedHeightDateLast, ComputedVecValue, - LazyDateLast, LazyTransformLast, NumericValue, + ComputedFromHeightLast, ComputedHeightDerivedLast, ComputedFromHeightAndDateLast, ComputedVecValue, + LazyFromDateLast, LazyTransformLast, NumericValue, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyDerivedBlockLast +pub struct LazyHeightDerivedLast where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, { #[deref] #[deref_mut] - pub dates: LazyDateLast, + pub dates: LazyFromDateLast, pub difficultyepoch: LazyTransformLast, } const VERSION: Version = Version::ZERO; -impl LazyDerivedBlockLast +impl LazyHeightDerivedLast where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -34,7 +34,7 @@ where pub fn from_computed>( name: &str, version: Version, - source: &ComputedBlockLast, + source: &ComputedFromHeightLast, ) -> Self where S1T: NumericValue, @@ -42,10 +42,10 @@ where let v = version + VERSION; Self { - dates: LazyDateLast::from_derived::( + dates: LazyFromDateLast::from_derived::( name, v, - source.dateindex.0.boxed_clone(), + source.dateindex.boxed_clone(), &source.rest, ), difficultyepoch: LazyTransformLast::from_boxed::( @@ -59,7 +59,7 @@ where pub fn from_derived_computed>( name: &str, version: Version, - source: &ComputedDerivedBlockLast, + source: &ComputedHeightDerivedLast, ) -> Self where S1T: NumericValue, @@ -67,10 +67,10 @@ where let v = version + VERSION; Self { - dates: LazyDateLast::from_derived::( + dates: LazyFromDateLast::from_derived::( name, v, - source.dateindex.0.boxed_clone(), + source.dateindex.boxed_clone(), &source.dates, ), difficultyepoch: LazyTransformLast::from_boxed::( @@ -84,7 +84,7 @@ where pub fn from_computed_height_date>( name: &str, version: Version, - source: &ComputedHeightDateLast, + source: &ComputedFromHeightAndDateLast, ) -> Self where S1T: PartialOrd, @@ -92,7 +92,7 @@ where let v = version + VERSION; Self { - dates: LazyDateLast::from_derived::( + dates: LazyFromDateLast::from_derived::( name, v, source.dateindex.boxed_clone(), @@ -101,7 +101,7 @@ where difficultyepoch: LazyTransformLast::from_boxed::( name, v, - source.difficultyepoch.0.boxed_clone(), + source.difficultyepoch.boxed_clone(), ), } } diff --git a/crates/brk_computer/src/internal/multi/derived_height/lazy_sum.rs b/crates/brk_computer/src/internal/multi/height_derived/lazy_sum.rs similarity index 76% rename from crates/brk_computer/src/internal/multi/derived_height/lazy_sum.rs rename to crates/brk_computer/src/internal/multi/height_derived/lazy_sum.rs index 93b6d60e4..c2cc35693 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/lazy_sum.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/lazy_sum.rs @@ -7,26 +7,26 @@ use schemars::JsonSchema; use vecdb::{IterableCloneableVec, UnaryTransform}; use crate::internal::{ - ComputedDerivedBlockSum, ComputedVecValue, LazyDateSum, LazyPeriodsSum, LazySum, + ComputedHeightDerivedSum, ComputedVecValue, LazyFromDateSum, LazyDateDerivedSum, LazySum, LazyTransformSum, NumericValue, SumVec, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyDerivedBlockSum +pub struct LazyHeightDerivedSum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, { #[deref] #[deref_mut] - pub dates: LazyDateSum, + pub dates: LazyFromDateSum, pub difficultyepoch: LazyTransformSum, } const VERSION: Version = Version::ZERO; -impl LazyDerivedBlockSum +impl LazyHeightDerivedSum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -35,13 +35,13 @@ where name: &str, version: Version, dateindex: &SumVec, - periods: &LazyPeriodsSum, + periods: &LazyDateDerivedSum, difficultyepoch: &LazySum, ) -> Self { let v = version + VERSION; Self { - dates: LazyDateSum::from_derived::(name, v, dateindex.0.boxed_clone(), periods), + dates: LazyFromDateSum::from_derived::(name, v, dateindex.boxed_clone(), periods), difficultyepoch: LazyTransformSum::from_boxed::( name, v, @@ -53,7 +53,7 @@ where pub fn from_derived_computed>( name: &str, version: Version, - source: &ComputedDerivedBlockSum, + source: &ComputedHeightDerivedSum, ) -> Self where S1T: NumericValue, @@ -61,10 +61,10 @@ where let v = version + VERSION; Self { - dates: LazyDateSum::from_derived::( + dates: LazyFromDateSum::from_derived::( name, v, - source.dateindex.0.boxed_clone(), + source.dateindex.boxed_clone(), &source.dates, ), difficultyepoch: LazyTransformSum::from_boxed::( diff --git a/crates/brk_computer/src/internal/multi/derived_height/lazy_sum_cum.rs b/crates/brk_computer/src/internal/multi/height_derived/lazy_sum_cum.rs similarity index 77% rename from crates/brk_computer/src/internal/multi/derived_height/lazy_sum_cum.rs rename to crates/brk_computer/src/internal/multi/height_derived/lazy_sum_cum.rs index 2e2c080b9..80545fbb0 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/lazy_sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/lazy_sum_cum.rs @@ -7,26 +7,26 @@ use schemars::JsonSchema; use vecdb::{IterableCloneableVec, UnaryTransform}; use crate::internal::{ - ComputedDerivedBlockSumCum, ComputedVecValue, LazyDateSumCum, LazyPeriodsSumCum, LazySumCum, + ComputedHeightDerivedSumCum, ComputedVecValue, LazyFromDateSumCum, LazyDateDerivedSumCum, LazySumCum, LazyTransformSumCum, NumericValue, SumCum, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct LazyDerivedBlockSumCum +pub struct LazyHeightDerivedSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, { #[deref] #[deref_mut] - pub dates: LazyDateSumCum, + pub dates: LazyFromDateSumCum, pub difficultyepoch: LazyTransformSumCum, } const VERSION: Version = Version::ZERO; -impl LazyDerivedBlockSumCum +impl LazyHeightDerivedSumCum where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -35,13 +35,13 @@ where name: &str, version: Version, dateindex: &SumCum, - periods: &LazyPeriodsSumCum, + periods: &LazyDateDerivedSumCum, difficultyepoch: &LazySumCum, ) -> Self { let v = version + VERSION; Self { - dates: LazyDateSumCum::from_sum_cum::(name, v, dateindex, periods), + dates: LazyFromDateSumCum::from_sum_cum::(name, v, dateindex, periods), difficultyepoch: LazyTransformSumCum::from_boxed_sum_raw::( name, v, @@ -54,7 +54,7 @@ where pub fn from_derived_computed>( name: &str, version: Version, - source: &ComputedDerivedBlockSumCum, + source: &ComputedHeightDerivedSumCum, ) -> Self where S1T: NumericValue, @@ -62,7 +62,7 @@ where let v = version + VERSION; Self { - dates: LazyDateSumCum::from_sum_cum::(name, v, &source.dateindex, &source.dates), + dates: LazyFromDateSumCum::from_sum_cum::(name, v, &source.dateindex, &source.dates), difficultyepoch: LazyTransformSumCum::from_boxed_sum_raw::( name, v, diff --git a/crates/brk_computer/src/internal/multi/derived_height/mod.rs b/crates/brk_computer/src/internal/multi/height_derived/mod.rs similarity index 91% rename from crates/brk_computer/src/internal/multi/derived_height/mod.rs rename to crates/brk_computer/src/internal/multi/height_derived/mod.rs index b0f432c1a..20dd1904a 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/mod.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/mod.rs @@ -11,6 +11,7 @@ mod lazy_sum; mod lazy_sum_cum; mod sum; mod sum_cum; +mod value_sum_cum; pub use binary_last::*; pub use binary_sum::*; @@ -25,3 +26,4 @@ pub use lazy_sum::*; pub use lazy_sum_cum::*; pub use sum::*; pub use sum_cum::*; +pub use value_sum_cum::*; diff --git a/crates/brk_computer/src/internal/multi/derived_height/sum.rs b/crates/brk_computer/src/internal/multi/height_derived/sum.rs similarity index 88% rename from crates/brk_computer/src/internal/multi/derived_height/sum.rs rename to crates/brk_computer/src/internal/multi/height_derived/sum.rs index cf11c739f..4ced10d35 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/sum.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/sum.rs @@ -1,4 +1,4 @@ -//! ComputedDerivedBlockSum - dateindex storage + difficultyepoch + lazy time periods. +//! ComputedHeightDerivedSum - dateindex storage + difficultyepoch + lazy time periods. use brk_error::Result; @@ -13,25 +13,25 @@ use vecdb::{ use crate::{ ComputeIndexes, indexes, - internal::{ComputedVecValue, LazyPeriodsSum, LazySum, NumericValue, SumVec}, + internal::{ComputedVecValue, LazyDateDerivedSum, LazySum, NumericValue, SumVec}, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDerivedBlockSum +pub struct ComputedHeightDerivedSum where T: ComputedVecValue + PartialOrd + JsonSchema, { pub dateindex: SumVec, #[deref] #[deref_mut] - pub dates: LazyPeriodsSum, + pub dates: LazyDateDerivedSum, pub difficultyepoch: LazySum, } const VERSION: Version = Version::ZERO; -impl ComputedDerivedBlockSum +impl ComputedHeightDerivedSum where T: NumericValue + JsonSchema, { @@ -46,7 +46,7 @@ where let v = version + VERSION; Ok(Self { - dates: LazyPeriodsSum::from_source(name, v, dateindex.0.boxed_clone(), indexes), + dates: LazyDateDerivedSum::from_source(name, v, dateindex.boxed_clone(), indexes), difficultyepoch: LazySum::from_source_raw( name, v, diff --git a/crates/brk_computer/src/internal/multi/derived_height/sum_cum.rs b/crates/brk_computer/src/internal/multi/height_derived/sum_cum.rs similarity index 89% rename from crates/brk_computer/src/internal/multi/derived_height/sum_cum.rs rename to crates/brk_computer/src/internal/multi/height_derived/sum_cum.rs index a57995e37..f73fc40ce 100644 --- a/crates/brk_computer/src/internal/multi/derived_height/sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/sum_cum.rs @@ -1,4 +1,4 @@ -//! ComputedDerivedBlockSumCum - aggregates derived from an external height source. +//! ComputedHeightDerivedSumCum - aggregates derived from an external height source. use brk_error::Result; @@ -14,14 +14,14 @@ use vecdb::{ use crate::{ ComputeIndexes, indexes, internal::{ - ComputedVecValue, CumulativeVec, LazyPeriodsSumCum, LazySumCum, NumericValue, SumCum, + ComputedVecValue, CumulativeVec, LazyDateDerivedSumCum, LazySumCum, NumericValue, SumCum, compute_cumulative_extend, }, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedDerivedBlockSumCum +pub struct ComputedHeightDerivedSumCum where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -30,13 +30,13 @@ where pub dateindex: SumCum, #[deref] #[deref_mut] - pub dates: LazyPeriodsSumCum, + pub dates: LazyDateDerivedSumCum, pub difficultyepoch: LazySumCum, } const VERSION: Version = Version::ZERO; -impl ComputedDerivedBlockSumCum +impl ComputedHeightDerivedSumCum where T: NumericValue + JsonSchema, { @@ -52,11 +52,11 @@ where let height_cumulative = CumulativeVec::forced_import(db, name, v)?; let dateindex = SumCum::forced_import_sum_raw(db, name, v)?; - let dates = LazyPeriodsSumCum::from_sources( + let dates = LazyDateDerivedSumCum::from_sources( name, v, - dateindex.sum.0.boxed_clone(), - dateindex.cumulative.0.boxed_clone(), + dateindex.boxed_sum(), + dateindex.boxed_cumulative(), indexes, ); @@ -64,7 +64,7 @@ where name, v, height_source.boxed_clone(), - height_cumulative.0.boxed_clone(), + height_cumulative.boxed_clone(), indexes.difficultyepoch.identity.boxed_clone(), ); diff --git a/crates/brk_computer/src/internal/multi/value/derived_height/sum_cum.rs b/crates/brk_computer/src/internal/multi/height_derived/value_sum_cum.rs similarity index 79% rename from crates/brk_computer/src/internal/multi/value/derived_height/sum_cum.rs rename to crates/brk_computer/src/internal/multi/height_derived/value_sum_cum.rs index 1d2a23126..6009e534d 100644 --- a/crates/brk_computer/src/internal/multi/value/derived_height/sum_cum.rs +++ b/crates/brk_computer/src/internal/multi/height_derived/value_sum_cum.rs @@ -8,7 +8,7 @@ use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec, use crate::{ ComputeIndexes, indexes, internal::{ - ClosePriceTimesSats, ComputedDerivedBlockSumCum, LazyBlockSumCum, LazyBlockSumCumHeight, + ClosePriceTimesSats, ComputedHeightDerivedSumCum, LazyFromHeightSumCum, LazyComputedFromHeightSumCum, SatsToBitcoin, }, price, @@ -16,15 +16,15 @@ use crate::{ /// Value wrapper for derived SumCum (derives from external height source). #[derive(Clone, Traversable)] -pub struct ValueDerivedBlockSumCum { - pub sats: ComputedDerivedBlockSumCum, - pub bitcoin: LazyBlockSumCum, - pub dollars: Option, Sats>>, +pub struct ValueHeightDerivedSumCum { + pub sats: ComputedHeightDerivedSumCum, + pub bitcoin: LazyFromHeightSumCum, + pub dollars: Option, Sats>>, } const VERSION: Version = Version::ZERO; -impl ValueDerivedBlockSumCum { +impl ValueHeightDerivedSumCum { pub fn forced_import( db: &Database, name: &str, @@ -35,7 +35,7 @@ impl ValueDerivedBlockSumCum { ) -> Result { let v = version + VERSION; - let sats = ComputedDerivedBlockSumCum::forced_import( + let sats = ComputedHeightDerivedSumCum::forced_import( db, name, sats_source.boxed_clone(), @@ -43,7 +43,7 @@ impl ValueDerivedBlockSumCum { indexes, )?; - let bitcoin = LazyBlockSumCum::from_derived::( + let bitcoin = LazyFromHeightSumCum::from_derived::( &format!("{name}_btc"), v, sats_source.boxed_clone(), @@ -58,7 +58,7 @@ impl ValueDerivedBlockSumCum { sats_source.boxed_clone(), ); - Some(LazyBlockSumCumHeight::forced_import( + Some(LazyComputedFromHeightSumCum::forced_import( db, &format!("{name}_usd"), v, diff --git a/crates/brk_computer/src/internal/multi/mod.rs b/crates/brk_computer/src/internal/multi/mod.rs index c21562de8..487798f2a 100644 --- a/crates/brk_computer/src/internal/multi/mod.rs +++ b/crates/brk_computer/src/internal/multi/mod.rs @@ -1,17 +1,19 @@ //! Multi-index composite types. -mod date; -mod derived_date; -mod derived_height; -mod derived_tx; -mod height; -mod specialized; -mod value; +mod date_derived; +mod from_date; +mod from_height; +mod from_height_and_date; +mod from_tx; +mod height_and_date; +mod height_derived; +mod tx_derived; -pub use date::*; -pub use derived_date::*; -pub use derived_height::*; -pub use derived_tx::*; -pub use height::*; -pub use specialized::*; -pub use value::*; +pub use date_derived::*; +pub use from_date::*; +pub use from_height::*; +pub use from_height_and_date::*; +pub use from_tx::*; +pub use height_and_date::*; +pub use height_derived::*; +pub use tx_derived::*; diff --git a/crates/brk_computer/src/internal/multi/specialized/mod.rs b/crates/brk_computer/src/internal/multi/specialized/mod.rs deleted file mode 100644 index 211f63fdf..000000000 --- a/crates/brk_computer/src/internal/multi/specialized/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -mod constant; -mod ohlc; -mod percentiles; -mod ratio; -mod stddev; - -pub use constant::*; -pub use ohlc::*; -pub use percentiles::*; -pub use ratio::*; -pub use stddev::*; diff --git a/crates/brk_computer/src/internal/multi/specialized/ohlc/mod.rs b/crates/brk_computer/src/internal/multi/specialized/ohlc/mod.rs deleted file mode 100644 index 604d49d61..000000000 --- a/crates/brk_computer/src/internal/multi/specialized/ohlc/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -mod computed; -mod lazy; -mod period; - -pub use computed::*; -pub use lazy::*; -pub use period::*; diff --git a/crates/brk_computer/src/internal/multi/derived_tx/distribution.rs b/crates/brk_computer/src/internal/multi/tx_derived/distribution.rs similarity index 65% rename from crates/brk_computer/src/internal/multi/derived_tx/distribution.rs rename to crates/brk_computer/src/internal/multi/tx_derived/distribution.rs index b4a5b6980..ccc8a358e 100644 --- a/crates/brk_computer/src/internal/multi/derived_tx/distribution.rs +++ b/crates/brk_computer/src/internal/multi/tx_derived/distribution.rs @@ -1,4 +1,4 @@ -//! ComputedTxDistribution - computes TxIndex data to height Distribution + dateindex MinMaxAverage + lazy aggregations. +//! TxDerivedDistribution - computes TxIndex data to height Distribution + dateindex MinMaxAverage + lazy aggregations. //! //! Note: Percentiles are computed at height level only. DateIndex and coarser //! periods only have average+min+max since computing percentiles across all @@ -16,14 +16,14 @@ use vecdb::{CollectableVec, Database, Exit, IterableCloneableVec}; use crate::{ ComputeIndexes, indexes, internal::{ - ComputedVecValue, LazyPeriodsDistribution, Distribution, LazyDistribution, MinMaxAverage, + ComputedVecValue, LazyDateDerivedDistribution, Distribution, LazyDistribution, MinMaxAverage, NumericValue, }, }; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct DerivedTxDistribution +pub struct TxDerivedDistribution where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -33,12 +33,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub dates: LazyPeriodsDistribution, + pub dates: LazyDateDerivedDistribution, } const VERSION: Version = Version::ZERO; -impl DerivedTxDistribution +impl TxDerivedDistribution where T: NumericValue + JsonSchema, { @@ -56,18 +56,18 @@ where LazyDistribution::::from_distribution( name, v, - height.average.0.boxed_clone(), - height.minmax.min.0.boxed_clone(), - height.minmax.max.0.boxed_clone(), + height.boxed_average(), + height.boxed_min(), + height.boxed_max(), indexes.difficultyepoch.identity.boxed_clone(), ); - let dates = LazyPeriodsDistribution::from_sources( + let dates = LazyDateDerivedDistribution::from_sources( name, v, - dateindex.average.0.boxed_clone(), - dateindex.minmax.min.0.boxed_clone(), - dateindex.minmax.max.0.boxed_clone(), + dateindex.boxed_average(), + dateindex.boxed_min(), + dateindex.boxed_max(), indexes, ); @@ -87,17 +87,33 @@ where txindex_source: &impl CollectableVec, exit: &Exit, ) -> Result<()> { - self.height.compute( + self.derive_from_with_skip(indexer, indexes, starting_indexes, txindex_source, exit, 0) + } + + /// Derive from source, skipping first N transactions per block from all calculations. + /// + /// Use `skip_count: 1` to exclude coinbase transactions from fee/feerate stats. + pub fn derive_from_with_skip( + &mut self, + indexer: &Indexer, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + txindex_source: &impl CollectableVec, + exit: &Exit, + skip_count: usize, + ) -> Result<()> { + self.height.compute_with_skip( starting_indexes.height, txindex_source, &indexer.vecs.transactions.first_txindex, &indexes.height.txindex_count, exit, + skip_count, )?; self.dateindex.compute( starting_indexes.dateindex, - &self.height.average.0, + &self.height.average().0, &indexes.dateindex.first_height, &indexes.dateindex.height_count, exit, diff --git a/crates/brk_computer/src/internal/multi/derived_tx/full.rs b/crates/brk_computer/src/internal/multi/tx_derived/full.rs similarity index 62% rename from crates/brk_computer/src/internal/multi/derived_tx/full.rs rename to crates/brk_computer/src/internal/multi/tx_derived/full.rs index a1cd8c1c0..fba515791 100644 --- a/crates/brk_computer/src/internal/multi/derived_tx/full.rs +++ b/crates/brk_computer/src/internal/multi/tx_derived/full.rs @@ -1,4 +1,4 @@ -//! DerivedTxFull - aggregates from TxIndex to height Full + dateindex Stats + lazy date periods. +//! TxDerivedFull - aggregates from TxIndex to height Full + dateindex Stats + lazy date periods. use brk_error::Result; use brk_indexer::Indexer; @@ -11,13 +11,13 @@ use vecdb::{CollectableVec, Database, Exit, IterableCloneableVec}; use crate::{ indexes, ComputeIndexes, - internal::{ComputedVecValue, LazyPeriodsFull, Full, LazyFull, NumericValue, Stats}, + internal::{ComputedVecValue, LazyDateDerivedFull, Full, LazyFull, NumericValue, Stats}, }; /// Aggregates from TxIndex to height/dateindex with full stats. #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct DerivedTxFull +pub struct TxDerivedFull where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -27,12 +27,12 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub dates: LazyPeriodsFull, + pub dates: LazyDateDerivedFull, } const VERSION: Version = Version::ZERO; -impl DerivedTxFull +impl TxDerivedFull where T: NumericValue + JsonSchema, { @@ -50,22 +50,22 @@ where LazyFull::::from_stats_aggregate( name, v, - height.distribution.average.0.boxed_clone(), - height.distribution.minmax.min.0.boxed_clone(), - height.distribution.minmax.max.0.boxed_clone(), - height.sum_cum.sum.0.boxed_clone(), - height.sum_cum.cumulative.0.boxed_clone(), + height.boxed_average(), + height.boxed_min(), + height.boxed_max(), + height.boxed_sum(), + height.boxed_cumulative(), indexes.difficultyepoch.identity.boxed_clone(), ); - let dates = LazyPeriodsFull::from_sources( + let dates = LazyDateDerivedFull::from_sources( name, v, - dateindex.average.0.boxed_clone(), - dateindex.minmax.min.0.boxed_clone(), - dateindex.minmax.max.0.boxed_clone(), - dateindex.sum_cum.sum.0.boxed_clone(), - dateindex.sum_cum.cumulative.0.boxed_clone(), + dateindex.boxed_average(), + dateindex.boxed_min(), + dateindex.boxed_max(), + dateindex.boxed_sum(), + dateindex.boxed_cumulative(), indexes, ); @@ -85,17 +85,33 @@ where txindex_source: &impl CollectableVec, exit: &Exit, ) -> Result<()> { - self.height.compute( + self.derive_from_with_skip(indexer, indexes, starting_indexes, txindex_source, exit, 0) + } + + /// Derive from source, skipping first N transactions per block from all calculations. + /// + /// Use `skip_count: 1` to exclude coinbase transactions from fee/feerate stats. + pub fn derive_from_with_skip( + &mut self, + indexer: &Indexer, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + txindex_source: &impl CollectableVec, + exit: &Exit, + skip_count: usize, + ) -> Result<()> { + self.height.compute_with_skip( starting_indexes.height, txindex_source, &indexer.vecs.transactions.first_txindex, &indexes.height.txindex_count, exit, + skip_count, )?; self.dateindex.compute( starting_indexes.dateindex, - &self.height.distribution.average.0, + &self.height.average().0, &indexes.dateindex.first_height, &indexes.dateindex.height_count, exit, diff --git a/crates/brk_computer/src/internal/multi/derived_tx/lazy_full.rs b/crates/brk_computer/src/internal/multi/tx_derived/lazy_full.rs similarity index 80% rename from crates/brk_computer/src/internal/multi/derived_tx/lazy_full.rs rename to crates/brk_computer/src/internal/multi/tx_derived/lazy_full.rs index 6d6d14dd9..3223644a6 100644 --- a/crates/brk_computer/src/internal/multi/derived_tx/lazy_full.rs +++ b/crates/brk_computer/src/internal/multi/tx_derived/lazy_full.rs @@ -1,4 +1,4 @@ -//! Lazy transform of DerivedTxFull. +//! Lazy transform of TxDerivedFull. use brk_traversable::Traversable; use brk_types::{ @@ -8,11 +8,11 @@ use brk_types::{ use schemars::JsonSchema; use vecdb::{IterableCloneableVec, UnaryTransform}; -use crate::internal::{ComputedVecValue, DerivedTxFull, LazyTransformFull, LazyTransformStats}; +use crate::internal::{ComputedVecValue, TxDerivedFull, LazyTransformFull, LazyTransformStats}; #[derive(Clone, Traversable)] #[traversable(merge)] -pub struct LazyDerivedTxFull +pub struct LazyTxDerivedFull where T: ComputedVecValue + PartialOrd + JsonSchema, S1T: ComputedVecValue, @@ -30,7 +30,7 @@ where const VERSION: Version = Version::ZERO; -impl LazyDerivedTxFull +impl LazyTxDerivedFull where T: ComputedVecValue + JsonSchema + 'static, S1T: ComputedVecValue + JsonSchema, @@ -38,7 +38,7 @@ where pub fn from_computed>( name: &str, version: Version, - source: &DerivedTxFull, + source: &TxDerivedFull, ) -> Self { let v = version + VERSION; @@ -58,11 +58,11 @@ where difficultyepoch: period!(difficultyepoch), dateindex: LazyTransformStats::from_boxed::( name, v, - source.dateindex.average.0.boxed_clone(), - source.dateindex.minmax.min.0.boxed_clone(), - source.dateindex.minmax.max.0.boxed_clone(), - source.dateindex.sum_cum.sum.0.boxed_clone(), - source.dateindex.sum_cum.cumulative.0.boxed_clone(), + source.dateindex.boxed_average(), + source.dateindex.boxed_min(), + source.dateindex.boxed_max(), + source.dateindex.boxed_sum(), + source.dateindex.boxed_cumulative(), ), weekindex: period!(weekindex), monthindex: period!(monthindex), diff --git a/crates/brk_computer/src/internal/multi/derived_tx/mod.rs b/crates/brk_computer/src/internal/multi/tx_derived/mod.rs similarity index 67% rename from crates/brk_computer/src/internal/multi/derived_tx/mod.rs rename to crates/brk_computer/src/internal/multi/tx_derived/mod.rs index 51b46a003..e5df1d57c 100644 --- a/crates/brk_computer/src/internal/multi/derived_tx/mod.rs +++ b/crates/brk_computer/src/internal/multi/tx_derived/mod.rs @@ -1,9 +1,9 @@ mod distribution; mod full; -mod lazy_distribution; mod lazy_full; +mod value_full; pub use distribution::*; pub use full::*; -pub use lazy_distribution::*; pub use lazy_full::*; +pub use value_full::*; diff --git a/crates/brk_computer/src/internal/multi/value/tx/derived_full.rs b/crates/brk_computer/src/internal/multi/tx_derived/value_full.rs similarity index 57% rename from crates/brk_computer/src/internal/multi/value/tx/derived_full.rs rename to crates/brk_computer/src/internal/multi/tx_derived/value_full.rs index 28c63249f..746793bd9 100644 --- a/crates/brk_computer/src/internal/multi/value/tx/derived_full.rs +++ b/crates/brk_computer/src/internal/multi/tx_derived/value_full.rs @@ -8,20 +8,20 @@ use vecdb::{CollectableVec, Database, Exit, IterableCloneableVec}; use crate::{ ComputeIndexes, indexes, - internal::{DerivedTxFull, ValueDollarsTxFull, LazyDerivedTxFull, SatsToBitcoin}, + internal::{TxDerivedFull, ValueDollarsFromTxFull, LazyTxDerivedFull, SatsToBitcoin}, price, }; #[derive(Clone, Traversable)] -pub struct ValueDerivedTxFull { - pub sats: DerivedTxFull, - pub bitcoin: LazyDerivedTxFull, - pub dollars: Option, +pub struct ValueTxDerivedFull { + pub sats: TxDerivedFull, + pub bitcoin: LazyTxDerivedFull, + pub dollars: Option, } const VERSION: Version = Version::ZERO; -impl ValueDerivedTxFull { +impl ValueTxDerivedFull { pub fn forced_import( db: &Database, name: &str, @@ -33,21 +33,22 @@ impl ValueDerivedTxFull { ) -> Result { let v = version + VERSION; - let sats = DerivedTxFull::forced_import(db, name, v, indexes)?; + let sats = TxDerivedFull::forced_import(db, name, v, indexes)?; let bitcoin = - LazyDerivedTxFull::from_computed::(&format!("{name}_btc"), v, &sats); + LazyTxDerivedFull::from_computed::(&format!("{name}_btc"), v, &sats); let dollars = price .map(|price| { - ValueDollarsTxFull::forced_import( + ValueDollarsFromTxFull::forced_import( db, &format!("{name}_usd"), v, indexes, + &sats.height, + price.usd.split.close.height.boxed_clone(), sats_txindex.boxed_clone(), indexer.vecs.transactions.height.boxed_clone(), - price.usd.split.close.height.boxed_clone(), ) }) .transpose()?; @@ -67,8 +68,29 @@ impl ValueDerivedTxFull { txindex_source: &impl CollectableVec, exit: &Exit, ) -> Result<()> { - self.sats - .derive_from(indexer, indexes, starting_indexes, txindex_source, exit)?; + self.derive_from_with_skip(indexer, indexes, starting_indexes, txindex_source, exit, 0) + } + + /// Derive from source, skipping first N transactions per block from all calculations. + /// + /// Use `skip_count: 1` to exclude coinbase transactions from fee/feerate stats. + pub fn derive_from_with_skip( + &mut self, + indexer: &Indexer, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + txindex_source: &impl CollectableVec, + exit: &Exit, + skip_count: usize, + ) -> Result<()> { + self.sats.derive_from_with_skip( + indexer, + indexes, + starting_indexes, + txindex_source, + exit, + skip_count, + )?; if let Some(dollars) = self.dollars.as_mut() { dollars.derive_from(indexer, indexes, starting_indexes, exit)?; diff --git a/crates/brk_computer/src/internal/multi/value/date/mod.rs b/crates/brk_computer/src/internal/multi/value/date/mod.rs deleted file mode 100644 index 45774b152..000000000 --- a/crates/brk_computer/src/internal/multi/value/date/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -mod derived_last; -mod height_date_last; -mod last; -mod lazy_last; - -pub use height_date_last::*; -pub use derived_last::*; -pub use last::*; -pub use lazy_last::*; diff --git a/crates/brk_computer/src/internal/multi/value/derived_height/mod.rs b/crates/brk_computer/src/internal/multi/value/derived_height/mod.rs deleted file mode 100644 index 9d6b32026..000000000 --- a/crates/brk_computer/src/internal/multi/value/derived_height/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod sum_cum; - -pub use sum_cum::*; diff --git a/crates/brk_computer/src/internal/multi/value/height/full.rs b/crates/brk_computer/src/internal/multi/value/height/full.rs deleted file mode 100644 index e78ae1e4b..000000000 --- a/crates/brk_computer/src/internal/multi/value/height/full.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! Value type for Full pattern from Height. - -use brk_error::Result; -use brk_traversable::Traversable; -use brk_types::{Bitcoin, Dollars, Height, Sats, Version}; -use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, PcoVec}; - -use crate::{ - ComputeIndexes, indexes, - internal::{ComputedBlockFull, LazyBlockFull, SatsToBitcoin}, - price, - traits::ComputeFromBitcoin, -}; - -#[derive(Clone, Traversable)] -pub struct ValueBlockFull { - pub sats: ComputedBlockFull, - pub bitcoin: LazyBlockFull, - pub dollars: Option>, -} - -const VERSION: Version = Version::ZERO; - -impl ValueBlockFull { - pub fn forced_import( - db: &Database, - name: &str, - version: Version, - indexes: &indexes::Vecs, - compute_dollars: bool, - ) -> Result { - let v = version + VERSION; - - let sats = ComputedBlockFull::forced_import(db, name, v, indexes)?; - - let bitcoin = LazyBlockFull::from_computed::( - &format!("{name}_btc"), - v, - sats.height.boxed_clone(), - &sats, - ); - - let dollars = compute_dollars - .then(|| ComputedBlockFull::forced_import(db, &format!("{name}_usd"), v, indexes)) - .transpose()?; - - Ok(Self { - sats, - bitcoin, - dollars, - }) - } - - pub fn compute_all( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - mut compute: F, - ) -> Result<()> - where - F: FnMut(&mut EagerVec>) -> Result<()>, - { - // Compute sats - self.sats - .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; - - // Compute dollars from bitcoin and price (if enabled) - if let (Some(dollars), Some(price)) = (self.dollars.as_mut(), price) { - let height_to_bitcoin = &self.bitcoin.height; - let height_to_price_close = &price.usd.split.close.height; - - dollars.compute_all(indexes, starting_indexes, exit, |v| { - v.compute_from_bitcoin( - starting_indexes.height, - height_to_bitcoin, - height_to_price_close, - exit, - ) - })?; - } - - Ok(()) - } -} diff --git a/crates/brk_computer/src/internal/multi/value/height/last.rs b/crates/brk_computer/src/internal/multi/value/height/last.rs deleted file mode 100644 index ee3ec24eb..000000000 --- a/crates/brk_computer/src/internal/multi/value/height/last.rs +++ /dev/null @@ -1,107 +0,0 @@ -//! Value type for Last pattern from Height. - -use brk_error::Result; -use brk_traversable::Traversable; -use brk_types::{Bitcoin, Dollars, Height, Sats, Version}; -use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, PcoVec}; - -use crate::{ - ComputeIndexes, indexes, - internal::{ComputedBlockLast, LazyBlockLast, SatsToBitcoin}, - price, - traits::ComputeFromBitcoin, -}; - -#[derive(Clone, Traversable)] -pub struct ValueBlockLast { - pub sats: ComputedBlockLast, - pub bitcoin: LazyBlockLast, - pub dollars: Option>, -} - -const VERSION: Version = Version::ZERO; - -impl ValueBlockLast { - pub fn forced_import( - db: &Database, - name: &str, - version: Version, - indexes: &indexes::Vecs, - compute_dollars: bool, - ) -> Result { - let v = version + VERSION; - - let sats = ComputedBlockLast::forced_import(db, name, v, indexes)?; - - let bitcoin = LazyBlockLast::from_computed::( - &format!("{name}_btc"), - v, - sats.height.boxed_clone(), - &sats, - ); - - let dollars = compute_dollars - .then(|| ComputedBlockLast::forced_import(db, &format!("{name}_usd"), v, indexes)) - .transpose()?; - - Ok(Self { - sats, - bitcoin, - dollars, - }) - } - - pub fn compute_all( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - mut compute: F, - ) -> Result<()> - where - F: FnMut(&mut EagerVec>) -> Result<()>, - { - // Compute sats (closure receives &mut height vec) - self.sats - .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; - - self.compute_dollars(indexes, price, starting_indexes, exit) - } - - /// Compute derived vecs from existing height data. - pub fn compute_rest( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - ) -> Result<()> { - self.sats.compute_rest(indexes, starting_indexes, exit)?; - self.compute_dollars(indexes, price, starting_indexes, exit) - } - - fn compute_dollars( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - ) -> Result<()> { - if let (Some(dollars), Some(price)) = (self.dollars.as_mut(), price) { - let height_to_bitcoin = &self.bitcoin.height; - let height_to_price_close = &price.usd.split.close.height; - - dollars.compute_all(indexes, starting_indexes, exit, |v| { - v.compute_from_bitcoin( - starting_indexes.height, - height_to_bitcoin, - height_to_price_close, - exit, - ) - })?; - } - - Ok(()) - } -} diff --git a/crates/brk_computer/src/internal/multi/value/height/mod.rs b/crates/brk_computer/src/internal/multi/value/height/mod.rs deleted file mode 100644 index 356e52aa1..000000000 --- a/crates/brk_computer/src/internal/multi/value/height/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -mod binary; -mod full; -mod last; -mod lazy_block_value; -mod lazy_binary_last; -mod lazy_computed_sum_cum; -mod lazy_derived; -mod lazy_difficultyepoch; -mod lazy_height; -mod lazy_last; -mod lazy_sum_cum; -mod sum; -mod sum_cum; - -pub use binary::*; -pub use full::*; -pub use last::*; -pub use lazy_block_value::*; -pub use lazy_binary_last::*; -pub use lazy_computed_sum_cum::*; -pub use lazy_derived::*; -pub use lazy_difficultyepoch::*; -pub use lazy_height::*; -pub use lazy_last::*; -pub use lazy_sum_cum::*; -pub use sum::*; -pub use sum_cum::*; diff --git a/crates/brk_computer/src/internal/multi/value/height/sum.rs b/crates/brk_computer/src/internal/multi/value/height/sum.rs deleted file mode 100644 index 3ad6143e1..000000000 --- a/crates/brk_computer/src/internal/multi/value/height/sum.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! Value type for Sum pattern from Height. - -use brk_error::Result; -use brk_traversable::Traversable; -use brk_types::{Bitcoin, Dollars, Height, Sats, Version}; -use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, PcoVec}; - -use crate::{ - ComputeIndexes, indexes, - internal::{ComputedBlockSum, LazyBlockSum, SatsToBitcoin}, - price, - traits::ComputeFromBitcoin, -}; - -#[derive(Clone, Traversable)] -pub struct ValueBlockSum { - pub sats: ComputedBlockSum, - pub bitcoin: LazyBlockSum, - pub dollars: Option>, -} - -const VERSION: Version = Version::ZERO; - -impl ValueBlockSum { - pub fn forced_import( - db: &Database, - name: &str, - version: Version, - indexes: &indexes::Vecs, - compute_dollars: bool, - ) -> Result { - let v = version + VERSION; - - let sats = ComputedBlockSum::forced_import(db, name, v, indexes)?; - - let bitcoin = LazyBlockSum::from_computed::( - &format!("{name}_btc"), - v, - sats.height.boxed_clone(), - &sats, - ); - - let dollars = compute_dollars - .then(|| ComputedBlockSum::forced_import(db, &format!("{name}_usd"), v, indexes)) - .transpose()?; - - Ok(Self { - sats, - bitcoin, - dollars, - }) - } - - pub fn compute_all( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - mut compute: F, - ) -> Result<()> - where - F: FnMut(&mut EagerVec>) -> Result<()>, - { - // Compute sats (closure receives &mut height vec) - self.sats - .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; - - // Compute dollars from bitcoin and price (if enabled) - if let (Some(dollars), Some(price)) = (self.dollars.as_mut(), price) { - let height_to_bitcoin = &self.bitcoin.height; - let height_to_price_close = &price.usd.split.close.height; - - dollars.compute_all(indexes, starting_indexes, exit, |v| { - v.compute_from_bitcoin( - starting_indexes.height, - height_to_bitcoin, - height_to_price_close, - exit, - ) - })?; - } - - Ok(()) - } -} diff --git a/crates/brk_computer/src/internal/multi/value/height/sum_cum.rs b/crates/brk_computer/src/internal/multi/value/height/sum_cum.rs deleted file mode 100644 index 08c5c08f2..000000000 --- a/crates/brk_computer/src/internal/multi/value/height/sum_cum.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! Value type for SumCum pattern from Height. - -use brk_error::Result; -use brk_traversable::Traversable; -use brk_types::{Bitcoin, Dollars, Height, Sats, Version}; -use vecdb::{Database, EagerVec, Exit, IterableCloneableVec, PcoVec}; - -use crate::{ - ComputeIndexes, indexes, - internal::{ComputedBlockSumCum, LazyBlockSumCum, SatsToBitcoin}, - price, - traits::ComputeFromBitcoin, -}; -use vecdb::IterableVec; - -#[derive(Clone, Traversable)] -pub struct ValueBlockSumCum { - pub sats: ComputedBlockSumCum, - pub bitcoin: LazyBlockSumCum, - pub dollars: Option>, -} - -const VERSION: Version = Version::ZERO; - -impl ValueBlockSumCum { - pub fn forced_import( - db: &Database, - name: &str, - version: Version, - indexes: &indexes::Vecs, - compute_dollars: bool, - ) -> Result { - let v = version + VERSION; - - let sats = ComputedBlockSumCum::forced_import(db, name, v, indexes)?; - - let bitcoin = LazyBlockSumCum::from_computed::( - &format!("{name}_btc"), - v, - sats.height.boxed_clone(), - &sats, - ); - - let dollars = compute_dollars - .then(|| ComputedBlockSumCum::forced_import(db, &format!("{name}_usd"), v, indexes)) - .transpose()?; - - Ok(Self { - sats, - bitcoin, - dollars, - }) - } - - pub fn compute_all( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - mut compute: F, - ) -> Result<()> - where - F: FnMut(&mut EagerVec>) -> Result<()>, - { - // Compute sats (closure receives &mut height vec) - self.sats - .compute_all(indexes, starting_indexes, exit, |v| compute(v))?; - - self.compute_dollars(indexes, price, starting_indexes, exit) - } - - /// Derive from an external height source (e.g., a LazyVec). - pub fn derive_from( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - source: &impl IterableVec, - exit: &Exit, - ) -> Result<()> { - // Derive sats from source - self.sats - .derive_from(indexes, starting_indexes, source, exit)?; - - self.compute_dollars(indexes, price, starting_indexes, exit) - } - - /// Compute rest (derived indexes) from already-computed height. - pub fn compute_rest( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - ) -> Result<()> { - self.sats.compute_rest(indexes, starting_indexes, exit)?; - self.compute_dollars(indexes, price, starting_indexes, exit) - } - - fn compute_dollars( - &mut self, - indexes: &indexes::Vecs, - price: Option<&price::Vecs>, - starting_indexes: &ComputeIndexes, - exit: &Exit, - ) -> Result<()> { - // Compute dollars from bitcoin and price (if enabled) - if let (Some(dollars), Some(price)) = (self.dollars.as_mut(), price) { - let height_to_bitcoin = &self.bitcoin.height; - let height_to_price_close = &price.usd.split.close.height; - - dollars.compute_all(indexes, starting_indexes, exit, |v| { - v.compute_from_bitcoin( - starting_indexes.height, - height_to_bitcoin, - height_to_price_close, - exit, - ) - })?; - } - - Ok(()) - } -} diff --git a/crates/brk_computer/src/internal/multi/value/mod.rs b/crates/brk_computer/src/internal/multi/value/mod.rs deleted file mode 100644 index 24adb7641..000000000 --- a/crates/brk_computer/src/internal/multi/value/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -mod date; -mod derived_height; -mod height; -mod tx; - -pub use date::*; -pub use derived_height::*; -pub use height::*; -pub use tx::*; diff --git a/crates/brk_computer/src/internal/multi/value/tx/dollars.rs b/crates/brk_computer/src/internal/multi/value/tx/dollars.rs deleted file mode 100644 index cf7fc514d..000000000 --- a/crates/brk_computer/src/internal/multi/value/tx/dollars.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Dollars from TxIndex with lazy txindex and eager aggregates. - -use brk_error::Result; -use brk_indexer::Indexer; -use brk_traversable::Traversable; -use brk_types::{ - Bitcoin, Close, DateIndex, DifficultyEpoch, Dollars, Height, Sats, TxIndex, Version, -}; -use derive_more::{Deref, DerefMut}; -use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, LazyVecFrom3}; - -use crate::{ - ComputeIndexes, indexes, - internal::{LazyPeriodsFull, Full, LazyFull, Stats}, -}; - -/// Lazy dollars at TxIndex: `sats * price[height]` -pub type LazyDollarsTxIndex = - LazyVecFrom3>; - -/// Dollars with lazy txindex field and eager height/dateindex aggregates. -#[derive(Clone, Deref, DerefMut, Traversable)] -#[traversable(merge)] -pub struct ValueDollarsTxFull { - #[traversable(skip)] - pub txindex: LazyDollarsTxIndex, - pub height: Full, - pub difficultyepoch: LazyFull, - pub dateindex: Stats, - #[deref] - #[deref_mut] - pub dates: LazyPeriodsFull, -} - -const VERSION: Version = Version::ZERO; - -impl ValueDollarsTxFull { - pub fn forced_import( - db: &Database, - name: &str, - version: Version, - indexes: &indexes::Vecs, - sats_txindex: IterableBoxedVec, - txindex_to_height: IterableBoxedVec, - height_to_price: IterableBoxedVec>, - ) -> Result { - let v = version + VERSION; - - let txindex = - create_lazy_txindex(name, v, sats_txindex, txindex_to_height, height_to_price); - let height = Full::forced_import(db, name, v)?; - let dateindex = Stats::forced_import(db, name, v)?; - - let difficultyepoch = - LazyFull::::from_stats_aggregate( - name, - v, - height.distribution.average.0.boxed_clone(), - height.distribution.minmax.min.0.boxed_clone(), - height.distribution.minmax.max.0.boxed_clone(), - height.sum_cum.sum.0.boxed_clone(), - height.sum_cum.cumulative.0.boxed_clone(), - indexes.difficultyepoch.identity.boxed_clone(), - ); - - let dates = LazyPeriodsFull::from_sources( - name, - v, - dateindex.average.0.boxed_clone(), - dateindex.minmax.min.0.boxed_clone(), - dateindex.minmax.max.0.boxed_clone(), - dateindex.sum_cum.sum.0.boxed_clone(), - dateindex.sum_cum.cumulative.0.boxed_clone(), - indexes, - ); - - Ok(Self { - txindex, - height, - difficultyepoch, - dateindex, - dates, - }) - } - - pub fn derive_from( - &mut self, - indexer: &Indexer, - indexes: &indexes::Vecs, - starting_indexes: &ComputeIndexes, - exit: &Exit, - ) -> Result<()> { - self.height.compute( - starting_indexes.height, - &self.txindex, - &indexer.vecs.transactions.first_txindex, - &indexes.height.txindex_count, - exit, - )?; - - self.dateindex.compute( - starting_indexes.dateindex, - &self.height.distribution.average.0, - &indexes.dateindex.first_height, - &indexes.dateindex.height_count, - exit, - )?; - - Ok(()) - } -} - -fn create_lazy_txindex( - name: &str, - version: Version, - sats_txindex: IterableBoxedVec, - txindex_to_height: IterableBoxedVec, - height_to_price: IterableBoxedVec>, -) -> LazyDollarsTxIndex { - LazyVecFrom3::init( - &format!("{name}_txindex"), - version, - sats_txindex, - txindex_to_height, - height_to_price, - |txindex, sats_iter, height_iter, price_iter| { - sats_iter.get(txindex).and_then(|sats| { - height_iter.get(txindex).and_then(|height| { - price_iter - .get(height) - .map(|close| *close * Bitcoin::from(sats)) - }) - }) - }, - ) -} diff --git a/crates/brk_computer/src/internal/multi/value/tx/mod.rs b/crates/brk_computer/src/internal/multi/value/tx/mod.rs deleted file mode 100644 index e1ec076b8..000000000 --- a/crates/brk_computer/src/internal/multi/value/tx/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -mod derived_full; -mod dollars; -mod full; - -pub use derived_full::*; -pub use dollars::*; -pub use full::*; diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_difficultyepoch.rs b/crates/brk_computer/src/internal/single/difficultyepoch/lazy_value.rs similarity index 79% rename from crates/brk_computer/src/internal/multi/value/height/lazy_difficultyepoch.rs rename to crates/brk_computer/src/internal/single/difficultyepoch/lazy_value.rs index c1a27b45f..d9fade809 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_difficultyepoch.rs +++ b/crates/brk_computer/src/internal/single/difficultyepoch/lazy_value.rs @@ -6,25 +6,37 @@ use brk_traversable::Traversable; use brk_types::{Bitcoin, Close, DifficultyEpoch, Dollars, Height, Sats, Version}; -use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom1, LazyVecFrom2, UnaryTransform}; +use vecdb::{ + BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom1, LazyVecFrom2, + UnaryTransform, +}; -use crate::internal::{ClosePriceTimesSats, LazyLast, SatsToBitcoin}; +use crate::internal::{ClosePriceTimesSats, LazyLast, SatsToBitcoin, ValueFromHeightLast}; use crate::price; const VERSION: Version = Version::ZERO; /// Lazy value type at difficultyepoch level - computed from height sats + price. /// -/// Use this when the source only has height-indexed sats (e.g., ValueHeightDateLast). +/// Use this when the source only has height-indexed sats (e.g., ValueFromHeightAndDateLast). /// Dollars are computed via price × sats binary transform. #[derive(Clone, Traversable)] -pub struct LazyValueDifficultyEpochFromHeight { +pub struct LazyValueDifficultyEpoch { pub sats: LazyLast, pub bitcoin: LazyVecFrom1, - pub dollars: Option, DifficultyEpoch, Sats>>, + pub dollars: Option< + LazyVecFrom2< + DifficultyEpoch, + Dollars, + DifficultyEpoch, + Close, + DifficultyEpoch, + Sats, + >, + >, } -impl LazyValueDifficultyEpochFromHeight { +impl LazyValueDifficultyEpoch { /// Create from height sats source and difficultyepoch identity. /// Bitcoin is derived from sats. Dollars are computed from price × sats. pub fn from_height_source( @@ -53,7 +65,11 @@ impl LazyValueDifficultyEpochFromHeight { ) }); - Self { sats, bitcoin, dollars } + Self { + sats, + bitcoin, + dollars, + } } } @@ -65,17 +81,26 @@ impl LazyValueDifficultyEpochFromHeight { pub struct LazyTransformedValueDifficultyEpoch { pub sats: LazyVecFrom1, pub bitcoin: LazyVecFrom1, - pub dollars: Option, DifficultyEpoch, Sats>>, + pub dollars: Option< + LazyVecFrom2< + DifficultyEpoch, + Dollars, + DifficultyEpoch, + Close, + DifficultyEpoch, + Sats, + >, + >, } impl LazyTransformedValueDifficultyEpoch { - /// Create transformed difficultyepoch values from a ValueBlockLast source. + /// Create transformed difficultyepoch values from a ValueFromHeightLast source. /// SatsTransform is applied to the source's difficultyepoch sats. /// BitcoinTransform converts source sats to bitcoin (should combine sats transform + conversion). /// Dollars are computed from price × transformed sats. pub fn from_block_source( name: &str, - source: &super::ValueBlockLast, + source: &ValueFromHeightLast, price: Option<&price::Vecs>, version: Version, ) -> Self @@ -107,6 +132,10 @@ impl LazyTransformedValueDifficultyEpoch { ) }); - Self { sats, bitcoin, dollars } + Self { + sats, + bitcoin, + dollars, + } } } diff --git a/crates/brk_computer/src/internal/single/difficultyepoch/mod.rs b/crates/brk_computer/src/internal/single/difficultyepoch/mod.rs new file mode 100644 index 000000000..66af87422 --- /dev/null +++ b/crates/brk_computer/src/internal/single/difficultyepoch/mod.rs @@ -0,0 +1,3 @@ +mod lazy_value; + +pub use lazy_value::*; diff --git a/crates/brk_computer/src/internal/single/group/distribution.rs b/crates/brk_computer/src/internal/single/group/distribution.rs index bace3b4a3..a8d234221 100644 --- a/crates/brk_computer/src/internal/single/group/distribution.rs +++ b/crates/brk_computer/src/internal/single/group/distribution.rs @@ -1,27 +1,25 @@ use brk_error::Result; use brk_traversable::Traversable; use schemars::JsonSchema; -use vecdb::{AnyVec, Database, Exit, IterableVec, VecIndex, VecValue, Version}; +use vecdb::{AnyVec, Database, Exit, IterableBoxedVec, IterableVec, VecIndex, VecValue, Version}; -use crate::internal::{AverageVec, ComputedVecValue}; +use crate::internal::{AverageVec, ComputedVecValue, MaxVec, MinVec}; -use super::{MinMax, Percentiles}; +use super::{MinMaxAverage, Percentiles}; /// Distribution stats (average + minmax + percentiles) #[derive(Clone, Traversable)] pub struct Distribution { #[traversable(flatten)] - pub average: AverageVec, + pub min_max_average: MinMaxAverage, #[traversable(flatten)] - pub minmax: MinMax, pub percentiles: Percentiles, } impl Distribution { pub fn forced_import(db: &Database, name: &str, version: Version) -> Result { Ok(Self { - average: AverageVec::forced_import(db, name, version)?, - minmax: MinMax::forced_import(db, name, version)?, + min_max_average: MinMaxAverage::forced_import(db, name, version)?, percentiles: Percentiles::forced_import(db, name, version)?, }) } @@ -37,6 +35,24 @@ impl Distribution { count_indexes: &impl IterableVec, exit: &Exit, ) -> Result<()> + where + A: VecIndex + VecValue + brk_types::CheckedSub, + { + self.compute_with_skip(max_from, source, first_indexes, count_indexes, exit, 0) + } + + /// Compute distribution stats, skipping first N items from all calculations. + /// + /// Use `skip_count: 1` to exclude coinbase transactions from fee/feerate stats. + pub fn compute_with_skip( + &mut self, + max_from: I, + source: &impl IterableVec, + first_indexes: &impl IterableVec, + count_indexes: &impl IterableVec, + exit: &Exit, + skip_count: usize, + ) -> Result<()> where A: VecIndex + VecValue + brk_types::CheckedSub, { @@ -46,11 +62,12 @@ impl Distribution { first_indexes, count_indexes, exit, + skip_count, None, // first None, // last - Some(&mut self.minmax.min.0), - Some(&mut self.minmax.max.0), - Some(&mut self.average.0), + Some(&mut self.min_max_average.minmax.min.0), + Some(&mut self.min_max_average.minmax.max.0), + Some(&mut self.min_max_average.average.0), None, // sum None, // cumulative Some(&mut self.percentiles.median.0), @@ -62,11 +79,8 @@ impl Distribution { } pub fn len(&self) -> usize { - self.average - .0 + self.min_max_average .len() - .min(self.minmax.min.0.len()) - .min(self.minmax.max.0.len()) .min(self.percentiles.pct10.0.len()) .min(self.percentiles.pct25.0.len()) .min(self.percentiles.median.0.len()) @@ -77,4 +91,30 @@ impl Distribution { pub fn starting_index(&self, max_from: I) -> I { max_from.min(I::from(self.len())) } + + // Accessors + pub fn average(&self) -> &AverageVec { + &self.min_max_average.average + } + + pub fn min(&self) -> &MinVec { + self.min_max_average.min() + } + + pub fn max(&self) -> &MaxVec { + self.min_max_average.max() + } + + // Boxed accessors + pub fn boxed_average(&self) -> IterableBoxedVec { + self.min_max_average.boxed_average() + } + + pub fn boxed_min(&self) -> IterableBoxedVec { + self.min_max_average.boxed_min() + } + + pub fn boxed_max(&self) -> IterableBoxedVec { + self.min_max_average.boxed_max() + } } diff --git a/crates/brk_computer/src/internal/single/group/full.rs b/crates/brk_computer/src/internal/single/group/full.rs index 42da39b31..e6491bb92 100644 --- a/crates/brk_computer/src/internal/single/group/full.rs +++ b/crates/brk_computer/src/internal/single/group/full.rs @@ -1,9 +1,9 @@ use brk_error::Result; use brk_traversable::Traversable; use schemars::JsonSchema; -use vecdb::{Database, Exit, IterableVec, VecIndex, VecValue, Version}; +use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec, VecIndex, VecValue, Version}; -use crate::internal::ComputedVecValue; +use crate::internal::{AverageVec, ComputedVecValue, CumulativeVec, MaxVec, MinVec, SumVec}; use super::{Distribution, SumCum}; @@ -36,6 +36,24 @@ impl Full { count_indexes: &impl IterableVec, exit: &Exit, ) -> Result<()> + where + A: VecIndex + VecValue + brk_types::CheckedSub, + { + self.compute_with_skip(max_from, source, first_indexes, count_indexes, exit, 0) + } + + /// Compute all stats, skipping first N items from all calculations. + /// + /// Use `skip_count: 1` to exclude coinbase transactions from fee/feerate stats. + pub fn compute_with_skip( + &mut self, + max_from: I, + source: &impl IterableVec, + first_indexes: &impl IterableVec, + count_indexes: &impl IterableVec, + exit: &Exit, + skip_count: usize, + ) -> Result<()> where A: VecIndex + VecValue + brk_types::CheckedSub, { @@ -45,11 +63,12 @@ impl Full { first_indexes, count_indexes, exit, + skip_count, None, // first None, // last - Some(&mut self.distribution.minmax.min.0), - Some(&mut self.distribution.minmax.max.0), - Some(&mut self.distribution.average.0), + Some(&mut self.distribution.min_max_average.minmax.min.0), + Some(&mut self.distribution.min_max_average.minmax.max.0), + Some(&mut self.distribution.min_max_average.average.0), Some(&mut self.sum_cum.sum.0), Some(&mut self.sum_cum.cumulative.0), Some(&mut self.distribution.percentiles.median.0), @@ -91,18 +110,60 @@ impl Full { // Source vecs None, // first not in Full None, // last not in Full - Some(&source.distribution.minmax.min.0), - Some(&source.distribution.minmax.max.0), - Some(&source.distribution.average.0), + Some(&source.distribution.min_max_average.minmax.min.0), + Some(&source.distribution.min_max_average.minmax.max.0), + Some(&source.distribution.min_max_average.average.0), Some(&source.sum_cum.sum.0), // Target vecs None, // first None, // last - Some(&mut self.distribution.minmax.min.0), - Some(&mut self.distribution.minmax.max.0), - Some(&mut self.distribution.average.0), + Some(&mut self.distribution.min_max_average.minmax.min.0), + Some(&mut self.distribution.min_max_average.minmax.max.0), + Some(&mut self.distribution.min_max_average.average.0), Some(&mut self.sum_cum.sum.0), Some(&mut self.sum_cum.cumulative.0), ) } + + // Accessors + pub fn average(&self) -> &AverageVec { + self.distribution.average() + } + + pub fn min(&self) -> &MinVec { + self.distribution.min() + } + + pub fn max(&self) -> &MaxVec { + self.distribution.max() + } + + pub fn sum(&self) -> &SumVec { + &self.sum_cum.sum + } + + pub fn cumulative(&self) -> &CumulativeVec { + &self.sum_cum.cumulative + } + + // Boxed accessors + pub fn boxed_average(&self) -> IterableBoxedVec { + self.distribution.boxed_average() + } + + pub fn boxed_min(&self) -> IterableBoxedVec { + self.distribution.boxed_min() + } + + pub fn boxed_max(&self) -> IterableBoxedVec { + self.distribution.boxed_max() + } + + pub fn boxed_sum(&self) -> IterableBoxedVec { + self.sum_cum.sum.0.boxed_clone() + } + + pub fn boxed_cumulative(&self) -> IterableBoxedVec { + self.sum_cum.cumulative.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/group/min_max_average.rs b/crates/brk_computer/src/internal/single/group/min_max_average.rs index fd2c74d00..8af45dc76 100644 --- a/crates/brk_computer/src/internal/single/group/min_max_average.rs +++ b/crates/brk_computer/src/internal/single/group/min_max_average.rs @@ -1,9 +1,9 @@ use brk_error::Result; use brk_traversable::Traversable; use schemars::JsonSchema; -use vecdb::{AnyVec, Database, Exit, IterableVec, VecIndex, VecValue, Version}; +use vecdb::{AnyVec, Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec, VecIndex, VecValue, Version}; -use crate::internal::{AverageVec, ComputedVecValue}; +use crate::internal::{AverageVec, ComputedVecValue, MaxVec, MinVec}; use super::MinMax; @@ -41,6 +41,7 @@ impl MinMaxAverage { first_indexes, count_indexes, exit, + 0, // min_skip_count None, // first None, // last Some(&mut self.minmax.min.0), @@ -102,4 +103,26 @@ impl MinMaxAverage { pub fn starting_index(&self, max_from: I) -> I { max_from.min(I::from(self.len())) } + + // Accessors + pub fn min(&self) -> &MinVec { + &self.minmax.min + } + + pub fn max(&self) -> &MaxVec { + &self.minmax.max + } + + // Boxed accessors + pub fn boxed_average(&self) -> IterableBoxedVec { + self.average.0.boxed_clone() + } + + pub fn boxed_min(&self) -> IterableBoxedVec { + self.minmax.min.0.boxed_clone() + } + + pub fn boxed_max(&self) -> IterableBoxedVec { + self.minmax.max.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/group/percentiles.rs b/crates/brk_computer/src/internal/single/group/percentiles.rs index 55d9ae58c..89462fe97 100644 --- a/crates/brk_computer/src/internal/single/group/percentiles.rs +++ b/crates/brk_computer/src/internal/single/group/percentiles.rs @@ -1,7 +1,7 @@ use brk_error::Result; use brk_traversable::Traversable; use schemars::JsonSchema; -use vecdb::{Database, VecIndex, Version}; +use vecdb::{Database, IterableBoxedVec, IterableCloneableVec, VecIndex, Version}; use crate::internal::{ComputedVecValue, MedianVec, Pct10Vec, Pct25Vec, Pct75Vec, Pct90Vec}; @@ -25,4 +25,25 @@ impl Percentiles { pct90: Pct90Vec::forced_import(db, name, version)?, }) } + + // Boxed accessors + pub fn boxed_pct10(&self) -> IterableBoxedVec { + self.pct10.0.boxed_clone() + } + + pub fn boxed_pct25(&self) -> IterableBoxedVec { + self.pct25.0.boxed_clone() + } + + pub fn boxed_median(&self) -> IterableBoxedVec { + self.median.0.boxed_clone() + } + + pub fn boxed_pct75(&self) -> IterableBoxedVec { + self.pct75.0.boxed_clone() + } + + pub fn boxed_pct90(&self) -> IterableBoxedVec { + self.pct90.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/group/stats.rs b/crates/brk_computer/src/internal/single/group/stats.rs index 00cfba581..072eb7cea 100644 --- a/crates/brk_computer/src/internal/single/group/stats.rs +++ b/crates/brk_computer/src/internal/single/group/stats.rs @@ -1,11 +1,11 @@ use brk_error::Result; use brk_traversable::Traversable; use schemars::JsonSchema; -use vecdb::{AnyVec, Database, Exit, IterableVec, VecIndex, VecValue, Version}; +use vecdb::{Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec, VecIndex, VecValue, Version}; -use crate::internal::{AverageVec, ComputedVecValue}; +use crate::internal::{AverageVec, ComputedVecValue, CumulativeVec, MaxVec, MinVec, SumVec}; -use super::{MinMax, SumCum}; +use super::{MinMaxAverage, SumCum}; /// Sum + Cumulative + Average + Min + Max. Like `Full` but without percentiles. #[derive(Clone, Traversable)] @@ -13,17 +13,14 @@ pub struct Stats { #[traversable(flatten)] pub sum_cum: SumCum, #[traversable(flatten)] - pub average: AverageVec, - #[traversable(flatten)] - pub minmax: MinMax, + pub min_max_average: MinMaxAverage, } impl Stats { pub fn forced_import(db: &Database, name: &str, version: Version) -> Result { Ok(Self { sum_cum: SumCum::forced_import(db, name, version)?, - average: AverageVec::forced_import(db, name, version)?, - minmax: MinMax::forced_import(db, name, version)?, + min_max_average: MinMaxAverage::forced_import(db, name, version)?, }) } @@ -45,11 +42,12 @@ impl Stats { first_indexes, count_indexes, exit, + 0, // min_skip_count None, // first None, // last - Some(&mut self.minmax.min.0), - Some(&mut self.minmax.max.0), - Some(&mut self.average.0), + Some(&mut self.min_max_average.minmax.min.0), + Some(&mut self.min_max_average.minmax.max.0), + Some(&mut self.min_max_average.average.0), Some(&mut self.sum_cum.sum.0), Some(&mut self.sum_cum.cumulative.0), None, // median @@ -61,14 +59,52 @@ impl Stats { } pub fn len(&self) -> usize { - self.sum_cum - .len() - .min(self.average.0.len()) - .min(self.minmax.min.0.len()) - .min(self.minmax.max.0.len()) + self.sum_cum.len().min(self.min_max_average.len()) } pub fn starting_index(&self, max_from: I) -> I { max_from.min(I::from(self.len())) } + + // Accessors + pub fn average(&self) -> &AverageVec { + &self.min_max_average.average + } + + pub fn min(&self) -> &MinVec { + self.min_max_average.min() + } + + pub fn max(&self) -> &MaxVec { + self.min_max_average.max() + } + + pub fn sum(&self) -> &SumVec { + &self.sum_cum.sum + } + + pub fn cumulative(&self) -> &CumulativeVec { + &self.sum_cum.cumulative + } + + // Boxed accessors + pub fn boxed_average(&self) -> IterableBoxedVec { + self.min_max_average.boxed_average() + } + + pub fn boxed_min(&self) -> IterableBoxedVec { + self.min_max_average.boxed_min() + } + + pub fn boxed_max(&self) -> IterableBoxedVec { + self.min_max_average.boxed_max() + } + + pub fn boxed_sum(&self) -> IterableBoxedVec { + self.sum_cum.sum.0.boxed_clone() + } + + pub fn boxed_cumulative(&self) -> IterableBoxedVec { + self.sum_cum.cumulative.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/group/sum_cum.rs b/crates/brk_computer/src/internal/single/group/sum_cum.rs index 313ebb100..418add0da 100644 --- a/crates/brk_computer/src/internal/single/group/sum_cum.rs +++ b/crates/brk_computer/src/internal/single/group/sum_cum.rs @@ -1,7 +1,7 @@ use brk_error::Result; use brk_traversable::Traversable; use schemars::JsonSchema; -use vecdb::{AnyVec, Database, Exit, IterableVec, VecIndex, VecValue, Version}; +use vecdb::{AnyVec, Database, Exit, IterableBoxedVec, IterableCloneableVec, IterableVec, VecIndex, VecValue, Version}; use crate::internal::{ComputedVecValue, CumulativeVec, SumVec}; @@ -48,6 +48,7 @@ impl SumCum { first_indexes, count_indexes, exit, + 0, // min_skip_count None, // first None, // last None, // min @@ -115,4 +116,13 @@ impl SumCum { Some(&mut self.cumulative.0), ) } + + // Boxed accessors + pub fn boxed_sum(&self) -> IterableBoxedVec { + self.sum.0.boxed_clone() + } + + pub fn boxed_cumulative(&self) -> IterableBoxedVec { + self.cumulative.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_derived.rs b/crates/brk_computer/src/internal/single/height/derived_values.rs similarity index 94% rename from crates/brk_computer/src/internal/multi/value/height/lazy_derived.rs rename to crates/brk_computer/src/internal/single/height/derived_values.rs index dc99bba59..de08a29de 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_derived.rs +++ b/crates/brk_computer/src/internal/single/height/derived_values.rs @@ -5,14 +5,14 @@ use vecdb::{IterableBoxedVec, LazyVecFrom1, LazyVecFrom2}; use crate::internal::{ClosePriceTimesSats, SatsToBitcoin}; #[derive(Clone, Traversable)] -pub struct LazyDerivedBlockValue { +pub struct LazyDerivedValuesHeight { pub bitcoin: LazyVecFrom1, pub dollars: Option, Height, Sats>>, } const VERSION: Version = Version::ZERO; -impl LazyDerivedBlockValue { +impl LazyDerivedValuesHeight { pub fn from_source( name: &str, sats_source: IterableBoxedVec, diff --git a/crates/brk_computer/src/internal/multi/value/height/lazy_height.rs b/crates/brk_computer/src/internal/single/height/lazy_value.rs similarity index 90% rename from crates/brk_computer/src/internal/multi/value/height/lazy_height.rs rename to crates/brk_computer/src/internal/single/height/lazy_value.rs index d10427a80..b222f50f7 100644 --- a/crates/brk_computer/src/internal/multi/value/height/lazy_height.rs +++ b/crates/brk_computer/src/internal/single/height/lazy_value.rs @@ -4,7 +4,7 @@ use brk_traversable::Traversable; use brk_types::{Bitcoin, Dollars, Height, Sats, Version}; use vecdb::{IterableCloneableVec, LazyVecFrom1, UnaryTransform}; -use crate::internal::SatsToBitcoin; +use crate::internal::{SatsToBitcoin, ValueFromHeightLast}; const VERSION: Version = Version::ZERO; @@ -12,16 +12,16 @@ const VERSION: Version = Version::ZERO; /// /// All fields are lazy transforms from existing sources - no storage. #[derive(Clone, Traversable)] -pub struct LazyValueBlockHeight { +pub struct LazyValueHeight { pub sats: LazyVecFrom1, pub bitcoin: LazyVecFrom1, pub dollars: Option>, } -impl LazyValueBlockHeight { +impl LazyValueHeight { pub fn from_block_source( name: &str, - source: &super::ValueBlockLast, + source: &ValueFromHeightLast, version: Version, ) -> Self where diff --git a/crates/brk_computer/src/internal/single/height/mod.rs b/crates/brk_computer/src/internal/single/height/mod.rs new file mode 100644 index 000000000..9e2522acd --- /dev/null +++ b/crates/brk_computer/src/internal/single/height/mod.rs @@ -0,0 +1,7 @@ +mod derived_values; +mod lazy_value; +mod value; + +pub use derived_values::*; +pub use lazy_value::*; +pub use value::*; diff --git a/crates/brk_computer/src/internal/single/value/height.rs b/crates/brk_computer/src/internal/single/height/value.rs similarity index 96% rename from crates/brk_computer/src/internal/single/value/height.rs rename to crates/brk_computer/src/internal/single/height/value.rs index f1d5ce006..07a2bd765 100644 --- a/crates/brk_computer/src/internal/single/value/height.rs +++ b/crates/brk_computer/src/internal/single/height/value.rs @@ -13,13 +13,13 @@ const VERSION: Version = Version::ZERO; /// /// Used for metrics that are computed per height but don't need index aggregations. #[derive(Clone, Traversable)] -pub struct ValueBlockHeight { +pub struct ValueHeight { pub sats: EagerVec>, pub bitcoin: LazyVecFrom1, pub dollars: Option>>, } -impl ValueBlockHeight { +impl ValueHeight { pub fn forced_import( db: &Database, name: &str, diff --git a/crates/brk_computer/src/internal/single/lazy/max.rs b/crates/brk_computer/src/internal/single/lazy/max.rs index 0da0b25ef..db5f044cf 100644 --- a/crates/brk_computer/src/internal/single/lazy/max.rs +++ b/crates/brk_computer/src/internal/single/lazy/max.rs @@ -31,9 +31,28 @@ where version: Version, source: IterableBoxedVec, len_source: IterableBoxedVec, + ) -> Self { + Self::from_source_inner(&format!("{name}_max"), version, source, len_source) + } + + /// Create from source without adding _max suffix. + pub fn from_source_raw( + name: &str, + version: Version, + source: IterableBoxedVec, + len_source: IterableBoxedVec, + ) -> Self { + Self::from_source_inner(name, version, source, len_source) + } + + fn from_source_inner( + name: &str, + version: Version, + source: IterableBoxedVec, + len_source: IterableBoxedVec, ) -> Self { Self(LazyVecFrom2::init( - &format!("{name}_max"), + name, version + VERSION, source, len_source, diff --git a/crates/brk_computer/src/internal/single/lazy/min.rs b/crates/brk_computer/src/internal/single/lazy/min.rs index bbf8491dd..dd530f8a5 100644 --- a/crates/brk_computer/src/internal/single/lazy/min.rs +++ b/crates/brk_computer/src/internal/single/lazy/min.rs @@ -31,9 +31,28 @@ where version: Version, source: IterableBoxedVec, len_source: IterableBoxedVec, + ) -> Self { + Self::from_source_inner(&format!("{name}_min"), version, source, len_source) + } + + /// Create from source without adding _min suffix. + pub fn from_source_raw( + name: &str, + version: Version, + source: IterableBoxedVec, + len_source: IterableBoxedVec, + ) -> Self { + Self::from_source_inner(name, version, source, len_source) + } + + fn from_source_inner( + name: &str, + version: Version, + source: IterableBoxedVec, + len_source: IterableBoxedVec, ) -> Self { Self(LazyVecFrom2::init( - &format!("{name}_min"), + name, version + VERSION, source, len_source, diff --git a/crates/brk_computer/src/internal/single/lazy_transform/binary_full.rs b/crates/brk_computer/src/internal/single/lazy_transform/binary_full.rs new file mode 100644 index 000000000..750027017 --- /dev/null +++ b/crates/brk_computer/src/internal/single/lazy_transform/binary_full.rs @@ -0,0 +1,101 @@ +//! Lazy binary transform for Full (without cumulative). +//! +//! Used for USD conversion where `usd = sats * price[height]`. +//! Cumulative cannot be lazy because `cum_usd ≠ cum_sats * price` - +//! it must be computed by summing historical `sum * price` values. + +use brk_traversable::Traversable; +use brk_types::Version; +use schemars::JsonSchema; +use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2, VecIndex}; + +use crate::internal::{ComputedVecValue, Full}; + +use super::LazyBinaryPercentiles; + +/// Lazy binary transform for Full stats (excluding cumulative). +/// +/// For USD conversion: each stat is computed as `sats_stat * price`. +/// Cumulative is excluded because it requires summing historical values. +#[derive(Clone, Traversable)] +pub struct LazyBinaryTransformFull +where + I: VecIndex, + T: ComputedVecValue + PartialOrd + JsonSchema, + S1T: ComputedVecValue, + S2T: ComputedVecValue, +{ + pub average: LazyVecFrom2, + pub min: LazyVecFrom2, + pub max: LazyVecFrom2, + #[traversable(flatten)] + pub percentiles: LazyBinaryPercentiles, + pub sum: LazyVecFrom2, +} + +impl LazyBinaryTransformFull +where + I: VecIndex, + T: ComputedVecValue + JsonSchema + 'static, + S1T: ComputedVecValue + JsonSchema, + S2T: ComputedVecValue + JsonSchema, +{ + /// Create from Full source and a second source (e.g., price). + /// + /// The transform F is applied as `F(source1_stat, source2)` for each stat. + pub fn from_full_and_source>( + name: &str, + version: Version, + source1: &Full, + source2: IterableBoxedVec, + ) -> Self { + Self { + average: LazyVecFrom2::transformed::( + &format!("{name}_average"), + version, + source1.boxed_average(), + source2.clone(), + ), + min: LazyVecFrom2::transformed::( + &format!("{name}_min"), + version, + source1.boxed_min(), + source2.clone(), + ), + max: LazyVecFrom2::transformed::( + &format!("{name}_max"), + version, + source1.boxed_max(), + source2.clone(), + ), + percentiles: LazyBinaryPercentiles::from_percentiles::( + name, + version, + &source1.distribution.percentiles, + source2.clone(), + ), + sum: LazyVecFrom2::transformed::( + &format!("{name}_sum"), + version, + source1.boxed_sum(), + source2, + ), + } + } + + pub fn boxed_average(&self) -> IterableBoxedVec { + self.average.boxed_clone() + } + + pub fn boxed_min(&self) -> IterableBoxedVec { + self.min.boxed_clone() + } + + pub fn boxed_max(&self) -> IterableBoxedVec { + self.max.boxed_clone() + } + + pub fn boxed_sum(&self) -> IterableBoxedVec { + self.sum.boxed_clone() + } +} diff --git a/crates/brk_computer/src/internal/single/lazy_transform/binary_percentiles.rs b/crates/brk_computer/src/internal/single/lazy_transform/binary_percentiles.rs new file mode 100644 index 000000000..7f7e4f395 --- /dev/null +++ b/crates/brk_computer/src/internal/single/lazy_transform/binary_percentiles.rs @@ -0,0 +1,71 @@ +//! Lazy binary transform for Percentiles. + +use brk_traversable::Traversable; +use brk_types::Version; +use schemars::JsonSchema; +use vecdb::{BinaryTransform, IterableBoxedVec, LazyVecFrom2, VecIndex}; + +use crate::internal::{ComputedVecValue, Percentiles}; + +#[derive(Clone, Traversable)] +pub struct LazyBinaryPercentiles +where + I: VecIndex, + T: ComputedVecValue + PartialOrd + JsonSchema, + S1T: ComputedVecValue, + S2T: ComputedVecValue, +{ + pub pct10: LazyVecFrom2, + pub pct25: LazyVecFrom2, + pub median: LazyVecFrom2, + pub pct75: LazyVecFrom2, + pub pct90: LazyVecFrom2, +} + +impl LazyBinaryPercentiles +where + I: VecIndex, + T: ComputedVecValue + JsonSchema + 'static, + S1T: ComputedVecValue + JsonSchema, + S2T: ComputedVecValue + JsonSchema, +{ + pub fn from_percentiles>( + name: &str, + version: Version, + source: &Percentiles, + source2: IterableBoxedVec, + ) -> Self { + Self { + pct10: LazyVecFrom2::transformed::( + &format!("{name}_pct10"), + version, + source.boxed_pct10(), + source2.clone(), + ), + pct25: LazyVecFrom2::transformed::( + &format!("{name}_pct25"), + version, + source.boxed_pct25(), + source2.clone(), + ), + median: LazyVecFrom2::transformed::( + &format!("{name}_median"), + version, + source.boxed_median(), + source2.clone(), + ), + pct75: LazyVecFrom2::transformed::( + &format!("{name}_pct75"), + version, + source.boxed_pct75(), + source2.clone(), + ), + pct90: LazyVecFrom2::transformed::( + &format!("{name}_pct90"), + version, + source.boxed_pct90(), + source2, + ), + } + } +} diff --git a/crates/brk_computer/src/internal/single/lazy_transform/binary_sum.rs b/crates/brk_computer/src/internal/single/lazy_transform/binary_sum.rs index aa6675aa9..f1dd6bf86 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/binary_sum.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/binary_sum.rs @@ -4,7 +4,7 @@ use brk_traversable::Traversable; use brk_types::Version; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{BinaryTransform, IterableBoxedVec, IterableCloneableVec, LazyVecFrom2, VecIndex}; +use vecdb::{BinaryTransform, IterableBoxedVec, LazyVecFrom2, VecIndex}; use crate::internal::{ComputedVecValue, SumVec}; @@ -37,8 +37,8 @@ where Self(LazyVecFrom2::transformed::( name, v, - source1.0.boxed_clone(), - source2.0.boxed_clone(), + source1.boxed_clone(), + source2.boxed_clone(), )) } diff --git a/crates/brk_computer/src/internal/single/lazy_transform/binary_sum_cum.rs b/crates/brk_computer/src/internal/single/lazy_transform/binary_sum_cum.rs index f3c1a28c2..44b5d49e8 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/binary_sum_cum.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/binary_sum_cum.rs @@ -38,14 +38,14 @@ where sum: LazyVecFrom2::transformed::( &format!("{name}_sum"), version, - source1.sum.0.boxed_clone(), - source2.sum.0.boxed_clone(), + source1.boxed_sum(), + source2.boxed_sum(), ), cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), version, - source1.cumulative.0.boxed_clone(), - source2.cumulative.0.boxed_clone(), + source1.boxed_cumulative(), + source2.boxed_cumulative(), ), } } @@ -61,14 +61,14 @@ where sum: LazyVecFrom2::transformed::( name, version, - source1.sum.0.boxed_clone(), - source2.sum.0.boxed_clone(), + source1.boxed_sum(), + source2.boxed_sum(), ), cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), version, - source1.cumulative.0.boxed_clone(), - source2.cumulative.0.boxed_clone(), + source1.boxed_cumulative(), + source2.boxed_cumulative(), ), } } @@ -188,14 +188,14 @@ where sum: LazyVecFrom2::transformed::( &format!("{name}_sum"), version, - source1.sum.0.boxed_clone(), - source2.0.boxed_clone(), + source1.boxed_sum(), + source2.boxed_clone(), ), cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), version, - source1.cumulative.0.boxed_clone(), - source2.0.boxed_clone(), + source1.boxed_cumulative(), + source2.boxed_clone(), ), } } @@ -211,14 +211,14 @@ where sum: LazyVecFrom2::transformed::( name, version, - source1.sum.0.boxed_clone(), - source2.0.boxed_clone(), + source1.boxed_sum(), + source2.boxed_clone(), ), cumulative: LazyVecFrom2::transformed::( &format!("{name}_cumulative"), version, - source1.cumulative.0.boxed_clone(), - source2.0.boxed_clone(), + source1.boxed_cumulative(), + source2.boxed_clone(), ), } } diff --git a/crates/brk_computer/src/internal/single/lazy_transform/full.rs b/crates/brk_computer/src/internal/single/lazy_transform/full.rs index 800f14388..2d45dd90a 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/full.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/full.rs @@ -3,7 +3,7 @@ use brk_traversable::Traversable; use brk_types::Version; use schemars::JsonSchema; -use vecdb::{IterableCloneableVec, LazyVecFrom1, UnaryTransform, VecIndex}; +use vecdb::{LazyVecFrom1, UnaryTransform, VecIndex}; use crate::internal::{ComputedVecValue, Full}; @@ -19,6 +19,7 @@ where pub average: LazyVecFrom1, pub min: LazyVecFrom1, pub max: LazyVecFrom1, + #[traversable(flatten)] pub percentiles: LazyPercentiles, pub sum: LazyVecFrom1, pub cumulative: LazyVecFrom1, @@ -39,17 +40,17 @@ where average: LazyVecFrom1::transformed::( &format!("{name}_average"), version, - source.distribution.average.0.boxed_clone(), + source.boxed_average(), ), min: LazyVecFrom1::transformed::( &format!("{name}_min"), version, - source.distribution.minmax.min.0.boxed_clone(), + source.boxed_min(), ), max: LazyVecFrom1::transformed::( &format!("{name}_max"), version, - source.distribution.minmax.max.0.boxed_clone(), + source.boxed_max(), ), percentiles: LazyPercentiles::from_percentiles::( name, @@ -59,12 +60,12 @@ where sum: LazyVecFrom1::transformed::( &format!("{name}_sum"), version, - source.sum_cum.sum.0.boxed_clone(), + source.boxed_sum(), ), cumulative: LazyVecFrom1::transformed::( &format!("{name}_cumulative"), version, - source.sum_cum.cumulative.0.boxed_clone(), + source.boxed_cumulative(), ), } } diff --git a/crates/brk_computer/src/internal/single/lazy_transform/last.rs b/crates/brk_computer/src/internal/single/lazy_transform/last.rs index d222787a6..04e315322 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/last.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/last.rs @@ -32,7 +32,7 @@ where Self(LazyVecFrom1::transformed::( name, version, - source.0.boxed_clone(), + source.boxed_clone(), )) } diff --git a/crates/brk_computer/src/internal/single/lazy_transform/mod.rs b/crates/brk_computer/src/internal/single/lazy_transform/mod.rs index 7cc7a6f78..6b0b9d99b 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/mod.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/mod.rs @@ -1,4 +1,6 @@ +mod binary_full; mod binary_last; +mod binary_percentiles; mod binary_sum; mod binary_sum_cum; mod full; @@ -8,7 +10,9 @@ mod stats; mod sum; mod sum_cum; +pub use binary_full::*; pub use binary_last::*; +pub use binary_percentiles::*; pub use binary_sum::*; pub use binary_sum_cum::*; pub use full::*; diff --git a/crates/brk_computer/src/internal/single/lazy_transform/percentiles.rs b/crates/brk_computer/src/internal/single/lazy_transform/percentiles.rs index 952fd0014..28dd8d6dd 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/percentiles.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/percentiles.rs @@ -3,7 +3,7 @@ use brk_traversable::Traversable; use brk_types::Version; use schemars::JsonSchema; -use vecdb::{IterableCloneableVec, LazyVecFrom1, UnaryTransform, VecIndex}; +use vecdb::{LazyVecFrom1, UnaryTransform, VecIndex}; use crate::internal::{ComputedVecValue, Percentiles}; @@ -36,27 +36,27 @@ where pct10: LazyVecFrom1::transformed::( &format!("{name}_pct10"), version, - source.pct10.0.boxed_clone(), + source.boxed_pct10(), ), pct25: LazyVecFrom1::transformed::( &format!("{name}_pct25"), version, - source.pct25.0.boxed_clone(), + source.boxed_pct25(), ), median: LazyVecFrom1::transformed::( &format!("{name}_median"), version, - source.median.0.boxed_clone(), + source.boxed_median(), ), pct75: LazyVecFrom1::transformed::( &format!("{name}_pct75"), version, - source.pct75.0.boxed_clone(), + source.boxed_pct75(), ), pct90: LazyVecFrom1::transformed::( &format!("{name}_pct90"), version, - source.pct90.0.boxed_clone(), + source.boxed_pct90(), ), } } diff --git a/crates/brk_computer/src/internal/single/lazy_transform/sum.rs b/crates/brk_computer/src/internal/single/lazy_transform/sum.rs index e5e961ee3..651bc79f3 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/sum.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/sum.rs @@ -4,7 +4,7 @@ use brk_traversable::Traversable; use brk_types::Version; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{IterableBoxedVec, IterableCloneableVec, LazyVecFrom1, UnaryTransform, VecIndex}; +use vecdb::{IterableBoxedVec, LazyVecFrom1, UnaryTransform, VecIndex}; use crate::internal::{ComputedVecValue, SumVec}; @@ -30,7 +30,7 @@ where Self(LazyVecFrom1::transformed::( name, version, - source.0.boxed_clone(), + source.boxed_clone(), )) } diff --git a/crates/brk_computer/src/internal/single/lazy_transform/sum_cum.rs b/crates/brk_computer/src/internal/single/lazy_transform/sum_cum.rs index f53e686a2..885adc252 100644 --- a/crates/brk_computer/src/internal/single/lazy_transform/sum_cum.rs +++ b/crates/brk_computer/src/internal/single/lazy_transform/sum_cum.rs @@ -3,7 +3,7 @@ use brk_traversable::Traversable; use brk_types::Version; use schemars::JsonSchema; -use vecdb::{IterableBoxedVec, IterableCloneableVec, LazyVecFrom1, UnaryTransform, VecIndex}; +use vecdb::{IterableBoxedVec, LazyVecFrom1, UnaryTransform, VecIndex}; use crate::internal::{ComputedVecValue, SumCum}; @@ -33,12 +33,12 @@ where sum: LazyVecFrom1::transformed::( &format!("{name}_sum"), version, - source.sum.0.boxed_clone(), + source.boxed_sum(), ), cumulative: LazyVecFrom1::transformed::( &format!("{name}_cumulative"), version, - source.cumulative.0.boxed_clone(), + source.boxed_cumulative(), ), } } @@ -50,11 +50,11 @@ where source: &SumCum, ) -> Self { Self { - sum: LazyVecFrom1::transformed::(name, version, source.sum.0.boxed_clone()), + sum: LazyVecFrom1::transformed::(name, version, source.boxed_sum()), cumulative: LazyVecFrom1::transformed::( &format!("{name}_cumulative"), version, - source.cumulative.0.boxed_clone(), + source.boxed_cumulative(), ), } } diff --git a/crates/brk_computer/src/internal/single/mod.rs b/crates/brk_computer/src/internal/single/mod.rs index ce496144d..0324abb84 100644 --- a/crates/brk_computer/src/internal/single/mod.rs +++ b/crates/brk_computer/src/internal/single/mod.rs @@ -1,17 +1,19 @@ //! Single-index types and primitives. +mod difficultyepoch; mod group; +mod height; mod lazy; mod lazy_transform; mod transform; mod tx; -mod value; mod vec; +pub use difficultyepoch::*; pub use group::*; +pub use height::*; pub use lazy::*; pub use lazy_transform::*; pub use transform::*; pub use tx::*; -pub use value::*; pub use vec::*; diff --git a/crates/brk_computer/src/internal/single/transform/mod.rs b/crates/brk_computer/src/internal/single/transform/mod.rs index b0cb6d221..5d7ceccf6 100644 --- a/crates/brk_computer/src/internal/single/transform/mod.rs +++ b/crates/brk_computer/src/internal/single/transform/mod.rs @@ -8,6 +8,7 @@ mod dollar_plus; mod dollar_times_tenths; mod f32_identity; mod half_close_price_times_sats; +mod ohlc; mod percentage_diff_close_dollars; mod percentage_dollars_f32; mod percentage_dollars_f32_neg; @@ -29,6 +30,7 @@ mod sat_mask; mod sat_plus; mod sat_plus_to_bitcoin; mod sat_to_bitcoin; +mod sats_times_close_price; mod u16_to_years; mod volatility_sqrt30; mod volatility_sqrt365; @@ -45,6 +47,7 @@ pub use dollar_plus::*; pub use dollar_times_tenths::*; pub use f32_identity::*; pub use half_close_price_times_sats::*; +pub use ohlc::*; pub use percentage_diff_close_dollars::*; pub use percentage_dollars_f32::*; pub use percentage_dollars_f32_neg::*; @@ -66,6 +69,7 @@ pub use sat_mask::*; pub use sat_plus::*; pub use sat_plus_to_bitcoin::*; pub use sat_to_bitcoin::*; +pub use sats_times_close_price::*; pub use u16_to_years::*; pub use volatility_sqrt30::*; pub use volatility_sqrt365::*; diff --git a/crates/brk_computer/src/internal/multi/specialized/ohlc/lazy.rs b/crates/brk_computer/src/internal/single/transform/ohlc.rs similarity index 58% rename from crates/brk_computer/src/internal/multi/specialized/ohlc/lazy.rs rename to crates/brk_computer/src/internal/single/transform/ohlc.rs index f4b9d2a37..1bf5e3fb7 100644 --- a/crates/brk_computer/src/internal/multi/specialized/ohlc/lazy.rs +++ b/crates/brk_computer/src/internal/single/transform/ohlc.rs @@ -1,7 +1,7 @@ -//! Lazy OHLC component extractors for height + dateindex. +//! Lazy OHLC component extractors. use brk_traversable::Traversable; -use brk_types::{Close, DateIndex, Height, High, Low, Open}; +use brk_types::{Close, High, Low, Open}; use schemars::JsonSchema; use serde::Serialize; use vecdb::{BytesVecValue, Formattable, LazyVecFrom1, VecIndex}; @@ -19,14 +19,3 @@ where pub low: LazyVecFrom1, I, SourceT>, pub close: LazyVecFrom1, I, SourceT>, } - -/// Lazy OHLC component extractors for height + dateindex. -#[derive(Clone, Traversable)] -pub struct LazyHeightDateOHLC -where - T: BytesVecValue + Formattable + Serialize + JsonSchema + 'static, - SourceT: BytesVecValue + Formattable + Serialize + JsonSchema + 'static, -{ - pub height: LazyOHLC, - pub dateindex: LazyOHLC, -} diff --git a/crates/brk_computer/src/internal/single/transform/sats_times_close_price.rs b/crates/brk_computer/src/internal/single/transform/sats_times_close_price.rs new file mode 100644 index 000000000..3df760477 --- /dev/null +++ b/crates/brk_computer/src/internal/single/transform/sats_times_close_price.rs @@ -0,0 +1,14 @@ +use brk_types::{Bitcoin, Close, Dollars, Sats}; +use vecdb::BinaryTransform; + +/// Sats * Close -> Dollars (sats / 1e8 × price) +/// Same as ClosePriceTimesSats but with swapped argument order. +/// Use when sats is the first source (e.g., Full) and price is second. +pub struct SatsTimesClosePrice; + +impl BinaryTransform, Dollars> for SatsTimesClosePrice { + #[inline(always)] + fn apply(sats: Sats, price: Close) -> Dollars { + *price * Bitcoin::from(sats) + } +} diff --git a/crates/brk_computer/src/internal/single/tx/distribution.rs b/crates/brk_computer/src/internal/single/tx/distribution.rs index a8628b691..ea5fa2d9d 100644 --- a/crates/brk_computer/src/internal/single/tx/distribution.rs +++ b/crates/brk_computer/src/internal/single/tx/distribution.rs @@ -1,4 +1,4 @@ -//! ComputedTxDistribution - eager txindex source + derived distribution. +//! ComputedFromTxDistribution - eager txindex source + derived distribution. use brk_error::Result; use brk_indexer::Indexer; @@ -10,14 +10,14 @@ use vecdb::{Database, EagerVec, Exit, ImportableVec, PcoVec}; use crate::{ ComputeIndexes, indexes, - internal::{ComputedVecValue, DerivedTxDistribution, NumericValue}, + internal::{ComputedVecValue, TxDerivedDistribution, NumericValue}, }; const VERSION: Version = Version::ZERO; #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(merge)] -pub struct ComputedTxDistribution +pub struct ComputedFromTxDistribution where T: ComputedVecValue + PartialOrd + JsonSchema, { @@ -25,10 +25,10 @@ where #[deref] #[deref_mut] #[traversable(flatten)] - pub distribution: DerivedTxDistribution, + pub distribution: TxDerivedDistribution, } -impl ComputedTxDistribution +impl ComputedFromTxDistribution where T: NumericValue + JsonSchema, { @@ -40,7 +40,7 @@ where ) -> Result { let v = version + VERSION; let txindex = EagerVec::forced_import(db, name, v)?; - let distribution = DerivedTxDistribution::forced_import(db, name, v, indexes)?; + let distribution = TxDerivedDistribution::forced_import(db, name, v, indexes)?; Ok(Self { txindex, distribution }) } @@ -51,7 +51,27 @@ where starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { - self.distribution - .derive_from(indexer, indexes, starting_indexes, &self.txindex, exit) + self.derive_from_with_skip(indexer, indexes, starting_indexes, exit, 0) + } + + /// Derive from source, skipping first N transactions per block from all calculations. + /// + /// Use `skip_count: 1` to exclude coinbase transactions from fee/feerate stats. + pub fn derive_from_with_skip( + &mut self, + indexer: &Indexer, + indexes: &indexes::Vecs, + starting_indexes: &ComputeIndexes, + exit: &Exit, + skip_count: usize, + ) -> Result<()> { + self.distribution.derive_from_with_skip( + indexer, + indexes, + starting_indexes, + &self.txindex, + exit, + skip_count, + ) } } diff --git a/crates/brk_computer/src/internal/single/value/mod.rs b/crates/brk_computer/src/internal/single/value/mod.rs deleted file mode 100644 index c8b12e279..000000000 --- a/crates/brk_computer/src/internal/single/value/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -mod height; - -pub use height::*; diff --git a/crates/brk_computer/src/internal/single/vec/average.rs b/crates/brk_computer/src/internal/single/vec/average.rs index 5ea94aad3..a286dd7b2 100644 --- a/crates/brk_computer/src/internal/single/vec/average.rs +++ b/crates/brk_computer/src/internal/single/vec/average.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_traversable::Traversable; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{Database, EagerVec, ImportableVec, PcoVec, VecIndex, Version}; +use vecdb::{Database, EagerVec, ImportableVec, IterableBoxedVec, IterableCloneableVec, PcoVec, VecIndex, Version}; use crate::internal::ComputedVecValue; @@ -23,4 +23,8 @@ impl AverageVec { pub fn inner(&self) -> &EagerVec> { &self.0 } + + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/vec/cumulative.rs b/crates/brk_computer/src/internal/single/vec/cumulative.rs index 4eeba6d6d..9d418ad3a 100644 --- a/crates/brk_computer/src/internal/single/vec/cumulative.rs +++ b/crates/brk_computer/src/internal/single/vec/cumulative.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_traversable::Traversable; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{Database, EagerVec, ImportableVec, PcoVec, VecIndex, Version}; +use vecdb::{Database, EagerVec, ImportableVec, IterableBoxedVec, IterableCloneableVec, PcoVec, VecIndex, Version}; use crate::internal::ComputedVecValue; @@ -22,4 +22,8 @@ impl CumulativeVec { pub fn inner(&self) -> &EagerVec> { &self.0 } + + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/vec/first.rs b/crates/brk_computer/src/internal/single/vec/first.rs index b4c00d9e3..c0daf43c4 100644 --- a/crates/brk_computer/src/internal/single/vec/first.rs +++ b/crates/brk_computer/src/internal/single/vec/first.rs @@ -4,8 +4,8 @@ use brk_types::StoredU64; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; use vecdb::{ - AnyStoredVec, AnyVec, Database, EagerVec, Exit, GenericStoredVec, ImportableVec, IterableVec, - PcoVec, VecIndex, VecValue, Version, + AnyStoredVec, AnyVec, Database, EagerVec, Exit, GenericStoredVec, ImportableVec, IterableBoxedVec, + IterableCloneableVec, IterableVec, PcoVec, VecIndex, VecValue, Version, }; use crate::internal::ComputedVecValue; @@ -24,6 +24,10 @@ impl FirstVec { &self.0 } + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } + /// Compute first values from a source vec. /// /// For each output index I, takes the first value from the corresponding diff --git a/crates/brk_computer/src/internal/single/vec/last.rs b/crates/brk_computer/src/internal/single/vec/last.rs index aabf4a20d..6e1edf57d 100644 --- a/crates/brk_computer/src/internal/single/vec/last.rs +++ b/crates/brk_computer/src/internal/single/vec/last.rs @@ -3,7 +3,7 @@ use brk_traversable::Traversable; use brk_types::{CheckedSub, StoredU64}; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{AnyStoredVec, AnyVec, Database, EagerVec, Exit, GenericStoredVec, ImportableVec, IterableVec, PcoVec, VecIndex, VecValue, Version}; +use vecdb::{AnyStoredVec, AnyVec, Database, EagerVec, Exit, GenericStoredVec, ImportableVec, IterableBoxedVec, IterableCloneableVec, IterableVec, PcoVec, VecIndex, VecValue, Version}; use crate::internal::ComputedVecValue; @@ -23,6 +23,10 @@ impl LastVec { &self.0 } + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } + /// Compute last values from a source vec. /// /// For each output index I, takes the last value from the corresponding diff --git a/crates/brk_computer/src/internal/single/vec/max.rs b/crates/brk_computer/src/internal/single/vec/max.rs index 7505e690c..bae57fd90 100644 --- a/crates/brk_computer/src/internal/single/vec/max.rs +++ b/crates/brk_computer/src/internal/single/vec/max.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_traversable::Traversable; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{Database, EagerVec, ImportableVec, PcoVec, VecIndex, Version}; +use vecdb::{Database, EagerVec, ImportableVec, IterableBoxedVec, IterableCloneableVec, PcoVec, VecIndex, Version}; use crate::internal::ComputedVecValue; @@ -21,4 +21,8 @@ impl MaxVec { pub fn inner(&self) -> &EagerVec> { &self.0 } + + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/vec/min.rs b/crates/brk_computer/src/internal/single/vec/min.rs index 8499455f3..06b43406c 100644 --- a/crates/brk_computer/src/internal/single/vec/min.rs +++ b/crates/brk_computer/src/internal/single/vec/min.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_traversable::Traversable; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{Database, EagerVec, ImportableVec, PcoVec, VecIndex, Version}; +use vecdb::{Database, EagerVec, ImportableVec, IterableBoxedVec, IterableCloneableVec, PcoVec, VecIndex, Version}; use crate::internal::ComputedVecValue; @@ -21,4 +21,8 @@ impl MinVec { pub fn inner(&self) -> &EagerVec> { &self.0 } + + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/internal/single/vec/percentiles.rs b/crates/brk_computer/src/internal/single/vec/percentiles.rs index be34bc264..8d051b350 100644 --- a/crates/brk_computer/src/internal/single/vec/percentiles.rs +++ b/crates/brk_computer/src/internal/single/vec/percentiles.rs @@ -4,7 +4,7 @@ use brk_error::Result; use brk_traversable::Traversable; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{Database, EagerVec, ImportableVec, PcoVec, VecIndex, Version}; +use vecdb::{Database, EagerVec, ImportableVec, IterableBoxedVec, IterableCloneableVec, PcoVec, VecIndex, Version}; use crate::internal::ComputedVecValue; @@ -25,6 +25,10 @@ macro_rules! define_percentile_vec { pub fn inner(&self) -> &EagerVec> { &self.0 } + + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } } }; } diff --git a/crates/brk_computer/src/internal/single/vec/sum.rs b/crates/brk_computer/src/internal/single/vec/sum.rs index 5098bde3e..c3d29ea14 100644 --- a/crates/brk_computer/src/internal/single/vec/sum.rs +++ b/crates/brk_computer/src/internal/single/vec/sum.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_traversable::Traversable; use derive_more::{Deref, DerefMut}; use schemars::JsonSchema; -use vecdb::{Database, EagerVec, ImportableVec, PcoVec, VecIndex, Version}; +use vecdb::{Database, EagerVec, ImportableVec, IterableBoxedVec, IterableCloneableVec, PcoVec, VecIndex, Version}; use crate::internal::ComputedVecValue; @@ -27,4 +27,8 @@ impl SumVec { pub fn inner(&self) -> &EagerVec> { &self.0 } + + pub fn boxed_clone(&self) -> IterableBoxedVec { + self.0.boxed_clone() + } } diff --git a/crates/brk_computer/src/lib.rs b/crates/brk_computer/src/lib.rs index e25e0f2f4..e76e7df62 100644 --- a/crates/brk_computer/src/lib.rs +++ b/crates/brk_computer/src/lib.rs @@ -314,13 +314,8 @@ impl Computer { // Scripts (needed for outputs.count.utxo_count) info!("Computing scripts..."); let i = Instant::now(); - self.scripts.compute( - indexer, - &self.indexes, - self.price.as_ref(), - &starting_indexes, - exit, - )?; + self.scripts + .compute(indexer, &self.indexes, &starting_indexes, exit)?; info!("Computed scripts in {:?}", i.elapsed()); // Outputs depends on inputs and scripts (for utxo_count) @@ -345,7 +340,6 @@ impl Computer { &self.inputs, &self.outputs, &starting_indexes, - self.price.as_ref(), exit, )?; info!("Computed transactions in {:?}", i.elapsed()); @@ -358,7 +352,6 @@ impl Computer { &self.indexes, &self.transactions, &starting_indexes, - self.price.as_ref(), exit, )?; info!("Computed blocks in {:?}", i.elapsed()); @@ -426,7 +419,6 @@ impl Computer { &self.transactions, &self.distribution, &starting_indexes, - self.price.as_ref(), exit, )?; info!("Computed supply in {:?}", i.elapsed()); diff --git a/crates/brk_computer/src/market/ath/import.rs b/crates/brk_computer/src/market/ath/import.rs index c27e8cf32..a99c01836 100644 --- a/crates/brk_computer/src/market/ath/import.rs +++ b/crates/brk_computer/src/market/ath/import.rs @@ -6,7 +6,7 @@ use super::Vecs; use crate::{ indexes, internal::{ - ComputedDateLast, ComputedHeightDateLast, LazyBinaryHeightDateLast, LazyDateLast, + ComputedFromDateLast, ComputedFromHeightAndDateLast, LazyBinaryFromHeightAndDateLast, LazyFromDateLast, PercentageDiffCloseDollars, StoredU16ToYears, }, price, @@ -19,12 +19,12 @@ impl Vecs { indexes: &indexes::Vecs, price: &price::Vecs, ) -> Result { - let price_ath = ComputedHeightDateLast::forced_import(db, "price_ath", version, indexes)?; + let price_ath = ComputedFromHeightAndDateLast::forced_import(db, "price_ath", version, indexes)?; let max_days_between_price_aths = - ComputedDateLast::forced_import(db, "max_days_between_price_aths", version, indexes)?; + ComputedFromDateLast::forced_import(db, "max_days_between_price_aths", version, indexes)?; - let max_years_between_price_aths = LazyDateLast::from_computed::( + let max_years_between_price_aths = LazyFromDateLast::from_computed::( "max_years_between_price_aths", version, max_days_between_price_aths.dateindex.boxed_clone(), @@ -32,9 +32,9 @@ impl Vecs { ); let days_since_price_ath = - ComputedDateLast::forced_import(db, "days_since_price_ath", version, indexes)?; + ComputedFromDateLast::forced_import(db, "days_since_price_ath", version, indexes)?; - let years_since_price_ath = LazyDateLast::from_computed::( + let years_since_price_ath = LazyFromDateLast::from_computed::( "years_since_price_ath", version, days_since_price_ath.dateindex.boxed_clone(), @@ -42,7 +42,7 @@ impl Vecs { ); let price_drawdown = - LazyBinaryHeightDateLast::from_computed_both_last::( + LazyBinaryFromHeightAndDateLast::from_computed_both_last::( "price_drawdown", version, EagerVec::forced_import(db, "price_drawdown", version)?, diff --git a/crates/brk_computer/src/market/ath/vecs.rs b/crates/brk_computer/src/market/ath/vecs.rs index 74edaaec7..8174c6d9c 100644 --- a/crates/brk_computer/src/market/ath/vecs.rs +++ b/crates/brk_computer/src/market/ath/vecs.rs @@ -2,16 +2,16 @@ use brk_traversable::Traversable; use brk_types::{Close, Dollars, StoredF32, StoredU16}; use crate::internal::{ - ComputedDateLast, ComputedHeightDateLast, LazyBinaryHeightDateLast, LazyDateLast, + ComputedFromDateLast, ComputedFromHeightAndDateLast, LazyBinaryFromHeightAndDateLast, LazyFromDateLast, }; /// All-time high related metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub price_ath: ComputedHeightDateLast, - pub price_drawdown: LazyBinaryHeightDateLast, Dollars>, - pub days_since_price_ath: ComputedDateLast, - pub years_since_price_ath: LazyDateLast, - pub max_days_between_price_aths: ComputedDateLast, - pub max_years_between_price_aths: LazyDateLast, + pub price_ath: ComputedFromHeightAndDateLast, + pub price_drawdown: LazyBinaryFromHeightAndDateLast, Dollars>, + pub days_since_price_ath: ComputedFromDateLast, + pub years_since_price_ath: LazyFromDateLast, + pub max_days_between_price_aths: ComputedFromDateLast, + pub max_years_between_price_aths: LazyFromDateLast, } diff --git a/crates/brk_computer/src/market/dca/import.rs b/crates/brk_computer/src/market/dca/import.rs index 27cc24cd1..236fb178a 100644 --- a/crates/brk_computer/src/market/dca/import.rs +++ b/crates/brk_computer/src/market/dca/import.rs @@ -5,7 +5,7 @@ use vecdb::Database; use super::{ByDcaCagr, ByDcaClass, ByDcaPeriod, DCA_CLASS_NAMES, DCA_PERIOD_NAMES, Vecs}; use crate::{ indexes, - internal::{ComputedDateLast, LazyBinaryDateLast, PercentageDiffCloseDollars, ValueDateLast}, + internal::{ComputedFromDateLast, LazyBinaryFromDateLast, PercentageDiffCloseDollars, ValueFromDateLast}, price, }; @@ -18,12 +18,12 @@ impl Vecs { ) -> Result { // DCA by period - stack (KISS) let period_stack = ByDcaPeriod::try_new(|name, _days| { - ValueDateLast::forced_import(db, &format!("{name}_dca_stack"), version, true, indexes) + ValueFromDateLast::forced_import(db, &format!("{name}_dca_stack"), version, true, indexes) })?; // DCA by period - average price let period_average_price = ByDcaPeriod::try_new(|name, _days| { - ComputedDateLast::forced_import( + ComputedFromDateLast::forced_import( db, &format!("{name}_dca_average_price"), version, @@ -35,7 +35,7 @@ impl Vecs { DCA_PERIOD_NAMES .zip_ref(&period_average_price) .map(|(name, average_price)| { - LazyBinaryDateLast::from_computed_both_last::( + LazyBinaryFromDateLast::from_computed_both_last::( &format!("{name}_dca_returns"), version, &price.usd.split.close, @@ -45,12 +45,12 @@ impl Vecs { // DCA by period - CAGR let period_cagr = ByDcaCagr::try_new(|name, _days| { - ComputedDateLast::forced_import(db, &format!("{name}_dca_cagr"), version, indexes) + ComputedFromDateLast::forced_import(db, &format!("{name}_dca_cagr"), version, indexes) })?; // Lump sum by period - stack (KISS) let period_lump_sum_stack = ByDcaPeriod::try_new(|name, _days| { - ValueDateLast::forced_import( + ValueFromDateLast::forced_import( db, &format!("{name}_lump_sum_stack"), version, @@ -61,19 +61,19 @@ impl Vecs { // DCA by year class - stack (KISS) let class_stack = ByDcaClass::try_new(|name, _year, _dateindex| { - ValueDateLast::forced_import(db, &format!("{name}_stack"), version, true, indexes) + ValueFromDateLast::forced_import(db, &format!("{name}_stack"), version, true, indexes) })?; // DCA by year class - average price let class_average_price = ByDcaClass::try_new(|name, _year, _dateindex| { - ComputedDateLast::forced_import(db, &format!("{name}_average_price"), version, indexes) + ComputedFromDateLast::forced_import(db, &format!("{name}_average_price"), version, indexes) })?; let class_returns = DCA_CLASS_NAMES .zip_ref(&class_average_price) .map(|(name, average_price)| { - LazyBinaryDateLast::from_computed_both_last::( + LazyBinaryFromDateLast::from_computed_both_last::( &format!("{name}_returns"), version, &price.usd.split.close, diff --git a/crates/brk_computer/src/market/dca/vecs.rs b/crates/brk_computer/src/market/dca/vecs.rs index 82da55f42..36043caf1 100644 --- a/crates/brk_computer/src/market/dca/vecs.rs +++ b/crates/brk_computer/src/market/dca/vecs.rs @@ -2,22 +2,22 @@ use brk_traversable::Traversable; use brk_types::{Close, Dollars, StoredF32}; use super::{ByDcaCagr, ByDcaClass, ByDcaPeriod}; -use crate::internal::{ComputedDateLast, LazyBinaryDateLast, ValueDateLast}; +use crate::internal::{ComputedFromDateLast, LazyBinaryFromDateLast, ValueFromDateLast}; /// Dollar-cost averaging metrics by time period and year class #[derive(Clone, Traversable)] pub struct Vecs { // DCA by period - KISS types - pub period_stack: ByDcaPeriod, - pub period_average_price: ByDcaPeriod>, - pub period_returns: ByDcaPeriod, Dollars>>, - pub period_cagr: ByDcaCagr>, + pub period_stack: ByDcaPeriod, + pub period_average_price: ByDcaPeriod>, + pub period_returns: ByDcaPeriod, Dollars>>, + pub period_cagr: ByDcaCagr>, // Lump sum by period (for comparison with DCA) - KISS types - pub period_lump_sum_stack: ByDcaPeriod, + pub period_lump_sum_stack: ByDcaPeriod, // DCA by year class - KISS types - pub class_stack: ByDcaClass, - pub class_average_price: ByDcaClass>, - pub class_returns: ByDcaClass, Dollars>>, + pub class_stack: ByDcaClass, + pub class_average_price: ByDcaClass>, + pub class_returns: ByDcaClass, Dollars>>, } diff --git a/crates/brk_computer/src/market/indicators/import.rs b/crates/brk_computer/src/market/indicators/import.rs index 7d507f60a..def74c71d 100644 --- a/crates/brk_computer/src/market/indicators/import.rs +++ b/crates/brk_computer/src/market/indicators/import.rs @@ -5,7 +5,7 @@ use vecdb::{Database, EagerVec, ImportableVec, IterableCloneableVec, LazyVecFrom use super::{super::moving_average, Vecs}; use crate::{ distribution, indexes, - internal::{ComputedDateLast, DifferenceF32, LazyBinaryDateLast, Ratio32, RsiFormula}, + internal::{ComputedFromDateLast, DifferenceF32, LazyBinaryFromDateLast, Ratio32, RsiFormula}, transactions, }; @@ -34,9 +34,13 @@ impl Vecs { .as_ref() .zip(transactions.volume.sent_sum.dollars.as_ref()) .map(|(market_cap, volume)| { - LazyBinaryDateLast::from_block_last_and_height_sum::( - "nvt", v, market_cap, volume, - ) + LazyBinaryFromDateLast::from_lazy_binary_block_last_and_lazy_binary_sum::< + Ratio32, + _, + _, + _, + _, + >("nvt", v, market_cap, volume) }); let rsi_gains = EagerVec::forced_import(db, "rsi_gains", v)?; @@ -85,7 +89,7 @@ impl Vecs { Ok(Self { puell_multiple: compute_dollars - .then(|| ComputedDateLast::forced_import(db, "puell_multiple", v, indexes)) + .then(|| ComputedFromDateLast::forced_import(db, "puell_multiple", v, indexes)) .transpose()?, nvt, rsi_gains, diff --git a/crates/brk_computer/src/market/indicators/vecs.rs b/crates/brk_computer/src/market/indicators/vecs.rs index b56fe5c35..5d8a14f5e 100644 --- a/crates/brk_computer/src/market/indicators/vecs.rs +++ b/crates/brk_computer/src/market/indicators/vecs.rs @@ -2,12 +2,12 @@ use brk_traversable::Traversable; use brk_types::{DateIndex, Dollars, StoredF32}; use vecdb::{EagerVec, LazyVecFrom2, PcoVec}; -use crate::internal::{ComputedDateLast, LazyBinaryDateLast}; +use crate::internal::{ComputedFromDateLast, LazyBinaryFromDateLast}; #[derive(Clone, Traversable)] pub struct Vecs { - pub puell_multiple: Option>, - pub nvt: Option>, + pub puell_multiple: Option>, + pub nvt: Option>, pub rsi_gains: EagerVec>, pub rsi_losses: EagerVec>, diff --git a/crates/brk_computer/src/market/lookback/import.rs b/crates/brk_computer/src/market/lookback/import.rs index ef331f486..b60d6e45a 100644 --- a/crates/brk_computer/src/market/lookback/import.rs +++ b/crates/brk_computer/src/market/lookback/import.rs @@ -3,12 +3,12 @@ use brk_types::Version; use vecdb::Database; use super::{ByLookbackPeriod, Vecs}; -use crate::{indexes, internal::ComputedDateLast}; +use crate::{indexes, internal::ComputedFromDateLast}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { let price_ago = ByLookbackPeriod::try_new(|name, _days| { - ComputedDateLast::forced_import(db, &format!("price_{name}_ago"), version, indexes) + ComputedFromDateLast::forced_import(db, &format!("price_{name}_ago"), version, indexes) })?; Ok(Self { price_ago }) diff --git a/crates/brk_computer/src/market/lookback/vecs.rs b/crates/brk_computer/src/market/lookback/vecs.rs index fa0724e33..61c59cb08 100644 --- a/crates/brk_computer/src/market/lookback/vecs.rs +++ b/crates/brk_computer/src/market/lookback/vecs.rs @@ -2,10 +2,10 @@ use brk_traversable::Traversable; use brk_types::Dollars; use super::ByLookbackPeriod; -use crate::internal::ComputedDateLast; +use crate::internal::ComputedFromDateLast; /// Price lookback metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub price_ago: ByLookbackPeriod>, + pub price_ago: ByLookbackPeriod>, } diff --git a/crates/brk_computer/src/market/moving_average/import.rs b/crates/brk_computer/src/market/moving_average/import.rs index b65388317..8b16ef06d 100644 --- a/crates/brk_computer/src/market/moving_average/import.rs +++ b/crates/brk_computer/src/market/moving_average/import.rs @@ -5,7 +5,7 @@ use vecdb::Database; use super::Vecs; use crate::{ indexes, - internal::{ComputedRatioVecsDate, DollarsTimesTenths, LazyDateLast}, + internal::{ComputedFromDateRatio, DollarsTimesTenths, LazyFromDateLast}, price, }; @@ -16,7 +16,7 @@ impl Vecs { indexes: &indexes::Vecs, price: Option<&price::Vecs>, ) -> Result { - let price_1w_sma = ComputedRatioVecsDate::forced_import( + let price_1w_sma = ComputedFromDateRatio::forced_import( db, "price_1w_sma", None, @@ -25,7 +25,7 @@ impl Vecs { true, price, )?; - let price_8d_sma = ComputedRatioVecsDate::forced_import( + let price_8d_sma = ComputedFromDateRatio::forced_import( db, "price_8d_sma", None, @@ -34,7 +34,7 @@ impl Vecs { true, price, )?; - let price_13d_sma = ComputedRatioVecsDate::forced_import( + let price_13d_sma = ComputedFromDateRatio::forced_import( db, "price_13d_sma", None, @@ -43,7 +43,7 @@ impl Vecs { true, price, )?; - let price_21d_sma = ComputedRatioVecsDate::forced_import( + let price_21d_sma = ComputedFromDateRatio::forced_import( db, "price_21d_sma", None, @@ -52,7 +52,7 @@ impl Vecs { true, price, )?; - let price_1m_sma = ComputedRatioVecsDate::forced_import( + let price_1m_sma = ComputedFromDateRatio::forced_import( db, "price_1m_sma", None, @@ -61,7 +61,7 @@ impl Vecs { true, price, )?; - let price_34d_sma = ComputedRatioVecsDate::forced_import( + let price_34d_sma = ComputedFromDateRatio::forced_import( db, "price_34d_sma", None, @@ -70,7 +70,7 @@ impl Vecs { true, price, )?; - let price_55d_sma = ComputedRatioVecsDate::forced_import( + let price_55d_sma = ComputedFromDateRatio::forced_import( db, "price_55d_sma", None, @@ -79,7 +79,7 @@ impl Vecs { true, price, )?; - let price_89d_sma = ComputedRatioVecsDate::forced_import( + let price_89d_sma = ComputedFromDateRatio::forced_import( db, "price_89d_sma", None, @@ -88,7 +88,7 @@ impl Vecs { true, price, )?; - let price_111d_sma = ComputedRatioVecsDate::forced_import( + let price_111d_sma = ComputedFromDateRatio::forced_import( db, "price_111d_sma", None, @@ -97,7 +97,7 @@ impl Vecs { true, price, )?; - let price_144d_sma = ComputedRatioVecsDate::forced_import( + let price_144d_sma = ComputedFromDateRatio::forced_import( db, "price_144d_sma", None, @@ -106,7 +106,7 @@ impl Vecs { true, price, )?; - let price_200d_sma = ComputedRatioVecsDate::forced_import( + let price_200d_sma = ComputedFromDateRatio::forced_import( db, "price_200d_sma", None, @@ -115,7 +115,7 @@ impl Vecs { true, price, )?; - let price_350d_sma = ComputedRatioVecsDate::forced_import( + let price_350d_sma = ComputedFromDateRatio::forced_import( db, "price_350d_sma", None, @@ -124,7 +124,7 @@ impl Vecs { true, price, )?; - let price_1y_sma = ComputedRatioVecsDate::forced_import( + let price_1y_sma = ComputedFromDateRatio::forced_import( db, "price_1y_sma", None, @@ -133,7 +133,7 @@ impl Vecs { true, price, )?; - let price_2y_sma = ComputedRatioVecsDate::forced_import( + let price_2y_sma = ComputedFromDateRatio::forced_import( db, "price_2y_sma", None, @@ -142,7 +142,7 @@ impl Vecs { true, price, )?; - let price_200w_sma = ComputedRatioVecsDate::forced_import( + let price_200w_sma = ComputedFromDateRatio::forced_import( db, "price_200w_sma", None, @@ -151,7 +151,7 @@ impl Vecs { true, price, )?; - let price_4y_sma = ComputedRatioVecsDate::forced_import( + let price_4y_sma = ComputedFromDateRatio::forced_import( db, "price_4y_sma", None, @@ -161,7 +161,7 @@ impl Vecs { price, )?; - let price_1w_ema = ComputedRatioVecsDate::forced_import( + let price_1w_ema = ComputedFromDateRatio::forced_import( db, "price_1w_ema", None, @@ -170,7 +170,7 @@ impl Vecs { true, price, )?; - let price_8d_ema = ComputedRatioVecsDate::forced_import( + let price_8d_ema = ComputedFromDateRatio::forced_import( db, "price_8d_ema", None, @@ -179,7 +179,7 @@ impl Vecs { true, price, )?; - let price_12d_ema = ComputedRatioVecsDate::forced_import( + let price_12d_ema = ComputedFromDateRatio::forced_import( db, "price_12d_ema", None, @@ -188,7 +188,7 @@ impl Vecs { true, price, )?; - let price_13d_ema = ComputedRatioVecsDate::forced_import( + let price_13d_ema = ComputedFromDateRatio::forced_import( db, "price_13d_ema", None, @@ -197,7 +197,7 @@ impl Vecs { true, price, )?; - let price_21d_ema = ComputedRatioVecsDate::forced_import( + let price_21d_ema = ComputedFromDateRatio::forced_import( db, "price_21d_ema", None, @@ -206,7 +206,7 @@ impl Vecs { true, price, )?; - let price_26d_ema = ComputedRatioVecsDate::forced_import( + let price_26d_ema = ComputedFromDateRatio::forced_import( db, "price_26d_ema", None, @@ -215,7 +215,7 @@ impl Vecs { true, price, )?; - let price_1m_ema = ComputedRatioVecsDate::forced_import( + let price_1m_ema = ComputedFromDateRatio::forced_import( db, "price_1m_ema", None, @@ -224,7 +224,7 @@ impl Vecs { true, price, )?; - let price_34d_ema = ComputedRatioVecsDate::forced_import( + let price_34d_ema = ComputedFromDateRatio::forced_import( db, "price_34d_ema", None, @@ -233,7 +233,7 @@ impl Vecs { true, price, )?; - let price_55d_ema = ComputedRatioVecsDate::forced_import( + let price_55d_ema = ComputedFromDateRatio::forced_import( db, "price_55d_ema", None, @@ -242,7 +242,7 @@ impl Vecs { true, price, )?; - let price_89d_ema = ComputedRatioVecsDate::forced_import( + let price_89d_ema = ComputedFromDateRatio::forced_import( db, "price_89d_ema", None, @@ -251,7 +251,7 @@ impl Vecs { true, price, )?; - let price_144d_ema = ComputedRatioVecsDate::forced_import( + let price_144d_ema = ComputedFromDateRatio::forced_import( db, "price_144d_ema", None, @@ -260,7 +260,7 @@ impl Vecs { true, price, )?; - let price_200d_ema = ComputedRatioVecsDate::forced_import( + let price_200d_ema = ComputedFromDateRatio::forced_import( db, "price_200d_ema", None, @@ -269,7 +269,7 @@ impl Vecs { true, price, )?; - let price_1y_ema = ComputedRatioVecsDate::forced_import( + let price_1y_ema = ComputedFromDateRatio::forced_import( db, "price_1y_ema", None, @@ -278,7 +278,7 @@ impl Vecs { true, price, )?; - let price_2y_ema = ComputedRatioVecsDate::forced_import( + let price_2y_ema = ComputedFromDateRatio::forced_import( db, "price_2y_ema", None, @@ -287,7 +287,7 @@ impl Vecs { true, price, )?; - let price_200w_ema = ComputedRatioVecsDate::forced_import( + let price_200w_ema = ComputedFromDateRatio::forced_import( db, "price_200w_ema", None, @@ -296,7 +296,7 @@ impl Vecs { true, price, )?; - let price_4y_ema = ComputedRatioVecsDate::forced_import( + let price_4y_ema = ComputedFromDateRatio::forced_import( db, "price_4y_ema", None, @@ -307,19 +307,19 @@ impl Vecs { )?; let price_200d_sma_source = price_200d_sma.price.as_ref().unwrap(); - let price_200d_sma_x2_4 = LazyDateLast::from_source::>( + let price_200d_sma_x2_4 = LazyFromDateLast::from_source::>( "price_200d_sma_x2_4", version, price_200d_sma_source, ); - let price_200d_sma_x0_8 = LazyDateLast::from_source::>( + let price_200d_sma_x0_8 = LazyFromDateLast::from_source::>( "price_200d_sma_x0_8", version, price_200d_sma_source, ); let price_350d_sma_source = price_350d_sma.price.as_ref().unwrap(); - let price_350d_sma_x2 = LazyDateLast::from_source::>( + let price_350d_sma_x2 = LazyFromDateLast::from_source::>( "price_350d_sma_x2", version, price_350d_sma_source, diff --git a/crates/brk_computer/src/market/moving_average/vecs.rs b/crates/brk_computer/src/market/moving_average/vecs.rs index f6ab01dca..6128a803e 100644 --- a/crates/brk_computer/src/market/moving_average/vecs.rs +++ b/crates/brk_computer/src/market/moving_average/vecs.rs @@ -1,46 +1,46 @@ use brk_traversable::Traversable; use brk_types::Dollars; -use crate::internal::{ComputedRatioVecsDate, LazyDateLast}; +use crate::internal::{ComputedFromDateRatio, LazyFromDateLast}; /// Simple and exponential moving average metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub price_1w_sma: ComputedRatioVecsDate, - pub price_8d_sma: ComputedRatioVecsDate, - pub price_13d_sma: ComputedRatioVecsDate, - pub price_21d_sma: ComputedRatioVecsDate, - pub price_1m_sma: ComputedRatioVecsDate, - pub price_34d_sma: ComputedRatioVecsDate, - pub price_55d_sma: ComputedRatioVecsDate, - pub price_89d_sma: ComputedRatioVecsDate, - pub price_111d_sma: ComputedRatioVecsDate, - pub price_144d_sma: ComputedRatioVecsDate, - pub price_200d_sma: ComputedRatioVecsDate, - pub price_350d_sma: ComputedRatioVecsDate, - pub price_1y_sma: ComputedRatioVecsDate, - pub price_2y_sma: ComputedRatioVecsDate, - pub price_200w_sma: ComputedRatioVecsDate, - pub price_4y_sma: ComputedRatioVecsDate, + pub price_1w_sma: ComputedFromDateRatio, + pub price_8d_sma: ComputedFromDateRatio, + pub price_13d_sma: ComputedFromDateRatio, + pub price_21d_sma: ComputedFromDateRatio, + pub price_1m_sma: ComputedFromDateRatio, + pub price_34d_sma: ComputedFromDateRatio, + pub price_55d_sma: ComputedFromDateRatio, + pub price_89d_sma: ComputedFromDateRatio, + pub price_111d_sma: ComputedFromDateRatio, + pub price_144d_sma: ComputedFromDateRatio, + pub price_200d_sma: ComputedFromDateRatio, + pub price_350d_sma: ComputedFromDateRatio, + pub price_1y_sma: ComputedFromDateRatio, + pub price_2y_sma: ComputedFromDateRatio, + pub price_200w_sma: ComputedFromDateRatio, + pub price_4y_sma: ComputedFromDateRatio, - pub price_1w_ema: ComputedRatioVecsDate, - pub price_8d_ema: ComputedRatioVecsDate, - pub price_12d_ema: ComputedRatioVecsDate, - pub price_13d_ema: ComputedRatioVecsDate, - pub price_21d_ema: ComputedRatioVecsDate, - pub price_26d_ema: ComputedRatioVecsDate, - pub price_1m_ema: ComputedRatioVecsDate, - pub price_34d_ema: ComputedRatioVecsDate, - pub price_55d_ema: ComputedRatioVecsDate, - pub price_89d_ema: ComputedRatioVecsDate, - pub price_144d_ema: ComputedRatioVecsDate, - pub price_200d_ema: ComputedRatioVecsDate, - pub price_1y_ema: ComputedRatioVecsDate, - pub price_2y_ema: ComputedRatioVecsDate, - pub price_200w_ema: ComputedRatioVecsDate, - pub price_4y_ema: ComputedRatioVecsDate, + pub price_1w_ema: ComputedFromDateRatio, + pub price_8d_ema: ComputedFromDateRatio, + pub price_12d_ema: ComputedFromDateRatio, + pub price_13d_ema: ComputedFromDateRatio, + pub price_21d_ema: ComputedFromDateRatio, + pub price_26d_ema: ComputedFromDateRatio, + pub price_1m_ema: ComputedFromDateRatio, + pub price_34d_ema: ComputedFromDateRatio, + pub price_55d_ema: ComputedFromDateRatio, + pub price_89d_ema: ComputedFromDateRatio, + pub price_144d_ema: ComputedFromDateRatio, + pub price_200d_ema: ComputedFromDateRatio, + pub price_1y_ema: ComputedFromDateRatio, + pub price_2y_ema: ComputedFromDateRatio, + pub price_200w_ema: ComputedFromDateRatio, + pub price_4y_ema: ComputedFromDateRatio, - pub price_200d_sma_x2_4: LazyDateLast, - pub price_200d_sma_x0_8: LazyDateLast, - pub price_350d_sma_x2: LazyDateLast, + pub price_200d_sma_x2_4: LazyFromDateLast, + pub price_200d_sma_x0_8: LazyFromDateLast, + pub price_350d_sma_x2: LazyFromDateLast, } diff --git a/crates/brk_computer/src/market/range/compute.rs b/crates/brk_computer/src/market/range/compute.rs index 2f4df1fb4..73fda9fc1 100644 --- a/crates/brk_computer/src/market/range/compute.rs +++ b/crates/brk_computer/src/market/range/compute.rs @@ -56,7 +56,7 @@ impl Vecs { Ok(()) })?; - self.dateindex_to_price_true_range.compute_transform3( + self.price_true_range.compute_transform3( starting_indexes.dateindex, open, high, @@ -70,9 +70,9 @@ impl Vecs { exit, )?; - self.dateindex_to_price_true_range_2w_sum.compute_sum( + self.price_true_range_2w_sum.compute_sum( starting_indexes.dateindex, - &self.dateindex_to_price_true_range, + &self.price_true_range, 14, exit, )?; @@ -83,7 +83,7 @@ impl Vecs { let log10n = (n as f32).log10(); v.compute_transform3( starting_indexes.dateindex, - &self.dateindex_to_price_true_range_2w_sum, + &self.price_true_range_2w_sum, &self.price_2w_max.dateindex, &self.price_2w_min.dateindex, |(i, tr_sum, max, min, ..)| { diff --git a/crates/brk_computer/src/market/range/import.rs b/crates/brk_computer/src/market/range/import.rs index e9256d23a..96f2bb9d5 100644 --- a/crates/brk_computer/src/market/range/import.rs +++ b/crates/brk_computer/src/market/range/import.rs @@ -3,72 +3,68 @@ use brk_types::Version; use vecdb::{Database, EagerVec, ImportableVec}; use super::Vecs; -use crate::{indexes, internal::ComputedDateLast}; +use crate::{indexes, internal::ComputedFromDateLast}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { let v1 = Version::ONE; Ok(Self { - price_1w_min: ComputedDateLast::forced_import( + price_1w_min: ComputedFromDateLast::forced_import( db, "price_1w_min", version + v1, indexes, )?, - price_1w_max: ComputedDateLast::forced_import( + price_1w_max: ComputedFromDateLast::forced_import( db, "price_1w_max", version + v1, indexes, )?, - price_2w_min: ComputedDateLast::forced_import( + price_2w_min: ComputedFromDateLast::forced_import( db, "price_2w_min", version + v1, indexes, )?, - price_2w_max: ComputedDateLast::forced_import( + price_2w_max: ComputedFromDateLast::forced_import( db, "price_2w_max", version + v1, indexes, )?, - price_1m_min: ComputedDateLast::forced_import( + price_1m_min: ComputedFromDateLast::forced_import( db, "price_1m_min", version + v1, indexes, )?, - price_1m_max: ComputedDateLast::forced_import( + price_1m_max: ComputedFromDateLast::forced_import( db, "price_1m_max", version + v1, indexes, )?, - price_1y_min: ComputedDateLast::forced_import( + price_1y_min: ComputedFromDateLast::forced_import( db, "price_1y_min", version + v1, indexes, )?, - price_1y_max: ComputedDateLast::forced_import( + price_1y_max: ComputedFromDateLast::forced_import( db, "price_1y_max", version + v1, indexes, )?, - dateindex_to_price_true_range: EagerVec::forced_import( - db, - "price_true_range", - version, - )?, - dateindex_to_price_true_range_2w_sum: EagerVec::forced_import( + price_true_range: EagerVec::forced_import(db, "price_true_range", version)?, + price_true_range_2w_sum: EagerVec::forced_import( db, "price_true_range_2w_sum", version, )?, - price_2w_choppiness_index: ComputedDateLast::forced_import( + price_2w_choppiness_index: ComputedFromDateLast::forced_import( db, "price_2w_choppiness_index", version + v1, diff --git a/crates/brk_computer/src/market/range/vecs.rs b/crates/brk_computer/src/market/range/vecs.rs index 4975e744c..46205928c 100644 --- a/crates/brk_computer/src/market/range/vecs.rs +++ b/crates/brk_computer/src/market/range/vecs.rs @@ -2,20 +2,20 @@ use brk_traversable::Traversable; use brk_types::{DateIndex, Dollars, StoredF32}; use vecdb::{EagerVec, PcoVec}; -use crate::internal::ComputedDateLast; +use crate::internal::ComputedFromDateLast; /// Price range and choppiness metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub price_1w_min: ComputedDateLast, - pub price_1w_max: ComputedDateLast, - pub price_2w_min: ComputedDateLast, - pub price_2w_max: ComputedDateLast, - pub price_1m_min: ComputedDateLast, - pub price_1m_max: ComputedDateLast, - pub price_1y_min: ComputedDateLast, - pub price_1y_max: ComputedDateLast, - pub dateindex_to_price_true_range: EagerVec>, - pub dateindex_to_price_true_range_2w_sum: EagerVec>, - pub price_2w_choppiness_index: ComputedDateLast, + pub price_1w_min: ComputedFromDateLast, + pub price_1w_max: ComputedFromDateLast, + pub price_2w_min: ComputedFromDateLast, + pub price_2w_max: ComputedFromDateLast, + pub price_1m_min: ComputedFromDateLast, + pub price_1m_max: ComputedFromDateLast, + pub price_1y_min: ComputedFromDateLast, + pub price_1y_max: ComputedFromDateLast, + pub price_true_range: EagerVec>, + pub price_true_range_2w_sum: EagerVec>, + pub price_2w_choppiness_index: ComputedFromDateLast, } diff --git a/crates/brk_computer/src/market/returns/import.rs b/crates/brk_computer/src/market/returns/import.rs index 9a64cbb3c..7776123e0 100644 --- a/crates/brk_computer/src/market/returns/import.rs +++ b/crates/brk_computer/src/market/returns/import.rs @@ -7,7 +7,7 @@ use super::Vecs; use crate::{ indexes, internal::{ - ComputedDateLast, ComputedStandardDeviationVecsDate, LazyBinaryDateLast, + ComputedFromDateLast, ComputedFromDateStdDev, LazyBinaryFromDateLast, PercentageDiffCloseDollars, StandardDeviationVecsOptions, }, market::dca::ByDcaCagr, @@ -28,7 +28,7 @@ impl Vecs { LOOKBACK_PERIOD_NAMES .zip_ref(&lookback.price_ago) .map(|(name, price_ago)| { - LazyBinaryDateLast::from_computed_both_last::( + LazyBinaryFromDateLast::from_computed_both_last::( &format!("{name}_price_returns"), version, &price.usd.split.close, @@ -38,10 +38,10 @@ impl Vecs { // CAGR (computed, 2y+ only) let cagr = ByDcaCagr::try_new(|name, _days| { - ComputedDateLast::forced_import(db, &format!("{name}_cagr"), version, indexes) + ComputedFromDateLast::forced_import(db, &format!("{name}_cagr"), version, indexes) })?; - let _1d_returns_1w_sd = ComputedStandardDeviationVecsDate::forced_import( + let _1d_returns_1w_sd = ComputedFromDateStdDev::forced_import( db, "1d_returns_1w_sd", 7, @@ -50,7 +50,7 @@ impl Vecs { StandardDeviationVecsOptions::default(), None, )?; - let _1d_returns_1m_sd = ComputedStandardDeviationVecsDate::forced_import( + let _1d_returns_1m_sd = ComputedFromDateStdDev::forced_import( db, "1d_returns_1m_sd", 30, @@ -59,7 +59,7 @@ impl Vecs { StandardDeviationVecsOptions::default(), None, )?; - let _1d_returns_1y_sd = ComputedStandardDeviationVecsDate::forced_import( + let _1d_returns_1y_sd = ComputedFromDateStdDev::forced_import( db, "1d_returns_1y_sd", 365, @@ -70,7 +70,7 @@ impl Vecs { )?; let downside_returns = EagerVec::forced_import(db, "downside_returns", version)?; - let downside_1w_sd = ComputedStandardDeviationVecsDate::forced_import( + let downside_1w_sd = ComputedFromDateStdDev::forced_import( db, "downside_1w_sd", 7, @@ -79,7 +79,7 @@ impl Vecs { StandardDeviationVecsOptions::default(), None, )?; - let downside_1m_sd = ComputedStandardDeviationVecsDate::forced_import( + let downside_1m_sd = ComputedFromDateStdDev::forced_import( db, "downside_1m_sd", 30, @@ -88,7 +88,7 @@ impl Vecs { StandardDeviationVecsOptions::default(), None, )?; - let downside_1y_sd = ComputedStandardDeviationVecsDate::forced_import( + let downside_1y_sd = ComputedFromDateStdDev::forced_import( db, "downside_1y_sd", 365, diff --git a/crates/brk_computer/src/market/returns/vecs.rs b/crates/brk_computer/src/market/returns/vecs.rs index 55080358c..b22f3f02f 100644 --- a/crates/brk_computer/src/market/returns/vecs.rs +++ b/crates/brk_computer/src/market/returns/vecs.rs @@ -3,26 +3,26 @@ use brk_types::{Close, DateIndex, Dollars, StoredF32}; use vecdb::{EagerVec, PcoVec}; use crate::{ - internal::{ComputedDateLast, ComputedStandardDeviationVecsDate, LazyBinaryDateLast}, + internal::{ComputedFromDateLast, ComputedFromDateStdDev, LazyBinaryFromDateLast}, market::{dca::ByDcaCagr, lookback::ByLookbackPeriod}, }; /// Price returns, CAGR, and returns standard deviation metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub price_returns: ByLookbackPeriod, Dollars>>, + pub price_returns: ByLookbackPeriod, Dollars>>, // CAGR (computed from returns, 2y+ only) - pub cagr: ByDcaCagr>, + pub cagr: ByDcaCagr>, // Returns standard deviation (computed from 1d returns) - pub _1d_returns_1w_sd: ComputedStandardDeviationVecsDate, - pub _1d_returns_1m_sd: ComputedStandardDeviationVecsDate, - pub _1d_returns_1y_sd: ComputedStandardDeviationVecsDate, + pub _1d_returns_1w_sd: ComputedFromDateStdDev, + pub _1d_returns_1m_sd: ComputedFromDateStdDev, + pub _1d_returns_1y_sd: ComputedFromDateStdDev, // Downside returns and deviation (for Sortino ratio) pub downside_returns: EagerVec>, - pub downside_1w_sd: ComputedStandardDeviationVecsDate, - pub downside_1m_sd: ComputedStandardDeviationVecsDate, - pub downside_1y_sd: ComputedStandardDeviationVecsDate, + pub downside_1w_sd: ComputedFromDateStdDev, + pub downside_1m_sd: ComputedFromDateStdDev, + pub downside_1y_sd: ComputedFromDateStdDev, } diff --git a/crates/brk_computer/src/market/volatility/import.rs b/crates/brk_computer/src/market/volatility/import.rs index 75de14d6f..fc11df8c9 100644 --- a/crates/brk_computer/src/market/volatility/import.rs +++ b/crates/brk_computer/src/market/volatility/import.rs @@ -4,46 +4,46 @@ use vecdb::{IterableCloneableVec, LazyVecFrom2}; use super::super::returns; use super::Vecs; use crate::internal::{ - LazyDateLast, RatioF32, StoredF32TimesSqrt7, StoredF32TimesSqrt30, StoredF32TimesSqrt365, + LazyFromDateLast, RatioF32, StoredF32TimesSqrt7, StoredF32TimesSqrt30, StoredF32TimesSqrt365, }; impl Vecs { pub fn forced_import(version: Version, returns: &returns::Vecs) -> Self { let v2 = Version::TWO; - let price_1w_volatility = LazyDateLast::from_source::( + let price_1w_volatility = LazyFromDateLast::from_source::( "price_1w_volatility", version + v2, &returns._1d_returns_1w_sd.sd, ); - let price_1m_volatility = LazyDateLast::from_source::( + let price_1m_volatility = LazyFromDateLast::from_source::( "price_1m_volatility", version + v2, &returns._1d_returns_1m_sd.sd, ); - let price_1y_volatility = LazyDateLast::from_source::( + let price_1y_volatility = LazyFromDateLast::from_source::( "price_1y_volatility", version + v2, &returns._1d_returns_1y_sd.sd, ); - let dateindex_to_sharpe_1w = LazyVecFrom2::transformed::( + let sharpe_1w = LazyVecFrom2::transformed::( "sharpe_1w", version + v2, returns.price_returns._1w.dateindex.boxed_clone(), price_1w_volatility.dateindex.boxed_clone(), ); - let dateindex_to_sharpe_1m = LazyVecFrom2::transformed::( + let sharpe_1m = LazyVecFrom2::transformed::( "sharpe_1m", version + v2, returns.price_returns._1m.dateindex.boxed_clone(), price_1m_volatility.dateindex.boxed_clone(), ); - let dateindex_to_sharpe_1y = LazyVecFrom2::transformed::( + let sharpe_1y = LazyVecFrom2::transformed::( "sharpe_1y", version + v2, returns.price_returns._1y.dateindex.boxed_clone(), @@ -51,21 +51,21 @@ impl Vecs { ); // Sortino ratio = returns / downside volatility - let dateindex_to_sortino_1w = LazyVecFrom2::transformed::( + let sortino_1w = LazyVecFrom2::transformed::( "sortino_1w", version + v2, returns.price_returns._1w.dateindex.boxed_clone(), returns.downside_1w_sd.sd.dateindex.boxed_clone(), ); - let dateindex_to_sortino_1m = LazyVecFrom2::transformed::( + let sortino_1m = LazyVecFrom2::transformed::( "sortino_1m", version + v2, returns.price_returns._1m.dateindex.boxed_clone(), returns.downside_1m_sd.sd.dateindex.boxed_clone(), ); - let dateindex_to_sortino_1y = LazyVecFrom2::transformed::( + let sortino_1y = LazyVecFrom2::transformed::( "sortino_1y", version + v2, returns.price_returns._1y.dateindex.boxed_clone(), @@ -76,12 +76,12 @@ impl Vecs { price_1w_volatility, price_1m_volatility, price_1y_volatility, - sharpe_1w: dateindex_to_sharpe_1w, - sharpe_1m: dateindex_to_sharpe_1m, - sharpe_1y: dateindex_to_sharpe_1y, - sortino_1w: dateindex_to_sortino_1w, - sortino_1m: dateindex_to_sortino_1m, - sortino_1y: dateindex_to_sortino_1y, + sharpe_1w, + sharpe_1m, + sharpe_1y, + sortino_1w, + sortino_1m, + sortino_1y, } } } diff --git a/crates/brk_computer/src/market/volatility/vecs.rs b/crates/brk_computer/src/market/volatility/vecs.rs index 60577e014..d1e1af918 100644 --- a/crates/brk_computer/src/market/volatility/vecs.rs +++ b/crates/brk_computer/src/market/volatility/vecs.rs @@ -2,14 +2,14 @@ use brk_traversable::Traversable; use brk_types::{DateIndex, StoredF32}; use vecdb::LazyVecFrom2; -use crate::internal::LazyDateLast; +use crate::internal::LazyFromDateLast; /// Price volatility metrics (derived from returns standard deviation) #[derive(Clone, Traversable)] pub struct Vecs { - pub price_1w_volatility: LazyDateLast, - pub price_1m_volatility: LazyDateLast, - pub price_1y_volatility: LazyDateLast, + pub price_1w_volatility: LazyFromDateLast, + pub price_1m_volatility: LazyFromDateLast, + pub price_1y_volatility: LazyFromDateLast, pub sharpe_1w: LazyVecFrom2, pub sharpe_1m: LazyVecFrom2, diff --git a/crates/brk_computer/src/outputs/count/import.rs b/crates/brk_computer/src/outputs/count/import.rs index 9360f2da9..39a9add3c 100644 --- a/crates/brk_computer/src/outputs/count/import.rs +++ b/crates/brk_computer/src/outputs/count/import.rs @@ -5,14 +5,14 @@ use vecdb::Database; use super::Vecs; use crate::{ indexes, - internal::{ComputedBlockFull, DerivedTxFull}, + internal::{ComputedFromHeightFull, TxDerivedFull}, }; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - total_count: DerivedTxFull::forced_import(db, "output_count", version, indexes)?, - utxo_count: ComputedBlockFull::forced_import(db, "exact_utxo_count", version, indexes)?, + total_count: TxDerivedFull::forced_import(db, "output_count", version, indexes)?, + utxo_count: ComputedFromHeightFull::forced_import(db, "exact_utxo_count", version, indexes)?, }) } } diff --git a/crates/brk_computer/src/outputs/count/vecs.rs b/crates/brk_computer/src/outputs/count/vecs.rs index 0aaf6784b..58a0784d9 100644 --- a/crates/brk_computer/src/outputs/count/vecs.rs +++ b/crates/brk_computer/src/outputs/count/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::StoredU64; -use crate::internal::{ComputedBlockFull, DerivedTxFull}; +use crate::internal::{ComputedFromHeightFull, TxDerivedFull}; #[derive(Clone, Traversable)] pub struct Vecs { - pub total_count: DerivedTxFull, - pub utxo_count: ComputedBlockFull, + pub total_count: TxDerivedFull, + pub utxo_count: ComputedFromHeightFull, } diff --git a/crates/brk_computer/src/pools/vecs.rs b/crates/brk_computer/src/pools/vecs.rs index 58f0f5664..f742014e1 100644 --- a/crates/brk_computer/src/pools/vecs.rs +++ b/crates/brk_computer/src/pools/vecs.rs @@ -9,9 +9,9 @@ use crate::{ blocks, indexes::{self, ComputeIndexes}, internal::{ - ComputedBlockLast, ComputedBlockSumCum, ComputedDateLast, DollarsPlus, LazyBinaryBlockLast, - LazyValueBlockSumCum, MaskSats, PercentageU32F32, SatsPlus, SatsPlusToBitcoin, - ValueBinaryBlock, + ComputedFromHeightLast, ComputedFromHeightSumCum, ComputedFromDateLast, DollarsPlus, LazyBinaryFromHeightLast, + LazyValueFromHeightSumCum, MaskSats, PercentageU32F32, SatsPlus, SatsPlusToBitcoin, + ValueBinaryFromHeight, }, price, transactions, }; @@ -20,21 +20,21 @@ use crate::{ pub struct Vecs { slug: PoolSlug, - pub blocks_mined: ComputedBlockSumCum, - pub _24h_blocks_mined: ComputedBlockLast, - pub _1w_blocks_mined: ComputedBlockLast, - pub _1m_blocks_mined: ComputedBlockLast, - pub _1y_blocks_mined: ComputedBlockLast, - pub subsidy: LazyValueBlockSumCum, - pub fee: LazyValueBlockSumCum, - pub coinbase: ValueBinaryBlock, - pub dominance: LazyBinaryBlockLast, + pub blocks_mined: ComputedFromHeightSumCum, + pub _24h_blocks_mined: ComputedFromHeightLast, + pub _1w_blocks_mined: ComputedFromHeightLast, + pub _1m_blocks_mined: ComputedFromHeightLast, + pub _1y_blocks_mined: ComputedFromHeightLast, + pub subsidy: LazyValueFromHeightSumCum, + pub fee: LazyValueFromHeightSumCum, + pub coinbase: ValueBinaryFromHeight, + pub dominance: LazyBinaryFromHeightLast, - pub _24h_dominance: LazyBinaryBlockLast, - pub _1w_dominance: LazyBinaryBlockLast, - pub _1m_dominance: LazyBinaryBlockLast, - pub _1y_dominance: LazyBinaryBlockLast, - pub days_since_block: ComputedDateLast, + pub _24h_dominance: LazyBinaryFromHeightLast, + pub _1w_dominance: LazyBinaryFromHeightLast, + pub _1m_dominance: LazyBinaryFromHeightLast, + pub _1y_dominance: LazyBinaryFromHeightLast, + pub days_since_block: ComputedFromDateLast, } impl Vecs { @@ -51,18 +51,18 @@ impl Vecs { let version = parent_version; let blocks_mined = - ComputedBlockSumCum::forced_import(db, &suffix("blocks_mined"), version, indexes)?; + ComputedFromHeightSumCum::forced_import(db, &suffix("blocks_mined"), version, indexes)?; let _24h_blocks_mined = - ComputedBlockLast::forced_import(db, &suffix("24h_blocks_mined"), version, indexes)?; + ComputedFromHeightLast::forced_import(db, &suffix("24h_blocks_mined"), version, indexes)?; let _1w_blocks_mined = - ComputedBlockLast::forced_import(db, &suffix("1w_blocks_mined"), version, indexes)?; + ComputedFromHeightLast::forced_import(db, &suffix("1w_blocks_mined"), version, indexes)?; let _1m_blocks_mined = - ComputedBlockLast::forced_import(db, &suffix("1m_blocks_mined"), version, indexes)?; + ComputedFromHeightLast::forced_import(db, &suffix("1m_blocks_mined"), version, indexes)?; let _1y_blocks_mined = - ComputedBlockLast::forced_import(db, &suffix("1y_blocks_mined"), version, indexes)?; + ComputedFromHeightLast::forced_import(db, &suffix("1y_blocks_mined"), version, indexes)?; - let subsidy = LazyValueBlockSumCum::forced_import::( + let subsidy = LazyValueFromHeightSumCum::forced_import::( db, &suffix("subsidy"), version, @@ -72,7 +72,7 @@ impl Vecs { price, )?; - let fee = LazyValueBlockSumCum::forced_import::( + let fee = LazyValueFromHeightSumCum::forced_import::( db, &suffix("fee"), version, @@ -83,31 +83,31 @@ impl Vecs { )?; Ok(Self { - dominance: LazyBinaryBlockLast::from_computed_sum_cum::( + dominance: LazyBinaryFromHeightLast::from_computed_sum_cum::( &suffix("dominance"), version, &blocks_mined, &blocks.count.block_count, ), - _24h_dominance: LazyBinaryBlockLast::from_computed_last::( + _24h_dominance: LazyBinaryFromHeightLast::from_computed_last::( &suffix("24h_dominance"), version, &_24h_blocks_mined, &blocks.count._24h_block_count, ), - _1w_dominance: LazyBinaryBlockLast::from_computed_last::( + _1w_dominance: LazyBinaryFromHeightLast::from_computed_last::( &suffix("1w_dominance"), version, &_1w_blocks_mined, &blocks.count._1w_block_count, ), - _1m_dominance: LazyBinaryBlockLast::from_computed_last::( + _1m_dominance: LazyBinaryFromHeightLast::from_computed_last::( &suffix("1m_dominance"), version, &_1m_blocks_mined, &blocks.count._1m_block_count, ), - _1y_dominance: LazyBinaryBlockLast::from_computed_last::( + _1y_dominance: LazyBinaryFromHeightLast::from_computed_last::( &suffix("1y_dominance"), version, &_1y_blocks_mined, @@ -119,7 +119,7 @@ impl Vecs { _1w_blocks_mined, _1m_blocks_mined, _1y_blocks_mined, - coinbase: ValueBinaryBlock::from_lazy::< + coinbase: ValueBinaryFromHeight::from_lazy::< SatsPlus, SatsPlusToBitcoin, DollarsPlus, @@ -128,7 +128,7 @@ impl Vecs { >(&suffix("coinbase"), version, &subsidy, &fee), subsidy, fee, - days_since_block: ComputedDateLast::forced_import( + days_since_block: ComputedFromDateLast::forced_import( db, &suffix("days_since_block"), version, diff --git a/crates/brk_computer/src/price/cents/import.rs b/crates/brk_computer/src/price/cents/import.rs index 2b52d0b86..4d5f0d504 100644 --- a/crates/brk_computer/src/price/cents/import.rs +++ b/crates/brk_computer/src/price/cents/import.rs @@ -3,14 +3,14 @@ use brk_types::{DateIndex, Height, OHLCCents, Version}; use vecdb::{Database, IterableCloneableVec, LazyVecFrom1}; use super::Vecs; -use crate::internal::{ComputedHeightDateBytes, LazyHeightDateOHLC, LazyOHLC}; +use crate::internal::{ComputedHeightAndDateBytes, LazyHeightAndDateOHLC, LazyOHLC}; impl Vecs { pub fn forced_import(db: &Database, version: Version) -> Result { - let ohlc: ComputedHeightDateBytes = - ComputedHeightDateBytes::forced_import(db, "ohlc_cents", version)?; + let ohlc: ComputedHeightAndDateBytes = + ComputedHeightAndDateBytes::forced_import(db, "ohlc_cents", version)?; - let components = LazyHeightDateOHLC { + let components = LazyHeightAndDateOHLC { height: LazyOHLC { open: LazyVecFrom1::init( "price_open_cents", diff --git a/crates/brk_computer/src/price/cents/vecs.rs b/crates/brk_computer/src/price/cents/vecs.rs index 03a9d0c83..1c567ff14 100644 --- a/crates/brk_computer/src/price/cents/vecs.rs +++ b/crates/brk_computer/src/price/cents/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::{Cents, OHLCCents}; -use crate::internal::{ComputedHeightDateBytes, LazyHeightDateOHLC}; +use crate::internal::{ComputedHeightAndDateBytes, LazyHeightAndDateOHLC}; #[derive(Clone, Traversable)] pub struct Vecs { - pub split: LazyHeightDateOHLC, - pub ohlc: ComputedHeightDateBytes, + pub split: LazyHeightAndDateOHLC, + pub ohlc: ComputedHeightAndDateBytes, } diff --git a/crates/brk_computer/src/price/sats/import.rs b/crates/brk_computer/src/price/sats/import.rs index 7c45915c2..6f40a16c2 100644 --- a/crates/brk_computer/src/price/sats/import.rs +++ b/crates/brk_computer/src/price/sats/import.rs @@ -5,14 +5,14 @@ use vecdb::{Database, EagerVec, ImportableVec}; use super::Vecs; use crate::{ indexes, - internal::{OHLCComputedVecs, OHLCPeriodVecs}, + internal::{ComputedOHLC, LazyFromHeightAndDateOHLC}, }; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - split: OHLCComputedVecs::forced_import(db, "price_sats", version, indexes)?, - ohlc: OHLCPeriodVecs { + split: ComputedOHLC::forced_import(db, "price_sats", version, indexes)?, + ohlc: LazyFromHeightAndDateOHLC { dateindex: EagerVec::forced_import(db, "price_ohlc_sats", version)?, week: EagerVec::forced_import(db, "price_ohlc_sats", version)?, month: EagerVec::forced_import(db, "price_ohlc_sats", version)?, diff --git a/crates/brk_computer/src/price/sats/vecs.rs b/crates/brk_computer/src/price/sats/vecs.rs index 9c585a2ec..ce7065e14 100644 --- a/crates/brk_computer/src/price/sats/vecs.rs +++ b/crates/brk_computer/src/price/sats/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::{OHLCSats, Sats}; -use crate::internal::{OHLCComputedVecs, OHLCPeriodVecs}; +use crate::internal::{ComputedOHLC, LazyFromHeightAndDateOHLC}; #[derive(Clone, Traversable)] pub struct Vecs { - pub split: OHLCComputedVecs, - pub ohlc: OHLCPeriodVecs, + pub split: ComputedOHLC, + pub ohlc: LazyFromHeightAndDateOHLC, } diff --git a/crates/brk_computer/src/price/usd/import.rs b/crates/brk_computer/src/price/usd/import.rs index c10378453..5e65147ff 100644 --- a/crates/brk_computer/src/price/usd/import.rs +++ b/crates/brk_computer/src/price/usd/import.rs @@ -5,14 +5,14 @@ use vecdb::{Database, EagerVec, ImportableVec}; use super::Vecs; use crate::{ indexes, - internal::{OHLCComputedVecs, OHLCPeriodVecs}, + internal::{ComputedOHLC, LazyFromHeightAndDateOHLC}, }; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - split: OHLCComputedVecs::forced_import(db, "price", version, indexes)?, - ohlc: OHLCPeriodVecs { + split: ComputedOHLC::forced_import(db, "price", version, indexes)?, + ohlc: LazyFromHeightAndDateOHLC { dateindex: EagerVec::forced_import(db, "price_ohlc", version)?, week: EagerVec::forced_import(db, "price_ohlc", version)?, month: EagerVec::forced_import(db, "price_ohlc", version)?, diff --git a/crates/brk_computer/src/price/usd/vecs.rs b/crates/brk_computer/src/price/usd/vecs.rs index 136ff6a4f..76865ca06 100644 --- a/crates/brk_computer/src/price/usd/vecs.rs +++ b/crates/brk_computer/src/price/usd/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::{Dollars, OHLCDollars}; -use crate::internal::{OHLCComputedVecs, OHLCPeriodVecs}; +use crate::internal::{ComputedOHLC, LazyFromHeightAndDateOHLC}; #[derive(Clone, Traversable)] pub struct Vecs { - pub split: OHLCComputedVecs, - pub ohlc: OHLCPeriodVecs, + pub split: ComputedOHLC, + pub ohlc: LazyFromHeightAndDateOHLC, } diff --git a/crates/brk_computer/src/scripts/compute.rs b/crates/brk_computer/src/scripts/compute.rs index 9a8483043..beeecca0c 100644 --- a/crates/brk_computer/src/scripts/compute.rs +++ b/crates/brk_computer/src/scripts/compute.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_indexer::Indexer; use vecdb::Exit; -use crate::{indexes, price, ComputeIndexes}; +use crate::{indexes, ComputeIndexes}; use super::Vecs; @@ -11,7 +11,6 @@ impl Vecs { &mut self, indexer: &Indexer, indexes: &indexes::Vecs, - price: Option<&price::Vecs>, starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { @@ -19,7 +18,7 @@ impl Vecs { .compute(indexer, indexes, starting_indexes, exit)?; self.value - .compute(indexer, indexes, price, starting_indexes, exit)?; + .compute(indexer, indexes, starting_indexes, exit)?; let _lock = exit.lock(); self.db.compact()?; diff --git a/crates/brk_computer/src/scripts/count/import.rs b/crates/brk_computer/src/scripts/count/import.rs index 02fea94bb..647d154e5 100644 --- a/crates/brk_computer/src/scripts/count/import.rs +++ b/crates/brk_computer/src/scripts/count/import.rs @@ -5,7 +5,7 @@ use vecdb::{Database, IterableCloneableVec}; use super::Vecs; use crate::{ indexes, - internal::{ComputedBlockFull, LazyBinaryBlockFull, PercentageU64F32}, + internal::{ComputedFromHeightFull, LazyBinaryFromHeightFull, PercentageU64F32}, outputs, }; @@ -16,23 +16,23 @@ impl Vecs { indexes: &indexes::Vecs, outputs: &outputs::Vecs, ) -> Result { - let p2a = ComputedBlockFull::forced_import(db, "p2a_count", version, indexes)?; - let p2ms = ComputedBlockFull::forced_import(db, "p2ms_count", version, indexes)?; - let p2pk33 = ComputedBlockFull::forced_import(db, "p2pk33_count", version, indexes)?; - let p2pk65 = ComputedBlockFull::forced_import(db, "p2pk65_count", version, indexes)?; - let p2pkh = ComputedBlockFull::forced_import(db, "p2pkh_count", version, indexes)?; - let p2sh = ComputedBlockFull::forced_import(db, "p2sh_count", version, indexes)?; - let p2tr = ComputedBlockFull::forced_import(db, "p2tr_count", version, indexes)?; - let p2wpkh = ComputedBlockFull::forced_import(db, "p2wpkh_count", version, indexes)?; - let p2wsh = ComputedBlockFull::forced_import(db, "p2wsh_count", version, indexes)?; + let p2a = ComputedFromHeightFull::forced_import(db, "p2a_count", version, indexes)?; + let p2ms = ComputedFromHeightFull::forced_import(db, "p2ms_count", version, indexes)?; + let p2pk33 = ComputedFromHeightFull::forced_import(db, "p2pk33_count", version, indexes)?; + let p2pk65 = ComputedFromHeightFull::forced_import(db, "p2pk65_count", version, indexes)?; + let p2pkh = ComputedFromHeightFull::forced_import(db, "p2pkh_count", version, indexes)?; + let p2sh = ComputedFromHeightFull::forced_import(db, "p2sh_count", version, indexes)?; + let p2tr = ComputedFromHeightFull::forced_import(db, "p2tr_count", version, indexes)?; + let p2wpkh = ComputedFromHeightFull::forced_import(db, "p2wpkh_count", version, indexes)?; + let p2wsh = ComputedFromHeightFull::forced_import(db, "p2wsh_count", version, indexes)?; // Aggregate counts (computed from per-type counts) - let segwit = ComputedBlockFull::forced_import(db, "segwit_count", version, indexes)?; + let segwit = ComputedFromHeightFull::forced_import(db, "segwit_count", version, indexes)?; // Adoption ratios (lazy) // Uses outputs.count.count as denominator (total output count) // At height level: per-block ratio; at dateindex level: sum-based ratio (% of new outputs) - let taproot_adoption = LazyBinaryBlockFull::from_height_and_txindex::( + let taproot_adoption = LazyBinaryFromHeightFull::from_height_and_txindex::( "taproot_adoption", version, p2tr.height.boxed_clone(), @@ -40,7 +40,7 @@ impl Vecs { &p2tr, &outputs.count.total_count, ); - let segwit_adoption = LazyBinaryBlockFull::from_height_and_txindex::( + let segwit_adoption = LazyBinaryFromHeightFull::from_height_and_txindex::( "segwit_adoption", version, segwit.height.boxed_clone(), @@ -59,14 +59,14 @@ impl Vecs { p2tr, p2wpkh, p2wsh, - opreturn: ComputedBlockFull::forced_import(db, "opreturn_count", version, indexes)?, - emptyoutput: ComputedBlockFull::forced_import( + opreturn: ComputedFromHeightFull::forced_import(db, "opreturn_count", version, indexes)?, + emptyoutput: ComputedFromHeightFull::forced_import( db, "emptyoutput_count", version, indexes, )?, - unknownoutput: ComputedBlockFull::forced_import( + unknownoutput: ComputedFromHeightFull::forced_import( db, "unknownoutput_count", version, diff --git a/crates/brk_computer/src/scripts/count/vecs.rs b/crates/brk_computer/src/scripts/count/vecs.rs index 646edcf52..149974c66 100644 --- a/crates/brk_computer/src/scripts/count/vecs.rs +++ b/crates/brk_computer/src/scripts/count/vecs.rs @@ -1,29 +1,29 @@ use brk_traversable::Traversable; use brk_types::{StoredF32, StoredU64}; -use crate::internal::{ComputedBlockFull, LazyBinaryBlockFull}; +use crate::internal::{ComputedFromHeightFull, LazyBinaryFromHeightFull}; #[derive(Clone, Traversable)] pub struct Vecs { // Per-type output counts - pub p2a: ComputedBlockFull, - pub p2ms: ComputedBlockFull, - pub p2pk33: ComputedBlockFull, - pub p2pk65: ComputedBlockFull, - pub p2pkh: ComputedBlockFull, - pub p2sh: ComputedBlockFull, - pub p2tr: ComputedBlockFull, - pub p2wpkh: ComputedBlockFull, - pub p2wsh: ComputedBlockFull, - pub opreturn: ComputedBlockFull, - pub emptyoutput: ComputedBlockFull, - pub unknownoutput: ComputedBlockFull, + pub p2a: ComputedFromHeightFull, + pub p2ms: ComputedFromHeightFull, + pub p2pk33: ComputedFromHeightFull, + pub p2pk65: ComputedFromHeightFull, + pub p2pkh: ComputedFromHeightFull, + pub p2sh: ComputedFromHeightFull, + pub p2tr: ComputedFromHeightFull, + pub p2wpkh: ComputedFromHeightFull, + pub p2wsh: ComputedFromHeightFull, + pub opreturn: ComputedFromHeightFull, + pub emptyoutput: ComputedFromHeightFull, + pub unknownoutput: ComputedFromHeightFull, // Aggregate counts /// SegWit output count (p2wpkh + p2wsh + p2tr) - pub segwit: ComputedBlockFull, + pub segwit: ComputedFromHeightFull, // Adoption ratios - pub taproot_adoption: LazyBinaryBlockFull, - pub segwit_adoption: LazyBinaryBlockFull, + pub taproot_adoption: LazyBinaryFromHeightFull, + pub segwit_adoption: LazyBinaryFromHeightFull, } diff --git a/crates/brk_computer/src/scripts/import.rs b/crates/brk_computer/src/scripts/import.rs index f3f6c20e4..b2c669814 100644 --- a/crates/brk_computer/src/scripts/import.rs +++ b/crates/brk_computer/src/scripts/import.rs @@ -21,10 +21,9 @@ impl Vecs { db.set_min_len(PAGE_SIZE * 50_000_000)?; let version = parent_version; - let compute_dollars = price.is_some(); let count = CountVecs::forced_import(&db, version, indexes, outputs)?; - let value = ValueVecs::forced_import(&db, version, indexes, compute_dollars)?; + let value = ValueVecs::forced_import(&db, version, indexes, price)?; let this = Self { db, count, value }; diff --git a/crates/brk_computer/src/scripts/value/compute.rs b/crates/brk_computer/src/scripts/value/compute.rs index 5e8f375e3..3b4489ce1 100644 --- a/crates/brk_computer/src/scripts/value/compute.rs +++ b/crates/brk_computer/src/scripts/value/compute.rs @@ -4,19 +4,18 @@ use brk_types::{Height, OutputType, Sats, TxOutIndex}; use vecdb::{AnyStoredVec, AnyVec, Exit, GenericStoredVec, TypedVecIterator, VecIndex}; use super::Vecs; -use crate::{ComputeIndexes, indexes, price}; +use crate::{ComputeIndexes, indexes}; impl Vecs { pub fn compute( &mut self, indexer: &Indexer, indexes: &indexes::Vecs, - price: Option<&price::Vecs>, starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { self.opreturn - .compute_all(indexes, price, starting_indexes, exit, |height_vec| { + .compute_all(indexes, starting_indexes, exit, |height_vec| { // Validate computed versions against dependencies let dep_version = indexer.vecs.outputs.first_txoutindex.version() + indexer.vecs.outputs.outputtype.version() diff --git a/crates/brk_computer/src/scripts/value/import.rs b/crates/brk_computer/src/scripts/value/import.rs index 726d19684..64e04fe08 100644 --- a/crates/brk_computer/src/scripts/value/import.rs +++ b/crates/brk_computer/src/scripts/value/import.rs @@ -3,22 +3,22 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ValueBlockFull}; +use crate::{indexes, internal::ValueFromHeightFull, price}; impl Vecs { pub fn forced_import( db: &Database, version: Version, indexes: &indexes::Vecs, - compute_dollars: bool, + price: Option<&price::Vecs>, ) -> Result { Ok(Self { - opreturn: ValueBlockFull::forced_import( + opreturn: ValueFromHeightFull::forced_import( db, "opreturn_value", version, indexes, - compute_dollars, + price, )?, }) } diff --git a/crates/brk_computer/src/scripts/value/vecs.rs b/crates/brk_computer/src/scripts/value/vecs.rs index 740316a8c..a6bd4ec43 100644 --- a/crates/brk_computer/src/scripts/value/vecs.rs +++ b/crates/brk_computer/src/scripts/value/vecs.rs @@ -1,8 +1,8 @@ use brk_traversable::Traversable; -use crate::internal::ValueBlockFull; +use crate::internal::ValueFromHeightFull; #[derive(Clone, Traversable)] pub struct Vecs { - pub opreturn: ValueBlockFull, + pub opreturn: ValueFromHeightFull, } diff --git a/crates/brk_computer/src/supply/burned/compute.rs b/crates/brk_computer/src/supply/burned/compute.rs index b9a6b51dd..8bd5c8860 100644 --- a/crates/brk_computer/src/supply/burned/compute.rs +++ b/crates/brk_computer/src/supply/burned/compute.rs @@ -3,7 +3,7 @@ use brk_types::{Height, Sats}; use vecdb::{AnyStoredVec, AnyVec, Exit, GenericStoredVec, TypedVecIterator, VecIndex}; use super::Vecs; -use crate::{ComputeIndexes, blocks, indexes, price, scripts}; +use crate::{ComputeIndexes, blocks, indexes, scripts}; impl Vecs { pub fn compute( @@ -12,12 +12,11 @@ impl Vecs { scripts: &scripts::Vecs, blocks: &blocks::Vecs, starting_indexes: &ComputeIndexes, - price: Option<&price::Vecs>, exit: &Exit, ) -> Result<()> { // 1. Compute opreturn supply - copy per-block opreturn values from scripts self.opreturn - .compute_all(indexes, price, starting_indexes, exit, |height_vec| { + .compute_all(indexes, starting_indexes, exit, |height_vec| { // Validate computed versions against dependencies let opreturn_dep_version = scripts.value.opreturn.sats.height.version(); @@ -53,7 +52,7 @@ impl Vecs { let unclaimed_height = &blocks.rewards.unclaimed_rewards.sats.height; self.unspendable - .compute_all(indexes, price, starting_indexes, exit, |height_vec| { + .compute_all(indexes, starting_indexes, exit, |height_vec| { let unspendable_dep_version = opreturn_height.version() + unclaimed_height.version(); height_vec.validate_computed_version_or_reset(unspendable_dep_version)?; diff --git a/crates/brk_computer/src/supply/burned/import.rs b/crates/brk_computer/src/supply/burned/import.rs index ebfd0e16b..740f8ce76 100644 --- a/crates/brk_computer/src/supply/burned/import.rs +++ b/crates/brk_computer/src/supply/burned/import.rs @@ -3,29 +3,29 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ValueBlockSumCum}; +use crate::{indexes, internal::ValueFromHeightSumCum, price}; impl Vecs { pub fn forced_import( db: &Database, version: Version, indexes: &indexes::Vecs, - compute_dollars: bool, + price: Option<&price::Vecs>, ) -> Result { Ok(Self { - opreturn: ValueBlockSumCum::forced_import( + opreturn: ValueFromHeightSumCum::forced_import( db, "opreturn_supply", version, indexes, - compute_dollars, + price, )?, - unspendable: ValueBlockSumCum::forced_import( + unspendable: ValueFromHeightSumCum::forced_import( db, "unspendable_supply", version, indexes, - compute_dollars, + price, )?, }) } diff --git a/crates/brk_computer/src/supply/burned/vecs.rs b/crates/brk_computer/src/supply/burned/vecs.rs index 009bd30c9..5c6fddd0b 100644 --- a/crates/brk_computer/src/supply/burned/vecs.rs +++ b/crates/brk_computer/src/supply/burned/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; -use crate::internal::ValueBlockSumCum; +use crate::internal::ValueFromHeightSumCum; /// Burned/unspendable supply metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub opreturn: ValueBlockSumCum, - pub unspendable: ValueBlockSumCum, + pub opreturn: ValueFromHeightSumCum, + pub unspendable: ValueFromHeightSumCum, } diff --git a/crates/brk_computer/src/supply/circulating/import.rs b/crates/brk_computer/src/supply/circulating/import.rs index 8541171cf..104fbee3e 100644 --- a/crates/brk_computer/src/supply/circulating/import.rs +++ b/crates/brk_computer/src/supply/circulating/import.rs @@ -3,14 +3,14 @@ use brk_types::Version; use super::Vecs; use crate::{ distribution, - internal::{DollarsIdentity, LazyValueBlockLast, SatsIdentity}, + internal::{DollarsIdentity, LazyValueFromHeightLast, SatsIdentity}, }; impl Vecs { pub fn import(version: Version, distribution: &distribution::Vecs) -> Self { let supply_metrics = &distribution.utxo_cohorts.all.metrics.supply; - Self(LazyValueBlockLast::from_block_source::< + Self(LazyValueFromHeightLast::from_block_source::< SatsIdentity, DollarsIdentity, >( diff --git a/crates/brk_computer/src/supply/circulating/vecs.rs b/crates/brk_computer/src/supply/circulating/vecs.rs index b6666f04b..0033363e4 100644 --- a/crates/brk_computer/src/supply/circulating/vecs.rs +++ b/crates/brk_computer/src/supply/circulating/vecs.rs @@ -1,8 +1,8 @@ use brk_traversable::Traversable; use derive_more::{Deref, DerefMut}; -use crate::internal::LazyValueBlockLast; +use crate::internal::LazyValueFromHeightLast; /// Circulating supply - lazy references to distribution's actual supply (KISS) #[derive(Clone, Deref, DerefMut, Traversable)] -pub struct Vecs(pub LazyValueBlockLast); +pub struct Vecs(pub LazyValueFromHeightLast); diff --git a/crates/brk_computer/src/supply/compute.rs b/crates/brk_computer/src/supply/compute.rs index 9997a4965..03392ac53 100644 --- a/crates/brk_computer/src/supply/compute.rs +++ b/crates/brk_computer/src/supply/compute.rs @@ -2,7 +2,7 @@ use brk_error::Result; use vecdb::Exit; use super::Vecs; -use crate::{blocks, distribution, indexes, price, scripts, transactions, ComputeIndexes}; +use crate::{blocks, distribution, indexes, scripts, transactions, ComputeIndexes}; impl Vecs { #[allow(clippy::too_many_arguments)] @@ -14,12 +14,11 @@ impl Vecs { transactions: &transactions::Vecs, distribution: &distribution::Vecs, starting_indexes: &ComputeIndexes, - price: Option<&price::Vecs>, exit: &Exit, ) -> Result<()> { // 1. Compute burned/unspendable supply self.burned - .compute(indexes, scripts, blocks, starting_indexes, price, exit)?; + .compute(indexes, scripts, blocks, starting_indexes, exit)?; // 2. Compute inflation rate self.inflation diff --git a/crates/brk_computer/src/supply/import.rs b/crates/brk_computer/src/supply/import.rs index bde71b2c1..db727445a 100644 --- a/crates/brk_computer/src/supply/import.rs +++ b/crates/brk_computer/src/supply/import.rs @@ -28,7 +28,7 @@ impl Vecs { let circulating = super::circulating::Vecs::import(version, distribution); // Burned/unspendable supply - computed from scripts - let burned = super::burned::Vecs::forced_import(&db, version, indexes, compute_dollars)?; + let burned = super::burned::Vecs::forced_import(&db, version, indexes, price)?; // Inflation rate let inflation = super::inflation::Vecs::forced_import(&db, version, indexes)?; diff --git a/crates/brk_computer/src/supply/inflation/import.rs b/crates/brk_computer/src/supply/inflation/import.rs index fa3289a9b..dd269cdb7 100644 --- a/crates/brk_computer/src/supply/inflation/import.rs +++ b/crates/brk_computer/src/supply/inflation/import.rs @@ -3,11 +3,11 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ComputedDateAverage}; +use crate::{indexes, internal::ComputedFromDateAverage}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { - Ok(Self(ComputedDateAverage::forced_import( + Ok(Self(ComputedFromDateAverage::forced_import( db, "inflation_rate", version, diff --git a/crates/brk_computer/src/supply/inflation/vecs.rs b/crates/brk_computer/src/supply/inflation/vecs.rs index 9bad0b793..0c78e1f71 100644 --- a/crates/brk_computer/src/supply/inflation/vecs.rs +++ b/crates/brk_computer/src/supply/inflation/vecs.rs @@ -2,9 +2,9 @@ use brk_traversable::Traversable; use brk_types::StoredF32; use derive_more::{Deref, DerefMut}; -use crate::internal::ComputedDateAverage; +use crate::internal::ComputedFromDateAverage; /// Inflation rate metrics #[derive(Clone, Deref, DerefMut, Traversable)] #[traversable(transparent)] -pub struct Vecs(pub ComputedDateAverage); +pub struct Vecs(pub ComputedFromDateAverage); diff --git a/crates/brk_computer/src/supply/market_cap/import.rs b/crates/brk_computer/src/supply/market_cap/import.rs index a7177a540..e1b5c2947 100644 --- a/crates/brk_computer/src/supply/market_cap/import.rs +++ b/crates/brk_computer/src/supply/market_cap/import.rs @@ -4,7 +4,7 @@ use vecdb::IterableCloneableVec; use super::Vecs; use crate::{ distribution, - internal::{DollarsIdentity, LazyBlockLast}, + internal::{DollarsIdentity, LazyFromHeightLast}, }; impl Vecs { @@ -12,7 +12,7 @@ impl Vecs { let supply_metrics = &distribution.utxo_cohorts.all.metrics.supply; supply_metrics.total.dollars.as_ref().map(|d| { - Self(LazyBlockLast::from_computed::( + Self(LazyFromHeightLast::from_lazy_binary_computed::( "market_cap", version, d.height.boxed_clone(), diff --git a/crates/brk_computer/src/supply/market_cap/vecs.rs b/crates/brk_computer/src/supply/market_cap/vecs.rs index 2f2f6afda..ea612339e 100644 --- a/crates/brk_computer/src/supply/market_cap/vecs.rs +++ b/crates/brk_computer/src/supply/market_cap/vecs.rs @@ -2,7 +2,7 @@ use brk_traversable::Traversable; use brk_types::Dollars; use derive_more::{Deref, DerefMut}; -use crate::internal::LazyBlockLast; +use crate::internal::LazyFromHeightLast; #[derive(Clone, Deref, DerefMut, Traversable)] -pub struct Vecs(pub LazyBlockLast); +pub struct Vecs(pub LazyFromHeightLast); diff --git a/crates/brk_computer/src/supply/velocity/import.rs b/crates/brk_computer/src/supply/velocity/import.rs index cd83dfbbc..ec9da80e8 100644 --- a/crates/brk_computer/src/supply/velocity/import.rs +++ b/crates/brk_computer/src/supply/velocity/import.rs @@ -3,7 +3,7 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ComputedDateAverage}; +use crate::{indexes, internal::ComputedFromDateAverage}; impl Vecs { pub fn forced_import( @@ -13,9 +13,9 @@ impl Vecs { compute_dollars: bool, ) -> Result { Ok(Self { - btc: ComputedDateAverage::forced_import(db, "btc_velocity", version, indexes)?, + btc: ComputedFromDateAverage::forced_import(db, "btc_velocity", version, indexes)?, usd: compute_dollars.then(|| { - ComputedDateAverage::forced_import(db, "usd_velocity", version, indexes) + ComputedFromDateAverage::forced_import(db, "usd_velocity", version, indexes) .unwrap() }), }) diff --git a/crates/brk_computer/src/supply/velocity/vecs.rs b/crates/brk_computer/src/supply/velocity/vecs.rs index 38f250d65..cbaa852d6 100644 --- a/crates/brk_computer/src/supply/velocity/vecs.rs +++ b/crates/brk_computer/src/supply/velocity/vecs.rs @@ -1,11 +1,11 @@ use brk_traversable::Traversable; use brk_types::StoredF64; -use crate::internal::ComputedDateAverage; +use crate::internal::ComputedFromDateAverage; /// Velocity metrics (annualized volume / circulating supply) #[derive(Clone, Traversable)] pub struct Vecs { - pub btc: ComputedDateAverage, - pub usd: Option>, + pub btc: ComputedFromDateAverage, + pub usd: Option>, } diff --git a/crates/brk_computer/src/traits/pricing.rs b/crates/brk_computer/src/traits/pricing.rs index 31ccbebe2..64ad4ce6a 100644 --- a/crates/brk_computer/src/traits/pricing.rs +++ b/crates/brk_computer/src/traits/pricing.rs @@ -28,7 +28,7 @@ use brk_traversable::Traversable; /// |------|-------|--------|----------| /// | `Data` | Computer top-level | `PricingData` | `()` | /// | `PriceRef<'a>` | Function params | `&price::Vecs` | `()` | -/// | `ComputedDollarsHeight` | Value wrappers (Height) | `ComputedBlock` | `()` | +/// | `ComputedDollarsHeight` | Value wrappers (Height) | `ComputedFromHeight` | `()` | /// | `ComputedDollarsDateIndex` | Value wrappers (DateIndex) | `ComputedVecsDate` | `()` | /// | `StdDevBandsUsd` | StdDev USD bands | `StdDevBandsUsdData` | `()` | /// | `RatioUsd` | Ratio USD variants | `RatioUsdData` | `()` | diff --git a/crates/brk_computer/src/transactions/compute.rs b/crates/brk_computer/src/transactions/compute.rs index 0a29a2763..8d1929dee 100644 --- a/crates/brk_computer/src/transactions/compute.rs +++ b/crates/brk_computer/src/transactions/compute.rs @@ -2,7 +2,7 @@ use brk_error::Result; use brk_indexer::Indexer; use vecdb::Exit; -use crate::{indexes, inputs, outputs, price, ComputeIndexes}; +use crate::{indexes, inputs, outputs, ComputeIndexes}; use super::Vecs; @@ -15,7 +15,6 @@ impl Vecs { inputs: &inputs::Vecs, outputs: &outputs::Vecs, starting_indexes: &ComputeIndexes, - price: Option<&price::Vecs>, exit: &Exit, ) -> Result<()> { // Count computes first @@ -49,7 +48,6 @@ impl Vecs { &inputs.count, &outputs.count, starting_indexes, - price, exit, )?; diff --git a/crates/brk_computer/src/transactions/count/import.rs b/crates/brk_computer/src/transactions/count/import.rs index 776fc3060..9ce41e2fa 100644 --- a/crates/brk_computer/src/transactions/count/import.rs +++ b/crates/brk_computer/src/transactions/count/import.rs @@ -4,7 +4,7 @@ use brk_types::{StoredBool, TxIndex, Version}; use vecdb::{Database, IterableCloneableVec, LazyVecFrom2}; use super::Vecs; -use crate::{indexes, internal::ComputedBlockFull}; +use crate::{indexes, internal::ComputedFromHeightFull}; impl Vecs { pub fn forced_import( @@ -27,7 +27,7 @@ impl Vecs { ); Ok(Self { - tx_count: ComputedBlockFull::forced_import(db, "tx_count", version, indexes)?, + tx_count: ComputedFromHeightFull::forced_import(db, "tx_count", version, indexes)?, is_coinbase: txindex_to_is_coinbase, }) } diff --git a/crates/brk_computer/src/transactions/count/vecs.rs b/crates/brk_computer/src/transactions/count/vecs.rs index 1cb8c4f5e..74ad02d45 100644 --- a/crates/brk_computer/src/transactions/count/vecs.rs +++ b/crates/brk_computer/src/transactions/count/vecs.rs @@ -2,10 +2,10 @@ use brk_traversable::Traversable; use brk_types::{Height, StoredBool, StoredU64, TxIndex}; use vecdb::LazyVecFrom2; -use crate::internal::ComputedBlockFull; +use crate::internal::ComputedFromHeightFull; #[derive(Clone, Traversable)] pub struct Vecs { - pub tx_count: ComputedBlockFull, + pub tx_count: ComputedFromHeightFull, pub is_coinbase: LazyVecFrom2, } diff --git a/crates/brk_computer/src/transactions/fees/compute.rs b/crates/brk_computer/src/transactions/fees/compute.rs index 1c51b5de1..e66963810 100644 --- a/crates/brk_computer/src/transactions/fees/compute.rs +++ b/crates/brk_computer/src/transactions/fees/compute.rs @@ -57,11 +57,13 @@ impl Vecs { exit, )?; + // Skip coinbase (first tx per block) since it has no fee self.fee - .derive_from(indexer, indexes, starting_indexes, exit)?; + .derive_from_with_skip(indexer, indexes, starting_indexes, exit, 1)?; + // Skip coinbase (first tx per block) since it has no feerate self.fee_rate - .derive_from(indexer, indexes, starting_indexes, exit)?; + .derive_from_with_skip(indexer, indexes, starting_indexes, exit, 1)?; Ok(()) } diff --git a/crates/brk_computer/src/transactions/fees/import.rs b/crates/brk_computer/src/transactions/fees/import.rs index c9db30aa9..02fe10b67 100644 --- a/crates/brk_computer/src/transactions/fees/import.rs +++ b/crates/brk_computer/src/transactions/fees/import.rs @@ -4,7 +4,10 @@ use brk_types::Version; use vecdb::{Database, EagerVec, ImportableVec}; use super::Vecs; -use crate::{indexes, internal::{ComputedTxDistribution, ValueTxFull}, price}; +use crate::{indexes, internal::{ComputedFromTxDistribution, ValueFromTxFull}, price}; + +/// Bump this when fee/feerate aggregation logic changes (e.g., skip coinbase). +const VERSION: Version = Version::ONE; impl Vecs { pub fn forced_import( @@ -14,11 +17,12 @@ impl Vecs { indexes: &indexes::Vecs, price: Option<&price::Vecs>, ) -> Result { + let v = version + VERSION; Ok(Self { input_value: EagerVec::forced_import(db, "input_value", version)?, output_value: EagerVec::forced_import(db, "output_value", version)?, - fee: ValueTxFull::forced_import(db, "fee", version, indexes, indexer, price)?, - fee_rate: ComputedTxDistribution::forced_import(db, "fee_rate", version, indexes)?, + fee: ValueFromTxFull::forced_import(db, "fee", v, indexes, indexer, price)?, + fee_rate: ComputedFromTxDistribution::forced_import(db, "fee_rate", v, indexes)?, }) } } diff --git a/crates/brk_computer/src/transactions/fees/vecs.rs b/crates/brk_computer/src/transactions/fees/vecs.rs index 458a1cd32..fd58c6f1b 100644 --- a/crates/brk_computer/src/transactions/fees/vecs.rs +++ b/crates/brk_computer/src/transactions/fees/vecs.rs @@ -2,12 +2,12 @@ use brk_traversable::Traversable; use brk_types::{FeeRate, Sats, TxIndex}; use vecdb::{EagerVec, PcoVec}; -use crate::internal::{ComputedTxDistribution, ValueTxFull}; +use crate::internal::{ComputedFromTxDistribution, ValueFromTxFull}; #[derive(Clone, Traversable)] pub struct Vecs { pub input_value: EagerVec>, pub output_value: EagerVec>, - pub fee: ValueTxFull, - pub fee_rate: ComputedTxDistribution, + pub fee: ValueFromTxFull, + pub fee_rate: ComputedFromTxDistribution, } diff --git a/crates/brk_computer/src/transactions/import.rs b/crates/brk_computer/src/transactions/import.rs index 37331e421..f9cc0fc8b 100644 --- a/crates/brk_computer/src/transactions/import.rs +++ b/crates/brk_computer/src/transactions/import.rs @@ -22,13 +22,12 @@ impl Vecs { db.set_min_len(PAGE_SIZE * 50_000_000)?; let version = parent_version; - let compute_dollars = price.is_some(); let count = CountVecs::forced_import(&db, version, indexer, indexes)?; let size = SizeVecs::forced_import(&db, version, indexer, indexes)?; let fees = FeesVecs::forced_import(&db, version, indexer, indexes, price)?; let versions = VersionsVecs::forced_import(&db, version, indexes)?; - let volume = VolumeVecs::forced_import(&db, version, indexes, compute_dollars)?; + let volume = VolumeVecs::forced_import(&db, version, indexes, price)?; let this = Self { db, diff --git a/crates/brk_computer/src/transactions/size/import.rs b/crates/brk_computer/src/transactions/size/import.rs index fe71bb73d..b5d5cc614 100644 --- a/crates/brk_computer/src/transactions/size/import.rs +++ b/crates/brk_computer/src/transactions/size/import.rs @@ -4,7 +4,7 @@ use brk_types::{TxIndex, VSize, Version, Weight}; use vecdb::{Database, IterableCloneableVec, LazyVecFrom2, VecIndex}; use super::Vecs; -use crate::{indexes, internal::LazyTxDistribution}; +use crate::{indexes, internal::LazyFromTxDistribution}; impl Vecs { pub fn forced_import( @@ -42,14 +42,14 @@ impl Vecs { ); Ok(Self { - vsize: LazyTxDistribution::forced_import( + vsize: LazyFromTxDistribution::forced_import( db, "tx_vsize", version, txindex_to_vsize, indexes, )?, - weight: LazyTxDistribution::forced_import( + weight: LazyFromTxDistribution::forced_import( db, "tx_weight", version, diff --git a/crates/brk_computer/src/transactions/size/vecs.rs b/crates/brk_computer/src/transactions/size/vecs.rs index 5811b2a81..46094191a 100644 --- a/crates/brk_computer/src/transactions/size/vecs.rs +++ b/crates/brk_computer/src/transactions/size/vecs.rs @@ -1,10 +1,10 @@ use brk_traversable::Traversable; use brk_types::{StoredU32, VSize, Weight}; -use crate::internal::LazyTxDistribution; +use crate::internal::LazyFromTxDistribution; #[derive(Clone, Traversable)] pub struct Vecs { - pub vsize: LazyTxDistribution, - pub weight: LazyTxDistribution, + pub vsize: LazyFromTxDistribution, + pub weight: LazyFromTxDistribution, } diff --git a/crates/brk_computer/src/transactions/versions/compute.rs b/crates/brk_computer/src/transactions/versions/compute.rs index de7d699ec..8c290fb0f 100644 --- a/crates/brk_computer/src/transactions/versions/compute.rs +++ b/crates/brk_computer/src/transactions/versions/compute.rs @@ -4,7 +4,7 @@ use brk_types::{StoredU64, TxVersion}; use vecdb::{Exit, TypedVecIterator}; use super::Vecs; -use crate::{ComputeIndexes, indexes, internal::ComputedBlockSumCum}; +use crate::{ComputeIndexes, indexes, internal::ComputedFromHeightSumCum}; impl Vecs { pub fn compute( @@ -14,7 +14,7 @@ impl Vecs { starting_indexes: &ComputeIndexes, exit: &Exit, ) -> Result<()> { - let tx_vany = |tx_vany: &mut ComputedBlockSumCum, txversion: TxVersion| { + let tx_vany = |tx_vany: &mut ComputedFromHeightSumCum, txversion: TxVersion| { let mut txversion_iter = indexer.vecs.transactions.txversion.iter()?; tx_vany.compute_all(indexes, starting_indexes, exit, |vec| { vec.compute_filtered_count_from_indexes( diff --git a/crates/brk_computer/src/transactions/versions/import.rs b/crates/brk_computer/src/transactions/versions/import.rs index 551e1e6c7..edebb01cf 100644 --- a/crates/brk_computer/src/transactions/versions/import.rs +++ b/crates/brk_computer/src/transactions/versions/import.rs @@ -3,14 +3,14 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::ComputedBlockSumCum}; +use crate::{indexes, internal::ComputedFromHeightSumCum}; impl Vecs { pub fn forced_import(db: &Database, version: Version, indexes: &indexes::Vecs) -> Result { Ok(Self { - v1: ComputedBlockSumCum::forced_import(db, "tx_v1", version, indexes)?, - v2: ComputedBlockSumCum::forced_import(db, "tx_v2", version, indexes)?, - v3: ComputedBlockSumCum::forced_import(db, "tx_v3", version, indexes)?, + v1: ComputedFromHeightSumCum::forced_import(db, "tx_v1", version, indexes)?, + v2: ComputedFromHeightSumCum::forced_import(db, "tx_v2", version, indexes)?, + v3: ComputedFromHeightSumCum::forced_import(db, "tx_v3", version, indexes)?, }) } } diff --git a/crates/brk_computer/src/transactions/versions/vecs.rs b/crates/brk_computer/src/transactions/versions/vecs.rs index 049d95939..468dbaeff 100644 --- a/crates/brk_computer/src/transactions/versions/vecs.rs +++ b/crates/brk_computer/src/transactions/versions/vecs.rs @@ -1,11 +1,11 @@ use brk_traversable::Traversable; use brk_types::StoredU64; -use crate::internal::ComputedBlockSumCum; +use crate::internal::ComputedFromHeightSumCum; #[derive(Clone, Traversable)] pub struct Vecs { - pub v1: ComputedBlockSumCum, - pub v2: ComputedBlockSumCum, - pub v3: ComputedBlockSumCum, + pub v1: ComputedFromHeightSumCum, + pub v2: ComputedFromHeightSumCum, + pub v3: ComputedFromHeightSumCum, } diff --git a/crates/brk_computer/src/transactions/volume/compute.rs b/crates/brk_computer/src/transactions/volume/compute.rs index 4d48013e6..ea3c46851 100644 --- a/crates/brk_computer/src/transactions/volume/compute.rs +++ b/crates/brk_computer/src/transactions/volume/compute.rs @@ -5,7 +5,7 @@ use vecdb::Exit; use super::super::{count, fees}; use super::Vecs; -use crate::{ComputeIndexes, indexes, inputs, outputs, price}; +use crate::{ComputeIndexes, indexes, inputs, outputs}; impl Vecs { #[allow(clippy::too_many_arguments)] @@ -18,11 +18,10 @@ impl Vecs { inputs_count: &inputs::CountVecs, outputs_count: &outputs::CountVecs, starting_indexes: &ComputeIndexes, - price: Option<&price::Vecs>, exit: &Exit, ) -> Result<()> { self.sent_sum - .compute_all(indexes, price, starting_indexes, exit, |v| { + .compute_all(indexes, starting_indexes, exit, |v| { v.compute_filtered_sum_from_indexes( starting_indexes.height, &indexer.vecs.transactions.first_txindex, diff --git a/crates/brk_computer/src/transactions/volume/import.rs b/crates/brk_computer/src/transactions/volume/import.rs index e89d87c78..e6cbfc6f0 100644 --- a/crates/brk_computer/src/transactions/volume/import.rs +++ b/crates/brk_computer/src/transactions/volume/import.rs @@ -3,40 +3,41 @@ use brk_types::Version; use vecdb::Database; use super::Vecs; -use crate::{indexes, internal::{ComputedDateLast, ValueBlockSum, ValueDateLast}}; +use crate::{indexes, internal::{ComputedFromDateLast, ValueFromHeightSum, ValueFromDateLast}, price}; impl Vecs { pub fn forced_import( db: &Database, version: Version, indexes: &indexes::Vecs, - compute_dollars: bool, + price: Option<&price::Vecs>, ) -> Result { let v2 = Version::TWO; + let compute_dollars = price.is_some(); Ok(Self { - sent_sum: ValueBlockSum::forced_import( + sent_sum: ValueFromHeightSum::forced_import( db, "sent_sum", version, indexes, - compute_dollars, + price, )?, - annualized_volume: ValueDateLast::forced_import( + annualized_volume: ValueFromDateLast::forced_import( db, "annualized_volume", version, compute_dollars, indexes, )?, - tx_per_sec: ComputedDateLast::forced_import(db, "tx_per_sec", version + v2, indexes)?, - outputs_per_sec: ComputedDateLast::forced_import( + tx_per_sec: ComputedFromDateLast::forced_import(db, "tx_per_sec", version + v2, indexes)?, + outputs_per_sec: ComputedFromDateLast::forced_import( db, "outputs_per_sec", version + v2, indexes, )?, - inputs_per_sec: ComputedDateLast::forced_import( + inputs_per_sec: ComputedFromDateLast::forced_import( db, "inputs_per_sec", version + v2, diff --git a/crates/brk_computer/src/transactions/volume/vecs.rs b/crates/brk_computer/src/transactions/volume/vecs.rs index 893b115ca..7c9b5cc78 100644 --- a/crates/brk_computer/src/transactions/volume/vecs.rs +++ b/crates/brk_computer/src/transactions/volume/vecs.rs @@ -1,14 +1,14 @@ use brk_traversable::Traversable; use brk_types::StoredF32; -use crate::internal::{ComputedDateLast, ValueBlockSum, ValueDateLast}; +use crate::internal::{ComputedFromDateLast, ValueFromHeightSum, ValueFromDateLast}; /// Volume metrics #[derive(Clone, Traversable)] pub struct Vecs { - pub sent_sum: ValueBlockSum, - pub annualized_volume: ValueDateLast, - pub tx_per_sec: ComputedDateLast, - pub outputs_per_sec: ComputedDateLast, - pub inputs_per_sec: ComputedDateLast, + pub sent_sum: ValueFromHeightSum, + pub annualized_volume: ValueFromDateLast, + pub tx_per_sec: ComputedFromDateLast, + pub outputs_per_sec: ComputedFromDateLast, + pub inputs_per_sec: ComputedFromDateLast, } diff --git a/crates/brk_indexer/src/vecs/blocks.rs b/crates/brk_indexer/src/vecs/blocks.rs index 0059567b6..1cf404f83 100644 --- a/crates/brk_indexer/src/vecs/blocks.rs +++ b/crates/brk_indexer/src/vecs/blocks.rs @@ -9,8 +9,10 @@ use crate::parallel_import; #[derive(Clone, Traversable)] pub struct BlocksVecs { pub blockhash: BytesVec, + #[traversable(wrap = "difficulty", rename = "raw")] pub difficulty: PcoVec, /// Doesn't guarantee continuity due to possible reorgs and more generally the nature of mining + #[traversable(wrap = "time")] pub timestamp: PcoVec, pub total_size: PcoVec, pub weight: PcoVec, diff --git a/crates/brk_query/src/impl/mining/block_fees.rs b/crates/brk_query/src/impl/mining/block_fees.rs index a88f4e024..313fa5712 100644 --- a/crates/brk_query/src/impl/mining/block_fees.rs +++ b/crates/brk_query/src/impl/mining/block_fees.rs @@ -21,8 +21,7 @@ impl Query { .fee .sats .dateindex - .average - .0 + .average() .iter(); Ok(iter.collect(|di, ts, h| { diff --git a/crates/brk_query/src/impl/mining/block_rewards.rs b/crates/brk_query/src/impl/mining/block_rewards.rs index b5b6daa75..1d486d60b 100644 --- a/crates/brk_query/src/impl/mining/block_rewards.rs +++ b/crates/brk_query/src/impl/mining/block_rewards.rs @@ -22,8 +22,7 @@ impl Query { .sats .dateindex .distribution - .average - .0 + .average() .iter(); Ok(iter.collect(|di, ts, h| { diff --git a/crates/brk_query/src/impl/mining/block_sizes.rs b/crates/brk_query/src/impl/mining/block_sizes.rs index 7d95774c5..dd41faf8b 100644 --- a/crates/brk_query/src/impl/mining/block_sizes.rs +++ b/crates/brk_query/src/impl/mining/block_sizes.rs @@ -21,8 +21,7 @@ impl Query { .size .dateindex .distribution - .average - .0 + .average() .iter(); let mut weights_vec = computer .blocks @@ -30,8 +29,7 @@ impl Query { .weight .dateindex .distribution - .average - .0 + .average() .iter(); let entries: Vec<_> = iter.collect(|di, ts, h| { diff --git a/crates/brk_query/src/impl/mining/epochs.rs b/crates/brk_query/src/impl/mining/epochs.rs index 9313e8938..b05dd3814 100644 --- a/crates/brk_query/src/impl/mining/epochs.rs +++ b/crates/brk_query/src/impl/mining/epochs.rs @@ -27,7 +27,7 @@ pub fn iter_difficulty_epochs( .first_height .iter(); let mut epoch_to_timestamp_iter = computer.blocks.time.timestamp.difficultyepoch.iter(); - let mut epoch_to_difficulty_iter = computer.blocks.mining.difficulty.difficultyepoch.iter(); + let mut epoch_to_difficulty_iter = computer.blocks.difficulty.raw.difficultyepoch.iter(); let mut results = Vec::with_capacity(end_epoch.to_usize() - start_epoch.to_usize() + 1); let mut prev_difficulty: Option = None; diff --git a/crates/brk_query/src/vecs.rs b/crates/brk_query/src/vecs.rs index f49ac8648..ed5e1ee0b 100644 --- a/crates/brk_query/src/vecs.rs +++ b/crates/brk_query/src/vecs.rs @@ -104,8 +104,6 @@ impl<'a> Vecs<'a> { .collect(), ) .merge_branches() - .unwrap() - .simplify() .unwrap(), ); this.matcher = Some(QuickMatch::new(&this.metrics)); diff --git a/crates/brk_traversable/tests/derive_tests.rs b/crates/brk_traversable/tests/derive_tests.rs deleted file mode 100644 index 76f4aaac0..000000000 --- a/crates/brk_traversable/tests/derive_tests.rs +++ /dev/null @@ -1,874 +0,0 @@ -//! Integration tests for the Traversable derive macro. -//! -//! Tests struct patterns similar to those in brk_computer to ensure -//! the derive macro produces correct tree structures. - -use std::collections::BTreeSet; - -use brk_traversable::{Index, MetricLeaf, MetricLeafWithSchema, Traversable, TreeNode}; -use brk_traversable_derive::Traversable; - -// ============================================================================ -// Mock vec types for testing -// ============================================================================ - -/// Mock leaf vec that produces a Leaf node with given name and index -struct MockVec { - name: String, - index: Index, -} - -impl MockVec { - fn new(name: &str, index: Index) -> Self { - Self { - name: name.to_string(), - index, - } - } -} - -impl Traversable for MockVec { - fn to_tree_node(&self) -> TreeNode { - TreeNode::Leaf(MetricLeafWithSchema::new( - MetricLeaf::new( - self.name.clone(), - "MockType".to_string(), - BTreeSet::from([self.index]), - ), - serde_json::Value::Null, - )) - } - - fn iter_any_exportable(&self) -> impl Iterator { - std::iter::empty() - } -} - -// ============================================================================ -// Helper functions -// ============================================================================ - -fn get_leaf_indexes(node: &TreeNode) -> Option<&BTreeSet> { - match node { - TreeNode::Leaf(l) => Some(l.indexes()), - _ => None, - } -} - -fn get_leaf_name(node: &TreeNode) -> Option<&str> { - match node { - TreeNode::Leaf(l) => Some(l.name()), - _ => None, - } -} - -// ============================================================================ -// Case 1: LazyBlockValue pattern -// ============================================================================ -// LazyBlockValue (no merge on struct): -// - sats: wrap="sats" -// - rest: LazyDerivedBlockValue with flatten -// - bitcoin: plain field -// - dollars: Option, plain field - -#[derive(Traversable)] -struct MockLazyDerivedBlockValue { - pub bitcoin: MockVec, - pub dollars: Option, -} - -#[derive(Traversable)] -struct MockLazyBlockValue { - #[traversable(rename = "sats")] - pub sats: MockVec, - #[traversable(flatten)] - pub rest: MockLazyDerivedBlockValue, -} - -#[test] -fn lazy_block_value_flat_denomination_siblings() { - let value = MockLazyBlockValue { - sats: MockVec::new("metric", Index::Height), - rest: MockLazyDerivedBlockValue { - bitcoin: MockVec::new("metric_btc", Index::Height), - dollars: Some(MockVec::new("metric_usd", Index::Height)), - }, - }; - - let tree = value.to_tree_node(); - - // rename="sats" keeps the leaf directly as sats: Leaf - // flatten on rest lifts bitcoin, dollars as direct leaves - // Result: { sats: Leaf, bitcoin: Leaf, dollars: Leaf } - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 3, "Expected sats, bitcoin, dollars. Got: {:?}", map.keys().collect::>()); - assert!(matches!(map.get("sats"), Some(TreeNode::Leaf(_)))); - assert!(matches!(map.get("bitcoin"), Some(TreeNode::Leaf(_)))); - assert!(matches!(map.get("dollars"), Some(TreeNode::Leaf(_)))); - } - _ => panic!("Expected branch"), - } -} - -#[test] -fn lazy_block_value_without_dollars() { - let value = MockLazyBlockValue { - sats: MockVec::new("metric", Index::Height), - rest: MockLazyDerivedBlockValue { - bitcoin: MockVec::new("metric_btc", Index::Height), - dollars: None, - }, - }; - - let tree = value.to_tree_node(); - - // Expected: { sats: Leaf, bitcoin: Leaf } (no dollars) - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 2); - assert!(map.contains_key("sats")); - assert!(map.contains_key("bitcoin")); - assert!(!map.contains_key("dollars")); - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 2: DerivedDateLast pattern (merge collapses to Leaf) -// ============================================================================ -// DerivedDateLast (merge): -// - weekindex: LazyLast with wrap="last" -// - monthindex: LazyLast with wrap="last" -// - yearindex: LazyLast with wrap="last" -// All produce { last: Leaf } → merge collapses to single Leaf - -#[derive(Traversable)] -#[traversable(wrap = "last")] -struct MockLazyLast(MockVec); - -#[derive(Traversable)] -#[traversable(merge)] -struct MockDerivedDateLast { - pub weekindex: MockLazyLast, - pub monthindex: MockLazyLast, - pub yearindex: MockLazyLast, -} - -#[test] -fn derived_date_last_collapses_to_leaf() { - let value = MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric", Index::MonthIndex)), - yearindex: MockLazyLast(MockVec::new("metric", Index::YearIndex)), - }; - - let tree = value.to_tree_node(); - - // All fields produce { last: Leaf } with same metric name - // Merge lifts all "last" keys → same name → collapses to single Leaf - match &tree { - TreeNode::Leaf(leaf) => { - assert_eq!(leaf.name(), "metric"); - let indexes = leaf.indexes(); - assert!(indexes.contains(&Index::WeekIndex)); - assert!(indexes.contains(&Index::MonthIndex)); - assert!(indexes.contains(&Index::YearIndex)); - } - TreeNode::Branch(map) => { - panic!("Expected Leaf, got Branch: {:?}", map.keys().collect::>()); - } - } -} - -// ============================================================================ -// Case 3: ComputedDateLast pattern (base + collapsed rest) -// ============================================================================ -// ComputedDateLast (merge): -// - dateindex: wrap="base" -// - rest: DerivedDateLast with flatten → collapses to Leaf -// If all same metric name → collapses to single Leaf - -#[derive(Traversable)] -#[traversable(merge)] -struct MockComputedDateLast { - #[traversable(wrap = "base")] - pub dateindex: MockVec, - #[traversable(flatten)] - pub rest: MockDerivedDateLast, -} - -#[test] -fn computed_date_last_collapses_to_leaf() { - let value = MockComputedDateLast { - dateindex: MockVec::new("metric", Index::DateIndex), - rest: MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric", Index::MonthIndex)), - yearindex: MockLazyLast(MockVec::new("metric", Index::YearIndex)), - }, - }; - - let tree = value.to_tree_node(); - - // dateindex produces { base: Leaf("metric", DateIndex) } - // rest (flatten) produces Leaf("metric", Week+Month+Year) → inserted as "rest" key - // All same metric name → collapses to single Leaf - match &tree { - TreeNode::Leaf(leaf) => { - assert_eq!(leaf.name(), "metric"); - let indexes = leaf.indexes(); - assert!(indexes.contains(&Index::DateIndex)); - assert!(indexes.contains(&Index::WeekIndex)); - assert!(indexes.contains(&Index::MonthIndex)); - assert!(indexes.contains(&Index::YearIndex)); - } - TreeNode::Branch(map) => { - panic!("Expected Leaf, got Branch: {:?}", map.keys().collect::>()); - } - } -} - -// ============================================================================ -// Case 4: ValueDerivedDateLast pattern (denomination siblings) -// ============================================================================ -// ValueDerivedDateLast (no merge): -// - sats: DerivedDateLast (merge) → Leaf -// - bitcoin: LazyDateLast (merge) → Leaf -// - dollars: Option> (merge) → Leaf - -#[derive(Traversable)] -struct MockValueDerivedDateLast { - pub sats: MockDerivedDateLast, - pub bitcoin: MockDerivedDateLast, - pub dollars: Option, -} - -#[test] -fn value_derived_date_last_denomination_leaves() { - let value = MockValueDerivedDateLast { - sats: MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric", Index::MonthIndex)), - yearindex: MockLazyLast(MockVec::new("metric", Index::YearIndex)), - }, - bitcoin: MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric_btc", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric_btc", Index::MonthIndex)), - yearindex: MockLazyLast(MockVec::new("metric_btc", Index::YearIndex)), - }, - dollars: Some(MockComputedDateLast { - dateindex: MockVec::new("metric_usd", Index::DateIndex), - rest: MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric_usd", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric_usd", Index::MonthIndex)), - yearindex: MockLazyLast(MockVec::new("metric_usd", Index::YearIndex)), - }, - }), - }; - - let tree = value.to_tree_node(); - - // Each inner type has merge → collapses to Leaf - // Outer has no merge → stays as Branch with denomination keys - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 3); - - // Each denomination is a collapsed Leaf - match map.get("sats") { - Some(TreeNode::Leaf(l)) => assert_eq!(l.name(), "metric"), - _ => panic!("Expected sats to be Leaf"), - } - match map.get("bitcoin") { - Some(TreeNode::Leaf(l)) => assert_eq!(l.name(), "metric_btc"), - _ => panic!("Expected bitcoin to be Leaf"), - } - match map.get("dollars") { - Some(TreeNode::Leaf(l)) => assert_eq!(l.name(), "metric_usd"), - _ => panic!("Expected dollars to be Leaf"), - } - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 5: SumCum pattern (sum + cumulative leaves) -// ============================================================================ -// SumCum produces { sum: Leaf, cumulative: Leaf } via wrap attributes - -#[derive(Traversable)] -#[traversable(wrap = "sum")] -struct MockSumVec(MockVec); - -#[derive(Traversable)] -#[traversable(wrap = "cumulative")] -struct MockCumulativeVec(MockVec); - -#[derive(Traversable)] -#[traversable(merge)] -struct MockSumCum { - pub sum: MockSumVec, - pub cumulative: MockCumulativeVec, -} - -#[test] -fn sum_cum_produces_two_leaves() { - let value = MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::DateIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::DateIndex)), - }; - - let tree = value.to_tree_node(); - - // { sum: Leaf, cumulative: Leaf } - different metric names, no collapse - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 2); - assert_eq!(get_leaf_name(map.get("sum").unwrap()), Some("metric_sum")); - assert_eq!(get_leaf_name(map.get("cumulative").unwrap()), Some("metric_cumulative")); - } - _ => panic!("Expected branch with sum and cumulative"), - } -} - -// ============================================================================ -// Case 6: DerivedDateSumCum pattern (multiple time periods merge) -// ============================================================================ -// DerivedDateSumCum (merge): -// - weekindex: SumCum → { sum: Leaf, cumulative: Leaf } -// - monthindex: SumCum → { sum: Leaf, cumulative: Leaf } -// Merge lifts all → merges same keys - -#[derive(Traversable)] -#[traversable(merge)] -struct MockDerivedDateSumCum { - pub weekindex: MockSumCum, - pub monthindex: MockSumCum, -} - -#[test] -fn derived_date_sum_cum_merges_time_periods() { - let value = MockDerivedDateSumCum { - weekindex: MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::WeekIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::WeekIndex)), - }, - monthindex: MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::MonthIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::MonthIndex)), - }, - }; - - let tree = value.to_tree_node(); - - // Each SumCum produces { sum, cumulative } - // Merge lifts from weekindex and monthindex - // Same keys merge → { sum: Leaf(Week+Month), cumulative: Leaf(Week+Month) } - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 2, "Expected sum, cumulative. Got: {:?}", map.keys().collect::>()); - - let sum_indexes = get_leaf_indexes(map.get("sum").unwrap()).unwrap(); - assert!(sum_indexes.contains(&Index::WeekIndex)); - assert!(sum_indexes.contains(&Index::MonthIndex)); - - let cum_indexes = get_leaf_indexes(map.get("cumulative").unwrap()).unwrap(); - assert!(cum_indexes.contains(&Index::WeekIndex)); - assert!(cum_indexes.contains(&Index::MonthIndex)); - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 7: ComputedBlockSumCum pattern (base + rest with flatten) -// ============================================================================ -// ComputedBlockSumCum (merge): -// - height: wrap="base" -// - rest: DerivedComputedBlockSumCum with flatten -// - height_cumulative: CumulativeVec -// - dateindex: SumCum -// - dates: DerivedDateSumCum with flatten -// - difficultyepoch: SumCum - -#[derive(Traversable)] -#[traversable(merge)] -struct MockDerivedComputedBlockSumCum { - pub height_cumulative: MockCumulativeVec, - pub dateindex: MockSumCum, - #[traversable(flatten)] - pub dates: MockDerivedDateSumCum, -} - -#[derive(Traversable)] -#[traversable(merge)] -struct MockComputedBlockSumCum { - #[traversable(wrap = "base")] - pub height: MockVec, - #[traversable(flatten)] - pub rest: MockDerivedComputedBlockSumCum, -} - -#[test] -fn computed_block_sum_cum_base_sum_cumulative() { - let value = MockComputedBlockSumCum { - height: MockVec::new("metric", Index::Height), - rest: MockDerivedComputedBlockSumCum { - height_cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::Height)), - dateindex: MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::DateIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::DateIndex)), - }, - dates: MockDerivedDateSumCum { - weekindex: MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::WeekIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::WeekIndex)), - }, - monthindex: MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::MonthIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::MonthIndex)), - }, - }, - }, - }; - - let tree = value.to_tree_node(); - - // Expected: { base, sum, cumulative } - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 3, "Expected base, sum, cumulative. Got: {:?}", map.keys().collect::>()); - - // base: only Height - let base_indexes = get_leaf_indexes(map.get("base").unwrap()).unwrap(); - assert!(base_indexes.contains(&Index::Height)); - assert_eq!(base_indexes.len(), 1); - - // sum: DateIndex, WeekIndex, MonthIndex (NOT Height) - let sum_indexes = get_leaf_indexes(map.get("sum").unwrap()).unwrap(); - assert!(!sum_indexes.contains(&Index::Height)); - assert!(sum_indexes.contains(&Index::DateIndex)); - assert!(sum_indexes.contains(&Index::WeekIndex)); - assert!(sum_indexes.contains(&Index::MonthIndex)); - - // cumulative: Height + all time indexes - let cum_indexes = get_leaf_indexes(map.get("cumulative").unwrap()).unwrap(); - assert!(cum_indexes.contains(&Index::Height)); - assert!(cum_indexes.contains(&Index::DateIndex)); - assert!(cum_indexes.contains(&Index::WeekIndex)); - assert!(cum_indexes.contains(&Index::MonthIndex)); - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 8: ValueBlockSumCum pattern (denominations with nested aggregations) -// ============================================================================ -// ValueBlockSumCum (no merge): -// - sats: ComputedBlockSumCum (merge) → { base, sum, cumulative } -// - bitcoin: ComputedBlockSumCum (merge) → { base, sum, cumulative } -// - dollars: Option (merge) → { base, sum, cumulative } - -#[derive(Traversable)] -struct MockValueBlockSumCum { - pub sats: MockComputedBlockSumCum, - pub bitcoin: MockComputedBlockSumCum, - pub dollars: Option, -} - -#[test] -fn value_block_sum_cum_denominations_with_aggregations() { - let make_computed = |prefix: &str| MockComputedBlockSumCum { - height: MockVec::new(prefix, Index::Height), - rest: MockDerivedComputedBlockSumCum { - height_cumulative: MockCumulativeVec(MockVec::new(&format!("{prefix}_cumulative"), Index::Height)), - dateindex: MockSumCum { - sum: MockSumVec(MockVec::new(&format!("{prefix}_sum"), Index::DateIndex)), - cumulative: MockCumulativeVec(MockVec::new(&format!("{prefix}_cumulative"), Index::DateIndex)), - }, - dates: MockDerivedDateSumCum { - weekindex: MockSumCum { - sum: MockSumVec(MockVec::new(&format!("{prefix}_sum"), Index::WeekIndex)), - cumulative: MockCumulativeVec(MockVec::new(&format!("{prefix}_cumulative"), Index::WeekIndex)), - }, - monthindex: MockSumCum { - sum: MockSumVec(MockVec::new(&format!("{prefix}_sum"), Index::MonthIndex)), - cumulative: MockCumulativeVec(MockVec::new(&format!("{prefix}_cumulative"), Index::MonthIndex)), - }, - }, - }, - }; - - let value = MockValueBlockSumCum { - sats: make_computed("metric"), - bitcoin: make_computed("metric_btc"), - dollars: Some(make_computed("metric_usd")), - }; - - let tree = value.to_tree_node(); - - // Outer has no merge → denominations as branches - // Each inner has merge → { base, sum, cumulative } - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 3); - - for denom in ["sats", "bitcoin", "dollars"] { - match map.get(denom) { - Some(TreeNode::Branch(inner)) => { - assert_eq!(inner.len(), 3, "Expected base, sum, cumulative for {denom}"); - assert!(inner.contains_key("base")); - assert!(inner.contains_key("sum")); - assert!(inner.contains_key("cumulative")); - } - _ => panic!("Expected branch for {denom}"), - } - } - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 9: Flatten of collapsed Leaf (edge case) -// ============================================================================ -// When flatten encounters a Leaf (from collapsed inner type), -// it inserts with field name as key. Merge on outer lifts wrapped values. - -#[derive(Traversable)] -#[traversable(merge)] -struct MockFlattenCollapsedLeaf { - #[traversable(wrap = "base")] - pub primary: MockVec, - #[traversable(flatten)] - pub collapsed: MockDerivedDateLast, // This collapses to Leaf -} - -#[test] -fn flatten_collapsed_leaf_uses_field_name() { - let value = MockFlattenCollapsedLeaf { - primary: MockVec::new("metric", Index::DateIndex), - collapsed: MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("other_metric", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("other_metric", Index::MonthIndex)), - yearindex: MockLazyLast(MockVec::new("other_metric", Index::YearIndex)), - }, - }; - - let tree = value.to_tree_node(); - - // With merge on outer: - // - primary with wrap="base" → { base: Leaf } → merge lifts to base: Leaf - // - collapsed (already merged to Leaf) → flatten inserts as "collapsed": Leaf - // Result: { base: Leaf, collapsed: Leaf } - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 2, "Expected base, collapsed. Got: {:?}", map.keys().collect::>()); - assert!(map.contains_key("base")); - assert!(map.contains_key("collapsed")); - - // Verify collapsed is a Leaf with the right indexes - match map.get("collapsed") { - Some(TreeNode::Leaf(l)) => { - assert_eq!(l.name(), "other_metric"); - let indexes = l.indexes(); - assert!(indexes.contains(&Index::WeekIndex)); - assert!(indexes.contains(&Index::MonthIndex)); - assert!(indexes.contains(&Index::YearIndex)); - } - _ => panic!("Expected collapsed to be Leaf"), - } - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 10: Rename attribute -// ============================================================================ - -#[derive(Traversable)] -struct MockRename { - #[traversable(rename = "custom_name")] - pub field: MockVec, -} - -#[test] -fn rename_attribute_changes_key() { - let value = MockRename { - field: MockVec::new("metric", Index::Height), - }; - - let tree = value.to_tree_node(); - - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 1); - assert!(map.contains_key("custom_name")); - assert!(!map.contains_key("field")); - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 11: Skip attribute -// ============================================================================ - -#[derive(Traversable)] -struct MockSkip { - pub included: MockVec, - #[traversable(skip)] - pub skipped: MockVec, -} - -#[test] -fn skip_attribute_excludes_field() { - let value = MockSkip { - included: MockVec::new("metric", Index::Height), - skipped: MockVec::new("should_not_appear", Index::Height), - }; - - let tree = value.to_tree_node(); - - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 1); - assert!(map.contains_key("included")); - assert!(!map.contains_key("skipped")); - } - _ => panic!("Expected branch"), - } -} - -// ============================================================================ -// Case 12: Transparent attribute (single-field delegation) -// ============================================================================ - -#[derive(Traversable)] -#[traversable(transparent)] -struct MockTransparent { - pub inner: MockVec, -} - -#[test] -fn transparent_delegates_to_inner() { - let value = MockTransparent { - inner: MockVec::new("metric", Index::Height), - }; - - let tree = value.to_tree_node(); - - // Should produce Leaf directly, not Branch { inner: Leaf } - match &tree { - TreeNode::Leaf(l) => { - assert_eq!(l.name(), "metric"); - } - _ => panic!("Expected Leaf (transparent delegation)"), - } -} - -// ============================================================================ -// Case 13: ValueBlockFull pattern (Full stats with multiple denominations) -// ============================================================================ -// ValueBlockFull pattern: -// - sats: ComputedBlockFull (merge) -// - bitcoin: LazyBlockFull (merge) -// - dollars: Option> (merge) -// -// Each ComputedBlockFull (merge): -// - height: wrap="base" -// - rest: DerivedComputedBlockFull (merge, flatten) -// - height_cumulative: CumulativeVec -// - dateindex: Full (distribution + sum_cum) -// - dates: DerivedDateFull (merge, flatten) -// - difficultyepoch: LazyFull - -// Mock for wrap="avg" -#[derive(Traversable)] -#[traversable(wrap = "avg")] -struct MockAvgVec(MockVec); - -// Mock for wrap="min" -#[derive(Traversable)] -#[traversable(wrap = "min")] -struct MockMinVec(MockVec); - -// Mock for wrap="max" -#[derive(Traversable)] -#[traversable(wrap = "max")] -struct MockMaxVec(MockVec); - -// Mock for wrap="median" -#[derive(Traversable)] -#[traversable(wrap = "median")] -struct MockMedianVec(MockVec); - -// MinMax struct -#[derive(Traversable)] -struct MockMinMax { - #[traversable(flatten)] - pub min: MockMinVec, - #[traversable(flatten)] - pub max: MockMaxVec, -} - -// Percentiles struct (simplified to just median for test) -#[derive(Traversable)] -struct MockPercentiles { - pub median: MockMedianVec, -} - -// Distribution = average + minmax + percentiles -#[derive(Traversable)] -struct MockDistribution { - pub average: MockAvgVec, - #[traversable(flatten)] - pub minmax: MockMinMax, - pub percentiles: MockPercentiles, -} - -// Full = Distribution + SumCum -#[derive(Traversable)] -struct MockFull { - pub distribution: MockDistribution, - pub sum_cum: MockSumCum, -} - -// LazyFull - all flattened -#[derive(Traversable)] -struct MockLazyFull { - #[traversable(flatten)] - pub avg: MockAvgVec, - #[traversable(flatten)] - pub min: MockMinVec, - #[traversable(flatten)] - pub max: MockMaxVec, - #[traversable(flatten)] - pub sum: MockSumVec, - #[traversable(flatten)] - pub cumulative: MockCumulativeVec, -} - -// DerivedDateFull (merge) - time periods with LazyFull -#[derive(Traversable)] -#[traversable(merge)] -struct MockDerivedDateFull { - pub weekindex: MockLazyFull, - pub monthindex: MockLazyFull, -} - -// DerivedComputedBlockFull (merge) -#[derive(Traversable)] -#[traversable(merge)] -struct MockDerivedComputedBlockFull { - pub height_cumulative: MockCumulativeVec, - pub dateindex: MockFull, - #[traversable(flatten)] - pub dates: MockDerivedDateFull, - pub difficultyepoch: MockLazyFull, -} - -// ComputedBlockFull (merge) -#[derive(Traversable)] -#[traversable(merge)] -struct MockComputedBlockFull { - #[traversable(wrap = "base")] - pub height: MockVec, - #[traversable(flatten)] - pub rest: MockDerivedComputedBlockFull, -} - -// ValueBlockFull - no merge (denominations as branches) -#[derive(Traversable)] -struct MockValueBlockFull { - pub sats: MockComputedBlockFull, - pub bitcoin: MockComputedBlockFull, - pub dollars: Option, -} - -fn make_lazy_full(name: &str, index: Index) -> MockLazyFull { - MockLazyFull { - avg: MockAvgVec(MockVec::new(&format!("{name}_avg"), index)), - min: MockMinVec(MockVec::new(&format!("{name}_min"), index)), - max: MockMaxVec(MockVec::new(&format!("{name}_max"), index)), - sum: MockSumVec(MockVec::new(&format!("{name}_sum"), index)), - cumulative: MockCumulativeVec(MockVec::new(&format!("{name}_cumulative"), index)), - } -} - -fn make_computed_block_full(name: &str) -> MockComputedBlockFull { - MockComputedBlockFull { - height: MockVec::new(name, Index::Height), - rest: MockDerivedComputedBlockFull { - height_cumulative: MockCumulativeVec(MockVec::new(&format!("{name}_cumulative"), Index::Height)), - dateindex: MockFull { - distribution: MockDistribution { - average: MockAvgVec(MockVec::new(&format!("{name}_avg"), Index::DateIndex)), - minmax: MockMinMax { - min: MockMinVec(MockVec::new(&format!("{name}_min"), Index::DateIndex)), - max: MockMaxVec(MockVec::new(&format!("{name}_max"), Index::DateIndex)), - }, - percentiles: MockPercentiles { - median: MockMedianVec(MockVec::new(&format!("{name}_median"), Index::DateIndex)), - }, - }, - sum_cum: MockSumCum { - sum: MockSumVec(MockVec::new(&format!("{name}_sum"), Index::DateIndex)), - cumulative: MockCumulativeVec(MockVec::new(&format!("{name}_cumulative"), Index::DateIndex)), - }, - }, - dates: MockDerivedDateFull { - weekindex: make_lazy_full(name, Index::WeekIndex), - monthindex: make_lazy_full(name, Index::MonthIndex), - }, - difficultyepoch: make_lazy_full(name, Index::DifficultyEpoch), - }, - } -} - -#[test] -fn value_block_full_denominations_as_branches() { - let value = MockValueBlockFull { - sats: make_computed_block_full("metric"), - bitcoin: make_computed_block_full("metric_btc"), - dollars: Some(make_computed_block_full("metric_usd")), - }; - - let tree = value.to_tree_node(); - - // Without merge on outer, denominations are branches - match &tree { - TreeNode::Branch(map) => { - assert_eq!(map.len(), 3, "Expected sats, bitcoin, dollars"); - assert!(map.contains_key("sats")); - assert!(map.contains_key("bitcoin")); - assert!(map.contains_key("dollars")); - - // Each denomination should have deeply merged inner structure - // The merge recursively flattens: dateindex, difficultyepoch become flat metric keys - for denom in ["sats", "bitcoin", "dollars"] { - match map.get(denom) { - Some(TreeNode::Branch(inner)) => { - // Inner merge produces flat structure: - // base, cumulative, avg, average, min, max, sum, minmax, percentiles - assert!(inner.contains_key("base"), "{denom} missing base"); - assert!(inner.contains_key("cumulative"), "{denom} missing cumulative"); - assert!(inner.contains_key("avg"), "{denom} missing avg"); - assert!(inner.contains_key("sum"), "{denom} missing sum"); - // dateindex and difficultyepoch are merged in, not separate branches - assert!(!inner.contains_key("dateindex"), "{denom} should NOT have dateindex branch"); - assert!(!inner.contains_key("difficultyepoch"), "{denom} should NOT have difficultyepoch branch"); - } - _ => panic!("Expected branch for {denom}"), - } - } - } - _ => panic!("Expected branch at top level"), - } -} - diff --git a/crates/brk_traversable/tests/traversable/common.rs b/crates/brk_traversable/tests/traversable/common.rs deleted file mode 100644 index 5d00d8e3b..000000000 --- a/crates/brk_traversable/tests/traversable/common.rs +++ /dev/null @@ -1,162 +0,0 @@ -//! Common mock types and helpers for traversable tests. - -use std::collections::BTreeSet; - -use brk_traversable::{Index, MetricLeaf, MetricLeafWithSchema, Traversable, TreeNode}; -use brk_traversable_derive::Traversable; - -/// Mock leaf vec that produces a Leaf node with given name and index. -/// This simulates the behavior of EagerVec>. -pub struct MockVec { - pub name: String, - pub index: Index, -} - -impl MockVec { - pub fn new(name: &str, index: Index) -> Self { - Self { - name: name.to_string(), - index, - } - } -} - -impl Traversable for MockVec { - fn to_tree_node(&self) -> TreeNode { - TreeNode::Leaf(MetricLeafWithSchema::new( - MetricLeaf::new( - self.name.clone(), - "MockType".to_string(), - BTreeSet::from([self.index]), - ), - serde_json::Value::Null, - )) - } - - fn iter_any_exportable(&self) -> impl Iterator { - std::iter::empty() - } -} - -// ============================================================================ -// Transparent Vec Types (matching real SumVec, CumulativeVec, MinVec, etc.) -// ============================================================================ -// All real Vec types are now transparent - they delegate directly to inner. - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockSumVec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockCumulativeVec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockMinVec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockMaxVec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockAverageVec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockMedianVec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockPct10Vec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockPct25Vec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockPct75Vec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockPct90Vec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLastVec(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockFirstVec(pub MockVec); - -// ============================================================================ -// Transparent Lazy Types (matching real LazySum, LazyCumulative, etc.) -// ============================================================================ -// All real Lazy* types are now transparent. - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLazySum(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLazyCumulative(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLazyMin(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLazyMax(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLazyAverage(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLazyFirst(pub MockVec); - -#[derive(Traversable)] -#[traversable(transparent)] -pub struct MockLazyLast(pub MockVec); - -// ============================================================================ -// Helper functions -// ============================================================================ - -pub fn get_leaf_indexes(node: &TreeNode) -> Option<&BTreeSet> { - match node { - TreeNode::Leaf(l) => Some(l.indexes()), - _ => None, - } -} - -pub fn get_leaf_name(node: &TreeNode) -> Option<&str> { - match node { - TreeNode::Leaf(l) => Some(l.name()), - _ => None, - } -} - -pub fn assert_is_leaf(node: &TreeNode, expected_name: &str) { - match node { - TreeNode::Leaf(l) => assert_eq!(l.name(), expected_name), - TreeNode::Branch(map) => panic!("Expected Leaf, got Branch: {:?}", map.keys().collect::>()), - } -} - -pub fn assert_is_branch_with_keys(node: &TreeNode, expected_keys: &[&str]) { - match node { - TreeNode::Branch(map) => { - for key in expected_keys { - assert!(map.contains_key(*key), "Missing key: {key}"); - } - assert_eq!(map.len(), expected_keys.len(), "Got keys: {:?}", map.keys().collect::>()); - } - TreeNode::Leaf(l) => panic!("Expected Branch, got Leaf: {}", l.name()), - } -} diff --git a/crates/brk_traversable/tests/traversable/computed_types.rs b/crates/brk_traversable/tests/traversable/computed_types.rs deleted file mode 100644 index f98c4c910..000000000 --- a/crates/brk_traversable/tests/traversable/computed_types.rs +++ /dev/null @@ -1,224 +0,0 @@ -//! Tests for Computed types from brk_computer/src/internal/computed/ -//! -//! Computed types combine base vecs with derived aggregations. -//! With merge, all same-key leaves collapse. -//! -//! Expected outputs: -//! - ComputedDateLast -> Leaf (all same name → single leaf) -//! - ComputedBlockSumCum -> { base, sum, cumulative } (with merged indexes) -//! - DerivedComputedBlockSumCum -> { height_cumulative, sum, cumulative } - -use brk_traversable::{Index, Traversable, TreeNode}; -use brk_traversable_derive::Traversable; - -use crate::common::*; -use crate::group_types::MockSumCum; -use crate::lazy_aggregation::MockLazySumCum; -use crate::derived_date::{MockDerivedDateLast, MockDerivedDateSumCum}; - -// ============================================================================ -// ComputedDateLast - Leaf (dateindex + rest collapse to single leaf) -// ============================================================================ - -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockComputedDateLast { - pub dateindex: MockLastVec, // transparent → Leaf - #[traversable(flatten)] - pub rest: MockDerivedDateLast, // merge → Leaf (all same name) -} - -#[test] -fn computed_date_last_collapses_to_leaf() { - let value = MockComputedDateLast { - dateindex: MockLastVec(MockVec::new("metric", Index::DateIndex)), - rest: MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric", Index::MonthIndex)), - quarterindex: MockLazyLast(MockVec::new("metric", Index::QuarterIndex)), - semesterindex: MockLazyLast(MockVec::new("metric", Index::SemesterIndex)), - yearindex: MockLazyLast(MockVec::new("metric", Index::YearIndex)), - decadeindex: MockLazyLast(MockVec::new("metric", Index::DecadeIndex)), - }, - }; - - let tree = value.to_tree_node(); - - // All same metric name → single Leaf with all indexes - match &tree { - TreeNode::Leaf(l) => { - assert_eq!(l.name(), "metric"); - let indexes = l.indexes(); - assert!(indexes.contains(&Index::DateIndex)); - assert!(indexes.contains(&Index::WeekIndex)); - assert!(indexes.contains(&Index::MonthIndex)); - assert!(indexes.contains(&Index::QuarterIndex)); - assert!(indexes.contains(&Index::SemesterIndex)); - assert!(indexes.contains(&Index::YearIndex)); - assert!(indexes.contains(&Index::DecadeIndex)); - assert_eq!(indexes.len(), 7); - } - TreeNode::Branch(map) => { - panic!("Expected Leaf, got Branch: {:?}", map.keys().collect::>()); - } - } -} - -// ============================================================================ -// DerivedComputedBlockSumCum - { height_cumulative, sum, cumulative } -// ============================================================================ - -// For merge to work correctly, all fields produce Branch output that merge will lift. -// height_cumulative is renamed to "cumulative" so it merges with other cumulative leaves. -// NO flatten used - rely entirely on merge to lift and merge same-key leaves. -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockDerivedComputedBlockSumCum { - #[traversable(rename = "cumulative")] // rename to merge with other cumulative leaves - pub height_cumulative: MockCumulativeVec, - pub dateindex: MockSumCum, // produces { sum, cumulative } - merge will lift - pub dates: MockDerivedDateSumCum, // produces { sum, cumulative } - merge will lift - pub difficultyepoch: MockLazySumCum, // produces { sum, cumulative } - merge will lift -} - -#[test] -fn derived_computed_block_sum_cum_merges_all() { - let value = MockDerivedComputedBlockSumCum { - height_cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::Height)), - dateindex: MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::DateIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::DateIndex)), - }, - dates: MockDerivedDateSumCum { - weekindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::WeekIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::WeekIndex)), - }, - monthindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::MonthIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::MonthIndex)), - }, - quarterindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::QuarterIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::QuarterIndex)), - }, - yearindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::YearIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::YearIndex)), - }, - }, - difficultyepoch: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::DifficultyEpoch)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::DifficultyEpoch)), - }, - }; - - let tree = value.to_tree_node(); - - // Debug: print tree structure - println!("Tree: {tree:#?}"); - - // height_cumulative renamed to "cumulative" → merges with other cumulative leaves - // sum merges from dateindex + dates + difficultyepoch - // cumulative merges from height_cumulative (renamed) + dateindex + dates + difficultyepoch - assert_is_branch_with_keys(&tree, &["sum", "cumulative"]); - - if let TreeNode::Branch(map) = &tree { - // sum: DateIndex + Week + Month + Quarter + Year + DifficultyEpoch - let sum_indexes = get_leaf_indexes(map.get("sum").unwrap()).unwrap(); - assert!(sum_indexes.contains(&Index::DateIndex)); - assert!(sum_indexes.contains(&Index::WeekIndex)); - assert!(sum_indexes.contains(&Index::MonthIndex)); - assert!(sum_indexes.contains(&Index::QuarterIndex)); - assert!(sum_indexes.contains(&Index::YearIndex)); - assert!(sum_indexes.contains(&Index::DifficultyEpoch)); - assert_eq!(sum_indexes.len(), 6); - - // cumulative: Height + DateIndex + Week + Month + Quarter + Year + DifficultyEpoch - let cum_indexes = get_leaf_indexes(map.get("cumulative").unwrap()).unwrap(); - assert!(cum_indexes.contains(&Index::Height), "cumulative SHOULD have Height from renamed height_cumulative"); - assert!(cum_indexes.contains(&Index::DateIndex)); - assert!(cum_indexes.contains(&Index::WeekIndex)); - assert!(cum_indexes.contains(&Index::MonthIndex)); - assert!(cum_indexes.contains(&Index::QuarterIndex)); - assert!(cum_indexes.contains(&Index::YearIndex)); - assert!(cum_indexes.contains(&Index::DifficultyEpoch)); - assert_eq!(cum_indexes.len(), 7); - } -} - -// ============================================================================ -// ComputedBlockSumCum - { base, sum, cumulative } -// ============================================================================ - -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockComputedBlockSumCum { - #[traversable(wrap = "base")] - pub height: MockSumVec, // wrap="base" → { base: Leaf } - pub rest: MockDerivedComputedBlockSumCum, // merge will lift from rest -} - -#[test] -fn computed_block_sum_cum_produces_base_sum_cumulative() { - let value = MockComputedBlockSumCum { - height: MockSumVec(MockVec::new("metric", Index::Height)), - rest: MockDerivedComputedBlockSumCum { - height_cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::Height)), - dateindex: MockSumCum { - sum: MockSumVec(MockVec::new("metric_sum", Index::DateIndex)), - cumulative: MockCumulativeVec(MockVec::new("metric_cumulative", Index::DateIndex)), - }, - dates: MockDerivedDateSumCum { - weekindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::WeekIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::WeekIndex)), - }, - monthindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::MonthIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::MonthIndex)), - }, - quarterindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::QuarterIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::QuarterIndex)), - }, - yearindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::YearIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::YearIndex)), - }, - }, - difficultyepoch: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::DifficultyEpoch)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::DifficultyEpoch)), - }, - }, - }; - - let tree = value.to_tree_node(); - - // base: Height only (from wrap="base") - // sum: all indexes except Height - // cumulative: all indexes INCLUDING Height (from renamed height_cumulative) - assert_is_branch_with_keys(&tree, &["base", "sum", "cumulative"]); - - if let TreeNode::Branch(map) = &tree { - // base: Height only - let base_indexes = get_leaf_indexes(map.get("base").unwrap()).unwrap(); - assert!(base_indexes.contains(&Index::Height)); - assert_eq!(base_indexes.len(), 1); - - // sum: DateIndex + all dates + DifficultyEpoch (NOT Height) - let sum_indexes = get_leaf_indexes(map.get("sum").unwrap()).unwrap(); - assert!(!sum_indexes.contains(&Index::Height), "sum should NOT have Height"); - assert!(sum_indexes.contains(&Index::DateIndex)); - assert!(sum_indexes.contains(&Index::DifficultyEpoch)); - assert_eq!(sum_indexes.len(), 6); - - // cumulative: Height + DateIndex + all dates + DifficultyEpoch - let cum_indexes = get_leaf_indexes(map.get("cumulative").unwrap()).unwrap(); - assert!(cum_indexes.contains(&Index::Height), "cumulative SHOULD have Height"); - assert!(cum_indexes.contains(&Index::DateIndex)); - assert!(cum_indexes.contains(&Index::DifficultyEpoch)); - assert_eq!(cum_indexes.len(), 7); - } -} diff --git a/crates/brk_traversable/tests/traversable/derived_date.rs b/crates/brk_traversable/tests/traversable/derived_date.rs deleted file mode 100644 index 43ab2cdef..000000000 --- a/crates/brk_traversable/tests/traversable/derived_date.rs +++ /dev/null @@ -1,172 +0,0 @@ -//! Tests for Derived Date types from brk_computer/src/internal/derived/date/ -//! -//! Derived Date types aggregate metrics across multiple time periods (week, month, etc.). -//! With merge, all same-key leaves collapse across time periods. -//! -//! Expected outputs: -//! - DerivedDateLast -> Leaf (all indexes merged) -//! - DerivedDateSumCum -> { sum: Leaf(all), cumulative: Leaf(all) } -//! - DerivedDateFull -> { average, min, max, sum, cumulative } (all with merged indexes) -//! - etc. - -use brk_traversable::{Index, Traversable, TreeNode}; -use brk_traversable_derive::Traversable; - -use crate::common::*; -use crate::lazy_aggregation::{MockLazyFull, MockLazySumCum}; - -// ============================================================================ -// DerivedDateLast - Leaf (all same name → single leaf with all indexes) -// ============================================================================ - -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockDerivedDateLast { - pub weekindex: MockLazyLast, - pub monthindex: MockLazyLast, - pub quarterindex: MockLazyLast, - pub semesterindex: MockLazyLast, - pub yearindex: MockLazyLast, - pub decadeindex: MockLazyLast, -} - -#[test] -fn derived_date_last_collapses_to_leaf() { - let value = MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric", Index::MonthIndex)), - quarterindex: MockLazyLast(MockVec::new("metric", Index::QuarterIndex)), - semesterindex: MockLazyLast(MockVec::new("metric", Index::SemesterIndex)), - yearindex: MockLazyLast(MockVec::new("metric", Index::YearIndex)), - decadeindex: MockLazyLast(MockVec::new("metric", Index::DecadeIndex)), - }; - - let tree = value.to_tree_node(); - - // All same metric name → collapses to single Leaf with all indexes - match &tree { - TreeNode::Leaf(l) => { - assert_eq!(l.name(), "metric"); - let indexes = l.indexes(); - assert!(indexes.contains(&Index::WeekIndex)); - assert!(indexes.contains(&Index::MonthIndex)); - assert!(indexes.contains(&Index::QuarterIndex)); - assert!(indexes.contains(&Index::SemesterIndex)); - assert!(indexes.contains(&Index::YearIndex)); - assert!(indexes.contains(&Index::DecadeIndex)); - assert_eq!(indexes.len(), 6); - } - TreeNode::Branch(map) => { - panic!("Expected Leaf, got Branch: {:?}", map.keys().collect::>()); - } - } -} - -// ============================================================================ -// DerivedDateSumCum - { sum: Leaf(all), cumulative: Leaf(all) } -// ============================================================================ - -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockDerivedDateSumCum { - pub weekindex: MockLazySumCum, - pub monthindex: MockLazySumCum, - pub quarterindex: MockLazySumCum, - pub yearindex: MockLazySumCum, -} - -#[test] -fn derived_date_sum_cum_merges_all_time_periods() { - let value = MockDerivedDateSumCum { - weekindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::WeekIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::WeekIndex)), - }, - monthindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::MonthIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::MonthIndex)), - }, - quarterindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::QuarterIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::QuarterIndex)), - }, - yearindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::YearIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::YearIndex)), - }, - }; - - let tree = value.to_tree_node(); - - // Merge lifts from all time periods → { sum: Leaf(all), cumulative: Leaf(all) } - assert_is_branch_with_keys(&tree, &["sum", "cumulative"]); - - if let TreeNode::Branch(map) = &tree { - // sum should have all 4 indexes - let sum_indexes = get_leaf_indexes(map.get("sum").unwrap()).unwrap(); - assert!(sum_indexes.contains(&Index::WeekIndex)); - assert!(sum_indexes.contains(&Index::MonthIndex)); - assert!(sum_indexes.contains(&Index::QuarterIndex)); - assert!(sum_indexes.contains(&Index::YearIndex)); - assert_eq!(sum_indexes.len(), 4); - - // cumulative should have all 4 indexes - let cum_indexes = get_leaf_indexes(map.get("cumulative").unwrap()).unwrap(); - assert_eq!(cum_indexes.len(), 4); - } -} - -// ============================================================================ -// DerivedDateFull - { average, min, max, sum, cumulative } (all merged) -// ============================================================================ - -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockDerivedDateFull { - pub weekindex: MockLazyFull, - pub monthindex: MockLazyFull, - pub yearindex: MockLazyFull, -} - -#[test] -fn derived_date_full_merges_all_stats() { - let value = MockDerivedDateFull { - weekindex: MockLazyFull { - average: MockLazyAverage(MockVec::new("m_avg", Index::WeekIndex)), - min: MockLazyMin(MockVec::new("m_min", Index::WeekIndex)), - max: MockLazyMax(MockVec::new("m_max", Index::WeekIndex)), - sum: MockLazySum(MockVec::new("m_sum", Index::WeekIndex)), - cumulative: MockLazyCumulative(MockVec::new("m_cum", Index::WeekIndex)), - }, - monthindex: MockLazyFull { - average: MockLazyAverage(MockVec::new("m_avg", Index::MonthIndex)), - min: MockLazyMin(MockVec::new("m_min", Index::MonthIndex)), - max: MockLazyMax(MockVec::new("m_max", Index::MonthIndex)), - sum: MockLazySum(MockVec::new("m_sum", Index::MonthIndex)), - cumulative: MockLazyCumulative(MockVec::new("m_cum", Index::MonthIndex)), - }, - yearindex: MockLazyFull { - average: MockLazyAverage(MockVec::new("m_avg", Index::YearIndex)), - min: MockLazyMin(MockVec::new("m_min", Index::YearIndex)), - max: MockLazyMax(MockVec::new("m_max", Index::YearIndex)), - sum: MockLazySum(MockVec::new("m_sum", Index::YearIndex)), - cumulative: MockLazyCumulative(MockVec::new("m_cum", Index::YearIndex)), - }, - }; - - let tree = value.to_tree_node(); - - // All same keys merge → { average, min, max, sum, cumulative } - assert_is_branch_with_keys(&tree, &["average", "min", "max", "sum", "cumulative"]); - - if let TreeNode::Branch(map) = &tree { - // Each should have 3 indexes (week, month, year) - for key in ["average", "min", "max", "sum", "cumulative"] { - let indexes = get_leaf_indexes(map.get(key).unwrap()).unwrap(); - assert_eq!(indexes.len(), 3, "{key} should have 3 indexes"); - assert!(indexes.contains(&Index::WeekIndex)); - assert!(indexes.contains(&Index::MonthIndex)); - assert!(indexes.contains(&Index::YearIndex)); - } - } -} diff --git a/crates/brk_traversable/tests/traversable/group_types.rs b/crates/brk_traversable/tests/traversable/group_types.rs deleted file mode 100644 index 68187e557..000000000 --- a/crates/brk_traversable/tests/traversable/group_types.rs +++ /dev/null @@ -1,239 +0,0 @@ -//! Tests for Group types from brk_computer/src/internal/group/ -//! -//! Group types aggregate multiple Vec types into logical groupings. -//! Expected outputs (flat structures): -//! - MinMax -> { min: Leaf, max: Leaf } -//! - SumCum -> { sum: Leaf, cumulative: Leaf } -//! - Percentiles -> { pct10, pct25, median, pct75, pct90 } -//! - Distribution -> { average, min, max, percentiles: {...} } -//! - Full -> { average, min, max, percentiles, sum, cumulative } -//! - Stats -> { sum, cumulative, average, min, max } -//! - MinMaxAverage -> { average, min, max } - -use brk_traversable::{Index, Traversable, TreeNode}; -use brk_traversable_derive::Traversable; - -use crate::common::*; - -// ============================================================================ -// MinMax - { min: Leaf, max: Leaf } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockMinMax { - #[traversable(flatten)] - pub min: MockMinVec, - #[traversable(flatten)] - pub max: MockMaxVec, -} - -#[test] -fn min_max_produces_two_leaves() { - let value = MockMinMax { - min: MockMinVec(MockVec::new("metric", Index::Height)), - max: MockMaxVec(MockVec::new("metric", Index::Height)), - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["min", "max"]); -} - -// ============================================================================ -// SumCum - { sum: Leaf, cumulative: Leaf } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockSumCum { - #[traversable(flatten)] - pub sum: MockSumVec, - #[traversable(flatten)] - pub cumulative: MockCumulativeVec, -} - -#[test] -fn sum_cum_produces_two_leaves() { - let value = MockSumCum { - sum: MockSumVec(MockVec::new("metric", Index::Height)), - cumulative: MockCumulativeVec(MockVec::new("metric", Index::Height)), - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["sum", "cumulative"]); -} - -// ============================================================================ -// Percentiles - { pct10, pct25, median, pct75, pct90 } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockPercentiles { - pub pct10: MockPct10Vec, - pub pct25: MockPct25Vec, - pub median: MockMedianVec, - pub pct75: MockPct75Vec, - pub pct90: MockPct90Vec, -} - -#[test] -fn percentiles_produces_five_leaves() { - let value = MockPercentiles { - pct10: MockPct10Vec(MockVec::new("m", Index::Height)), - pct25: MockPct25Vec(MockVec::new("m", Index::Height)), - median: MockMedianVec(MockVec::new("m", Index::Height)), - pct75: MockPct75Vec(MockVec::new("m", Index::Height)), - pct90: MockPct90Vec(MockVec::new("m", Index::Height)), - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["pct10", "pct25", "median", "pct75", "pct90"]); -} - -// ============================================================================ -// Distribution - { average, min, max, percentiles: {...} } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockDistribution { - #[traversable(flatten)] - pub average: MockAverageVec, - #[traversable(flatten)] - pub minmax: MockMinMax, - pub percentiles: MockPercentiles, -} - -#[test] -fn distribution_flattens_average_and_minmax() { - let value = MockDistribution { - average: MockAverageVec(MockVec::new("m", Index::Height)), - minmax: MockMinMax { - min: MockMinVec(MockVec::new("m", Index::Height)), - max: MockMaxVec(MockVec::new("m", Index::Height)), - }, - percentiles: MockPercentiles { - pct10: MockPct10Vec(MockVec::new("m", Index::Height)), - pct25: MockPct25Vec(MockVec::new("m", Index::Height)), - median: MockMedianVec(MockVec::new("m", Index::Height)), - pct75: MockPct75Vec(MockVec::new("m", Index::Height)), - pct90: MockPct90Vec(MockVec::new("m", Index::Height)), - }, - }; - - let tree = value.to_tree_node(); - - // average and minmax are flattened, percentiles stays grouped - assert_is_branch_with_keys(&tree, &["average", "min", "max", "percentiles"]); - - // Verify percentiles is a branch with 5 keys - if let TreeNode::Branch(map) = &tree { - assert_is_branch_with_keys( - map.get("percentiles").unwrap(), - &["pct10", "pct25", "median", "pct75", "pct90"], - ); - } -} - -// ============================================================================ -// Full - { average, min, max, percentiles, sum, cumulative } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockFull { - #[traversable(flatten)] - pub distribution: MockDistribution, - #[traversable(flatten)] - pub sum_cum: MockSumCum, -} - -#[test] -fn full_flattens_distribution_and_sum_cum() { - let value = MockFull { - distribution: MockDistribution { - average: MockAverageVec(MockVec::new("m", Index::Height)), - minmax: MockMinMax { - min: MockMinVec(MockVec::new("m", Index::Height)), - max: MockMaxVec(MockVec::new("m", Index::Height)), - }, - percentiles: MockPercentiles { - pct10: MockPct10Vec(MockVec::new("m", Index::Height)), - pct25: MockPct25Vec(MockVec::new("m", Index::Height)), - median: MockMedianVec(MockVec::new("m", Index::Height)), - pct75: MockPct75Vec(MockVec::new("m", Index::Height)), - pct90: MockPct90Vec(MockVec::new("m", Index::Height)), - }, - }, - sum_cum: MockSumCum { - sum: MockSumVec(MockVec::new("m", Index::Height)), - cumulative: MockCumulativeVec(MockVec::new("m", Index::Height)), - }, - }; - - let tree = value.to_tree_node(); - - // Everything flattened except percentiles - assert_is_branch_with_keys( - &tree, - &["average", "min", "max", "percentiles", "sum", "cumulative"], - ); -} - -// ============================================================================ -// Stats - { sum, cumulative, average, min, max } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockStats { - #[traversable(flatten)] - pub sum_cum: MockSumCum, - #[traversable(flatten)] - pub average: MockAverageVec, - #[traversable(flatten)] - pub minmax: MockMinMax, -} - -#[test] -fn stats_flattens_all() { - let value = MockStats { - sum_cum: MockSumCum { - sum: MockSumVec(MockVec::new("m", Index::Height)), - cumulative: MockCumulativeVec(MockVec::new("m", Index::Height)), - }, - average: MockAverageVec(MockVec::new("m", Index::Height)), - minmax: MockMinMax { - min: MockMinVec(MockVec::new("m", Index::Height)), - max: MockMaxVec(MockVec::new("m", Index::Height)), - }, - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["sum", "cumulative", "average", "min", "max"]); -} - -// ============================================================================ -// MinMaxAverage - { average, min, max } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockMinMaxAverage { - pub average: MockAverageVec, - #[traversable(flatten)] - pub minmax: MockMinMax, -} - -#[test] -fn min_max_average_flattens_minmax() { - let value = MockMinMaxAverage { - average: MockAverageVec(MockVec::new("m", Index::Height)), - minmax: MockMinMax { - min: MockMinVec(MockVec::new("m", Index::Height)), - max: MockMaxVec(MockVec::new("m", Index::Height)), - }, - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["average", "min", "max"]); -} diff --git a/crates/brk_traversable/tests/traversable/lazy_aggregation.rs b/crates/brk_traversable/tests/traversable/lazy_aggregation.rs deleted file mode 100644 index 86f6df42f..000000000 --- a/crates/brk_traversable/tests/traversable/lazy_aggregation.rs +++ /dev/null @@ -1,176 +0,0 @@ -//! Tests for Lazy Aggregation types from brk_computer/src/internal/aggregation/ -//! -//! Lazy aggregation types compose multiple Lazy* types. -//! Expected outputs (flat structures): -//! - LazySumCum -> { sum: Leaf, cumulative: Leaf } -//! - LazyDistribution -> { average, min, max } -//! - LazyFull -> { average, min, max, sum, cumulative } - -use brk_traversable::{Index, Traversable, TreeNode}; -use brk_traversable_derive::Traversable; - -use crate::common::*; - -// ============================================================================ -// LazySumCum - { sum: Leaf, cumulative: Leaf } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockLazySumCum { - #[traversable(flatten)] - pub sum: MockLazySum, - #[traversable(flatten)] - pub cumulative: MockLazyCumulative, -} - -#[test] -fn lazy_sum_cum_produces_two_leaves() { - let value = MockLazySumCum { - sum: MockLazySum(MockVec::new("metric", Index::WeekIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric", Index::WeekIndex)), - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["sum", "cumulative"]); -} - -// ============================================================================ -// LazyDistribution - { average, min, max } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockLazyDistribution { - #[traversable(flatten)] - pub average: MockLazyAverage, - #[traversable(flatten)] - pub min: MockLazyMin, - #[traversable(flatten)] - pub max: MockLazyMax, -} - -#[test] -fn lazy_distribution_produces_three_leaves() { - let value = MockLazyDistribution { - average: MockLazyAverage(MockVec::new("m", Index::WeekIndex)), - min: MockLazyMin(MockVec::new("m", Index::WeekIndex)), - max: MockLazyMax(MockVec::new("m", Index::WeekIndex)), - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["average", "min", "max"]); -} - -// ============================================================================ -// LazyFull - { average, min, max, sum, cumulative } -// ============================================================================ - -#[derive(Traversable)] -pub struct MockLazyFull { - #[traversable(flatten)] - pub average: MockLazyAverage, - #[traversable(flatten)] - pub min: MockLazyMin, - #[traversable(flatten)] - pub max: MockLazyMax, - #[traversable(flatten)] - pub sum: MockLazySum, - #[traversable(flatten)] - pub cumulative: MockLazyCumulative, -} - -#[test] -fn lazy_full_produces_five_leaves() { - let value = MockLazyFull { - average: MockLazyAverage(MockVec::new("m", Index::DifficultyEpoch)), - min: MockLazyMin(MockVec::new("m", Index::DifficultyEpoch)), - max: MockLazyMax(MockVec::new("m", Index::DifficultyEpoch)), - sum: MockLazySum(MockVec::new("m", Index::DifficultyEpoch)), - cumulative: MockLazyCumulative(MockVec::new("m", Index::DifficultyEpoch)), - }; - - let tree = value.to_tree_node(); - - assert_is_branch_with_keys(&tree, &["average", "min", "max", "sum", "cumulative"]); -} - -// ============================================================================ -// Merge behavior: Multiple time periods collapse to single leaves -// ============================================================================ - -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockDerivedDateSumCum { - pub weekindex: MockLazySumCum, - pub monthindex: MockLazySumCum, -} - -#[test] -fn derived_date_sum_cum_merges_time_periods() { - let value = MockDerivedDateSumCum { - weekindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::WeekIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::WeekIndex)), - }, - monthindex: MockLazySumCum { - sum: MockLazySum(MockVec::new("metric_sum", Index::MonthIndex)), - cumulative: MockLazyCumulative(MockVec::new("metric_cumulative", Index::MonthIndex)), - }, - }; - - let tree = value.to_tree_node(); - - // Merge lifts children from weekindex and monthindex - // Same keys merge → { sum: Leaf(Week+Month), cumulative: Leaf(Week+Month) } - assert_is_branch_with_keys(&tree, &["sum", "cumulative"]); - - if let TreeNode::Branch(map) = &tree { - // sum should have both indexes merged - let sum_indexes = get_leaf_indexes(map.get("sum").unwrap()).unwrap(); - assert!(sum_indexes.contains(&Index::WeekIndex)); - assert!(sum_indexes.contains(&Index::MonthIndex)); - - // cumulative should have both indexes merged - let cum_indexes = get_leaf_indexes(map.get("cumulative").unwrap()).unwrap(); - assert!(cum_indexes.contains(&Index::WeekIndex)); - assert!(cum_indexes.contains(&Index::MonthIndex)); - } -} - -// ============================================================================ -// Full merge: All same metric name → collapses to single Leaf -// ============================================================================ - -#[derive(Traversable)] -#[traversable(merge)] -pub struct MockDerivedDateLast { - pub weekindex: MockLazyLast, - pub monthindex: MockLazyLast, - pub yearindex: MockLazyLast, -} - -#[test] -fn derived_date_last_collapses_to_single_leaf() { - let value = MockDerivedDateLast { - weekindex: MockLazyLast(MockVec::new("metric", Index::WeekIndex)), - monthindex: MockLazyLast(MockVec::new("metric", Index::MonthIndex)), - yearindex: MockLazyLast(MockVec::new("metric", Index::YearIndex)), - }; - - let tree = value.to_tree_node(); - - // All same metric name → collapses to single Leaf with all indexes - match &tree { - TreeNode::Leaf(l) => { - assert_eq!(l.name(), "metric"); - let indexes = l.indexes(); - assert!(indexes.contains(&Index::WeekIndex)); - assert!(indexes.contains(&Index::MonthIndex)); - assert!(indexes.contains(&Index::YearIndex)); - } - TreeNode::Branch(map) => { - panic!("Expected Leaf, got Branch: {:?}", map.keys().collect::>()); - } - } -} diff --git a/crates/brk_traversable/tests/traversable/main.rs b/crates/brk_traversable/tests/traversable/main.rs deleted file mode 100644 index e2da782b0..000000000 --- a/crates/brk_traversable/tests/traversable/main.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! Structured integration tests for the Traversable derive macro. -//! -//! These tests verify the tree structure output for each category of types -//! in brk_computer/src/internal, ensuring the traversable attributes produce -//! the expected flat/merged structures. - -mod common; - -mod group_types; -mod lazy_aggregation; -mod derived_date; -mod computed_types; diff --git a/crates/brk_types/src/ohlc.rs b/crates/brk_types/src/ohlc.rs index a7241b967..844a9091c 100644 --- a/crates/brk_types/src/ohlc.rs +++ b/crates/brk_types/src/ohlc.rs @@ -391,6 +391,7 @@ impl Bytes for OHLCSats { Pco, JsonSchema, )] +#[schemars(transparent)] #[repr(transparent)] pub struct Open(T); @@ -521,6 +522,7 @@ where Pco, JsonSchema, )] +#[schemars(transparent)] #[repr(transparent)] pub struct High(T); @@ -651,6 +653,7 @@ where Pco, JsonSchema, )] +#[schemars(transparent)] #[repr(transparent)] pub struct Low(T); @@ -781,6 +784,7 @@ where Pco, JsonSchema, )] +#[schemars(transparent)] #[repr(transparent)] pub struct Close(T); diff --git a/crates/brk_types/src/treenode.rs b/crates/brk_types/src/treenode.rs index 81365881f..ef696c0ba 100644 --- a/crates/brk_types/src/treenode.rs +++ b/crates/brk_types/src/treenode.rs @@ -1,7 +1,4 @@ -use std::{ - collections::{BTreeMap, BTreeSet}, - sync::LazyLock, -}; +use std::collections::{BTreeMap, BTreeSet}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -48,13 +45,40 @@ pub struct MetricLeafWithSchema { pub schema: serde_json::Value, } +/// Extract JSON type from a schema, following $ref if needed. +pub fn extract_json_type(schema: &serde_json::Value) -> String { + // Direct type field + if let Some(t) = schema.get("type").and_then(|v| v.as_str()) { + return t.to_string(); + } + + // Handle $ref - look up in definitions + if let Some(ref_path) = schema.get("$ref").and_then(|v| v.as_str()) { + if let Some(def_name) = ref_path.rsplit('/').next() { + // Check both "$defs" (draft 2020-12) and "definitions" (older drafts) + for defs_key in &["$defs", "definitions"] { + if let Some(defs) = schema.get(defs_key) { + if let Some(def) = defs.get(def_name) { + return extract_json_type(def); + } + } + } + } + } + + // Handle allOf with single element + if let Some(all_of) = schema.get("allOf").and_then(|v| v.as_array()) { + if all_of.len() == 1 { + return extract_json_type(&all_of[0]); + } + } + + "object".to_string() +} + impl MetricLeafWithSchema { pub fn new(leaf: MetricLeaf, schema: serde_json::Value) -> Self { - let openapi_type = schema - .get("type") - .and_then(|v| v.as_str()) - .unwrap_or("object") - .to_string(); + let openapi_type = extract_json_type(&schema); Self { leaf, openapi_type, @@ -113,15 +137,6 @@ pub enum TreeNode { const BASE: &str = "base"; -/// List of prefixes to remove during simplification -static PREFIXES: LazyLock> = LazyLock::new(|| { - ["indexes", "timeindexes", "chainindexes", "addresstype"] - .into_iter() - .chain(Index::all().iter().map(|i| i.serialize_long())) - .map(|s| format!("{s}_to_")) - .collect() -}); - impl TreeNode { pub fn is_empty(&self) -> bool { if let Self::Branch(tree) = self { @@ -275,35 +290,6 @@ impl TreeNode { } } } - - /// Recursively simplifies the tree by removing known prefixes from keys (consuming version). - /// If multiple keys map to the same simplified name, checks for conflicts. - /// Returns None if there are conflicts (same simplified key, different values). - pub fn simplify(self) -> Option { - match self { - Self::Leaf(_) => Some(self), - Self::Branch(map) => { - let mut simplified: BTreeMap = BTreeMap::new(); - - for (key, node) in map { - // Recursively simplify the child node first - let simplified_node = node.simplify()?; - - // Remove prefixes from the key - let simplified_key = PREFIXES - .iter() - .find_map(|prefix| key.strip_prefix(prefix)) - .map(String::from) - .unwrap_or(key); - - // Try to merge into the result - Self::merge_node(&mut simplified, simplified_key, simplified_node)?; - } - - Some(Self::Branch(simplified)) - } - } - } } #[cfg(test)] diff --git a/modules/brk-client/index.js b/modules/brk-client/index.js index a327baeb5..dd61724b3 100644 --- a/modules/brk-client/index.js +++ b/modules/brk-client/index.js @@ -800,7 +800,7 @@ function createMetricPattern4(client, name) { /** * @template T - * @typedef {{ name: string, by: { decadeindex: MetricEndpoint, monthindex: MetricEndpoint, quarterindex: MetricEndpoint, semesterindex: MetricEndpoint, weekindex: MetricEndpoint, yearindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern5 + * @typedef {{ name: string, by: { dateindex: MetricEndpoint, height: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern5 */ /** @@ -811,40 +811,6 @@ function createMetricPattern4(client, name) { * @returns {MetricPattern5} */ function createMetricPattern5(client, name) { - return { - name, - by: { - get decadeindex() { return _endpoint(client, name, 'decadeindex'); }, - get monthindex() { return _endpoint(client, name, 'monthindex'); }, - get quarterindex() { return _endpoint(client, name, 'quarterindex'); }, - get semesterindex() { return _endpoint(client, name, 'semesterindex'); }, - get weekindex() { return _endpoint(client, name, 'weekindex'); }, - get yearindex() { return _endpoint(client, name, 'yearindex'); } - }, - indexes() { - return ['decadeindex', 'monthindex', 'quarterindex', 'semesterindex', 'weekindex', 'yearindex']; - }, - get(index) { - if (this.indexes().includes(index)) { - return _endpoint(client, name, index); - } - } - }; -} - -/** - * @template T - * @typedef {{ name: string, by: { dateindex: MetricEndpoint, height: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern6 - */ - -/** - * Create a MetricPattern6 accessor - * @template T - * @param {BrkClientBase} client - * @param {string} name - The metric vec name - * @returns {MetricPattern6} - */ -function createMetricPattern6(client, name) { return { name, by: { @@ -864,17 +830,17 @@ function createMetricPattern6(client, name) { /** * @template T - * @typedef {{ name: string, by: { dateindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern7 + * @typedef {{ name: string, by: { dateindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern6 */ /** - * Create a MetricPattern7 accessor + * Create a MetricPattern6 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern7} + * @returns {MetricPattern6} */ -function createMetricPattern7(client, name) { +function createMetricPattern6(client, name) { return { name, by: { @@ -893,17 +859,17 @@ function createMetricPattern7(client, name) { /** * @template T - * @typedef {{ name: string, by: { decadeindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern8 + * @typedef {{ name: string, by: { decadeindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern7 */ /** - * Create a MetricPattern8 accessor + * Create a MetricPattern7 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern8} + * @returns {MetricPattern7} */ -function createMetricPattern8(client, name) { +function createMetricPattern7(client, name) { return { name, by: { @@ -922,17 +888,17 @@ function createMetricPattern8(client, name) { /** * @template T - * @typedef {{ name: string, by: { difficultyepoch: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern9 + * @typedef {{ name: string, by: { difficultyepoch: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern8 */ /** - * Create a MetricPattern9 accessor + * Create a MetricPattern8 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern9} + * @returns {MetricPattern8} */ -function createMetricPattern9(client, name) { +function createMetricPattern8(client, name) { return { name, by: { @@ -951,17 +917,17 @@ function createMetricPattern9(client, name) { /** * @template T - * @typedef {{ name: string, by: { emptyoutputindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern10 + * @typedef {{ name: string, by: { emptyoutputindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern9 */ /** - * Create a MetricPattern10 accessor + * Create a MetricPattern9 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern10} + * @returns {MetricPattern9} */ -function createMetricPattern10(client, name) { +function createMetricPattern9(client, name) { return { name, by: { @@ -980,17 +946,17 @@ function createMetricPattern10(client, name) { /** * @template T - * @typedef {{ name: string, by: { halvingepoch: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern11 + * @typedef {{ name: string, by: { halvingepoch: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern10 */ /** - * Create a MetricPattern11 accessor + * Create a MetricPattern10 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern11} + * @returns {MetricPattern10} */ -function createMetricPattern11(client, name) { +function createMetricPattern10(client, name) { return { name, by: { @@ -1009,17 +975,17 @@ function createMetricPattern11(client, name) { /** * @template T - * @typedef {{ name: string, by: { height: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern12 + * @typedef {{ name: string, by: { height: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern11 */ /** - * Create a MetricPattern12 accessor + * Create a MetricPattern11 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern12} + * @returns {MetricPattern11} */ -function createMetricPattern12(client, name) { +function createMetricPattern11(client, name) { return { name, by: { @@ -1038,17 +1004,17 @@ function createMetricPattern12(client, name) { /** * @template T - * @typedef {{ name: string, by: { txinindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern13 + * @typedef {{ name: string, by: { txinindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern12 */ /** - * Create a MetricPattern13 accessor + * Create a MetricPattern12 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern13} + * @returns {MetricPattern12} */ -function createMetricPattern13(client, name) { +function createMetricPattern12(client, name) { return { name, by: { @@ -1067,17 +1033,17 @@ function createMetricPattern13(client, name) { /** * @template T - * @typedef {{ name: string, by: { monthindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern14 + * @typedef {{ name: string, by: { monthindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern13 */ /** - * Create a MetricPattern14 accessor + * Create a MetricPattern13 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern14} + * @returns {MetricPattern13} */ -function createMetricPattern14(client, name) { +function createMetricPattern13(client, name) { return { name, by: { @@ -1096,17 +1062,17 @@ function createMetricPattern14(client, name) { /** * @template T - * @typedef {{ name: string, by: { opreturnindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern15 + * @typedef {{ name: string, by: { opreturnindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern14 */ /** - * Create a MetricPattern15 accessor + * Create a MetricPattern14 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern15} + * @returns {MetricPattern14} */ -function createMetricPattern15(client, name) { +function createMetricPattern14(client, name) { return { name, by: { @@ -1125,17 +1091,17 @@ function createMetricPattern15(client, name) { /** * @template T - * @typedef {{ name: string, by: { txoutindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern16 + * @typedef {{ name: string, by: { txoutindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern15 */ /** - * Create a MetricPattern16 accessor + * Create a MetricPattern15 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern16} + * @returns {MetricPattern15} */ -function createMetricPattern16(client, name) { +function createMetricPattern15(client, name) { return { name, by: { @@ -1154,17 +1120,17 @@ function createMetricPattern16(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2aaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern17 + * @typedef {{ name: string, by: { p2aaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern16 */ /** - * Create a MetricPattern17 accessor + * Create a MetricPattern16 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern17} + * @returns {MetricPattern16} */ -function createMetricPattern17(client, name) { +function createMetricPattern16(client, name) { return { name, by: { @@ -1183,17 +1149,17 @@ function createMetricPattern17(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2msoutputindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern18 + * @typedef {{ name: string, by: { p2msoutputindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern17 */ /** - * Create a MetricPattern18 accessor + * Create a MetricPattern17 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern18} + * @returns {MetricPattern17} */ -function createMetricPattern18(client, name) { +function createMetricPattern17(client, name) { return { name, by: { @@ -1212,17 +1178,17 @@ function createMetricPattern18(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2pk33addressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern19 + * @typedef {{ name: string, by: { p2pk33addressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern18 */ /** - * Create a MetricPattern19 accessor + * Create a MetricPattern18 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern19} + * @returns {MetricPattern18} */ -function createMetricPattern19(client, name) { +function createMetricPattern18(client, name) { return { name, by: { @@ -1241,17 +1207,17 @@ function createMetricPattern19(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2pk65addressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern20 + * @typedef {{ name: string, by: { p2pk65addressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern19 */ /** - * Create a MetricPattern20 accessor + * Create a MetricPattern19 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern20} + * @returns {MetricPattern19} */ -function createMetricPattern20(client, name) { +function createMetricPattern19(client, name) { return { name, by: { @@ -1270,17 +1236,17 @@ function createMetricPattern20(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2pkhaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern21 + * @typedef {{ name: string, by: { p2pkhaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern20 */ /** - * Create a MetricPattern21 accessor + * Create a MetricPattern20 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern21} + * @returns {MetricPattern20} */ -function createMetricPattern21(client, name) { +function createMetricPattern20(client, name) { return { name, by: { @@ -1299,17 +1265,17 @@ function createMetricPattern21(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2shaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern22 + * @typedef {{ name: string, by: { p2shaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern21 */ /** - * Create a MetricPattern22 accessor + * Create a MetricPattern21 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern22} + * @returns {MetricPattern21} */ -function createMetricPattern22(client, name) { +function createMetricPattern21(client, name) { return { name, by: { @@ -1328,17 +1294,17 @@ function createMetricPattern22(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2traddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern23 + * @typedef {{ name: string, by: { p2traddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern22 */ /** - * Create a MetricPattern23 accessor + * Create a MetricPattern22 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern23} + * @returns {MetricPattern22} */ -function createMetricPattern23(client, name) { +function createMetricPattern22(client, name) { return { name, by: { @@ -1357,17 +1323,17 @@ function createMetricPattern23(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2wpkhaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern24 + * @typedef {{ name: string, by: { p2wpkhaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern23 */ /** - * Create a MetricPattern24 accessor + * Create a MetricPattern23 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern24} + * @returns {MetricPattern23} */ -function createMetricPattern24(client, name) { +function createMetricPattern23(client, name) { return { name, by: { @@ -1386,17 +1352,17 @@ function createMetricPattern24(client, name) { /** * @template T - * @typedef {{ name: string, by: { p2wshaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern25 + * @typedef {{ name: string, by: { p2wshaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern24 */ /** - * Create a MetricPattern25 accessor + * Create a MetricPattern24 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern25} + * @returns {MetricPattern24} */ -function createMetricPattern25(client, name) { +function createMetricPattern24(client, name) { return { name, by: { @@ -1415,17 +1381,17 @@ function createMetricPattern25(client, name) { /** * @template T - * @typedef {{ name: string, by: { quarterindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern26 + * @typedef {{ name: string, by: { quarterindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern25 */ /** - * Create a MetricPattern26 accessor + * Create a MetricPattern25 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern26} + * @returns {MetricPattern25} */ -function createMetricPattern26(client, name) { +function createMetricPattern25(client, name) { return { name, by: { @@ -1444,17 +1410,17 @@ function createMetricPattern26(client, name) { /** * @template T - * @typedef {{ name: string, by: { semesterindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern27 + * @typedef {{ name: string, by: { semesterindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern26 */ /** - * Create a MetricPattern27 accessor + * Create a MetricPattern26 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern27} + * @returns {MetricPattern26} */ -function createMetricPattern27(client, name) { +function createMetricPattern26(client, name) { return { name, by: { @@ -1473,17 +1439,17 @@ function createMetricPattern27(client, name) { /** * @template T - * @typedef {{ name: string, by: { txindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern28 + * @typedef {{ name: string, by: { txindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern27 */ /** - * Create a MetricPattern28 accessor + * Create a MetricPattern27 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern28} + * @returns {MetricPattern27} */ -function createMetricPattern28(client, name) { +function createMetricPattern27(client, name) { return { name, by: { @@ -1502,17 +1468,17 @@ function createMetricPattern28(client, name) { /** * @template T - * @typedef {{ name: string, by: { unknownoutputindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern29 + * @typedef {{ name: string, by: { unknownoutputindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern28 */ /** - * Create a MetricPattern29 accessor + * Create a MetricPattern28 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern29} + * @returns {MetricPattern28} */ -function createMetricPattern29(client, name) { +function createMetricPattern28(client, name) { return { name, by: { @@ -1531,17 +1497,17 @@ function createMetricPattern29(client, name) { /** * @template T - * @typedef {{ name: string, by: { weekindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern30 + * @typedef {{ name: string, by: { weekindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern29 */ /** - * Create a MetricPattern30 accessor + * Create a MetricPattern29 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern30} + * @returns {MetricPattern29} */ -function createMetricPattern30(client, name) { +function createMetricPattern29(client, name) { return { name, by: { @@ -1560,17 +1526,17 @@ function createMetricPattern30(client, name) { /** * @template T - * @typedef {{ name: string, by: { yearindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern31 + * @typedef {{ name: string, by: { yearindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern30 */ /** - * Create a MetricPattern31 accessor + * Create a MetricPattern30 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern31} + * @returns {MetricPattern30} */ -function createMetricPattern31(client, name) { +function createMetricPattern30(client, name) { return { name, by: { @@ -1589,17 +1555,17 @@ function createMetricPattern31(client, name) { /** * @template T - * @typedef {{ name: string, by: { loadedaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern32 + * @typedef {{ name: string, by: { loadedaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern31 */ /** - * Create a MetricPattern32 accessor + * Create a MetricPattern31 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern32} + * @returns {MetricPattern31} */ -function createMetricPattern32(client, name) { +function createMetricPattern31(client, name) { return { name, by: { @@ -1618,17 +1584,17 @@ function createMetricPattern32(client, name) { /** * @template T - * @typedef {{ name: string, by: { emptyaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern33 + * @typedef {{ name: string, by: { emptyaddressindex: MetricEndpoint }, indexes: () => Index[], get: (index: Index) => MetricEndpoint|undefined }} MetricPattern32 */ /** - * Create a MetricPattern33 accessor + * Create a MetricPattern32 accessor * @template T * @param {BrkClientBase} client * @param {string} name - The metric vec name - * @returns {MetricPattern33} + * @returns {MetricPattern32} */ -function createMetricPattern33(client, name) { +function createMetricPattern32(client, name) { return { name, by: { @@ -1649,9 +1615,9 @@ function createMetricPattern33(client, name) { /** * @typedef {Object} RealizedPattern3 - * @property {MetricPattern7} adjustedSopr - * @property {MetricPattern7} adjustedSopr30dEma - * @property {MetricPattern7} adjustedSopr7dEma + * @property {MetricPattern6} adjustedSopr + * @property {MetricPattern6} adjustedSopr30dEma + * @property {MetricPattern6} adjustedSopr7dEma * @property {MetricPattern1} adjustedValueCreated * @property {MetricPattern1} adjustedValueDestroyed * @property {MetricPattern4} mvrv @@ -1670,14 +1636,14 @@ function createMetricPattern33(client, name) { * @property {ActivePriceRatioPattern} realizedPriceExtra * @property {BlockCountPattern} realizedProfit * @property {BlockCountPattern} realizedProfitRelToRealizedCap - * @property {MetricPattern7} realizedProfitToLossRatio + * @property {MetricPattern6} realizedProfitToLossRatio * @property {MetricPattern1} realizedValue - * @property {MetricPattern7} sellSideRiskRatio - * @property {MetricPattern7} sellSideRiskRatio30dEma - * @property {MetricPattern7} sellSideRiskRatio7dEma - * @property {MetricPattern7} sopr - * @property {MetricPattern7} sopr30dEma - * @property {MetricPattern7} sopr7dEma + * @property {MetricPattern6} sellSideRiskRatio + * @property {MetricPattern6} sellSideRiskRatio30dEma + * @property {MetricPattern6} sellSideRiskRatio7dEma + * @property {MetricPattern6} sopr + * @property {MetricPattern6} sopr30dEma + * @property {MetricPattern6} sopr7dEma * @property {MetricPattern1} totalRealizedPnl * @property {MetricPattern1} valueCreated * @property {MetricPattern1} valueDestroyed @@ -1691,9 +1657,9 @@ function createMetricPattern33(client, name) { */ function createRealizedPattern3(client, acc) { return { - adjustedSopr: createMetricPattern7(client, _m(acc, 'adjusted_sopr')), - adjustedSopr30dEma: createMetricPattern7(client, _m(acc, 'adjusted_sopr_30d_ema')), - adjustedSopr7dEma: createMetricPattern7(client, _m(acc, 'adjusted_sopr_7d_ema')), + adjustedSopr: createMetricPattern6(client, _m(acc, 'adjusted_sopr')), + adjustedSopr30dEma: createMetricPattern6(client, _m(acc, 'adjusted_sopr_30d_ema')), + adjustedSopr7dEma: createMetricPattern6(client, _m(acc, 'adjusted_sopr_7d_ema')), adjustedValueCreated: createMetricPattern1(client, _m(acc, 'adjusted_value_created')), adjustedValueDestroyed: createMetricPattern1(client, _m(acc, 'adjusted_value_destroyed')), mvrv: createMetricPattern4(client, _m(acc, 'mvrv')), @@ -1712,14 +1678,14 @@ function createRealizedPattern3(client, acc) { realizedPriceExtra: createActivePriceRatioPattern(client, _m(acc, 'realized_price_ratio')), realizedProfit: createBlockCountPattern(client, _m(acc, 'realized_profit')), realizedProfitRelToRealizedCap: createBlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')), - realizedProfitToLossRatio: createMetricPattern7(client, _m(acc, 'realized_profit_to_loss_ratio')), + realizedProfitToLossRatio: createMetricPattern6(client, _m(acc, 'realized_profit_to_loss_ratio')), realizedValue: createMetricPattern1(client, _m(acc, 'realized_value')), - sellSideRiskRatio: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio')), - sellSideRiskRatio30dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), - sellSideRiskRatio7dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), - sopr: createMetricPattern7(client, _m(acc, 'sopr')), - sopr30dEma: createMetricPattern7(client, _m(acc, 'sopr_30d_ema')), - sopr7dEma: createMetricPattern7(client, _m(acc, 'sopr_7d_ema')), + sellSideRiskRatio: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio')), + sellSideRiskRatio30dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), + sellSideRiskRatio7dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), + sopr: createMetricPattern6(client, _m(acc, 'sopr')), + sopr30dEma: createMetricPattern6(client, _m(acc, 'sopr_30d_ema')), + sopr7dEma: createMetricPattern6(client, _m(acc, 'sopr_7d_ema')), totalRealizedPnl: createMetricPattern1(client, _m(acc, 'total_realized_pnl')), valueCreated: createMetricPattern1(client, _m(acc, 'value_created')), valueDestroyed: createMetricPattern1(client, _m(acc, 'value_destroyed')), @@ -1728,9 +1694,9 @@ function createRealizedPattern3(client, acc) { /** * @typedef {Object} RealizedPattern4 - * @property {MetricPattern7} adjustedSopr - * @property {MetricPattern7} adjustedSopr30dEma - * @property {MetricPattern7} adjustedSopr7dEma + * @property {MetricPattern6} adjustedSopr + * @property {MetricPattern6} adjustedSopr30dEma + * @property {MetricPattern6} adjustedSopr7dEma * @property {MetricPattern1} adjustedValueCreated * @property {MetricPattern1} adjustedValueDestroyed * @property {MetricPattern4} mvrv @@ -1749,12 +1715,12 @@ function createRealizedPattern3(client, acc) { * @property {BlockCountPattern} realizedProfit * @property {BlockCountPattern} realizedProfitRelToRealizedCap * @property {MetricPattern1} realizedValue - * @property {MetricPattern7} sellSideRiskRatio - * @property {MetricPattern7} sellSideRiskRatio30dEma - * @property {MetricPattern7} sellSideRiskRatio7dEma - * @property {MetricPattern7} sopr - * @property {MetricPattern7} sopr30dEma - * @property {MetricPattern7} sopr7dEma + * @property {MetricPattern6} sellSideRiskRatio + * @property {MetricPattern6} sellSideRiskRatio30dEma + * @property {MetricPattern6} sellSideRiskRatio7dEma + * @property {MetricPattern6} sopr + * @property {MetricPattern6} sopr30dEma + * @property {MetricPattern6} sopr7dEma * @property {MetricPattern1} totalRealizedPnl * @property {MetricPattern1} valueCreated * @property {MetricPattern1} valueDestroyed @@ -1768,9 +1734,9 @@ function createRealizedPattern3(client, acc) { */ function createRealizedPattern4(client, acc) { return { - adjustedSopr: createMetricPattern7(client, _m(acc, 'adjusted_sopr')), - adjustedSopr30dEma: createMetricPattern7(client, _m(acc, 'adjusted_sopr_30d_ema')), - adjustedSopr7dEma: createMetricPattern7(client, _m(acc, 'adjusted_sopr_7d_ema')), + adjustedSopr: createMetricPattern6(client, _m(acc, 'adjusted_sopr')), + adjustedSopr30dEma: createMetricPattern6(client, _m(acc, 'adjusted_sopr_30d_ema')), + adjustedSopr7dEma: createMetricPattern6(client, _m(acc, 'adjusted_sopr_7d_ema')), adjustedValueCreated: createMetricPattern1(client, _m(acc, 'adjusted_value_created')), adjustedValueDestroyed: createMetricPattern1(client, _m(acc, 'adjusted_value_destroyed')), mvrv: createMetricPattern4(client, _m(acc, 'mvrv')), @@ -1789,12 +1755,12 @@ function createRealizedPattern4(client, acc) { realizedProfit: createBlockCountPattern(client, _m(acc, 'realized_profit')), realizedProfitRelToRealizedCap: createBlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')), realizedValue: createMetricPattern1(client, _m(acc, 'realized_value')), - sellSideRiskRatio: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio')), - sellSideRiskRatio30dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), - sellSideRiskRatio7dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), - sopr: createMetricPattern7(client, _m(acc, 'sopr')), - sopr30dEma: createMetricPattern7(client, _m(acc, 'sopr_30d_ema')), - sopr7dEma: createMetricPattern7(client, _m(acc, 'sopr_7d_ema')), + sellSideRiskRatio: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio')), + sellSideRiskRatio30dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), + sellSideRiskRatio7dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), + sopr: createMetricPattern6(client, _m(acc, 'sopr')), + sopr30dEma: createMetricPattern6(client, _m(acc, 'sopr_30d_ema')), + sopr7dEma: createMetricPattern6(client, _m(acc, 'sopr_7d_ema')), totalRealizedPnl: createMetricPattern1(client, _m(acc, 'total_realized_pnl')), valueCreated: createMetricPattern1(client, _m(acc, 'value_created')), valueDestroyed: createMetricPattern1(client, _m(acc, 'value_destroyed')), @@ -1890,14 +1856,14 @@ function createRatio1ySdPattern(client, acc) { * @property {ActivePriceRatioPattern} realizedPriceExtra * @property {BlockCountPattern} realizedProfit * @property {BlockCountPattern} realizedProfitRelToRealizedCap - * @property {MetricPattern7} realizedProfitToLossRatio + * @property {MetricPattern6} realizedProfitToLossRatio * @property {MetricPattern1} realizedValue - * @property {MetricPattern7} sellSideRiskRatio - * @property {MetricPattern7} sellSideRiskRatio30dEma - * @property {MetricPattern7} sellSideRiskRatio7dEma - * @property {MetricPattern7} sopr - * @property {MetricPattern7} sopr30dEma - * @property {MetricPattern7} sopr7dEma + * @property {MetricPattern6} sellSideRiskRatio + * @property {MetricPattern6} sellSideRiskRatio30dEma + * @property {MetricPattern6} sellSideRiskRatio7dEma + * @property {MetricPattern6} sopr + * @property {MetricPattern6} sopr30dEma + * @property {MetricPattern6} sopr7dEma * @property {MetricPattern1} totalRealizedPnl * @property {MetricPattern1} valueCreated * @property {MetricPattern1} valueDestroyed @@ -1927,14 +1893,14 @@ function createRealizedPattern2(client, acc) { realizedPriceExtra: createActivePriceRatioPattern(client, _m(acc, 'realized_price_ratio')), realizedProfit: createBlockCountPattern(client, _m(acc, 'realized_profit')), realizedProfitRelToRealizedCap: createBlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')), - realizedProfitToLossRatio: createMetricPattern7(client, _m(acc, 'realized_profit_to_loss_ratio')), + realizedProfitToLossRatio: createMetricPattern6(client, _m(acc, 'realized_profit_to_loss_ratio')), realizedValue: createMetricPattern1(client, _m(acc, 'realized_value')), - sellSideRiskRatio: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio')), - sellSideRiskRatio30dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), - sellSideRiskRatio7dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), - sopr: createMetricPattern7(client, _m(acc, 'sopr')), - sopr30dEma: createMetricPattern7(client, _m(acc, 'sopr_30d_ema')), - sopr7dEma: createMetricPattern7(client, _m(acc, 'sopr_7d_ema')), + sellSideRiskRatio: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio')), + sellSideRiskRatio30dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), + sellSideRiskRatio7dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), + sopr: createMetricPattern6(client, _m(acc, 'sopr')), + sopr30dEma: createMetricPattern6(client, _m(acc, 'sopr_30d_ema')), + sopr7dEma: createMetricPattern6(client, _m(acc, 'sopr_7d_ema')), totalRealizedPnl: createMetricPattern1(client, _m(acc, 'total_realized_pnl')), valueCreated: createMetricPattern1(client, _m(acc, 'value_created')), valueDestroyed: createMetricPattern1(client, _m(acc, 'value_destroyed')), @@ -1959,12 +1925,12 @@ function createRealizedPattern2(client, acc) { * @property {BlockCountPattern} realizedProfit * @property {BlockCountPattern} realizedProfitRelToRealizedCap * @property {MetricPattern1} realizedValue - * @property {MetricPattern7} sellSideRiskRatio - * @property {MetricPattern7} sellSideRiskRatio30dEma - * @property {MetricPattern7} sellSideRiskRatio7dEma - * @property {MetricPattern7} sopr - * @property {MetricPattern7} sopr30dEma - * @property {MetricPattern7} sopr7dEma + * @property {MetricPattern6} sellSideRiskRatio + * @property {MetricPattern6} sellSideRiskRatio30dEma + * @property {MetricPattern6} sellSideRiskRatio7dEma + * @property {MetricPattern6} sopr + * @property {MetricPattern6} sopr30dEma + * @property {MetricPattern6} sopr7dEma * @property {MetricPattern1} totalRealizedPnl * @property {MetricPattern1} valueCreated * @property {MetricPattern1} valueDestroyed @@ -1994,12 +1960,12 @@ function createRealizedPattern(client, acc) { realizedProfit: createBlockCountPattern(client, _m(acc, 'realized_profit')), realizedProfitRelToRealizedCap: createBlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')), realizedValue: createMetricPattern1(client, _m(acc, 'realized_value')), - sellSideRiskRatio: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio')), - sellSideRiskRatio30dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), - sellSideRiskRatio7dEma: createMetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), - sopr: createMetricPattern7(client, _m(acc, 'sopr')), - sopr30dEma: createMetricPattern7(client, _m(acc, 'sopr_30d_ema')), - sopr7dEma: createMetricPattern7(client, _m(acc, 'sopr_7d_ema')), + sellSideRiskRatio: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio')), + sellSideRiskRatio30dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')), + sellSideRiskRatio7dEma: createMetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')), + sopr: createMetricPattern6(client, _m(acc, 'sopr')), + sopr30dEma: createMetricPattern6(client, _m(acc, 'sopr_30d_ema')), + sopr7dEma: createMetricPattern6(client, _m(acc, 'sopr_7d_ema')), totalRealizedPnl: createMetricPattern1(client, _m(acc, 'total_realized_pnl')), valueCreated: createMetricPattern1(client, _m(acc, 'value_created')), valueDestroyed: createMetricPattern1(client, _m(acc, 'value_destroyed')), @@ -2062,7 +2028,7 @@ function createPrice111dSmaPattern(client, acc) { } /** - * @typedef {Object} PercentilesPattern2 + * @typedef {Object} PercentilesPattern * @property {MetricPattern4} costBasisPct05 * @property {MetricPattern4} costBasisPct10 * @property {MetricPattern4} costBasisPct15 @@ -2085,12 +2051,12 @@ function createPrice111dSmaPattern(client, acc) { */ /** - * Create a PercentilesPattern2 pattern node + * Create a PercentilesPattern pattern node * @param {BrkClientBase} client * @param {string} acc - Accumulated metric name - * @returns {PercentilesPattern2} + * @returns {PercentilesPattern} */ -function createPercentilesPattern2(client, acc) { +function createPercentilesPattern(client, acc) { return { costBasisPct05: createMetricPattern4(client, _m(acc, 'pct05')), costBasisPct10: createMetricPattern4(client, _m(acc, 'pct10')), @@ -2423,6 +2389,45 @@ function createClassAveragePricePattern(client, acc) { }; } +/** + * @template T + * @typedef {Object} FullnessPattern + * @property {MetricPattern2} average + * @property {MetricPattern11} base + * @property {MetricPattern1} cumulative + * @property {MetricPattern2} max + * @property {MetricPattern6} median + * @property {MetricPattern2} min + * @property {MetricPattern6} pct10 + * @property {MetricPattern6} pct25 + * @property {MetricPattern6} pct75 + * @property {MetricPattern6} pct90 + * @property {MetricPattern2} sum + */ + +/** + * Create a FullnessPattern pattern node + * @template T + * @param {BrkClientBase} client + * @param {string} acc - Accumulated metric name + * @returns {FullnessPattern} + */ +function createFullnessPattern(client, acc) { + return { + average: createMetricPattern2(client, _m(acc, 'average')), + base: createMetricPattern11(client, acc), + cumulative: createMetricPattern1(client, _m(acc, 'cumulative')), + max: createMetricPattern2(client, _m(acc, 'max')), + median: createMetricPattern6(client, _m(acc, 'median')), + min: createMetricPattern2(client, _m(acc, 'min')), + pct10: createMetricPattern6(client, _m(acc, 'pct10')), + pct25: createMetricPattern6(client, _m(acc, 'pct25')), + pct75: createMetricPattern6(client, _m(acc, 'pct75')), + pct90: createMetricPattern6(client, _m(acc, 'pct90')), + sum: createMetricPattern2(client, _m(acc, 'sum')), + }; +} + /** * @typedef {Object} RelativePattern * @property {MetricPattern1} negUnrealizedLossRelToMarketCap @@ -2493,6 +2498,43 @@ function createRelativePattern2(client, acc) { }; } +/** + * @template T + * @typedef {Object} SizePattern + * @property {MetricPattern1} average + * @property {MetricPattern1} cumulative + * @property {MetricPattern1} max + * @property {MetricPattern11} median + * @property {MetricPattern1} min + * @property {MetricPattern11} pct10 + * @property {MetricPattern11} pct25 + * @property {MetricPattern11} pct75 + * @property {MetricPattern11} pct90 + * @property {MetricPattern1} sum + */ + +/** + * Create a SizePattern pattern node + * @template T + * @param {BrkClientBase} client + * @param {string} acc - Accumulated metric name + * @returns {SizePattern} + */ +function createSizePattern(client, acc) { + return { + average: createMetricPattern1(client, _m(acc, 'average')), + cumulative: createMetricPattern1(client, _m(acc, 'cumulative')), + max: createMetricPattern1(client, _m(acc, 'max')), + median: createMetricPattern11(client, _m(acc, 'median')), + min: createMetricPattern1(client, _m(acc, 'min')), + pct10: createMetricPattern11(client, _m(acc, 'pct10')), + pct25: createMetricPattern11(client, _m(acc, 'pct25')), + pct75: createMetricPattern11(client, _m(acc, 'pct75')), + pct90: createMetricPattern11(client, _m(acc, 'pct90')), + sum: createMetricPattern1(client, _m(acc, 'sum')), + }; +} + /** * @typedef {Object} AddrCountPattern * @property {MetricPattern1} all @@ -2526,53 +2568,18 @@ function createAddrCountPattern(client, acc) { }; } -/** - * @template T - * @typedef {Object} OhlcPattern - * @property {MetricPattern7} dateindex - * @property {MetricPattern8} decade - * @property {MetricPattern9} difficultyepoch - * @property {MetricPattern12} height - * @property {MetricPattern14} month - * @property {MetricPattern26} quarter - * @property {MetricPattern27} semester - * @property {MetricPattern30} week - * @property {MetricPattern31} year - */ - -/** - * Create a OhlcPattern pattern node - * @template T - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {OhlcPattern} - */ -function createOhlcPattern(client, acc) { - return { - dateindex: createMetricPattern7(client, acc), - decade: createMetricPattern8(client, acc), - difficultyepoch: createMetricPattern9(client, acc), - height: createMetricPattern12(client, acc), - month: createMetricPattern14(client, acc), - quarter: createMetricPattern26(client, acc), - semester: createMetricPattern27(client, acc), - week: createMetricPattern30(client, acc), - year: createMetricPattern31(client, acc), - }; -} - /** * @template T * @typedef {Object} FeeRatePattern * @property {MetricPattern1} average * @property {MetricPattern1} max - * @property {MetricPattern12} median + * @property {MetricPattern11} median * @property {MetricPattern1} min - * @property {MetricPattern12} pct10 - * @property {MetricPattern12} pct25 - * @property {MetricPattern12} pct75 - * @property {MetricPattern12} pct90 - * @property {MetricPattern28} txindex + * @property {MetricPattern11} pct10 + * @property {MetricPattern11} pct25 + * @property {MetricPattern11} pct75 + * @property {MetricPattern11} pct90 + * @property {MetricPattern27} txindex */ /** @@ -2586,13 +2593,13 @@ function createFeeRatePattern(client, acc) { return { average: createMetricPattern1(client, _m(acc, 'average')), max: createMetricPattern1(client, _m(acc, 'max')), - median: createMetricPattern12(client, _m(acc, 'median')), + median: createMetricPattern11(client, _m(acc, 'median')), min: createMetricPattern1(client, _m(acc, 'min')), - pct10: createMetricPattern12(client, _m(acc, 'pct10')), - pct25: createMetricPattern12(client, _m(acc, 'pct25')), - pct75: createMetricPattern12(client, _m(acc, 'pct75')), - pct90: createMetricPattern12(client, _m(acc, 'pct90')), - txindex: createMetricPattern28(client, acc), + pct10: createMetricPattern11(client, _m(acc, 'pct10')), + pct25: createMetricPattern11(client, _m(acc, 'pct25')), + pct75: createMetricPattern11(client, _m(acc, 'pct75')), + pct90: createMetricPattern11(client, _m(acc, 'pct90')), + txindex: createMetricPattern27(client, acc), }; } @@ -2628,29 +2635,29 @@ function create_0satsPattern(client, acc) { } /** - * @typedef {Object} _10yPattern + * @typedef {Object} _0satsPattern2 * @property {ActivityPattern2} activity * @property {CostBasisPattern} costBasis * @property {OutputsPattern} outputs - * @property {RealizedPattern4} realized - * @property {RelativePattern} relative + * @property {RealizedPattern} realized + * @property {RelativePattern4} relative * @property {SupplyPattern2} supply * @property {UnrealizedPattern} unrealized */ /** - * Create a _10yPattern pattern node + * Create a _0satsPattern2 pattern node * @param {BrkClientBase} client * @param {string} acc - Accumulated metric name - * @returns {_10yPattern} + * @returns {_0satsPattern2} */ -function create_10yPattern(client, acc) { +function create_0satsPattern2(client, acc) { return { activity: createActivityPattern2(client, acc), costBasis: createCostBasisPattern(client, acc), outputs: createOutputsPattern(client, acc), - realized: createRealizedPattern4(client, acc), - relative: createRelativePattern(client, acc), + realized: createRealizedPattern(client, acc), + relative: createRelativePattern4(client, _m(acc, 'supply_in')), supply: createSupplyPattern2(client, _m(acc, 'supply')), unrealized: createUnrealizedPattern(client, acc), }; @@ -2686,29 +2693,29 @@ function create_10yTo12yPattern(client, acc) { } /** - * @typedef {Object} _0satsPattern2 + * @typedef {Object} _10yPattern * @property {ActivityPattern2} activity * @property {CostBasisPattern} costBasis * @property {OutputsPattern} outputs - * @property {RealizedPattern} realized - * @property {RelativePattern4} relative + * @property {RealizedPattern4} realized + * @property {RelativePattern} relative * @property {SupplyPattern2} supply * @property {UnrealizedPattern} unrealized */ /** - * Create a _0satsPattern2 pattern node + * Create a _10yPattern pattern node * @param {BrkClientBase} client * @param {string} acc - Accumulated metric name - * @returns {_0satsPattern2} + * @returns {_10yPattern} */ -function create_0satsPattern2(client, acc) { +function create_10yPattern(client, acc) { return { activity: createActivityPattern2(client, acc), costBasis: createCostBasisPattern(client, acc), outputs: createOutputsPattern(client, acc), - realized: createRealizedPattern(client, acc), - relative: createRelativePattern4(client, _m(acc, 'supply_in')), + realized: createRealizedPattern4(client, acc), + relative: createRelativePattern(client, acc), supply: createSupplyPattern2(client, _m(acc, 'supply')), unrealized: createUnrealizedPattern(client, acc), }; @@ -2801,72 +2808,12 @@ function createPeriodCagrPattern(client, acc) { }; } -/** - * @template T - * @typedef {Object} BitcoinPattern - * @property {MetricPattern2} average - * @property {MetricPattern1} cumulative - * @property {MetricPattern12} height - * @property {MetricPattern2} max - * @property {MetricPattern2} min - * @property {PercentilesPattern} percentiles - * @property {MetricPattern2} sum - */ - -/** - * Create a BitcoinPattern pattern node - * @template T - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {BitcoinPattern} - */ -function createBitcoinPattern(client, acc) { - return { - average: createMetricPattern2(client, _m(acc, 'average')), - cumulative: createMetricPattern1(client, _m(acc, 'cumulative')), - height: createMetricPattern12(client, acc), - max: createMetricPattern2(client, _m(acc, 'max')), - min: createMetricPattern2(client, _m(acc, 'min')), - percentiles: createPercentilesPattern(client, acc), - sum: createMetricPattern2(client, _m(acc, 'sum')), - }; -} - -/** - * @template T - * @typedef {Object} SizePattern - * @property {MetricPattern1} average - * @property {MetricPattern1} cumulative - * @property {MetricPattern1} max - * @property {MetricPattern1} min - * @property {PercentilesPattern} percentiles - * @property {MetricPattern1} sum - */ - -/** - * Create a SizePattern pattern node - * @template T - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {SizePattern} - */ -function createSizePattern(client, acc) { - return { - average: createMetricPattern1(client, _m(acc, 'average')), - cumulative: createMetricPattern1(client, _m(acc, 'cumulative')), - max: createMetricPattern1(client, _m(acc, 'max')), - min: createMetricPattern1(client, _m(acc, 'min')), - percentiles: createPercentilesPattern(client, acc), - sum: createMetricPattern1(client, _m(acc, 'sum')), - }; -} - /** * @typedef {Object} ActivityPattern2 * @property {BlockCountPattern} coinblocksDestroyed * @property {BlockCountPattern} coindaysDestroyed - * @property {MetricPattern12} satblocksDestroyed - * @property {MetricPattern12} satdaysDestroyed + * @property {MetricPattern11} satblocksDestroyed + * @property {MetricPattern11} satdaysDestroyed * @property {UnclaimedRewardsPattern} sent */ @@ -2880,138 +2827,42 @@ function createActivityPattern2(client, acc) { return { coinblocksDestroyed: createBlockCountPattern(client, _m(acc, 'coinblocks_destroyed')), coindaysDestroyed: createBlockCountPattern(client, _m(acc, 'coindays_destroyed')), - satblocksDestroyed: createMetricPattern12(client, _m(acc, 'satblocks_destroyed')), - satdaysDestroyed: createMetricPattern12(client, _m(acc, 'satdays_destroyed')), + satblocksDestroyed: createMetricPattern11(client, _m(acc, 'satblocks_destroyed')), + satdaysDestroyed: createMetricPattern11(client, _m(acc, 'satdays_destroyed')), sent: createUnclaimedRewardsPattern(client, _m(acc, 'sent')), }; } /** * @template T - * @typedef {Object} PercentilesPattern - * @property {MetricPattern7} median - * @property {MetricPattern7} pct10 - * @property {MetricPattern7} pct25 - * @property {MetricPattern7} pct75 - * @property {MetricPattern7} pct90 + * @typedef {Object} SplitPattern + * @property {MetricPattern5} close + * @property {MetricPattern5} high + * @property {MetricPattern5} low + * @property {MetricPattern5} open */ /** - * Create a PercentilesPattern pattern node + * Create a SplitPattern pattern node * @template T * @param {BrkClientBase} client * @param {string} acc - Accumulated metric name - * @returns {PercentilesPattern} + * @returns {SplitPattern} */ -function createPercentilesPattern(client, acc) { +function createSplitPattern(client, acc) { return { - median: createMetricPattern7(client, _m(acc, 'median')), - pct10: createMetricPattern7(client, _m(acc, 'pct10')), - pct25: createMetricPattern7(client, _m(acc, 'pct25')), - pct75: createMetricPattern7(client, _m(acc, 'pct75')), - pct90: createMetricPattern7(client, _m(acc, 'pct90')), - }; -} - -/** - * @typedef {Object} DateindexPattern2 - * @property {MetricPattern7} close - * @property {MetricPattern7} high - * @property {MetricPattern7} low - * @property {MetricPattern7} open - */ - -/** - * Create a DateindexPattern2 pattern node - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {DateindexPattern2} - */ -function createDateindexPattern2(client, acc) { - return { - close: createMetricPattern7(client, _m(acc, 'close_cents')), - high: createMetricPattern7(client, _m(acc, 'high_cents')), - low: createMetricPattern7(client, _m(acc, 'low_cents')), - open: createMetricPattern7(client, _m(acc, 'open_cents')), - }; -} - -/** - * @template T - * @typedef {Object} HighPattern - * @property {MetricPattern7} dateindex - * @property {MetricPattern9} difficultyepoch - * @property {MetricPattern12} height - * @property {MetricPattern5} rest - */ - -/** - * Create a HighPattern pattern node - * @template T - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {HighPattern} - */ -function createHighPattern(client, acc) { - return { - dateindex: createMetricPattern7(client, acc), - difficultyepoch: createMetricPattern9(client, _m(acc, 'max')), - height: createMetricPattern12(client, acc), - rest: createMetricPattern5(client, _m(acc, 'max')), - }; -} - -/** - * @template T - * @typedef {Object} SplitPattern2 - * @property {MetricPattern1} close - * @property {HighPattern} high - * @property {HighPattern} low - * @property {MetricPattern1} open - */ - -/** - * Create a SplitPattern2 pattern node - * @template T - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {SplitPattern2} - */ -function createSplitPattern2(client, acc) { - return { - close: createMetricPattern1(client, _m(acc, 'close')), - high: createHighPattern(client, _m(acc, 'high')), - low: createHighPattern(client, _m(acc, 'low')), - open: createMetricPattern1(client, _m(acc, 'open')), - }; -} - -/** - * @typedef {Object} _24hCoinbaseSumPattern - * @property {MetricPattern12} bitcoin - * @property {MetricPattern12} dollars - * @property {MetricPattern12} sats - */ - -/** - * Create a _24hCoinbaseSumPattern pattern node - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {_24hCoinbaseSumPattern} - */ -function create_24hCoinbaseSumPattern(client, acc) { - return { - bitcoin: createMetricPattern12(client, _m(acc, 'btc')), - dollars: createMetricPattern12(client, _m(acc, 'usd')), - sats: createMetricPattern12(client, acc), + close: createMetricPattern5(client, _m(acc, 'close_cents')), + high: createMetricPattern5(client, _m(acc, 'high_cents')), + low: createMetricPattern5(client, _m(acc, 'low_cents')), + open: createMetricPattern5(client, _m(acc, 'open_cents')), }; } /** * @typedef {Object} CoinbasePattern - * @property {BitcoinPattern} bitcoin - * @property {BitcoinPattern} dollars - * @property {BitcoinPattern} sats + * @property {FullnessPattern} bitcoin + * @property {FullnessPattern} dollars + * @property {FullnessPattern} sats */ /** @@ -3022,9 +2873,72 @@ function create_24hCoinbaseSumPattern(client, acc) { */ function createCoinbasePattern(client, acc) { return { - bitcoin: createBitcoinPattern(client, _m(acc, 'btc')), - dollars: createBitcoinPattern(client, _m(acc, 'usd')), - sats: createBitcoinPattern(client, acc), + bitcoin: createFullnessPattern(client, _m(acc, 'btc')), + dollars: createFullnessPattern(client, _m(acc, 'usd')), + sats: createFullnessPattern(client, acc), + }; +} + +/** + * @typedef {Object} SegwitAdoptionPattern + * @property {MetricPattern11} base + * @property {MetricPattern2} cumulative + * @property {MetricPattern2} sum + */ + +/** + * Create a SegwitAdoptionPattern pattern node + * @param {BrkClientBase} client + * @param {string} acc - Accumulated metric name + * @returns {SegwitAdoptionPattern} + */ +function createSegwitAdoptionPattern(client, acc) { + return { + base: createMetricPattern11(client, acc), + cumulative: createMetricPattern2(client, _m(acc, 'cumulative')), + sum: createMetricPattern2(client, _m(acc, 'sum')), + }; +} + +/** + * @typedef {Object} _24hCoinbaseSumPattern + * @property {MetricPattern11} bitcoin + * @property {MetricPattern11} dollars + * @property {MetricPattern11} sats + */ + +/** + * Create a _24hCoinbaseSumPattern pattern node + * @param {BrkClientBase} client + * @param {string} acc - Accumulated metric name + * @returns {_24hCoinbaseSumPattern} + */ +function create_24hCoinbaseSumPattern(client, acc) { + return { + bitcoin: createMetricPattern11(client, _m(acc, 'btc')), + dollars: createMetricPattern11(client, _m(acc, 'usd')), + sats: createMetricPattern11(client, acc), + }; +} + +/** + * @typedef {Object} CostBasisPattern2 + * @property {MetricPattern1} max + * @property {MetricPattern1} min + * @property {PercentilesPattern} percentiles + */ + +/** + * Create a CostBasisPattern2 pattern node + * @param {BrkClientBase} client + * @param {string} acc - Accumulated metric name + * @returns {CostBasisPattern2} + */ +function createCostBasisPattern2(client, acc) { + return { + max: createMetricPattern1(client, _m(acc, 'max_cost_basis')), + min: createMetricPattern1(client, _m(acc, 'min_cost_basis')), + percentiles: createPercentilesPattern(client, _m(acc, 'cost_basis')), }; } @@ -3050,63 +2964,21 @@ function createUnclaimedRewardsPattern(client, acc) { } /** - * @typedef {Object} CostBasisPattern2 - * @property {MetricPattern1} max - * @property {MetricPattern1} min - * @property {PercentilesPattern2} percentiles + * @typedef {Object} RelativePattern4 + * @property {MetricPattern1} supplyInLossRelToOwnSupply + * @property {MetricPattern1} supplyInProfitRelToOwnSupply */ /** - * Create a CostBasisPattern2 pattern node + * Create a RelativePattern4 pattern node * @param {BrkClientBase} client * @param {string} acc - Accumulated metric name - * @returns {CostBasisPattern2} + * @returns {RelativePattern4} */ -function createCostBasisPattern2(client, acc) { +function createRelativePattern4(client, acc) { return { - max: createMetricPattern1(client, _m(acc, 'max_cost_basis')), - min: createMetricPattern1(client, _m(acc, 'min_cost_basis')), - percentiles: createPercentilesPattern2(client, _m(acc, 'cost_basis')), - }; -} - -/** - * @typedef {Object} SegwitAdoptionPattern - * @property {MetricPattern2} cumulative - * @property {MetricPattern12} height - * @property {MetricPattern2} sum - */ - -/** - * Create a SegwitAdoptionPattern pattern node - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {SegwitAdoptionPattern} - */ -function createSegwitAdoptionPattern(client, acc) { - return { - cumulative: createMetricPattern2(client, _m(acc, 'cumulative')), - height: createMetricPattern12(client, acc), - sum: createMetricPattern2(client, _m(acc, 'sum')), - }; -} - -/** - * @typedef {Object} SatsPattern - * @property {OhlcPattern} ohlc - * @property {SplitPattern2} split - */ - -/** - * Create a SatsPattern pattern node - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {SatsPattern} - */ -function createSatsPattern(client, acc) { - return { - ohlc: createOhlcPattern(client, _m(acc, 'ohlc_sats')), - split: createSplitPattern2(client, _m(acc, 'sats')), + supplyInLossRelToOwnSupply: createMetricPattern1(client, _m(acc, 'loss_rel_to_own_supply')), + supplyInProfitRelToOwnSupply: createMetricPattern1(client, _m(acc, 'profit_rel_to_own_supply')), }; } @@ -3129,25 +3001,6 @@ function createCostBasisPattern(client, acc) { }; } -/** - * @typedef {Object} _1dReturns1mSdPattern - * @property {MetricPattern4} sd - * @property {MetricPattern4} sma - */ - -/** - * Create a _1dReturns1mSdPattern pattern node - * @param {BrkClientBase} client - * @param {string} acc - Accumulated metric name - * @returns {_1dReturns1mSdPattern} - */ -function create_1dReturns1mSdPattern(client, acc) { - return { - sd: createMetricPattern4(client, _m(acc, 'sd')), - sma: createMetricPattern4(client, _m(acc, 'sma')), - }; -} - /** * @typedef {Object} SupplyPattern2 * @property {_24hCoinbaseSumPattern} halved @@ -3168,28 +3021,117 @@ function createSupplyPattern2(client, acc) { } /** - * @typedef {Object} RelativePattern4 - * @property {MetricPattern1} supplyInLossRelToOwnSupply - * @property {MetricPattern1} supplyInProfitRelToOwnSupply + * @typedef {Object} _1dReturns1mSdPattern + * @property {MetricPattern4} sd + * @property {MetricPattern4} sma */ /** - * Create a RelativePattern4 pattern node + * Create a _1dReturns1mSdPattern pattern node * @param {BrkClientBase} client * @param {string} acc - Accumulated metric name - * @returns {RelativePattern4} + * @returns {_1dReturns1mSdPattern} */ -function createRelativePattern4(client, acc) { +function create_1dReturns1mSdPattern(client, acc) { return { - supplyInLossRelToOwnSupply: createMetricPattern1(client, _m(acc, 'loss_rel_to_own_supply')), - supplyInProfitRelToOwnSupply: createMetricPattern1(client, _m(acc, 'profit_rel_to_own_supply')), + sd: createMetricPattern4(client, _m(acc, 'sd')), + sma: createMetricPattern4(client, _m(acc, 'sma')), + }; +} + +/** + * @template T + * @typedef {Object} CentsPattern + * @property {MetricPattern5} ohlc + * @property {SplitPattern} split + */ + +/** + * Create a CentsPattern pattern node + * @template T + * @param {BrkClientBase} client + * @param {string} acc - Accumulated metric name + * @returns {CentsPattern} + */ +function createCentsPattern(client, acc) { + return { + ohlc: createMetricPattern5(client, _m(acc, 'ohlc_sats')), + split: createSplitPattern(client, _m(acc, 'sats')), + }; +} + +/** + * @template T + * @typedef {Object} UsdPricePattern + * @property {MetricPattern5} ohlc + * @property {UsdPriceSplitPattern} split + */ + +/** + * @template T + * @typedef {Object} UsdPriceSplitPattern + * @property {MetricPattern1} close + * @property {MetricPattern1} high + * @property {MetricPattern1} low + * @property {MetricPattern1} open + */ + +/** + * Create a UsdPricePattern pattern node + * @template T + * @param {BrkClientBase} client + * @returns {UsdPricePattern} + */ +function createUsdPricePattern(client) { + return { + ohlc: createMetricPattern5(client, 'price_ohlc'), + split: { + close: createMetricPattern1(client, 'price_close'), + high: createMetricPattern1(client, 'price_high'), + low: createMetricPattern1(client, 'price_low'), + open: createMetricPattern1(client, 'price_open'), + }, + }; +} + +/** + * @template T + * @typedef {Object} SatsPricePattern + * @property {MetricPattern5} ohlc + * @property {SatsPriceSplitPattern} split + */ + +/** + * @template T + * @typedef {Object} SatsPriceSplitPattern + * @property {MetricPattern1} close + * @property {MetricPattern1} high + * @property {MetricPattern1} low + * @property {MetricPattern1} open + */ + +/** + * Create a SatsPricePattern pattern node + * @template T + * @param {BrkClientBase} client + * @returns {SatsPricePattern} + */ +function createSatsPricePattern(client) { + return { + ohlc: createMetricPattern5(client, 'price_ohlc_sats'), + split: { + close: createMetricPattern1(client, 'price_sats_close'), + high: createMetricPattern1(client, 'price_sats_high'), + low: createMetricPattern1(client, 'price_sats_low'), + open: createMetricPattern1(client, 'price_sats_open'), + }, }; } /** * @template T * @typedef {Object} BlockCountPattern - * @property {MetricPattern2} cumulative + * @property {MetricPattern1} cumulative * @property {MetricPattern1} sum */ @@ -3202,7 +3144,7 @@ function createRelativePattern4(client, acc) { */ function createBlockCountPattern(client, acc) { return { - cumulative: createMetricPattern2(client, _m(acc, 'cumulative')), + cumulative: createMetricPattern1(client, _m(acc, 'cumulative')), sum: createMetricPattern1(client, acc), }; } @@ -3244,7 +3186,7 @@ function createOutputsPattern(client, acc) { /** * @template T * @typedef {Object} EmptyPattern - * @property {MetricPattern25} identity + * @property {MetricPattern23} identity */ /** @@ -3256,7 +3198,7 @@ function createOutputsPattern(client, acc) { */ function createEmptyPattern(client, acc) { return { - identity: createMetricPattern25(client, acc), + identity: createMetricPattern23(client, acc), }; } @@ -3283,60 +3225,63 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Addresses - * @property {MetricPattern12} firstP2aaddressindex - * @property {MetricPattern12} firstP2pk33addressindex - * @property {MetricPattern12} firstP2pk65addressindex - * @property {MetricPattern12} firstP2pkhaddressindex - * @property {MetricPattern12} firstP2shaddressindex - * @property {MetricPattern12} firstP2traddressindex - * @property {MetricPattern12} firstP2wpkhaddressindex - * @property {MetricPattern12} firstP2wshaddressindex - * @property {MetricPattern17} p2abytes - * @property {MetricPattern19} p2pk33bytes - * @property {MetricPattern20} p2pk65bytes - * @property {MetricPattern21} p2pkhbytes - * @property {MetricPattern22} p2shbytes - * @property {MetricPattern23} p2trbytes - * @property {MetricPattern24} p2wpkhbytes - * @property {MetricPattern25} p2wshbytes + * @property {MetricPattern11} firstP2aaddressindex + * @property {MetricPattern11} firstP2pk33addressindex + * @property {MetricPattern11} firstP2pk65addressindex + * @property {MetricPattern11} firstP2pkhaddressindex + * @property {MetricPattern11} firstP2shaddressindex + * @property {MetricPattern11} firstP2traddressindex + * @property {MetricPattern11} firstP2wpkhaddressindex + * @property {MetricPattern11} firstP2wshaddressindex + * @property {MetricPattern16} p2abytes + * @property {MetricPattern18} p2pk33bytes + * @property {MetricPattern19} p2pk65bytes + * @property {MetricPattern20} p2pkhbytes + * @property {MetricPattern21} p2shbytes + * @property {MetricPattern22} p2trbytes + * @property {MetricPattern23} p2wpkhbytes + * @property {MetricPattern24} p2wshbytes */ /** * @typedef {Object} CatalogTree_Blocks - * @property {MetricPattern12} blockhash + * @property {MetricPattern11} blockhash * @property {CatalogTree_Blocks_Count} count * @property {CatalogTree_Blocks_Difficulty} difficulty + * @property {FullnessPattern} fullness * @property {CatalogTree_Blocks_Halving} halving * @property {CatalogTree_Blocks_Interval} interval * @property {CatalogTree_Blocks_Mining} mining * @property {CatalogTree_Blocks_Rewards} rewards - * @property {CatalogTree_Blocks_Size} size + * @property {SizePattern} size * @property {CatalogTree_Blocks_Time} time - * @property {MetricPattern12} timestamp - * @property {MetricPattern12} totalSize - * @property {CatalogTree_Blocks_Weight} weight + * @property {MetricPattern11} totalSize + * @property {FullnessPattern} vbytes + * @property {FullnessPattern} weight */ /** * @typedef {Object} CatalogTree_Blocks_Count * @property {MetricPattern1} _1mBlockCount - * @property {MetricPattern12} _1mStart + * @property {MetricPattern11} _1mStart * @property {MetricPattern1} _1wBlockCount - * @property {MetricPattern12} _1wStart + * @property {MetricPattern11} _1wStart * @property {MetricPattern1} _1yBlockCount - * @property {MetricPattern12} _1yStart + * @property {MetricPattern11} _1yStart * @property {MetricPattern1} _24hBlockCount - * @property {MetricPattern12} _24hStart + * @property {MetricPattern11} _24hStart * @property {BlockCountPattern} blockCount * @property {MetricPattern4} blockCountTarget */ /** * @typedef {Object} CatalogTree_Blocks_Difficulty - * @property {MetricPattern12} base - * @property {MetricPattern1} blocksBeforeNextDifficultyAdjustment - * @property {MetricPattern1} daysBeforeNextDifficultyAdjustment + * @property {MetricPattern1} adjustment + * @property {MetricPattern1} asHash + * @property {MetricPattern1} blocksBeforeNextAdjustment + * @property {MetricPattern1} daysBeforeNextAdjustment * @property {MetricPattern4} epoch + * @property {MetricPattern1} raw */ /** @@ -3349,21 +3294,18 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Blocks_Interval * @property {MetricPattern2} average - * @property {MetricPattern12} base + * @property {MetricPattern11} base * @property {MetricPattern2} max - * @property {MetricPattern7} median + * @property {MetricPattern6} median * @property {MetricPattern2} min - * @property {MetricPattern7} pct10 - * @property {MetricPattern7} pct25 - * @property {MetricPattern7} pct75 - * @property {MetricPattern7} pct90 + * @property {MetricPattern6} pct10 + * @property {MetricPattern6} pct25 + * @property {MetricPattern6} pct75 + * @property {MetricPattern6} pct90 */ /** * @typedef {Object} CatalogTree_Blocks_Mining - * @property {MetricPattern2} difficulty - * @property {MetricPattern1} difficultyAdjustment - * @property {MetricPattern1} difficultyAsHash * @property {MetricPattern1} hashPricePhs * @property {MetricPattern1} hashPricePhsMin * @property {MetricPattern1} hashPriceRebound @@ -3385,43 +3327,19 @@ function createEmptyPattern(client, acc) { * @typedef {Object} CatalogTree_Blocks_Rewards * @property {_24hCoinbaseSumPattern} _24hCoinbaseSum * @property {CoinbasePattern} coinbase - * @property {MetricPattern7} feeDominance + * @property {MetricPattern6} feeDominance * @property {CoinbasePattern} subsidy - * @property {MetricPattern7} subsidyDominance + * @property {MetricPattern6} subsidyDominance * @property {MetricPattern4} subsidyUsd1ySma * @property {UnclaimedRewardsPattern} unclaimedRewards */ -/** - * @typedef {Object} CatalogTree_Blocks_Size - * @property {SizePattern} size - * @property {CatalogTree_Blocks_Size_Vbytes} vbytes - */ - -/** - * @typedef {Object} CatalogTree_Blocks_Size_Vbytes - * @property {MetricPattern2} average - * @property {MetricPattern12} base - * @property {MetricPattern1} cumulative - * @property {MetricPattern2} max - * @property {MetricPattern2} min - * @property {PercentilesPattern} percentiles - * @property {MetricPattern2} sum - */ - /** * @typedef {Object} CatalogTree_Blocks_Time - * @property {MetricPattern12} date - * @property {MetricPattern12} dateFixed - * @property {MetricPattern2} timestamp - * @property {MetricPattern12} timestampFixed - */ - -/** - * @typedef {Object} CatalogTree_Blocks_Weight - * @property {MetricPattern12} base - * @property {BitcoinPattern} fullness - * @property {SizePattern} weight + * @property {MetricPattern11} date + * @property {MetricPattern11} dateFixed + * @property {MetricPattern1} timestamp + * @property {MetricPattern11} timestampFixed */ /** @@ -3486,24 +3404,24 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Constants - * @property {MetricPattern3} constant0 - * @property {MetricPattern3} constant1 - * @property {MetricPattern3} constant100 - * @property {MetricPattern3} constant2 - * @property {MetricPattern3} constant20 - * @property {MetricPattern3} constant3 - * @property {MetricPattern3} constant30 - * @property {MetricPattern3} constant382 - * @property {MetricPattern3} constant4 - * @property {MetricPattern3} constant50 - * @property {MetricPattern3} constant600 - * @property {MetricPattern3} constant618 - * @property {MetricPattern3} constant70 - * @property {MetricPattern3} constant80 - * @property {MetricPattern3} constantMinus1 - * @property {MetricPattern3} constantMinus2 - * @property {MetricPattern3} constantMinus3 - * @property {MetricPattern3} constantMinus4 + * @property {MetricPattern1} constant0 + * @property {MetricPattern1} constant1 + * @property {MetricPattern1} constant100 + * @property {MetricPattern1} constant2 + * @property {MetricPattern1} constant20 + * @property {MetricPattern1} constant3 + * @property {MetricPattern1} constant30 + * @property {MetricPattern1} constant382 + * @property {MetricPattern1} constant4 + * @property {MetricPattern1} constant50 + * @property {MetricPattern1} constant600 + * @property {MetricPattern1} constant618 + * @property {MetricPattern1} constant70 + * @property {MetricPattern1} constant80 + * @property {MetricPattern1} constantMinus1 + * @property {MetricPattern1} constantMinus2 + * @property {MetricPattern1} constantMinus3 + * @property {MetricPattern1} constantMinus4 */ /** @@ -3512,10 +3430,10 @@ function createEmptyPattern(client, acc) { * @property {CatalogTree_Distribution_AddressCohorts} addressCohorts * @property {CatalogTree_Distribution_AddressesData} addressesData * @property {CatalogTree_Distribution_AnyAddressIndexes} anyAddressIndexes - * @property {MetricPattern12} chainState + * @property {MetricPattern11} chainState * @property {AddrCountPattern} emptyAddrCount - * @property {MetricPattern33} emptyaddressindex - * @property {MetricPattern32} loadedaddressindex + * @property {MetricPattern32} emptyaddressindex + * @property {MetricPattern31} loadedaddressindex * @property {CatalogTree_Distribution_UtxoCohorts} utxoCohorts */ @@ -3581,20 +3499,20 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Distribution_AddressesData - * @property {MetricPattern33} empty - * @property {MetricPattern32} loaded + * @property {MetricPattern32} empty + * @property {MetricPattern31} loaded */ /** * @typedef {Object} CatalogTree_Distribution_AnyAddressIndexes - * @property {MetricPattern17} p2a - * @property {MetricPattern19} p2pk33 - * @property {MetricPattern20} p2pk65 - * @property {MetricPattern21} p2pkh - * @property {MetricPattern22} p2sh - * @property {MetricPattern23} p2tr - * @property {MetricPattern24} p2wpkh - * @property {MetricPattern25} p2wsh + * @property {MetricPattern16} p2a + * @property {MetricPattern18} p2pk33 + * @property {MetricPattern19} p2pk65 + * @property {MetricPattern20} p2pkh + * @property {MetricPattern21} p2sh + * @property {MetricPattern22} p2tr + * @property {MetricPattern23} p2wpkh + * @property {MetricPattern24} p2wsh */ /** @@ -3865,105 +3783,105 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Indexes_Dateindex - * @property {MetricPattern7} date - * @property {MetricPattern7} firstHeight - * @property {MetricPattern7} heightCount - * @property {MetricPattern7} identity - * @property {MetricPattern7} monthindex - * @property {MetricPattern7} weekindex + * @property {MetricPattern6} date + * @property {MetricPattern6} firstHeight + * @property {MetricPattern6} heightCount + * @property {MetricPattern6} identity + * @property {MetricPattern6} monthindex + * @property {MetricPattern6} weekindex */ /** * @typedef {Object} CatalogTree_Indexes_Decadeindex - * @property {MetricPattern8} firstYearindex - * @property {MetricPattern8} identity - * @property {MetricPattern8} yearindexCount + * @property {MetricPattern7} firstYearindex + * @property {MetricPattern7} identity + * @property {MetricPattern7} yearindexCount */ /** * @typedef {Object} CatalogTree_Indexes_Difficultyepoch - * @property {MetricPattern9} firstHeight - * @property {MetricPattern9} heightCount - * @property {MetricPattern9} identity + * @property {MetricPattern8} firstHeight + * @property {MetricPattern8} heightCount + * @property {MetricPattern8} identity */ /** * @typedef {Object} CatalogTree_Indexes_Halvingepoch - * @property {MetricPattern11} firstHeight - * @property {MetricPattern11} identity + * @property {MetricPattern10} firstHeight + * @property {MetricPattern10} identity */ /** * @typedef {Object} CatalogTree_Indexes_Height - * @property {MetricPattern12} dateindex - * @property {MetricPattern12} difficultyepoch - * @property {MetricPattern12} halvingepoch - * @property {MetricPattern12} identity - * @property {MetricPattern12} txindexCount + * @property {MetricPattern11} dateindex + * @property {MetricPattern11} difficultyepoch + * @property {MetricPattern11} halvingepoch + * @property {MetricPattern11} identity + * @property {MetricPattern11} txindexCount */ /** * @typedef {Object} CatalogTree_Indexes_Monthindex - * @property {MetricPattern14} dateindexCount - * @property {MetricPattern14} firstDateindex - * @property {MetricPattern14} identity - * @property {MetricPattern14} quarterindex - * @property {MetricPattern14} semesterindex - * @property {MetricPattern14} yearindex + * @property {MetricPattern13} dateindexCount + * @property {MetricPattern13} firstDateindex + * @property {MetricPattern13} identity + * @property {MetricPattern13} quarterindex + * @property {MetricPattern13} semesterindex + * @property {MetricPattern13} yearindex */ /** * @typedef {Object} CatalogTree_Indexes_Quarterindex - * @property {MetricPattern26} firstMonthindex - * @property {MetricPattern26} identity - * @property {MetricPattern26} monthindexCount + * @property {MetricPattern25} firstMonthindex + * @property {MetricPattern25} identity + * @property {MetricPattern25} monthindexCount */ /** * @typedef {Object} CatalogTree_Indexes_Semesterindex - * @property {MetricPattern27} firstMonthindex - * @property {MetricPattern27} identity - * @property {MetricPattern27} monthindexCount + * @property {MetricPattern26} firstMonthindex + * @property {MetricPattern26} identity + * @property {MetricPattern26} monthindexCount */ /** * @typedef {Object} CatalogTree_Indexes_Txindex - * @property {MetricPattern28} identity - * @property {MetricPattern28} inputCount - * @property {MetricPattern28} outputCount + * @property {MetricPattern27} identity + * @property {MetricPattern27} inputCount + * @property {MetricPattern27} outputCount */ /** * @typedef {Object} CatalogTree_Indexes_Weekindex - * @property {MetricPattern30} dateindexCount - * @property {MetricPattern30} firstDateindex - * @property {MetricPattern30} identity + * @property {MetricPattern29} dateindexCount + * @property {MetricPattern29} firstDateindex + * @property {MetricPattern29} identity */ /** * @typedef {Object} CatalogTree_Indexes_Yearindex - * @property {MetricPattern31} decadeindex - * @property {MetricPattern31} firstMonthindex - * @property {MetricPattern31} identity - * @property {MetricPattern31} monthindexCount + * @property {MetricPattern30} decadeindex + * @property {MetricPattern30} firstMonthindex + * @property {MetricPattern30} identity + * @property {MetricPattern30} monthindexCount */ /** * @typedef {Object} CatalogTree_Inputs * @property {SizePattern} count - * @property {MetricPattern12} firstTxinindex - * @property {MetricPattern13} outpoint - * @property {MetricPattern13} outputtype + * @property {MetricPattern11} firstTxinindex + * @property {MetricPattern12} outpoint + * @property {MetricPattern12} outputtype * @property {CatalogTree_Inputs_Spent} spent - * @property {MetricPattern13} txindex - * @property {MetricPattern13} typeindex - * @property {MetricPattern13} witnessSize + * @property {MetricPattern12} txindex + * @property {MetricPattern12} typeindex + * @property {MetricPattern12} witnessSize */ /** * @typedef {Object} CatalogTree_Inputs_Spent - * @property {MetricPattern13} txoutindex - * @property {MetricPattern13} value + * @property {MetricPattern12} txoutindex + * @property {MetricPattern12} value */ /** @@ -4017,25 +3935,25 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Market_Indicators - * @property {MetricPattern7} gini - * @property {MetricPattern7} macdHistogram - * @property {MetricPattern7} macdLine - * @property {MetricPattern7} macdSignal + * @property {MetricPattern6} gini + * @property {MetricPattern6} macdHistogram + * @property {MetricPattern6} macdLine + * @property {MetricPattern6} macdSignal * @property {MetricPattern4} nvt - * @property {MetricPattern7} piCycle + * @property {MetricPattern6} piCycle * @property {MetricPattern4} puellMultiple - * @property {MetricPattern7} rsi14d - * @property {MetricPattern7} rsi14dMax - * @property {MetricPattern7} rsi14dMin - * @property {MetricPattern7} rsiAverageGain14d - * @property {MetricPattern7} rsiAverageLoss14d - * @property {MetricPattern7} rsiGains - * @property {MetricPattern7} rsiLosses - * @property {MetricPattern7} stochD - * @property {MetricPattern7} stochK - * @property {MetricPattern7} stochRsi - * @property {MetricPattern7} stochRsiD - * @property {MetricPattern7} stochRsiK + * @property {MetricPattern6} rsi14d + * @property {MetricPattern6} rsi14dMax + * @property {MetricPattern6} rsi14dMin + * @property {MetricPattern6} rsiAverageGain14d + * @property {MetricPattern6} rsiAverageLoss14d + * @property {MetricPattern6} rsiGains + * @property {MetricPattern6} rsiLosses + * @property {MetricPattern6} stochD + * @property {MetricPattern6} stochK + * @property {MetricPattern6} stochRsi + * @property {MetricPattern6} stochRsiD + * @property {MetricPattern6} stochRsiK */ /** @@ -4093,8 +4011,8 @@ function createEmptyPattern(client, acc) { * @property {MetricPattern4} price2wChoppinessIndex * @property {MetricPattern4} price2wMax * @property {MetricPattern4} price2wMin - * @property {MetricPattern7} priceTrueRange - * @property {MetricPattern7} priceTrueRange2wSum + * @property {MetricPattern6} priceTrueRange + * @property {MetricPattern6} priceTrueRange2wSum */ /** @@ -4106,7 +4024,7 @@ function createEmptyPattern(client, acc) { * @property {_1dReturns1mSdPattern} downside1mSd * @property {_1dReturns1mSdPattern} downside1wSd * @property {_1dReturns1mSdPattern} downside1ySd - * @property {MetricPattern7} downsideReturns + * @property {MetricPattern6} downsideReturns * @property {PriceAgoPattern} priceReturns */ @@ -4115,39 +4033,39 @@ function createEmptyPattern(client, acc) { * @property {MetricPattern4} price1mVolatility * @property {MetricPattern4} price1wVolatility * @property {MetricPattern4} price1yVolatility - * @property {MetricPattern7} sharpe1m - * @property {MetricPattern7} sharpe1w - * @property {MetricPattern7} sharpe1y - * @property {MetricPattern7} sortino1m - * @property {MetricPattern7} sortino1w - * @property {MetricPattern7} sortino1y + * @property {MetricPattern6} sharpe1m + * @property {MetricPattern6} sharpe1w + * @property {MetricPattern6} sharpe1y + * @property {MetricPattern6} sortino1m + * @property {MetricPattern6} sortino1w + * @property {MetricPattern6} sortino1y */ /** * @typedef {Object} CatalogTree_Outputs * @property {CatalogTree_Outputs_Count} count - * @property {MetricPattern12} firstTxoutindex - * @property {MetricPattern16} outputtype + * @property {MetricPattern11} firstTxoutindex + * @property {MetricPattern15} outputtype * @property {CatalogTree_Outputs_Spent} spent - * @property {MetricPattern16} txindex - * @property {MetricPattern16} typeindex - * @property {MetricPattern16} value + * @property {MetricPattern15} txindex + * @property {MetricPattern15} typeindex + * @property {MetricPattern15} value */ /** * @typedef {Object} CatalogTree_Outputs_Count * @property {SizePattern} totalCount - * @property {BitcoinPattern} utxoCount + * @property {FullnessPattern} utxoCount */ /** * @typedef {Object} CatalogTree_Outputs_Spent - * @property {MetricPattern16} txinindex + * @property {MetricPattern15} txinindex */ /** * @typedef {Object} CatalogTree_Pools - * @property {MetricPattern12} pool + * @property {MetricPattern11} heightToPool * @property {CatalogTree_Pools_Vecs} vecs */ @@ -4315,60 +4233,48 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Positions - * @property {MetricPattern12} blockPosition - * @property {MetricPattern28} txPosition + * @property {MetricPattern11} blockPosition + * @property {MetricPattern27} txPosition */ /** * @typedef {Object} CatalogTree_Price - * @property {CatalogTree_Price_Cents} cents - * @property {SatsPattern} sats - * @property {SatsPattern} usd - */ - -/** - * @typedef {Object} CatalogTree_Price_Cents - * @property {MetricPattern6} ohlc - * @property {CatalogTree_Price_Cents_Split} split - */ - -/** - * @typedef {Object} CatalogTree_Price_Cents_Split - * @property {DateindexPattern2} dateindex - * @property {DateindexPattern2} height + * @property {CentsPattern} cents + * @property {CentsPattern} sats + * @property {CentsPattern} usd */ /** * @typedef {Object} CatalogTree_Scripts * @property {CatalogTree_Scripts_Count} count - * @property {MetricPattern10} emptyToTxindex - * @property {MetricPattern12} firstEmptyoutputindex - * @property {MetricPattern12} firstOpreturnindex - * @property {MetricPattern12} firstP2msoutputindex - * @property {MetricPattern12} firstUnknownoutputindex - * @property {MetricPattern15} opreturnToTxindex - * @property {MetricPattern18} p2msToTxindex - * @property {MetricPattern29} unknownToTxindex + * @property {MetricPattern9} emptyToTxindex + * @property {MetricPattern11} firstEmptyoutputindex + * @property {MetricPattern11} firstOpreturnindex + * @property {MetricPattern11} firstP2msoutputindex + * @property {MetricPattern11} firstUnknownoutputindex + * @property {MetricPattern14} opreturnToTxindex + * @property {MetricPattern17} p2msToTxindex + * @property {MetricPattern28} unknownToTxindex * @property {CatalogTree_Scripts_Value} value */ /** * @typedef {Object} CatalogTree_Scripts_Count - * @property {BitcoinPattern} emptyoutput - * @property {BitcoinPattern} opreturn - * @property {BitcoinPattern} p2a - * @property {BitcoinPattern} p2ms - * @property {BitcoinPattern} p2pk33 - * @property {BitcoinPattern} p2pk65 - * @property {BitcoinPattern} p2pkh - * @property {BitcoinPattern} p2sh - * @property {BitcoinPattern} p2tr - * @property {BitcoinPattern} p2wpkh - * @property {BitcoinPattern} p2wsh - * @property {BitcoinPattern} segwit + * @property {FullnessPattern} emptyoutput + * @property {FullnessPattern} opreturn + * @property {FullnessPattern} p2a + * @property {FullnessPattern} p2ms + * @property {FullnessPattern} p2pk33 + * @property {FullnessPattern} p2pk65 + * @property {FullnessPattern} p2pkh + * @property {FullnessPattern} p2sh + * @property {FullnessPattern} p2tr + * @property {FullnessPattern} p2wpkh + * @property {FullnessPattern} p2wsh + * @property {FullnessPattern} segwit * @property {SegwitAdoptionPattern} segwitAdoption * @property {SegwitAdoptionPattern} taprootAdoption - * @property {BitcoinPattern} unknownoutput + * @property {FullnessPattern} unknownoutput */ /** @@ -4399,43 +4305,58 @@ function createEmptyPattern(client, acc) { /** * @typedef {Object} CatalogTree_Transactions - * @property {MetricPattern28} baseSize + * @property {MetricPattern27} baseSize * @property {CatalogTree_Transactions_Count} count * @property {CatalogTree_Transactions_Fees} fees - * @property {MetricPattern12} firstTxindex - * @property {MetricPattern28} firstTxinindex - * @property {MetricPattern28} firstTxoutindex - * @property {MetricPattern28} height - * @property {MetricPattern28} isExplicitlyRbf - * @property {MetricPattern28} rawlocktime + * @property {MetricPattern11} firstTxindex + * @property {MetricPattern27} firstTxinindex + * @property {MetricPattern27} firstTxoutindex + * @property {MetricPattern27} height + * @property {MetricPattern27} isExplicitlyRbf + * @property {MetricPattern27} rawlocktime * @property {CatalogTree_Transactions_Size} size - * @property {MetricPattern28} totalSize - * @property {MetricPattern28} txid - * @property {MetricPattern28} txversion + * @property {MetricPattern27} totalSize + * @property {MetricPattern27} txid + * @property {MetricPattern27} txversion * @property {CatalogTree_Transactions_Versions} versions * @property {CatalogTree_Transactions_Volume} volume */ /** * @typedef {Object} CatalogTree_Transactions_Count - * @property {MetricPattern28} isCoinbase - * @property {BitcoinPattern} txCount + * @property {MetricPattern27} isCoinbase + * @property {FullnessPattern} txCount */ /** * @typedef {Object} CatalogTree_Transactions_Fees * @property {CatalogTree_Transactions_Fees_Fee} fee * @property {FeeRatePattern} feeRate - * @property {MetricPattern28} inputValue - * @property {MetricPattern28} outputValue + * @property {MetricPattern27} inputValue + * @property {MetricPattern27} outputValue */ /** * @typedef {Object} CatalogTree_Transactions_Fees_Fee * @property {SizePattern} bitcoin - * @property {SizePattern} dollars + * @property {CatalogTree_Transactions_Fees_Fee_Dollars} dollars * @property {SizePattern} sats - * @property {MetricPattern28} txindex + * @property {MetricPattern27} txindex + */ + +/** + * @typedef {Object} CatalogTree_Transactions_Fees_Fee_Dollars + * @property {MetricPattern1} average + * @property {MetricPattern2} cumulative + * @property {MetricPattern11} heightCumulative + * @property {MetricPattern1} max + * @property {MetricPattern11} median + * @property {MetricPattern1} min + * @property {MetricPattern11} pct10 + * @property {MetricPattern11} pct25 + * @property {MetricPattern11} pct75 + * @property {MetricPattern11} pct90 + * @property {MetricPattern1} sum */ /** @@ -5375,43 +5296,46 @@ class BrkClient extends BrkClientBase { _buildTree(basePath) { return { addresses: { - firstP2aaddressindex: createMetricPattern12(this, 'first_p2aaddressindex'), - firstP2pk33addressindex: createMetricPattern12(this, 'first_p2pk33addressindex'), - firstP2pk65addressindex: createMetricPattern12(this, 'first_p2pk65addressindex'), - firstP2pkhaddressindex: createMetricPattern12(this, 'first_p2pkhaddressindex'), - firstP2shaddressindex: createMetricPattern12(this, 'first_p2shaddressindex'), - firstP2traddressindex: createMetricPattern12(this, 'first_p2traddressindex'), - firstP2wpkhaddressindex: createMetricPattern12(this, 'first_p2wpkhaddressindex'), - firstP2wshaddressindex: createMetricPattern12(this, 'first_p2wshaddressindex'), - p2abytes: createMetricPattern17(this, 'p2abytes'), - p2pk33bytes: createMetricPattern19(this, 'p2pk33bytes'), - p2pk65bytes: createMetricPattern20(this, 'p2pk65bytes'), - p2pkhbytes: createMetricPattern21(this, 'p2pkhbytes'), - p2shbytes: createMetricPattern22(this, 'p2shbytes'), - p2trbytes: createMetricPattern23(this, 'p2trbytes'), - p2wpkhbytes: createMetricPattern24(this, 'p2wpkhbytes'), - p2wshbytes: createMetricPattern25(this, 'p2wshbytes') + firstP2aaddressindex: createMetricPattern11(this, 'first_p2aaddressindex'), + firstP2pk33addressindex: createMetricPattern11(this, 'first_p2pk33addressindex'), + firstP2pk65addressindex: createMetricPattern11(this, 'first_p2pk65addressindex'), + firstP2pkhaddressindex: createMetricPattern11(this, 'first_p2pkhaddressindex'), + firstP2shaddressindex: createMetricPattern11(this, 'first_p2shaddressindex'), + firstP2traddressindex: createMetricPattern11(this, 'first_p2traddressindex'), + firstP2wpkhaddressindex: createMetricPattern11(this, 'first_p2wpkhaddressindex'), + firstP2wshaddressindex: createMetricPattern11(this, 'first_p2wshaddressindex'), + p2abytes: createMetricPattern16(this, 'p2abytes'), + p2pk33bytes: createMetricPattern18(this, 'p2pk33bytes'), + p2pk65bytes: createMetricPattern19(this, 'p2pk65bytes'), + p2pkhbytes: createMetricPattern20(this, 'p2pkhbytes'), + p2shbytes: createMetricPattern21(this, 'p2shbytes'), + p2trbytes: createMetricPattern22(this, 'p2trbytes'), + p2wpkhbytes: createMetricPattern23(this, 'p2wpkhbytes'), + p2wshbytes: createMetricPattern24(this, 'p2wshbytes') }, blocks: { - blockhash: createMetricPattern12(this, 'blockhash'), + blockhash: createMetricPattern11(this, 'blockhash'), count: { _1mBlockCount: createMetricPattern1(this, '1m_block_count'), - _1mStart: createMetricPattern12(this, '1m_start'), + _1mStart: createMetricPattern11(this, '1m_start'), _1wBlockCount: createMetricPattern1(this, '1w_block_count'), - _1wStart: createMetricPattern12(this, '1w_start'), + _1wStart: createMetricPattern11(this, '1w_start'), _1yBlockCount: createMetricPattern1(this, '1y_block_count'), - _1yStart: createMetricPattern12(this, '1y_start'), + _1yStart: createMetricPattern11(this, '1y_start'), _24hBlockCount: createMetricPattern1(this, '24h_block_count'), - _24hStart: createMetricPattern12(this, '24h_start'), + _24hStart: createMetricPattern11(this, '24h_start'), blockCount: createBlockCountPattern(this, 'block_count'), blockCountTarget: createMetricPattern4(this, 'block_count_target') }, difficulty: { - base: createMetricPattern12(this, 'difficulty'), - blocksBeforeNextDifficultyAdjustment: createMetricPattern1(this, 'blocks_before_next_difficulty_adjustment'), - daysBeforeNextDifficultyAdjustment: createMetricPattern1(this, 'days_before_next_difficulty_adjustment'), - epoch: createMetricPattern4(this, 'difficultyepoch') + adjustment: createMetricPattern1(this, 'difficulty_adjustment'), + asHash: createMetricPattern1(this, 'difficulty_as_hash'), + blocksBeforeNextAdjustment: createMetricPattern1(this, 'blocks_before_next_difficulty_adjustment'), + daysBeforeNextAdjustment: createMetricPattern1(this, 'days_before_next_difficulty_adjustment'), + epoch: createMetricPattern4(this, 'difficultyepoch'), + raw: createMetricPattern1(this, 'difficulty') }, + fullness: createFullnessPattern(this, 'block_fullness'), halving: { blocksBeforeNextHalving: createMetricPattern1(this, 'blocks_before_next_halving'), daysBeforeNextHalving: createMetricPattern1(this, 'days_before_next_halving'), @@ -5419,19 +5343,16 @@ class BrkClient extends BrkClientBase { }, interval: { average: createMetricPattern2(this, 'block_interval_average'), - base: createMetricPattern12(this, 'block_interval'), + base: createMetricPattern11(this, 'block_interval'), max: createMetricPattern2(this, 'block_interval_max'), - median: createMetricPattern7(this, 'block_interval_median'), + median: createMetricPattern6(this, 'block_interval_median'), min: createMetricPattern2(this, 'block_interval_min'), - pct10: createMetricPattern7(this, 'block_interval_pct10'), - pct25: createMetricPattern7(this, 'block_interval_pct25'), - pct75: createMetricPattern7(this, 'block_interval_pct75'), - pct90: createMetricPattern7(this, 'block_interval_pct90') + pct10: createMetricPattern6(this, 'block_interval_pct10'), + pct25: createMetricPattern6(this, 'block_interval_pct25'), + pct75: createMetricPattern6(this, 'block_interval_pct75'), + pct90: createMetricPattern6(this, 'block_interval_pct90') }, mining: { - difficulty: createMetricPattern2(this, 'difficulty'), - difficultyAdjustment: createMetricPattern1(this, 'difficulty_adjustment'), - difficultyAsHash: createMetricPattern1(this, 'difficulty_as_hash'), hashPricePhs: createMetricPattern1(this, 'hash_price_phs'), hashPricePhsMin: createMetricPattern1(this, 'hash_price_phs_min'), hashPriceRebound: createMetricPattern1(this, 'hash_price_rebound'), @@ -5451,37 +5372,22 @@ class BrkClient extends BrkClientBase { rewards: { _24hCoinbaseSum: create_24hCoinbaseSumPattern(this, '24h_coinbase_sum'), coinbase: createCoinbasePattern(this, 'coinbase'), - feeDominance: createMetricPattern7(this, 'fee_dominance'), + feeDominance: createMetricPattern6(this, 'fee_dominance'), subsidy: createCoinbasePattern(this, 'subsidy'), - subsidyDominance: createMetricPattern7(this, 'subsidy_dominance'), + subsidyDominance: createMetricPattern6(this, 'subsidy_dominance'), subsidyUsd1ySma: createMetricPattern4(this, 'subsidy_usd_1y_sma'), unclaimedRewards: createUnclaimedRewardsPattern(this, 'unclaimed_rewards') }, - size: { - size: createSizePattern(this, 'block_size'), - vbytes: { - average: createMetricPattern2(this, 'block_vbytes_average'), - base: createMetricPattern12(this, 'block_vbytes'), - cumulative: createMetricPattern1(this, 'block_vbytes_cumulative'), - max: createMetricPattern2(this, 'block_vbytes_max'), - min: createMetricPattern2(this, 'block_vbytes_min'), - percentiles: createPercentilesPattern(this, 'block_vbytes'), - sum: createMetricPattern2(this, 'block_vbytes_sum') - } - }, + size: createSizePattern(this, 'block_size'), time: { - date: createMetricPattern12(this, 'date'), - dateFixed: createMetricPattern12(this, 'date_fixed'), - timestamp: createMetricPattern2(this, 'timestamp'), - timestampFixed: createMetricPattern12(this, 'timestamp_fixed') + date: createMetricPattern11(this, 'date'), + dateFixed: createMetricPattern11(this, 'date_fixed'), + timestamp: createMetricPattern1(this, 'timestamp'), + timestampFixed: createMetricPattern11(this, 'timestamp_fixed') }, - timestamp: createMetricPattern12(this, 'timestamp'), - totalSize: createMetricPattern12(this, 'total_size'), - weight: { - base: createMetricPattern12(this, 'weight'), - fullness: createBitcoinPattern(this, 'block_fullness'), - weight: createSizePattern(this, 'block_weight') - } + totalSize: createMetricPattern11(this, 'total_size'), + vbytes: createFullnessPattern(this, 'block_vbytes'), + weight: createFullnessPattern(this, '') }, cointime: { activity: { @@ -5524,24 +5430,24 @@ class BrkClient extends BrkClientBase { } }, constants: { - constant0: createMetricPattern3(this, 'constant_0'), - constant1: createMetricPattern3(this, 'constant_1'), - constant100: createMetricPattern3(this, 'constant_100'), - constant2: createMetricPattern3(this, 'constant_2'), - constant20: createMetricPattern3(this, 'constant_20'), - constant3: createMetricPattern3(this, 'constant_3'), - constant30: createMetricPattern3(this, 'constant_30'), - constant382: createMetricPattern3(this, 'constant_38_2'), - constant4: createMetricPattern3(this, 'constant_4'), - constant50: createMetricPattern3(this, 'constant_50'), - constant600: createMetricPattern3(this, 'constant_600'), - constant618: createMetricPattern3(this, 'constant_61_8'), - constant70: createMetricPattern3(this, 'constant_70'), - constant80: createMetricPattern3(this, 'constant_80'), - constantMinus1: createMetricPattern3(this, 'constant_minus_1'), - constantMinus2: createMetricPattern3(this, 'constant_minus_2'), - constantMinus3: createMetricPattern3(this, 'constant_minus_3'), - constantMinus4: createMetricPattern3(this, 'constant_minus_4') + constant0: createMetricPattern1(this, 'constant_0'), + constant1: createMetricPattern1(this, 'constant_1'), + constant100: createMetricPattern1(this, 'constant_100'), + constant2: createMetricPattern1(this, 'constant_2'), + constant20: createMetricPattern1(this, 'constant_20'), + constant3: createMetricPattern1(this, 'constant_3'), + constant30: createMetricPattern1(this, 'constant_30'), + constant382: createMetricPattern1(this, 'constant_38_2'), + constant4: createMetricPattern1(this, 'constant_4'), + constant50: createMetricPattern1(this, 'constant_50'), + constant600: createMetricPattern1(this, 'constant_600'), + constant618: createMetricPattern1(this, 'constant_61_8'), + constant70: createMetricPattern1(this, 'constant_70'), + constant80: createMetricPattern1(this, 'constant_80'), + constantMinus1: createMetricPattern1(this, 'constant_minus_1'), + constantMinus2: createMetricPattern1(this, 'constant_minus_2'), + constantMinus3: createMetricPattern1(this, 'constant_minus_3'), + constantMinus4: createMetricPattern1(this, 'constant_minus_4') }, distribution: { addrCount: createAddrCountPattern(this, 'addr_count'), @@ -5595,23 +5501,23 @@ class BrkClient extends BrkClientBase { } }, addressesData: { - empty: createMetricPattern33(this, 'emptyaddressdata'), - loaded: createMetricPattern32(this, 'loadedaddressdata') + empty: createMetricPattern32(this, 'emptyaddressdata'), + loaded: createMetricPattern31(this, 'loadedaddressdata') }, anyAddressIndexes: { - p2a: createMetricPattern17(this, 'anyaddressindex'), - p2pk33: createMetricPattern19(this, 'anyaddressindex'), - p2pk65: createMetricPattern20(this, 'anyaddressindex'), - p2pkh: createMetricPattern21(this, 'anyaddressindex'), - p2sh: createMetricPattern22(this, 'anyaddressindex'), - p2tr: createMetricPattern23(this, 'anyaddressindex'), - p2wpkh: createMetricPattern24(this, 'anyaddressindex'), - p2wsh: createMetricPattern25(this, 'anyaddressindex') + p2a: createMetricPattern16(this, 'anyaddressindex'), + p2pk33: createMetricPattern18(this, 'anyaddressindex'), + p2pk65: createMetricPattern19(this, 'anyaddressindex'), + p2pkh: createMetricPattern20(this, 'anyaddressindex'), + p2sh: createMetricPattern21(this, 'anyaddressindex'), + p2tr: createMetricPattern22(this, 'anyaddressindex'), + p2wpkh: createMetricPattern23(this, 'anyaddressindex'), + p2wsh: createMetricPattern24(this, 'anyaddressindex') }, - chainState: createMetricPattern12(this, 'chain'), + chainState: createMetricPattern11(this, 'chain'), emptyAddrCount: createAddrCountPattern(this, 'empty_addr_count'), - emptyaddressindex: createMetricPattern33(this, 'emptyaddressindex'), - loadedaddressindex: createMetricPattern32(this, 'loadedaddressindex'), + emptyaddressindex: createMetricPattern32(this, 'emptyaddressindex'), + loadedaddressindex: createMetricPattern31(this, 'loadedaddressindex'), utxoCohorts: { ageRange: { _10yTo12y: create_10yTo12yPattern(this, 'utxos_at_least_10y_up_to_12y_old'), @@ -5817,83 +5723,83 @@ class BrkClient extends BrkClientBase { unknown: createEmptyPattern(this, 'unknownoutputindex') }, dateindex: { - date: createMetricPattern7(this, 'dateindex_date'), - firstHeight: createMetricPattern7(this, 'dateindex_first_height'), - heightCount: createMetricPattern7(this, 'dateindex_height_count'), - identity: createMetricPattern7(this, 'dateindex'), - monthindex: createMetricPattern7(this, 'dateindex_monthindex'), - weekindex: createMetricPattern7(this, 'dateindex_weekindex') + date: createMetricPattern6(this, 'dateindex_date'), + firstHeight: createMetricPattern6(this, 'dateindex_first_height'), + heightCount: createMetricPattern6(this, 'dateindex_height_count'), + identity: createMetricPattern6(this, 'dateindex'), + monthindex: createMetricPattern6(this, 'dateindex_monthindex'), + weekindex: createMetricPattern6(this, 'dateindex_weekindex') }, decadeindex: { - firstYearindex: createMetricPattern8(this, 'decadeindex_first_yearindex'), - identity: createMetricPattern8(this, 'decadeindex'), - yearindexCount: createMetricPattern8(this, 'decadeindex_yearindex_count') + firstYearindex: createMetricPattern7(this, 'decadeindex_first_yearindex'), + identity: createMetricPattern7(this, 'decadeindex'), + yearindexCount: createMetricPattern7(this, 'decadeindex_yearindex_count') }, difficultyepoch: { - firstHeight: createMetricPattern9(this, 'difficultyepoch_first_height'), - heightCount: createMetricPattern9(this, 'difficultyepoch_height_count'), - identity: createMetricPattern9(this, 'difficultyepoch') + firstHeight: createMetricPattern8(this, 'difficultyepoch_first_height'), + heightCount: createMetricPattern8(this, 'difficultyepoch_height_count'), + identity: createMetricPattern8(this, 'difficultyepoch') }, halvingepoch: { - firstHeight: createMetricPattern11(this, 'halvingepoch_first_height'), - identity: createMetricPattern11(this, 'halvingepoch') + firstHeight: createMetricPattern10(this, 'halvingepoch_first_height'), + identity: createMetricPattern10(this, 'halvingepoch') }, height: { - dateindex: createMetricPattern12(this, 'height_dateindex'), - difficultyepoch: createMetricPattern12(this, 'height_difficultyepoch'), - halvingepoch: createMetricPattern12(this, 'height_halvingepoch'), - identity: createMetricPattern12(this, 'height'), - txindexCount: createMetricPattern12(this, 'height_txindex_count') + dateindex: createMetricPattern11(this, 'height_dateindex'), + difficultyepoch: createMetricPattern11(this, 'height_difficultyepoch'), + halvingepoch: createMetricPattern11(this, 'height_halvingepoch'), + identity: createMetricPattern11(this, 'height'), + txindexCount: createMetricPattern11(this, 'height_txindex_count') }, monthindex: { - dateindexCount: createMetricPattern14(this, 'monthindex_dateindex_count'), - firstDateindex: createMetricPattern14(this, 'monthindex_first_dateindex'), - identity: createMetricPattern14(this, 'monthindex'), - quarterindex: createMetricPattern14(this, 'monthindex_quarterindex'), - semesterindex: createMetricPattern14(this, 'monthindex_semesterindex'), - yearindex: createMetricPattern14(this, 'monthindex_yearindex') + dateindexCount: createMetricPattern13(this, 'monthindex_dateindex_count'), + firstDateindex: createMetricPattern13(this, 'monthindex_first_dateindex'), + identity: createMetricPattern13(this, 'monthindex'), + quarterindex: createMetricPattern13(this, 'monthindex_quarterindex'), + semesterindex: createMetricPattern13(this, 'monthindex_semesterindex'), + yearindex: createMetricPattern13(this, 'monthindex_yearindex') }, quarterindex: { - firstMonthindex: createMetricPattern26(this, 'quarterindex_first_monthindex'), - identity: createMetricPattern26(this, 'quarterindex'), - monthindexCount: createMetricPattern26(this, 'quarterindex_monthindex_count') + firstMonthindex: createMetricPattern25(this, 'quarterindex_first_monthindex'), + identity: createMetricPattern25(this, 'quarterindex'), + monthindexCount: createMetricPattern25(this, 'quarterindex_monthindex_count') }, semesterindex: { - firstMonthindex: createMetricPattern27(this, 'semesterindex_first_monthindex'), - identity: createMetricPattern27(this, 'semesterindex'), - monthindexCount: createMetricPattern27(this, 'semesterindex_monthindex_count') + firstMonthindex: createMetricPattern26(this, 'semesterindex_first_monthindex'), + identity: createMetricPattern26(this, 'semesterindex'), + monthindexCount: createMetricPattern26(this, 'semesterindex_monthindex_count') }, txindex: { - identity: createMetricPattern28(this, 'txindex'), - inputCount: createMetricPattern28(this, 'txindex_input_count'), - outputCount: createMetricPattern28(this, 'txindex_output_count') + identity: createMetricPattern27(this, 'txindex'), + inputCount: createMetricPattern27(this, 'txindex_input_count'), + outputCount: createMetricPattern27(this, 'txindex_output_count') }, txinindex: createEmptyPattern(this, 'txinindex'), txoutindex: createEmptyPattern(this, 'txoutindex'), weekindex: { - dateindexCount: createMetricPattern30(this, 'weekindex_dateindex_count'), - firstDateindex: createMetricPattern30(this, 'weekindex_first_dateindex'), - identity: createMetricPattern30(this, 'weekindex') + dateindexCount: createMetricPattern29(this, 'weekindex_dateindex_count'), + firstDateindex: createMetricPattern29(this, 'weekindex_first_dateindex'), + identity: createMetricPattern29(this, 'weekindex') }, yearindex: { - decadeindex: createMetricPattern31(this, 'yearindex_decadeindex'), - firstMonthindex: createMetricPattern31(this, 'yearindex_first_monthindex'), - identity: createMetricPattern31(this, 'yearindex'), - monthindexCount: createMetricPattern31(this, 'yearindex_monthindex_count') + decadeindex: createMetricPattern30(this, 'yearindex_decadeindex'), + firstMonthindex: createMetricPattern30(this, 'yearindex_first_monthindex'), + identity: createMetricPattern30(this, 'yearindex'), + monthindexCount: createMetricPattern30(this, 'yearindex_monthindex_count') } }, inputs: { count: createSizePattern(this, 'input_count'), - firstTxinindex: createMetricPattern12(this, 'first_txinindex'), - outpoint: createMetricPattern13(this, 'outpoint'), - outputtype: createMetricPattern13(this, 'outputtype'), + firstTxinindex: createMetricPattern11(this, 'first_txinindex'), + outpoint: createMetricPattern12(this, 'outpoint'), + outputtype: createMetricPattern12(this, 'outputtype'), spent: { - txoutindex: createMetricPattern13(this, 'txoutindex'), - value: createMetricPattern13(this, 'value') + txoutindex: createMetricPattern12(this, 'txoutindex'), + value: createMetricPattern12(this, 'value') }, - txindex: createMetricPattern13(this, 'txindex'), - typeindex: createMetricPattern13(this, 'typeindex'), - witnessSize: createMetricPattern13(this, 'witness_size') + txindex: createMetricPattern12(this, 'txindex'), + typeindex: createMetricPattern12(this, 'typeindex'), + witnessSize: createMetricPattern12(this, 'witness_size') }, market: { ath: { @@ -5927,25 +5833,25 @@ class BrkClient extends BrkClientBase { periodStack: createPeriodLumpSumStackPattern(this, '') }, indicators: { - gini: createMetricPattern7(this, 'gini'), - macdHistogram: createMetricPattern7(this, 'macd_histogram'), - macdLine: createMetricPattern7(this, 'macd_line'), - macdSignal: createMetricPattern7(this, 'macd_signal'), + gini: createMetricPattern6(this, 'gini'), + macdHistogram: createMetricPattern6(this, 'macd_histogram'), + macdLine: createMetricPattern6(this, 'macd_line'), + macdSignal: createMetricPattern6(this, 'macd_signal'), nvt: createMetricPattern4(this, 'nvt'), - piCycle: createMetricPattern7(this, 'pi_cycle'), + piCycle: createMetricPattern6(this, 'pi_cycle'), puellMultiple: createMetricPattern4(this, 'puell_multiple'), - rsi14d: createMetricPattern7(this, 'rsi_14d'), - rsi14dMax: createMetricPattern7(this, 'rsi_14d_max'), - rsi14dMin: createMetricPattern7(this, 'rsi_14d_min'), - rsiAverageGain14d: createMetricPattern7(this, 'rsi_average_gain_14d'), - rsiAverageLoss14d: createMetricPattern7(this, 'rsi_average_loss_14d'), - rsiGains: createMetricPattern7(this, 'rsi_gains'), - rsiLosses: createMetricPattern7(this, 'rsi_losses'), - stochD: createMetricPattern7(this, 'stoch_d'), - stochK: createMetricPattern7(this, 'stoch_k'), - stochRsi: createMetricPattern7(this, 'stoch_rsi'), - stochRsiD: createMetricPattern7(this, 'stoch_rsi_d'), - stochRsiK: createMetricPattern7(this, 'stoch_rsi_k') + rsi14d: createMetricPattern6(this, 'rsi_14d'), + rsi14dMax: createMetricPattern6(this, 'rsi_14d_max'), + rsi14dMin: createMetricPattern6(this, 'rsi_14d_min'), + rsiAverageGain14d: createMetricPattern6(this, 'rsi_average_gain_14d'), + rsiAverageLoss14d: createMetricPattern6(this, 'rsi_average_loss_14d'), + rsiGains: createMetricPattern6(this, 'rsi_gains'), + rsiLosses: createMetricPattern6(this, 'rsi_losses'), + stochD: createMetricPattern6(this, 'stoch_d'), + stochK: createMetricPattern6(this, 'stoch_k'), + stochRsi: createMetricPattern6(this, 'stoch_rsi'), + stochRsiD: createMetricPattern6(this, 'stoch_rsi_d'), + stochRsiK: createMetricPattern6(this, 'stoch_rsi_k') }, lookback: { priceAgo: createPriceAgoPattern(this, 'price') @@ -5997,8 +5903,8 @@ class BrkClient extends BrkClientBase { price2wChoppinessIndex: createMetricPattern4(this, 'price_2w_choppiness_index'), price2wMax: createMetricPattern4(this, 'price_2w_max'), price2wMin: createMetricPattern4(this, 'price_2w_min'), - priceTrueRange: createMetricPattern7(this, 'price_true_range'), - priceTrueRange2wSum: createMetricPattern7(this, 'price_true_range_2w_sum') + priceTrueRange: createMetricPattern6(this, 'price_true_range'), + priceTrueRange2wSum: createMetricPattern6(this, 'price_true_range_2w_sum') }, returns: { _1dReturns1mSd: create_1dReturns1mSdPattern(this, '1d_returns_1m_sd'), @@ -6008,37 +5914,37 @@ class BrkClient extends BrkClientBase { downside1mSd: create_1dReturns1mSdPattern(this, 'downside_1m_sd'), downside1wSd: create_1dReturns1mSdPattern(this, 'downside_1w_sd'), downside1ySd: create_1dReturns1mSdPattern(this, 'downside_1y_sd'), - downsideReturns: createMetricPattern7(this, 'downside_returns'), + downsideReturns: createMetricPattern6(this, 'downside_returns'), priceReturns: createPriceAgoPattern(this, 'price_returns') }, volatility: { price1mVolatility: createMetricPattern4(this, 'price_1m_volatility'), price1wVolatility: createMetricPattern4(this, 'price_1w_volatility'), price1yVolatility: createMetricPattern4(this, 'price_1y_volatility'), - sharpe1m: createMetricPattern7(this, 'sharpe_1m'), - sharpe1w: createMetricPattern7(this, 'sharpe_1w'), - sharpe1y: createMetricPattern7(this, 'sharpe_1y'), - sortino1m: createMetricPattern7(this, 'sortino_1m'), - sortino1w: createMetricPattern7(this, 'sortino_1w'), - sortino1y: createMetricPattern7(this, 'sortino_1y') + sharpe1m: createMetricPattern6(this, 'sharpe_1m'), + sharpe1w: createMetricPattern6(this, 'sharpe_1w'), + sharpe1y: createMetricPattern6(this, 'sharpe_1y'), + sortino1m: createMetricPattern6(this, 'sortino_1m'), + sortino1w: createMetricPattern6(this, 'sortino_1w'), + sortino1y: createMetricPattern6(this, 'sortino_1y') } }, outputs: { count: { totalCount: createSizePattern(this, 'output_count'), - utxoCount: createBitcoinPattern(this, 'exact_utxo_count') + utxoCount: createFullnessPattern(this, 'exact_utxo_count') }, - firstTxoutindex: createMetricPattern12(this, 'first_txoutindex'), - outputtype: createMetricPattern16(this, 'outputtype'), + firstTxoutindex: createMetricPattern11(this, 'first_txoutindex'), + outputtype: createMetricPattern15(this, 'outputtype'), spent: { - txinindex: createMetricPattern16(this, 'txinindex') + txinindex: createMetricPattern15(this, 'txinindex') }, - txindex: createMetricPattern16(this, 'txindex'), - typeindex: createMetricPattern16(this, 'typeindex'), - value: createMetricPattern16(this, 'value') + txindex: createMetricPattern15(this, 'txindex'), + typeindex: createMetricPattern15(this, 'typeindex'), + value: createMetricPattern15(this, 'value') }, pools: { - pool: createMetricPattern12(this, 'pool'), + heightToPool: createMetricPattern11(this, 'pool'), vecs: { aaopool: createAaopoolPattern(this, 'aaopool'), antpool: createAaopoolPattern(this, 'antpool'), @@ -6201,46 +6107,40 @@ class BrkClient extends BrkClientBase { } }, positions: { - blockPosition: createMetricPattern12(this, 'position'), - txPosition: createMetricPattern28(this, 'position') + blockPosition: createMetricPattern11(this, 'position'), + txPosition: createMetricPattern27(this, 'position') }, price: { - cents: { - ohlc: createMetricPattern6(this, 'ohlc_cents'), - split: { - dateindex: createDateindexPattern2(this, 'price'), - height: createDateindexPattern2(this, 'price') - } - }, - sats: createSatsPattern(this, 'price'), - usd: createSatsPattern(this, 'price') + cents: createCentsPattern(this, 'cents'), + sats: createSatsPricePattern(this), + usd: createUsdPricePattern(this) }, scripts: { count: { - emptyoutput: createBitcoinPattern(this, 'emptyoutput_count'), - opreturn: createBitcoinPattern(this, 'opreturn_count'), - p2a: createBitcoinPattern(this, 'p2a_count'), - p2ms: createBitcoinPattern(this, 'p2ms_count'), - p2pk33: createBitcoinPattern(this, 'p2pk33_count'), - p2pk65: createBitcoinPattern(this, 'p2pk65_count'), - p2pkh: createBitcoinPattern(this, 'p2pkh_count'), - p2sh: createBitcoinPattern(this, 'p2sh_count'), - p2tr: createBitcoinPattern(this, 'p2tr_count'), - p2wpkh: createBitcoinPattern(this, 'p2wpkh_count'), - p2wsh: createBitcoinPattern(this, 'p2wsh_count'), - segwit: createBitcoinPattern(this, 'segwit_count'), + emptyoutput: createFullnessPattern(this, 'emptyoutput_count'), + opreturn: createFullnessPattern(this, 'opreturn_count'), + p2a: createFullnessPattern(this, 'p2a_count'), + p2ms: createFullnessPattern(this, 'p2ms_count'), + p2pk33: createFullnessPattern(this, 'p2pk33_count'), + p2pk65: createFullnessPattern(this, 'p2pk65_count'), + p2pkh: createFullnessPattern(this, 'p2pkh_count'), + p2sh: createFullnessPattern(this, 'p2sh_count'), + p2tr: createFullnessPattern(this, 'p2tr_count'), + p2wpkh: createFullnessPattern(this, 'p2wpkh_count'), + p2wsh: createFullnessPattern(this, 'p2wsh_count'), + segwit: createFullnessPattern(this, 'segwit_count'), segwitAdoption: createSegwitAdoptionPattern(this, 'segwit_adoption'), taprootAdoption: createSegwitAdoptionPattern(this, 'taproot_adoption'), - unknownoutput: createBitcoinPattern(this, 'unknownoutput_count') + unknownoutput: createFullnessPattern(this, 'unknownoutput_count') }, - emptyToTxindex: createMetricPattern10(this, 'txindex'), - firstEmptyoutputindex: createMetricPattern12(this, 'first_emptyoutputindex'), - firstOpreturnindex: createMetricPattern12(this, 'first_opreturnindex'), - firstP2msoutputindex: createMetricPattern12(this, 'first_p2msoutputindex'), - firstUnknownoutputindex: createMetricPattern12(this, 'first_unknownoutputindex'), - opreturnToTxindex: createMetricPattern15(this, 'txindex'), - p2msToTxindex: createMetricPattern18(this, 'txindex'), - unknownToTxindex: createMetricPattern29(this, 'txindex'), + emptyToTxindex: createMetricPattern9(this, 'txindex'), + firstEmptyoutputindex: createMetricPattern11(this, 'first_emptyoutputindex'), + firstOpreturnindex: createMetricPattern11(this, 'first_opreturnindex'), + firstP2msoutputindex: createMetricPattern11(this, 'first_p2msoutputindex'), + firstUnknownoutputindex: createMetricPattern11(this, 'first_unknownoutputindex'), + opreturnToTxindex: createMetricPattern14(this, 'txindex'), + p2msToTxindex: createMetricPattern17(this, 'txindex'), + unknownToTxindex: createMetricPattern28(this, 'txindex'), value: { opreturn: createCoinbasePattern(this, 'opreturn_value') } @@ -6259,35 +6159,47 @@ class BrkClient extends BrkClientBase { } }, transactions: { - baseSize: createMetricPattern28(this, 'base_size'), + baseSize: createMetricPattern27(this, 'base_size'), count: { - isCoinbase: createMetricPattern28(this, 'is_coinbase'), - txCount: createBitcoinPattern(this, 'tx_count') + isCoinbase: createMetricPattern27(this, 'is_coinbase'), + txCount: createFullnessPattern(this, 'tx_count') }, fees: { fee: { bitcoin: createSizePattern(this, 'fee_btc'), - dollars: createSizePattern(this, 'fee_usd'), + dollars: { + average: createMetricPattern1(this, 'fee_usd_average'), + cumulative: createMetricPattern2(this, 'fee_usd_cumulative'), + heightCumulative: createMetricPattern11(this, 'fee_usd_cumulative'), + max: createMetricPattern1(this, 'fee_usd_max'), + median: createMetricPattern11(this, 'fee_usd_median'), + min: createMetricPattern1(this, 'fee_usd_min'), + pct10: createMetricPattern11(this, 'fee_usd_pct10'), + pct25: createMetricPattern11(this, 'fee_usd_pct25'), + pct75: createMetricPattern11(this, 'fee_usd_pct75'), + pct90: createMetricPattern11(this, 'fee_usd_pct90'), + sum: createMetricPattern1(this, 'fee_usd_sum') + }, sats: createSizePattern(this, 'fee'), - txindex: createMetricPattern28(this, 'fee') + txindex: createMetricPattern27(this, 'fee') }, feeRate: createFeeRatePattern(this, 'fee_rate'), - inputValue: createMetricPattern28(this, 'input_value'), - outputValue: createMetricPattern28(this, 'output_value') + inputValue: createMetricPattern27(this, 'input_value'), + outputValue: createMetricPattern27(this, 'output_value') }, - firstTxindex: createMetricPattern12(this, 'first_txindex'), - firstTxinindex: createMetricPattern28(this, 'first_txinindex'), - firstTxoutindex: createMetricPattern28(this, 'first_txoutindex'), - height: createMetricPattern28(this, 'height'), - isExplicitlyRbf: createMetricPattern28(this, 'is_explicitly_rbf'), - rawlocktime: createMetricPattern28(this, 'rawlocktime'), + firstTxindex: createMetricPattern11(this, 'first_txindex'), + firstTxinindex: createMetricPattern27(this, 'first_txinindex'), + firstTxoutindex: createMetricPattern27(this, 'first_txoutindex'), + height: createMetricPattern27(this, 'height'), + isExplicitlyRbf: createMetricPattern27(this, 'is_explicitly_rbf'), + rawlocktime: createMetricPattern27(this, 'rawlocktime'), size: { vsize: createFeeRatePattern(this, ''), weight: createFeeRatePattern(this, '') }, - totalSize: createMetricPattern28(this, 'total_size'), - txid: createMetricPattern28(this, 'txid'), - txversion: createMetricPattern28(this, 'txversion'), + totalSize: createMetricPattern27(this, 'total_size'), + txid: createMetricPattern27(this, 'txid'), + txversion: createMetricPattern27(this, 'txversion'), versions: { v1: createBlockCountPattern(this, 'tx_v1'), v2: createBlockCountPattern(this, 'tx_v2'), diff --git a/modules/modern-screenshot/4.6.6/dist/index.d.ts b/modules/modern-screenshot/4.6.6/dist/index.d.ts index b50a7fd8e..114e2072e 100644 --- a/modules/modern-screenshot/4.6.6/dist/index.d.ts +++ b/modules/modern-screenshot/4.6.6/dist/index.d.ts @@ -1,3 +1,4 @@ +// @ts-nocheck interface Options { /** * Width in pixels to be applied to node before rendering. diff --git a/modules/modern-screenshot/4.6.6/dist/index.mjs b/modules/modern-screenshot/4.6.6/dist/index.mjs index e3c44f815..0489904a0 100644 --- a/modules/modern-screenshot/4.6.6/dist/index.mjs +++ b/modules/modern-screenshot/4.6.6/dist/index.mjs @@ -1,3 +1,4 @@ +// @ts-nocheck function changeJpegDpi(uint8Array, dpi) { uint8Array[13] = 1; uint8Array[14] = dpi >> 8; diff --git a/packages/brk_client/brk_client/__init__.py b/packages/brk_client/brk_client/__init__.py index 1f17db017..e11e1355a 100644 --- a/packages/brk_client/brk_client/__init__.py +++ b/packages/brk_client/brk_client/__init__.py @@ -802,58 +802,6 @@ class MetricPattern4(Generic[T]): class _MetricPattern5By(Generic[T]): """Index endpoint methods container.""" - def __init__(self, client: BrkClientBase, name: str): - self._client = client - self._name = name - - def by_decadeindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'decadeindex') - - def by_monthindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'monthindex') - - def by_quarterindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'quarterindex') - - def by_semesterindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'semesterindex') - - def by_weekindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'weekindex') - - def by_yearindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'yearindex') - -class MetricPattern5(Generic[T]): - """Index accessor for metrics with 6 indexes.""" - - def __init__(self, client: BrkClientBase, name: str): - self._client = client - self._name = name - self.by: _MetricPattern5By[T] = _MetricPattern5By(client, name) - - @property - def name(self) -> str: - """Get the metric name.""" - return self._name - - def indexes(self) -> List[str]: - """Get the list of available indexes.""" - return ['decadeindex', 'monthindex', 'quarterindex', 'semesterindex', 'weekindex', 'yearindex'] - - def get(self, index: str) -> Optional[MetricEndpoint[T]]: - """Get an endpoint for a specific index, if supported.""" - if index == 'decadeindex': return self.by.by_decadeindex() - elif index == 'monthindex': return self.by.by_monthindex() - elif index == 'quarterindex': return self.by.by_quarterindex() - elif index == 'semesterindex': return self.by.by_semesterindex() - elif index == 'weekindex': return self.by.by_weekindex() - elif index == 'yearindex': return self.by.by_yearindex() - return None - -class _MetricPattern6By(Generic[T]): - """Index endpoint methods container.""" - def __init__(self, client: BrkClientBase, name: str): self._client = client self._name = name @@ -864,13 +812,13 @@ class _MetricPattern6By(Generic[T]): def by_height(self) -> MetricEndpoint[T]: return MetricEndpoint(self._client, self._name, 'height') -class MetricPattern6(Generic[T]): +class MetricPattern5(Generic[T]): """Index accessor for metrics with 2 indexes.""" def __init__(self, client: BrkClientBase, name: str): self._client = client self._name = name - self.by: _MetricPattern6By[T] = _MetricPattern6By(client, name) + self.by: _MetricPattern5By[T] = _MetricPattern5By(client, name) @property def name(self) -> str: @@ -887,7 +835,7 @@ class MetricPattern6(Generic[T]): elif index == 'height': return self.by.by_height() return None -class _MetricPattern7By(Generic[T]): +class _MetricPattern6By(Generic[T]): """Index endpoint methods container.""" def __init__(self, client: BrkClientBase, name: str): @@ -897,6 +845,38 @@ class _MetricPattern7By(Generic[T]): def by_dateindex(self) -> MetricEndpoint[T]: return MetricEndpoint(self._client, self._name, 'dateindex') +class MetricPattern6(Generic[T]): + """Index accessor for metrics with 1 indexes.""" + + def __init__(self, client: BrkClientBase, name: str): + self._client = client + self._name = name + self.by: _MetricPattern6By[T] = _MetricPattern6By(client, name) + + @property + def name(self) -> str: + """Get the metric name.""" + return self._name + + def indexes(self) -> List[str]: + """Get the list of available indexes.""" + return ['dateindex'] + + def get(self, index: str) -> Optional[MetricEndpoint[T]]: + """Get an endpoint for a specific index, if supported.""" + if index == 'dateindex': return self.by.by_dateindex() + return None + +class _MetricPattern7By(Generic[T]): + """Index endpoint methods container.""" + + def __init__(self, client: BrkClientBase, name: str): + self._client = client + self._name = name + + def by_decadeindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'decadeindex') + class MetricPattern7(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -912,11 +892,11 @@ class MetricPattern7(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['dateindex'] + return ['decadeindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'dateindex': return self.by.by_dateindex() + if index == 'decadeindex': return self.by.by_decadeindex() return None class _MetricPattern8By(Generic[T]): @@ -926,8 +906,8 @@ class _MetricPattern8By(Generic[T]): self._client = client self._name = name - def by_decadeindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'decadeindex') + def by_difficultyepoch(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'difficultyepoch') class MetricPattern8(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -944,11 +924,11 @@ class MetricPattern8(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['decadeindex'] + return ['difficultyepoch'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'decadeindex': return self.by.by_decadeindex() + if index == 'difficultyepoch': return self.by.by_difficultyepoch() return None class _MetricPattern9By(Generic[T]): @@ -958,8 +938,8 @@ class _MetricPattern9By(Generic[T]): self._client = client self._name = name - def by_difficultyepoch(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'difficultyepoch') + def by_emptyoutputindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'emptyoutputindex') class MetricPattern9(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -976,11 +956,11 @@ class MetricPattern9(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['difficultyepoch'] + return ['emptyoutputindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'difficultyepoch': return self.by.by_difficultyepoch() + if index == 'emptyoutputindex': return self.by.by_emptyoutputindex() return None class _MetricPattern10By(Generic[T]): @@ -990,8 +970,8 @@ class _MetricPattern10By(Generic[T]): self._client = client self._name = name - def by_emptyoutputindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'emptyoutputindex') + def by_halvingepoch(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'halvingepoch') class MetricPattern10(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1008,11 +988,11 @@ class MetricPattern10(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['emptyoutputindex'] + return ['halvingepoch'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'emptyoutputindex': return self.by.by_emptyoutputindex() + if index == 'halvingepoch': return self.by.by_halvingepoch() return None class _MetricPattern11By(Generic[T]): @@ -1022,8 +1002,8 @@ class _MetricPattern11By(Generic[T]): self._client = client self._name = name - def by_halvingepoch(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'halvingepoch') + def by_height(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'height') class MetricPattern11(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1040,11 +1020,11 @@ class MetricPattern11(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['halvingepoch'] + return ['height'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'halvingepoch': return self.by.by_halvingepoch() + if index == 'height': return self.by.by_height() return None class _MetricPattern12By(Generic[T]): @@ -1054,8 +1034,8 @@ class _MetricPattern12By(Generic[T]): self._client = client self._name = name - def by_height(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'height') + def by_txinindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'txinindex') class MetricPattern12(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1072,11 +1052,11 @@ class MetricPattern12(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['height'] + return ['txinindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'height': return self.by.by_height() + if index == 'txinindex': return self.by.by_txinindex() return None class _MetricPattern13By(Generic[T]): @@ -1086,8 +1066,8 @@ class _MetricPattern13By(Generic[T]): self._client = client self._name = name - def by_txinindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'txinindex') + def by_monthindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'monthindex') class MetricPattern13(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1104,11 +1084,11 @@ class MetricPattern13(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['txinindex'] + return ['monthindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'txinindex': return self.by.by_txinindex() + if index == 'monthindex': return self.by.by_monthindex() return None class _MetricPattern14By(Generic[T]): @@ -1118,8 +1098,8 @@ class _MetricPattern14By(Generic[T]): self._client = client self._name = name - def by_monthindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'monthindex') + def by_opreturnindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'opreturnindex') class MetricPattern14(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1136,11 +1116,11 @@ class MetricPattern14(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['monthindex'] + return ['opreturnindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'monthindex': return self.by.by_monthindex() + if index == 'opreturnindex': return self.by.by_opreturnindex() return None class _MetricPattern15By(Generic[T]): @@ -1150,8 +1130,8 @@ class _MetricPattern15By(Generic[T]): self._client = client self._name = name - def by_opreturnindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'opreturnindex') + def by_txoutindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'txoutindex') class MetricPattern15(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1168,11 +1148,11 @@ class MetricPattern15(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['opreturnindex'] + return ['txoutindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'opreturnindex': return self.by.by_opreturnindex() + if index == 'txoutindex': return self.by.by_txoutindex() return None class _MetricPattern16By(Generic[T]): @@ -1182,8 +1162,8 @@ class _MetricPattern16By(Generic[T]): self._client = client self._name = name - def by_txoutindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'txoutindex') + def by_p2aaddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2aaddressindex') class MetricPattern16(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1200,11 +1180,11 @@ class MetricPattern16(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['txoutindex'] + return ['p2aaddressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'txoutindex': return self.by.by_txoutindex() + if index == 'p2aaddressindex': return self.by.by_p2aaddressindex() return None class _MetricPattern17By(Generic[T]): @@ -1214,8 +1194,8 @@ class _MetricPattern17By(Generic[T]): self._client = client self._name = name - def by_p2aaddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2aaddressindex') + def by_p2msoutputindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2msoutputindex') class MetricPattern17(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1232,11 +1212,11 @@ class MetricPattern17(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2aaddressindex'] + return ['p2msoutputindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2aaddressindex': return self.by.by_p2aaddressindex() + if index == 'p2msoutputindex': return self.by.by_p2msoutputindex() return None class _MetricPattern18By(Generic[T]): @@ -1246,8 +1226,8 @@ class _MetricPattern18By(Generic[T]): self._client = client self._name = name - def by_p2msoutputindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2msoutputindex') + def by_p2pk33addressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2pk33addressindex') class MetricPattern18(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1264,11 +1244,11 @@ class MetricPattern18(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2msoutputindex'] + return ['p2pk33addressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2msoutputindex': return self.by.by_p2msoutputindex() + if index == 'p2pk33addressindex': return self.by.by_p2pk33addressindex() return None class _MetricPattern19By(Generic[T]): @@ -1278,8 +1258,8 @@ class _MetricPattern19By(Generic[T]): self._client = client self._name = name - def by_p2pk33addressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2pk33addressindex') + def by_p2pk65addressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2pk65addressindex') class MetricPattern19(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1296,11 +1276,11 @@ class MetricPattern19(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2pk33addressindex'] + return ['p2pk65addressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2pk33addressindex': return self.by.by_p2pk33addressindex() + if index == 'p2pk65addressindex': return self.by.by_p2pk65addressindex() return None class _MetricPattern20By(Generic[T]): @@ -1310,8 +1290,8 @@ class _MetricPattern20By(Generic[T]): self._client = client self._name = name - def by_p2pk65addressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2pk65addressindex') + def by_p2pkhaddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2pkhaddressindex') class MetricPattern20(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1328,11 +1308,11 @@ class MetricPattern20(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2pk65addressindex'] + return ['p2pkhaddressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2pk65addressindex': return self.by.by_p2pk65addressindex() + if index == 'p2pkhaddressindex': return self.by.by_p2pkhaddressindex() return None class _MetricPattern21By(Generic[T]): @@ -1342,8 +1322,8 @@ class _MetricPattern21By(Generic[T]): self._client = client self._name = name - def by_p2pkhaddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2pkhaddressindex') + def by_p2shaddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2shaddressindex') class MetricPattern21(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1360,11 +1340,11 @@ class MetricPattern21(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2pkhaddressindex'] + return ['p2shaddressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2pkhaddressindex': return self.by.by_p2pkhaddressindex() + if index == 'p2shaddressindex': return self.by.by_p2shaddressindex() return None class _MetricPattern22By(Generic[T]): @@ -1374,8 +1354,8 @@ class _MetricPattern22By(Generic[T]): self._client = client self._name = name - def by_p2shaddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2shaddressindex') + def by_p2traddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2traddressindex') class MetricPattern22(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1392,11 +1372,11 @@ class MetricPattern22(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2shaddressindex'] + return ['p2traddressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2shaddressindex': return self.by.by_p2shaddressindex() + if index == 'p2traddressindex': return self.by.by_p2traddressindex() return None class _MetricPattern23By(Generic[T]): @@ -1406,8 +1386,8 @@ class _MetricPattern23By(Generic[T]): self._client = client self._name = name - def by_p2traddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2traddressindex') + def by_p2wpkhaddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2wpkhaddressindex') class MetricPattern23(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1424,11 +1404,11 @@ class MetricPattern23(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2traddressindex'] + return ['p2wpkhaddressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2traddressindex': return self.by.by_p2traddressindex() + if index == 'p2wpkhaddressindex': return self.by.by_p2wpkhaddressindex() return None class _MetricPattern24By(Generic[T]): @@ -1438,8 +1418,8 @@ class _MetricPattern24By(Generic[T]): self._client = client self._name = name - def by_p2wpkhaddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2wpkhaddressindex') + def by_p2wshaddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'p2wshaddressindex') class MetricPattern24(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1456,11 +1436,11 @@ class MetricPattern24(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2wpkhaddressindex'] + return ['p2wshaddressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2wpkhaddressindex': return self.by.by_p2wpkhaddressindex() + if index == 'p2wshaddressindex': return self.by.by_p2wshaddressindex() return None class _MetricPattern25By(Generic[T]): @@ -1470,8 +1450,8 @@ class _MetricPattern25By(Generic[T]): self._client = client self._name = name - def by_p2wshaddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'p2wshaddressindex') + def by_quarterindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'quarterindex') class MetricPattern25(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1488,11 +1468,11 @@ class MetricPattern25(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['p2wshaddressindex'] + return ['quarterindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'p2wshaddressindex': return self.by.by_p2wshaddressindex() + if index == 'quarterindex': return self.by.by_quarterindex() return None class _MetricPattern26By(Generic[T]): @@ -1502,8 +1482,8 @@ class _MetricPattern26By(Generic[T]): self._client = client self._name = name - def by_quarterindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'quarterindex') + def by_semesterindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'semesterindex') class MetricPattern26(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1520,11 +1500,11 @@ class MetricPattern26(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['quarterindex'] + return ['semesterindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'quarterindex': return self.by.by_quarterindex() + if index == 'semesterindex': return self.by.by_semesterindex() return None class _MetricPattern27By(Generic[T]): @@ -1534,8 +1514,8 @@ class _MetricPattern27By(Generic[T]): self._client = client self._name = name - def by_semesterindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'semesterindex') + def by_txindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'txindex') class MetricPattern27(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1552,11 +1532,11 @@ class MetricPattern27(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['semesterindex'] + return ['txindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'semesterindex': return self.by.by_semesterindex() + if index == 'txindex': return self.by.by_txindex() return None class _MetricPattern28By(Generic[T]): @@ -1566,8 +1546,8 @@ class _MetricPattern28By(Generic[T]): self._client = client self._name = name - def by_txindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'txindex') + def by_unknownoutputindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'unknownoutputindex') class MetricPattern28(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1584,11 +1564,11 @@ class MetricPattern28(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['txindex'] + return ['unknownoutputindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'txindex': return self.by.by_txindex() + if index == 'unknownoutputindex': return self.by.by_unknownoutputindex() return None class _MetricPattern29By(Generic[T]): @@ -1598,8 +1578,8 @@ class _MetricPattern29By(Generic[T]): self._client = client self._name = name - def by_unknownoutputindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'unknownoutputindex') + def by_weekindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'weekindex') class MetricPattern29(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1616,11 +1596,11 @@ class MetricPattern29(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['unknownoutputindex'] + return ['weekindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'unknownoutputindex': return self.by.by_unknownoutputindex() + if index == 'weekindex': return self.by.by_weekindex() return None class _MetricPattern30By(Generic[T]): @@ -1630,8 +1610,8 @@ class _MetricPattern30By(Generic[T]): self._client = client self._name = name - def by_weekindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'weekindex') + def by_yearindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'yearindex') class MetricPattern30(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1648,11 +1628,11 @@ class MetricPattern30(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['weekindex'] + return ['yearindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'weekindex': return self.by.by_weekindex() + if index == 'yearindex': return self.by.by_yearindex() return None class _MetricPattern31By(Generic[T]): @@ -1662,8 +1642,8 @@ class _MetricPattern31By(Generic[T]): self._client = client self._name = name - def by_yearindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'yearindex') + def by_loadedaddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'loadedaddressindex') class MetricPattern31(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1680,11 +1660,11 @@ class MetricPattern31(Generic[T]): def indexes(self) -> List[str]: """Get the list of available indexes.""" - return ['yearindex'] + return ['loadedaddressindex'] def get(self, index: str) -> Optional[MetricEndpoint[T]]: """Get an endpoint for a specific index, if supported.""" - if index == 'yearindex': return self.by.by_yearindex() + if index == 'loadedaddressindex': return self.by.by_loadedaddressindex() return None class _MetricPattern32By(Generic[T]): @@ -1694,8 +1674,8 @@ class _MetricPattern32By(Generic[T]): self._client = client self._name = name - def by_loadedaddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'loadedaddressindex') + def by_emptyaddressindex(self) -> MetricEndpoint[T]: + return MetricEndpoint(self._client, self._name, 'emptyaddressindex') class MetricPattern32(Generic[T]): """Index accessor for metrics with 1 indexes.""" @@ -1710,38 +1690,6 @@ class MetricPattern32(Generic[T]): """Get the metric name.""" return self._name - def indexes(self) -> List[str]: - """Get the list of available indexes.""" - return ['loadedaddressindex'] - - def get(self, index: str) -> Optional[MetricEndpoint[T]]: - """Get an endpoint for a specific index, if supported.""" - if index == 'loadedaddressindex': return self.by.by_loadedaddressindex() - return None - -class _MetricPattern33By(Generic[T]): - """Index endpoint methods container.""" - - def __init__(self, client: BrkClientBase, name: str): - self._client = client - self._name = name - - def by_emptyaddressindex(self) -> MetricEndpoint[T]: - return MetricEndpoint(self._client, self._name, 'emptyaddressindex') - -class MetricPattern33(Generic[T]): - """Index accessor for metrics with 1 indexes.""" - - def __init__(self, client: BrkClientBase, name: str): - self._client = client - self._name = name - self.by: _MetricPattern33By[T] = _MetricPattern33By(client, name) - - @property - def name(self) -> str: - """Get the metric name.""" - return self._name - def indexes(self) -> List[str]: """Get the list of available indexes.""" return ['emptyaddressindex'] @@ -1758,9 +1706,9 @@ class RealizedPattern3: def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.adjusted_sopr: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'adjusted_sopr')) - self.adjusted_sopr_30d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'adjusted_sopr_30d_ema')) - self.adjusted_sopr_7d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'adjusted_sopr_7d_ema')) + self.adjusted_sopr: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'adjusted_sopr')) + self.adjusted_sopr_30d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'adjusted_sopr_30d_ema')) + self.adjusted_sopr_7d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'adjusted_sopr_7d_ema')) self.adjusted_value_created: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'adjusted_value_created')) self.adjusted_value_destroyed: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'adjusted_value_destroyed')) self.mvrv: MetricPattern4[StoredF32] = MetricPattern4(client, _m(acc, 'mvrv')) @@ -1779,14 +1727,14 @@ class RealizedPattern3: self.realized_price_extra: ActivePriceRatioPattern = ActivePriceRatioPattern(client, _m(acc, 'realized_price_ratio')) self.realized_profit: BlockCountPattern[Dollars] = BlockCountPattern(client, _m(acc, 'realized_profit')) self.realized_profit_rel_to_realized_cap: BlockCountPattern[StoredF32] = BlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')) - self.realized_profit_to_loss_ratio: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'realized_profit_to_loss_ratio')) + self.realized_profit_to_loss_ratio: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'realized_profit_to_loss_ratio')) self.realized_value: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'realized_value')) - self.sell_side_risk_ratio: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio')) - self.sell_side_risk_ratio_30d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) - self.sell_side_risk_ratio_7d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) - self.sopr: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr')) - self.sopr_30d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_30d_ema')) - self.sopr_7d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_7d_ema')) + self.sell_side_risk_ratio: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio')) + self.sell_side_risk_ratio_30d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) + self.sell_side_risk_ratio_7d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) + self.sopr: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr')) + self.sopr_30d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_30d_ema')) + self.sopr_7d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_7d_ema')) self.total_realized_pnl: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'total_realized_pnl')) self.value_created: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_created')) self.value_destroyed: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_destroyed')) @@ -1796,9 +1744,9 @@ class RealizedPattern4: def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.adjusted_sopr: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'adjusted_sopr')) - self.adjusted_sopr_30d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'adjusted_sopr_30d_ema')) - self.adjusted_sopr_7d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'adjusted_sopr_7d_ema')) + self.adjusted_sopr: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'adjusted_sopr')) + self.adjusted_sopr_30d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'adjusted_sopr_30d_ema')) + self.adjusted_sopr_7d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'adjusted_sopr_7d_ema')) self.adjusted_value_created: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'adjusted_value_created')) self.adjusted_value_destroyed: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'adjusted_value_destroyed')) self.mvrv: MetricPattern4[StoredF32] = MetricPattern4(client, _m(acc, 'mvrv')) @@ -1817,12 +1765,12 @@ class RealizedPattern4: self.realized_profit: BlockCountPattern[Dollars] = BlockCountPattern(client, _m(acc, 'realized_profit')) self.realized_profit_rel_to_realized_cap: BlockCountPattern[StoredF32] = BlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')) self.realized_value: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'realized_value')) - self.sell_side_risk_ratio: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio')) - self.sell_side_risk_ratio_30d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) - self.sell_side_risk_ratio_7d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) - self.sopr: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr')) - self.sopr_30d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_30d_ema')) - self.sopr_7d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_7d_ema')) + self.sell_side_risk_ratio: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio')) + self.sell_side_risk_ratio_30d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) + self.sell_side_risk_ratio_7d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) + self.sopr: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr')) + self.sopr_30d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_30d_ema')) + self.sopr_7d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_7d_ema')) self.total_realized_pnl: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'total_realized_pnl')) self.value_created: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_created')) self.value_destroyed: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_destroyed')) @@ -1882,14 +1830,14 @@ class RealizedPattern2: self.realized_price_extra: ActivePriceRatioPattern = ActivePriceRatioPattern(client, _m(acc, 'realized_price_ratio')) self.realized_profit: BlockCountPattern[Dollars] = BlockCountPattern(client, _m(acc, 'realized_profit')) self.realized_profit_rel_to_realized_cap: BlockCountPattern[StoredF32] = BlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')) - self.realized_profit_to_loss_ratio: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'realized_profit_to_loss_ratio')) + self.realized_profit_to_loss_ratio: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'realized_profit_to_loss_ratio')) self.realized_value: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'realized_value')) - self.sell_side_risk_ratio: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio')) - self.sell_side_risk_ratio_30d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) - self.sell_side_risk_ratio_7d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) - self.sopr: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr')) - self.sopr_30d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_30d_ema')) - self.sopr_7d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_7d_ema')) + self.sell_side_risk_ratio: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio')) + self.sell_side_risk_ratio_30d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) + self.sell_side_risk_ratio_7d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) + self.sopr: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr')) + self.sopr_30d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_30d_ema')) + self.sopr_7d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_7d_ema')) self.total_realized_pnl: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'total_realized_pnl')) self.value_created: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_created')) self.value_destroyed: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_destroyed')) @@ -1915,12 +1863,12 @@ class RealizedPattern: self.realized_profit: BlockCountPattern[Dollars] = BlockCountPattern(client, _m(acc, 'realized_profit')) self.realized_profit_rel_to_realized_cap: BlockCountPattern[StoredF32] = BlockCountPattern(client, _m(acc, 'realized_profit_rel_to_realized_cap')) self.realized_value: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'realized_value')) - self.sell_side_risk_ratio: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio')) - self.sell_side_risk_ratio_30d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) - self.sell_side_risk_ratio_7d_ema: MetricPattern7[StoredF32] = MetricPattern7(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) - self.sopr: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr')) - self.sopr_30d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_30d_ema')) - self.sopr_7d_ema: MetricPattern7[StoredF64] = MetricPattern7(client, _m(acc, 'sopr_7d_ema')) + self.sell_side_risk_ratio: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio')) + self.sell_side_risk_ratio_30d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_30d_ema')) + self.sell_side_risk_ratio_7d_ema: MetricPattern6[StoredF32] = MetricPattern6(client, _m(acc, 'sell_side_risk_ratio_7d_ema')) + self.sopr: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr')) + self.sopr_30d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_30d_ema')) + self.sopr_7d_ema: MetricPattern6[StoredF64] = MetricPattern6(client, _m(acc, 'sopr_7d_ema')) self.total_realized_pnl: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'total_realized_pnl')) self.value_created: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_created')) self.value_destroyed: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'value_destroyed')) @@ -1951,7 +1899,7 @@ class Price111dSmaPattern: self.ratio_pct99_usd: MetricPattern4[Dollars] = MetricPattern4(client, _m(acc, 'ratio_pct99_usd')) self.ratio_sd: Ratio1ySdPattern = Ratio1ySdPattern(client, _m(acc, 'ratio')) -class PercentilesPattern2: +class PercentilesPattern: """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): @@ -2117,6 +2065,23 @@ class ClassAveragePricePattern(Generic[T]): self._2024: MetricPattern4[T] = MetricPattern4(client, _m(acc, '2024_average_price')) self._2025: MetricPattern4[T] = MetricPattern4(client, _m(acc, '2025_average_price')) +class FullnessPattern(Generic[T]): + """Pattern struct for repeated tree structure.""" + + def __init__(self, client: BrkClientBase, acc: str): + """Create pattern node with accumulated metric name.""" + self.average: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'average')) + self.base: MetricPattern11[T] = MetricPattern11(client, acc) + self.cumulative: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'cumulative')) + self.max: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'max')) + self.median: MetricPattern6[T] = MetricPattern6(client, _m(acc, 'median')) + self.min: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'min')) + self.pct10: MetricPattern6[T] = MetricPattern6(client, _m(acc, 'pct10')) + self.pct25: MetricPattern6[T] = MetricPattern6(client, _m(acc, 'pct25')) + self.pct75: MetricPattern6[T] = MetricPattern6(client, _m(acc, 'pct75')) + self.pct90: MetricPattern6[T] = MetricPattern6(client, _m(acc, 'pct90')) + self.sum: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'sum')) + class RelativePattern: """Pattern struct for repeated tree structure.""" @@ -2149,6 +2114,22 @@ class RelativePattern2: self.unrealized_profit_rel_to_own_market_cap: MetricPattern1[StoredF32] = MetricPattern1(client, _m(acc, 'unrealized_profit_rel_to_own_market_cap')) self.unrealized_profit_rel_to_own_total_unrealized_pnl: MetricPattern1[StoredF32] = MetricPattern1(client, _m(acc, 'unrealized_profit_rel_to_own_total_unrealized_pnl')) +class SizePattern(Generic[T]): + """Pattern struct for repeated tree structure.""" + + def __init__(self, client: BrkClientBase, acc: str): + """Create pattern node with accumulated metric name.""" + self.average: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'average')) + self.cumulative: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'cumulative')) + self.max: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'max')) + self.median: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'median')) + self.min: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'min')) + self.pct10: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct10')) + self.pct25: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct25')) + self.pct75: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct75')) + self.pct90: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct90')) + self.sum: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'sum')) + class AddrCountPattern: """Pattern struct for repeated tree structure.""" @@ -2164,21 +2145,6 @@ class AddrCountPattern: self.p2wpkh: MetricPattern1[StoredU64] = MetricPattern1(client, (f'p2wpkh_addr_{{acc}}' if acc else 'p2wpkh_addr')) self.p2wsh: MetricPattern1[StoredU64] = MetricPattern1(client, (f'p2wsh_addr_{{acc}}' if acc else 'p2wsh_addr')) -class OhlcPattern(Generic[T]): - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.dateindex: MetricPattern7[T] = MetricPattern7(client, acc) - self.decade: MetricPattern8[T] = MetricPattern8(client, acc) - self.difficultyepoch: MetricPattern9[T] = MetricPattern9(client, acc) - self.height: MetricPattern12[T] = MetricPattern12(client, acc) - self.month: MetricPattern14[T] = MetricPattern14(client, acc) - self.quarter: MetricPattern26[T] = MetricPattern26(client, acc) - self.semester: MetricPattern27[T] = MetricPattern27(client, acc) - self.week: MetricPattern30[T] = MetricPattern30(client, acc) - self.year: MetricPattern31[T] = MetricPattern31(client, acc) - class FeeRatePattern(Generic[T]): """Pattern struct for repeated tree structure.""" @@ -2186,13 +2152,13 @@ class FeeRatePattern(Generic[T]): """Create pattern node with accumulated metric name.""" self.average: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'average')) self.max: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'max')) - self.median: MetricPattern12[T] = MetricPattern12(client, _m(acc, 'median')) + self.median: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'median')) self.min: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'min')) - self.pct10: MetricPattern12[T] = MetricPattern12(client, _m(acc, 'pct10')) - self.pct25: MetricPattern12[T] = MetricPattern12(client, _m(acc, 'pct25')) - self.pct75: MetricPattern12[T] = MetricPattern12(client, _m(acc, 'pct75')) - self.pct90: MetricPattern12[T] = MetricPattern12(client, _m(acc, 'pct90')) - self.txindex: MetricPattern28[T] = MetricPattern28(client, acc) + self.pct10: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct10')) + self.pct25: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct25')) + self.pct75: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct75')) + self.pct90: MetricPattern11[T] = MetricPattern11(client, _m(acc, 'pct90')) + self.txindex: MetricPattern27[T] = MetricPattern27(client, acc) class _0satsPattern: """Pattern struct for repeated tree structure.""" @@ -2208,7 +2174,7 @@ class _0satsPattern: self.supply: SupplyPattern2 = SupplyPattern2(client, _m(acc, 'supply')) self.unrealized: UnrealizedPattern = UnrealizedPattern(client, acc) -class _10yPattern: +class _0satsPattern2: """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): @@ -2216,8 +2182,8 @@ class _10yPattern: self.activity: ActivityPattern2 = ActivityPattern2(client, acc) self.cost_basis: CostBasisPattern = CostBasisPattern(client, acc) self.outputs: OutputsPattern = OutputsPattern(client, acc) - self.realized: RealizedPattern4 = RealizedPattern4(client, acc) - self.relative: RelativePattern = RelativePattern(client, acc) + self.realized: RealizedPattern = RealizedPattern(client, acc) + self.relative: RelativePattern4 = RelativePattern4(client, _m(acc, 'supply_in')) self.supply: SupplyPattern2 = SupplyPattern2(client, _m(acc, 'supply')) self.unrealized: UnrealizedPattern = UnrealizedPattern(client, acc) @@ -2234,7 +2200,7 @@ class _10yTo12yPattern: self.supply: SupplyPattern2 = SupplyPattern2(client, _m(acc, 'supply')) self.unrealized: UnrealizedPattern = UnrealizedPattern(client, acc) -class _0satsPattern2: +class _10yPattern: """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): @@ -2242,8 +2208,8 @@ class _0satsPattern2: self.activity: ActivityPattern2 = ActivityPattern2(client, acc) self.cost_basis: CostBasisPattern = CostBasisPattern(client, acc) self.outputs: OutputsPattern = OutputsPattern(client, acc) - self.realized: RealizedPattern = RealizedPattern(client, acc) - self.relative: RelativePattern4 = RelativePattern4(client, _m(acc, 'supply_in')) + self.realized: RealizedPattern4 = RealizedPattern4(client, acc) + self.relative: RelativePattern = RelativePattern(client, acc) self.supply: SupplyPattern2 = SupplyPattern2(client, _m(acc, 'supply')) self.unrealized: UnrealizedPattern = UnrealizedPattern(client, acc) @@ -2286,31 +2252,6 @@ class PeriodCagrPattern: self._6y: MetricPattern4[StoredF32] = MetricPattern4(client, (f'6y_{{acc}}' if acc else '6y')) self._8y: MetricPattern4[StoredF32] = MetricPattern4(client, (f'8y_{{acc}}' if acc else '8y')) -class BitcoinPattern(Generic[T]): - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.average: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'average')) - self.cumulative: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'cumulative')) - self.height: MetricPattern12[T] = MetricPattern12(client, acc) - self.max: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'max')) - self.min: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'min')) - self.percentiles: PercentilesPattern[T] = PercentilesPattern(client, acc) - self.sum: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'sum')) - -class SizePattern(Generic[T]): - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.average: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'average')) - self.cumulative: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'cumulative')) - self.max: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'max')) - self.min: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'min')) - self.percentiles: PercentilesPattern[T] = PercentilesPattern(client, acc) - self.sum: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'sum')) - class ActivityPattern2: """Pattern struct for repeated tree structure.""" @@ -2318,68 +2259,55 @@ class ActivityPattern2: """Create pattern node with accumulated metric name.""" self.coinblocks_destroyed: BlockCountPattern[StoredF64] = BlockCountPattern(client, _m(acc, 'coinblocks_destroyed')) self.coindays_destroyed: BlockCountPattern[StoredF64] = BlockCountPattern(client, _m(acc, 'coindays_destroyed')) - self.satblocks_destroyed: MetricPattern12[Sats] = MetricPattern12(client, _m(acc, 'satblocks_destroyed')) - self.satdays_destroyed: MetricPattern12[Sats] = MetricPattern12(client, _m(acc, 'satdays_destroyed')) + self.satblocks_destroyed: MetricPattern11[Sats] = MetricPattern11(client, _m(acc, 'satblocks_destroyed')) + self.satdays_destroyed: MetricPattern11[Sats] = MetricPattern11(client, _m(acc, 'satdays_destroyed')) self.sent: UnclaimedRewardsPattern = UnclaimedRewardsPattern(client, _m(acc, 'sent')) -class PercentilesPattern(Generic[T]): +class SplitPattern(Generic[T]): """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.median: MetricPattern7[T] = MetricPattern7(client, _m(acc, 'median')) - self.pct10: MetricPattern7[T] = MetricPattern7(client, _m(acc, 'pct10')) - self.pct25: MetricPattern7[T] = MetricPattern7(client, _m(acc, 'pct25')) - self.pct75: MetricPattern7[T] = MetricPattern7(client, _m(acc, 'pct75')) - self.pct90: MetricPattern7[T] = MetricPattern7(client, _m(acc, 'pct90')) - -class DateindexPattern2: - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.close: MetricPattern7[Cents] = MetricPattern7(client, _m(acc, 'close_cents')) - self.high: MetricPattern7[Cents] = MetricPattern7(client, _m(acc, 'high_cents')) - self.low: MetricPattern7[Cents] = MetricPattern7(client, _m(acc, 'low_cents')) - self.open: MetricPattern7[Cents] = MetricPattern7(client, _m(acc, 'open_cents')) - -class HighPattern(Generic[T]): - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.dateindex: MetricPattern7[T] = MetricPattern7(client, acc) - self.difficultyepoch: MetricPattern9[T] = MetricPattern9(client, _m(acc, 'max')) - self.height: MetricPattern12[T] = MetricPattern12(client, acc) - self.rest: MetricPattern5[T] = MetricPattern5(client, _m(acc, 'max')) - -class SplitPattern2(Generic[T]): - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.close: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'close')) - self.high: HighPattern[T] = HighPattern(client, _m(acc, 'high')) - self.low: HighPattern[T] = HighPattern(client, _m(acc, 'low')) - self.open: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'open')) - -class _24hCoinbaseSumPattern: - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.bitcoin: MetricPattern12[Bitcoin] = MetricPattern12(client, _m(acc, 'btc')) - self.dollars: MetricPattern12[Dollars] = MetricPattern12(client, _m(acc, 'usd')) - self.sats: MetricPattern12[Sats] = MetricPattern12(client, acc) + self.close: MetricPattern5[T] = MetricPattern5(client, _m(acc, 'close_cents')) + self.high: MetricPattern5[T] = MetricPattern5(client, _m(acc, 'high_cents')) + self.low: MetricPattern5[T] = MetricPattern5(client, _m(acc, 'low_cents')) + self.open: MetricPattern5[T] = MetricPattern5(client, _m(acc, 'open_cents')) class CoinbasePattern: """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.bitcoin: BitcoinPattern[Bitcoin] = BitcoinPattern(client, _m(acc, 'btc')) - self.dollars: BitcoinPattern[Dollars] = BitcoinPattern(client, _m(acc, 'usd')) - self.sats: BitcoinPattern[Sats] = BitcoinPattern(client, acc) + self.bitcoin: FullnessPattern[Bitcoin] = FullnessPattern(client, _m(acc, 'btc')) + self.dollars: FullnessPattern[Dollars] = FullnessPattern(client, _m(acc, 'usd')) + self.sats: FullnessPattern[Sats] = FullnessPattern(client, acc) + +class SegwitAdoptionPattern: + """Pattern struct for repeated tree structure.""" + + def __init__(self, client: BrkClientBase, acc: str): + """Create pattern node with accumulated metric name.""" + self.base: MetricPattern11[StoredF32] = MetricPattern11(client, acc) + self.cumulative: MetricPattern2[StoredF32] = MetricPattern2(client, _m(acc, 'cumulative')) + self.sum: MetricPattern2[StoredF32] = MetricPattern2(client, _m(acc, 'sum')) + +class _24hCoinbaseSumPattern: + """Pattern struct for repeated tree structure.""" + + def __init__(self, client: BrkClientBase, acc: str): + """Create pattern node with accumulated metric name.""" + self.bitcoin: MetricPattern11[Bitcoin] = MetricPattern11(client, _m(acc, 'btc')) + self.dollars: MetricPattern11[Dollars] = MetricPattern11(client, _m(acc, 'usd')) + self.sats: MetricPattern11[Sats] = MetricPattern11(client, acc) + +class CostBasisPattern2: + """Pattern struct for repeated tree structure.""" + + def __init__(self, client: BrkClientBase, acc: str): + """Create pattern node with accumulated metric name.""" + self.max: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'max_cost_basis')) + self.min: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'min_cost_basis')) + self.percentiles: PercentilesPattern = PercentilesPattern(client, _m(acc, 'cost_basis')) class UnclaimedRewardsPattern: """Pattern struct for repeated tree structure.""" @@ -2390,31 +2318,13 @@ class UnclaimedRewardsPattern: self.dollars: BlockCountPattern[Dollars] = BlockCountPattern(client, _m(acc, 'usd')) self.sats: BlockCountPattern[Sats] = BlockCountPattern(client, acc) -class CostBasisPattern2: +class RelativePattern4: """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.max: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'max_cost_basis')) - self.min: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'min_cost_basis')) - self.percentiles: PercentilesPattern2 = PercentilesPattern2(client, _m(acc, 'cost_basis')) - -class SegwitAdoptionPattern: - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.cumulative: MetricPattern2[StoredF32] = MetricPattern2(client, _m(acc, 'cumulative')) - self.height: MetricPattern12[StoredF32] = MetricPattern12(client, acc) - self.sum: MetricPattern2[StoredF32] = MetricPattern2(client, _m(acc, 'sum')) - -class SatsPattern: - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.ohlc: OhlcPattern[OHLCSats] = OhlcPattern(client, _m(acc, 'ohlc_sats')) - self.split: SplitPattern2[Sats] = SplitPattern2(client, _m(acc, 'sats')) + self.supply_in_loss_rel_to_own_supply: MetricPattern1[StoredF64] = MetricPattern1(client, _m(acc, 'loss_rel_to_own_supply')) + self.supply_in_profit_rel_to_own_supply: MetricPattern1[StoredF64] = MetricPattern1(client, _m(acc, 'profit_rel_to_own_supply')) class CostBasisPattern: """Pattern struct for repeated tree structure.""" @@ -2424,14 +2334,6 @@ class CostBasisPattern: self.max: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'max_cost_basis')) self.min: MetricPattern1[Dollars] = MetricPattern1(client, _m(acc, 'min_cost_basis')) -class _1dReturns1mSdPattern: - """Pattern struct for repeated tree structure.""" - - def __init__(self, client: BrkClientBase, acc: str): - """Create pattern node with accumulated metric name.""" - self.sd: MetricPattern4[StoredF32] = MetricPattern4(client, _m(acc, 'sd')) - self.sma: MetricPattern4[StoredF32] = MetricPattern4(client, _m(acc, 'sma')) - class SupplyPattern2: """Pattern struct for repeated tree structure.""" @@ -2440,20 +2342,28 @@ class SupplyPattern2: self.halved: _24hCoinbaseSumPattern = _24hCoinbaseSumPattern(client, _m(acc, 'half')) self.total: _24hCoinbaseSumPattern = _24hCoinbaseSumPattern(client, acc) -class RelativePattern4: +class _1dReturns1mSdPattern: """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.supply_in_loss_rel_to_own_supply: MetricPattern1[StoredF64] = MetricPattern1(client, _m(acc, 'loss_rel_to_own_supply')) - self.supply_in_profit_rel_to_own_supply: MetricPattern1[StoredF64] = MetricPattern1(client, _m(acc, 'profit_rel_to_own_supply')) + self.sd: MetricPattern4[StoredF32] = MetricPattern4(client, _m(acc, 'sd')) + self.sma: MetricPattern4[StoredF32] = MetricPattern4(client, _m(acc, 'sma')) + +class CentsPattern(Generic[T]): + """Pattern struct for repeated tree structure.""" + + def __init__(self, client: BrkClientBase, acc: str): + """Create pattern node with accumulated metric name.""" + self.ohlc: MetricPattern5[T] = MetricPattern5(client, _m(acc, 'ohlc_sats')) + self.split: SplitPattern[T] = SplitPattern(client, _m(acc, 'sats')) class BlockCountPattern(Generic[T]): """Pattern struct for repeated tree structure.""" def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.cumulative: MetricPattern2[T] = MetricPattern2(client, _m(acc, 'cumulative')) + self.cumulative: MetricPattern1[T] = MetricPattern1(client, _m(acc, 'cumulative')) self.sum: MetricPattern1[T] = MetricPattern1(client, acc) class RealizedPriceExtraPattern: @@ -2475,7 +2385,7 @@ class EmptyPattern(Generic[T]): def __init__(self, client: BrkClientBase, acc: str): """Create pattern node with accumulated metric name.""" - self.identity: MetricPattern25[T] = MetricPattern25(client, acc) + self.identity: MetricPattern23[T] = MetricPattern23(client, acc) # Catalog tree classes @@ -2503,52 +2413,53 @@ class CatalogTree_Addresses: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.first_p2aaddressindex: MetricPattern12[P2AAddressIndex] = MetricPattern12(client, f'{base_path}_first_p2aaddressindex') - self.first_p2pk33addressindex: MetricPattern12[P2PK33AddressIndex] = MetricPattern12(client, f'{base_path}_first_p2pk33addressindex') - self.first_p2pk65addressindex: MetricPattern12[P2PK65AddressIndex] = MetricPattern12(client, f'{base_path}_first_p2pk65addressindex') - self.first_p2pkhaddressindex: MetricPattern12[P2PKHAddressIndex] = MetricPattern12(client, f'{base_path}_first_p2pkhaddressindex') - self.first_p2shaddressindex: MetricPattern12[P2SHAddressIndex] = MetricPattern12(client, f'{base_path}_first_p2shaddressindex') - self.first_p2traddressindex: MetricPattern12[P2TRAddressIndex] = MetricPattern12(client, f'{base_path}_first_p2traddressindex') - self.first_p2wpkhaddressindex: MetricPattern12[P2WPKHAddressIndex] = MetricPattern12(client, f'{base_path}_first_p2wpkhaddressindex') - self.first_p2wshaddressindex: MetricPattern12[P2WSHAddressIndex] = MetricPattern12(client, f'{base_path}_first_p2wshaddressindex') - self.p2abytes: MetricPattern17[P2ABytes] = MetricPattern17(client, f'{base_path}_p2abytes') - self.p2pk33bytes: MetricPattern19[P2PK33Bytes] = MetricPattern19(client, f'{base_path}_p2pk33bytes') - self.p2pk65bytes: MetricPattern20[P2PK65Bytes] = MetricPattern20(client, f'{base_path}_p2pk65bytes') - self.p2pkhbytes: MetricPattern21[P2PKHBytes] = MetricPattern21(client, f'{base_path}_p2pkhbytes') - self.p2shbytes: MetricPattern22[P2SHBytes] = MetricPattern22(client, f'{base_path}_p2shbytes') - self.p2trbytes: MetricPattern23[P2TRBytes] = MetricPattern23(client, f'{base_path}_p2trbytes') - self.p2wpkhbytes: MetricPattern24[P2WPKHBytes] = MetricPattern24(client, f'{base_path}_p2wpkhbytes') - self.p2wshbytes: MetricPattern25[P2WSHBytes] = MetricPattern25(client, f'{base_path}_p2wshbytes') + self.first_p2aaddressindex: MetricPattern11[P2AAddressIndex] = MetricPattern11(client, f'{base_path}_first_p2aaddressindex') + self.first_p2pk33addressindex: MetricPattern11[P2PK33AddressIndex] = MetricPattern11(client, f'{base_path}_first_p2pk33addressindex') + self.first_p2pk65addressindex: MetricPattern11[P2PK65AddressIndex] = MetricPattern11(client, f'{base_path}_first_p2pk65addressindex') + self.first_p2pkhaddressindex: MetricPattern11[P2PKHAddressIndex] = MetricPattern11(client, f'{base_path}_first_p2pkhaddressindex') + self.first_p2shaddressindex: MetricPattern11[P2SHAddressIndex] = MetricPattern11(client, f'{base_path}_first_p2shaddressindex') + self.first_p2traddressindex: MetricPattern11[P2TRAddressIndex] = MetricPattern11(client, f'{base_path}_first_p2traddressindex') + self.first_p2wpkhaddressindex: MetricPattern11[P2WPKHAddressIndex] = MetricPattern11(client, f'{base_path}_first_p2wpkhaddressindex') + self.first_p2wshaddressindex: MetricPattern11[P2WSHAddressIndex] = MetricPattern11(client, f'{base_path}_first_p2wshaddressindex') + self.p2abytes: MetricPattern16[P2ABytes] = MetricPattern16(client, f'{base_path}_p2abytes') + self.p2pk33bytes: MetricPattern18[P2PK33Bytes] = MetricPattern18(client, f'{base_path}_p2pk33bytes') + self.p2pk65bytes: MetricPattern19[P2PK65Bytes] = MetricPattern19(client, f'{base_path}_p2pk65bytes') + self.p2pkhbytes: MetricPattern20[P2PKHBytes] = MetricPattern20(client, f'{base_path}_p2pkhbytes') + self.p2shbytes: MetricPattern21[P2SHBytes] = MetricPattern21(client, f'{base_path}_p2shbytes') + self.p2trbytes: MetricPattern22[P2TRBytes] = MetricPattern22(client, f'{base_path}_p2trbytes') + self.p2wpkhbytes: MetricPattern23[P2WPKHBytes] = MetricPattern23(client, f'{base_path}_p2wpkhbytes') + self.p2wshbytes: MetricPattern24[P2WSHBytes] = MetricPattern24(client, f'{base_path}_p2wshbytes') class CatalogTree_Blocks: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.blockhash: MetricPattern12[BlockHash] = MetricPattern12(client, f'{base_path}_blockhash') + self.blockhash: MetricPattern11[BlockHash] = MetricPattern11(client, f'{base_path}_blockhash') self.count: CatalogTree_Blocks_Count = CatalogTree_Blocks_Count(client, f'{base_path}_count') self.difficulty: CatalogTree_Blocks_Difficulty = CatalogTree_Blocks_Difficulty(client, f'{base_path}_difficulty') + self.fullness: FullnessPattern[StoredF32] = FullnessPattern(client, 'block_fullness') self.halving: CatalogTree_Blocks_Halving = CatalogTree_Blocks_Halving(client, f'{base_path}_halving') self.interval: CatalogTree_Blocks_Interval = CatalogTree_Blocks_Interval(client, f'{base_path}_interval') self.mining: CatalogTree_Blocks_Mining = CatalogTree_Blocks_Mining(client, f'{base_path}_mining') self.rewards: CatalogTree_Blocks_Rewards = CatalogTree_Blocks_Rewards(client, f'{base_path}_rewards') - self.size: CatalogTree_Blocks_Size = CatalogTree_Blocks_Size(client, f'{base_path}_size') + self.size: SizePattern[StoredU64] = SizePattern(client, 'block_size') self.time: CatalogTree_Blocks_Time = CatalogTree_Blocks_Time(client, f'{base_path}_time') - self.timestamp: MetricPattern12[Timestamp] = MetricPattern12(client, f'{base_path}_timestamp') - self.total_size: MetricPattern12[StoredU64] = MetricPattern12(client, f'{base_path}_total_size') - self.weight: CatalogTree_Blocks_Weight = CatalogTree_Blocks_Weight(client, f'{base_path}_weight') + self.total_size: MetricPattern11[StoredU64] = MetricPattern11(client, f'{base_path}_total_size') + self.vbytes: FullnessPattern[StoredU64] = FullnessPattern(client, 'block_vbytes') + self.weight: FullnessPattern[Weight] = FullnessPattern(client, '') class CatalogTree_Blocks_Count: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): self._1m_block_count: MetricPattern1[StoredU32] = MetricPattern1(client, f'{base_path}__1m_block_count') - self._1m_start: MetricPattern12[Height] = MetricPattern12(client, f'{base_path}__1m_start') + self._1m_start: MetricPattern11[Height] = MetricPattern11(client, f'{base_path}__1m_start') self._1w_block_count: MetricPattern1[StoredU32] = MetricPattern1(client, f'{base_path}__1w_block_count') - self._1w_start: MetricPattern12[Height] = MetricPattern12(client, f'{base_path}__1w_start') + self._1w_start: MetricPattern11[Height] = MetricPattern11(client, f'{base_path}__1w_start') self._1y_block_count: MetricPattern1[StoredU32] = MetricPattern1(client, f'{base_path}__1y_block_count') - self._1y_start: MetricPattern12[Height] = MetricPattern12(client, f'{base_path}__1y_start') + self._1y_start: MetricPattern11[Height] = MetricPattern11(client, f'{base_path}__1y_start') self._24h_block_count: MetricPattern1[StoredU32] = MetricPattern1(client, f'{base_path}__24h_block_count') - self._24h_start: MetricPattern12[Height] = MetricPattern12(client, f'{base_path}__24h_start') + self._24h_start: MetricPattern11[Height] = MetricPattern11(client, f'{base_path}__24h_start') self.block_count: BlockCountPattern[StoredU32] = BlockCountPattern(client, 'block_count') self.block_count_target: MetricPattern4[StoredU64] = MetricPattern4(client, f'{base_path}_block_count_target') @@ -2556,10 +2467,12 @@ class CatalogTree_Blocks_Difficulty: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.base: MetricPattern12[StoredF64] = MetricPattern12(client, f'{base_path}_base') - self.blocks_before_next_difficulty_adjustment: MetricPattern1[StoredU32] = MetricPattern1(client, f'{base_path}_blocks_before_next_difficulty_adjustment') - self.days_before_next_difficulty_adjustment: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_days_before_next_difficulty_adjustment') + self.adjustment: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_adjustment') + self.as_hash: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_as_hash') + self.blocks_before_next_adjustment: MetricPattern1[StoredU32] = MetricPattern1(client, f'{base_path}_blocks_before_next_adjustment') + self.days_before_next_adjustment: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_days_before_next_adjustment') self.epoch: MetricPattern4[DifficultyEpoch] = MetricPattern4(client, f'{base_path}_epoch') + self.raw: MetricPattern1[StoredF64] = MetricPattern1(client, f'{base_path}_raw') class CatalogTree_Blocks_Halving: """Catalog tree node.""" @@ -2574,22 +2487,19 @@ class CatalogTree_Blocks_Interval: def __init__(self, client: BrkClientBase, base_path: str = ''): self.average: MetricPattern2[Timestamp] = MetricPattern2(client, f'{base_path}_average') - self.base: MetricPattern12[Timestamp] = MetricPattern12(client, f'{base_path}_base') + self.base: MetricPattern11[Timestamp] = MetricPattern11(client, f'{base_path}_base') self.max: MetricPattern2[Timestamp] = MetricPattern2(client, f'{base_path}_max') - self.median: MetricPattern7[Timestamp] = MetricPattern7(client, f'{base_path}_median') + self.median: MetricPattern6[Timestamp] = MetricPattern6(client, f'{base_path}_median') self.min: MetricPattern2[Timestamp] = MetricPattern2(client, f'{base_path}_min') - self.pct10: MetricPattern7[Timestamp] = MetricPattern7(client, f'{base_path}_pct10') - self.pct25: MetricPattern7[Timestamp] = MetricPattern7(client, f'{base_path}_pct25') - self.pct75: MetricPattern7[Timestamp] = MetricPattern7(client, f'{base_path}_pct75') - self.pct90: MetricPattern7[Timestamp] = MetricPattern7(client, f'{base_path}_pct90') + self.pct10: MetricPattern6[Timestamp] = MetricPattern6(client, f'{base_path}_pct10') + self.pct25: MetricPattern6[Timestamp] = MetricPattern6(client, f'{base_path}_pct25') + self.pct75: MetricPattern6[Timestamp] = MetricPattern6(client, f'{base_path}_pct75') + self.pct90: MetricPattern6[Timestamp] = MetricPattern6(client, f'{base_path}_pct90') class CatalogTree_Blocks_Mining: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.difficulty: MetricPattern2[StoredF64] = MetricPattern2(client, f'{base_path}_difficulty') - self.difficulty_adjustment: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_difficulty_adjustment') - self.difficulty_as_hash: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_difficulty_as_hash') self.hash_price_phs: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_hash_price_phs') self.hash_price_phs_min: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_hash_price_phs_min') self.hash_price_rebound: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_hash_price_rebound') @@ -2612,47 +2522,20 @@ class CatalogTree_Blocks_Rewards: def __init__(self, client: BrkClientBase, base_path: str = ''): self._24h_coinbase_sum: _24hCoinbaseSumPattern = _24hCoinbaseSumPattern(client, '24h_coinbase_sum') self.coinbase: CoinbasePattern = CoinbasePattern(client, 'coinbase') - self.fee_dominance: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_fee_dominance') + self.fee_dominance: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_fee_dominance') self.subsidy: CoinbasePattern = CoinbasePattern(client, 'subsidy') - self.subsidy_dominance: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_subsidy_dominance') + self.subsidy_dominance: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_subsidy_dominance') self.subsidy_usd_1y_sma: MetricPattern4[Dollars] = MetricPattern4(client, f'{base_path}_subsidy_usd_1y_sma') self.unclaimed_rewards: UnclaimedRewardsPattern = UnclaimedRewardsPattern(client, 'unclaimed_rewards') -class CatalogTree_Blocks_Size: - """Catalog tree node.""" - - def __init__(self, client: BrkClientBase, base_path: str = ''): - self.size: SizePattern[StoredU64] = SizePattern(client, 'block_size') - self.vbytes: CatalogTree_Blocks_Size_Vbytes = CatalogTree_Blocks_Size_Vbytes(client, f'{base_path}_vbytes') - -class CatalogTree_Blocks_Size_Vbytes: - """Catalog tree node.""" - - def __init__(self, client: BrkClientBase, base_path: str = ''): - self.average: MetricPattern2[StoredU64] = MetricPattern2(client, f'{base_path}_average') - self.base: MetricPattern12[StoredU64] = MetricPattern12(client, f'{base_path}_base') - self.cumulative: MetricPattern1[StoredU64] = MetricPattern1(client, f'{base_path}_cumulative') - self.max: MetricPattern2[StoredU64] = MetricPattern2(client, f'{base_path}_max') - self.min: MetricPattern2[StoredU64] = MetricPattern2(client, f'{base_path}_min') - self.percentiles: PercentilesPattern[StoredU64] = PercentilesPattern(client, 'block_vbytes') - self.sum: MetricPattern2[StoredU64] = MetricPattern2(client, f'{base_path}_sum') - class CatalogTree_Blocks_Time: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.date: MetricPattern12[Date] = MetricPattern12(client, f'{base_path}_date') - self.date_fixed: MetricPattern12[Date] = MetricPattern12(client, f'{base_path}_date_fixed') - self.timestamp: MetricPattern2[Timestamp] = MetricPattern2(client, f'{base_path}_timestamp') - self.timestamp_fixed: MetricPattern12[Timestamp] = MetricPattern12(client, f'{base_path}_timestamp_fixed') - -class CatalogTree_Blocks_Weight: - """Catalog tree node.""" - - def __init__(self, client: BrkClientBase, base_path: str = ''): - self.base: MetricPattern12[Weight] = MetricPattern12(client, f'{base_path}_base') - self.fullness: BitcoinPattern[StoredF32] = BitcoinPattern(client, 'block_fullness') - self.weight: SizePattern[Weight] = SizePattern(client, 'block_weight') + self.date: MetricPattern11[Date] = MetricPattern11(client, f'{base_path}_date') + self.date_fixed: MetricPattern11[Date] = MetricPattern11(client, f'{base_path}_date_fixed') + self.timestamp: MetricPattern1[Timestamp] = MetricPattern1(client, f'{base_path}_timestamp') + self.timestamp_fixed: MetricPattern11[Timestamp] = MetricPattern11(client, f'{base_path}_timestamp_fixed') class CatalogTree_Cointime: """Catalog tree node.""" @@ -2725,24 +2608,24 @@ class CatalogTree_Constants: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.constant_0: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_0') - self.constant_1: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_1') - self.constant_100: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_100') - self.constant_2: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_2') - self.constant_20: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_20') - self.constant_3: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_3') - self.constant_30: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_30') - self.constant_38_2: MetricPattern3[StoredF32] = MetricPattern3(client, f'{base_path}_constant_38_2') - self.constant_4: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_4') - self.constant_50: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_50') - self.constant_600: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_600') - self.constant_61_8: MetricPattern3[StoredF32] = MetricPattern3(client, f'{base_path}_constant_61_8') - self.constant_70: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_70') - self.constant_80: MetricPattern3[StoredU16] = MetricPattern3(client, f'{base_path}_constant_80') - self.constant_minus_1: MetricPattern3[StoredI16] = MetricPattern3(client, f'{base_path}_constant_minus_1') - self.constant_minus_2: MetricPattern3[StoredI16] = MetricPattern3(client, f'{base_path}_constant_minus_2') - self.constant_minus_3: MetricPattern3[StoredI16] = MetricPattern3(client, f'{base_path}_constant_minus_3') - self.constant_minus_4: MetricPattern3[StoredI16] = MetricPattern3(client, f'{base_path}_constant_minus_4') + self.constant_0: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_0') + self.constant_1: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_1') + self.constant_100: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_100') + self.constant_2: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_2') + self.constant_20: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_20') + self.constant_3: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_3') + self.constant_30: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_30') + self.constant_38_2: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_constant_38_2') + self.constant_4: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_4') + self.constant_50: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_50') + self.constant_600: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_600') + self.constant_61_8: MetricPattern1[StoredF32] = MetricPattern1(client, f'{base_path}_constant_61_8') + self.constant_70: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_70') + self.constant_80: MetricPattern1[StoredU16] = MetricPattern1(client, f'{base_path}_constant_80') + self.constant_minus_1: MetricPattern1[StoredI16] = MetricPattern1(client, f'{base_path}_constant_minus_1') + self.constant_minus_2: MetricPattern1[StoredI16] = MetricPattern1(client, f'{base_path}_constant_minus_2') + self.constant_minus_3: MetricPattern1[StoredI16] = MetricPattern1(client, f'{base_path}_constant_minus_3') + self.constant_minus_4: MetricPattern1[StoredI16] = MetricPattern1(client, f'{base_path}_constant_minus_4') class CatalogTree_Distribution: """Catalog tree node.""" @@ -2752,10 +2635,10 @@ class CatalogTree_Distribution: self.address_cohorts: CatalogTree_Distribution_AddressCohorts = CatalogTree_Distribution_AddressCohorts(client, f'{base_path}_address_cohorts') self.addresses_data: CatalogTree_Distribution_AddressesData = CatalogTree_Distribution_AddressesData(client, f'{base_path}_addresses_data') self.any_address_indexes: CatalogTree_Distribution_AnyAddressIndexes = CatalogTree_Distribution_AnyAddressIndexes(client, f'{base_path}_any_address_indexes') - self.chain_state: MetricPattern12[SupplyState] = MetricPattern12(client, f'{base_path}_chain_state') + self.chain_state: MetricPattern11[SupplyState] = MetricPattern11(client, f'{base_path}_chain_state') self.empty_addr_count: AddrCountPattern = AddrCountPattern(client, 'empty_addr_count') - self.emptyaddressindex: MetricPattern33[EmptyAddressIndex] = MetricPattern33(client, f'{base_path}_emptyaddressindex') - self.loadedaddressindex: MetricPattern32[LoadedAddressIndex] = MetricPattern32(client, f'{base_path}_loadedaddressindex') + self.emptyaddressindex: MetricPattern32[EmptyAddressIndex] = MetricPattern32(client, f'{base_path}_emptyaddressindex') + self.loadedaddressindex: MetricPattern31[LoadedAddressIndex] = MetricPattern31(client, f'{base_path}_loadedaddressindex') self.utxo_cohorts: CatalogTree_Distribution_UtxoCohorts = CatalogTree_Distribution_UtxoCohorts(client, f'{base_path}_utxo_cohorts') class CatalogTree_Distribution_AddressCohorts: @@ -2826,21 +2709,21 @@ class CatalogTree_Distribution_AddressesData: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.empty: MetricPattern33[EmptyAddressData] = MetricPattern33(client, f'{base_path}_empty') - self.loaded: MetricPattern32[LoadedAddressData] = MetricPattern32(client, f'{base_path}_loaded') + self.empty: MetricPattern32[EmptyAddressData] = MetricPattern32(client, f'{base_path}_empty') + self.loaded: MetricPattern31[LoadedAddressData] = MetricPattern31(client, f'{base_path}_loaded') class CatalogTree_Distribution_AnyAddressIndexes: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.p2a: MetricPattern17[AnyAddressIndex] = MetricPattern17(client, f'{base_path}_p2a') - self.p2pk33: MetricPattern19[AnyAddressIndex] = MetricPattern19(client, f'{base_path}_p2pk33') - self.p2pk65: MetricPattern20[AnyAddressIndex] = MetricPattern20(client, f'{base_path}_p2pk65') - self.p2pkh: MetricPattern21[AnyAddressIndex] = MetricPattern21(client, f'{base_path}_p2pkh') - self.p2sh: MetricPattern22[AnyAddressIndex] = MetricPattern22(client, f'{base_path}_p2sh') - self.p2tr: MetricPattern23[AnyAddressIndex] = MetricPattern23(client, f'{base_path}_p2tr') - self.p2wpkh: MetricPattern24[AnyAddressIndex] = MetricPattern24(client, f'{base_path}_p2wpkh') - self.p2wsh: MetricPattern25[AnyAddressIndex] = MetricPattern25(client, f'{base_path}_p2wsh') + self.p2a: MetricPattern16[AnyAddressIndex] = MetricPattern16(client, f'{base_path}_p2a') + self.p2pk33: MetricPattern18[AnyAddressIndex] = MetricPattern18(client, f'{base_path}_p2pk33') + self.p2pk65: MetricPattern19[AnyAddressIndex] = MetricPattern19(client, f'{base_path}_p2pk65') + self.p2pkh: MetricPattern20[AnyAddressIndex] = MetricPattern20(client, f'{base_path}_p2pkh') + self.p2sh: MetricPattern21[AnyAddressIndex] = MetricPattern21(client, f'{base_path}_p2sh') + self.p2tr: MetricPattern22[AnyAddressIndex] = MetricPattern22(client, f'{base_path}_p2tr') + self.p2wpkh: MetricPattern23[AnyAddressIndex] = MetricPattern23(client, f'{base_path}_p2wpkh') + self.p2wsh: MetricPattern24[AnyAddressIndex] = MetricPattern24(client, f'{base_path}_p2wsh') class CatalogTree_Distribution_UtxoCohorts: """Catalog tree node.""" @@ -3129,117 +3012,117 @@ class CatalogTree_Indexes_Dateindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.date: MetricPattern7[Date] = MetricPattern7(client, f'{base_path}_date') - self.first_height: MetricPattern7[Height] = MetricPattern7(client, f'{base_path}_first_height') - self.height_count: MetricPattern7[StoredU64] = MetricPattern7(client, f'{base_path}_height_count') - self.identity: MetricPattern7[DateIndex] = MetricPattern7(client, f'{base_path}_identity') - self.monthindex: MetricPattern7[MonthIndex] = MetricPattern7(client, f'{base_path}_monthindex') - self.weekindex: MetricPattern7[WeekIndex] = MetricPattern7(client, f'{base_path}_weekindex') + self.date: MetricPattern6[Date] = MetricPattern6(client, f'{base_path}_date') + self.first_height: MetricPattern6[Height] = MetricPattern6(client, f'{base_path}_first_height') + self.height_count: MetricPattern6[StoredU64] = MetricPattern6(client, f'{base_path}_height_count') + self.identity: MetricPattern6[DateIndex] = MetricPattern6(client, f'{base_path}_identity') + self.monthindex: MetricPattern6[MonthIndex] = MetricPattern6(client, f'{base_path}_monthindex') + self.weekindex: MetricPattern6[WeekIndex] = MetricPattern6(client, f'{base_path}_weekindex') class CatalogTree_Indexes_Decadeindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.first_yearindex: MetricPattern8[YearIndex] = MetricPattern8(client, f'{base_path}_first_yearindex') - self.identity: MetricPattern8[DecadeIndex] = MetricPattern8(client, f'{base_path}_identity') - self.yearindex_count: MetricPattern8[StoredU64] = MetricPattern8(client, f'{base_path}_yearindex_count') + self.first_yearindex: MetricPattern7[YearIndex] = MetricPattern7(client, f'{base_path}_first_yearindex') + self.identity: MetricPattern7[DecadeIndex] = MetricPattern7(client, f'{base_path}_identity') + self.yearindex_count: MetricPattern7[StoredU64] = MetricPattern7(client, f'{base_path}_yearindex_count') class CatalogTree_Indexes_Difficultyepoch: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.first_height: MetricPattern9[Height] = MetricPattern9(client, f'{base_path}_first_height') - self.height_count: MetricPattern9[StoredU64] = MetricPattern9(client, f'{base_path}_height_count') - self.identity: MetricPattern9[DifficultyEpoch] = MetricPattern9(client, f'{base_path}_identity') + self.first_height: MetricPattern8[Height] = MetricPattern8(client, f'{base_path}_first_height') + self.height_count: MetricPattern8[StoredU64] = MetricPattern8(client, f'{base_path}_height_count') + self.identity: MetricPattern8[DifficultyEpoch] = MetricPattern8(client, f'{base_path}_identity') class CatalogTree_Indexes_Halvingepoch: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.first_height: MetricPattern11[Height] = MetricPattern11(client, f'{base_path}_first_height') - self.identity: MetricPattern11[HalvingEpoch] = MetricPattern11(client, f'{base_path}_identity') + self.first_height: MetricPattern10[Height] = MetricPattern10(client, f'{base_path}_first_height') + self.identity: MetricPattern10[HalvingEpoch] = MetricPattern10(client, f'{base_path}_identity') class CatalogTree_Indexes_Height: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.dateindex: MetricPattern12[DateIndex] = MetricPattern12(client, f'{base_path}_dateindex') - self.difficultyepoch: MetricPattern12[DifficultyEpoch] = MetricPattern12(client, f'{base_path}_difficultyepoch') - self.halvingepoch: MetricPattern12[HalvingEpoch] = MetricPattern12(client, f'{base_path}_halvingepoch') - self.identity: MetricPattern12[Height] = MetricPattern12(client, f'{base_path}_identity') - self.txindex_count: MetricPattern12[StoredU64] = MetricPattern12(client, f'{base_path}_txindex_count') + self.dateindex: MetricPattern11[DateIndex] = MetricPattern11(client, f'{base_path}_dateindex') + self.difficultyepoch: MetricPattern11[DifficultyEpoch] = MetricPattern11(client, f'{base_path}_difficultyepoch') + self.halvingepoch: MetricPattern11[HalvingEpoch] = MetricPattern11(client, f'{base_path}_halvingepoch') + self.identity: MetricPattern11[Height] = MetricPattern11(client, f'{base_path}_identity') + self.txindex_count: MetricPattern11[StoredU64] = MetricPattern11(client, f'{base_path}_txindex_count') class CatalogTree_Indexes_Monthindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.dateindex_count: MetricPattern14[StoredU64] = MetricPattern14(client, f'{base_path}_dateindex_count') - self.first_dateindex: MetricPattern14[DateIndex] = MetricPattern14(client, f'{base_path}_first_dateindex') - self.identity: MetricPattern14[MonthIndex] = MetricPattern14(client, f'{base_path}_identity') - self.quarterindex: MetricPattern14[QuarterIndex] = MetricPattern14(client, f'{base_path}_quarterindex') - self.semesterindex: MetricPattern14[SemesterIndex] = MetricPattern14(client, f'{base_path}_semesterindex') - self.yearindex: MetricPattern14[YearIndex] = MetricPattern14(client, f'{base_path}_yearindex') + self.dateindex_count: MetricPattern13[StoredU64] = MetricPattern13(client, f'{base_path}_dateindex_count') + self.first_dateindex: MetricPattern13[DateIndex] = MetricPattern13(client, f'{base_path}_first_dateindex') + self.identity: MetricPattern13[MonthIndex] = MetricPattern13(client, f'{base_path}_identity') + self.quarterindex: MetricPattern13[QuarterIndex] = MetricPattern13(client, f'{base_path}_quarterindex') + self.semesterindex: MetricPattern13[SemesterIndex] = MetricPattern13(client, f'{base_path}_semesterindex') + self.yearindex: MetricPattern13[YearIndex] = MetricPattern13(client, f'{base_path}_yearindex') class CatalogTree_Indexes_Quarterindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.first_monthindex: MetricPattern26[MonthIndex] = MetricPattern26(client, f'{base_path}_first_monthindex') - self.identity: MetricPattern26[QuarterIndex] = MetricPattern26(client, f'{base_path}_identity') - self.monthindex_count: MetricPattern26[StoredU64] = MetricPattern26(client, f'{base_path}_monthindex_count') + self.first_monthindex: MetricPattern25[MonthIndex] = MetricPattern25(client, f'{base_path}_first_monthindex') + self.identity: MetricPattern25[QuarterIndex] = MetricPattern25(client, f'{base_path}_identity') + self.monthindex_count: MetricPattern25[StoredU64] = MetricPattern25(client, f'{base_path}_monthindex_count') class CatalogTree_Indexes_Semesterindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.first_monthindex: MetricPattern27[MonthIndex] = MetricPattern27(client, f'{base_path}_first_monthindex') - self.identity: MetricPattern27[SemesterIndex] = MetricPattern27(client, f'{base_path}_identity') - self.monthindex_count: MetricPattern27[StoredU64] = MetricPattern27(client, f'{base_path}_monthindex_count') + self.first_monthindex: MetricPattern26[MonthIndex] = MetricPattern26(client, f'{base_path}_first_monthindex') + self.identity: MetricPattern26[SemesterIndex] = MetricPattern26(client, f'{base_path}_identity') + self.monthindex_count: MetricPattern26[StoredU64] = MetricPattern26(client, f'{base_path}_monthindex_count') class CatalogTree_Indexes_Txindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.identity: MetricPattern28[TxIndex] = MetricPattern28(client, f'{base_path}_identity') - self.input_count: MetricPattern28[StoredU64] = MetricPattern28(client, f'{base_path}_input_count') - self.output_count: MetricPattern28[StoredU64] = MetricPattern28(client, f'{base_path}_output_count') + self.identity: MetricPattern27[TxIndex] = MetricPattern27(client, f'{base_path}_identity') + self.input_count: MetricPattern27[StoredU64] = MetricPattern27(client, f'{base_path}_input_count') + self.output_count: MetricPattern27[StoredU64] = MetricPattern27(client, f'{base_path}_output_count') class CatalogTree_Indexes_Weekindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.dateindex_count: MetricPattern30[StoredU64] = MetricPattern30(client, f'{base_path}_dateindex_count') - self.first_dateindex: MetricPattern30[DateIndex] = MetricPattern30(client, f'{base_path}_first_dateindex') - self.identity: MetricPattern30[WeekIndex] = MetricPattern30(client, f'{base_path}_identity') + self.dateindex_count: MetricPattern29[StoredU64] = MetricPattern29(client, f'{base_path}_dateindex_count') + self.first_dateindex: MetricPattern29[DateIndex] = MetricPattern29(client, f'{base_path}_first_dateindex') + self.identity: MetricPattern29[WeekIndex] = MetricPattern29(client, f'{base_path}_identity') class CatalogTree_Indexes_Yearindex: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.decadeindex: MetricPattern31[DecadeIndex] = MetricPattern31(client, f'{base_path}_decadeindex') - self.first_monthindex: MetricPattern31[MonthIndex] = MetricPattern31(client, f'{base_path}_first_monthindex') - self.identity: MetricPattern31[YearIndex] = MetricPattern31(client, f'{base_path}_identity') - self.monthindex_count: MetricPattern31[StoredU64] = MetricPattern31(client, f'{base_path}_monthindex_count') + self.decadeindex: MetricPattern30[DecadeIndex] = MetricPattern30(client, f'{base_path}_decadeindex') + self.first_monthindex: MetricPattern30[MonthIndex] = MetricPattern30(client, f'{base_path}_first_monthindex') + self.identity: MetricPattern30[YearIndex] = MetricPattern30(client, f'{base_path}_identity') + self.monthindex_count: MetricPattern30[StoredU64] = MetricPattern30(client, f'{base_path}_monthindex_count') class CatalogTree_Inputs: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): self.count: SizePattern[StoredU64] = SizePattern(client, 'input_count') - self.first_txinindex: MetricPattern12[TxInIndex] = MetricPattern12(client, f'{base_path}_first_txinindex') - self.outpoint: MetricPattern13[OutPoint] = MetricPattern13(client, f'{base_path}_outpoint') - self.outputtype: MetricPattern13[OutputType] = MetricPattern13(client, f'{base_path}_outputtype') + self.first_txinindex: MetricPattern11[TxInIndex] = MetricPattern11(client, f'{base_path}_first_txinindex') + self.outpoint: MetricPattern12[OutPoint] = MetricPattern12(client, f'{base_path}_outpoint') + self.outputtype: MetricPattern12[OutputType] = MetricPattern12(client, f'{base_path}_outputtype') self.spent: CatalogTree_Inputs_Spent = CatalogTree_Inputs_Spent(client, f'{base_path}_spent') - self.txindex: MetricPattern13[TxIndex] = MetricPattern13(client, f'{base_path}_txindex') - self.typeindex: MetricPattern13[TypeIndex] = MetricPattern13(client, f'{base_path}_typeindex') - self.witness_size: MetricPattern13[StoredU32] = MetricPattern13(client, f'{base_path}_witness_size') + self.txindex: MetricPattern12[TxIndex] = MetricPattern12(client, f'{base_path}_txindex') + self.typeindex: MetricPattern12[TypeIndex] = MetricPattern12(client, f'{base_path}_typeindex') + self.witness_size: MetricPattern12[StoredU32] = MetricPattern12(client, f'{base_path}_witness_size') class CatalogTree_Inputs_Spent: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.txoutindex: MetricPattern13[TxOutIndex] = MetricPattern13(client, f'{base_path}_txoutindex') - self.value: MetricPattern13[Sats] = MetricPattern13(client, f'{base_path}_value') + self.txoutindex: MetricPattern12[TxOutIndex] = MetricPattern12(client, f'{base_path}_txoutindex') + self.value: MetricPattern12[Sats] = MetricPattern12(client, f'{base_path}_value') class CatalogTree_Market: """Catalog tree node.""" @@ -3298,25 +3181,25 @@ class CatalogTree_Market_Indicators: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.gini: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_gini') - self.macd_histogram: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_macd_histogram') - self.macd_line: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_macd_line') - self.macd_signal: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_macd_signal') + self.gini: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_gini') + self.macd_histogram: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_macd_histogram') + self.macd_line: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_macd_line') + self.macd_signal: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_macd_signal') self.nvt: MetricPattern4[StoredF32] = MetricPattern4(client, f'{base_path}_nvt') - self.pi_cycle: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_pi_cycle') + self.pi_cycle: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_pi_cycle') self.puell_multiple: MetricPattern4[StoredF32] = MetricPattern4(client, f'{base_path}_puell_multiple') - self.rsi_14d: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_rsi_14d') - self.rsi_14d_max: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_rsi_14d_max') - self.rsi_14d_min: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_rsi_14d_min') - self.rsi_average_gain_14d: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_rsi_average_gain_14d') - self.rsi_average_loss_14d: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_rsi_average_loss_14d') - self.rsi_gains: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_rsi_gains') - self.rsi_losses: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_rsi_losses') - self.stoch_d: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_stoch_d') - self.stoch_k: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_stoch_k') - self.stoch_rsi: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_stoch_rsi') - self.stoch_rsi_d: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_stoch_rsi_d') - self.stoch_rsi_k: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_stoch_rsi_k') + self.rsi_14d: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_rsi_14d') + self.rsi_14d_max: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_rsi_14d_max') + self.rsi_14d_min: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_rsi_14d_min') + self.rsi_average_gain_14d: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_rsi_average_gain_14d') + self.rsi_average_loss_14d: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_rsi_average_loss_14d') + self.rsi_gains: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_rsi_gains') + self.rsi_losses: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_rsi_losses') + self.stoch_d: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_stoch_d') + self.stoch_k: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_stoch_k') + self.stoch_rsi: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_stoch_rsi') + self.stoch_rsi_d: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_stoch_rsi_d') + self.stoch_rsi_k: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_stoch_rsi_k') class CatalogTree_Market_Lookback: """Catalog tree node.""" @@ -3377,8 +3260,8 @@ class CatalogTree_Market_Range: self.price_2w_choppiness_index: MetricPattern4[StoredF32] = MetricPattern4(client, f'{base_path}_price_2w_choppiness_index') self.price_2w_max: MetricPattern4[Dollars] = MetricPattern4(client, f'{base_path}_price_2w_max') self.price_2w_min: MetricPattern4[Dollars] = MetricPattern4(client, f'{base_path}_price_2w_min') - self.price_true_range: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_price_true_range') - self.price_true_range_2w_sum: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_price_true_range_2w_sum') + self.price_true_range: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_price_true_range') + self.price_true_range_2w_sum: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_price_true_range_2w_sum') class CatalogTree_Market_Returns: """Catalog tree node.""" @@ -3391,7 +3274,7 @@ class CatalogTree_Market_Returns: self.downside_1m_sd: _1dReturns1mSdPattern = _1dReturns1mSdPattern(client, 'downside_1m_sd') self.downside_1w_sd: _1dReturns1mSdPattern = _1dReturns1mSdPattern(client, 'downside_1w_sd') self.downside_1y_sd: _1dReturns1mSdPattern = _1dReturns1mSdPattern(client, 'downside_1y_sd') - self.downside_returns: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_downside_returns') + self.downside_returns: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_downside_returns') self.price_returns: PriceAgoPattern[StoredF32] = PriceAgoPattern(client, 'price_returns') class CatalogTree_Market_Volatility: @@ -3401,43 +3284,43 @@ class CatalogTree_Market_Volatility: self.price_1m_volatility: MetricPattern4[StoredF32] = MetricPattern4(client, f'{base_path}_price_1m_volatility') self.price_1w_volatility: MetricPattern4[StoredF32] = MetricPattern4(client, f'{base_path}_price_1w_volatility') self.price_1y_volatility: MetricPattern4[StoredF32] = MetricPattern4(client, f'{base_path}_price_1y_volatility') - self.sharpe_1m: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_sharpe_1m') - self.sharpe_1w: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_sharpe_1w') - self.sharpe_1y: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_sharpe_1y') - self.sortino_1m: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_sortino_1m') - self.sortino_1w: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_sortino_1w') - self.sortino_1y: MetricPattern7[StoredF32] = MetricPattern7(client, f'{base_path}_sortino_1y') + self.sharpe_1m: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_sharpe_1m') + self.sharpe_1w: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_sharpe_1w') + self.sharpe_1y: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_sharpe_1y') + self.sortino_1m: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_sortino_1m') + self.sortino_1w: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_sortino_1w') + self.sortino_1y: MetricPattern6[StoredF32] = MetricPattern6(client, f'{base_path}_sortino_1y') class CatalogTree_Outputs: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): self.count: CatalogTree_Outputs_Count = CatalogTree_Outputs_Count(client, f'{base_path}_count') - self.first_txoutindex: MetricPattern12[TxOutIndex] = MetricPattern12(client, f'{base_path}_first_txoutindex') - self.outputtype: MetricPattern16[OutputType] = MetricPattern16(client, f'{base_path}_outputtype') + self.first_txoutindex: MetricPattern11[TxOutIndex] = MetricPattern11(client, f'{base_path}_first_txoutindex') + self.outputtype: MetricPattern15[OutputType] = MetricPattern15(client, f'{base_path}_outputtype') self.spent: CatalogTree_Outputs_Spent = CatalogTree_Outputs_Spent(client, f'{base_path}_spent') - self.txindex: MetricPattern16[TxIndex] = MetricPattern16(client, f'{base_path}_txindex') - self.typeindex: MetricPattern16[TypeIndex] = MetricPattern16(client, f'{base_path}_typeindex') - self.value: MetricPattern16[Sats] = MetricPattern16(client, f'{base_path}_value') + self.txindex: MetricPattern15[TxIndex] = MetricPattern15(client, f'{base_path}_txindex') + self.typeindex: MetricPattern15[TypeIndex] = MetricPattern15(client, f'{base_path}_typeindex') + self.value: MetricPattern15[Sats] = MetricPattern15(client, f'{base_path}_value') class CatalogTree_Outputs_Count: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): self.total_count: SizePattern[StoredU64] = SizePattern(client, 'output_count') - self.utxo_count: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'exact_utxo_count') + self.utxo_count: FullnessPattern[StoredU64] = FullnessPattern(client, 'exact_utxo_count') class CatalogTree_Outputs_Spent: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.txinindex: MetricPattern16[TxInIndex] = MetricPattern16(client, f'{base_path}_txinindex') + self.txinindex: MetricPattern15[TxInIndex] = MetricPattern15(client, f'{base_path}_txinindex') class CatalogTree_Pools: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.pool: MetricPattern12[PoolSlug] = MetricPattern12(client, f'{base_path}_pool') + self.height_to_pool: MetricPattern11[PoolSlug] = MetricPattern11(client, f'{base_path}_height_to_pool') self.vecs: CatalogTree_Pools_Vecs = CatalogTree_Pools_Vecs(client, f'{base_path}_vecs') class CatalogTree_Pools_Vecs: @@ -3607,65 +3490,51 @@ class CatalogTree_Positions: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.block_position: MetricPattern12[BlkPosition] = MetricPattern12(client, f'{base_path}_block_position') - self.tx_position: MetricPattern28[BlkPosition] = MetricPattern28(client, f'{base_path}_tx_position') + self.block_position: MetricPattern11[BlkPosition] = MetricPattern11(client, f'{base_path}_block_position') + self.tx_position: MetricPattern27[BlkPosition] = MetricPattern27(client, f'{base_path}_tx_position') class CatalogTree_Price: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.cents: CatalogTree_Price_Cents = CatalogTree_Price_Cents(client, f'{base_path}_cents') - self.sats: SatsPattern = SatsPattern(client, 'price') - self.usd: SatsPattern = SatsPattern(client, 'price') - -class CatalogTree_Price_Cents: - """Catalog tree node.""" - - def __init__(self, client: BrkClientBase, base_path: str = ''): - self.ohlc: MetricPattern6[OHLCCents] = MetricPattern6(client, f'{base_path}_ohlc') - self.split: CatalogTree_Price_Cents_Split = CatalogTree_Price_Cents_Split(client, f'{base_path}_split') - -class CatalogTree_Price_Cents_Split: - """Catalog tree node.""" - - def __init__(self, client: BrkClientBase, base_path: str = ''): - self.dateindex: DateindexPattern2 = DateindexPattern2(client, 'price') - self.height: DateindexPattern2 = DateindexPattern2(client, 'price') + self.cents: CentsPattern[OHLCCents] = CentsPattern(client, 'cents') + self.sats: CentsPattern[OHLCSats] = CentsPattern(client, 'price') + self.usd: CentsPattern[OHLCDollars] = CentsPattern(client, 'price') class CatalogTree_Scripts: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): self.count: CatalogTree_Scripts_Count = CatalogTree_Scripts_Count(client, f'{base_path}_count') - self.empty_to_txindex: MetricPattern10[TxIndex] = MetricPattern10(client, f'{base_path}_empty_to_txindex') - self.first_emptyoutputindex: MetricPattern12[EmptyOutputIndex] = MetricPattern12(client, f'{base_path}_first_emptyoutputindex') - self.first_opreturnindex: MetricPattern12[OpReturnIndex] = MetricPattern12(client, f'{base_path}_first_opreturnindex') - self.first_p2msoutputindex: MetricPattern12[P2MSOutputIndex] = MetricPattern12(client, f'{base_path}_first_p2msoutputindex') - self.first_unknownoutputindex: MetricPattern12[UnknownOutputIndex] = MetricPattern12(client, f'{base_path}_first_unknownoutputindex') - self.opreturn_to_txindex: MetricPattern15[TxIndex] = MetricPattern15(client, f'{base_path}_opreturn_to_txindex') - self.p2ms_to_txindex: MetricPattern18[TxIndex] = MetricPattern18(client, f'{base_path}_p2ms_to_txindex') - self.unknown_to_txindex: MetricPattern29[TxIndex] = MetricPattern29(client, f'{base_path}_unknown_to_txindex') + self.empty_to_txindex: MetricPattern9[TxIndex] = MetricPattern9(client, f'{base_path}_empty_to_txindex') + self.first_emptyoutputindex: MetricPattern11[EmptyOutputIndex] = MetricPattern11(client, f'{base_path}_first_emptyoutputindex') + self.first_opreturnindex: MetricPattern11[OpReturnIndex] = MetricPattern11(client, f'{base_path}_first_opreturnindex') + self.first_p2msoutputindex: MetricPattern11[P2MSOutputIndex] = MetricPattern11(client, f'{base_path}_first_p2msoutputindex') + self.first_unknownoutputindex: MetricPattern11[UnknownOutputIndex] = MetricPattern11(client, f'{base_path}_first_unknownoutputindex') + self.opreturn_to_txindex: MetricPattern14[TxIndex] = MetricPattern14(client, f'{base_path}_opreturn_to_txindex') + self.p2ms_to_txindex: MetricPattern17[TxIndex] = MetricPattern17(client, f'{base_path}_p2ms_to_txindex') + self.unknown_to_txindex: MetricPattern28[TxIndex] = MetricPattern28(client, f'{base_path}_unknown_to_txindex') self.value: CatalogTree_Scripts_Value = CatalogTree_Scripts_Value(client, f'{base_path}_value') class CatalogTree_Scripts_Count: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.emptyoutput: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'emptyoutput_count') - self.opreturn: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'opreturn_count') - self.p2a: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2a_count') - self.p2ms: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2ms_count') - self.p2pk33: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2pk33_count') - self.p2pk65: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2pk65_count') - self.p2pkh: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2pkh_count') - self.p2sh: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2sh_count') - self.p2tr: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2tr_count') - self.p2wpkh: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2wpkh_count') - self.p2wsh: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'p2wsh_count') - self.segwit: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'segwit_count') + self.emptyoutput: FullnessPattern[StoredU64] = FullnessPattern(client, 'emptyoutput_count') + self.opreturn: FullnessPattern[StoredU64] = FullnessPattern(client, 'opreturn_count') + self.p2a: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2a_count') + self.p2ms: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2ms_count') + self.p2pk33: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2pk33_count') + self.p2pk65: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2pk65_count') + self.p2pkh: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2pkh_count') + self.p2sh: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2sh_count') + self.p2tr: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2tr_count') + self.p2wpkh: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2wpkh_count') + self.p2wsh: FullnessPattern[StoredU64] = FullnessPattern(client, 'p2wsh_count') + self.segwit: FullnessPattern[StoredU64] = FullnessPattern(client, 'segwit_count') self.segwit_adoption: SegwitAdoptionPattern = SegwitAdoptionPattern(client, 'segwit_adoption') self.taproot_adoption: SegwitAdoptionPattern = SegwitAdoptionPattern(client, 'taproot_adoption') - self.unknownoutput: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'unknownoutput_count') + self.unknownoutput: FullnessPattern[StoredU64] = FullnessPattern(client, 'unknownoutput_count') class CatalogTree_Scripts_Value: """Catalog tree node.""" @@ -3701,19 +3570,19 @@ class CatalogTree_Transactions: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.base_size: MetricPattern28[StoredU32] = MetricPattern28(client, f'{base_path}_base_size') + self.base_size: MetricPattern27[StoredU32] = MetricPattern27(client, f'{base_path}_base_size') self.count: CatalogTree_Transactions_Count = CatalogTree_Transactions_Count(client, f'{base_path}_count') self.fees: CatalogTree_Transactions_Fees = CatalogTree_Transactions_Fees(client, f'{base_path}_fees') - self.first_txindex: MetricPattern12[TxIndex] = MetricPattern12(client, f'{base_path}_first_txindex') - self.first_txinindex: MetricPattern28[TxInIndex] = MetricPattern28(client, f'{base_path}_first_txinindex') - self.first_txoutindex: MetricPattern28[TxOutIndex] = MetricPattern28(client, f'{base_path}_first_txoutindex') - self.height: MetricPattern28[Height] = MetricPattern28(client, f'{base_path}_height') - self.is_explicitly_rbf: MetricPattern28[StoredBool] = MetricPattern28(client, f'{base_path}_is_explicitly_rbf') - self.rawlocktime: MetricPattern28[RawLockTime] = MetricPattern28(client, f'{base_path}_rawlocktime') + self.first_txindex: MetricPattern11[TxIndex] = MetricPattern11(client, f'{base_path}_first_txindex') + self.first_txinindex: MetricPattern27[TxInIndex] = MetricPattern27(client, f'{base_path}_first_txinindex') + self.first_txoutindex: MetricPattern27[TxOutIndex] = MetricPattern27(client, f'{base_path}_first_txoutindex') + self.height: MetricPattern27[Height] = MetricPattern27(client, f'{base_path}_height') + self.is_explicitly_rbf: MetricPattern27[StoredBool] = MetricPattern27(client, f'{base_path}_is_explicitly_rbf') + self.rawlocktime: MetricPattern27[RawLockTime] = MetricPattern27(client, f'{base_path}_rawlocktime') self.size: CatalogTree_Transactions_Size = CatalogTree_Transactions_Size(client, f'{base_path}_size') - self.total_size: MetricPattern28[StoredU32] = MetricPattern28(client, f'{base_path}_total_size') - self.txid: MetricPattern28[Txid] = MetricPattern28(client, f'{base_path}_txid') - self.txversion: MetricPattern28[TxVersion] = MetricPattern28(client, f'{base_path}_txversion') + self.total_size: MetricPattern27[StoredU32] = MetricPattern27(client, f'{base_path}_total_size') + self.txid: MetricPattern27[Txid] = MetricPattern27(client, f'{base_path}_txid') + self.txversion: MetricPattern27[TxVersion] = MetricPattern27(client, f'{base_path}_txversion') self.versions: CatalogTree_Transactions_Versions = CatalogTree_Transactions_Versions(client, f'{base_path}_versions') self.volume: CatalogTree_Transactions_Volume = CatalogTree_Transactions_Volume(client, f'{base_path}_volume') @@ -3721,8 +3590,8 @@ class CatalogTree_Transactions_Count: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): - self.is_coinbase: MetricPattern28[StoredBool] = MetricPattern28(client, f'{base_path}_is_coinbase') - self.tx_count: BitcoinPattern[StoredU64] = BitcoinPattern(client, 'tx_count') + self.is_coinbase: MetricPattern27[StoredBool] = MetricPattern27(client, f'{base_path}_is_coinbase') + self.tx_count: FullnessPattern[StoredU64] = FullnessPattern(client, 'tx_count') class CatalogTree_Transactions_Fees: """Catalog tree node.""" @@ -3730,17 +3599,33 @@ class CatalogTree_Transactions_Fees: def __init__(self, client: BrkClientBase, base_path: str = ''): self.fee: CatalogTree_Transactions_Fees_Fee = CatalogTree_Transactions_Fees_Fee(client, f'{base_path}_fee') self.fee_rate: FeeRatePattern[FeeRate] = FeeRatePattern(client, 'fee_rate') - self.input_value: MetricPattern28[Sats] = MetricPattern28(client, f'{base_path}_input_value') - self.output_value: MetricPattern28[Sats] = MetricPattern28(client, f'{base_path}_output_value') + self.input_value: MetricPattern27[Sats] = MetricPattern27(client, f'{base_path}_input_value') + self.output_value: MetricPattern27[Sats] = MetricPattern27(client, f'{base_path}_output_value') class CatalogTree_Transactions_Fees_Fee: """Catalog tree node.""" def __init__(self, client: BrkClientBase, base_path: str = ''): self.bitcoin: SizePattern[Bitcoin] = SizePattern(client, 'fee_btc') - self.dollars: SizePattern[Dollars] = SizePattern(client, 'fee_usd') + self.dollars: CatalogTree_Transactions_Fees_Fee_Dollars = CatalogTree_Transactions_Fees_Fee_Dollars(client, f'{base_path}_dollars') self.sats: SizePattern[Sats] = SizePattern(client, 'fee') - self.txindex: MetricPattern28[Sats] = MetricPattern28(client, f'{base_path}_txindex') + self.txindex: MetricPattern27[Sats] = MetricPattern27(client, f'{base_path}_txindex') + +class CatalogTree_Transactions_Fees_Fee_Dollars: + """Catalog tree node.""" + + def __init__(self, client: BrkClientBase, base_path: str = ''): + self.average: MetricPattern1[Dollars] = MetricPattern1(client, f'{base_path}_average') + self.cumulative: MetricPattern2[Dollars] = MetricPattern2(client, f'{base_path}_cumulative') + self.height_cumulative: MetricPattern11[Dollars] = MetricPattern11(client, f'{base_path}_height_cumulative') + self.max: MetricPattern1[Dollars] = MetricPattern1(client, f'{base_path}_max') + self.median: MetricPattern11[Dollars] = MetricPattern11(client, f'{base_path}_median') + self.min: MetricPattern1[Dollars] = MetricPattern1(client, f'{base_path}_min') + self.pct10: MetricPattern11[Dollars] = MetricPattern11(client, f'{base_path}_pct10') + self.pct25: MetricPattern11[Dollars] = MetricPattern11(client, f'{base_path}_pct25') + self.pct75: MetricPattern11[Dollars] = MetricPattern11(client, f'{base_path}_pct75') + self.pct90: MetricPattern11[Dollars] = MetricPattern11(client, f'{base_path}_pct90') + self.sum: MetricPattern1[Dollars] = MetricPattern1(client, f'{base_path}_sum') class CatalogTree_Transactions_Size: """Catalog tree node.""" diff --git a/websites/bitview/index.html b/websites/bitview/index.html index 0e5df449c..16b3be0d2 100644 --- a/websites/bitview/index.html +++ b/websites/bitview/index.html @@ -1560,37 +1560,37 @@ - - + + - + - + - - + + - + - - + + - + - + @@ -1600,10 +1600,10 @@ - + - + @@ -1630,37 +1630,37 @@ "imports": { "/scripts/chart/index.js": "/scripts/chart/index.02f627a6.js", "/scripts/chart/oklch.js": "/scripts/chart/oklch.21450255.js", - "/scripts/entry.js": "/scripts/entry.15f91516.js", - "/scripts/lazy.js": "/scripts/lazy.cdb73318.js", + "/scripts/entry.js": "/scripts/entry.10db80a8.js", + "/scripts/lazy.js": "/scripts/lazy.1ae52534.js", "/scripts/main.js": "/scripts/main.22a5bd79.js", - "/scripts/modules/brk-client/index.js": "/scripts/modules/brk-client/index.84ec1604.js", + "/scripts/modules/brk-client/index.js": "/scripts/modules/brk-client/index.922b14c3.js", "/scripts/modules/lean-qr/2.6.1/index.mjs": "/scripts/modules/lean-qr/2.6.1/index.09195c13.mjs", "/scripts/modules/leeoniya-ufuzzy/1.0.19/dist/uFuzzy.mjs": "/scripts/modules/leeoniya-ufuzzy/1.0.19/dist/uFuzzy.803b7fb0.mjs", "/scripts/modules/lightweight-charts/5.0.9/dist/lightweight-charts.standalone.production.mjs": "/scripts/modules/lightweight-charts/5.0.9/dist/lightweight-charts.standalone.production.1e264451.mjs", "/scripts/modules/lightweight-charts/5.1.0/dist/lightweight-charts.standalone.production.mjs": "/scripts/modules/lightweight-charts/5.1.0/dist/lightweight-charts.standalone.production.5c2a821a.mjs", - "/scripts/modules/modern-screenshot/4.6.6/dist/index.mjs": "/scripts/modules/modern-screenshot/4.6.6/dist/index.6340736f.mjs", + "/scripts/modules/modern-screenshot/4.6.6/dist/index.mjs": "/scripts/modules/modern-screenshot/4.6.6/dist/index.0f951334.mjs", "/scripts/modules/modern-screenshot/4.6.7/dist/index.js": "/scripts/modules/modern-screenshot/4.6.7/dist/index.070574d6.js", "/scripts/modules/modern-screenshot/4.6.7/dist/index.mjs": "/scripts/modules/modern-screenshot/4.6.7/dist/index.e9e389fe.mjs", "/scripts/modules/modern-screenshot/4.6.7/dist/worker.js": "/scripts/modules/modern-screenshot/4.6.7/dist/worker.1265d9cd.js", "/scripts/modules/solidjs-signals/0.6.3/dist/prod.js": "/scripts/modules/solidjs-signals/0.6.3/dist/prod.2f80e335.js", "/scripts/modules/solidjs-signals/0.8.5/dist/prod.js": "/scripts/modules/solidjs-signals/0.8.5/dist/prod.8ae56250.js", "/scripts/options/_partial_old.js": "/scripts/options/_partial_old.62bf3faa.js", - "/scripts/options/chain.js": "/scripts/options/chain.c1c621f8.js", - "/scripts/options/cohorts/address.js": "/scripts/options/cohorts/address.225a99f5.js", + "/scripts/options/chain.js": "/scripts/options/chain.4fe9edeb.js", + "/scripts/options/cohorts/address.js": "/scripts/options/cohorts/address.446eab82.js", "/scripts/options/cohorts/data.js": "/scripts/options/cohorts/data.92c2a350.js", "/scripts/options/cohorts/index.js": "/scripts/options/cohorts/index.47f11280.js", - "/scripts/options/cohorts/shared.js": "/scripts/options/cohorts/shared.d6cac56c.js", + "/scripts/options/cohorts/shared.js": "/scripts/options/cohorts/shared.028a47f5.js", "/scripts/options/cohorts/types.js": "/scripts/options/cohorts/types.1e23c94d.js", - "/scripts/options/cohorts/utxo.js": "/scripts/options/cohorts/utxo.531a3d0f.js", - "/scripts/options/cointime.js": "/scripts/options/cointime.520e3634.js", + "/scripts/options/cohorts/utxo.js": "/scripts/options/cohorts/utxo.90aa2b4f.js", + "/scripts/options/cointime.js": "/scripts/options/cointime.d859b72a.js", "/scripts/options/colors/cohorts.js": "/scripts/options/colors/cohorts.262d4551.js", "/scripts/options/colors/index.js": "/scripts/options/colors/index.a54dc83f.js", "/scripts/options/colors/misc.js": "/scripts/options/colors/misc.bee7dbee.js", - "/scripts/options/constants.js": "/scripts/options/constants.988e7f83.js", + "/scripts/options/constants.js": "/scripts/options/constants.190d9d82.js", "/scripts/options/context.js": "/scripts/options/context.bd3985fb.js", "/scripts/options/full.js": "/scripts/options/full.cbb89ca5.js", "/scripts/options/market/averages.js": "/scripts/options/market/averages.52ae3c62.js", - "/scripts/options/market/index.js": "/scripts/options/market/index.d5972147.js", + "/scripts/options/market/index.js": "/scripts/options/market/index.e6011fff.js", "/scripts/options/market/indicators/bands.js": "/scripts/options/market/indicators/bands.eb583383.js", "/scripts/options/market/indicators/index.js": "/scripts/options/market/indicators/index.70e9b3e4.js", "/scripts/options/market/indicators/momentum.js": "/scripts/options/market/indicators/momentum.8f20362c.js", @@ -1670,10 +1670,10 @@ "/scripts/options/market/performance.js": "/scripts/options/market/performance.f381010b.js", "/scripts/options/market/utils.js": "/scripts/options/market/utils.e3e058d8.js", "/scripts/options/partial.js": "/scripts/options/partial.1bfb5914.js", - "/scripts/options/series.js": "/scripts/options/series.d82ddec3.js", + "/scripts/options/series.js": "/scripts/options/series.3702ffc7.js", "/scripts/options/types.js": "/scripts/options/types.19186083.js", "/scripts/options/unused.js": "/scripts/options/unused.24a71427.js", - "/scripts/panes/chart/index.js": "/scripts/panes/chart/index.11dc206b.js", + "/scripts/panes/chart/index.js": "/scripts/panes/chart/index.3d231714.js", "/scripts/panes/chart/screenshot.js": "/scripts/panes/chart/screenshot.adc8da89.js", "/scripts/panes/explorer.js": "/scripts/panes/explorer.91a5a9ae.js", "/scripts/panes/nav.js": "/scripts/panes/nav.0338dc4b.js", diff --git a/websites/bitview/scripts/chart/index.js b/websites/bitview/scripts/chart/index.js index 9b55f6411..25553c09f 100644 --- a/websites/bitview/scripts/chart/index.js +++ b/websites/bitview/scripts/chart/index.js @@ -397,7 +397,12 @@ function createChartElement({ const valuesResource = resources.useMetricEndpoint(valuesNode); _valuesResource = valuesResource; - series.url.set(() => `${brk.baseUrl}${valuesResource.path}`); + series.url.set(() => { + const base = brk.baseUrl.endsWith("/") + ? brk.baseUrl.slice(0, -1) + : brk.baseUrl; + return `${base}${valuesResource.path}`; + }); signals.createEffect(active, (active) => { if (active) { diff --git a/websites/bitview/scripts/entry.js b/websites/bitview/scripts/entry.js index 70e3db4d1..c504b4e5a 100644 --- a/websites/bitview/scripts/entry.js +++ b/websites/bitview/scripts/entry.js @@ -5,7 +5,7 @@ * * @import { Signal, Signals, Accessor } from "./signals.js"; * - * @import { BrkClient, CatalogTree_Computed_Distribution_UtxoCohorts as UtxoCohortTree, CatalogTree_Computed_Distribution_AddressCohorts as AddressCohortTree, CatalogTree_Computed_Distribution_UtxoCohorts_All as AllUtxoPattern, _10yTo12yPattern as MinAgePattern, _0satsPattern2 as UtxoAmountPattern, _0satsPattern as AddressAmountPattern, Ratio1ySdPattern, Dollars, Price111dSmaPattern as EmaRatioPattern, Index, BlockCountPattern, BitcoinPattern, BlockSizePattern, BlockIntervalPattern, CoinbasePattern, ActivePriceRatioPattern, _0satsPattern, UnclaimedRewardsPattern as ValuePattern, SentPattern as RewardPattern, Metric, MetricPattern, AnyMetricPattern, MetricEndpoint, MetricData, AnyMetricEndpoint, AnyMetricData, DollarsPattern, CountPattern2 } from "./modules/brk-client/index.js" + * @import { BrkClient, CatalogTree_Distribution_UtxoCohorts as UtxoCohortTree, CatalogTree_Distribution_AddressCohorts as AddressCohortTree, CatalogTree_Distribution_UtxoCohorts_All as AllUtxoPattern, _10yTo12yPattern as MinAgePattern, _0satsPattern2 as UtxoAmountPattern, _0satsPattern as AddressAmountPattern, Ratio1ySdPattern, Dollars, Price111dSmaPattern as EmaRatioPattern, Index, BlockCountPattern, SizePattern, FullnessPattern, FeeRatePattern, CoinbasePattern, ActivePriceRatioPattern, _0satsPattern, UnclaimedRewardsPattern as ValuePattern, Metric, MetricPattern, AnyMetricPattern, MetricEndpoint, MetricData, AnyMetricEndpoint, AnyMetricData, AddrCountPattern, CatalogTree_Blocks_Interval as IntervalPattern } from "./modules/brk-client/index.js" * * @import { Resources, MetricResource } from './resources.js' * @@ -55,7 +55,7 @@ * @typedef {{ name: string, title: string, color: Color, tree: PatternWithCostBasisPercentiles }} CohortWithCostBasisPercentiles * * Tree branch types - * @typedef {InstanceType["tree"]["computed"]["market"]} Market + * @typedef {InstanceType["tree"]["market"]} Market * @typedef {Market["movingAverage"]} MarketMovingAverage * @typedef {Market["dca"]} MarketDca * @@ -65,7 +65,3 @@ * Chartable index IDs (subset of IndexName that can be charted) * @typedef {"height" | "dateindex" | "weekindex" | "monthindex" | "quarterindex" | "semesterindex" | "yearindex" | "decadeindex"} ChartableIndex */ - -// DO NOT CHANGE, Exact format is expected in `brk_bundler` -// @ts-ignore -import("./main.js"); diff --git a/websites/bitview/scripts/lazy.js b/websites/bitview/scripts/lazy.js index 1c36e0468..d971e1fcc 100644 --- a/websites/bitview/scripts/lazy.js +++ b/websites/bitview/scripts/lazy.js @@ -3,7 +3,7 @@ const imports = { return import("./signals.js").then((d) => d.default); }, async leanQr() { - return import("./modules/lean-qr/2.6.0/index.mjs").then((d) => d); + return import("./modules/lean-qr/2.6.1/index.mjs").then((d) => d); }, async ufuzzy() { return import("./modules/leeoniya-ufuzzy/1.0.19/dist/uFuzzy.mjs").then( diff --git a/websites/bitview/scripts/options/chain.js b/websites/bitview/scripts/options/chain.js index 0398e04aa..8b39f0312 100644 --- a/websites/bitview/scripts/options/chain.js +++ b/websites/bitview/scripts/options/chain.js @@ -8,7 +8,19 @@ import { Unit } from "../utils/units.js"; * @returns {PartialOptionsGroup} */ export function createChainSection(ctx) { - const { colors, brk, s, createPriceLine } = ctx; + const { + colors, + brk, + s, + createPriceLine, + fromSizePattern, + fromFullnessPattern, + fromFeeRatePattern, + fromCoinbasePattern, + fromValuePattern, + fromBlockCountWithUnit, + fromIntervalPattern, + } = ctx; const { blocks, transactions, @@ -20,409 +32,6 @@ export function createChainSection(ctx) { supply, } = brk.tree; - /** - * Create sum/cumulative series from a BlockCountPattern - * @template T - * @param {BlockCountPattern} pattern - * @param {string} name - * @param {Color} [sumColor] - * @param {Color} [cumulativeColor] - * @param {Unit} unit - */ - const fromBlockCount = (pattern, name, unit, sumColor, cumulativeColor) => [ - s({ - metric: pattern.sum, - name: `${name} sum`, - color: sumColor, - unit, - }), - s({ - metric: pattern.cumulative, - name: `${name} cumulative`, - color: cumulativeColor ?? colors.blue, - unit, - defaultActive: false, - }), - ]; - - /** - * Create series from BlockSizePattern (has average, min, max, percentiles) - * @template T - * @param {BlockSizePattern} pattern - * @param {string} name - * @param {Unit} unit - */ - const fromBlockSize = (pattern, name, unit) => [ - s({ metric: pattern.average, name: `${name} avg`, unit }), - s({ - metric: pattern.sum, - name: `${name} sum`, - color: colors.blue, - unit, - defaultActive: false, - }), - s({ - metric: pattern.cumulative, - name: `${name} cumulative`, - color: colors.indigo, - unit, - defaultActive: false, - }), - s({ - metric: pattern.min, - name: `${name} min`, - color: colors.red, - unit, - defaultActive: false, - }), - s({ - metric: pattern.max, - name: `${name} max`, - color: colors.green, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct10, - name: `${name} pct10`, - color: colors.rose, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct25, - name: `${name} pct25`, - color: colors.pink, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.median, - name: `${name} median`, - color: colors.purple, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct75, - name: `${name} pct75`, - color: colors.violet, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct90, - name: `${name} pct90`, - color: colors.fuchsia, - unit, - defaultActive: false, - }), - ]; - - /** - * Create series from CountPattern2 (has distribution with percentiles, no height index on cumulative) - * @template T - * @param {CountPattern2} pattern - * @param {string} name - * @param {Unit} unit - */ - const fromCountPattern2 = (pattern, name, unit) => [ - s({ metric: pattern.average, name: `${name} Average`, unit }), - s({ - metric: pattern.sum, - name: `${name} sum`, - color: colors.blue, - unit, - defaultActive: false, - }), - s({ - metric: pattern.cumulative, - name: `${name} cumulative`, - color: colors.indigo, - unit, - defaultActive: false, - }), - s({ - metric: pattern.min, - name: `${name} min`, - color: colors.red, - unit, - defaultActive: false, - }), - s({ - metric: pattern.max, - name: `${name} max`, - color: colors.green, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct10, - name: `${name} pct10`, - color: colors.rose, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct25, - name: `${name} pct25`, - color: colors.pink, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.median, - name: `${name} median`, - color: colors.purple, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct75, - name: `${name} pct75`, - color: colors.violet, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct90, - name: `${name} pct90`, - color: colors.fuchsia, - unit, - defaultActive: false, - }), - ]; - - /** - * Create series from BlockIntervalPattern (has average, min, max, percentiles) - * @template T - * @param {BlockIntervalPattern} pattern - * @param {string} name - * @param {Unit} unit - */ - const fromBlockInterval = (pattern, name, unit) => [ - s({ metric: pattern.average, name: `${name} avg`, unit }), - s({ - metric: pattern.min, - name: `${name} min`, - color: colors.red, - unit, - defaultActive: false, - }), - s({ - metric: pattern.max, - name: `${name} max`, - color: colors.green, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct10, - name: `${name} pct10`, - color: colors.rose, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct25, - name: `${name} pct25`, - color: colors.pink, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.median, - name: `${name} median`, - color: colors.purple, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct75, - name: `${name} pct75`, - color: colors.violet, - unit, - defaultActive: false, - }), - s({ - metric: pattern.percentiles.pct90, - name: `${name} pct90`, - color: colors.fuchsia, - unit, - defaultActive: false, - }), - ]; - - /** - * Create series from DollarsPattern (has base, cumulative) - * @template T - * @param {DollarsPattern} pattern - * @param {string} name - * @param {Unit} unit - * @param {Color} [sumColor] - * @param {Color} [cumulativeColor] - */ - const fromBitcoin = (pattern, name, unit, sumColor, cumulativeColor) => [ - s({ metric: pattern.base, name: `${name}`, color: sumColor, unit }), - s({ - metric: pattern.cumulative, - name: `${name} cumulative`, - color: cumulativeColor ?? colors.blue, - unit, - defaultActive: false, - }), - ]; - - /** - * Create series from CoinbasePattern (has sats, bitcoin, dollars as BitcoinPattern) - * BitcoinPattern has .base and .cumulative (no .sum) - * @param {CoinbasePattern} pattern - * @param {string} name - * @param {Color} sumColor - * @param {Color} cumulativeColor - */ - const fromCoinbase = (pattern, name, sumColor, cumulativeColor) => [ - s({ - metric: pattern.sats.base, - name: `${name}`, - color: sumColor, - unit: Unit.sats, - }), - s({ - metric: pattern.sats.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.sats, - defaultActive: false, - }), - s({ - metric: pattern.bitcoin.base, - name: `${name}`, - color: sumColor, - unit: Unit.btc, - }), - s({ - metric: pattern.bitcoin.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.btc, - defaultActive: false, - }), - s({ - metric: pattern.dollars.base, - name: `${name}`, - color: sumColor, - unit: Unit.usd, - }), - s({ - metric: pattern.dollars.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.usd, - defaultActive: false, - }), - ]; - - /** - * Create series from ValuePattern (has sats, bitcoin, dollars as BlockCountPattern) - * BlockCountPattern has .base, .sum, and .cumulative - * @param {ValuePattern} pattern - * @param {string} name - * @param {Color} sumColor - * @param {Color} cumulativeColor - */ - const fromValuePattern = (pattern, name, sumColor, cumulativeColor) => [ - s({ - metric: pattern.sats.sum, - name: `${name}`, - color: sumColor, - unit: Unit.sats, - }), - s({ - metric: pattern.sats.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.sats, - defaultActive: false, - }), - s({ - metric: pattern.bitcoin.sum, - name: `${name}`, - color: sumColor, - unit: Unit.btc, - }), - s({ - metric: pattern.bitcoin.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.btc, - defaultActive: false, - }), - s({ - metric: pattern.dollars.sum, - name: `${name}`, - color: sumColor, - unit: Unit.usd, - }), - s({ - metric: pattern.dollars.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.usd, - defaultActive: false, - }), - ]; - - /** - * Create series from RewardPattern (has .base as Indexes2, plus bitcoin/dollars as BlockCountPattern, sats as SatsPattern) - * Note: SatsPattern only has cumulative and sum, so we use pattern.base for raw sats - * @param {RewardPattern} pattern - * @param {string} name - * @param {Color} sumColor - * @param {Color} cumulativeColor - */ - const fromRewardPattern = (pattern, name, sumColor, cumulativeColor) => [ - s({ - metric: pattern.base, - name: `${name}`, - color: sumColor, - unit: Unit.sats, - }), - s({ - metric: pattern.sats.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.sats, - defaultActive: false, - }), - s({ - metric: pattern.bitcoin.sum, - name: `${name}`, - color: sumColor, - unit: Unit.btc, - }), - s({ - metric: pattern.bitcoin.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.btc, - defaultActive: false, - }), - s({ - metric: pattern.dollarsSource, - name: `${name}`, - color: sumColor, - unit: Unit.usd, - }), - s({ - metric: pattern.dollars.cumulative, - name: `${name} cumulative`, - color: cumulativeColor, - unit: Unit.usd, - defaultActive: false, - }), - ]; - // Build pools tree dynamically const poolEntries = Object.entries(pools.vecs); const poolsTree = poolEntries.map(([key, pool]) => { @@ -503,19 +112,9 @@ export function createChainSection(ctx) { name: "Rewards", title: `Rewards collected by ${poolName}`, bottom: [ - ...fromValuePattern( - pool.coinbase, - "coinbase", - colors.orange, - colors.red, - ), - ...fromRewardPattern( - pool.subsidy, - "subsidy", - colors.lime, - colors.emerald, - ), - ...fromRewardPattern(pool.fee, "fee", colors.cyan, colors.indigo), + ...fromValuePattern(pool.coinbase, "coinbase", colors.orange, colors.red), + ...fromValuePattern(pool.subsidy, "subsidy", colors.lime, colors.emerald), + ...fromValuePattern(pool.fee, "fee", colors.cyan, colors.indigo), ], }, { @@ -544,7 +143,7 @@ export function createChainSection(ctx) { name: "Count", title: "Block Count", bottom: [ - ...fromBlockCount(blocks.count.blockCount, "Block", Unit.count), + ...fromBlockCountWithUnit(blocks.count.blockCount, "Block", Unit.count), s({ metric: blocks.count.blockCountTarget, name: "Target", @@ -579,16 +178,7 @@ export function createChainSection(ctx) { name: "Interval", title: "Block Interval", bottom: [ - s({ - metric: blocks.interval.interval, - name: "Interval", - unit: Unit.secs, - }), - ...fromBlockInterval( - blocks.interval.blockInterval, - "Interval", - Unit.secs, - ), + ...fromIntervalPattern(blocks.interval, "Interval", Unit.secs), createPriceLine({ unit: Unit.secs, name: "Target", number: 600 }), ], }, @@ -596,19 +186,9 @@ export function createChainSection(ctx) { name: "Size", title: "Block Size", bottom: [ - s({ - metric: blocks.size.vbytes, - name: "vbytes raw", - unit: Unit.vb, - }), - s({ - metric: indexed.block.weight, - name: "weight raw", - unit: Unit.wu, - }), - ...fromBlockSize(blocks.size.blockSize, "size", Unit.bytes), - ...fromBlockSize(blocks.weight.blockWeight, "weight", Unit.wu), - ...fromBlockSize(blocks.size.blockVbytes, "vbytes", Unit.vb), + ...fromSizePattern(blocks.size, "Size", Unit.bytes), + ...fromFullnessPattern(blocks.vbytes, "Vbytes", Unit.vb), + ...fromFullnessPattern(blocks.weight, "Weight", Unit.wu), ], }, ], @@ -621,7 +201,7 @@ export function createChainSection(ctx) { { name: "Count", title: "Transaction Count", - bottom: fromBitcoin( + bottom: fromFullnessPattern( transactions.count.txCount, "Count", Unit.count, @@ -632,7 +212,7 @@ export function createChainSection(ctx) { title: "Transaction Volume", bottom: [ s({ - metric: transactions.volume.sentSum.sats.sum, + metric: transactions.volume.sentSum.sats, name: "Sent", unit: Unit.sats, }), @@ -647,21 +227,21 @@ export function createChainSection(ctx) { unit: Unit.usd, }), s({ - metric: transactions.volume.annualizedVolume, + metric: transactions.volume.annualizedVolume.sats, name: "annualized", color: colors.red, unit: Unit.sats, defaultActive: false, }), s({ - metric: transactions.volume.annualizedVolumeBtc, + metric: transactions.volume.annualizedVolume.bitcoin, name: "annualized", color: colors.red, unit: Unit.btc, defaultActive: false, }), s({ - metric: transactions.volume.annualizedVolumeUsd, + metric: transactions.volume.annualizedVolume.dollars, name: "annualized", color: colors.lime, unit: Unit.usd, @@ -673,35 +253,17 @@ export function createChainSection(ctx) { name: "Size", title: "Transaction Size", bottom: [ - ...fromBlockInterval(transactions.size.weight, "weight", Unit.wu), - ...fromBlockInterval(transactions.size.vsize, "vsize", Unit.vb), + ...fromFeeRatePattern(transactions.size.weight, "weight", Unit.wu), + ...fromFeeRatePattern(transactions.size.vsize, "vsize", Unit.vb), ], }, { name: "Versions", title: "Transaction Versions", bottom: [ - ...fromBlockCount( - transactions.versions.v1, - "v1", - Unit.count, - colors.orange, - colors.red, - ), - ...fromBlockCount( - transactions.versions.v2, - "v2", - Unit.count, - colors.cyan, - colors.blue, - ), - ...fromBlockCount( - transactions.versions.v3, - "v3", - Unit.count, - colors.lime, - colors.green, - ), + ...fromBlockCountWithUnit(transactions.versions.v1, "v1", Unit.count, colors.orange, colors.red), + ...fromBlockCountWithUnit(transactions.versions.v2, "v2", Unit.count, colors.cyan, colors.blue), + ...fromBlockCountWithUnit(transactions.versions.v3, "v3", Unit.count, colors.lime, colors.green), ], }, { @@ -742,7 +304,7 @@ export function createChainSection(ctx) { { name: "Count", title: "Transaction Input Count", - bottom: [...fromCountPattern2(inputs.count, "Input", Unit.count)], + bottom: [...fromSizePattern(inputs.count, "Input", Unit.count)], }, { name: "Speed", @@ -765,7 +327,13 @@ export function createChainSection(ctx) { { name: "Count", title: "Transaction Output Count", - bottom: [...fromCountPattern2(outputs.count, "Output", Unit.count)], + bottom: [ + ...fromSizePattern( + outputs.count.totalCount, + "Output", + Unit.count, + ), + ], }, { name: "Speed", @@ -781,23 +349,13 @@ export function createChainSection(ctx) { ], }, - // UTXO { name: "UTXO", tree: [ { name: "Count", title: "UTXO Count", - bottom: [ - s({ - metric: mergeMetricPatterns( - outputs.count.utxoCount.base, - outputs.count.utxoCount.sum, - ), - name: "Count", - unit: Unit.count, - }), - ], + bottom: fromFullnessPattern(outputs.count.utxoCount, "Count", Unit.count), }, ], }, @@ -806,12 +364,7 @@ export function createChainSection(ctx) { { name: "Coinbase", title: "Coinbase Rewards", - bottom: fromCoinbase( - blocks.rewards.coinbase, - "Coinbase", - colors.orange, - colors.red, - ), + bottom: fromCoinbasePattern(blocks.rewards.coinbase, "Coinbase"), }, // Subsidy @@ -819,12 +372,7 @@ export function createChainSection(ctx) { name: "Subsidy", title: "Block Subsidy", bottom: [ - ...fromCoinbase( - blocks.rewards.subsidy, - "Subsidy", - colors.lime, - colors.emerald, - ), + ...fromCoinbasePattern(blocks.rewards.subsidy, "Subsidy"), s({ metric: blocks.rewards.subsidyDominance, name: "Dominance", @@ -893,8 +441,9 @@ export function createChainSection(ctx) { title: "Fee Rate", bottom: [ s({ - metric: transactions.fees.feeRate.base, - name: "Rate", + metric: transactions.fees.feeRate.median, + name: "Median", + color: colors.purple, unit: Unit.feeRate, }), s({ @@ -902,12 +451,7 @@ export function createChainSection(ctx) { name: "Average", color: colors.blue, unit: Unit.feeRate, - }), - s({ - metric: transactions.fees.feeRate.percentiles.median, - name: "Median", - color: colors.purple, - unit: Unit.feeRate, + defaultActive: false, }), s({ metric: transactions.fees.feeRate.min, @@ -924,28 +468,28 @@ export function createChainSection(ctx) { defaultActive: false, }), s({ - metric: transactions.fees.feeRate.percentiles.pct10, + metric: transactions.fees.feeRate.pct10, name: "pct10", color: colors.rose, unit: Unit.feeRate, defaultActive: false, }), s({ - metric: transactions.fees.feeRate.percentiles.pct25, + metric: transactions.fees.feeRate.pct25, name: "pct25", color: colors.pink, unit: Unit.feeRate, defaultActive: false, }), s({ - metric: transactions.fees.feeRate.percentiles.pct75, + metric: transactions.fees.feeRate.pct75, name: "pct75", color: colors.violet, unit: Unit.feeRate, defaultActive: false, }), s({ - metric: transactions.fees.feeRate.percentiles.pct90, + metric: transactions.fees.feeRate.pct90, name: "pct90", color: colors.fuchsia, unit: Unit.feeRate, @@ -1004,22 +548,19 @@ export function createChainSection(ctx) { title: "Network Difficulty", bottom: [ s({ - metric: blocks.mining.difficulty, + metric: blocks.difficulty.raw, name: "Difficulty", unit: Unit.difficulty, }), s({ - metric: mergeMetricPatterns( - blocks.mining.difficultyAdjustment.base, - blocks.mining.difficultyAdjustment.rest, - ), + metric: blocks.difficulty.adjustment, name: "Adjustment", color: colors.orange, unit: Unit.percentage, defaultActive: false, }), s({ - metric: blocks.mining.difficultyAsHash, + metric: blocks.difficulty.asHash, name: "As hash", color: colors.default, unit: Unit.hashRate, @@ -1027,14 +568,14 @@ export function createChainSection(ctx) { options: { lineStyle: 1 }, }), s({ - metric: blocks.difficulty.blocksBeforeNextDifficultyAdjustment, + metric: blocks.difficulty.blocksBeforeNextAdjustment, name: "Blocks until adj.", color: colors.indigo, unit: Unit.blocks, defaultActive: false, }), s({ - metric: blocks.difficulty.daysBeforeNextDifficultyAdjustment, + metric: blocks.difficulty.daysBeforeNextAdjustment, name: "Days until adj.", color: colors.purple, unit: Unit.days, @@ -1134,7 +675,7 @@ export function createChainSection(ctx) { unit: Unit.days, }), s({ - metric: blocks.halving.halvingepoch, + metric: blocks.halving.epoch, name: "Halving epoch", color: colors.purple, unit: Unit.epoch, @@ -1173,8 +714,8 @@ export function createChainSection(ctx) { { name: "Outputs", title: "OP_RETURN Outputs", - bottom: fromBitcoin( - scripts.count.opreturnCount, + bottom: fromFullnessPattern( + scripts.count.opreturn, "Count", Unit.count, ), @@ -1190,10 +731,7 @@ export function createChainSection(ctx) { title: "Inflation Rate", bottom: [ s({ - metric: mergeMetricPatterns( - supply.inflation.indexes.dateindex, - supply.inflation.indexes.rest, - ), + metric: supply.inflation, name: "Rate", unit: Unit.percentage, }), diff --git a/websites/bitview/scripts/options/cohorts/address.js b/websites/bitview/scripts/options/cohorts/address.js index 35bedb585..521ed6ec8 100644 --- a/websites/bitview/scripts/options/cohorts/address.js +++ b/websites/bitview/scripts/options/cohorts/address.js @@ -322,7 +322,7 @@ function createCostBasisSection(ctx, list, useGroupName, title) { title: `Min Cost Basis ${title}`, top: list.map(({ color, name, tree }) => s({ - metric: tree.costBasis.minCostBasis, + metric: tree.costBasis.min, name: useGroupName ? name : "Min", color, unit: Unit.usd, @@ -334,7 +334,7 @@ function createCostBasisSection(ctx, list, useGroupName, title) { title: `Max Cost Basis ${title}`, top: list.map(({ color, name, tree }) => s({ - metric: tree.costBasis.maxCostBasis, + metric: tree.costBasis.max, name: useGroupName ? name : "Max", color, unit: Unit.usd, @@ -355,7 +355,7 @@ function createCostBasisSection(ctx, list, useGroupName, title) { * @returns {PartialOptionsTree} */ function createActivitySection(ctx, list, useGroupName, title) { - const { s, brk } = ctx; + const { s } = ctx; return [ { diff --git a/websites/bitview/scripts/options/cohorts/shared.js b/websites/bitview/scripts/options/cohorts/shared.js index 15cc6bdf2..0c610d362 100644 --- a/websites/bitview/scripts/options/cohorts/shared.js +++ b/websites/bitview/scripts/options/cohorts/shared.js @@ -14,19 +14,19 @@ export function createSingleSupplySeries(ctx, cohort) { return [ s({ - metric: tree.supply.supply.sats, + metric: tree.supply.total.sats, name: "Supply", color: colors.default, unit: Unit.sats, }), s({ - metric: tree.supply.supply.bitcoin, + metric: tree.supply.total.bitcoin, name: "Supply", color: colors.default, unit: Unit.btc, }), s({ - metric: tree.supply.supply.dollars, + metric: tree.supply.total.dollars, name: "Supply", color: colors.default, unit: Unit.usd, @@ -78,21 +78,21 @@ export function createSingleSupplySeries(ctx, cohort) { unit: Unit.usd, }), s({ - metric: tree.supply.supplyHalf.sats, + metric: tree.supply.halved.sats, name: "half", color: colors.gray, unit: Unit.sats, options: { lineStyle: 4 }, }), s({ - metric: tree.supply.supplyHalf.bitcoin, + metric: tree.supply.halved.bitcoin, name: "half", color: colors.gray, unit: Unit.btc, options: { lineStyle: 4 }, }), s({ - metric: tree.supply.supplyHalf.dollars, + metric: tree.supply.halved.dollars, name: "half", color: colors.gray, unit: Unit.usd, @@ -147,9 +147,9 @@ export function createGroupedSupplyTotalSeries(ctx, list) { const constant100 = brk.tree.constants.constant100; return list.flatMap(({ color, name, tree }) => [ - s({ metric: tree.supply.supply.sats, name, color, unit: Unit.sats }), - s({ metric: tree.supply.supply.bitcoin, name, color, unit: Unit.btc }), - s({ metric: tree.supply.supply.dollars, name, color, unit: Unit.usd }), + s({ metric: tree.supply.total.sats, name, color, unit: Unit.sats }), + s({ metric: tree.supply.total.bitcoin, name, color, unit: Unit.btc }), + s({ metric: tree.supply.total.dollars, name, color, unit: Unit.usd }), "supplyRelToCirculatingSupply" in tree.relative ? s({ metric: tree.relative.supplyRelToCirculatingSupply, @@ -255,7 +255,7 @@ export function createUtxoCountSeries(ctx, list, useGroupName) { return list.flatMap(({ color, name, tree }) => [ s({ - metric: tree.supply.utxoCount, + metric: tree.outputs.utxoCount, name: useGroupName ? name : "Count", color, unit: Unit.count, @@ -351,13 +351,13 @@ export function createCostBasisMinMaxSeries(ctx, list, useGroupName) { return list.flatMap(({ color, name, tree }) => [ s({ - metric: tree.costBasis.minCostBasis, + metric: tree.costBasis.min, name: useGroupName ? `${name} min` : "Min", color, unit: Unit.usd, }), s({ - metric: tree.costBasis.maxCostBasis, + metric: tree.costBasis.max, name: useGroupName ? `${name} max` : "Max", color, unit: Unit.usd, diff --git a/websites/bitview/scripts/options/cohorts/utxo.js b/websites/bitview/scripts/options/cohorts/utxo.js index c7595dbe8..b17cffdf7 100644 --- a/websites/bitview/scripts/options/cohorts/utxo.js +++ b/websites/bitview/scripts/options/cohorts/utxo.js @@ -298,7 +298,7 @@ function createRealizedCapWithExtras(ctx, list, args, useGroupName) { * @returns {PartialOptionsTree} */ function createRealizedPnlSection(ctx, args, title) { - const { colors, s, brk } = ctx; + const { colors, s } = ctx; const { tree } = args; return [ @@ -307,19 +307,13 @@ function createRealizedPnlSection(ctx, args, title) { title: `Realized Profit And Loss ${title}`, bottom: [ s({ - metric: mergeMetricPatterns( - tree.realized.realizedProfit.base, - tree.realized.realizedProfit.sum, - ), + metric: tree.realized.realizedProfit.sum, name: "Profit", color: colors.green, unit: Unit.usd, }), s({ - metric: mergeMetricPatterns( - tree.realized.realizedLoss.base, - tree.realized.realizedLoss.sum, - ), + metric: tree.realized.realizedLoss.sum, name: "Loss", color: colors.red, defaultActive: false, @@ -437,7 +431,7 @@ function createCostBasisSectionWithPercentiles(ctx, list, useGroupName, title) { title: `Min Cost Basis ${title}`, top: list.map(({ color, name, tree }) => s({ - metric: tree.costBasis.minCostBasis, + metric: tree.costBasis.min, name: useGroupName ? name : "Min", color, unit: Unit.usd, @@ -449,7 +443,7 @@ function createCostBasisSectionWithPercentiles(ctx, list, useGroupName, title) { title: `Max Cost Basis ${title}`, top: list.map(({ color, name, tree }) => s({ - metric: tree.costBasis.maxCostBasis, + metric: tree.costBasis.max, name: useGroupName ? name : "Max", color, unit: Unit.usd, @@ -486,7 +480,7 @@ function createCostBasisSectionBasic(ctx, list, useGroupName, title) { title: `Min Cost Basis ${title}`, top: list.map(({ color, name, tree }) => s({ - metric: tree.costBasis.minCostBasis, + metric: tree.costBasis.min, name: useGroupName ? name : "Min", color, unit: Unit.usd, @@ -498,7 +492,7 @@ function createCostBasisSectionBasic(ctx, list, useGroupName, title) { title: `Max Cost Basis ${title}`, top: list.map(({ color, name, tree }) => s({ - metric: tree.costBasis.maxCostBasis, + metric: tree.costBasis.max, name: useGroupName ? name : "Max", color, unit: Unit.usd, @@ -519,7 +513,7 @@ function createCostBasisSectionBasic(ctx, list, useGroupName, title) { * @returns {PartialOptionsTree} */ function createActivitySection(ctx, list, useGroupName, title) { - const { s, brk } = ctx; + const { s } = ctx; return [ { @@ -530,10 +524,7 @@ function createActivitySection(ctx, list, useGroupName, title) { title: `Coinblocks Destroyed ${title}`, bottom: list.flatMap(({ color, name, tree }) => [ s({ - metric: mergeMetricPatterns( - tree.activity.coinblocksDestroyed.base, - tree.activity.coinblocksDestroyed.sum, - ), + metric: tree.activity.coinblocksDestroyed.sum, name: useGroupName ? name : "Coinblocks", color, unit: Unit.coinblocks, @@ -545,10 +536,7 @@ function createActivitySection(ctx, list, useGroupName, title) { title: `Coindays Destroyed ${title}`, bottom: list.flatMap(({ color, name, tree }) => [ s({ - metric: mergeMetricPatterns( - tree.activity.coindaysDestroyed.base, - tree.activity.coindaysDestroyed.sum, - ), + metric: tree.activity.coindaysDestroyed.sum, name: useGroupName ? name : "Coindays", color, unit: Unit.coindays, diff --git a/websites/bitview/scripts/options/cointime.js b/websites/bitview/scripts/options/cointime.js index 990c12af3..2601a381d 100644 --- a/websites/bitview/scripts/options/cointime.js +++ b/websites/bitview/scripts/options/cointime.js @@ -273,7 +273,7 @@ export function createCointimeSection(ctx) { title: "Compare Cointime Capitalizations", bottom: [ s({ - metric: supply.marketCap.height, + metric: supply.marketCap, name: "Market", color: colors.default, unit: Unit.usd, @@ -295,7 +295,7 @@ export function createCointimeSection(ctx) { bottom: [ s({ metric, name, color, unit: Unit.usd }), s({ - metric: supply.marketCap.height, + metric: supply.marketCap, name: "Market", color: colors.default, unit: Unit.usd, @@ -318,19 +318,19 @@ export function createCointimeSection(ctx) { bottom: [ // All supply (different pattern structure) s({ - metric: all.supply.supply.sats, + metric: all.supply.total.sats, name: "All", color: colors.orange, unit: Unit.sats, }), s({ - metric: all.supply.supply.bitcoin, + metric: all.supply.total.bitcoin, name: "All", color: colors.orange, unit: Unit.btc, }), s({ - metric: all.supply.supply.dollars, + metric: all.supply.total.dollars, name: "All", color: colors.orange, unit: Unit.usd, @@ -432,10 +432,7 @@ export function createCointimeSection(ctx) { title: "Cointime-Adjusted Inflation Rate", bottom: [ s({ - metric: mergeMetricPatterns( - supply.inflation.indexes.dateindex, - supply.inflation.indexes.rest, - ), + metric: supply.inflation, name: "Base", color: colors.orange, unit: Unit.percentage, @@ -454,7 +451,7 @@ export function createCointimeSection(ctx) { title: "Cointime-Adjusted Transactions Velocity", bottom: [ s({ - metric: supply.velocity.btc.dateindex, + metric: supply.velocity.btc, name: "BTC", color: colors.orange, unit: Unit.ratio, @@ -466,10 +463,7 @@ export function createCointimeSection(ctx) { unit: Unit.ratio, }), s({ - metric: mergeMetricPatterns( - supply.velocity.usd.dateindex, - supply.velocity.usd.rest, - ), + metric: supply.velocity.usd, name: "USD", color: colors.emerald, unit: Unit.ratio, diff --git a/websites/bitview/scripts/options/constants.js b/websites/bitview/scripts/options/constants.js index 93d5b5aa9..c344cbc6d 100644 --- a/websites/bitview/scripts/options/constants.js +++ b/websites/bitview/scripts/options/constants.js @@ -3,7 +3,7 @@ /** * Get constant pattern by number dynamically from tree * Examples: 0 → constant0, 38.2 → constant382, -1 → constantMinus1 - * @param {BrkClient["tree"]["computed"]["constants"]} constants + * @param {BrkClient["tree"]["constants"]} constants * @param {number} num * @returns {AnyMetricPattern} */ @@ -22,7 +22,7 @@ export function getConstant(constants, num) { /** * Create a price line series (horizontal reference line) * @param {Object} args - * @param {BrkClient["tree"]["computed"]["constants"]} args.constants + * @param {BrkClient["tree"]["constants"]} args.constants * @param {Colors} args.colors * @param {number} [args.number] * @param {string} [args.name] @@ -59,7 +59,7 @@ export function createPriceLine({ /** * Create multiple price lines from an array of numbers * @param {Object} args - * @param {BrkClient["tree"]["computed"]["constants"]} args.constants + * @param {BrkClient["tree"]["constants"]} args.constants * @param {Colors} args.colors * @param {number[]} args.numbers * @param {Unit} args.unit diff --git a/websites/bitview/scripts/options/context.js b/websites/bitview/scripts/options/context.js index b9e60cb93..a4a93c5c8 100644 --- a/websites/bitview/scripts/options/context.js +++ b/websites/bitview/scripts/options/context.js @@ -1,4 +1,16 @@ -import { s, fromBlockCount, fromBitcoin, fromBlockSize } from "./series.js"; +import { + s, + fromBlockCount, + fromBitcoin, + fromBlockSize, + fromSizePattern, + fromFullnessPattern, + fromFeeRatePattern, + fromCoinbasePattern, + fromValuePattern, + fromBlockCountWithUnit, + fromIntervalPattern, +} from "./series.js"; import { createPriceLine, createPriceLines, line } from "./constants.js"; /** @@ -23,6 +35,20 @@ export function createContext({ colors, brk }) { fromBitcoin(colors, pattern, title, color), fromBlockSize: (pattern, title, color) => fromBlockSize(colors, pattern, title, color), + fromSizePattern: (pattern, title, unit) => + fromSizePattern(colors, pattern, title, unit), + fromFullnessPattern: (pattern, title, unit) => + fromFullnessPattern(colors, pattern, title, unit), + fromFeeRatePattern: (pattern, title, unit) => + fromFeeRatePattern(colors, pattern, title, unit), + fromCoinbasePattern: (pattern, title) => + fromCoinbasePattern(colors, pattern, title), + fromValuePattern: (pattern, title, sumColor, cumulativeColor) => + fromValuePattern(colors, pattern, title, sumColor, cumulativeColor), + fromBlockCountWithUnit: (pattern, title, unit, sumColor, cumulativeColor) => + fromBlockCountWithUnit(colors, pattern, title, unit, sumColor, cumulativeColor), + fromIntervalPattern: (pattern, title, unit, color) => + fromIntervalPattern(colors, pattern, title, unit, color), createPriceLine: (args) => createPriceLine({ constants, colors, ...args }), createPriceLines: (args) => diff --git a/websites/bitview/scripts/options/market/index.js b/websites/bitview/scripts/options/market/index.js index 9e7fe9c5c..8e3264c2d 100644 --- a/websites/bitview/scripts/options/market/index.js +++ b/websites/bitview/scripts/options/market/index.js @@ -42,10 +42,7 @@ export function createMarketSection(ctx) { title: "Market Capitalization", bottom: [ s({ - metric: brk.mergeMetricPatterns( - supply.marketCap.height, - supply.marketCap.indexes, - ), + metric: supply.marketCap, name: "Capitalization", unit: Unit.usd, }), diff --git a/websites/bitview/scripts/options/series.js b/websites/bitview/scripts/options/series.js index c3418d903..eb60cdc48 100644 --- a/websites/bitview/scripts/options/series.js +++ b/websites/bitview/scripts/options/series.js @@ -1,5 +1,7 @@ /** Series helpers for creating chart series blueprints */ +import { Unit } from "../utils/units.js"; + /** * Create a single series from a tree accessor * @param {Object} args @@ -32,13 +34,7 @@ export function s({ metric, name, color, defaultActive, unit, options }) { */ export function fromBlockCount(colors, pattern, title, color) { return [ - { metric: pattern.base, title, color: color ?? colors.default }, - { - metric: pattern.sum, - title: `${title} (sum)`, - color: colors.red, - defaultActive: false, - }, + { metric: pattern.sum, title, color: color ?? colors.default }, { metric: pattern.cumulative, title: `${title} (cum.)`, @@ -49,9 +45,9 @@ export function fromBlockCount(colors, pattern, title, color) { } /** - * Create series from a DollarsPattern ({ base, sum, cumulative, average, min, max, percentiles.* }) + * Create series from a FullnessPattern ({ base, sum, cumulative, average, min, max, percentiles }) * @param {Colors} colors - * @param {DollarsPattern} pattern + * @param {FullnessPattern} pattern * @param {string} title * @param {Color} [color] * @returns {AnyFetchedSeriesBlueprint[]} @@ -85,31 +81,31 @@ export function fromBitcoin(colors, pattern, title, color) { defaultActive: false, }, { - metric: pattern.percentiles.median, + metric: pattern.median, title: "Median", color: colors.amber, defaultActive: false, }, { - metric: pattern.percentiles.pct75, + metric: pattern.pct75, title: "pct75", color: colors.red, defaultActive: false, }, { - metric: pattern.percentiles.pct25, + metric: pattern.pct25, title: "pct25", color: colors.yellow, defaultActive: false, }, { - metric: pattern.percentiles.pct90, + metric: pattern.pct90, title: "pct90", color: colors.rose, defaultActive: false, }, { - metric: pattern.percentiles.pct10, + metric: pattern.pct10, title: "pct10", color: colors.lime, defaultActive: false, @@ -118,9 +114,9 @@ export function fromBitcoin(colors, pattern, title, color) { } /** - * Create series from a BlockSizePattern ({ sum, cumulative, avg, min, max, distribution.percentiles.* }) + * Create series from a SizePattern ({ sum, cumulative, average, min, max, percentiles }) * @param {Colors} colors - * @param {BlockSizePattern} pattern + * @param {SizePattern} pattern * @param {string} title * @param {Color} [color] * @returns {AnyFetchedSeriesBlueprint[]} @@ -148,34 +144,377 @@ export function fromBlockSize(colors, pattern, title, color) { defaultActive: false, }, { - metric: pattern.distribution.percentiles.median, + metric: pattern.median, title: "Median", color: colors.amber, defaultActive: false, }, { - metric: pattern.distribution.percentiles.pct75, + metric: pattern.pct75, title: "pct75", color: colors.red, defaultActive: false, }, { - metric: pattern.distribution.percentiles.pct25, + metric: pattern.pct25, title: "pct25", color: colors.yellow, defaultActive: false, }, { - metric: pattern.distribution.percentiles.pct90, + metric: pattern.pct90, title: "pct90", color: colors.rose, defaultActive: false, }, { - metric: pattern.distribution.percentiles.pct10, + metric: pattern.pct10, title: "pct10", color: colors.lime, defaultActive: false, }, ]; } + +/** + * Create series from a SizePattern ({ average, sum, cumulative, min, max, percentiles }) + * @param {Colors} colors + * @param {SizePattern} pattern + * @param {string} title + * @param {Unit} unit + * @returns {AnyFetchedSeriesBlueprint[]} + */ +export function fromSizePattern(colors, pattern, title, unit) { + return [ + { metric: pattern.average, title: `${title} avg`, unit }, + { + metric: pattern.sum, + title: `${title} sum`, + color: colors.blue, + unit, + defaultActive: false, + }, + { + metric: pattern.cumulative, + title: `${title} cumulative`, + color: colors.indigo, + unit, + defaultActive: false, + }, + { + metric: pattern.min, + title: `${title} min`, + color: colors.red, + unit, + defaultActive: false, + }, + { + metric: pattern.max, + title: `${title} max`, + color: colors.green, + unit, + defaultActive: false, + }, + { + metric: pattern.pct10, + title: `${title} pct10`, + color: colors.rose, + unit, + defaultActive: false, + }, + { + metric: pattern.pct25, + title: `${title} pct25`, + color: colors.pink, + unit, + defaultActive: false, + }, + { + metric: pattern.median, + title: `${title} median`, + color: colors.purple, + unit, + defaultActive: false, + }, + { + metric: pattern.pct75, + title: `${title} pct75`, + color: colors.violet, + unit, + defaultActive: false, + }, + { + metric: pattern.pct90, + title: `${title} pct90`, + color: colors.fuchsia, + unit, + defaultActive: false, + }, + ]; +} + +/** + * Create series from a FullnessPattern ({ base, average, sum, cumulative, min, max, percentiles }) + * @param {Colors} colors + * @param {FullnessPattern} pattern + * @param {string} title + * @param {Unit} unit + * @returns {AnyFetchedSeriesBlueprint[]} + */ +export function fromFullnessPattern(colors, pattern, title, unit) { + return [ + { metric: pattern.base, title, unit }, + { + metric: pattern.average, + title: `${title} avg`, + color: colors.purple, + unit, + defaultActive: false, + }, + { + metric: pattern.sum, + title: `${title} sum`, + color: colors.blue, + unit, + defaultActive: false, + }, + { + metric: pattern.cumulative, + title: `${title} cumulative`, + color: colors.indigo, + unit, + defaultActive: false, + }, + { + metric: pattern.min, + title: `${title} min`, + color: colors.red, + unit, + defaultActive: false, + }, + { + metric: pattern.max, + title: `${title} max`, + color: colors.green, + unit, + defaultActive: false, + }, + { + metric: pattern.pct10, + title: `${title} pct10`, + color: colors.rose, + unit, + defaultActive: false, + }, + { + metric: pattern.pct25, + title: `${title} pct25`, + color: colors.pink, + unit, + defaultActive: false, + }, + { + metric: pattern.median, + title: `${title} median`, + color: colors.violet, + unit, + defaultActive: false, + }, + { + metric: pattern.pct75, + title: `${title} pct75`, + color: colors.fuchsia, + unit, + defaultActive: false, + }, + { + metric: pattern.pct90, + title: `${title} pct90`, + color: colors.amber, + unit, + defaultActive: false, + }, + ]; +} + +/** + * Create series from a FeeRatePattern ({ average, min, max, percentiles }) + * @param {Colors} colors + * @param {FeeRatePattern} pattern + * @param {string} title + * @param {Unit} unit + * @returns {AnyFetchedSeriesBlueprint[]} + */ +export function fromFeeRatePattern(colors, pattern, title, unit) { + return [ + { metric: pattern.average, title: `${title} avg`, unit }, + { + metric: pattern.min, + title: `${title} min`, + color: colors.red, + unit, + defaultActive: false, + }, + { + metric: pattern.max, + title: `${title} max`, + color: colors.green, + unit, + defaultActive: false, + }, + { + metric: pattern.pct10, + title: `${title} pct10`, + color: colors.rose, + unit, + defaultActive: false, + }, + { + metric: pattern.pct25, + title: `${title} pct25`, + color: colors.pink, + unit, + defaultActive: false, + }, + { + metric: pattern.median, + title: `${title} median`, + color: colors.purple, + unit, + defaultActive: false, + }, + { + metric: pattern.pct75, + title: `${title} pct75`, + color: colors.violet, + unit, + defaultActive: false, + }, + { + metric: pattern.pct90, + title: `${title} pct90`, + color: colors.fuchsia, + unit, + defaultActive: false, + }, + ]; +} + +/** + * Create series from a CoinbasePattern ({ sats, bitcoin, dollars } each as FullnessPattern) + * @param {Colors} colors + * @param {CoinbasePattern} pattern + * @param {string} title + * @returns {AnyFetchedSeriesBlueprint[]} + */ +export function fromCoinbasePattern(colors, pattern, title) { + return [ + ...fromFullnessPattern(colors, pattern.sats, title, Unit.sats), + ...fromFullnessPattern(colors, pattern.bitcoin, title, Unit.btc), + ...fromFullnessPattern(colors, pattern.dollars, title, Unit.usd), + ]; +} + +/** + * Create series from a ValuePattern ({ sats, bitcoin, dollars } each as BlockCountPattern with sum + cumulative) + * @param {Colors} colors + * @param {ValuePattern} pattern + * @param {string} title + * @param {Color} [sumColor] + * @param {Color} [cumulativeColor] + * @returns {AnyFetchedSeriesBlueprint[]} + */ +export function fromValuePattern(colors, pattern, title, sumColor, cumulativeColor) { + return [ + { + metric: pattern.sats.sum, + title, + color: sumColor, + unit: Unit.sats, + }, + { + metric: pattern.sats.cumulative, + title: `${title} cumulative`, + color: cumulativeColor ?? colors.blue, + unit: Unit.sats, + defaultActive: false, + }, + { + metric: pattern.bitcoin.sum, + title, + color: sumColor, + unit: Unit.btc, + }, + { + metric: pattern.bitcoin.cumulative, + title: `${title} cumulative`, + color: cumulativeColor ?? colors.blue, + unit: Unit.btc, + defaultActive: false, + }, + { + metric: pattern.dollars.sum, + title, + color: sumColor, + unit: Unit.usd, + }, + { + metric: pattern.dollars.cumulative, + title: `${title} cumulative`, + color: cumulativeColor ?? colors.blue, + unit: Unit.usd, + defaultActive: false, + }, + ]; +} + +/** + * Create sum/cumulative series from a BlockCountPattern with explicit unit and colors + * @param {Colors} colors + * @param {BlockCountPattern} pattern + * @param {string} title + * @param {Unit} unit + * @param {Color} [sumColor] + * @param {Color} [cumulativeColor] + * @returns {AnyFetchedSeriesBlueprint[]} + */ +export function fromBlockCountWithUnit(colors, pattern, title, unit, sumColor, cumulativeColor) { + return [ + { + metric: pattern.sum, + title: `${title} sum`, + color: sumColor, + unit, + }, + { + metric: pattern.cumulative, + title: `${title} cumulative`, + color: cumulativeColor ?? colors.blue, + unit, + defaultActive: false, + }, + ]; +} + +/** + * Create series from an IntervalPattern (base + average/min/max/median/percentiles, no sum/cumulative) + * @param {Colors} colors + * @param {IntervalPattern} pattern + * @param {string} title + * @param {Unit} unit + * @param {Color} [color] + * @returns {AnyFetchedSeriesBlueprint[]} + */ +export function fromIntervalPattern(colors, pattern, title, unit, color) { + return [ + { metric: pattern.base, title, color, unit }, + { metric: pattern.average, title: `${title} avg`, color: colors.purple, unit, defaultActive: false }, + { metric: pattern.min, title: `${title} min`, color: colors.red, unit, defaultActive: false }, + { metric: pattern.max, title: `${title} max`, color: colors.green, unit, defaultActive: false }, + { metric: pattern.median, title: `${title} median`, color: colors.violet, unit, defaultActive: false }, + { metric: pattern.pct10, title: `${title} pct10`, color: colors.rose, unit, defaultActive: false }, + { metric: pattern.pct25, title: `${title} pct25`, color: colors.pink, unit, defaultActive: false }, + { metric: pattern.pct75, title: `${title} pct75`, color: colors.fuchsia, unit, defaultActive: false }, + { metric: pattern.pct90, title: `${title} pct90`, color: colors.amber, unit, defaultActive: false }, + ]; +} diff --git a/websites/bitview/scripts/options/types.js b/websites/bitview/scripts/options/types.js index c989ff289..54b72dc42 100644 --- a/websites/bitview/scripts/options/types.js +++ b/websites/bitview/scripts/options/types.js @@ -170,8 +170,15 @@ * @property {BrkClient} brk * @property {(args: { metric: AnyMetricPattern, name: string, unit: Unit, color?: Color, defaultActive?: boolean, options?: LineSeriesPartialOptions }) => AnyFetchedSeriesBlueprint} s * @property {(pattern: BlockCountPattern, title: string, color?: Color) => AnyFetchedSeriesBlueprint[]} fromBlockCount - * @property {(pattern: DollarsPattern, title: string, color?: Color) => AnyFetchedSeriesBlueprint[]} fromBitcoin - * @property {(pattern: BlockSizePattern, title: string, color?: Color) => AnyFetchedSeriesBlueprint[]} fromBlockSize + * @property {(pattern: FullnessPattern, title: string, color?: Color) => AnyFetchedSeriesBlueprint[]} fromBitcoin + * @property {(pattern: SizePattern, title: string, color?: Color) => AnyFetchedSeriesBlueprint[]} fromBlockSize + * @property {(pattern: SizePattern, title: string, unit: Unit) => AnyFetchedSeriesBlueprint[]} fromSizePattern + * @property {(pattern: FullnessPattern, title: string, unit: Unit) => AnyFetchedSeriesBlueprint[]} fromFullnessPattern + * @property {(pattern: FeeRatePattern, title: string, unit: Unit) => AnyFetchedSeriesBlueprint[]} fromFeeRatePattern + * @property {(pattern: CoinbasePattern, title: string) => AnyFetchedSeriesBlueprint[]} fromCoinbasePattern + * @property {(pattern: ValuePattern, title: string, sumColor?: Color, cumulativeColor?: Color) => AnyFetchedSeriesBlueprint[]} fromValuePattern + * @property {(pattern: BlockCountPattern, title: string, unit: Unit, sumColor?: Color, cumulativeColor?: Color) => AnyFetchedSeriesBlueprint[]} fromBlockCountWithUnit + * @property {(pattern: IntervalPattern, title: string, unit: Unit, color?: Color) => AnyFetchedSeriesBlueprint[]} fromIntervalPattern * @property {(args: { number?: number, name?: string, defaultActive?: boolean, lineStyle?: LineStyle, color?: Color, unit: Unit }) => FetchedLineSeriesBlueprint} createPriceLine * @property {(args: { numbers: number[], unit: Unit }) => FetchedLineSeriesBlueprint[]} createPriceLines * @property {(args: { constant: AnyMetricPattern, name: string, unit: Unit, color?: Color, lineStyle?: number, defaultActive?: boolean }) => FetchedLineSeriesBlueprint} line diff --git a/websites/bitview/scripts/panes/chart/index.js b/websites/bitview/scripts/panes/chart/index.js index 177a88751..747ffaad8 100644 --- a/websites/bitview/scripts/panes/chart/index.js +++ b/websites/bitview/scripts/panes/chart/index.js @@ -331,7 +331,7 @@ export function init({ case null: case CANDLE: { series = chart.addCandlestickSeries({ - metric: brk.tree.price.usd.priceOhlc, + metric: brk.tree.price.usd.ohlc, name: "Price", unit: topUnit, setDataCallback: printLatest, @@ -341,7 +341,7 @@ export function init({ } case LINE: { series = chart.addLineSeries({ - metric: brk.tree.price.usd.priceClose, + metric: brk.tree.price.usd.split.close, name: "Price", unit: topUnit, color: colors.default, @@ -361,7 +361,7 @@ export function init({ case null: case CANDLE: { series = chart.addCandlestickSeries({ - metric: brk.tree.price.sats.priceOhlcInSats, + metric: brk.tree.price.sats.ohlc, name: "Price", unit: topUnit, inverse: true, @@ -372,7 +372,7 @@ export function init({ } case LINE: { series = chart.addLineSeries({ - metric: brk.tree.price.sats.priceCloseInSats, + metric: brk.tree.price.sats.split.close, name: "Price", unit: topUnit, color: colors.default,