Skip to content

Commit

Permalink
Add hardcoded override to ElectionScore (#455)
Browse files Browse the repository at this point in the history
* Add hardcoded override to ElectionScore so that we can give it the traits it needs

* cargo fmt + another comment

* copy over custom trait impls too
  • Loading branch information
jsdw authored Feb 16, 2022
1 parent 0e0553a commit eeb8b4b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
6 changes: 6 additions & 0 deletions codegen/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,12 @@ impl RuntimeGenerator {
"frame_support::traits::misc::WrapperKeepOpaque",
parse_quote!(::subxt::WrapperKeepOpaque),
),
// We override this because it's used as a key in a BTreeMap, and so we
// need to implement some extra derives for it for that to compile.
(
"sp_npos_elections::ElectionScore",
parse_quote!(::subxt::ElectionScore),
),
]
.iter()
.map(|(path, substitute): &(&str, syn::TypePath)| {
Expand Down
38 changes: 38 additions & 0 deletions subxt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,3 +239,41 @@ impl<T> PhantomDataSendSync<T> {

unsafe impl<T> Send for PhantomDataSendSync<T> {}
unsafe impl<T> Sync for PhantomDataSendSync<T> {}

/// [`ElectionScore`] overrides any generated instance of `sp_npos_elections::ElectionScore` found
/// in the metadata, so that we can add some extra derives required for it to be used as the key
/// in a [`std::collections::BTreeMap`].
#[derive(Encode, Decode, Debug, PartialEq, Eq)]
pub struct ElectionScore {
/// The minimal winner, in terms of total backing stake.
///
/// This parameter should be maximized.
pub minimal_stake: u128,
/// The sum of the total backing of all winners.
///
/// This parameter should maximized
pub sum_stake: u128,
/// The sum squared of the total backing of all winners, aka. the variance.
///
/// Ths parameter should be minimized.
pub sum_stake_squared: u128,
}

// These are copied from the original impl; they don't affect encoding/decoding but help
// to keep the ordering the same if we then work with the decoded results.
impl Ord for ElectionScore {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// we delegate this to the lexicographic cmp of slices`, and to incorporate that we want the
// third element to be minimized, we swap them.
[self.minimal_stake, self.sum_stake, other.sum_stake_squared].cmp(&[
other.minimal_stake,
other.sum_stake,
self.sum_stake_squared,
])
}
}
impl PartialOrd for ElectionScore {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}

0 comments on commit eeb8b4b

Please sign in to comment.