Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions pallets/game/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -994,6 +994,13 @@ pub mod benches {
);
let mut iterator = Players::<T>::iter_from_key(target_player.clone());
let mut credits_awarded = 0;
// Worst case: the player moves to a next limit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the weights need a regen for this.

let granted = T::PlayerStatementLimit::get();
let next = granted.clone().saturating_add(StatementAllowance::new(1, 1));
PlayerStatementLimits::<T>::put(PlayerStatementLimitsRecord {
granted: granted.into(),
next: Some(next.into()),
});

#[block]
{
Expand Down
124 changes: 106 additions & 18 deletions pallets/game/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,16 @@
//! All players in the game are given some statement store usage allowance. The player's allowance
//! is cleared and their statements removed when archived or offboarded.
//!
//! Every live player holds [`PlayerStatementLimitsRecord::granted`]. The statement store sums the
//! grants of all pallets per account, so a revocation uses the granted amount, not the current
//! `PlayerStatementLimit`. The player processing of the next game moves every live player to a
//! changed `PlayerStatementLimit`. Until then, new players get the previous limit.
Comment thread
agustinustheo marked this conversation as resolved.
Resolved
//! The pallet accepts no sign-up, offboard, statement account change or game cancellation
//! during player processing, so one record covers every live player.
//!
//! A `PlayerStatementLimit` with a zero dimension grants zero. The statement store deletes such
//! an allowance, so a later revocation of the other dimension would reduce the restored limit.
//!
//! # NFT claim credits
//!
//! A player earns one credit per successful report of one player on another, in one round of one
Expand Down Expand Up @@ -338,6 +348,7 @@ use indiv_pallet_score::AccountOrPerson;
use indiv_support::{
credit_trees::AwardCredits,
offchain::{submit_authorized, TX_LONGEVITY},
statement_allowance::BoundedStatementAllowance,
traits::{Alias, CommunicationIdentifier, Context},
tx_priority,
weight_budget::OcwWeightBudget,
Expand Down Expand Up @@ -393,7 +404,7 @@ pub mod pallet {
pub const PRODUCT_NAME: &[u8] = b"dim2";

/// The current storage version.
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);

#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
Expand Down Expand Up @@ -779,6 +790,13 @@ pub mod pallet {
pub(crate) type StmtAccountToAlias<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, Alias>;

/// The statement allowances that the pallet grants to live players.
///
/// It is unset only while no player holds an allowance. The first grant then stores the
/// current `PlayerStatementLimit`.
#[pallet::storage]
pub type PlayerStatementLimits<T: Config> = StorageValue<_, PlayerStatementLimitsRecord>;

/// The communication identifiers used by players to establish an encrypted P2P connection in
/// order to play the game. The account under which the communication identifier is registered
/// should be the same account used to interact with the statement store.
Expand Down Expand Up @@ -1562,10 +1580,7 @@ pub mod pallet {

if let Some(stmt_account) = stmt_account {
if player_is_offboarding {
decrease_allowance_by(
stmt_account.clone().into(),
T::PlayerStatementLimit::get(),
);
Self::revoke_player_allowance(&stmt_account);
}
Self::deposit_event(Event::<T>::StmtUsageRemoved { who: stmt_account.into() });
}
Expand Down Expand Up @@ -2782,6 +2797,69 @@ pub mod pallet {
Self::deposit_event(Event::<T>::GameCancelled { game_index: game.index, reason });
}

/// Return `PlayerStatementLimit`, or zero when one of its dimensions is zero.
fn player_statement_limit() -> BoundedStatementAllowance {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe let's rename this function, it is too close to player_statement_limits I think we should avoid using it directly, so we can make the name more in this direction, like dynamic_player_statement_limit.

let limit = T::PlayerStatementLimit::get();
if limit.is_depleted() {
BoundedStatementAllowance::default()
} else {
limit.into()
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we should fix sp-statement-store to not remove when one dimension is non-zero. this looks like a very tricky API.


/// Return [`PlayerStatementLimits`], or [`Self::player_statement_limit`] when unset.
pub(crate) fn player_statement_limits() -> PlayerStatementLimitsRecord {
PlayerStatementLimits::<T>::get().unwrap_or_else(|| PlayerStatementLimitsRecord {
granted: Self::player_statement_limit(),
next: None,
})
}

/// Grant [`PlayerStatementLimitsRecord::granted`] to `account`.
///
/// Store [`PlayerStatementLimits`] when unset, so revocations use the same amount.
fn grant_player_allowance(account: &T::AccountId) {
let granted = PlayerStatementLimits::<T>::get()
.unwrap_or_else(|| {
let limits = PlayerStatementLimitsRecord {
granted: Self::player_statement_limit(),
next: None,
};
PlayerStatementLimits::<T>::put(&limits);
limits
})
.granted;
increase_allowance_by(account.clone().into(), granted.into());
}

fn revoke_player_allowance(account: &T::AccountId) {
let granted = Self::player_statement_limits().granted;
decrease_allowance_by(account.clone().into(), granted.into());
}

/// Move the allowance of `player_id` from [`PlayerStatementLimitsRecord::granted`] to
/// [`PlayerStatementLimitsRecord::next`], if set.
///
/// Grant before revoking: the statement store removes the whole allowance of an account
/// when one dimension reaches zero.
fn update_player_allowance(player_id: &AccountOrPerson<T::AccountId>) {
let PlayerStatementLimitsRecord { granted, next: Some(next) } =
Self::player_statement_limits()
else {
return;
};
let stmt_account = match player_id {
AccountOrPerson::Person(alias) => AliasToStmtAccount::<T>::get(alias)
.defensive_proof(
"indiv-pallet-game: alias player must have a statement account",
),
AccountOrPerson::Account(account) => Some(account.clone()),
};
let Some(stmt_account) = stmt_account else { return };
increase_allowance_by(stmt_account.clone().into(), next.into());
decrease_allowance_by(stmt_account.into(), granted.into());
}

/// **Warning**: Storage must be rollbacked on error.
fn sign_up_inner(
args: SignUpArgs<T::AccountId, T::AccountSignature, AirdropProofOf<T>>,
Expand Down Expand Up @@ -2816,10 +2894,7 @@ pub mod pallet {
if prev_stmt_account != Some(statement_account.clone()) {
if let Some(prev_stmt_account) = prev_stmt_account {
StmtAccountToAlias::<T>::remove(&prev_stmt_account);
decrease_allowance_by(
prev_stmt_account.clone().into(),
T::PlayerStatementLimit::get(),
);
Self::revoke_player_allowance(&prev_stmt_account);
Self::deposit_event(Event::<T>::StmtUsageRemoved {
who: prev_stmt_account.into(),
});
Expand All @@ -2838,10 +2913,7 @@ pub mod pallet {

StmtAccountToAlias::<T>::insert(&statement_account, who);
AliasToStmtAccount::<T>::insert(who, &statement_account);
increase_allowance_by(
statement_account.clone().into(),
T::PlayerStatementLimit::get(),
);
Self::grant_player_allowance(&statement_account);
}
CommunicationIdentifiers::<T>::insert(&statement_account, identifier_key);

Expand Down Expand Up @@ -2915,7 +2987,7 @@ pub mod pallet {
// An account-identified player gets allowance when signed up
if !already_playing {
if let Some(account) = who.account() {
increase_allowance_by(account.clone().into(), T::PlayerStatementLimit::get());
Self::grant_player_allowance(account);
}
}

Expand Down Expand Up @@ -3720,10 +3792,7 @@ pub mod pallet {
};

if let Some(stmt_account) = stmt_account {
decrease_allowance_by(
stmt_account.clone().into(),
T::PlayerStatementLimit::get(),
);
Self::revoke_player_allowance(&stmt_account);
Self::deposit_event(Event::<T>::StmtUsageRemoved { who: stmt_account.into() });
}

Expand All @@ -3749,6 +3818,7 @@ pub mod pallet {
credibility => credibility,
};

Self::update_player_allowance(&player_id);
Players::<T>::insert(
&player_id,
Player {
Expand Down Expand Up @@ -3796,6 +3866,15 @@ pub mod pallet {
return;
};

if last_iteration.is_none() {
let limits = Self::player_statement_limits();
let limit = Self::player_statement_limit();
let next = (limit != limits.granted).then_some(limit);
if next != limits.next {
PlayerStatementLimits::<T>::put(PlayerStatementLimitsRecord { next, ..limits });
}
}

@gui1117 gui1117 Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we could move it into its own function and the code at the end too, then we write down on top of PlayerStatementLimits that is must never be read/write directly but instead use the manager in the module player_statement_limit::PlayerStatementLimitManager. and put all those functions there. Similar to coinage and recycler_manager::RecyclerManager.

But also it is ok as it is.


let mut iterator = match last_iteration.clone() {
None => Players::<T>::iter(),
Some(last) => Players::<T>::iter_from_key(last),
Expand Down Expand Up @@ -3849,6 +3928,15 @@ pub mod pallet {
"indiv-pallet-game: session was started before the process players phase",
);

if let Some(PlayerStatementLimitsRecord { next: Some(next), .. }) =
PlayerStatementLimits::<T>::get()
{
PlayerStatementLimits::<T>::put(PlayerStatementLimitsRecord {
granted: next,
next: None,
});
}

game.state =
GameState::PlayerProcess { step: PlayerProcessStep::Step2ClearIndices };
}
Expand Down
39 changes: 39 additions & 0 deletions pallets/game/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ extern crate alloc;

use crate::{
Config, Game, GameAirdrop, GameIdx, GameInfo, GameSchedule, GameSchedules, GameState, Pallet,
PlayerStatementLimits, PlayerStatementLimitsRecord,
};
use alloc::vec::Vec;
use frame_support::{
migrations::VersionedMigration, pallet_prelude::*, storage_alias,
traits::UncheckedOnRuntimeUpgrade,
};
use sp_statement_store::StatementAllowance;

const LOG_TARGET: &str = "runtime::game::migration";

Expand Down Expand Up @@ -172,3 +174,40 @@ pub mod v1 {
}
}
}

/// Stores `Granted` as [`PlayerStatementLimitsRecord::granted`].
///
/// `Granted` must be the allowance that live players hold before the upgrade.
pub type MigrateV1ToV2<T, Granted> = VersionedMigration<
1,
2,
v2::InitialisePlayerStatementLimits<T, Granted>,
Pallet<T>,
<T as frame_system::Config>::DbWeight,
>;

pub mod v2 {
use super::*;

/// Use [`super::MigrateV1ToV2`] rather than this directly.
pub struct InitialisePlayerStatementLimits<T, Granted>(PhantomData<(T, Granted)>);

impl<T: Config, Granted: Get<StatementAllowance>> UncheckedOnRuntimeUpgrade
for InitialisePlayerStatementLimits<T, Granted>
{
fn on_runtime_upgrade() -> Weight {
PlayerStatementLimits::<T>::put(PlayerStatementLimitsRecord {
granted: Granted::get().into(),
next: None,
});
log::info!(target: LOG_TARGET, "initialised PlayerStatementLimits");
T::DbWeight::get().writes(1)
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
ensure!(PlayerStatementLimits::<T>::exists(), "PlayerStatementLimits is not set");
Ok(())
}
}
}
2 changes: 1 addition & 1 deletion pallets/game/src/mock_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ impl pallet_assets_holder::Config for Test {
}

parameter_types! {
pub PlayerStatementLimit: StatementAllowance = StatementAllowance {
pub storage PlayerStatementLimit: StatementAllowance = StatementAllowance {
max_size: 1000,
max_count: 1000,
};
Expand Down
Loading
Loading