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

fix: save graced contracts total amount due #631

Merged
merged 5 commits into from
Mar 9, 2023
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
46 changes: 21 additions & 25 deletions substrate-node/pallets/pallet-smart-contract/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -953,8 +953,6 @@ impl<T: Config> Pallet<T> {

Self::_update_contract_state(&mut contract, &types::ContractState::Deleted(cause))?;
Self::bill_contract(contract.contract_id)?;
// Remove all associated storage
Self::remove_contract(contract.contract_id);

Ok(().into())
}
Expand Down Expand Up @@ -1132,17 +1130,11 @@ impl<T: Config> Pallet<T> {
pallet_tfgrid::Twins::<T>::get(contract.twin_id).ok_or(Error::<T>::TwinNotExists)?;
let usable_balance = Self::get_usable_balance(&twin.account_id);

let mut seconds_elapsed = BillingFrequency::<T>::get() * 6;
// Calculate amount of seconds elapsed based on the contract lock struct

let now = <timestamp::Pallet<T>>::get().saturated_into::<u64>() / 1000;
// this will set the seconds elapsed to the default billing cycle duration in seconds
// if there is no contract lock object yet. A contract lock object will be created later in this function
// https://github.com/threefoldtech/tfchain/issues/261
let contract_lock = ContractLock::<T>::get(contract.contract_id);
if contract_lock.lock_updated != 0 {
seconds_elapsed = now.checked_sub(contract_lock.lock_updated).unwrap_or(0);
}

// Calculate amount of seconds elapsed based on the contract lock struct
let mut contract_lock = ContractLock::<T>::get(contract.contract_id);
let seconds_elapsed = now.checked_sub(contract_lock.lock_updated).unwrap_or(0);

let (amount_due, discount_received) =
contract.calculate_contract_cost_tft(usable_balance, seconds_elapsed)?;
Expand All @@ -1155,17 +1147,27 @@ impl<T: Config> Pallet<T> {
return Ok(().into());
};

let total_lock_amount = contract_lock.amount_locked + amount_due;
// Handle grace
let contract = Self::handle_grace(&mut contract, usable_balance, amount_due)?;
let contract = Self::handle_grace(&mut contract, usable_balance, total_lock_amount)?;

// Only update contract lock in state (Created, GracePeriod)
if !matches!(contract.state, types::ContractState::Deleted(_)) {
// increment cycles billed and update the internal lock struct
contract_lock.lock_updated = now;
contract_lock.cycles += 1;
contract_lock.amount_locked = total_lock_amount;
}

// If still in grace period, no need to continue doing locking and other stuff
if matches!(contract.state, types::ContractState::GracePeriod(_)) {
log::debug!("contract {} is still in grace", contract.contract_id);
ContractLock::<T>::insert(contract.contract_id, &contract_lock);
return Ok(().into());
}

// Handle contract lock operations
Self::handle_lock(contract, amount_due)?;
Self::handle_lock(contract, &mut contract_lock, amount_due)?;

// Always emit a contract billed event
let contract_bill = types::ContractBill {
Expand All @@ -1185,8 +1187,12 @@ impl<T: Config> Pallet<T> {
// If the contract is in delete state, remove all associated storage
if matches!(contract.state, types::ContractState::Deleted(_)) {
Self::remove_contract(contract.contract_id);
return Ok(().into());
}
Comment on lines 1188 to 1191
Copy link
Collaborator

Choose a reason for hiding this comment

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

In the bill_contract() context, the only way to have a contract in Deleted state is just after the handle_grace()
So i guess this block can be moved above
With this you can get rid of the if at line 1157

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Well, the contract is also moved to state Deleted if the user cancels it:

Self::_update_contract_state(&mut contract, &types::ContractState::Deleted(cause))?;

Copy link
Collaborator

Choose a reason for hiding this comment

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

Btw, I don't understand why there is a Deleted state for contract because I don't see something specific done with this info
Just removing the contract would not be fine?
or I miss something

Copy link
Collaborator

Choose a reason for hiding this comment

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

Well, the contract is also moved to state Deleted if the user cancels it:

Self::_update_contract_state(&mut contract, &types::ContractState::Deleted(cause))?;

Ok, I see
So even when Deleted it is billed and need to reach the end of bill_contract()

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Btw, I don't understand why there is a Deleted state for contract because I don't see something specific done with this info Just removing the contract would not be fine? or I miss something

It's a leftover state from where we did not remove contracts from chain but marked them as deleted for ever. We can in a next iteration remove this maybe?


// Finally update the lock
ContractLock::<T>::insert(contract.contract_id, &contract_lock);

log::info!("successfully billed contract with id {:?}", contract_id,);

Ok(().into())
Expand Down Expand Up @@ -1297,20 +1303,11 @@ impl<T: Config> Pallet<T> {

fn handle_lock(
contract: &mut types::Contract<T>,
contract_lock: &mut types::ContractLock<BalanceOf<T>>,
amount_due: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
let now = <timestamp::Pallet<T>>::get().saturated_into::<u64>() / 1000;

let mut contract_lock = ContractLock::<T>::get(contract.contract_id);
// Only update contract lock in state (Created, GracePeriod)
if !matches!(contract.state, types::ContractState::Deleted(_)) {
// increment cycles billed and update the internal lock struct
contract_lock.lock_updated = now;
contract_lock.cycles += 1;
contract_lock.amount_locked = contract_lock.amount_locked + amount_due;
ContractLock::<T>::insert(contract.contract_id, &contract_lock);
}

// Only lock an amount from the user's balance if the contract is in create state
// The lock is specified on the user's account, since a user can have multiple contracts
// Just extend the lock with the amount due for this contract billing period (lock will be created if not exists)
Expand Down Expand Up @@ -1379,7 +1376,6 @@ impl<T: Config> Pallet<T> {
contract_lock.lock_updated = now;
contract_lock.amount_locked = BalanceOf::<T>::saturated_from(0 as u128);
contract_lock.cycles = 0;
ContractLock::<T>::insert(contract.contract_id, &contract_lock);
}

Ok(().into())
Expand Down
15 changes: 10 additions & 5 deletions substrate-node/pallets/pallet-smart-contract/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1829,7 +1829,11 @@ fn test_rent_contract_canceled_due_to_out_of_funds_should_cancel_node_contracts_
// check_report_cost(1, 3, amount_due_as_u128, 12, discount_received);

let our_events = System::events();
assert_eq!(our_events.len(), 10);
assert_eq!(our_events.len(), 21);

for e in our_events.clone() {
log::info!("event: {:?}", e);
}

assert_eq!(
our_events[5],
Expand All @@ -1855,7 +1859,7 @@ fn test_rent_contract_canceled_due_to_out_of_funds_should_cancel_node_contracts_
);

assert_eq!(
our_events[8],
our_events[19],
record(MockEvent::SmartContractModule(SmartContractEvent::<
TestRuntime,
>::NodeContractCanceled {
Expand All @@ -1865,7 +1869,7 @@ fn test_rent_contract_canceled_due_to_out_of_funds_should_cancel_node_contracts_
}))
);
assert_eq!(
our_events[9],
our_events[20],
record(MockEvent::SmartContractModule(SmartContractEvent::<
TestRuntime,
>::RentContractCanceled {
Expand Down Expand Up @@ -3216,9 +3220,10 @@ fn validate_distribution_rewards(
} else {
// 50% is sent to the sales account
let sales_account_balance = Balances::free_balance(&pricing_policy.certified_sales_account);
assert_eq!(
assert_eq_error_rate!(
sales_account_balance,
Perbill::from_percent(50) * total_amount_billed
Perbill::from_percent(50) * total_amount_billed,
1
);
}

Expand Down