Contracts remove deposit accounts (#14589)

* contracts: refactor currency to use fungible traits

* contracts: refactor currency to use fungible traits

* contracts: add minor improvements

* contracts: max holds config set

* contracts: fix some typos

* contracts: map token errors

* fix typo

* contracts: add 0 balance transfer to test

* contracts: not transfer if value is zero

* contracts: [WIP] add StorageDepositHold

* contracts: add storage deposit held event

* contracts: clean up some code and comments

* contracts: add deposit storage released event

* contracts: update comment

* contracts: update slash cannot kill account test

* contracts: fix tests

* contracts: add some comments to the slashing test

* contracts: add some comments to the slashing test

* contracts: remove references to Currency

* contracts: do not transfer if from equals to

* bound BalanceOf<T>

* added FixedPointOperand to Balance trait

* move migrate sequence to config

* remove commented out code

* Update frame/contracts/src/lib.rs

Co-authored-by: PG Herveou <pgherveou@gmail.com>

* remove Migrations generic

* make runtime use noop migrations

* restrict is_upgrade_supported

* undo is_upgrade_supported change

* Update bin/node/runtime/src/lib.rs

Co-authored-by: PG Herveou <pgherveou@gmail.com>

* add rust doc example for `Migrations`

* feature gate NoopMigration

* fix example code

* improve example

* wip

* remove FixedPointOperand from trait

* trait bound BalanceOf

* more trait bound BalanceOf

* update to use RuntimeHoldReason

* replace Fungible for Currency

* update runtime

* WIP

* make v10 benchmark generic over currency

* solve merge conflicts

* make v12 migration benchmarking generic over DepositPerItem and DepositPerByte

* give some format

* fix tests and old migrations

* add migration v13 placholder

* wip

* wip

* add benchmarking

* add weights

* wip

* [pallet_collective] Enforce prime is a valid member of collective in set_members extrinsic (#14354)

* Updated set_members extrinsic to enforce prime is valid member of collective

* Added additional tests for set_members extrinsic

* applied the code review suggestions

* update to docify 0.2.0 / crate-relative embed paths (#14570)

* Fix Society v2 migration (#14421)

* fix society v2 migration

* Update frame/society/src/migrations.rs

* Update frame/society/src/migrations.rs

Co-authored-by: Bastian Köcher <git@kchr.de>

* Update frame/society/src/migrations.rs

Co-authored-by: Bastian Köcher <git@kchr.de>

* update for versioned upgrade

* fix society v2 migration

* remove references to members being sorted from commnets

* fix type

* fix can_migrate check

* add sanity log

* fix sanity check

* kick ci

* kick ci

* run tests with --experimental flag

* versioned migration cleanup

* revert pipeline change

* use defensive!

* semicolons

* defensive and doc comment

* address pr comment

* feature gate the versioned migration

* defensive_unwrap_or

* fix test

* fix doc comment

* change defensive to a log warning

* remove can_migrate anti-pattern

* Update frame/society/Cargo.toml

Co-authored-by: Bastian Köcher <git@kchr.de>

* add experimental feature warning to doc comment

* update doc comment

* bump ci

* kick ci

* kick ci

* kick ci

---------

Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Bastian Köcher <git@kchr.de>

* Moves `Block` to `frame_system` instead of `construct_runtime` and removes `Header` and `BlockNumber` (#14437)

* Initial setup

* Adds node block

* Uses UncheckedExtrinsic and removes Where section

* Updates frame_system to use Block

* Adds deprecation warning

* Fixes pallet-timestamp

* Removes Header and BlockNumber

* Addresses review comments

* Addresses review comments

* Adds comment about compiler bug

* Removes where clause

* Refactors code

* Fixes errors in cargo check

* Fixes errors in cargo check

* Fixes warnings in cargo check

* Formatting

* Fixes construct_runtime tests

* Uses import instead of full path for BlockNumber

* Uses import instead of full path for Header

* Formatting

* Fixes construct_runtime tests

* Fixes imports in benchmarks

* Formatting

* Fixes construct_runtime tests

* Formatting

* Minor updates

* Fixes construct_runtime ui tests

* Fixes construct_runtime ui tests with 1.70

* Fixes docs

* Fixes docs

* Adds u128 mock block type

* Fixes split example

* fixes for cumulus

* ".git/.scripts/commands/fmt/fmt.sh"

* Updates new tests

* Fixes fully-qualified path in few places

* Formatting

* Update frame/examples/default-config/src/lib.rs

Co-authored-by: Juan <juangirini@gmail.com>

* Update frame/support/procedural/src/construct_runtime/mod.rs

Co-authored-by: Juan <juangirini@gmail.com>

* ".git/.scripts/commands/fmt/fmt.sh"

* Addresses some review comments

* Fixes build

* ".git/.scripts/commands/fmt/fmt.sh"

* Update frame/democracy/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/democracy/src/lib.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/support/procedural/src/construct_runtime/mod.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/support/procedural/src/construct_runtime/mod.rs

Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Addresses review comments

* Updates trait bounds

* Minor fix

* ".git/.scripts/commands/fmt/fmt.sh"

* Removes unnecessary bound

* ".git/.scripts/commands/fmt/fmt.sh"

* Updates test

* Fixes build

* Adds a bound for header

* ".git/.scripts/commands/fmt/fmt.sh"

* Removes where block

* Minor fix

* Minor fix

* Fixes tests

* ".git/.scripts/commands/update-ui/update-ui.sh" 1.70

* Updates test

* Update primitives/runtime/src/traits.rs

Co-authored-by: Bastian Köcher <git@kchr.de>

* Update primitives/runtime/src/traits.rs

Co-authored-by: Bastian Köcher <git@kchr.de>

* Updates doc

* Updates doc

---------

Co-authored-by: command-bot <>
Co-authored-by: Juan <juangirini@gmail.com>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Bastian Köcher <git@kchr.de>

* Refactor the asset-conversion-tx-payment pallet (#14558)

* Code refactoring

* Fix imports

* Typo

* Update frame/asset-conversion/src/types.rs

Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com>

* Sync docs

---------

Co-authored-by: parity-processbot <>
Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com>

* wip

* wip

* wip

* improve try-runtime imports

* remove deposit account

* wip

* wip

* fix benchmark test

* improved rustdocs

* improved rustdocs

* remove log

* ignore variable

* reduce caller funding

* wip

* fix tests

* fix tests

* move v13 out

* add v14

* update v13 migration

* v13 migration

* benchmark v13_migration

* fix broken compilation

* ".git/.scripts/commands/bench/bench.sh" --subcommand=pallet --runtime=dev --target_dir=substrate --pallet=pallet_contracts

* remove all the `where BalanceOf`

* add Balance to Config

* improve docs

* add new deposit storage error

* remove todo message

* wip

* rename migration v13 pre rebase

* fix tests

* add missing migration;

* bump storage version

* apply review suggestions

* improved comment

* remove unnecessary code

* simplify migrations

* mock balance

* mock more for benchmarks

* make room for rebaes

* make room for rebase

* fix benchmarking tests

* fix benchmarking tests with caller

* improve cargo toml

* solve nit

* Update frame/contracts/src/lib.rs

Co-authored-by: Alexander Theißen <alex.theissen@me.com>

* Update frame/contracts/src/exec.rs

Co-authored-by: Alexander Theißen <alex.theissen@me.com>

* Update frame/contracts/src/exec.rs

Co-authored-by: Alexander Theißen <alex.theissen@me.com>

* Update frame/contracts/src/storage/meter.rs

Co-authored-by: Alexander Theißen <alex.theissen@me.com>

* review improvements

* remove extra events

* update cargo

* undo update cargo

* review updates

* wip

* wip

* fix test

* remove type Balance

* add extra fields to events

* fix zepter ci

* fix tests

* remove commented out code

* remove deposit_account from benchmarking

* update v15 migration

* wip

* remove deposit account from codebase

* add contract info to v15

* make try-runtime fixes

* fix wrong v14 logs

* add extra post upgrade steps

* remove old comments

* wip

* fix delegate deposit test

* ".git/.scripts/commands/bench/bench.sh" --subcommand=pallet --runtime=dev --target_dir=substrate --pallet=pallet_contracts

* wip

* wip

* wip

* implement review updates

* ".git/.scripts/commands/bench/bench.sh" --subcommand=pallet --runtime=dev --target_dir=substrate --pallet=pallet_contracts

* fix documentation

* fix consumers/providers

* fix consumers/providers

* do not check consumers in migration

* review comments addressed

* update fully qualified System

* wip

* wip

* Transfer to beneficiary after `transfer_on_hold` (#14767)

* transfer to beneficiary after transfer_on_hold

* wip

* add consumer comment

* review updates

* fix typo

* make clippy happy

* refactor `Terminated`

* rename ContractStatus to ContractState

* rename status to state

* replace Contribution::Alive to ContractState::Alive

* defer storage deposit charge

* ".git/.scripts/commands/fmt/fmt.sh"

* remove unused imports

* Update frame/contracts/src/migration/v15.rs

Co-authored-by: Sasha Gryaznov <hi@agryaznov.com>

* Update frame/contracts/src/storage/meter.rs

Co-authored-by: Sasha Gryaznov <hi@agryaznov.com>

---------

Co-authored-by: PG Herveou <pgherveou@gmail.com>
Co-authored-by: Toufeeq Pasha <47236805+ToufeeqP@users.noreply.github.com>
Co-authored-by: Sam Johnson <sam@durosoft.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Co-authored-by: Bastian Köcher <git@kchr.de>
Co-authored-by: gupnik <17176722+gupnik@users.noreply.github.com>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: Jegor Sidorenko <5252494+jsidorenko@users.noreply.github.com>
Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com>
Co-authored-by: command-bot <>
Co-authored-by: Alexander Theißen <alex.theissen@me.com>
Co-authored-by: Sasha Gryaznov <hi@agryaznov.com>
This commit is contained in:
Juan
2023-08-18 16:24:55 +02:00
committed by GitHub
parent 91d2ac11b3
commit 9c5315961e
15 changed files with 1931 additions and 1523 deletions
-13
View File
@@ -40,12 +40,6 @@ pub trait AddressGenerator<T: Config> {
input_data: &[u8],
salt: &[u8],
) -> T::AccountId;
/// The address of the deposit account of `contract_addr`.
///
/// The address is generated once on instantiation and then stored in the contracts
/// metadata. Hence changes do only affect newly created contracts.
fn deposit_address(contract_addr: &T::AccountId) -> T::AccountId;
}
/// Default address generator.
@@ -71,11 +65,4 @@ impl<T: Config> AddressGenerator<T> for DefaultAddressGenerator {
Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
.expect("infinite length input; no invalid inputs for type; qed")
}
/// Formula: `hash("contract_depo_v1" ++ contract_addr)`
fn deposit_address(contract_addr: &T::AccountId) -> T::AccountId {
let entropy = (b"contract_depo_v1", contract_addr).using_encoded(T::Hashing::hash);
Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
.expect("infinite length input; no invalid inputs for type; qed")
}
}
@@ -30,7 +30,9 @@ use self::{
};
use crate::{
exec::{AccountIdOf, Key},
migration::{codegen::LATEST_MIGRATION_VERSION, v09, v10, v11, v12, v13, v14, MigrationStep},
migration::{
codegen::LATEST_MIGRATION_VERSION, v09, v10, v11, v12, v13, v14, v15, MigrationStep,
},
wasm::CallFlags,
Pallet as Contracts, *,
};
@@ -296,6 +298,19 @@ benchmarks! {
m.step();
}
// This benchmarks the v15 migration step (remove deposit account).
#[pov_mode = Measured]
v15_migration_step {
let contract = <Contract<T>>::with_caller(
whitelisted_caller(), WasmModule::dummy(), vec![],
)?;
v15::store_old_contract_info::<T>(contract.account_id.clone(), contract.info()?);
let mut m = v15::Migration::<T>::default();
}: {
m.step();
}
// This benchmarks the weight of executing Migration::migrate to execute a noop migration.
#[pov_mode = Measured]
migration_noop {
@@ -397,10 +412,9 @@ benchmarks! {
let addr = Contracts::<T>::contract_address(&caller, &hash, &input, &salt);
}: _(origin, value, Weight::MAX, None, code, input, salt)
verify {
let deposit_account = Contract::<T>::address_info(&addr)?.deposit_account().clone();
let deposit = T::Currency::balance(&deposit_account);
let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr);
// uploading the code reserves some balance in the callers account
let code_deposit = T::Currency::total_balance_on_hold(&caller);
let code_deposit = T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &caller);
assert_eq!(
T::Currency::balance(&caller),
caller_funding::<T>() - value - deposit - code_deposit - Pallet::<T>::min_balance(),
@@ -427,8 +441,7 @@ benchmarks! {
Contracts::<T>::store_code_raw(code, caller.clone())?;
}: _(origin, value, Weight::MAX, None, hash, input, salt)
verify {
let deposit_account = Contract::<T>::address_info(&addr)?.deposit_account().clone();
let deposit = T::Currency::balance(&deposit_account);
let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &addr);
// value was removed from the caller
assert_eq!(
T::Currency::balance(&caller),
@@ -451,15 +464,13 @@ benchmarks! {
let instance = Contract::<T>::with_caller(
whitelisted_caller(), WasmModule::dummy(), vec![],
)?;
let deposit_account = instance.info()?.deposit_account().clone();
let value = Pallet::<T>::min_balance();
let origin = RawOrigin::Signed(instance.caller.clone());
let callee = instance.addr.clone();
let before = T::Currency::balance(&instance.account_id);
let before_deposit = T::Currency::balance(&deposit_account);
}: _(origin, callee, value, Weight::MAX, None, data)
verify {
let deposit = T::Currency::balance(&deposit_account);
let deposit = T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id);
// value and value transferred via call should be removed from the caller
assert_eq!(
T::Currency::balance(&instance.caller),
@@ -930,15 +941,14 @@ benchmarks! {
});
let instance = Contract::<T>::new(code, vec![])?;
let origin = RawOrigin::Signed(instance.caller.clone());
let deposit_account = instance.info()?.deposit_account().clone();
assert_eq!(T::Currency::total_balance(&beneficiary), 0u32.into());
assert_eq!(T::Currency::balance(&instance.account_id), Pallet::<T>::min_balance() * 2u32.into());
assert_ne!(T::Currency::balance(&deposit_account), 0u32.into());
assert_ne!(T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into());
}: call(origin, instance.addr.clone(), 0u32.into(), Weight::MAX, None, vec![])
verify {
if r > 0 {
assert_eq!(T::Currency::total_balance(&instance.account_id), 0u32.into());
assert_eq!(T::Currency::total_balance(&deposit_account), 0u32.into());
assert_eq!(T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &instance.account_id), 0u32.into());
assert_eq!(T::Currency::total_balance(&beneficiary), Pallet::<T>::min_balance() * 2u32.into());
}
}
+14 -46
View File
@@ -19,10 +19,10 @@
use crate::unsafe_debug::ExecutionObserver;
use crate::{
gas::GasMeter,
storage::{self, meter::Diff, DepositAccount, WriteOutcome},
storage::{self, meter::Diff, WriteOutcome},
BalanceOf, CodeHash, CodeInfo, CodeInfoOf, Config, ContractInfo, ContractInfoOf,
DebugBufferVec, Determinism, Error, Event, Nonce, Origin, Pallet as Contracts, Schedule,
System, WasmBlob, LOG_TARGET,
WasmBlob, LOG_TARGET,
};
use frame_support::{
crypto::ecdsa::ECDSAExt,
@@ -33,7 +33,7 @@ use frame_support::{
storage::{with_transaction, TransactionOutcome},
traits::{
fungible::{Inspect, Mutate},
tokens::{Fortitude::Polite, Preservation},
tokens::Preservation,
Contains, OriginTrait, Randomness, Time,
},
weights::Weight,
@@ -547,7 +547,7 @@ enum CachedContract<T: Config> {
///
/// In this case a reload is neither allowed nor possible. Please note that recursive
/// calls cannot remove a contract as this is checked and denied.
Terminated(DepositAccount<T>),
Terminated,
}
impl<T: Config> CachedContract<T> {
@@ -568,15 +568,6 @@ impl<T: Config> CachedContract<T> {
None
}
}
/// Returns `Some` iff the contract is not `Cached::Invalidated`.
fn deposit_account(&self) -> Option<&DepositAccount<T>> {
match self {
CachedContract::Cached(contract) => Some(contract.deposit_account()),
CachedContract::Terminated(deposit_account) => Some(&deposit_account),
CachedContract::Invalidated => None,
}
}
}
impl<T: Config> Frame<T> {
@@ -655,9 +646,7 @@ impl<T: Config> CachedContract<T> {
/// Terminate and return the contract info.
fn terminate(&mut self, account_id: &T::AccountId) -> ContractInfo<T> {
self.load(account_id);
let contract = get_cached_or_panic_after_load!(self);
let deposit_account = contract.deposit_account().clone();
get_cached_or_panic_after_load!(mem::replace(self, Self::Terminated(deposit_account)))
get_cached_or_panic_after_load!(mem::replace(self, Self::Terminated))
}
}
@@ -955,7 +944,7 @@ where
match (entry_point, delegated_code_hash) {
(ExportedFunction::Constructor, _) => {
// It is not allowed to terminate a contract inside its constructor.
if matches!(frame.contract_info, CachedContract::Terminated(_)) {
if matches!(frame.contract_info, CachedContract::Terminated) {
return Err(Error::<T>::TerminatedInConstructor.into())
}
@@ -1059,18 +1048,8 @@ where
// in its contract info. The load is necessary to pull it from storage in case
// it was invalidated.
frame.contract_info.load(account_id);
let deposit_account = frame
.contract_info
.deposit_account()
.expect(
"Is only `None` when the info is invalidated.
We just re-loaded from storage which either makes the state `Cached` or `Terminated`.
qed",
)
.clone();
let mut contract = frame.contract_info.into_contract();
prev.nested_storage
.absorb(frame.nested_storage, deposit_account, contract.as_mut());
prev.nested_storage.absorb(frame.nested_storage, account_id, contract.as_mut());
// In case the contract wasn't terminated we need to persist changes made to it.
if let Some(contract) = contract {
@@ -1105,14 +1084,10 @@ where
if !persist {
return
}
let deposit_account = self.first_frame.contract_info.deposit_account().expect(
"Is only `None` when the info is invalidated. The first frame can't be invalidated.
qed",
).clone();
let mut contract = self.first_frame.contract_info.as_contract();
self.storage_meter.absorb(
mem::take(&mut self.first_frame.nested_storage),
deposit_account,
&self.first_frame.account_id,
contract.as_deref_mut(),
);
if let Some(contract) = contract {
@@ -1311,14 +1286,8 @@ where
}
let frame = self.top_frame_mut();
let info = frame.terminate();
frame.nested_storage.terminate(&info);
System::<T>::dec_consumers(&frame.account_id);
Self::transfer(
Preservation::Expendable,
&frame.account_id,
beneficiary,
T::Currency::reducible_balance(&frame.account_id, Preservation::Expendable, Polite),
)?;
frame.nested_storage.terminate(&info, beneficiary.clone());
info.queue_trie_for_deletion();
ContractInfoOf::<T>::remove(&frame.account_id);
E::decrement_refcount(info.code_hash);
@@ -1327,7 +1296,7 @@ where
E::decrement_refcount(*code_hash);
frame
.nested_storage
.charge_deposit(info.deposit_account().clone(), StorageDeposit::Refund(*deposit));
.charge_deposit(frame.account_id.clone(), StorageDeposit::Refund(*deposit));
}
Contracts::<T>::deposit_event(
@@ -1521,8 +1490,7 @@ where
let deposit = StorageDeposit::Charge(new_base_deposit)
.saturating_sub(&StorageDeposit::Charge(old_base_deposit));
let deposit_account = info.deposit_account().clone();
frame.nested_storage.charge_deposit(deposit_account, deposit);
frame.nested_storage.charge_deposit(frame.account_id.clone(), deposit);
E::increment_refcount(hash)?;
E::decrement_refcount(prev_hash);
@@ -1573,7 +1541,7 @@ where
<WasmBlob<T>>::increment_refcount(code_hash)?;
frame
.nested_storage
.charge_deposit(info.deposit_account().clone(), StorageDeposit::Charge(deposit));
.charge_deposit(frame.account_id.clone(), StorageDeposit::Charge(deposit));
Ok(())
}
@@ -1589,7 +1557,7 @@ where
frame
.nested_storage
.charge_deposit(info.deposit_account().clone(), StorageDeposit::Refund(deposit));
.charge_deposit(frame.account_id.clone(), StorageDeposit::Refund(deposit));
Ok(())
}
}
+17 -1
View File
@@ -187,7 +187,7 @@ pub mod pallet {
use sp_runtime::Perbill;
/// The current storage version.
pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(14);
pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(15);
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
@@ -899,6 +899,20 @@ pub mod pallet {
/// The code hash that was delegate called.
code_hash: CodeHash<T>,
},
/// Some funds have been transferred and held as storage deposit.
StorageDepositTransferredAndHeld {
from: T::AccountId,
to: T::AccountId,
amount: BalanceOf<T>,
},
/// Some storage deposit funds have been transferred and released.
StorageDepositTransferredAndReleased {
from: T::AccountId,
to: T::AccountId,
amount: BalanceOf<T>,
},
}
#[pallet::error]
@@ -999,6 +1013,8 @@ pub mod pallet {
pub enum HoldReason {
/// The Pallet has reserved it for storing code on-chain.
CodeUploadDepositReserve,
/// The Pallet has reserved it for storage deposit.
StorageDepositReserve,
}
/// A mapping from a contract's code hash to its code.
@@ -63,6 +63,7 @@ pub mod v11;
pub mod v12;
pub mod v13;
pub mod v14;
pub mod v15;
include!(concat!(env!("OUT_DIR"), "/migration_codegen.rs"));
use crate::{weights::WeightInfo, Config, Error, MigrationInProgress, Pallet, Weight, LOG_TARGET};
+15 -4
View File
@@ -19,7 +19,6 @@
//! See <https://github.com/paritytech/substrate/pull/13369>.
use crate::{
address::AddressGenerator,
exec::AccountIdOf,
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
@@ -40,7 +39,10 @@ use frame_support::{
use sp_core::hexdisplay::HexDisplay;
#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;
use sp_runtime::{traits::Zero, Perbill, Saturating};
use sp_runtime::{
traits::{Hash, TrailingZeroInput, Zero},
Perbill, Saturating,
};
use sp_std::{ops::Deref, prelude::*};
mod old {
@@ -135,6 +137,16 @@ type ContractInfoOf<T: Config, OldCurrency> = StorageMap<
ContractInfo<T, OldCurrency>,
>;
/// Formula: `hash("contract_depo_v1" ++ contract_addr)`
fn deposit_address<T: Config>(
contract_addr: &<T as frame_system::Config>::AccountId,
) -> <T as frame_system::Config>::AccountId {
let entropy = (b"contract_depo_v1", contract_addr)
.using_encoded(<T as frame_system::Config>::Hashing::hash);
Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
.expect("infinite length input; no invalid inputs for type; qed")
}
impl<T: Config, OldCurrency: 'static> MigrationStep for Migration<T, OldCurrency>
where
OldCurrency: ReservableCurrency<<T as frame_system::Config>::AccountId>
@@ -162,8 +174,7 @@ where
log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode()));
// Get the new deposit account address
let deposit_account: DepositAccount<T> =
DepositAccount(T::AddressGenerator::deposit_address(&account));
let deposit_account: DepositAccount<T> = DepositAccount(deposit_address::<T>(&account));
// Calculate the existing deposit, that should be reserved on the contract account
let old_deposit = contract
@@ -20,9 +20,8 @@
use crate::{
migration::{IsFinished, MigrationStep},
storage::DepositAccount,
weights::WeightInfo,
BalanceOf, CodeHash, Config, Pallet, TrieId, Weight, LOG_TARGET,
AccountIdOf, BalanceOf, CodeHash, Config, Pallet, TrieId, Weight, LOG_TARGET,
};
use codec::{Decode, Encode};
use frame_support::{codec, pallet_prelude::*, storage_alias, DefaultNoBound};
@@ -30,15 +29,13 @@ use sp_runtime::BoundedBTreeMap;
use sp_std::prelude::*;
mod old {
use crate::storage::DepositAccount;
use super::*;
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
pub struct ContractInfo<T: Config> {
pub trie_id: TrieId,
pub deposit_account: DepositAccount<T>,
pub deposit_account: AccountIdOf<T>,
pub code_hash: CodeHash<T>,
pub storage_bytes: u32,
pub storage_items: u32,
@@ -58,9 +55,13 @@ mod old {
#[cfg(feature = "runtime-benchmarks")]
pub fn store_old_contract_info<T: Config>(account: T::AccountId, info: crate::ContractInfo<T>) {
use sp_runtime::traits::{Hash, TrailingZeroInput};
let entropy = (b"contract_depo_v1", account.clone()).using_encoded(T::Hashing::hash);
let deposit_account = Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
.expect("infinite length input; no invalid inputs for type; qed");
let info = old::ContractInfo {
trie_id: info.trie_id.clone(),
deposit_account: info.deposit_account().clone(),
deposit_account,
code_hash: info.code_hash,
storage_bytes: Default::default(),
storage_items: Default::default(),
@@ -79,7 +80,7 @@ pub type ContractInfoOf<T: Config> =
#[scale_info(skip_type_params(T))]
pub struct ContractInfo<T: Config> {
trie_id: TrieId,
deposit_account: DepositAccount<T>,
deposit_account: AccountIdOf<T>,
code_hash: CodeHash<T>,
storage_bytes: u32,
storage_items: u32,
+11 -8
View File
@@ -15,7 +15,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! Update the code owner balance, make the storage deposit reserved balance to be held instead.
//! Update the code owner balance, make the code upload deposit balance to be held instead of
//! reserved. Since [`Currency`](frame_support::traits::Currency) has been
//! [deprecated](https://github.com/paritytech/substrate/pull/12951), we need the deposits to be
//! handled by the [`frame_support::traits::fungible`] traits.
use crate::{
exec::AccountIdOf,
@@ -102,7 +105,7 @@ where
T: Config,
OldCurrency: ReservableCurrency<<T as frame_system::Config>::AccountId>,
{
/// Total reserved balance as storage deposit for the owner.
/// Total reserved balance as code upload deposit for the owner.
reserved: old::BalanceOf<T, OldCurrency>,
/// Total balance of the owner.
total: old::BalanceOf<T, OldCurrency>,
@@ -140,7 +143,7 @@ where
};
if let Some((hash, code_info)) = iter.next() {
log::debug!(target: LOG_TARGET, "Migrating storage deposit for 0x{:?}", HexDisplay::from(&code_info.owner.encode()));
log::debug!(target: LOG_TARGET, "Migrating code upload deposit for 0x{:?}", HexDisplay::from(&code_info.owner.encode()));
let remaining = OldCurrency::unreserve(&code_info.owner, code_info.deposit);
@@ -185,7 +188,7 @@ where
self.last_code_hash = Some(hash);
(IsFinished::No, T::WeightInfo::v14_migration_step())
} else {
log::debug!(target: LOG_TARGET, "No more storage deposit to migrate");
log::debug!(target: LOG_TARGET, "No more code upload deposit to migrate");
(IsFinished::Yes, T::WeightInfo::v14_migration_step())
}
}
@@ -197,8 +200,8 @@ where
let mut owner_balance_allocation =
BTreeMap::<AccountIdOf<T>, BalanceAllocation<T, OldCurrency>>::new();
// Calculates the balance allocation by accumulating the storage deposits of all codes owned
// by an owner.
// Calculates the balance allocation by accumulating the code upload deposits of all codes
// owned by an owner.
for (_, code_info) in info {
owner_balance_allocation
.entry(code_info.owner.clone())
@@ -229,7 +232,7 @@ where
T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &owner);
log::debug!(
target: LOG_TARGET,
"Validating storage deposit for owner 0x{:?}, reserved: {:?}, held: {:?}",
"Validating code upload deposit for owner 0x{:?}, reserved: {:?}, held: {:?}",
HexDisplay::from(&owner.encode()),
old_balance_allocation.reserved,
held
@@ -260,7 +263,7 @@ where
log::info!(
target: LOG_TARGET,
"Total held amount for storage deposit: {:?}",
"Total held amount for code upload deposit: {:?}",
total_held
);
@@ -0,0 +1,327 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Move contracts' _reserved_ balance from the `deposit_account` to be _held_ in the contract's
//! account instead. Since [`Currency`](frame_support::traits::Currency) has been
//! [deprecated](https://github.com/paritytech/substrate/pull/12951), we need the deposits to be
//! handled by the [`frame_support::traits::fungible`] traits instead. For this transfer the
//! balance from the deposit account to the contract's account and hold it in there.
//! Then the deposit account is not needed anymore and we can get rid of it.
use crate::{
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
AccountIdOf, BalanceOf, CodeHash, Config, HoldReason, Pallet, TrieId, Weight, LOG_TARGET,
};
#[cfg(feature = "try-runtime")]
use frame_support::{dispatch::Vec, traits::fungible::InspectHold};
use frame_support::{
pallet_prelude::*,
storage_alias,
traits::{
fungible::{Mutate, MutateHold},
tokens::{fungible::Inspect, Fortitude, Preservation},
},
BoundedBTreeMap, DefaultNoBound,
};
use frame_system::Pallet as System;
use sp_core::hexdisplay::HexDisplay;
#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;
use sp_runtime::{traits::Zero, Saturating};
mod old {
use super::*;
#[derive(
Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen,
)]
#[scale_info(skip_type_params(T))]
pub struct ContractInfo<T: Config> {
pub trie_id: TrieId,
pub deposit_account: AccountIdOf<T>,
pub code_hash: CodeHash<T>,
pub storage_bytes: u32,
pub storage_items: u32,
pub storage_byte_deposit: BalanceOf<T>,
pub storage_item_deposit: BalanceOf<T>,
pub storage_base_deposit: BalanceOf<T>,
pub delegate_dependencies:
BoundedBTreeMap<CodeHash<T>, BalanceOf<T>, T::MaxDelegateDependencies>,
}
#[storage_alias]
pub type ContractInfoOf<T: Config> = StorageMap<
Pallet<T>,
Twox64Concat,
<T as frame_system::Config>::AccountId,
ContractInfo<T>,
>;
}
#[cfg(feature = "runtime-benchmarks")]
pub fn store_old_contract_info<T: Config>(account: T::AccountId, info: crate::ContractInfo<T>) {
use sp_runtime::traits::{Hash, TrailingZeroInput};
let entropy = (b"contract_depo_v1", account.clone()).using_encoded(T::Hashing::hash);
let deposit_account = Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref()))
.expect("infinite length input; no invalid inputs for type; qed");
let info = old::ContractInfo {
trie_id: info.trie_id.clone(),
deposit_account,
code_hash: info.code_hash,
storage_bytes: Default::default(),
storage_items: Default::default(),
storage_byte_deposit: info.storage_byte_deposit,
storage_item_deposit: Default::default(),
storage_base_deposit: info.storage_base_deposit(),
delegate_dependencies: info.delegate_dependencies().clone(),
};
old::ContractInfoOf::<T>::insert(account, info);
}
#[derive(Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
struct ContractInfo<T: Config> {
pub trie_id: TrieId,
pub code_hash: CodeHash<T>,
pub storage_bytes: u32,
pub storage_items: u32,
pub storage_byte_deposit: BalanceOf<T>,
pub storage_item_deposit: BalanceOf<T>,
pub storage_base_deposit: BalanceOf<T>,
pub delegate_dependencies:
BoundedBTreeMap<CodeHash<T>, BalanceOf<T>, T::MaxDelegateDependencies>,
}
#[storage_alias]
type ContractInfoOf<T: Config> =
StorageMap<Pallet<T>, Twox64Concat, <T as frame_system::Config>::AccountId, ContractInfo<T>>;
#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)]
pub struct Migration<T: Config> {
last_account: Option<T::AccountId>,
}
impl<T: Config> MigrationStep for Migration<T> {
const VERSION: u16 = 15;
fn max_step_weight() -> Weight {
T::WeightInfo::v15_migration_step()
}
fn step(&mut self) -> (IsFinished, Weight) {
let mut iter = if let Some(last_account) = self.last_account.take() {
old::ContractInfoOf::<T>::iter_from(old::ContractInfoOf::<T>::hashed_key_for(
last_account,
))
} else {
old::ContractInfoOf::<T>::iter()
};
if let Some((account, old_contract)) = iter.next() {
let deposit_account = &old_contract.deposit_account;
System::<T>::dec_consumers(deposit_account);
// Get the deposit balance to transfer.
let total_deposit_balance = T::Currency::total_balance(deposit_account);
let reducible_deposit_balance = T::Currency::reducible_balance(
deposit_account,
Preservation::Expendable,
Fortitude::Force,
);
if total_deposit_balance > reducible_deposit_balance {
// This should never happen, as by design all balance in the deposit account is
// storage deposit and therefore reducible after decrementing the consumer
// reference.
log::warn!(
target: LOG_TARGET,
"Deposit account 0x{:?} for contract 0x{:?} has some non-reducible balance {:?} from a total of {:?} that will remain in there.",
HexDisplay::from(&deposit_account.encode()),
HexDisplay::from(&account.encode()),
total_deposit_balance.saturating_sub(reducible_deposit_balance),
total_deposit_balance
);
}
// Move balance reserved from the deposit account back to the contract account.
// Let the deposit account die.
log::debug!(
target: LOG_TARGET,
"Transferring {:?} from the deposit account 0x{:?} to the contract 0x{:?}.",
reducible_deposit_balance,
HexDisplay::from(&deposit_account.encode()),
HexDisplay::from(&account.encode())
);
let transferred_deposit_balance = T::Currency::transfer(
deposit_account,
&account,
reducible_deposit_balance,
Preservation::Expendable,
)
.unwrap_or_else(|err| {
log::error!(
target: LOG_TARGET,
"Failed to transfer {:?} from the deposit account 0x{:?} to the contract 0x{:?}, reason: {:?}.",
reducible_deposit_balance,
HexDisplay::from(&deposit_account.encode()),
HexDisplay::from(&account.encode()),
err
);
Zero::zero()
});
// Hold the reserved balance.
if transferred_deposit_balance == Zero::zero() {
log::warn!(
target: LOG_TARGET,
"No balance to hold as storage deposit on the contract 0x{:?}.",
HexDisplay::from(&account.encode())
);
} else {
log::debug!(
target: LOG_TARGET,
"Holding {:?} as storage deposit on the contract 0x{:?}.",
transferred_deposit_balance,
HexDisplay::from(&account.encode())
);
T::Currency::hold(
&HoldReason::StorageDepositReserve.into(),
&account,
transferred_deposit_balance,
)
.unwrap_or_else(|err| {
log::error!(
target: LOG_TARGET,
"Failed to hold {:?} as storage deposit on the contract 0x{:?}, reason: {:?}.",
transferred_deposit_balance,
HexDisplay::from(&account.encode()),
err
);
});
}
log::debug!(target: LOG_TARGET, "===");
let info = ContractInfo {
trie_id: old_contract.trie_id,
code_hash: old_contract.code_hash,
storage_bytes: old_contract.storage_bytes,
storage_items: old_contract.storage_items,
storage_byte_deposit: old_contract.storage_byte_deposit,
storage_item_deposit: old_contract.storage_item_deposit,
storage_base_deposit: old_contract.storage_base_deposit,
delegate_dependencies: old_contract.delegate_dependencies,
};
ContractInfoOf::<T>::insert(account.clone(), info);
// Store last key for next migration step
self.last_account = Some(account);
(IsFinished::No, T::WeightInfo::v15_migration_step())
} else {
log::info!(target: LOG_TARGET, "Done Migrating Storage Deposits.");
(IsFinished::Yes, T::WeightInfo::v15_migration_step())
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade_step() -> Result<Vec<u8>, TryRuntimeError> {
let sample: Vec<_> = old::ContractInfoOf::<T>::iter().take(100).collect();
log::debug!(target: LOG_TARGET, "Taking sample of {} contracts", sample.len());
let state: Vec<(T::AccountId, old::ContractInfo<T>, BalanceOf<T>, BalanceOf<T>)> = sample
.iter()
.map(|(account, contract)| {
(
account.clone(),
contract.clone(),
T::Currency::total_balance(&account),
T::Currency::total_balance(&contract.deposit_account),
)
})
.collect();
Ok(state.encode())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade_step(state: Vec<u8>) -> Result<(), TryRuntimeError> {
let sample =
<Vec<(T::AccountId, old::ContractInfo<T>, BalanceOf<T>, BalanceOf<T>)> as Decode>::decode(
&mut &state[..],
)
.expect("pre_upgrade_step provides a valid state; qed");
log::debug!(target: LOG_TARGET, "Validating sample of {} contracts", sample.len());
for (account, old_contract, old_account_balance, old_deposit_balance) in sample {
log::debug!(target: LOG_TARGET, "===");
log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode()));
let on_hold =
T::Currency::balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account);
let account_balance = T::Currency::total_balance(&account);
log::debug!(
target: LOG_TARGET,
"Validating balances match. Old deposit account's balance: {:?}. Contract's on hold: {:?}. Old contract's total balance: {:?}, Contract's total balance: {:?}.",
old_deposit_balance,
on_hold,
old_account_balance,
account_balance
);
ensure!(
old_account_balance.saturating_add(old_deposit_balance) == account_balance,
"total balance mismatch"
);
ensure!(old_deposit_balance == on_hold, "deposit mismatch");
ensure!(
!System::<T>::account_exists(&old_contract.deposit_account),
"deposit account still exists"
);
let migration_contract_info = ContractInfoOf::<T>::try_get(&account).unwrap();
let crate_contract_info = crate::ContractInfoOf::<T>::try_get(&account).unwrap();
ensure!(
migration_contract_info.trie_id == crate_contract_info.trie_id,
"trie_id mismatch"
);
ensure!(
migration_contract_info.code_hash == crate_contract_info.code_hash,
"code_hash mismatch"
);
ensure!(
migration_contract_info.storage_byte_deposit ==
crate_contract_info.storage_byte_deposit,
"storage_byte_deposit mismatch"
);
ensure!(
migration_contract_info.storage_base_deposit ==
crate_contract_info.storage_base_deposit(),
"storage_base_deposit mismatch"
);
ensure!(
&migration_contract_info.delegate_dependencies ==
crate_contract_info.delegate_dependencies(),
"delegate_dependencies mismatch"
);
}
Ok(())
}
}
+7 -31
View File
@@ -22,15 +22,15 @@ pub mod meter;
use crate::{
exec::{AccountIdOf, Key},
weights::WeightInfo,
AddressGenerator, BalanceOf, CodeHash, CodeInfo, Config, ContractInfoOf, DeletionQueue,
DeletionQueueCounter, Error, Pallet, TrieId, SENTINEL,
BalanceOf, CodeHash, CodeInfo, Config, ContractInfoOf, DeletionQueue, DeletionQueueCounter,
Error, Pallet, TrieId, SENTINEL,
};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
dispatch::DispatchError,
storage::child::{self, ChildInfo},
weights::Weight,
CloneNoBound, DefaultNoBound, RuntimeDebugNoBound,
CloneNoBound, DefaultNoBound,
};
use scale_info::TypeInfo;
use sp_core::Get;
@@ -39,7 +39,7 @@ use sp_runtime::{
traits::{Hash, Saturating, Zero},
BoundedBTreeMap, DispatchResult, RuntimeDebug,
};
use sp_std::{marker::PhantomData, ops::Deref, prelude::*};
use sp_std::{marker::PhantomData, prelude::*};
use self::meter::Diff;
@@ -50,10 +50,6 @@ use self::meter::Diff;
pub struct ContractInfo<T: Config> {
/// Unique ID for the subtree encoded as a bytes vector.
pub trie_id: TrieId,
/// The account that holds this contracts storage deposit.
///
/// This is held in a separate account to prevent the contract from spending it.
deposit_account: DepositAccount<T>,
/// The code associated with a given account.
pub code_hash: CodeHash<T>,
/// How many bytes of storage are accumulated in this contract's child trie.
@@ -99,11 +95,8 @@ impl<T: Config> ContractInfo<T> {
.expect("Runtime uses a reasonable hash size. Hence sizeof(T::Hash) <= 128; qed")
};
let deposit_account = DepositAccount(T::AddressGenerator::deposit_address(account));
let contract = Self {
trie_id,
deposit_account,
code_hash,
storage_bytes: 0,
storage_items: 0,
@@ -133,11 +126,6 @@ impl<T: Config> ContractInfo<T> {
.saturating_sub(Pallet::<T>::min_balance())
}
/// Returns the account that storage deposits should be deposited into.
pub fn deposit_account(&self) -> &DepositAccount<T> {
&self.deposit_account
}
/// Returns the storage base deposit of the contract.
pub fn storage_base_deposit(&self) -> BalanceOf<T> {
self.storage_base_deposit
@@ -233,9 +221,9 @@ impl<T: Config> ContractInfo<T> {
let upload_deposit = T::CodeHashLockupDepositPercent::get().mul_ceil(code_info.deposit());
// Instantiate needs to transfer at least the minimum balance in order to pull the
// deposit account into existence.
// We also add another `ed` here which goes to the contract's own account into existence.
let deposit = info_deposit.saturating_add(upload_deposit).max(ed).saturating_add(ed);
// contract's own account into existence, as the deposit itself does not contribute to the
// `ed`.
let deposit = info_deposit.saturating_add(upload_deposit).saturating_add(ed);
self.storage_base_deposit = deposit;
deposit
@@ -391,18 +379,6 @@ impl WriteOutcome {
}
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebugNoBound, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
pub struct DepositAccount<T: Config>(AccountIdOf<T>);
impl<T: Config> Deref for DepositAccount<T> {
type Target = AccountIdOf<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Manage the removal of contracts storage that are marked for deletion.
///
/// When a contract is deleted by calling `seal_terminate` it becomes inaccessible
+146 -92
View File
@@ -18,25 +18,28 @@
//! This module contains functions to meter the storage deposit.
use crate::{
storage::{ContractInfo, DepositAccount},
BalanceOf, CodeInfo, Config, Error, Inspect, Origin, Pallet, StorageDeposit as Deposit, System,
storage::ContractInfo, AccountIdOf, BalanceOf, CodeInfo, Config, Error, Event, HoldReason,
Inspect, Origin, Pallet, StorageDeposit as Deposit, System, LOG_TARGET,
};
use frame_support::{
dispatch::{fmt::Debug, DispatchError},
ensure,
traits::{
fungible::Mutate,
tokens::{Fortitude::Polite, Preservation, WithdrawConsequence},
fungible::{Mutate, MutateHold},
tokens::{
Fortitude, Fortitude::Polite, Precision, Preservation, Restriction, WithdrawConsequence,
},
Get,
},
DefaultNoBound, RuntimeDebugNoBound,
};
use sp_api::HashT;
use sp_runtime::{
traits::{Saturating, Zero},
FixedPointNumber, FixedU128,
};
use sp_std::{marker::PhantomData, vec::Vec};
use sp_std::{marker::PhantomData, vec, vec::Vec};
/// Deposit that uses the native fungible's balance type.
pub type DepositOf<T> = Deposit<BalanceOf<T>>;
@@ -75,16 +78,15 @@ pub trait Ext<T: Config> {
/// This is called to inform the implementer that some balance should be charged due to
/// some interaction of the `origin` with a `contract`.
///
/// The balance transfer can either flow from `origin` to `deposit_account` or the other way
/// The balance transfer can either flow from `origin` to `contract` or the other way
/// around depending on whether `amount` constitutes a `Charge` or a `Refund`.
/// It is guaranteed that this succeeds because no more balance than returned by
/// `check_limit` is ever charged. This is why this function is infallible.
/// `terminated` designates whether the `contract` was terminated.
/// It should be used in combination with `check_limit` to check that no more balance than this
/// limit is ever charged.
fn charge(
origin: &T::AccountId,
deposit_account: &DepositAccount<T>,
contract: &T::AccountId,
amount: &DepositOf<T>,
terminated: bool,
state: &ContractState<T>,
) -> Result<(), DispatchError>;
}
@@ -220,6 +222,15 @@ impl Diff {
}
}
/// The state of a contract.
///
/// In case of termination the beneficiary is indicated.
#[derive(RuntimeDebugNoBound, Clone, PartialEq, Eq)]
pub enum ContractState<T: Config> {
Alive,
Terminated { beneficiary: AccountIdOf<T> },
}
/// Records information to charge or refund a plain account.
///
/// All the charges are deferred to the end of a whole call stack. Reason is that by doing
@@ -231,9 +242,9 @@ impl Diff {
/// exhausted.
#[derive(RuntimeDebugNoBound, Clone)]
struct Charge<T: Config> {
deposit_account: DepositAccount<T>,
contract: T::AccountId,
amount: DepositOf<T>,
terminated: bool,
state: ContractState<T>,
}
/// Records the storage changes of a storage meter.
@@ -245,8 +256,9 @@ enum Contribution<T: Config> {
/// its execution. In this process the [`Diff`] was converted into a [`Deposit`].
Checked(DepositOf<T>),
/// The contract was terminated. In this process the [`Diff`] was converted into a [`Deposit`]
/// in order to calculate the refund.
Terminated(DepositOf<T>),
/// in order to calculate the refund. Upon termination the `reducible_balance` in the
/// contract's account is transferred to the [`beneficiary`].
Terminated { deposit: DepositOf<T>, beneficiary: AccountIdOf<T> },
}
impl<T: Config> Contribution<T> {
@@ -254,7 +266,8 @@ impl<T: Config> Contribution<T> {
fn update_contract(&self, info: Option<&mut ContractInfo<T>>) -> DepositOf<T> {
match self {
Self::Alive(diff) => diff.update_contract::<T>(info),
Self::Terminated(deposit) | Self::Checked(deposit) => deposit.clone(),
Self::Terminated { deposit, beneficiary: _ } | Self::Checked(deposit) =>
deposit.clone(),
}
}
}
@@ -279,7 +292,7 @@ where
/// usage for this sub call separately. This is necessary because we want to exchange balance
/// with the current contract we are interacting with.
pub fn nested(&self, limit: BalanceOf<T>) -> RawMeter<T, E, Nested> {
debug_assert!(self.is_alive());
debug_assert!(matches!(self.contract_state(), ContractState::Alive));
// If a special limit is specified higher than it is available,
// we want to enforce the lesser limit to the nested meter, to fail in the sub-call.
let limit = self.available().min(limit);
@@ -293,7 +306,7 @@ where
/// Absorb a child that was spawned to handle a sub call.
///
/// This should be called whenever a sub call comes to its end and it is **not** reverted.
/// This does the actual balance transfer from/to `origin` and `deposit_account` based on the
/// This does the actual balance transfer from/to `origin` and `contract` based on the
/// overall storage consumption of the call. It also updates the supplied contract info.
///
/// In case a contract reverted the child meter should just be dropped in order to revert
@@ -303,12 +316,12 @@ where
///
/// - `absorbed`: The child storage meter that should be absorbed.
/// - `origin`: The origin that spawned the original root meter.
/// - `deposit_account`: The contract's deposit account that this sub call belongs to.
/// - `contract`: The contract's account that this sub call belongs to.
/// - `info`: The info of the contract in question. `None` if the contract was terminated.
pub fn absorb(
&mut self,
absorbed: RawMeter<T, E, Nested>,
deposit_account: DepositAccount<T>,
contract: &T::AccountId,
info: Option<&mut ContractInfo<T>>,
) {
let own_deposit = absorbed.own_contribution.update_contract(info);
@@ -319,9 +332,9 @@ where
self.charges.extend_from_slice(&absorbed.charges);
if !own_deposit.is_zero() {
self.charges.push(Charge {
deposit_account,
contract: contract.clone(),
amount: own_deposit,
terminated: absorbed.is_terminated(),
state: absorbed.contract_state(),
});
}
}
@@ -331,14 +344,13 @@ where
self.total_deposit.available(&self.limit)
}
/// True if the contract is alive.
fn is_alive(&self) -> bool {
matches!(self.own_contribution, Contribution::Alive(_))
}
/// True if the contract is terminated.
fn is_terminated(&self) -> bool {
matches!(self.own_contribution, Contribution::Terminated(_))
/// Returns the state of the currently executed contract.
fn contract_state(&self) -> ContractState<T> {
match &self.own_contribution {
Contribution::Terminated { deposit: _, beneficiary } =>
ContractState::Terminated { beneficiary: beneficiary.clone() },
_ => ContractState::Alive,
}
}
}
@@ -375,7 +387,6 @@ where
///
/// This drops the root meter in order to make sure it is only called when the whole
/// execution did finish.
pub fn try_into_deposit(self, origin: &Origin<T>) -> Result<DepositOf<T>, DispatchError> {
// Only refund or charge deposit if the origin is not root.
let origin = match origin {
@@ -383,10 +394,10 @@ where
Origin::Signed(o) => o,
};
for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Refund(_))) {
E::charge(origin, &charge.deposit_account, &charge.amount, charge.terminated)?;
E::charge(origin, &charge.contract, &charge.amount, &charge.state)?;
}
for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Charge(_))) {
E::charge(origin, &charge.deposit_account, &charge.amount, charge.terminated)?;
E::charge(origin, &charge.contract, &charge.amount, &charge.state)?;
}
Ok(self.total_deposit)
}
@@ -412,9 +423,9 @@ where
/// change. This is the case when a `delegate_dependency` is added or removed, or when the
/// `code_hash` is updated. [`Self::charge`] cannot be used here because we keep track of the
/// deposit charge separately from the storage charge.
pub fn charge_deposit(&mut self, deposit_account: DepositAccount<T>, amount: DepositOf<T>) {
pub fn charge_deposit(&mut self, contract: T::AccountId, amount: DepositOf<T>) {
self.total_deposit = self.total_deposit.saturating_add(&amount);
self.charges.push(Charge { deposit_account, amount, terminated: false });
self.charges.push(Charge { contract, amount, state: ContractState::Alive });
}
/// Charges from `origin` a storage deposit for contract instantiation.
@@ -427,7 +438,7 @@ where
contract_info: &mut ContractInfo<T>,
code_info: &CodeInfo<T>,
) -> Result<DepositOf<T>, DispatchError> {
debug_assert!(self.is_alive());
debug_assert!(matches!(self.contract_state(), ContractState::Alive));
let ed = Pallet::<T>::min_balance();
let deposit = contract_info.update_base_deposit(&code_info);
@@ -439,34 +450,32 @@ where
// We do not increase `own_contribution` because this will be charged later when the
// contract execution does conclude and hence would lead to a double charge.
self.total_deposit = deposit.clone();
self.total_deposit = Deposit::Charge(ed);
// Normally, deposit charges are deferred to be able to coalesce them with refunds.
// However, we need to charge immediately so that the account is created before
// charges possibly below the ed are collected and fail.
E::charge(
origin,
contract_info.deposit_account(),
&deposit.saturating_sub(&Deposit::Charge(ed)),
false,
)?;
System::<T>::inc_consumers(contract_info.deposit_account())?;
// We also need to make sure that the contract's account itself exists.
// We need to make sure that the contract's account exists.
T::Currency::transfer(origin, contract, ed, Preservation::Preserve)?;
// A consumer is added at account creation and removed it on termination, otherwise the
// runtime could remove the account. As long as a contract exists its account must exist.
// With the consumer, a correct runtime cannot remove the account.
System::<T>::inc_consumers(contract)?;
self.charge_deposit(contract.clone(), deposit.saturating_sub(&Deposit::Charge(ed)));
Ok(deposit)
}
/// Call to tell the meter that the currently executing contract was executed.
/// Call to tell the meter that the currently executing contract was terminated.
///
/// This will manipulate the meter so that all storage deposit accumulated in
/// `contract_info` will be refunded to the `origin` of the meter.
pub fn terminate(&mut self, info: &ContractInfo<T>) {
debug_assert!(self.is_alive());
self.own_contribution = Contribution::Terminated(Deposit::Refund(info.total_deposit()));
/// `contract_info` will be refunded to the `origin` of the meter. And the free
/// (`reducible_balance`) will be sent to the `beneficiary`.
pub fn terminate(&mut self, info: &ContractInfo<T>, beneficiary: T::AccountId) {
debug_assert!(matches!(self.contract_state(), ContractState::Alive));
self.own_contribution = Contribution::Terminated {
deposit: Deposit::Refund(info.total_deposit()),
beneficiary,
};
}
/// [`Self::charge`] does not enforce the storage limit since we want to do this check as late
@@ -485,7 +494,7 @@ where
let deposit = self.own_contribution.update_contract(info);
let total_deposit = self.total_deposit.saturating_add(&deposit);
// We don't want to override a `Terminated` with a `Checked`.
if self.is_alive() {
if matches!(self.contract_state(), ContractState::Alive) {
self.own_contribution = Contribution::Checked(deposit);
}
if let Deposit::Charge(amount) = total_deposit {
@@ -533,31 +542,77 @@ impl<T: Config> Ext<T> for ReservingExt {
fn charge(
origin: &T::AccountId,
deposit_account: &DepositAccount<T>,
contract: &T::AccountId,
amount: &DepositOf<T>,
terminated: bool,
state: &ContractState<T>,
) -> Result<(), DispatchError> {
match amount {
Deposit::Charge(amount) | Deposit::Refund(amount) if amount.is_zero() => return Ok(()),
Deposit::Charge(amount) => {
T::Currency::transfer(origin, deposit_account, *amount, Preservation::Preserve)?;
Ok(())
// This could fail if the `origin` does not have enough liquidity. Ideally, though,
// this should have been checked before with `check_limit`.
T::Currency::transfer_and_hold(
&HoldReason::StorageDepositReserve.into(),
origin,
contract,
*amount,
Precision::Exact,
Preservation::Preserve,
Fortitude::Polite,
)?;
Pallet::<T>::deposit_event(
vec![T::Hashing::hash_of(&origin), T::Hashing::hash_of(&contract)],
Event::StorageDepositTransferredAndHeld {
from: origin.clone(),
to: contract.clone(),
amount: *amount,
},
);
},
Deposit::Refund(amount) => {
if terminated {
System::<T>::dec_consumers(&deposit_account);
}
T::Currency::transfer(
deposit_account,
let transferred = T::Currency::transfer_on_hold(
&HoldReason::StorageDepositReserve.into(),
contract,
origin,
*amount,
// We can safely make it `Expendable` because our own consumer prevents a
// removal.
Preservation::Expendable,
Precision::BestEffort,
Restriction::Free,
Fortitude::Polite,
)?;
Ok(())
Pallet::<T>::deposit_event(
vec![T::Hashing::hash_of(&contract), T::Hashing::hash_of(&origin)],
Event::StorageDepositTransferredAndReleased {
from: contract.clone(),
to: origin.clone(),
amount: transferred,
},
);
if transferred < *amount {
// This should never happen, if it does it means that there is a bug in the
// runtime logic. In the rare case this happens we try to refund as much as we
// can, thus the `Precision::BestEffort`.
log::error!(
target: LOG_TARGET,
"Failed to repatriate full storage deposit {:?} from contract {:?} to origin {:?}. Transferred {:?}.",
amount, contract, origin, transferred,
);
}
},
}
if let ContractState::<T>::Terminated { beneficiary } = state {
System::<T>::dec_consumers(&contract);
// Whatever is left in the contract is sent to the termination beneficiary.
T::Currency::transfer(
&contract,
&beneficiary,
T::Currency::reducible_balance(&contract, Preservation::Expendable, Polite),
Preservation::Expendable,
)?;
}
Ok(())
}
}
@@ -593,9 +648,9 @@ mod tests {
#[derive(Debug, PartialEq, Eq, Clone)]
struct Charge {
origin: AccountIdOf<Test>,
contract: DepositAccount<Test>,
contract: AccountIdOf<Test>,
amount: DepositOf<Test>,
terminated: bool,
state: ContractState<Test>,
}
#[derive(Default, Debug, PartialEq, Eq, Clone)]
@@ -627,16 +682,16 @@ mod tests {
fn charge(
origin: &AccountIdOf<Test>,
contract: &DepositAccount<Test>,
contract: &AccountIdOf<Test>,
amount: &DepositOf<Test>,
terminated: bool,
state: &ContractState<Test>,
) -> Result<(), DispatchError> {
TestExtTestValue::mutate(|ext| {
ext.charges.push(Charge {
origin: origin.clone(),
contract: contract.clone(),
amount: amount.clone(),
terminated,
state: state.clone(),
})
});
Ok(())
@@ -664,7 +719,6 @@ mod tests {
fn new_info(info: StorageInfo) -> ContractInfo<Test> {
ContractInfo::<Test> {
trie_id: Default::default(),
deposit_account: DepositAccount([0u8; 32].into()),
code_hash: Default::default(),
storage_bytes: info.bytes,
storage_items: info.items,
@@ -700,7 +754,7 @@ mod tests {
// an empty charge does not create a `Charge` entry
let mut nested0 = meter.nested(BalanceOf::<Test>::zero());
nested0.charge(&Default::default());
meter.absorb(nested0, DepositAccount(BOB), None);
meter.absorb(nested0, &BOB, None);
assert_eq!(
TestExtTestValue::get(),
@@ -722,21 +776,21 @@ mod tests {
charges: vec![
Charge {
origin: ALICE,
contract: DepositAccount(CHARLIE),
contract: CHARLIE,
amount: Deposit::Refund(10),
terminated: false,
state: ContractState::Alive,
},
Charge {
origin: ALICE,
contract: DepositAccount(CHARLIE),
contract: CHARLIE,
amount: Deposit::Refund(20),
terminated: false,
state: ContractState::Alive,
},
Charge {
origin: ALICE,
contract: DepositAccount(BOB),
contract: BOB,
amount: Deposit::Charge(2),
terminated: false,
state: ContractState::Alive,
},
],
},
@@ -777,7 +831,7 @@ mod tests {
});
let mut nested1 = nested0.nested(BalanceOf::<Test>::zero());
nested1.charge(&Diff { items_removed: 5, ..Default::default() });
nested0.absorb(nested1, DepositAccount(CHARLIE), Some(&mut nested1_info));
nested0.absorb(nested1, &CHARLIE, Some(&mut nested1_info));
let mut nested2_info = new_info(StorageInfo {
bytes: 100,
@@ -787,10 +841,10 @@ mod tests {
});
let mut nested2 = nested0.nested(BalanceOf::<Test>::zero());
nested2.charge(&Diff { items_removed: 7, ..Default::default() });
nested0.absorb(nested2, DepositAccount(CHARLIE), Some(&mut nested2_info));
nested0.absorb(nested2, &CHARLIE, Some(&mut nested2_info));
nested0.enforce_limit(Some(&mut nested0_info)).unwrap();
meter.absorb(nested0, DepositAccount(BOB), Some(&mut nested0_info));
meter.absorb(nested0, &BOB, Some(&mut nested0_info));
assert_eq!(meter.try_into_deposit(&test_case.origin).unwrap(), test_case.deposit);
@@ -813,15 +867,15 @@ mod tests {
charges: vec![
Charge {
origin: ALICE,
contract: DepositAccount(CHARLIE),
contract: CHARLIE,
amount: Deposit::Refund(119),
terminated: true,
state: ContractState::Terminated { beneficiary: CHARLIE },
},
Charge {
origin: ALICE,
contract: DepositAccount(BOB),
contract: BOB,
amount: Deposit::Charge(12),
terminated: false,
state: ContractState::Alive,
},
],
},
@@ -857,11 +911,11 @@ mod tests {
let mut nested1 = nested0.nested(BalanceOf::<Test>::zero());
nested1.charge(&Diff { items_removed: 5, ..Default::default() });
nested1.charge(&Diff { bytes_added: 20, ..Default::default() });
nested1.terminate(&nested1_info);
nested1.terminate(&nested1_info, CHARLIE);
nested0.enforce_limit(Some(&mut nested1_info)).unwrap();
nested0.absorb(nested1, DepositAccount(CHARLIE), None);
nested0.absorb(nested1, &CHARLIE, None);
meter.absorb(nested0, DepositAccount(BOB), None);
meter.absorb(nested0, &BOB, None);
assert_eq!(meter.try_into_deposit(&test_case.origin).unwrap(), test_case.deposit);
assert_eq!(TestExtTestValue::get(), test_case.expected)
File diff suppressed because it is too large Load Diff
+1108 -1055
View File
File diff suppressed because it is too large Load Diff