Skip to content

Commit

Permalink
Payout provider share tests (#195)
Browse files Browse the repository at this point in the history
  • Loading branch information
aie0 authored Dec 13, 2023
1 parent 2885ae9 commit e24b417
Show file tree
Hide file tree
Showing 7 changed files with 423 additions and 75 deletions.
1 change: 1 addition & 0 deletions node/service/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ pub fn cere_dev_genesis(
nomination_pools: Default::default(),
ddc_clusters: Default::default(),
ddc_nodes: Default::default(),
ddc_payouts: Default::default(),
}
}

Expand Down
24 changes: 18 additions & 6 deletions pallets/ddc-customers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,13 +217,14 @@ pub mod pallet {

#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub feeder_account: Option<T::AccountId>,
pub buckets: Vec<(ClusterId, T::AccountId, BalanceOf<T>)>,
}

#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig { buckets: Default::default() }
GenesisConfig { feeder_account: None, buckets: Default::default() }
}
}

Expand All @@ -232,8 +233,19 @@ pub mod pallet {
fn build(&self) {
let account_id = <Pallet<T>>::account_id();
let min = <T as pallet::Config>::Currency::minimum_balance();
if <T as pallet::Config>::Currency::free_balance(&account_id) < min {
let _ = <T as pallet::Config>::Currency::make_free_balance_be(&account_id, min);

let balance = <T as pallet::Config>::Currency::free_balance(&account_id);
if balance < min {
if let Some(vault) = &self.feeder_account {
let _ = <T as pallet::Config>::Currency::transfer(
vault,
&account_id,
min - balance,
ExistenceRequirement::AllowDeath,
);
} else {
let _ = <T as pallet::Config>::Currency::make_free_balance_be(&account_id, min);
}
}

for &(ref cluster_id, ref owner_id, ref deposit) in &self.buckets {
Expand Down Expand Up @@ -438,7 +450,7 @@ pub mod pallet {
old_total.checked_sub(&ledger.total).ok_or(Error::<T>::ArithmeticUnderflow)?;

<T as pallet::Config>::Currency::transfer(
&Self::sub_account_id(&owner),
&Self::account_id(),
&owner,
value,
ExistenceRequirement::AllowDeath,
Expand Down Expand Up @@ -471,7 +483,7 @@ pub mod pallet {
) -> DispatchResult {
<T as pallet::Config>::Currency::transfer(
owner,
&Self::sub_account_id(owner),
&Self::account_id(),
ledger.total,
ExistenceRequirement::AllowDeath,
)?;
Expand Down Expand Up @@ -570,7 +582,7 @@ pub mod pallet {
}

<T as pallet::Config>::Currency::transfer(
&Self::sub_account_id(&content_owner),
&Self::account_id(),
&billing_vault,
actually_charged,
ExistenceRequirement::AllowDeath,
Expand Down
10 changes: 8 additions & 2 deletions pallets/ddc-customers/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use ddc_traits::cluster::{

use frame_support::{
construct_runtime, parameter_types,
traits::{ConstU32, ConstU64, Everything},
traits::{ConstU32, ConstU64, Everything, GenesisBuild},
weights::constants::RocksDbWeight,
};
use frame_system::mocking::{MockBlock, MockUncheckedExtrinsic};
Expand Down Expand Up @@ -238,11 +238,17 @@ impl ExtBuilder {
sp_tracing::try_init_simple();
let mut storage = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();

let _ = pallet_balances::GenesisConfig::<Test> {
let _balance_genesis = pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 100), (2, 100), (3, 1000)],
}
.assimilate_storage(&mut storage);

let _customer_genesis = pallet_ddc_customers::GenesisConfig::<Test> {
feeder_account: None,
buckets: Default::default(),
}
.assimilate_storage(&mut storage);

TestExternalities::new(storage)
}
pub fn build_and_execute(self, test: impl FnOnce()) {
Expand Down
17 changes: 11 additions & 6 deletions pallets/ddc-customers/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ fn charge_content_owner_works() {
let balance_after_deposit = Balances::free_balance(account_3);
assert_eq!(balance_before_deposit - deposit, balance_after_deposit);

let pallet_balance = Balances::free_balance(DdcCustomers::sub_account_id(&account_3));
assert_eq!(deposit, pallet_balance);
let pallet_balance = Balances::free_balance(DdcCustomers::account_id());
assert_eq!(deposit, pallet_balance - Balances::minimum_balance());

// Check storage
assert_eq!(
Expand All @@ -170,8 +170,7 @@ fn charge_content_owner_works() {
let account_balance = Balances::free_balance(account_3);
assert_eq!(balance_after_deposit, account_balance);

let pallet_balance_after_charge =
Balances::free_balance(DdcCustomers::sub_account_id(&account_3));
let pallet_balance_after_charge = Balances::free_balance(DdcCustomers::account_id());
assert_eq!(pallet_balance - charged, pallet_balance_after_charge);

// Check storage
Expand All @@ -198,7 +197,10 @@ fn charge_content_owner_works() {
})
);

assert_eq!(0, Balances::free_balance(DdcCustomers::sub_account_id(&account_3)));
assert_eq!(
0,
Balances::free_balance(DdcCustomers::account_id()) - Balances::minimum_balance()
);
assert_eq!(charge_result, deposit - charge1);

assert_ok!(DdcCustomers::deposit_extra(RuntimeOrigin::signed(account_3), deposit));
Expand All @@ -212,7 +214,10 @@ fn charge_content_owner_works() {
})
);

assert_eq!(deposit, Balances::free_balance(DdcCustomers::sub_account_id(&account_3)));
assert_eq!(
deposit,
Balances::free_balance(DdcCustomers::account_id()) - Balances::minimum_balance()
);
})
}

Expand Down
70 changes: 59 additions & 11 deletions pallets/ddc-payouts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,11 @@ pub mod pallet {
pub type DebtorCustomers<T: Config> =
StorageDoubleMap<_, Blake2_128Concat, ClusterId, Blake2_128Concat, T::AccountId, u128>;

#[pallet::storage]
#[pallet::getter(fn owing_providers)]
pub type OwingProviders<T: Config> =
StorageDoubleMap<_, Blake2_128Concat, ClusterId, Blake2_128Concat, T::AccountId, u128>;

#[derive(Clone, Encode, Decode, RuntimeDebug, TypeInfo, PartialEq)]
#[scale_info(skip_type_params(T))]
pub struct BillingReport<T: Config> {
Expand Down Expand Up @@ -316,13 +321,11 @@ pub mod pallet {
Error::<T>::NotExpectedState
);

let mut billing_report = BillingReport::<T> {
vault: Self::sub_account_id(cluster_id, era),
let billing_report = BillingReport::<T> {
vault: Self::account_id(),
state: State::Initialized,
..Default::default()
};
billing_report.vault = Self::sub_account_id(cluster_id, era);
billing_report.state = State::Initialized;
ActiveBillingReports::<T>::insert(cluster_id, era, billing_report);

Self::deposit_event(Event::<T>::BillingReportInitialized { cluster_id, era });
Expand Down Expand Up @@ -398,12 +401,6 @@ pub mod pallet {
.ok_or(Error::<T>::ArithmeticOverflow)?;

let customer_id = payer.0.clone();
/*let amount_actually_charged = T::CustomerCharger::charge_content_owner(
customer_id.clone(),
updated_billing_report.vault.clone(),
total_customer_charge,
)?;*/

let amount_actually_charged = match T::CustomerCharger::charge_content_owner(
customer_id.clone(),
updated_billing_report.vault.clone(),
Expand Down Expand Up @@ -682,7 +679,21 @@ pub mod pallet {

let node_provider_id = payee.0;
if amount_to_reward > 0 {
let reward: BalanceOf<T> = amount_to_reward.saturated_into::<BalanceOf<T>>();
let mut reward: BalanceOf<T> =
amount_to_reward.saturated_into::<BalanceOf<T>>();

let balance = <T as pallet::Config>::Currency::free_balance(
&updated_billing_report.vault,
) - <T as pallet::Config>::Currency::minimum_balance();

if reward > balance {
ensure!(
reward - balance <= MaxDust::get().into(),
Error::<T>::NotDistributedBalance
);

reward = balance;
}

<T as pallet::Config>::Currency::transfer(
&updated_billing_report.vault,
Expand Down Expand Up @@ -916,7 +927,44 @@ pub mod pallet {
Ok(())
}

#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub feeder_account: Option<T::AccountId>,
}

#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig { feeder_account: None }
}
}

#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
let account_id = <Pallet<T>>::account_id();
let min = <T as pallet::Config>::Currency::minimum_balance();
let balance = <T as pallet::Config>::Currency::free_balance(&account_id);
if balance < min {
if let Some(vault) = &self.feeder_account {
let _ = <T as pallet::Config>::Currency::transfer(
vault,
&account_id,
min - balance,
ExistenceRequirement::AllowDeath,
);
} else {
let _ = <T as pallet::Config>::Currency::make_free_balance_be(&account_id, min);
}
}
}
}

impl<T: Config> Pallet<T> {
pub fn account_id() -> T::AccountId {
T::PalletId::get().into_account_truncating()
}

pub fn sub_account_id(cluster_id: ClusterId, era: DdcEra) -> T::AccountId {
let mut bytes = Vec::new();
bytes.extend_from_slice(&cluster_id[..]);
Expand Down
58 changes: 43 additions & 15 deletions pallets/ddc-payouts/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,12 @@ construct_runtime!(
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
DdcPayouts: pallet_ddc_payouts::{Pallet, Call, Storage, Event<T>},
DdcPayouts: pallet_ddc_payouts::{Pallet, Call, Storage, Config<T>, Event<T>},
}
);

pub static MAX_DUST: u16 = 20000;

parameter_types! {
pub static ExistentialDeposit: Balance = 1;
}
Expand Down Expand Up @@ -120,13 +122,28 @@ impl<T: Config> CustomerCharger<T> for TestCustomerCharger {
billing_vault: T::AccountId,
amount: u128,
) -> Result<u128, DispatchError> {
ensure!(amount > 1_000_000, DispatchError::BadOrigin); // any error will do

let mut amount_to_charge = amount;
let temp = ACCOUNT_ID_5.to_ne_bytes();
let mut temp = ACCOUNT_ID_1.to_ne_bytes();
let account_1 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_2.to_ne_bytes();
let account_2 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_3.to_ne_bytes();
let account_3 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_4.to_ne_bytes();
let account_4 = T::AccountId::decode(&mut &temp[..]).unwrap();
temp = ACCOUNT_ID_5.to_ne_bytes();
let account_5 = T::AccountId::decode(&mut &temp[..]).unwrap();

if amount_to_charge < 50_000_000 && content_owner != account_5 {
if content_owner == account_1 ||
content_owner == account_2 ||
content_owner == account_3 ||
content_owner == account_4 ||
content_owner == account_5
{
ensure!(amount > 1_000_000, DispatchError::BadOrigin); // any error will do
}

if amount_to_charge < 50_000_000 && content_owner == account_3 {
amount_to_charge = PARTIAL_CHARGE; // for user 3
}

Expand All @@ -142,6 +159,10 @@ impl<T: Config> CustomerCharger<T> for TestCustomerCharger {
}
}

pub const ACCOUNT_ID_1: AccountId = 1;
pub const ACCOUNT_ID_2: AccountId = 2;
pub const ACCOUNT_ID_3: AccountId = 3;
pub const ACCOUNT_ID_4: AccountId = 4;
pub const ACCOUNT_ID_5: AccountId = 5;
pub struct TestClusterCreator;
impl<T: Config> ClusterCreator<T, Balance> for TestClusterCreator {
Expand Down Expand Up @@ -280,11 +301,19 @@ impl<T: frame_system::Config> SortedListProvider<T::AccountId> for TestValidator
}
}

pub fn get_fees(cluster_id: &ClusterId) -> Result<ClusterFeesParams, ClusterVisitorError> {
pub fn get_fees(cluster_id: &ClusterId) -> ClusterFeesParams {
if *cluster_id == FREE_CLUSTER_ID || *cluster_id == ONE_CLUSTER_ID {
Ok(PRICING_FEES_ZERO)
PRICING_FEES_ZERO
} else {
Ok(PRICING_FEES)
PRICING_FEES
}
}

pub fn get_pricing(cluster_id: &ClusterId) -> ClusterPricingParams {
if *cluster_id == FREE_CLUSTER_ID || *cluster_id == ONE_CLUSTER_ID {
PRICING_PARAMS_ONE
} else {
PRICING_PARAMS
}
}

Expand Down Expand Up @@ -315,15 +344,11 @@ impl<T: Config> ClusterVisitor<T> for TestClusterVisitor {
fn get_pricing_params(
cluster_id: &ClusterId,
) -> Result<ClusterPricingParams, ClusterVisitorError> {
if *cluster_id == FREE_CLUSTER_ID || *cluster_id == ONE_CLUSTER_ID {
Ok(PRICING_PARAMS_ONE)
} else {
Ok(PRICING_PARAMS)
}
Ok(get_pricing(cluster_id))
}

fn get_fees_params(cluster_id: &ClusterId) -> Result<ClusterFeesParams, ClusterVisitorError> {
get_fees(cluster_id)
Ok(get_fees(cluster_id))
}

fn get_reserve_account_id(
Expand All @@ -349,7 +374,7 @@ impl ExtBuilder {
sp_tracing::try_init_simple();
let mut storage = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();

let _ = pallet_balances::GenesisConfig::<Test> {
let _balance_genesis = pallet_balances::GenesisConfig::<Test> {
balances: vec![
(1, 10000000000000000000000000000),
(2, 10), // < PARTIAL_CHARGE
Expand All @@ -360,6 +385,9 @@ impl ExtBuilder {
}
.assimilate_storage(&mut storage);

let _payout_genesis = pallet_ddc_payouts::GenesisConfig::<Test> { feeder_account: None }
.assimilate_storage(&mut storage);

TestExternalities::new(storage)
}
pub fn build_and_execute(self, test: impl FnOnce()) {
Expand Down
Loading

0 comments on commit e24b417

Please sign in to comment.