Skip to content

Commit

Permalink
fmt: format code
Browse files Browse the repository at this point in the history
  • Loading branch information
sameh-farouk committed Aug 14, 2024
1 parent 7d03ead commit 6d60e78
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 57 deletions.
46 changes: 19 additions & 27 deletions substrate-node/pallets/pallet-smart-contract/src/billing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl<T: Config> Pallet<T> {
pub fn bill_contracts_for_block(block_number: BlockNumberFor<T>) {
let index = Self::get_billing_loop_index_from_block_number(block_number);
let contract_ids = ContractsToBillAt::<T>::get(index);

if contract_ids.is_empty() {
log::info!(
"No contracts to bill at block {:?}, index: {:?}",
Expand All @@ -36,19 +36,19 @@ impl<T: Config> Pallet<T> {
);
return;
}

log::info!(
"Contracts to bill at block {:?}: {:?}",
block_number,
contract_ids,
);

let mut succeeded_contracts = Vec::new();
let mut failed_contracts = Vec::new();
let mut skipped_contracts = Vec::new();
let mut missing_contracts = Vec::new();
let mut already_sent_contracts = Vec::new();

for contract_id in contract_ids {
if let Some(contract) = Contracts::<T>::get(contract_id) {
if Self::should_bill_contract(&contract) {
Expand All @@ -71,22 +71,22 @@ impl<T: Config> Pallet<T> {
missing_contracts.push(contract_id);
}
}

// Log the results at the end of the function
if !succeeded_contracts.is_empty() {
log::info!(
"Successfully submitted signed transactions for contracts: {:?}",
succeeded_contracts
);
}

if !already_sent_contracts.is_empty() {
log::info!(
"Signed transactions for contracts were already sent: {:?}",
already_sent_contracts
);
}

if !skipped_contracts.is_empty() {
log::info!(
"Skipped billing node contracts (no IP/CU/SU/NU to bill): {:?}",
Expand All @@ -100,13 +100,10 @@ impl<T: Config> Pallet<T> {
failed_contracts
);
}

if !missing_contracts.is_empty() {
log::error!(
"Contracts not found in storage: {:?}",
missing_contracts
);
}
log::error!("Contracts not found in storage: {:?}", missing_contracts);
}
}
fn should_bill_contract(contract: &types::Contract<T>) -> bool {
match &contract.contract_type {
Expand Down Expand Up @@ -348,7 +345,7 @@ impl<T: Config> Pallet<T> {
contract_payment_state.last_updated_seconds = now;
contract_payment_state.cycles.defensive_saturating_inc();
ContractPaymentState::<T>::insert(contract.contract_id, &contract_payment_state);

Ok(().into())
}

Expand All @@ -358,23 +355,18 @@ impl<T: Config> Pallet<T> {
contract_payment_state: &mut types::ContractPaymentState<BalanceOf<T>>,
) {
if !contract_lock.is_migrated() {
log::debug!("Migrating contract to new payment state, CL: {:?}", contract_lock);
log::debug!(
"Migrating contract to new payment state, CL: {:?}",
contract_lock
);
contract_payment_state.last_updated_seconds = contract_lock.lock_updated;
contract_payment_state.standard_overdrafted = contract_lock.amount_locked;
contract_payment_state.additional_overdrafted = contract_lock.extra_amount_locked;
contract_payment_state.cycles = contract_lock.cycles;
log::debug!(
"Migrated contract to new payment state, CPS: {:?}",
contract_payment_state
);

let locks = pallet_balances::Pallet::<T>::locks(&account_id);
for lock in locks {
log::debug!(
"Removing lock: {:?} for account: {:?}",
lock.id,
account_id,
);
log::debug!("Removing lock: {:?} for account: {:?}", lock.id, account_id,);
pallet_balances::Pallet::<T>::remove_lock(lock.id, &account_id);
}
}
Expand Down Expand Up @@ -517,7 +509,7 @@ impl<T: Config> Pallet<T> {
let standard_rewards = contract_payment_state.standard_reserved;
let additional_rewards = contract_payment_state.additional_reserved;
// distribute additional rewards to the farm twin

let reminder = if let types::ContractData::RentContract(_) = &contract.contract_type {
log::info!(
"Distributing additional rewards from twin {:?} with amount {:?}",
Expand All @@ -533,7 +525,7 @@ impl<T: Config> Pallet<T> {
} else {
BalanceOf::<T>::zero()
};

let distributed_additional_amount = additional_rewards.saturating_sub(reminder);
if reminder > BalanceOf::<T>::zero() {
log::warn!(
Expand Down Expand Up @@ -674,7 +666,7 @@ impl<T: Config> Pallet<T> {

let total_distributed =
foundation_share + staking_pool_share + total_provider_share + sales_share;

// Calculate the amount to burn, which is the remainder after distributing the rewards to the beneficiaries.
// This should be 35% of the total amount, but we calculate it to avoid rounding errors
let amount_to_burn = amount.defensive_saturating_sub(total_distributed);
Expand Down
23 changes: 17 additions & 6 deletions substrate-node/pallets/pallet-smart-contract/src/grid_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,15 +321,18 @@ impl<T: Config> Pallet<T> {
}

Self::update_contract_state(contract, &types::ContractState::Deleted(cause))?;
log::debug!("Billing for contract {} kicked in due to cancel request", contract.contract_id);
log::debug!(
"Billing for contract {} kicked in due to cancel request",
contract.contract_id
);
Self::bill_contract(contract.contract_id)?;

Ok(().into())
}

pub fn remove_contract(contract_id: u64) -> DispatchResultWithPostInfo {
let contract = Contracts::<T>::get(contract_id).ok_or(Error::<T>::ContractNotExists)?;

log::debug!("removing contract {}", contract_id);
match contract.contract_type.clone() {
types::ContractData::NodeContract(mut node_contract) => {
Expand Down Expand Up @@ -377,7 +380,10 @@ impl<T: Config> Pallet<T> {
ContractPaymentState::<T>::remove(contract_id);
// Clean up contract from billing loop
// This is the only place it should be done
log::debug!("cleaning up deleted contract {} from billing loop", contract_id);
log::debug!(
"cleaning up deleted contract {} from billing loop",
contract_id
);
Self::remove_contract_from_billing_loop(contract_id)?;

Ok(().into())
Expand Down Expand Up @@ -703,12 +709,14 @@ impl<T: Config> ChangeNode<LocationOf<T>, InterfaceOf<T>, SerialNumberOf<T>> for
&mut contract,
&types::ContractState::Deleted(types::Cause::CanceledByUser),
);
log::debug!("Billing for node contract {} kicked in due to node deletion", contract.contract_id);
log::debug!(
"Billing for node contract {} kicked in due to node deletion",
contract.contract_id
);
let res = Self::bill_contract(node_contract_id);
if let Err(e) = res {
log::error!("error in node_deleted hook while billing contract {:?}: {:?}. Contract could be in dirty state", node_contract_id, e);
}

}
}

Expand All @@ -720,7 +728,10 @@ impl<T: Config> ChangeNode<LocationOf<T>, InterfaceOf<T>, SerialNumberOf<T>> for
&mut contract,
&types::ContractState::Deleted(types::Cause::CanceledByUser),
);
log::debug!("Billing for rent contract {} kicked in due to node deletion", contract.contract_id);
log::debug!(
"Billing for rent contract {} kicked in due to node deletion",
contract.contract_id
);
let res = Self::bill_contract(contract.contract_id);
if let Err(e) = res {
log::error!("error in node_deleted hook while billing contract id {:?}: {:?}. Contract could be in dirty state", rc_id, e);
Expand Down
12 changes: 9 additions & 3 deletions substrate-node/pallets/pallet-smart-contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ pub mod pallet {
use super::*;
use frame_support::{
pallet_prelude::*,
traits::{Currency, Get, Hooks, LockIdentifier, LockableCurrency, OnUnbalanced, ReservableCurrency, tokens::fungible::*},
traits::{
tokens::fungible::*, Currency, Get, Hooks, LockIdentifier, LockableCurrency,
OnUnbalanced, ReservableCurrency,
},
};
use frame_system::{
self as system, ensure_signed,
Expand Down Expand Up @@ -213,7 +216,10 @@ pub mod pallet {
+ pallet_session::Config
{
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type Currency: LockableCurrency<Self::AccountId> + ReservableCurrency<Self::AccountId> + InspectHold<Self::AccountId> + Inspect<Self::AccountId>;
type Currency: LockableCurrency<Self::AccountId>
+ ReservableCurrency<Self::AccountId>
+ InspectHold<Self::AccountId>
+ Inspect<Self::AccountId>;
/// Handler for the unbalanced decrement when slashing (burning collateral)
type Burn: OnUnbalanced<NegativeImbalanceOf<Self>>;
type StakingPoolAccount: Get<Self::AccountId>;
Expand Down Expand Up @@ -348,7 +354,7 @@ pub mod pallet {
contract_id: u64,
timestamp: u64,
partial_billed_amount: BalanceOf<T>, // amount billed
overdrafted_amount: BalanceOf<T>, // amount overdrafted
overdrafted_amount: BalanceOf<T>, // amount overdrafted
},
// RewardDistributed
RewardDistributed {
Expand Down
58 changes: 37 additions & 21 deletions substrate-node/pallets/pallet-smart-contract/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ use crate::{
use frame_support::{
assert_noop, assert_ok, bounded_vec,
dispatch::Pays,
traits::{LockableCurrency, WithdrawReasons, Currency},
traits::{Currency, LockableCurrency, WithdrawReasons},
BoundedVec,
};
use frame_system::{EventRecord, Phase, RawOrigin};
use log::info;
use pallet_tfgrid::{
types::{self as pallet_tfgrid_types, LocationInput}, ResourcesInput
types::{self as pallet_tfgrid_types, LocationInput},
ResourcesInput,
};
use sp_core::H256;
use sp_runtime::{assert_eq_error_rate, traits::SaturatedConversion, Perbill, Percent};
Expand Down Expand Up @@ -997,7 +998,7 @@ fn test_node_contract_billing_details() {
SmartContractModule::contract_to_bill_at_block(index),
vec![contract_id]
);

activate_billing_accounts(false);

let initial_total_issuance = Balances::total_issuance();
Expand Down Expand Up @@ -1401,7 +1402,7 @@ fn test_node_contract_billing_cycles_delete_node_cancels_contract() {
let mut ips: BoundedVec<PublicIP, crate::MaxNodeContractPublicIPs<TestRuntime>> =
vec![].try_into().unwrap();
ips.try_push(public_ip).unwrap();

log::debug!("events : {:?}", our_events);
assert_eq!(
our_events.contains(&record(MockEvent::SmartContractModule(
Expand Down Expand Up @@ -1595,7 +1596,10 @@ fn test_node_contract_billing_cycles_cancel_contract_during_cycle_without_balanc
.unwrap();

let usable_balance_before_canceling = Balances::free_balance(&twin.account_id);
info!("usable balance before canceling: {:?}", usable_balance_before_canceling);
info!(
"usable balance before canceling: {:?}",
usable_balance_before_canceling
);
assert_ne!(usable_balance_before_canceling, 0);

assert_ok!(SmartContractModule::cancel_contract(
Expand All @@ -1606,14 +1610,23 @@ fn test_node_contract_billing_cycles_cancel_contract_during_cycle_without_balanc
// After canceling contract, and not being able to pay for the remainder of the cycle
// where the cancel was excecuted, should deduct as much as possible from the user
let usable_balance_after_canceling = Balances::free_balance(&twin.account_id);
info!("usable balance after canceling: {:?}", usable_balance_after_canceling);
info!("total amount billed: {:?}", total_amount_billed + (usable_balance_before_canceling - usable_balance_after_canceling));
assert_eq!(
usable_balance_after_canceling,
500
info!(
"usable balance after canceling: {:?}",
usable_balance_after_canceling
);
info!(
"total amount billed: {:?}",
total_amount_billed
+ (usable_balance_before_canceling - usable_balance_after_canceling)
);
assert_eq!(usable_balance_after_canceling, 500);

validate_distribution_rewards(initial_total_issuance, total_amount_billed + (usable_balance_before_canceling - usable_balance_after_canceling), false);
validate_distribution_rewards(
initial_total_issuance,
total_amount_billed
+ (usable_balance_before_canceling - usable_balance_after_canceling),
false,
);
});
}

Expand Down Expand Up @@ -2065,7 +2078,6 @@ fn test_rent_contract_canceled_mid_cycle_should_bill_for_remainder() {

let twin = TfgridModule::twins(2).unwrap();


let reserved_balance = Balances::reserved_balance(&twin.account_id);
info!("reserved balance: {:?}", reserved_balance);

Expand Down Expand Up @@ -3955,7 +3967,7 @@ fn test_set_dedicated_node_extra_fee_and_create_rent_contract_billing_works() {
let mut extra_fee_cost_tft = 0;

// advance 25 cycles to reach reward distribution block
for i in 1..=DistributionFrequency::get() as u64 + 1u64{
for i in 1..=DistributionFrequency::get() as u64 + 1u64 {
let block_number = start_block + i * BillingFrequency::get();
pool_state.write().should_call_bill_contract(
rent_contract_id,
Expand All @@ -3964,7 +3976,7 @@ fn test_set_dedicated_node_extra_fee_and_create_rent_contract_billing_works() {
);
log::debug!("i {} after pool block_number: {}", i, block_number);

run_to_block( block_number, Some(&mut pool_state));
run_to_block(block_number, Some(&mut pool_state));
log::debug!("i {} after run block_number: {}", i, block_number);

// check why aggregating seconds elapsed is giving different results
Expand All @@ -3978,8 +3990,8 @@ fn test_set_dedicated_node_extra_fee_and_create_rent_contract_billing_works() {
rent_contract_cost_tft += contract_cost_tft;

// aggregate extra fee cost
extra_fee_cost_tft += rent_contract
.calculate_extra_fee_cost_tft(node_id, elapsed_time_in_secs);
extra_fee_cost_tft +=
rent_contract.calculate_extra_fee_cost_tft(node_id, elapsed_time_in_secs);
}

let then = SmartContractModule::get_current_timestamp_in_secs();
Expand Down Expand Up @@ -4207,8 +4219,9 @@ fn calculate_tft_cost(contract_id: u64, twin_id: u32, blocks: u64) -> (u64, type
let twin = TfgridModule::twins(twin_id).unwrap();
let b = Balances::free_balance(&twin.account_id);
let contract = SmartContractModule::contracts(contract_id).unwrap();
let (amount_due, discount_received) =
contract.calculate_contract_cost_tft(b, blocks * 6, None).unwrap();
let (amount_due, discount_received) = contract
.calculate_contract_cost_tft(b, blocks * 6, None)
.unwrap();

(amount_due, discount_received)
}
Expand Down Expand Up @@ -4555,20 +4568,23 @@ fn get_timestamp_in_seconds_for_block(block_number: u64) -> u64 {
}

fn activate_billing_accounts(had_solution_provider: bool) {

let pricing_policy = TfgridModule::pricing_policies(1).unwrap();
let foundation_account = pricing_policy.foundation_account;
let sales_account = pricing_policy.certified_sales_account;
let staking_pool_account = get_staking_pool_account();
let mut billing_accounts = vec![foundation_account, sales_account, staking_pool_account];
// push solution_provider_account if SmartContractModule::solution_providers(1) has Some
if had_solution_provider {
let solution_provider_account = SmartContractModule::solution_providers(1).unwrap().providers[0].who.clone();
let solution_provider_account = SmartContractModule::solution_providers(1)
.unwrap()
.providers[0]
.who
.clone();
billing_accounts.push(solution_provider_account);
}
for account in billing_accounts {
if Balances::free_balance(&account) == 0 {
let _ = Balances::deposit_creating(&account, 500);
}
}
}
}
1 change: 1 addition & 0 deletions substrate-node/pallets/pallet-smart-contract/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,7 @@ pub enum ServiceContractState {
AgreementReady,
ApprovedByBoth,
}

// This code defines a custom SignedExtension `ContractIdProvides`
// SignedExtension is a trait that allows developers to add custom logic to the transaction validation process.
// It ensures that transactions of type bill_contract_for_block are unique per block based on the provided contract ID.
Expand Down

0 comments on commit 6d60e78

Please sign in to comment.