Skip to content

Commit 3e75b86

Browse files
committed
Include staking stats, fix tests
1 parent 3debccd commit 3e75b86

5 files changed

Lines changed: 60 additions & 18 deletions

File tree

src/api/handler/simulate.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ mod tests {
125125
use crate::simulate::MockSimulateService;
126126
use crate::snapshot::MockSnapshotService;
127127
use crate::models::Chain;
128-
use crate::models::{RunParameters, SimulationResult};
128+
use crate::models::{RunParameters, SimulationResult, StakingStats};
129129
use std::sync::Arc;
130130

131131
#[tokio::test]
@@ -143,6 +143,11 @@ mod tests {
143143
desired_validators: 0,
144144
},
145145
active_validators: vec![],
146+
staking_stats: StakingStats {
147+
total_staked: 0,
148+
lowest_staked: 0,
149+
avg_staked: 0,
150+
},
146151
})
147152
});
148153
let snapshot_service: MockSnapshotService<PolkadotMinerConfig, Storage> = MockSnapshotService::new();

src/models.rs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,20 +153,41 @@ pub struct RunParameters {
153153
#[derive(Debug)]
154154
pub struct SimulationResult {
155155
pub run_parameters: RunParameters,
156-
pub active_validators: Vec<Validator>
156+
pub staking_stats: StakingStats,
157+
pub active_validators: Vec<Validator>,
158+
}
159+
160+
#[derive(Debug)]
161+
pub struct StakingStats {
162+
pub total_staked: Balance,
163+
pub lowest_staked: Balance,
164+
pub avg_staked: Balance,
165+
}
166+
167+
#[derive(Debug, Serialize)]
168+
pub struct StakingStatsOutput {
169+
pub total_staked: String,
170+
pub lowest_staked: String,
171+
pub avg_staked: String,
157172
}
158173

159174
// Output simulation with formatted stake strings
160175
#[derive(Debug, Serialize)]
161176
pub struct SimulationResultOutput {
162177
pub run_parameters: RunParameters,
163-
pub active_validators: Vec<ValidatorOutput>
178+
pub staking_stats: StakingStatsOutput,
179+
pub active_validators: Vec<ValidatorOutput>,
164180
}
165181

166182
impl SimulationResult {
167183
pub fn to_output(&self, chain: Chain) -> SimulationResultOutput {
168184
SimulationResultOutput {
169185
run_parameters: self.run_parameters.clone(),
186+
staking_stats: StakingStatsOutput {
187+
total_staked: chain.format_stake(self.staking_stats.total_staked),
188+
lowest_staked: chain.format_stake(self.staking_stats.lowest_staked),
189+
avg_staked: chain.format_stake(self.staking_stats.avg_staked),
190+
},
170191
active_validators: self.active_validators.iter().map(|v| {
171192
ValidatorOutput {
172193
stash: v.stash.clone(),

src/multi_block_state_client.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,6 @@ impl Phase {
119119
/// Check if snapshots are available in this phase.
120120
///
121121
/// Snapshots are available in:
122-
/// - `Snapshot(0)` - when snapshot creation is complete (all pages fetched)
123122
/// - `Done` - snapshot is done, waiting for export
124123
/// - `Signed` - signed phase is open
125124
/// - `SignedValidation` - validating signed results
@@ -128,17 +127,16 @@ impl Phase {
128127
///
129128
/// Snapshots are NOT available in:
130129
/// - `Off` - election hasn't started
131-
/// - `Snapshot(n)` where n > 0 - snapshot is still being created
130+
/// - `Snapshot(n)` - snapshot is still being created
132131
/// - `Emergency` - emergency phase locks the pallet
133132
pub fn has_snapshot(&self) -> bool {
134133
match self {
135-
Phase::Snapshot(0) => true, // Snapshot complete
136134
Phase::Done => true,
137135
Phase::Signed(_) => true,
138136
Phase::SignedValidation(_) => true,
139137
Phase::Unsigned(_) => true,
140138
Phase::Export(_) => true,
141-
Phase::Snapshot(_) => false, // Still being created (n > 0)
139+
Phase::Snapshot(_) => false,
142140
Phase::Off => false,
143141
Phase::Emergency => false,
144142
}
@@ -380,14 +378,14 @@ mod tests {
380378
async fn fetch<Addr>(
381379
&self,
382380
address: &Addr,
383-
) -> Result<Option<<Addr as Address>::Target>, Box<dyn std::error::Error>>
381+
) -> Result<Option<<Addr as Address>::Target>, Box<dyn std::error::Error + Send + Sync>>
384382
where
385383
Addr: Address<IsFetchable = Yes> + Sync + 'static;
386384

387385
async fn fetch_or_default<Addr>(
388386
&self,
389387
address: &Addr,
390-
) -> Result<<Addr as Address>::Target, Box<dyn std::error::Error>>
388+
) -> Result<<Addr as Address>::Target, Box<dyn std::error::Error + Send + Sync>>
391389
where
392390
Addr: Address<IsFetchable = Yes, IsDefaultable = Yes> + Sync + 'static;
393391
}

src/simulate.rs

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::collections::BTreeMap;
1+
use std::collections::{BTreeMap};
22
use std::sync::Arc;
33

44
use pallet_staking::ValidatorPrefs;
@@ -12,7 +12,7 @@ use sp_runtime::Perbill;
1212
use tracing::info;
1313
use frame_support::BoundedVec;
1414
use mockall::automock;
15-
use crate::{miner_config, multi_block_state_client::{MultiBlockClientTrait, StorageTrait, VoterData, VoterSnapshotPage}, primitives::Storage, snapshot::SnapshotService};
15+
use crate::{miner_config, models::StakingStats, multi_block_state_client::{MultiBlockClientTrait, StorageTrait, VoterData, VoterSnapshotPage}, primitives::Storage, snapshot::SnapshotService};
1616

1717
use crate::{models::{Validator, ValidatorNomination, SimulationResult, RunParameters}, multi_block_state_client::ChainClientTrait, primitives::AccountId};
1818

@@ -323,9 +323,18 @@ where
323323
.collect::<Result<Vec<_>, _>>()
324324
.map_err(|e| e.to_string())?;
325325

326+
let total_staked = active_validators.iter().map(|v| v.total_stake).sum();
327+
let lowest_staked = active_validators.iter().map(|v| v.total_stake).min().unwrap_or(0);
328+
let avg_staked = total_staked / active_validators.len() as u128;
329+
326330
let simulation_result = crate::models::SimulationResult {
327331
run_parameters: run_parameters.clone(),
328-
active_validators
332+
active_validators,
333+
staking_stats: StakingStats {
334+
total_staked: total_staked,
335+
lowest_staked: lowest_staked,
336+
avg_staked: avg_staked,
337+
},
329338
};
330339

331340
Ok(simulation_result)
@@ -358,14 +367,14 @@ mod tests {
358367
async fn fetch<Addr>(
359368
&self,
360369
address: &Addr,
361-
) -> Result<Option<<Addr as Address>::Target>, Box<dyn std::error::Error>>
370+
) -> Result<Option<<Addr as Address>::Target>, Box<dyn std::error::Error + Send + Sync>>
362371
where
363372
Addr: Address<IsFetchable = Yes> + Sync + 'static;
364373

365374
async fn fetch_or_default<Addr>(
366375
&self,
367376
address: &Addr,
368-
) -> Result<<Addr as Address>::Target, Box<dyn std::error::Error>>
377+
) -> Result<<Addr as Address>::Target, Box<dyn std::error::Error + Send + Sync>>
369378
where
370379
Addr: Address<IsFetchable = Yes, IsDefaultable = Yes> + Sync + 'static;
371380
}
@@ -402,6 +411,9 @@ mod tests {
402411
storage: MockDummyStorage::new(),
403412
_block_number: 100,
404413
};
414+
415+
mock_client.expect_get_phase()
416+
.returning(|_storage: &MockDummyStorage| Ok(Phase::Snapshot(0)));
405417

406418
let block_details_clone = block_details.clone();
407419
mock_client.expect_get_block_details()
@@ -465,6 +477,9 @@ mod tests {
465477
storage: MockDummyStorage::new(),
466478
_block_number: 100,
467479
};
480+
481+
mock_client.expect_get_phase()
482+
.returning(|_storage: &MockDummyStorage| Ok(Phase::Snapshot(0)));
468483

469484
let block_details_clone = block_details.clone();
470485
mock_client.expect_get_block_details()
@@ -552,6 +567,9 @@ mod tests {
552567
storage: MockDummyStorage::new(),
553568
_block_number: 100,
554569
};
570+
571+
mock_client.expect_get_phase()
572+
.returning(|_storage: &MockDummyStorage| Ok(Phase::Snapshot(0)));
555573

556574
let block_details_clone = block_details.clone();
557575
mock_client.expect_get_block_details()

src/snapshot.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -313,14 +313,14 @@ mod tests {
313313
async fn fetch<Addr>(
314314
&self,
315315
address: &Addr,
316-
) -> Result<Option<<Addr as Address>::Target>, Box<dyn std::error::Error>>
316+
) -> Result<Option<<Addr as Address>::Target>, Box<dyn std::error::Error + Send + Sync>>
317317
where
318318
Addr: Address<IsFetchable = Yes> + Sync + 'static;
319319

320320
async fn fetch_or_default<Addr>(
321321
&self,
322322
address: &Addr,
323-
) -> Result<<Addr as Address>::Target, Box<dyn std::error::Error>>
323+
) -> Result<<Addr as Address>::Target, Box<dyn std::error::Error + Send + Sync>>
324324
where
325325
Addr: Address<IsFetchable = Yes, IsDefaultable = Yes> + Sync + 'static;
326326
}
@@ -396,7 +396,7 @@ mod tests {
396396

397397
let result = snapshot_service.get_snapshot_data_from_multi_block(&BlockDetails::<MockDummyStorage> {
398398
block_hash: Some(Hash::zero()),
399-
phase: Phase::Snapshot(0),
399+
phase: Phase::Signed(10),
400400
round: 1,
401401
n_pages: 1,
402402
desired_targets: 10,
@@ -601,7 +601,7 @@ mod tests {
601601
.with(eq(None))
602602
.returning(|_block: Option<H256>| Ok(BlockDetails::<MockDummyStorage> {
603603
block_hash: Some(Hash::zero()),
604-
phase: Phase::Snapshot(0),
604+
phase: Phase::Signed(10),
605605
round: 1,
606606
n_pages: 1,
607607
desired_targets: 10,

0 commit comments

Comments
 (0)