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

XDM: Close init channels and take protocol fee when channel being closed is in init state #2829

Merged
merged 4 commits into from
Jun 12, 2024
Merged
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
13 changes: 11 additions & 2 deletions crates/pallet-domains/src/block_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ use scale_info::TypeInfo;
use sp_core::Get;
use sp_domains::merkle_tree::MerkleTree;
use sp_domains::{
ChainId, ConfirmedDomainBlock, DomainId, DomainsTransfersTracker, ExecutionReceipt, OperatorId,
Transfers,
ChainId, ConfirmedDomainBlock, DomainId, DomainsTransfersTracker, ExecutionReceipt,
OnChainRewards, OperatorId, Transfers,
};
use sp_runtime::traits::{BlockNumberProvider, CheckedSub, One, Saturating, Zero};
use sp_std::cmp::Ordering;
Expand Down Expand Up @@ -377,6 +377,15 @@ pub(crate) fn process_execution_receipt<T: Config>(
update_domain_transfers::<T>(domain_id, &execution_receipt.transfers, block_fees)
.map_err(|_| Error::DomainTransfersTracking)?;

// handle chain rewards from the domain
execution_receipt
.block_fees
.chain_rewards
.into_iter()
.for_each(|(chain_id, reward)| {
T::OnChainRewards::on_chain_rewards(chain_id, reward)
});

LatestConfirmedDomainBlock::<T>::insert(
domain_id,
ConfirmedDomainBlock {
Expand Down
24 changes: 22 additions & 2 deletions crates/pallet-domains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use crate::domain_registry::Error as DomainRegistryError;
use crate::runtime_registry::into_complete_raw_genesis;
#[cfg(feature = "runtime-benchmarks")]
pub use crate::staking::do_register_operator;
use crate::staking::OperatorStatus;
use crate::staking::{do_reward_operators, OperatorStatus};
use crate::staking_epoch::EpochTransitionResult;
use crate::weights::WeightInfo;
#[cfg(not(feature = "std"))]
Expand Down Expand Up @@ -222,7 +222,7 @@ mod pallet {
use sp_domains::bundle_producer_election::ProofOfElectionError;
use sp_domains::{
BundleDigest, ConfirmedDomainBlock, DomainBundleSubmitted, DomainId,
DomainsTransfersTracker, EpochIndex, GenesisDomain, OnDomainInstantiated,
DomainsTransfersTracker, EpochIndex, GenesisDomain, OnChainRewards, OnDomainInstantiated,
OperatorAllowList, OperatorId, OperatorPublicKey, OperatorSignature, RuntimeId,
RuntimeObject, RuntimeType,
};
Expand Down Expand Up @@ -418,6 +418,9 @@ mod pallet {

/// Fraud proof storage key provider
type FraudProofStorageKeyProvider: FraudProofStorageKeyProvider;

/// Hook to handle chain rewards.
type OnChainRewards: OnChainRewards<BalanceOf<Self>>;
}

#[pallet::pallet]
Expand Down Expand Up @@ -2379,6 +2382,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>) {
// 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);
}
}

#[cfg(not(feature = "runtime-benchmarks"))]
fn actual_slash_operator_weight(slashed_nominators: u32) -> Weight {
T::WeightInfo::slash_operator(slashed_nominators)
Expand Down Expand Up @@ -2485,6 +2500,11 @@ impl<T: Config> Pallet<T> {

Ok(leaf_data.state_root())
}

/// Returns true if the Domain is registered.
pub fn is_domain_registered(domain_id: DomainId) -> bool {
DomainStakingSummary::<T>::contains_key(domain_id)
}
}

impl<T: Config> sp_domains::DomainOwner<T::AccountId> for Pallet<T> {
Expand Down
1 change: 1 addition & 0 deletions crates/pallet-domains/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ impl pallet_domains::Config for Test {
type MmrHash = H256;
type MmrProofVerifier = ();
type FraudProofStorageKeyProvider = ();
type OnChainRewards = ();
}

pub struct ExtrinsicStorageFees;
Expand Down
15 changes: 15 additions & 0 deletions crates/sp-domains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,10 @@ pub struct BlockFees<Balance> {
pub domain_execution_fee: Balance,
/// Burned balances on domain chain
pub burned_balance: Balance,
/// Rewards for the chain.
// TODO: remove this before mainnet. Skipping to maintain compatibility with Gemini
#[codec(skip)]
pub chain_rewards: BTreeMap<ChainId, Balance>,
}

impl<Balance> BlockFees<Balance>
Expand All @@ -289,11 +293,13 @@ where
domain_execution_fee: Balance,
consensus_storage_fee: Balance,
burned_balance: Balance,
chain_rewards: BTreeMap<ChainId, Balance>,
) -> Self {
BlockFees {
consensus_storage_fee,
domain_execution_fee,
burned_balance,
chain_rewards,
}
}

Expand Down Expand Up @@ -1393,6 +1399,15 @@ pub struct OperatorSigningKeyProofOfOwnershipData<AccountId> {
pub operator_owner: AccountId,
}

/// Hook to handle chain rewards.
pub trait OnChainRewards<Balance> {
fn on_chain_rewards(chain_id: ChainId, reward: Balance);
}

impl<Balance> OnChainRewards<Balance> for () {
fn on_chain_rewards(_chain_id: ChainId, _reward: Balance) {}
}

sp_api::decl_runtime_apis! {
/// API necessary for domains pallet.
#[api_version(4)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,12 @@ where

match bad_receipt_type {
BadReceiptType::BlockFees => {
receipt.block_fees =
BlockFees::new(random_seed.into(), random_seed.into(), random_seed.into());
receipt.block_fees = BlockFees::new(
random_seed.into(),
random_seed.into(),
random_seed.into(),
BTreeMap::default(),
);
}
BadReceiptType::Transfers => {
receipt.transfers.transfers_in =
Expand Down
36 changes: 35 additions & 1 deletion crates/subspace-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ use sp_runtime::traits::{
};
use sp_runtime::transaction_validity::{TransactionSource, TransactionValidity};
use sp_runtime::{
create_runtime_str, generic, AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode,
create_runtime_str, generic, AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill,
};
use sp_std::collections::btree_map::BTreeMap;
use sp_std::marker::PhantomData;
Expand Down Expand Up @@ -450,6 +450,14 @@ impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
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, fees)
}
}
}

pub struct MmrProofVerifier;
Expand Down Expand Up @@ -507,6 +515,14 @@ impl sp_messenger::StorageKeys for StorageKeys {
parameter_types! {
// TODO: update value
pub const ChannelReserveFee: Balance = 100 * SSC;
pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
}

pub struct DomainRegistration;
impl sp_messenger::DomainRegistration for DomainRegistration {
fn is_domain_registered(domain_id: DomainId) -> bool {
Domains::is_domain_registered(domain_id)
}
}

impl pallet_messenger::Config for Runtime {
Expand All @@ -531,6 +547,8 @@ impl pallet_messenger::Config for Runtime {
type DomainOwner = Domains;
type HoldIdentifier = HoldIdentifier;
type ChannelReserveFee = ChannelReserveFee;
type ChannelInitReservePortion = ChannelInitReservePortion;
type DomainRegistration = DomainRegistration;
}

impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
Expand Down Expand Up @@ -627,6 +645,21 @@ impl pallet_domains::BlockSlot<Runtime> for BlockSlot {
}
}

pub struct OnChainRewards;

impl sp_domains::OnChainRewards<Balance> for OnChainRewards {
fn on_chain_rewards(chain_id: ChainId, reward: Balance) {
match chain_id {
ChainId::Consensus => {
if let Some(block_author) = Subspace::find_block_reward_address() {
let _ = Balances::deposit_creating(&block_author, reward);
}
}
ChainId::Domain(domain_id) => Domains::reward_domain_operators(domain_id, reward),
}
}
}

impl pallet_domains::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type DomainHash = DomainHash;
Expand Down Expand Up @@ -666,6 +699,7 @@ impl pallet_domains::Config for Runtime {
type MmrHash = mmr::Hash;
type MmrProofVerifier = MmrProofVerifier;
type FraudProofStorageKeyProvider = StorageKeyProvider;
type OnChainRewards = OnChainRewards;
}

parameter_types! {
Expand Down
13 changes: 12 additions & 1 deletion domains/pallets/block-fees/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ mod pallet {
use frame_system::pallet_prelude::*;
use scale_info::TypeInfo;
use sp_block_fees::{InherentError, InherentType, INHERENT_IDENTIFIER};
use sp_domains::BlockFees;
use sp_domains::{BlockFees, ChainId};
use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize, Saturating};
use sp_runtime::{FixedPointOperand, SaturatedConversion};
use sp_std::fmt::Debug;
Expand Down Expand Up @@ -194,6 +194,17 @@ mod pallet {
});
}

/// Note chain reward fees.
pub fn note_chain_rewards(chain_id: ChainId, balance: T::Balance) {
CollectedBlockFees::<T>::mutate(|block_fees| {
let total_balance = match block_fees.chain_rewards.get(&chain_id) {
None => balance,
Some(prev_balance) => prev_balance.saturating_add(balance),
};
block_fees.chain_rewards.insert(chain_id, total_balance)
});
}

/// Return the final domain transaction byte fee, which consist of:
/// - The `ConsensusChainByteFee` for the consensus chain storage cost since the domain
/// transaction need to be bundled and submitted to the consensus chain first.
Expand Down
8 changes: 7 additions & 1 deletion domains/pallets/messenger/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ mod benchmarks {
dst_chain_id,
dummy_channel_params::<T>(),
None,
true,
));
let channel = Channels::<T>::get(dst_chain_id, channel_id).expect("channel should exist");
assert_eq!(channel.state, ChannelState::Initiated);
Expand Down Expand Up @@ -248,7 +249,12 @@ mod benchmarks {
let channel_id = NextChannelId::<T>::get(dst_chain_id);
let list = BTreeSet::from([dst_chain_id]);
ChainAllowlist::<T>::put(list);
assert_ok!(Messenger::<T>::do_init_channel(dst_chain_id, params, None));
assert_ok!(Messenger::<T>::do_init_channel(
dst_chain_id,
params,
None,
true
));
let channel = Channels::<T>::get(dst_chain_id, channel_id).expect("channel should exist");
assert_eq!(channel.state, ChannelState::Initiated);

Expand Down
Loading
Loading