Skip to content

Commit

Permalink
Mutable contract address (#1548)
Browse files Browse the repository at this point in the history
* Mutable contract address

* Update account id type

* Remove dbg

* Fix tests

* Fix benchmark
  • Loading branch information
AurevoirXavier authored Jul 25, 2024
1 parent ea5784a commit 06a70ad
Show file tree
Hide file tree
Showing 20 changed files with 434 additions and 248 deletions.
3 changes: 2 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion pallet/account-migration/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ impl darwinia_staking::Config for Runtime {
type Deposit = Deposit;
type IssuingManager = ();
type Kton = Dummy;
type KtonRewardDistributionContract = ();
type KtonStakerNotifier = ();
type MaxDeposits = ();
type Ring = Dummy;
Expand Down
7 changes: 4 additions & 3 deletions pallet/staking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ log = { workspace = true }
scale-info = { workspace = true }

# darwinia
darwinia-ethtx-forwarder = { workspace = true }
darwinia-staking-traits = { workspace = true }
dc-types = { workspace = true }
darwinia-ethtx-forwarder = { workspace = true }
darwinia-staking-traits = { workspace = true }
dc-primitives = { workspace = true }
# darwinia optional
darwinia-deposit = { workspace = true, optional = true }

Expand Down Expand Up @@ -61,6 +61,7 @@ std = [
# darwinia
"darwinia-ethtx-forwarder/std",
"darwinia-staking-traits/std",
"dc-primitives/std",
# darwinia optional
"darwinia-deposit?/std",

Expand Down
15 changes: 12 additions & 3 deletions pallet/staking/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
// darwinia
use crate::*;
use darwinia_deposit::SimpleAsset;
use dc_types::UNIT;
use dc_primitives::UNIT;
// polkadot-sdk
use frame_benchmarking::v2;
use frame_system::RawOrigin;
Expand Down Expand Up @@ -162,16 +162,25 @@ mod benchmarks {
fn set_rate_limit() {
// Worst-case scenario:
//
// Set max unstake ring successfully.
// Set successfully.
#[extrinsic_call]
_(RawOrigin::Root, 1);
}

#[benchmark]
fn set_kton_reward_distribution_contract() {
// Worst-case scenario:
//
// Set successfully.
#[extrinsic_call]
_(RawOrigin::Root, frame_benchmarking::whitelisted_caller::<T::AccountId>());
}

#[benchmark]
fn set_collator_count() {
// Worst-case scenario:
//
// Set collator count successfully.
// Set successfully.
#[extrinsic_call]
_(RawOrigin::Root, 1);
}
Expand Down
58 changes: 31 additions & 27 deletions pallet/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ use ethabi::{Function, Param, ParamType, StateMutability};
use ethereum::TransactionAction;
// darwinia
use darwinia_ethtx_forwarder::{ForwardEthOrigin, ForwardRequest, TxType};
use dc_types::{Balance, Moment};
use dc_primitives::{AccountId, Balance, Moment};
// polkadot-sdk
use frame_support::{
pallet_prelude::*, traits::Currency, DefaultNoBound, EqNoBound, PalletId, PartialEqNoBound,
Expand Down Expand Up @@ -105,7 +105,7 @@ pub mod pallet {
pub trait DepositConfig {}

#[pallet::config]
pub trait Config: frame_system::Config + DepositConfig {
pub trait Config: frame_system::Config<AccountId = AccountId> + DepositConfig {
/// Override the [`frame_system::Config::RuntimeEvent`].
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

Expand Down Expand Up @@ -137,10 +137,6 @@ pub mod pallet {
/// Maximum deposit count.
#[pallet::constant]
type MaxDeposits: Get<u32>;

/// Address of the KTON reward distribution contract.
#[pallet::constant]
type KtonRewardDistributionContract: Get<Self::AccountId>;
}

#[allow(missing_docs)]
Expand Down Expand Up @@ -295,6 +291,17 @@ pub mod pallet {
#[pallet::getter(fn rate_limit_state)]
pub type RateLimitState<T: Config> = StorageValue<_, RateLimiter, ValueQuery>;

/// KTON reward distribution contract address.
#[pallet::storage]
#[pallet::getter(fn kton_reward_distribution_contract)]
pub type KtonRewardDistributionContract<T: Config> =
StorageValue<_, T::AccountId, ValueQuery, KtonRewardDistributionContractDefault<T>>;
/// Default value for [`KtonRewardDistributionContract`].
#[pallet::type_value]
pub fn KtonRewardDistributionContractDefault<T: Config>() -> T::AccountId {
account_id()
}

#[derive(DefaultNoBound)]
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
Expand Down Expand Up @@ -531,7 +538,7 @@ pub mod pallet {
Ok(())
}

/// Set max unstake RING limit.
/// Set the max unstake RING limit.
#[pallet::call_index(9)]
#[pallet::weight(<T as Config>::WeightInfo::set_rate_limit())]
pub fn set_rate_limit(origin: OriginFor<T>, amount: Balance) -> DispatchResult {
Expand All @@ -542,7 +549,21 @@ pub mod pallet {
Ok(())
}

/// Set collator count.
/// Set the KTON reward distribution contract address.
#[pallet::call_index(10)]
#[pallet::weight(<T as Config>::WeightInfo::set_kton_reward_distribution_contract())]
pub fn set_kton_reward_distribution_contract(
origin: OriginFor<T>,
address: T::AccountId,
) -> DispatchResult {
ensure_root(origin)?;

<KtonRewardDistributionContract<T>>::put(address);

Ok(())
}

/// Set the collator count.
///
/// This will apply to the incoming session.
///
Expand Down Expand Up @@ -649,7 +670,7 @@ pub mod pallet {
};

reward(account_id(), actual_reward_to_ring);
reward(T::KtonRewardDistributionContract::get(), reward_to_kton);
reward(<KtonRewardDistributionContract<T>>::get(), reward_to_kton);

T::KtonStakerNotifier::notify(reward_to_kton);
}
Expand Down Expand Up @@ -971,22 +992,6 @@ where
PalletId(*b"da/staki").into_account_truncating()
}

/// The address of the `StakingRewardDistribution` contract.
/// 0x0DBFbb1Ab6e42F89661B4f98d5d0acdBE21d1ffC.
pub struct KtonRewardDistributionContract;
impl<T> Get<T> for KtonRewardDistributionContract
where
T: From<[u8; 20]>,
{
fn get() -> T {
[
13, 191, 187, 26, 182, 228, 47, 137, 102, 27, 79, 152, 213, 208, 172, 219, 226, 29, 31,
252,
]
.into()
}
}

/// `StakingRewardDistribution` contact notification interface.
pub trait KtonStakerNotification {
/// Notify the KTON staker contract.
Expand All @@ -1001,10 +1006,9 @@ impl<T> KtonStakerNotification for KtonStakerNotifier<T>
where
T: Config + darwinia_ethtx_forwarder::Config,
T::RuntimeOrigin: Into<Result<ForwardEthOrigin, T::RuntimeOrigin>> + From<ForwardEthOrigin>,
<T as frame_system::Config>::AccountId: Into<H160>,
{
fn notify(amount: Balance) {
let krd_contract = T::KtonRewardDistributionContract::get().into();
let krd_contract = <KtonRewardDistributionContract<T>>::get().into();
#[allow(deprecated)]
let function = Function {
name: "distributeRewards".into(),
Expand Down
8 changes: 4 additions & 4 deletions pallet/staking/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ use crate::*;
///
/// https://github.com/darwinia-network/KtonDAO/blob/722bdf62942868de2eeaf19bc70d7a165fc031af/src/Owned.sol#L5.
/// https://github.com/darwinia-network/KtonDAO/blob/045b5b59d56b426cb8b06b9da912d0a3ad0a636d/src/staking/KtonDAOVault.sol#L36.
pub fn migrate_staking_reward_distribution_contract<T>()
where
pub fn migrate_staking_reward_distribution_contract<T>(
kton_reward_distribution_contract: T::AccountId,
) where
T: Config + darwinia_ethtx_forwarder::Config,
T::RuntimeOrigin: Into<Result<ForwardEthOrigin, T::RuntimeOrigin>> + From<ForwardEthOrigin>,
<T as frame_system::Config>::AccountId: Into<H160>,
{
// Treasury pallet account.
let sender =
H160([109, 111, 100, 108, 100, 97, 47, 116, 114, 115, 114, 121, 0, 0, 0, 0, 0, 0, 0, 0]);
let krd_contract = T::KtonRewardDistributionContract::get().into();
let krd_contract = kton_reward_distribution_contract.into();
// 0x000000000Ae5DB7BDAf8D071e680452e33d91Dd5.
let krd_contract_old = H160([
0, 0, 0, 0, 10, 229, 219, 123, 218, 248, 208, 113, 230, 128, 69, 46, 51, 217, 29, 213,
Expand Down
2 changes: 1 addition & 1 deletion pallet/staking/src/migration/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use core::marker::PhantomData;
// darwinia
use crate::*;
use dc_types::UNIT;
use dc_primitives::UNIT;
// polkadot-sdk
use frame_support::traits::OnRuntimeUpgrade;
#[cfg(feature = "try-runtime")]
Expand Down
36 changes: 27 additions & 9 deletions pallet/staking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@
pub use crate as darwinia_staking;

// darwinia
use dc_types::{Balance, Moment, UNIT};
use dc_primitives::{AccountId, Balance, Moment, UNIT};
// polkadot-sdk
use frame_support::{
derive_impl,
traits::{Currency, OnInitialize},
};
use sp_core::H160;
use sp_io::TestExternalities;
use sp_runtime::{BuildStorage, RuntimeAppPublic};

pub type AccountId = u32;
pub type BlockNumber = frame_system::pallet_prelude::BlockNumberFor<Runtime>;

#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
Expand Down Expand Up @@ -105,7 +105,7 @@ impl pallet_session::SessionHandler<AccountId> for SessionHandler {

fn on_before_session_ending() {}

fn on_disabled(_: AccountId) {}
fn on_disabled(_: u32) {}
}
impl sp_runtime::BoundToRuntimeAppPublic for SessionHandler {
type Public = sp_runtime::testing::UintAuthorityId;
Expand All @@ -126,12 +126,27 @@ frame_support::parameter_types! {
pub const TreasuryPalletId: frame_support::PalletId = frame_support::PalletId(*b"da/trsry");
pub TreasuryAccount: AccountId = Treasury::account_id();
}
#[cfg(feature = "runtime-benchmarks")]
pub struct DummyBenchmarkHelper;
#[cfg(feature = "runtime-benchmarks")]
impl<AssetKind> pallet_treasury::ArgumentsFactory<AssetKind, AccountId> for DummyBenchmarkHelper
where
AssetKind: Default,
{
fn create_asset_kind(_: u32) -> AssetKind {
Default::default()
}

fn create_beneficiary(_: [u8; 32]) -> AccountId {
Default::default()
}
}
impl pallet_treasury::Config for Runtime {
type ApproveOrigin = frame_system::EnsureRoot<AccountId>;
type AssetKind = ();
type BalanceConverter = frame_support::traits::tokens::UnityAssetBalanceConversion;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
type BenchmarkHelper = DummyBenchmarkHelper;
type Beneficiary = AccountId;
type BeneficiaryLookup = Self::Lookup;
type Burn = ();
Expand Down Expand Up @@ -276,7 +291,6 @@ impl darwinia_staking::Config for Runtime {
type Deposit = Deposit;
type IssuingManager = StatedOnSessionEnd;
type Kton = KtonStaking;
type KtonRewardDistributionContract = ();
type KtonStakerNotifier = ();
type MaxDeposits = <Self as darwinia_deposit::Config>::MaxDeposits;
type Ring = RingStaking;
Expand Down Expand Up @@ -345,7 +359,7 @@ impl ExtBuilder {

pallet_balances::GenesisConfig::<Runtime> {
balances: (1..=10)
.map(|i| (i, 1_000 * UNIT))
.map(|i| (account_id_of(i), 1_000 * UNIT))
.chain([(Treasury::account_id(), 1_000_000 * UNIT)])
.collect(),
}
Expand All @@ -355,7 +369,7 @@ impl ExtBuilder {
rate_limit: 100 * UNIT,
collator_count: self.collator_count,
collators: if self.genesis_collator {
(1..=self.collator_count).map(|i| (i, UNIT)).collect()
(1..=self.collator_count as u64).map(|i| (account_id_of(i), UNIT)).collect()
} else {
Default::default()
},
Expand All @@ -365,8 +379,8 @@ impl ExtBuilder {
.unwrap();
if self.genesis_collator {
pallet_session::GenesisConfig::<Runtime> {
keys: (1..=self.collator_count)
.map(|i| (i, i, SessionKeys { uint: (i as u64).into() }))
keys: (1..=self.collator_count as u64)
.map(|i| (account_id_of(i), account_id_of(i), SessionKeys { uint: i.into() }))
.collect(),
}
.assimilate_storage(&mut storage)
Expand All @@ -386,6 +400,10 @@ impl Default for ExtBuilder {
}
}

pub fn account_id_of(i: u64) -> AccountId {
H160::from_low_u64_le(i).into()
}

pub fn initialize_block(number: BlockNumber) {
System::set_block_number(number);
Efflux::time(1);
Expand Down
Loading

0 comments on commit 06a70ad

Please sign in to comment.