Skip to content

Commit

Permalink
fix: tests
Browse files Browse the repository at this point in the history
  • Loading branch information
supreme committed Aug 31, 2024
1 parent 5e6706d commit 4fa1b6c
Show file tree
Hide file tree
Showing 5 changed files with 159 additions and 139 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

139 changes: 108 additions & 31 deletions pallets/offworker/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ extern crate alloc;
use alloc::vec::Vec;
use frame_support::traits::Get;
use frame_system::{
self as system,
offchain::{AppCrypto, CreateSignedTransaction, SignedPayload, Signer, SigningTypes},
pallet_prelude::BlockNumberFor,
};
use pallet_subnet_emission::subnet_consensus::yuma::{params::YumaParams, YumaOutput};
use pallet_subspace::Weights;
use pallet_subnet_emission::subnet_consensus::yuma::YumaOutput;
use pallet_subspace::Pallet as SubspaceModule;
use parity_scale_codec::{Decode, Encode};
use scale_info::prelude::marker::PhantomData;
use sp_core::crypto::KeyTypeId;
Expand Down Expand Up @@ -310,6 +309,88 @@ impl<T: Config> Pallet<T> {
}
}

// Copying profitability calulations
// =================================

/// Determines if the copier's performance is irrational based on cumulative dividends.
///
/// # Arguments
///
/// * `consensus_result` - A `ConsensusSimulationResult` struct containing simulation data.
///
/// # Returns
///
/// * `true` if the copier's cumulative dividends are significantly lower than the adjusted average
/// delegate dividends, and the `epoch_block_sum` is less than `max_encryption_period`.
/// * `false` otherwise, including when `epoch_block_sum` is greater than or equal to
/// `max_encryption_period`.
///
/// # Note
///
/// The function compares `cumulative_copier_divs` against an adjusted
/// `cumulative_avg_delegate_divs`, taking into account the `min_underperf_threshold`.
#[must_use]
pub fn is_copying_irrational<T: pallet_subspace::Config>(
consensus_result: ConsensusSimulationResult<T>,
) -> bool {
if consensus_result.black_box_age >= consensus_result.max_encryption_period {
return true;
}
consensus_result.cumulative_copier_divs
< I64F64::from_num(1)
.saturating_sub(consensus_result.min_underperf_threshold)
.saturating_mul(consensus_result.cumulative_avg_delegate_divs)
}

/// Calculates the average delegate dividends for a copier.
///
/// # Arguments
///
/// * `netuid` - The network UID.
/// * `dividends` - A slice of dividend values for each UID.
/// * `copier_uid` - The UID of the copier.
/// * `delegation_fee` - The delegation fee percentage.
///
/// # Returns
///
/// The calculated average delegate dividends as an `I64F64` fixed-point number.
pub fn calculate_avg_delegate_divs<T: pallet_subspace::Config>(
netuid: u16,
dividends: &[u16],
copier_uid: u16,
delegation_fee: Percent,
) -> impl Into<I64F64> {
let copier_idx = copier_uid as usize;
let fee_factor = I64F64::from_num(100 - delegation_fee.deconstruct()) / I64F64::from_num(100);

let (total_stake, total_dividends) = dividends
.iter()
.enumerate()
.filter(|&(i, &div)| i != copier_idx && div != 0)
.fold(
(I64F64::from_num(0), I64F64::from_num(0)),
|(stake_acc, div_acc), (i, &div)| {
(
stake_acc + I64F64::from_num(get_stake_for_uid::<T>(netuid, i as u16)),
div_acc + I64F64::from_num(div),
)
},
);

let average_dividends = total_dividends / total_stake;
let copier_stake = I64F64::from_num(get_stake_for_uid::<T>(netuid, copier_uid));

average_dividends * fee_factor * copier_stake
}

// TODO:
// get rid of this shit, make it more efficient
#[inline]
pub fn get_stake_for_uid<T: pallet_subspace::Config>(netuid: u16, module_uid: u16) -> u64 {
SubspaceModule::<T>::get_key_for_uid(netuid, module_uid)
.map_or(0, |key| SubspaceModule::<T>::get_delegated_stake(&key))
}

/// Represents the result of a consensus simulation.
///
/// # Type Parameters
Expand Down Expand Up @@ -347,33 +428,29 @@ impl<T: pallet_subspace::Config> Default for ConsensusSimulationResult<T> {
}
}
}

/// Determines if the copier's performance is irrational based on cumulative dividends.
///
/// # Arguments
///
/// * `consensus_result` - A `ConsensusSimulationResult` struct containing simulation data.
///
/// # Returns
///
/// * `true` if the copier's cumulative dividends are significantly lower than the adjusted average
/// delegate dividends, and the `epoch_block_sum` is less than `max_encryption_period`.
/// * `false` otherwise, including when `epoch_block_sum` is greater than or equal to
/// `max_encryption_period`.
///
/// # Note
///
/// The function compares `cumulative_copier_divs` against an adjusted
/// `cumulative_avg_delegate_divs`, taking into account the `min_underperf_threshold`.
#[must_use]
pub fn is_copying_irrational<T: pallet_subspace::Config>(
consensus_result: ConsensusSimulationResult<T>,
) -> bool {
if consensus_result.black_box_age >= consensus_result.max_encryption_period {
return true;
impl<T: pallet_subspace::Config> ConsensusSimulationResult<T> {
pub fn update(
&mut self,
yuma_output: YumaOutput<T>,
tempo: u64,
copier_uid: u16,
delegation_fee: Percent,
) {
let avg_delegate_divs = calculate_avg_delegate_divs::<T>(
yuma_output.subnet_id,
&yuma_output.dividends,
copier_uid,
delegation_fee,
)
.into();
let copier_divs = I64F64::from_num(yuma_output.dividends[copier_uid as usize]);

self.cumulative_copier_divs += copier_divs;
self.cumulative_avg_delegate_divs += avg_delegate_divs;
self.black_box_age += tempo;
// TODO:
// make configurable as subnet params
self.max_encryption_period = 3_000; // sample for now
self.min_underperf_threshold = I64F64::from_num(0.1); // sample for now
}
consensus_result.cumulative_copier_divs
< I64F64::from_num(1)
.saturating_sub(consensus_result.min_underperf_threshold)
.saturating_mul(consensus_result.cumulative_avg_delegate_divs)
}
1 change: 1 addition & 0 deletions tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ sp-runtime.workspace = true
sp-arithmetic.workspace = true
bty.workspace = true
log.workspace = true
rand.workspace = true

pallet-governance = { path = "../pallets/governance", features = ["std"] }
pallet-subspace = { path = "../pallets/subspace", features = ["std"] }
Expand Down
55 changes: 0 additions & 55 deletions tests/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -768,60 +768,6 @@ macro_rules! update_params {
}};
}

pub fn calculate_avg_delegate_divs(
netuid: &u16,
dividends: &[u16],
copier_uid: u16,
delegation_fee: Percent,
) -> I64F64 {
let subnet_keys = Uids::<Test>::iter_prefix(netuid).map(|(key, _)| key).collect::<Vec<_>>();
let stakes: Vec<u64> =
subnet_keys.iter().map(|key| SubspaceMod::get_delegated_stake(key)).collect();

let is_valid_div = |&(i, &div): &(usize, &u16)| i != copier_uid as usize && div != 0;

let total_stake: I64F64 = stakes
.iter()
.enumerate()
.filter(|&(i, _)| i != copier_uid as usize)
.map(|(_, &stake)| I64F64::from_num(stake))
.sum();

let total_dividends: I64F64 = dividends
.iter()
.enumerate()
.filter(is_valid_div)
.map(|(_, &div)| I64F64::from_num(div))
.sum();

let average_dividends = total_dividends / total_stake;

let divs_without_fee = average_dividends
* (I64F64::from_num(100 - delegation_fee.deconstruct()) / I64F64::from_num(100));

let copier_stake = I64F64::from_num(stakes[copier_uid as usize]);

divs_without_fee * copier_stake
}

macro_rules! update_consensus_simulation_result {
($result:expr, $yuma_output:expr, $tempo:expr, $copier_uid:expr, $delegation_fee:expr) => {{
let avg_delegate_divs = calculate_avg_delegate_divs(
&$yuma_output.subnet_id,
&$yuma_output.dividends,
$copier_uid,
$delegation_fee,
);
let copier_divs = I64F64::from_num($yuma_output.dividends[$copier_uid as usize]);

$result.cumulative_copier_divs += copier_divs;
$result.cumulative_avg_delegate_divs += avg_delegate_divs;
$result.black_box_age += $tempo;
$result.max_encryption_period = 3_000; // Sample
$result.min_underperf_threshold = I64F64::from_num(0.1); // Sample
}};
}

macro_rules! assert_ok {
( $x:expr $(,)? ) => {
match $x {
Expand All @@ -848,5 +794,4 @@ macro_rules! assert_in_range {

pub(crate) use assert_in_range;
pub(crate) use assert_ok;
pub(crate) use update_consensus_simulation_result;
pub(crate) use update_params;
Loading

0 comments on commit 4fa1b6c

Please sign in to comment.