Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add source to the OperatorRewarded event #3136

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
15 changes: 11 additions & 4 deletions crates/pallet-domains/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ use sp_core::crypto::{Ss58Codec, UncheckedFrom};
use sp_core::ByteArray;
use sp_domains::{
dummy_opaque_bundle, BlockFees, DomainId, ExecutionReceipt, OperatorAllowList, OperatorId,
OperatorPublicKey, OperatorSignature, PermissionedActionAllowedBy, ProofOfElection,
RuntimeType, SealedSingletonReceipt, SingletonReceipt, Transfers,
OperatorPublicKey, OperatorRewardSource, OperatorSignature, PermissionedActionAllowedBy,
ProofOfElection, RuntimeType, SealedSingletonReceipt, SingletonReceipt, Transfers,
};
use sp_domains_fraud_proof::fraud_proof::FraudProof;
use sp_runtime::traits::{CheckedAdd, One, Zero};
Expand Down Expand Up @@ -286,6 +286,7 @@ mod benchmarks {

do_reward_operators::<T>(
domain_id,
OperatorRewardSource::Dummy,
operator_ids[..n as usize].to_vec().into_iter(),
operator_rewards,
)
Expand Down Expand Up @@ -337,6 +338,7 @@ mod benchmarks {

do_reward_operators::<T>(
domain_id,
OperatorRewardSource::Dummy,
operator_ids.clone().into_iter(),
operator_rewards,
)
Expand Down Expand Up @@ -449,8 +451,13 @@ mod benchmarks {
}
assert_eq!(PendingStakingOperationCount::<T>::get(domain_id), p);

do_reward_operators::<T>(domain_id, operator_ids.into_iter(), operator_rewards)
.expect("reward operator should success");
do_reward_operators::<T>(
domain_id,
OperatorRewardSource::Dummy,
operator_ids.into_iter(),
operator_rewards,
)
.expect("reward operator should success");

let epoch_index = DomainStakingSummary::<T>::get(domain_id)
.expect("staking summary must exist")
Expand Down
10 changes: 7 additions & 3 deletions crates/pallet-domains/src/block_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,8 @@ pub(crate) fn verify_execution_receipt<T: Config>(

/// Details of the confirmed domain block such as operators, rewards they would receive.
#[derive(Debug, PartialEq)]
pub(crate) struct ConfirmedDomainBlockInfo<DomainNumber, Balance> {
pub(crate) struct ConfirmedDomainBlockInfo<ConsensusNumber, DomainNumber, Balance> {
pub consensus_block_number: ConsensusNumber,
pub domain_block_number: DomainNumber,
pub operator_ids: Vec<OperatorId>,
pub rewards: Balance,
Expand All @@ -327,8 +328,10 @@ pub(crate) struct ConfirmedDomainBlockInfo<DomainNumber, Balance> {
pub paid_bundle_storage_fees: BTreeMap<OperatorId, u32>,
}

pub(crate) type ProcessExecutionReceiptResult<T> =
Result<Option<ConfirmedDomainBlockInfo<DomainBlockNumberFor<T>, BalanceOf<T>>>, Error>;
pub(crate) type ProcessExecutionReceiptResult<T> = Result<
Option<ConfirmedDomainBlockInfo<BlockNumberFor<T>, DomainBlockNumberFor<T>, BalanceOf<T>>>,
Error,
>;

/// Process the execution receipt to add it to the block tree
/// Returns the domain block number that was pruned, if any
Expand Down Expand Up @@ -429,6 +432,7 @@ pub(crate) fn process_execution_receipt<T: Config>(
});

return Ok(Some(ConfirmedDomainBlockInfo {
consensus_block_number: execution_receipt.consensus_block_number,
domain_block_number: to_prune,
operator_ids,
rewards: execution_receipt.block_fees.domain_execution_fee,
Expand Down
22 changes: 17 additions & 5 deletions crates/pallet-domains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ use sp_core::H256;
use sp_domains::bundle_producer_election::BundleProducerElectionParams;
use sp_domains::{
DomainBundleLimit, DomainId, DomainInstanceData, ExecutionReceipt, OpaqueBundle, OperatorId,
OperatorPublicKey, OperatorSignature, ProofOfElection, RuntimeId, SealedSingletonReceipt,
DOMAIN_EXTRINSICS_SHUFFLING_SEED_SUBJECT, EMPTY_EXTRINSIC_ROOT,
OperatorPublicKey, OperatorRewardSource, OperatorSignature, ProofOfElection, RuntimeId,
SealedSingletonReceipt, DOMAIN_EXTRINSICS_SHUFFLING_SEED_SUBJECT, EMPTY_EXTRINSIC_ROOT,
};
use sp_domains_fraud_proof::fraud_proof::{
DomainRuntimeCodeAt, FraudProof, FraudProofVariant, InvalidBlockFeesProof,
Expand Down Expand Up @@ -231,7 +231,8 @@ mod pallet {
use sp_domains::{
BundleDigest, DomainBundleSubmitted, DomainId, DomainSudoCall, DomainsTransfersTracker,
EpochIndex, GenesisDomain, OnChainRewards, OnDomainInstantiated, OperatorAllowList,
OperatorId, OperatorPublicKey, OperatorSignature, RuntimeId, RuntimeObject, RuntimeType,
OperatorId, OperatorPublicKey, OperatorRewardSource, OperatorSignature, RuntimeId,
RuntimeObject, RuntimeType,
};
use sp_domains_fraud_proof::fraud_proof_runtime_interface::domain_runtime_call;
use sp_domains_fraud_proof::storage_proof::{self, FraudProofStorageKeyProvider};
Expand Down Expand Up @@ -976,6 +977,7 @@ mod pallet {
nominator_id: NominatorId<T>,
},
OperatorRewarded {
source: OperatorRewardSource<BlockNumberFor<T>>,
operator_id: OperatorId,
reward: BalanceOf<T>,
},
Expand Down Expand Up @@ -1134,6 +1136,9 @@ mod pallet {

do_reward_operators::<T>(
domain_id,
OperatorRewardSource::Bundle {
at_block_number: confirmed_block_info.consensus_block_number,
},
confirmed_block_info.operator_ids.into_iter(),
confirmed_block_info.rewards,
)
Expand Down Expand Up @@ -1749,6 +1754,9 @@ mod pallet {

do_reward_operators::<T>(
domain_id,
OperatorRewardSource::Bundle {
at_block_number: confirmed_block_info.consensus_block_number,
},
confirmed_block_info.operator_ids.into_iter(),
confirmed_block_info.rewards,
)
Expand Down Expand Up @@ -2833,14 +2841,18 @@ impl<T: Config> Pallet<T> {
}

/// Reward the active operators of this domain epoch.
pub fn reward_domain_operators(domain_id: DomainId, rewards: BalanceOf<T>) {
pub fn reward_domain_operators(
domain_id: DomainId,
source: OperatorRewardSource<BlockNumberFor<T>>,
rewards: BalanceOf<T>,
) {
// If domain is not instantiated, then we don't care at the moment.
if let Some(domain_stake_summary) = DomainStakingSummary::<T>::get(domain_id) {
let operators = domain_stake_summary
.current_epoch_rewards
.into_keys()
.collect::<Vec<OperatorId>>();
let _ = do_reward_operators::<T>(domain_id, operators.into_iter(), rewards);
let _ = do_reward_operators::<T>(domain_id, source, operators.into_iter(), rewards);
}
}

Expand Down
26 changes: 20 additions & 6 deletions crates/pallet-domains/src/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ use codec::{Decode, Encode};
use frame_support::traits::fungible::{Inspect, MutateHold};
use frame_support::traits::tokens::{Fortitude, Precision, Preservation};
use frame_support::{ensure, PalletError};
use frame_system::pallet_prelude::BlockNumberFor;
use scale_info::TypeInfo;
use sp_core::{sr25519, Get};
use sp_domains::{
DomainId, EpochIndex, OperatorId, OperatorPublicKey, OperatorSignature,
DomainId, EpochIndex, OperatorId, OperatorPublicKey, OperatorRewardSource, OperatorSignature,
OperatorSigningKeyProofOfOwnershipData,
};
use sp_runtime::traits::{CheckedAdd, CheckedSub, Zero};
Expand Down Expand Up @@ -1327,6 +1328,7 @@ pub(crate) fn do_cleanup_operator<T: Config>(
/// Distribute the reward to the operators equally and drop any dust to treasury.
pub(crate) fn do_reward_operators<T: Config>(
domain_id: DomainId,
source: OperatorRewardSource<BlockNumberFor<T>>,
operators: IntoIter<OperatorId>,
rewards: BalanceOf<T>,
) -> Result<(), Error> {
Expand Down Expand Up @@ -1374,6 +1376,7 @@ pub(crate) fn do_reward_operators<T: Config>(
.insert(operator_id, total_reward);

Pallet::<T>::deposit_event(Event::OperatorRewarded {
source: source.clone(),
operator_id,
reward: operator_reward,
});
Expand Down Expand Up @@ -1470,7 +1473,7 @@ pub(crate) mod tests {
use sp_core::{sr25519, Pair, U256};
use sp_domains::{
BlockFees, DomainId, OperatorAllowList, OperatorId, OperatorPair, OperatorPublicKey,
OperatorSignature, Transfers,
OperatorRewardSource, OperatorSignature, Transfers,
};
use sp_runtime::traits::Zero;
use sp_runtime::{PerThing, Perbill};
Expand Down Expand Up @@ -2018,6 +2021,7 @@ pub(crate) mod tests {
if !operator_reward.is_zero() {
do_reward_operators::<Test>(
domain_id,
OperatorRewardSource::Dummy,
vec![operator_id].into_iter(),
operator_reward,
)
Expand Down Expand Up @@ -2865,8 +2869,13 @@ pub(crate) mod tests {
.unwrap();
}

do_reward_operators::<Test>(domain_id, vec![operator_id].into_iter(), 20 * SSC)
.unwrap();
do_reward_operators::<Test>(
domain_id,
OperatorRewardSource::Dummy,
vec![operator_id].into_iter(),
20 * SSC,
)
.unwrap();
do_finalize_domain_current_epoch::<Test>(domain_id).unwrap();

// Manually convert previous withdrawal in share to balance
Expand Down Expand Up @@ -3024,8 +3033,13 @@ pub(crate) mod tests {
.unwrap();
}

do_reward_operators::<Test>(domain_id, vec![operator_id].into_iter(), 20 * SSC)
.unwrap();
do_reward_operators::<Test>(
domain_id,
OperatorRewardSource::Dummy,
vec![operator_id].into_iter(),
20 * SSC,
)
.unwrap();
do_finalize_domain_current_epoch::<Test>(domain_id).unwrap();

// Manually convert previous withdrawal in share to balance
Expand Down
30 changes: 23 additions & 7 deletions crates/pallet-domains/src/staking_epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,8 @@ mod tests {
use frame_support::traits::fungible::InspectHold;
use sp_core::{Pair, U256};
use sp_domains::{
BlockFees, DomainId, OperatorPair, OperatorSigningKeyProofOfOwnershipData, Transfers,
BlockFees, DomainId, OperatorPair, OperatorRewardSource,
OperatorSigningKeyProofOfOwnershipData, Transfers,
};
use sp_runtime::traits::Zero;
use sp_runtime::{PerThing, Percent};
Expand Down Expand Up @@ -605,8 +606,13 @@ mod tests {
}

if !rewards.is_zero() {
do_reward_operators::<Test>(domain_id, vec![operator_id].into_iter(), rewards)
.unwrap()
do_reward_operators::<Test>(
domain_id,
OperatorRewardSource::Dummy,
vec![operator_id].into_iter(),
rewards,
)
.unwrap()
}

// de-register operator
Expand Down Expand Up @@ -770,8 +776,13 @@ mod tests {
}

if !rewards.is_zero() {
do_reward_operators::<Test>(domain_id, vec![operator_id].into_iter(), rewards)
.unwrap();
do_reward_operators::<Test>(
domain_id,
OperatorRewardSource::Dummy,
vec![operator_id].into_iter(),
rewards,
)
.unwrap();
}

do_finalize_domain_current_epoch::<Test>(domain_id).unwrap();
Expand Down Expand Up @@ -864,8 +875,13 @@ mod tests {
Operators::<Test>::insert(operator_id, operator);
let expected_operator_tax = nomination_tax.mul_ceil(operator_rewards);

do_reward_operators::<Test>(domain_id, vec![operator_id].into_iter(), operator_rewards)
.unwrap();
do_reward_operators::<Test>(
domain_id,
OperatorRewardSource::Dummy,
vec![operator_id].into_iter(),
operator_rewards,
)
.unwrap();

operator_take_reward_tax_and_stake::<Test>(domain_id).unwrap();
let operator = Operators::<Test>::get(operator_id).unwrap();
Expand Down
10 changes: 10 additions & 0 deletions crates/sp-domains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,16 @@ impl<Balance> OnChainRewards<Balance> for () {
fn on_chain_rewards(_chain_id: ChainId, _reward: Balance) {}
}

#[derive(Debug, Decode, Encode, TypeInfo, PartialEq, Eq, Clone)]
pub enum OperatorRewardSource<Number> {
Bundle {
at_block_number: Number,
},
XDMProtocolFees,
#[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
Copy link
Contributor

Choose a reason for hiding this comment

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

It seems like this dummy is only used in tests and benchmarks, so I’m not sure we want it enabled for all std code?

Suggested change
#[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
#[cfg(any(test, feature = "runtime-benchmarks"))]

Copy link
Member Author

Choose a reason for hiding this comment

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

I considered using test but interestingly it doesn't compile...

Copy link
Contributor

Choose a reason for hiding this comment

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

That’s concerning, because I can only see Dummy used inside test and feature = "runtime-benchmarks" in this PR. So #[cfg(any(test, feature = "runtime-benchmarks"))] should be enough to make it compile.

What’s the exact compile error?
Is that something you can check, or would you like me to?

Copy link
Contributor

Choose a reason for hiding this comment

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

Oh, I see why this happens. subspace-test-service is compiled as a production binary, not a #![cfg(test)] binary.

We could fix this by adding a new feature to sp-domains, and making the test crates depend on it.

Dummy,
}

sp_api::decl_runtime_apis! {
/// API necessary for domains pallet.
pub trait DomainsApi<DomainHeader: HeaderT> {
Expand Down
11 changes: 8 additions & 3 deletions crates/subspace-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ use sp_core::{ConstBool, OpaqueMetadata, H256};
use sp_domains::bundle_producer_election::BundleProducerElectionParams;
use sp_domains::{
ChannelId, DomainAllowlistUpdates, DomainId, DomainInstanceData, ExecutionReceiptFor,
OperatorId, OperatorPublicKey, DOMAIN_STORAGE_FEE_MULTIPLIER, INITIAL_DOMAIN_TX_RANGE,
OperatorId, OperatorPublicKey, OperatorRewardSource, DOMAIN_STORAGE_FEE_MULTIPLIER,
INITIAL_DOMAIN_TX_RANGE,
};
use sp_domains_fraud_proof::fraud_proof::FraudProof;
use sp_domains_fraud_proof::storage_proof::{
Expand Down Expand Up @@ -590,7 +591,7 @@ impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
// on consensus chain, reward the domain operators
// balance is already on this consensus runtime
if let ChainId::Domain(domain_id) = chain_id {
Domains::reward_domain_operators(domain_id, fees)
Domains::reward_domain_operators(domain_id, OperatorRewardSource::XDMProtocolFees, fees)
}
}
}
Expand Down Expand Up @@ -793,7 +794,11 @@ impl sp_domains::OnChainRewards<Balance> for OnChainRewards {
let _ = Balances::deposit_creating(&block_author, reward);
}
}
ChainId::Domain(domain_id) => Domains::reward_domain_operators(domain_id, reward),
ChainId::Domain(domain_id) => Domains::reward_domain_operators(
domain_id,
OperatorRewardSource::XDMProtocolFees,
reward,
),
}
}
}
Expand Down
30 changes: 26 additions & 4 deletions test/subspace-test-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ use sp_core::{OpaqueMetadata, H256};
use sp_domains::bundle_producer_election::BundleProducerElectionParams;
use sp_domains::{
DomainAllowlistUpdates, DomainId, DomainInstanceData, ExecutionReceiptFor, OpaqueBundle,
OpaqueBundles, OperatorId, OperatorPublicKey, DOMAIN_STORAGE_FEE_MULTIPLIER,
INITIAL_DOMAIN_TX_RANGE,
OpaqueBundles, OperatorId, OperatorPublicKey, OperatorRewardSource,
DOMAIN_STORAGE_FEE_MULTIPLIER, INITIAL_DOMAIN_TX_RANGE,
};
use sp_domains_fraud_proof::fraud_proof::FraudProof;
use sp_domains_fraud_proof::storage_proof::{
Expand Down Expand Up @@ -603,6 +603,24 @@ parameter_types! {
pub const ChannelFeeModel: FeeModel<Balance> = FeeModel{relay_fee: SSC};
}

pub struct OnXDMRewards;

impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
fn on_xdm_rewards(reward: Balance) {
if let Some(block_author) = Subspace::find_block_reward_address() {
let _ = Balances::deposit_creating(&block_author, reward);
}
}

fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
// on consensus chain, reward the domain operators
// balance is already on this consensus runtime
if let ChainId::Domain(domain_id) = chain_id {
Domains::reward_domain_operators(domain_id, OperatorRewardSource::XDMProtocolFees, fees)
}
}
}

impl pallet_messenger::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type SelfChainId = SelfChainId;
Expand All @@ -618,7 +636,7 @@ impl pallet_messenger::Config for Runtime {
type Currency = Balances;
type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
type OnXDMRewards = ();
type OnXDMRewards = OnXDMRewards;
type MmrHash = mmr::Hash;
type MmrProofVerifier = MmrProofVerifier;
type StorageKeys = StorageKeys;
Expand Down Expand Up @@ -719,7 +737,11 @@ impl sp_domains::OnChainRewards<Balance> for OnChainRewards {
let _ = Balances::deposit_creating(&block_author, reward);
}
}
ChainId::Domain(domain_id) => Domains::reward_domain_operators(domain_id, reward),
ChainId::Domain(domain_id) => Domains::reward_domain_operators(
domain_id,
OperatorRewardSource::XDMProtocolFees,
reward,
),
}
}
}
Expand Down
Loading