1use std::path::PathBuf;
5
6use alloy::primitives::U256;
7use degenbot_db::ops::HealReport;
8use degenbot_db::{
9 render_completed_market_manifest, AaveMarketPurgeCount, CompletedMarketManifest, SchemaState,
10};
11
12use crate::error::{CliError, ExitCode};
13use crate::pool::PoolFamily;
14use crate::strategy::StrategyFacetDescriptor;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum CommandReport {
19 Database(DatabaseReport),
21 Exchange(ExchangeReport),
23 Pool(PoolReport),
25 Aave(AaveReport),
27 Fleet(FleetReport),
29 Path(PathReport),
31 Strategy(StrategyReport),
33 Config(ConfigReport),
35}
36
37impl CommandReport {
38 #[must_use]
40 pub fn render_lines(&self) -> Vec<String> {
41 match self {
42 Self::Database(report) => report.render_lines(),
43 Self::Exchange(report) => report.render_lines(),
44 Self::Pool(report) => report.render_lines(),
45 Self::Aave(report) => report.render_lines(),
46 Self::Fleet(report) => report.render_lines(),
47 Self::Path(report) => report.render_lines(),
48 Self::Strategy(report) => report.render_lines(),
49 Self::Config(report) => report.render_lines(),
50 }
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct ConfigValue {
61 pub key: String,
63 pub value: String,
66 pub source: Option<degenbot_config::Source>,
68}
69
70impl ConfigValue {
71 #[must_use]
73 pub fn new(key: &str, value: String, source: degenbot_config::Source) -> Self {
74 Self {
75 key: key.to_string(),
76 value,
77 source: Some(source),
78 }
79 }
80
81 #[must_use]
83 pub fn unresolved(key: &str) -> Self {
84 Self {
85 key: key.to_string(),
86 value: String::new(),
87 source: None,
88 }
89 }
90
91 #[must_use]
95 pub fn line(&self) -> String {
96 match self.source {
97 Some(_) => format!(
98 "{} = {}",
99 self.key,
100 degenbot_config::redact_uri(&self.value)
101 ),
102 None => format!("{} = (unresolved)", self.key),
103 }
104 }
105
106 #[must_use]
108 pub fn resolved_line(&self) -> String {
109 match self.source {
110 Some(source) => format!(
111 "{} = {} ({source})",
112 self.key,
113 degenbot_config::redact_uri(&self.value)
114 ),
115 None => format!("{} = (unresolved)", self.key),
116 }
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq)]
122pub enum ConfigReport {
123 Shown {
126 file: Option<PathBuf>,
128 values: Vec<ConfigValue>,
130 resolved: bool,
132 },
133 Path(PathBuf),
135 Got {
138 key: String,
140 value: String,
142 source: Option<degenbot_config::Source>,
144 },
145 Set {
147 key: String,
149 value: String,
151 outcome: crate::strategy::MutationOutcome,
153 },
154 Unset {
156 key: String,
158 outcome: crate::strategy::MutationOutcome,
160 },
161}
162
163impl ConfigReport {
164 #[must_use]
166 pub fn render_lines(&self) -> Vec<String> {
167 match self {
168 Self::Shown {
169 file,
170 values,
171 resolved,
172 } => {
173 let mut lines = vec![match file {
177 Some(path) if path.exists() => format!("config = {}", path.display()),
178 Some(path) => format!("config = {} (not yet created)", path.display()),
179 None => "config = (no config file location)".to_string(),
180 }];
181 lines.extend(values.iter().map(|value| {
182 if *resolved {
183 value.resolved_line()
184 } else {
185 value.line()
186 }
187 }));
188 lines
189 }
190 Self::Path(path) => vec![path.display().to_string()],
191 Self::Got { key, value, source } => vec![match source {
192 Some(source) => {
193 format!("{key} = {} ({source})", degenbot_config::redact_uri(value))
194 }
195 None => format!("{key} = (unresolved)"),
196 }],
197 Self::Set {
198 key,
199 value,
200 outcome,
201 } => vec![
202 format!("set {key} = {}", degenbot_config::redact_uri(value)),
203 shadow_line(outcome),
204 ],
205 Self::Unset { key, outcome } => {
206 vec![format!("removed {key}"), shadow_line(outcome)]
207 }
208 }
209 }
210}
211
212#[derive(Debug)]
214pub struct CommandOutcome {
215 result: Result<CommandReport, CliError>,
216 pub exit_code: ExitCode,
218}
219
220impl CommandOutcome {
221 #[must_use]
223 pub(crate) const fn new(result: Result<CommandReport, CliError>, exit_code: ExitCode) -> Self {
224 Self { result, exit_code }
225 }
226
227 #[must_use]
229 pub fn report(&self) -> Option<&CommandReport> {
230 self.result.as_ref().ok()
231 }
232
233 #[must_use]
235 pub fn error(&self) -> Option<&CliError> {
236 self.result.as_ref().err()
237 }
238}
239
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum DryRunKind {
243 Cutover,
245 Heal,
247}
248
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub enum CutoverOutcome {
252 Converted,
254 AlreadyRustOwned,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
260pub enum DatabaseReport {
261 BackedUp {
263 source: PathBuf,
265 backup: PathBuf,
267 },
268 Reset {
270 path: PathBuf,
272 },
273 Compacted {
275 path: PathBuf,
277 },
278 Inspected {
280 path: PathBuf,
282 state: SchemaState,
284 },
285 Cutover {
287 path: PathBuf,
289 state: SchemaState,
291 outcome: CutoverOutcome,
293 },
294 Healed {
296 path: PathBuf,
298 report: HealReport,
300 },
301 DryRun {
303 path: PathBuf,
305 state: SchemaState,
307 kind: DryRunKind,
309 },
310}
311
312impl DatabaseReport {
313 #[must_use]
315 pub fn render_lines(&self) -> Vec<String> {
316 match self {
317 Self::BackedUp { backup, .. } => {
318 vec![format!("Backed up SQLite database to {}", backup.display())]
319 }
320 Self::Reset { path } => {
321 vec![format!(
322 "Initialized new SQLite database at {}",
323 path.display()
324 )]
325 }
326 Self::Compacted { path } => {
327 vec![format!("Compacted SQLite database at {}", path.display())]
328 }
329 Self::Inspected { state, .. } => {
330 vec![format!("Schema state: {}.", schema_state_label(state))]
331 }
332 Self::Cutover { path, outcome, .. } => match outcome {
333 CutoverOutcome::Converted => vec![format!(
334 "Cut over database at {} from Alembic to Rust ownership (the \
335 `alembic_version` table was dropped and `_degenbot_db_schema_version` \
336 was stamped).",
337 path.display()
338 )],
339 CutoverOutcome::AlreadyRustOwned => {
340 vec!["The database is already Rust-owned; cutover was a no-op.".to_string()]
341 }
342 },
343 Self::Healed { path, report } => healed_lines(path, report),
344 Self::DryRun { state, kind, .. } => vec![match kind {
345 DryRunKind::Cutover => cutover_dry_run_line(state),
346 DryRunKind::Heal => heal_dry_run_line(state),
347 }],
348 }
349 }
350}
351
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub enum ActivateOutcome {
355 Activated,
357 AlreadyActive,
359}
360
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
363pub enum DeactivateOutcome {
364 Deactivated,
366 AlreadyDeactivated,
368 NoEntry,
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum ExchangeActiveState {
375 Active,
377 Inactive,
379 NoEntry,
381}
382
383impl ExchangeActiveState {
384 #[must_use]
386 pub const fn as_str(self) -> &'static str {
387 match self {
388 Self::Active => "active",
389 Self::Inactive => "inactive",
390 Self::NoEntry => "not in database",
391 }
392 }
393}
394
395#[derive(Debug, Clone, PartialEq, Eq)]
397pub struct ExchangeListRow {
398 pub chain_id: u64,
400 pub chain_label: &'static str,
402 pub display_name: &'static str,
404 pub dex_slug: &'static str,
406 pub factory: String,
408 pub state: ExchangeActiveState,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq)]
414pub enum ExchangeReport {
415 Activated {
417 chain_id: u64,
419 chain_label: &'static str,
421 display_name: &'static str,
423 dex_slug: &'static str,
425 outcome: ActivateOutcome,
427 },
428 Deactivated {
430 chain_id: u64,
432 chain_label: &'static str,
434 display_name: &'static str,
436 dex_slug: &'static str,
438 outcome: DeactivateOutcome,
440 },
441 Listed {
443 rows: Vec<ExchangeListRow>,
445 },
446}
447
448impl ExchangeReport {
449 #[must_use]
451 pub fn render_lines(&self) -> Vec<String> {
452 match self {
453 Self::Activated {
454 chain_id,
455 chain_label,
456 display_name,
457 outcome,
458 ..
459 } => match outcome {
460 ActivateOutcome::Activated => vec![format!(
461 "Activated {display_name} on {chain_label} (chain ID {chain_id})."
462 )],
463 ActivateOutcome::AlreadyActive => {
464 vec!["Exchange is already activated.".to_string()]
465 }
466 },
467 Self::Deactivated {
468 chain_id,
469 chain_label,
470 display_name,
471 outcome,
472 ..
473 } => match outcome {
474 DeactivateOutcome::Deactivated => vec![format!(
475 "Deactivated {display_name} on {chain_label} (chain ID {chain_id})."
476 )],
477 DeactivateOutcome::AlreadyDeactivated => {
478 vec!["Exchange is already deactivated.".to_string()]
479 }
480 DeactivateOutcome::NoEntry => vec![format!(
481 "The database has no entry for {display_name} on {chain_label} \
482 (chain ID {chain_id})."
483 )],
484 },
485 Self::Listed { rows } => rows
486 .iter()
487 .map(|row| {
488 format!(
489 "{} on {} (chain ID {}): {}",
490 row.display_name,
491 row.chain_label,
492 row.chain_id,
493 row.state.as_str()
494 )
495 })
496 .collect(),
497 }
498 }
499}
500
501#[derive(Debug, Clone, PartialEq, Eq)]
503pub enum PoolReport {
504 Updated {
506 chain_id: i64,
508 from_block: u64,
510 to_block: u64,
512 chunks_committed: usize,
514 total_pools_written: usize,
516 total_liquidity_applies: usize,
518 },
519 UpdateCancelled {
521 chain_id: i64,
523 },
524 Verified {
526 pool: String,
528 family: PoolFamily,
530 block_number: u64,
532 divergences: Vec<degenbot_pool_updater::LiquidityDivergence>,
534 },
535}
536
537impl PoolReport {
538 #[must_use]
540 pub fn render_lines(&self) -> Vec<String> {
541 match self {
542 Self::Updated {
543 chain_id,
544 from_block,
545 to_block,
546 chunks_committed,
547 total_pools_written,
548 total_liquidity_applies,
549 } => vec![format!(
550 "Chain {chain_id}: advanced {from_block}->{to_block} in {chunks_committed} \
551 chunks ({total_pools_written} pools written, {total_liquidity_applies} \
552 liquidity applies)."
553 )],
554 Self::UpdateCancelled { chain_id } => vec![format!(
555 "Chain {chain_id}: cancelled (committed chunks stay durable)."
556 )],
557 Self::Verified {
558 pool,
559 family,
560 block_number,
561 divergences,
562 } => verification_lines(pool, *family, *block_number, divergences),
563 }
564 }
565}
566
567#[derive(Debug, Clone, PartialEq, Eq)]
569pub enum FleetReport {
570 Posture {
574 effective: String,
576 },
577}
578
579impl FleetReport {
580 #[must_use]
582 pub fn render_lines(&self) -> Vec<String> {
583 match self {
584 Self::Posture { effective } => vec![effective.clone()],
585 }
586 }
587}
588
589#[derive(Debug, Clone, PartialEq, Eq)]
591pub enum PathReport {
592 Added {
594 detail: String,
596 },
597 Discovered {
599 detail: String,
601 },
602}
603
604impl PathReport {
605 #[must_use]
607 pub fn render_lines(&self) -> Vec<String> {
608 match self {
609 Self::Added { detail } | Self::Discovered { detail } => vec![detail.clone()],
610 }
611 }
612}
613
614#[derive(Debug, Clone, PartialEq, Eq)]
616pub enum StrategyReport {
617 Listed {
619 rows: Vec<StrategyFacetDescriptor>,
621 },
622 Shown {
624 descriptor: StrategyFacetDescriptor,
626 activation: Option<crate::strategy::EndpointSummary>,
629 },
630 Activated {
632 facet: crate::strategy::StrategyFacet,
634 summary: crate::strategy::EndpointSummary,
636 outcome: crate::strategy::MutationOutcome,
638 },
639 Deactivated {
641 facet: crate::strategy::StrategyFacet,
643 outcome: crate::strategy::MutationOutcome,
645 },
646 Set {
648 facet: crate::strategy::StrategyFacet,
650 key: &'static str,
652 outcome: crate::strategy::MutationOutcome,
654 },
655 Defaulted {
658 facet: crate::strategy::StrategyFacet,
660 key: &'static str,
662 },
663}
664
665impl StrategyReport {
666 #[must_use]
668 pub fn render_lines(&self) -> Vec<String> {
669 match self {
670 Self::Listed { rows } => rows
671 .iter()
672 .map(|descriptor| {
673 format!(
674 "{} ({}) -> {} [{} declared key(s)]",
675 descriptor.facet.as_str(),
676 descriptor.trigger_kind,
677 descriptor.config_section,
678 descriptor.fields.len()
679 )
680 })
681 .collect(),
682 Self::Shown {
683 descriptor,
684 activation,
685 } => {
686 let mut lines = vec![format!(
687 "{}: {} strategy",
688 descriptor.config_section, descriptor.trigger_kind
689 )];
690 lines.push(format!(" selector: {}", descriptor.facet.as_str()));
691 if let Some(summary) = activation {
692 lines.push(format!(" posture: {}", posture_line(summary)));
693 }
694 if descriptor.fields.is_empty() {
695 lines.push(" declared keys: (none yet)".to_string());
696 } else {
697 for (field, env) in descriptor.fields.iter().zip(&descriptor.envs) {
698 lines.push(format!(" {field} ({env})"));
699 }
700 }
701 lines
702 }
703 Self::Activated {
704 facet,
705 summary,
706 outcome,
707 } => vec![
708 format!("activated strategy {}", facet.as_str()),
709 format!(" endpoints: {}", posture_line(summary)),
710 shadow_line(outcome),
711 ],
712 Self::Deactivated { facet, outcome } => vec![
713 format!(
714 "deactivated strategy {} (recorded endpoints kept)",
715 facet.as_str()
716 ),
717 shadow_line(outcome),
718 ],
719 Self::Set {
720 facet,
721 key,
722 outcome,
723 } => vec![
724 format!("set {}.{}", facet.config_section(), key),
725 shadow_line(outcome),
726 ],
727 Self::Defaulted { facet, key } => vec![format!(
728 "restored {}.{} to its declared default",
729 facet.config_section(),
730 key
731 )],
732 }
733 }
734}
735
736fn posture_line(summary: &crate::strategy::EndpointSummary) -> String {
738 match summary {
739 crate::strategy::EndpointSummary::Inactive => "inactive".to_string(),
740 crate::strategy::EndpointSummary::Unset => {
741 "UNSET (activation requires --endpoints or --endpoints-default)".to_string()
742 }
743 crate::strategy::EndpointSummary::Default(urls) => {
744 format!("default ({})", urls.join(", "))
745 }
746 crate::strategy::EndpointSummary::Explicit(urls) => urls.join(", "),
747 }
748}
749
750fn shadow_line(outcome: &crate::strategy::MutationOutcome) -> String {
752 match outcome {
753 crate::strategy::MutationOutcome::Applied => " applies at load time".to_string(),
754 crate::strategy::MutationOutcome::Shadowed { env } => {
755 format!(" WARNING: {env} is set in the environment and will shadow this write")
756 }
757 }
758}
759
760fn verification_lines(
762 pool: &str,
763 family: PoolFamily,
764 block_number: u64,
765 divergences: &[degenbot_pool_updater::LiquidityDivergence],
766) -> Vec<String> {
767 use degenbot_pool_updater::LiquidityDivergence;
768 if divergences.is_empty() {
769 return vec![format!(
770 "GREEN: {} pool {pool} matches on-chain truth at block {block_number}.",
771 family.as_str()
772 )];
773 }
774 let mut lines = vec![format!(
775 "RED: {} divergence(s) for {} pool {pool} at block {block_number}:",
776 divergences.len(),
777 family.as_str()
778 )];
779 for divergence in divergences {
780 lines.push(match divergence {
781 LiquidityDivergence::TickGross {
782 tick,
783 expected,
784 actual,
785 } => format!(" tick {tick}: TickGross expected={expected} actual={actual}"),
786 LiquidityDivergence::TickNet {
787 tick,
788 expected,
789 actual,
790 } => format!(" tick {tick}: TickNet expected={expected} actual={actual}"),
791 LiquidityDivergence::BitmapWord {
792 word,
793 expected,
794 actual,
795 } => format!(" word {word}: BitmapWord expected={expected} actual={actual}"),
796 LiquidityDivergence::TickPresence {
797 tick,
798 stored,
799 observed,
800 } => format!(" tick {tick}: TickPresence stored={stored} observed={observed}"),
801 });
802 }
803 lines
804}
805
806#[derive(Debug, Clone, PartialEq, Eq)]
808pub enum AaveUpdateOutcome {
809 Advanced {
811 from_block: u64,
813 to_block: u64,
815 chunks_committed: usize,
817 total_events_applied: usize,
819 },
820 Cancelled,
822 NeedsBootstrap,
824 DryRun {
826 last_update_block: i64,
828 to_block: Option<u64>,
830 },
831}
832
833#[derive(Debug, Clone, PartialEq, Eq)]
839pub struct AaveReinit {
840 pub market_activated: bool,
842 pub contract_row_present: bool,
845 pub last_update_block: Option<i64>,
848}
849
850#[derive(Debug, Clone, PartialEq, Eq)]
852pub struct AaveUpdateEntry {
853 pub chain_id: i64,
855 pub market_id: i64,
857 pub market_name: String,
859 pub outcome: AaveUpdateOutcome,
861}
862
863#[derive(Debug, Clone, PartialEq, Eq)]
865pub struct AavePositionLine {
866 pub symbol: String,
868 pub balance: U256,
870}
871
872#[derive(Debug, Clone, PartialEq, Eq)]
874pub enum AaveReport {
875 Activated {
877 chain_id: u64,
879 chain_label: &'static str,
881 market_id: i64,
883 market_name: String,
885 created: bool,
887 },
888 Deactivated {
890 chain_id: u64,
892 market_id: Option<i64>,
894 outcome: DeactivateOutcome,
896 },
897 Digest {
899 manifest: CompletedMarketManifest,
903 },
904 Updated {
906 entries: Vec<AaveUpdateEntry>,
908 },
909 Reset {
911 chain_id: u64,
913 market_id: i64,
915 market_name: String,
917 counts: Vec<AaveMarketPurgeCount>,
920 dry_run: bool,
922 reinit: Option<AaveReinit>,
924 },
925 Position {
927 user_address: String,
929 market: String,
931 chain_id: u64,
933 collateral: Vec<AavePositionLine>,
935 debt: Vec<AavePositionLine>,
937 },
938 PositionNoMarket {
940 market: String,
942 chain_id: u64,
944 },
945 PositionNoUser {
947 user_address: String,
949 market: String,
951 chain_id: u64,
953 },
954}
955
956impl AaveReport {
957 #[must_use]
959 pub fn render_lines(&self) -> Vec<String> {
960 match self {
961 Self::Activated {
962 chain_id,
963 chain_label,
964 market_id,
965 market_name,
966 created,
967 } => vec![
968 format!("Activated Aave V3 on {chain_label} (chain ID {chain_id})."),
969 format!(" Market: {market_name} (id={market_id}, created={created})."),
970 ],
971 Self::Deactivated {
972 chain_id, outcome, ..
973 } => match outcome {
974 DeactivateOutcome::Deactivated => vec![format!(
975 "Deactivated Aave V3 on {} (chain ID {chain_id}).",
976 chain_label_for(*chain_id)
977 )],
978 DeactivateOutcome::AlreadyDeactivated => Vec::new(),
979 DeactivateOutcome::NoEntry => {
980 vec![format!(
981 "The database has no entry for Aave V3 on {} (chain ID {chain_id}).",
982 chain_label_for(*chain_id)
983 )]
984 }
985 },
986 Self::Digest { manifest } => vec![render_completed_market_manifest(manifest)],
990 Self::Updated { entries } => entries.iter().flat_map(entry_lines).collect(),
991 Self::Reset {
992 chain_id,
993 market_id,
994 market_name,
995 counts,
996 dry_run,
997 reinit,
998 } => reset_lines(
999 *chain_id,
1000 *market_id,
1001 market_name,
1002 counts,
1003 *dry_run,
1004 reinit.as_ref(),
1005 ),
1006 Self::Position {
1007 user_address,
1008 market,
1009 chain_id,
1010 collateral,
1011 debt,
1012 } => position_lines(user_address, market, *chain_id, collateral, debt),
1013 Self::PositionNoMarket { market, chain_id } => {
1014 vec![format!(
1015 "No market found with name '{market}' on chain {chain_id}."
1016 )]
1017 }
1018 Self::PositionNoUser {
1019 user_address,
1020 market,
1021 chain_id,
1022 } => vec![format!(
1023 "No Aave user found for address {user_address} in market '{market}' on chain \
1024 {chain_id}."
1025 )],
1026 }
1027 }
1028}
1029
1030fn chain_label_for(chain_id: u64) -> String {
1032 match chain_id {
1033 1 => "Ethereum".to_string(),
1034 8453 => "Base".to_string(),
1035 other => other.to_string(),
1036 }
1037}
1038
1039fn entry_lines(entry: &AaveUpdateEntry) -> Vec<String> {
1041 let AaveUpdateEntry {
1042 chain_id,
1043 market_id,
1044 market_name,
1045 outcome,
1046 } = entry;
1047 match outcome {
1048 AaveUpdateOutcome::Advanced {
1049 from_block,
1050 to_block,
1051 chunks_committed,
1052 total_events_applied,
1053 } => vec![format!(
1054 "Chain {chain_id} market {market_id} ({market_name}): advanced {from_block}-> \
1055 {to_block} in {chunks_committed} chunks ({total_events_applied} events applied)."
1056 )],
1057 AaveUpdateOutcome::Cancelled => vec![format!(
1058 "Chain {chain_id} market {market_id}: cancelled (committed chunks stay durable)."
1059 )],
1060 AaveUpdateOutcome::NeedsBootstrap => vec![format!(
1061 "Chain {chain_id} market {market_id} ({market_name}): needs bootstrapping \
1062 (last_update_block is None); skipping. Bootstrap the stamp before running."
1063 )],
1064 AaveUpdateOutcome::DryRun {
1065 last_update_block,
1066 to_block,
1067 } => vec![format!(
1068 "Dry run: would advance chain {chain_id} market {market_id} ({market_name}) from \
1069 block {last_update_block} to {} (no changes committed).",
1070 render_opt_block(*to_block)
1071 )],
1072 }
1073}
1074
1075fn reset_lines(
1078 chain_id: u64,
1079 market_id: i64,
1080 market_name: &str,
1081 counts: &[AaveMarketPurgeCount],
1082 dry_run: bool,
1083 reinit: Option<&AaveReinit>,
1084) -> Vec<String> {
1085 let mut lines = Vec::with_capacity(counts.len() + 3);
1086 if dry_run {
1087 lines.push(format!(
1088 "Dry run: would reset chain {chain_id} market {market_id} ({market_name}); \
1089 nothing deleted."
1090 ));
1091 } else {
1092 lines.push(format!(
1093 "Reset chain {chain_id} market {market_id} ({market_name})."
1094 ));
1095 }
1096 for count in counts {
1097 lines.push(format!(" {}: {} row(s)", count.table, count.rows));
1098 }
1099 match reinit {
1100 Some(reinit) => lines.push(format!(
1101 " re-initialized via the activate seam: market row active = {}, \
1102 POOL_ADDRESS_PROVIDER row = {}, last_update_block = {}",
1103 reinit.market_activated,
1104 reinit.contract_row_present,
1105 render_opt_block(
1106 reinit
1107 .last_update_block
1108 .map(|b| u64::try_from(b).unwrap_or(0))
1109 )
1110 )),
1111 None if dry_run => lines.push(
1112 " re-init skipped: the purge was previewed, so the market's state is unchanged."
1113 .to_string(),
1114 ),
1115 None => {}
1116 }
1117 lines
1118}
1119
1120fn render_opt_block(block: Option<u64>) -> String {
1122 block.map_or_else(|| "None".to_string(), |n| n.to_string())
1123}
1124
1125fn position_lines(
1127 user_address: &str,
1128 market: &str,
1129 chain_id: u64,
1130 collateral: &[AavePositionLine],
1131 debt: &[AavePositionLine],
1132) -> Vec<String> {
1133 let mut lines = vec![
1134 format!("Aave V3 Positions for {user_address}"),
1135 format!("Market: {market} (Chain: {chain_id})"),
1136 "=".repeat(60),
1137 ];
1138 if collateral.is_empty() {
1139 lines.push("No collateral positions found.".to_string());
1140 } else {
1141 lines.push("Collateral Positions:".to_string());
1142 lines.push("-".repeat(60));
1143 lines.extend(
1144 collateral
1145 .iter()
1146 .map(|p| format!(" {}: {} (scaled)", p.symbol, p.balance)),
1147 );
1148 }
1149 if debt.is_empty() {
1150 lines.push("No debt positions found.".to_string());
1151 } else {
1152 lines.push("Debt Positions:".to_string());
1153 lines.push("-".repeat(60));
1154 lines.extend(
1155 debt.iter()
1156 .map(|p| format!(" {}: {} (scaled)", p.symbol, p.balance)),
1157 );
1158 }
1159 lines
1160}
1161
1162fn healed_lines(path: &std::path::Path, report: &HealReport) -> Vec<String> {
1164 if matches!(report.old_state, SchemaState::RustOwned { .. }) {
1165 return vec![format!(
1166 "Database at {} is already Rust-owned; heal is a no-op (no copy, no .bak).",
1167 path.display()
1168 )];
1169 }
1170 let total_rows: u64 = report.rows_copied.values().sum();
1171 let n_tables = report.rows_copied.len();
1172 let mut lines = vec![format!(
1173 "Healed database at {}: {total_rows} rows across {n_tables} tables copied; old DB \
1174 preserved at {}; new state: {}.",
1175 path.display(),
1176 report.bak_path.display(),
1177 schema_state_label(&report.new_state)
1178 )];
1179 if !report.warnings.is_empty() {
1180 lines.push(format!("Warnings: {}", report.warnings.join("; ")));
1181 }
1182 lines
1183}
1184
1185#[must_use]
1187pub fn cutover_dry_run_line(state: &SchemaState) -> String {
1188 let label = schema_state_label(state);
1189 match state {
1190 SchemaState::LegacyAlembic => format!(
1191 "Schema state: {label}. Would cutover from Alembic to Rust ownership (drop \
1192 `alembic_version`, stamp `_degenbot_db_schema_version`)."
1193 ),
1194 SchemaState::RustOwned { .. } => {
1195 format!("Schema state: {label}. Already Rust-owned — cutover is a no-op.")
1196 }
1197 SchemaState::FreshStandalone { .. } => {
1198 format!("Schema state: {label}. No legacy history — nothing to cutover.")
1199 }
1200 SchemaState::Unrecognized => {
1201 format!("Schema state: {label}. Unrecognized database (foreign file).")
1202 }
1203 }
1204}
1205
1206#[must_use]
1208pub fn heal_dry_run_line(state: &SchemaState) -> String {
1209 let label = schema_state_label(state);
1210 match state {
1211 SchemaState::LegacyAlembic => format!(
1212 "Schema state: {label}. Would heal: rebuild at the Rust head schema, copy all \
1213 rows, drop alembic_version, stamp _degenbot_db_schema_version, atomic-swap with \
1214 a *.bak backup."
1215 ),
1216 SchemaState::RustOwned { .. } => {
1217 format!("Schema state: {label}. Already Rust-owned — heal is a no-op.")
1218 }
1219 SchemaState::FreshStandalone { .. } => format!(
1220 "Schema state: {label}. Empty file — heal produces a fresh RustOwned DB (0 rows \
1221 copied)."
1222 ),
1223 SchemaState::Unrecognized => {
1224 format!(
1225 "Schema state: {label}. Unrecognized database (foreign file) — heal would \
1226 refuse."
1227 )
1228 }
1229 }
1230}
1231
1232#[must_use]
1235pub fn schema_state_label(state: &SchemaState) -> &'static str {
1236 match state {
1237 SchemaState::LegacyAlembic => "legacy_alembic",
1238 SchemaState::FreshStandalone { .. } => "fresh_standalone",
1239 SchemaState::RustOwned { .. } => "rust_owned",
1240 SchemaState::Unrecognized => "unrecognized",
1241 }
1242}