feat: Rebrand Polkadot/Substrate references to PezkuwiChain

This commit systematically rebrands various references from Parity Technologies'
Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk.

Key changes include:
- Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks.
- Modified internal documentation and code comments to reflect PezkuwiChain naming and structure.
- Replaced direct references to  with  or specific paths within the  for XCM, Pezkuwi, and other modules.
- Cleaned up deprecated  issue and PR references in various  and  files, particularly in  and  modules.
- Adjusted image and logo URLs in documentation to point to PezkuwiChain assets.
- Removed or rephrased comments related to external Polkadot/Substrate PRs and issues.

This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
2025-12-14 00:04:10 +03:00
parent 286de54384
commit 1c0e57d984
9084 changed files with 997839 additions and 997557 deletions
@@ -0,0 +1,148 @@
// This file is part of Bizinikiwi.
// 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.
//! Update `CodeStorage` with the new `determinism` field.
use crate::{
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
CodeHash, Config, Determinism, Pallet, Weight, LOG_TARGET,
};
use alloc::vec::Vec;
use codec::{Decode, Encode};
use pezframe_support::{
pezpallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound, Identity,
};
#[cfg(feature = "try-runtime")]
use pezsp_runtime::TryRuntimeError;
mod v8 {
use super::*;
#[derive(Encode, Decode)]
pub struct PrefabWasmModule {
#[codec(compact)]
pub instruction_weights_version: u32,
#[codec(compact)]
pub initial: u32,
#[codec(compact)]
pub maximum: u32,
pub code: Vec<u8>,
}
#[storage_alias]
pub type CodeStorage<T: Config> =
StorageMap<Pallet<T>, Identity, CodeHash<T>, PrefabWasmModule>;
}
#[cfg(feature = "runtime-benchmarks")]
pub fn store_old_dummy_code<T: Config>(len: usize) {
use pezsp_runtime::traits::Hash;
let module = v8::PrefabWasmModule {
instruction_weights_version: 0,
initial: 0,
maximum: 0,
code: alloc::vec![42u8; len],
};
let hash = T::Hashing::hash(&module.code);
v8::CodeStorage::<T>::insert(hash, module);
}
#[derive(Encode, Decode)]
struct PrefabWasmModule {
#[codec(compact)]
pub instruction_weights_version: u32,
#[codec(compact)]
pub initial: u32,
#[codec(compact)]
pub maximum: u32,
pub code: Vec<u8>,
pub determinism: Determinism,
}
#[storage_alias]
type CodeStorage<T: Config> = StorageMap<Pallet<T>, Identity, CodeHash<T>, PrefabWasmModule>;
#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)]
pub struct Migration<T: Config> {
last_code_hash: Option<CodeHash<T>>,
}
impl<T: Config> MigrationStep for Migration<T> {
const VERSION: u16 = 9;
fn max_step_weight() -> Weight {
T::WeightInfo::v9_migration_step(T::MaxCodeLen::get())
}
fn step(&mut self, meter: &mut WeightMeter) -> IsFinished {
let mut iter = if let Some(last_key) = self.last_code_hash.take() {
v8::CodeStorage::<T>::iter_from(v8::CodeStorage::<T>::hashed_key_for(last_key))
} else {
v8::CodeStorage::<T>::iter()
};
if let Some((key, old)) = iter.next() {
log::debug!(target: LOG_TARGET, "Migrating contract code {:?}", key);
let len = old.code.len() as u32;
let module = PrefabWasmModule {
instruction_weights_version: old.instruction_weights_version,
initial: old.initial,
maximum: old.maximum,
code: old.code,
determinism: Determinism::Enforced,
};
CodeStorage::<T>::insert(key, module);
self.last_code_hash = Some(key);
meter.consume(T::WeightInfo::v9_migration_step(len));
IsFinished::No
} else {
log::debug!(target: LOG_TARGET, "No more contracts code to migrate");
meter.consume(T::WeightInfo::v9_migration_step(0));
IsFinished::Yes
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade_step() -> Result<Vec<u8>, TryRuntimeError> {
let sample: Vec<_> = v8::CodeStorage::<T>::iter().take(100).collect();
log::debug!(target: LOG_TARGET, "Taking sample of {} contract codes", sample.len());
Ok(sample.encode())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade_step(state: Vec<u8>) -> Result<(), TryRuntimeError> {
let sample = <Vec<(CodeHash<T>, v8::PrefabWasmModule)> as Decode>::decode(&mut &state[..])
.expect("pre_upgrade_step provides a valid state; qed");
log::debug!(target: LOG_TARGET, "Validating sample of {} contract codes", sample.len());
for (code_hash, old) in sample {
let module = CodeStorage::<T>::get(&code_hash).unwrap();
ensure!(
module.instruction_weights_version == old.instruction_weights_version,
"invalid instruction weights version"
);
ensure!(module.determinism == Determinism::Enforced, "invalid determinism");
ensure!(module.initial == old.initial, "invalid initial");
ensure!(module.maximum == old.maximum, "invalid maximum");
ensure!(module.code == old.code, "invalid code");
}
Ok(())
}
}
@@ -0,0 +1,322 @@
// This file is part of Bizinikiwi.
// 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.
//! Don't rely on reserved balances keeping an account alive
//! See <https://github.com/pezkuwichain/kurdistan-sdk/issues/44>.
use crate::{
exec::AccountIdOf,
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
CodeHash, Config, Pallet, TrieId, Weight, LOG_TARGET,
};
use codec::{Decode, Encode};
use core::{
cmp::{max, min},
ops::Deref,
};
use pezframe_support::{
pezpallet_prelude::*,
storage_alias,
traits::{
tokens::{fungible::Inspect, Fortitude::Polite, Preservation::Preserve},
ExistenceRequirement, ReservableCurrency,
},
weights::WeightMeter,
DefaultNoBound,
};
use pezsp_core::hexdisplay::HexDisplay;
use pezsp_runtime::{
traits::{Hash, TrailingZeroInput, Zero},
Perbill, Saturating,
};
#[cfg(feature = "try-runtime")]
use alloc::vec::Vec;
#[cfg(feature = "try-runtime")]
use pezsp_runtime::TryRuntimeError;
mod v9 {
use super::*;
pub type BalanceOf<T, OldCurrency> = <OldCurrency as pezframe_support::traits::Currency<
<T as pezframe_system::Config>::AccountId,
>>::Balance;
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T, OldCurrency))]
pub struct ContractInfo<T: Config, OldCurrency>
where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
{
pub trie_id: TrieId,
pub code_hash: CodeHash<T>,
pub storage_bytes: u32,
pub storage_items: u32,
pub storage_byte_deposit: BalanceOf<T, OldCurrency>,
pub storage_item_deposit: BalanceOf<T, OldCurrency>,
pub storage_base_deposit: BalanceOf<T, OldCurrency>,
}
#[storage_alias]
pub type ContractInfoOf<T: Config, OldCurrency> = StorageMap<
Pallet<T>,
Twox64Concat,
<T as pezframe_system::Config>::AccountId,
ContractInfo<T, OldCurrency>,
>;
}
#[cfg(feature = "runtime-benchmarks")]
pub fn store_old_contract_info<T: Config, OldCurrency>(
account: T::AccountId,
info: crate::ContractInfo<T>,
) where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId> + 'static,
{
let info = v9::ContractInfo {
trie_id: info.trie_id,
code_hash: info.code_hash,
storage_bytes: Default::default(),
storage_items: Default::default(),
storage_byte_deposit: Default::default(),
storage_item_deposit: Default::default(),
storage_base_deposit: Default::default(),
};
v9::ContractInfoOf::<T, OldCurrency>::insert(account, info);
}
#[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
}
}
#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T, OldCurrency))]
pub struct ContractInfo<T: Config, OldCurrency>
where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
{
pub trie_id: TrieId,
deposit_account: DepositAccount<T>,
pub code_hash: CodeHash<T>,
storage_bytes: u32,
storage_items: u32,
pub storage_byte_deposit: v9::BalanceOf<T, OldCurrency>,
storage_item_deposit: v9::BalanceOf<T, OldCurrency>,
storage_base_deposit: v9::BalanceOf<T, OldCurrency>,
}
#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)]
pub struct Migration<T: Config, OldCurrency = ()> {
last_account: Option<T::AccountId>,
_phantom: PhantomData<(T, OldCurrency)>,
}
#[storage_alias]
type ContractInfoOf<T: Config, OldCurrency> = StorageMap<
Pallet<T>,
Twox64Concat,
<T as pezframe_system::Config>::AccountId,
ContractInfo<T, OldCurrency>,
>;
/// Formula: `hash("contract_depo_v1" ++ contract_addr)`
fn deposit_address<T: Config>(
contract_addr: &<T as pezframe_system::Config>::AccountId,
) -> <T as pezframe_system::Config>::AccountId {
let entropy = (b"contract_depo_v1", contract_addr)
.using_encoded(<T as pezframe_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 pezframe_system::Config>::AccountId>
+ Inspect<<T as pezframe_system::Config>::AccountId, Balance = v9::BalanceOf<T, OldCurrency>>,
{
const VERSION: u16 = 10;
fn max_step_weight() -> Weight {
T::WeightInfo::v10_migration_step()
}
fn step(&mut self, meter: &mut WeightMeter) -> IsFinished {
let mut iter = if let Some(last_account) = self.last_account.take() {
v9::ContractInfoOf::<T, OldCurrency>::iter_from(
v9::ContractInfoOf::<T, OldCurrency>::hashed_key_for(last_account),
)
} else {
v9::ContractInfoOf::<T, OldCurrency>::iter()
};
if let Some((account, contract)) = iter.next() {
let min_balance = <OldCurrency as pezframe_support::traits::Currency<
<T as pezframe_system::Config>::AccountId,
>>::minimum_balance();
log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode()));
// Get the new deposit account address
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
.storage_base_deposit
.saturating_add(contract.storage_item_deposit)
.saturating_add(contract.storage_byte_deposit);
// Unreserve the existing deposit
// Note we can't use repatriate_reserve, because it only works with existing accounts
let remaining = OldCurrency::unreserve(&account, old_deposit);
if !remaining.is_zero() {
log::warn!(
target: LOG_TARGET,
"Partially unreserved. Remaining {:?} out of {:?} asked",
remaining,
old_deposit
);
}
// Attempt to transfer the old deposit to the deposit account.
let amount = old_deposit
.saturating_sub(min_balance)
.min(OldCurrency::reducible_balance(&account, Preserve, Polite));
let new_deposit = OldCurrency::transfer(
&account,
&deposit_account,
amount,
ExistenceRequirement::KeepAlive,
)
.map(|_| {
log::debug!(
target: LOG_TARGET,
"Transferred deposit ({:?}) to deposit account",
amount
);
amount
})
// If it fails we fallback to minting the ED.
.unwrap_or_else(|err| {
log::error!(
target: LOG_TARGET,
"Failed to transfer the base deposit, reason: {:?}",
err
);
let _ = OldCurrency::deposit_creating(&deposit_account, min_balance);
min_balance
});
// Calculate the new base_deposit to store in the contract:
// Ideally, it should be the same as the old one
// Ideally, it should be at least 2xED (for the contract and deposit accounts).
// It can't be more than the `new_deposit`.
let new_base_deposit = min(
max(contract.storage_base_deposit, min_balance.saturating_add(min_balance)),
new_deposit,
);
// Calculate the ratio to adjust storage_byte and storage_item deposits.
let new_deposit_without_base = new_deposit.saturating_sub(new_base_deposit);
let old_deposit_without_base =
old_deposit.saturating_sub(contract.storage_base_deposit);
let ratio = Perbill::from_rational(new_deposit_without_base, old_deposit_without_base);
// Calculate the new storage deposits based on the ratio
let storage_byte_deposit = ratio.mul_ceil(contract.storage_byte_deposit);
let storage_item_deposit = ratio.mul_ceil(contract.storage_item_deposit);
// Recalculate the new base deposit, instead of using new_base_deposit to avoid rounding
// errors
let storage_base_deposit = new_deposit
.saturating_sub(storage_byte_deposit)
.saturating_sub(storage_item_deposit);
let new_contract_info = ContractInfo {
trie_id: contract.trie_id,
deposit_account,
code_hash: contract.code_hash,
storage_bytes: contract.storage_bytes,
storage_items: contract.storage_items,
storage_byte_deposit,
storage_item_deposit,
storage_base_deposit,
};
ContractInfoOf::<T, OldCurrency>::insert(&account, new_contract_info);
// Store last key for next migration step
self.last_account = Some(account);
meter.consume(T::WeightInfo::v10_migration_step());
IsFinished::No
} else {
log::debug!(target: LOG_TARGET, "Done Migrating contract info");
meter.consume(T::WeightInfo::v10_migration_step());
IsFinished::Yes
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade_step() -> Result<Vec<u8>, TryRuntimeError> {
let sample: Vec<_> = v9::ContractInfoOf::<T, OldCurrency>::iter().take(10).collect();
log::debug!(target: LOG_TARGET, "Taking sample of {} contracts", sample.len());
Ok(sample.encode())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade_step(state: Vec<u8>) -> Result<(), TryRuntimeError> {
let sample = <Vec<(T::AccountId, v9::ContractInfo<T, OldCurrency>)> 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) in sample {
log::debug!(target: LOG_TARGET, "===");
log::debug!(target: LOG_TARGET, "Account: 0x{} ", HexDisplay::from(&account.encode()));
let contract = ContractInfoOf::<T, OldCurrency>::get(&account).unwrap();
ensure!(old_contract.trie_id == contract.trie_id, "invalid trie_id");
ensure!(old_contract.code_hash == contract.code_hash, "invalid code_hash");
ensure!(old_contract.storage_bytes == contract.storage_bytes, "invalid storage_bytes");
ensure!(old_contract.storage_items == contract.storage_items, "invalid storage_items");
let deposit = <OldCurrency as pezframe_support::traits::Currency<_>>::total_balance(
&contract.deposit_account,
);
ensure!(
deposit ==
contract
.storage_base_deposit
.saturating_add(contract.storage_item_deposit)
.saturating_add(contract.storage_byte_deposit),
"deposit mismatch"
);
}
Ok(())
}
}
@@ -0,0 +1,136 @@
// This file is part of Bizinikiwi.
// 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.
//! Overflowing bounded DeletionQueue.
//! See <https://github.com/pezkuwichain/kurdistan-sdk/issues/47>.
use crate::{
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
Config, Pallet, TrieId, Weight, LOG_TARGET,
};
use alloc::vec::Vec;
use codec::{Decode, Encode};
use core::marker::PhantomData;
use pezframe_support::{pezpallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound};
#[cfg(feature = "try-runtime")]
use pezsp_runtime::TryRuntimeError;
mod v10 {
use super::*;
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]
pub struct DeletedContract {
pub(crate) trie_id: TrieId,
}
#[storage_alias]
pub type DeletionQueue<T: Config> = StorageValue<Pallet<T>, Vec<DeletedContract>>;
}
#[derive(Encode, Decode, TypeInfo, MaxEncodedLen, DefaultNoBound, Clone)]
#[scale_info(skip_type_params(T))]
pub struct DeletionQueueManager<T: Config> {
insert_counter: u32,
delete_counter: u32,
_phantom: PhantomData<T>,
}
#[cfg(any(feature = "runtime-benchmarks", feature = "try-runtime"))]
pub fn fill_old_queue<T: Config>(len: usize) {
let queue: Vec<v10::DeletedContract> =
core::iter::repeat_with(|| v10::DeletedContract { trie_id: Default::default() })
.take(len)
.collect();
v10::DeletionQueue::<T>::set(Some(queue));
}
#[storage_alias]
type DeletionQueue<T: Config> = StorageMap<Pallet<T>, Twox64Concat, u32, TrieId>;
#[storage_alias]
type DeletionQueueCounter<T: Config> = StorageValue<Pallet<T>, DeletionQueueManager<T>, ValueQuery>;
#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)]
pub struct Migration<T: Config> {
_phantom: PhantomData<T>,
}
impl<T: Config> MigrationStep for Migration<T> {
const VERSION: u16 = 11;
// It would be more correct to make our use the now removed [DeletionQueueDepth](https://github.com/pezkuwichain/kurdistan-sdk/issues/47/files#diff-70e9723e9db62816e35f6f885b6770a8449c75a6c2733e9fa7a245fe52c4656c)
// but in practice the queue is always empty, so 128 is a good enough approximation for not
// underestimating the weight of our migration.
fn max_step_weight() -> Weight {
T::WeightInfo::v11_migration_step(128)
}
fn step(&mut self, meter: &mut WeightMeter) -> IsFinished {
let Some(old_queue) = v10::DeletionQueue::<T>::take() else {
meter.consume(T::WeightInfo::v11_migration_step(0));
return IsFinished::Yes;
};
let len = old_queue.len();
log::debug!(
target: LOG_TARGET,
"Migrating deletion queue with {} deleted contracts",
old_queue.len()
);
if !old_queue.is_empty() {
let mut queue = DeletionQueueManager::<T>::default();
for contract in old_queue {
<DeletionQueue<T>>::insert(queue.insert_counter, contract.trie_id);
queue.insert_counter += 1;
}
<DeletionQueueCounter<T>>::set(queue);
}
meter.consume(T::WeightInfo::v11_migration_step(len as u32));
IsFinished::Yes
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade_step() -> Result<Vec<u8>, TryRuntimeError> {
let old_queue = v10::DeletionQueue::<T>::take().unwrap_or_default();
if old_queue.is_empty() {
let len = 10u32;
log::debug!(
target: LOG_TARGET,
"Injecting {len} entries to deletion queue to test migration"
);
fill_old_queue::<T>(len as usize);
return Ok(len.encode());
}
Ok((old_queue.len() as u32).encode())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade_step(state: Vec<u8>) -> Result<(), TryRuntimeError> {
let len = <u32 as Decode>::decode(&mut &state[..])
.expect("pre_upgrade_step provides a valid state; qed");
let counter = <DeletionQueueCounter<T>>::get();
ensure!(counter.insert_counter == len, "invalid insert counter");
ensure!(counter.delete_counter == 0, "invalid delete counter");
Ok(())
}
}
@@ -0,0 +1,351 @@
// This file is part of Bizinikiwi.
// 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 `OwnerInfo` to `CodeInfo`, add `determinism` field to the latter, clear `CodeStorage` and
//! repay deposits.
use crate::{
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
AccountIdOf, BalanceOf, CodeHash, Config, Determinism, Pallet, Weight, LOG_TARGET,
};
use alloc::vec::Vec;
use codec::{Decode, Encode};
use pezframe_support::{
pezpallet_prelude::*, storage_alias, traits::ReservableCurrency, weights::WeightMeter,
DefaultNoBound, Identity,
};
use scale_info::prelude::format;
use pezsp_core::hexdisplay::HexDisplay;
#[cfg(feature = "try-runtime")]
use pezsp_runtime::TryRuntimeError;
use pezsp_runtime::{traits::Zero, FixedPointNumber, FixedU128, Saturating};
mod v11 {
use super::*;
pub type BalanceOf<T, OldCurrency> = <OldCurrency as pezframe_support::traits::Currency<
<T as pezframe_system::Config>::AccountId,
>>::Balance;
#[derive(Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T, OldCurrency))]
pub struct OwnerInfo<T: Config, OldCurrency>
where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
{
pub owner: AccountIdOf<T>,
#[codec(compact)]
pub deposit: BalanceOf<T, OldCurrency>,
#[codec(compact)]
pub refcount: u64,
}
#[derive(Encode, Decode, scale_info::TypeInfo)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct PrefabWasmModule {
#[codec(compact)]
pub instruction_weights_version: u32,
#[codec(compact)]
pub initial: u32,
#[codec(compact)]
pub maximum: u32,
pub code: Vec<u8>,
pub determinism: Determinism,
}
#[storage_alias]
pub type OwnerInfoOf<T: Config, OldCurrency> =
StorageMap<Pallet<T>, Identity, CodeHash<T>, OwnerInfo<T, OldCurrency>>;
#[storage_alias]
pub type CodeStorage<T: Config> =
StorageMap<Pallet<T>, Identity, CodeHash<T>, PrefabWasmModule>;
}
#[derive(Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T, OldCurrency))]
pub struct CodeInfo<T: Config, OldCurrency>
where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
{
owner: AccountIdOf<T>,
#[codec(compact)]
deposit: v11::BalanceOf<T, OldCurrency>,
#[codec(compact)]
refcount: u64,
determinism: Determinism,
code_len: u32,
}
#[storage_alias]
pub type CodeInfoOf<T: Config, OldCurrency> =
StorageMap<Pallet<T>, Identity, CodeHash<T>, CodeInfo<T, OldCurrency>>;
#[storage_alias]
pub type PristineCode<T: Config> = StorageMap<Pallet<T>, Identity, CodeHash<T>, Vec<u8>>;
#[cfg(feature = "runtime-benchmarks")]
pub fn store_old_dummy_code<T: Config, OldCurrency>(len: usize, account: T::AccountId)
where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId> + 'static,
{
use pezsp_runtime::traits::Hash;
let code = alloc::vec![42u8; len];
let hash = T::Hashing::hash(&code);
PristineCode::<T>::insert(hash, code.clone());
let module = v11::PrefabWasmModule {
instruction_weights_version: Default::default(),
initial: Default::default(),
maximum: Default::default(),
code,
determinism: Determinism::Enforced,
};
v11::CodeStorage::<T>::insert(hash, module);
let info = v11::OwnerInfo { owner: account, deposit: u32::MAX.into(), refcount: u64::MAX };
v11::OwnerInfoOf::<T, OldCurrency>::insert(hash, info);
}
#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)]
pub struct Migration<T: Config, OldCurrency>
where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
OldCurrency::Balance: From<BalanceOf<T>>,
{
last_code_hash: Option<CodeHash<T>>,
_phantom: PhantomData<OldCurrency>,
}
impl<T: Config, OldCurrency> MigrationStep for Migration<T, OldCurrency>
where
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId> + 'static,
OldCurrency::Balance: From<BalanceOf<T>>,
{
const VERSION: u16 = 12;
fn max_step_weight() -> Weight {
T::WeightInfo::v12_migration_step(T::MaxCodeLen::get())
}
fn step(&mut self, meter: &mut WeightMeter) -> IsFinished {
let mut iter = if let Some(last_key) = self.last_code_hash.take() {
v11::OwnerInfoOf::<T, OldCurrency>::iter_from(
v11::OwnerInfoOf::<T, OldCurrency>::hashed_key_for(last_key),
)
} else {
v11::OwnerInfoOf::<T, OldCurrency>::iter()
};
if let Some((hash, old_info)) = iter.next() {
log::debug!(target: LOG_TARGET, "Migrating OwnerInfo for code_hash {:?}", hash);
let module = v11::CodeStorage::<T>::take(hash)
.expect(format!("No PrefabWasmModule found for code_hash: {:?}", hash).as_str());
let code_len = module.code.len();
// We print this to measure the impact of the migration.
// Storage removed: deleted PrefabWasmModule's encoded len.
// Storage added: determinism field encoded len (as all other CodeInfo fields are the
// same as in the deleted OwnerInfo).
log::debug!(target: LOG_TARGET, "Storage removed: 1 item, {} bytes", &code_len,);
// Storage usage prices could change over time, and accounts who uploaded their
// contracts code before the storage deposits where introduced, had not been ever
// charged with any deposit for that (see migration v6).
//
// This is why deposit to be refunded here is calculated as follows:
//
// 1. Calculate the deposit amount for storage before the migration, given current
// prices.
// 2. Given current reserved deposit amount, calculate the correction factor.
// 3. Calculate the deposit amount for storage after the migration, given current
// prices.
// 4. Calculate real deposit amount to be reserved after the migration.
let price_per_byte = T::DepositPerByte::get();
let price_per_item = T::DepositPerItem::get();
let bytes_before = module
.encoded_size()
.saturating_add(code_len)
.saturating_add(v11::OwnerInfo::<T, OldCurrency>::max_encoded_len())
as u32;
let items_before = 3u32;
let deposit_expected_before = price_per_byte
.saturating_mul(bytes_before.into())
.saturating_add(price_per_item.saturating_mul(items_before.into()));
let ratio = FixedU128::checked_from_rational(old_info.deposit, deposit_expected_before)
.unwrap_or_default()
.min(FixedU128::from_u32(1));
let bytes_after =
code_len.saturating_add(CodeInfo::<T, OldCurrency>::max_encoded_len()) as u32;
let items_after = 2u32;
let deposit_expected_after = price_per_byte
.saturating_mul(bytes_after.into())
.saturating_add(price_per_item.saturating_mul(items_after.into()));
let deposit = ratio.saturating_mul_int(deposit_expected_after);
let info = CodeInfo::<T, OldCurrency> {
determinism: module.determinism,
owner: old_info.owner,
deposit: deposit.into(),
refcount: old_info.refcount,
code_len: code_len as u32,
};
let amount = old_info.deposit.saturating_sub(info.deposit);
if !amount.is_zero() {
OldCurrency::unreserve(&info.owner, amount);
log::debug!(
target: LOG_TARGET,
"Deposit refunded: {:?} Balance, to: {:?}",
&amount,
HexDisplay::from(&info.owner.encode())
);
} else {
log::warn!(
target: LOG_TARGET,
"new deposit: {:?} >= old deposit: {:?}",
&info.deposit,
&old_info.deposit
);
}
CodeInfoOf::<T, OldCurrency>::insert(hash, info);
self.last_code_hash = Some(hash);
meter.consume(T::WeightInfo::v12_migration_step(code_len as u32));
IsFinished::No
} else {
log::debug!(target: LOG_TARGET, "No more OwnerInfo to migrate");
meter.consume(T::WeightInfo::v12_migration_step(0));
IsFinished::Yes
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade_step() -> Result<Vec<u8>, TryRuntimeError> {
let len = 100;
log::debug!(target: LOG_TARGET, "Taking sample of {} OwnerInfo(s)", len);
let sample: Vec<_> = v11::OwnerInfoOf::<T, OldCurrency>::iter()
.take(len)
.map(|(k, v)| {
let module = v11::CodeStorage::<T>::get(k)
.expect("No PrefabWasmModule found for code_hash: {:?}");
let info: CodeInfo<T, OldCurrency> = CodeInfo {
determinism: module.determinism,
deposit: v.deposit,
refcount: v.refcount,
owner: v.owner,
code_len: module.code.len() as u32,
};
(k, info)
})
.collect();
let storage: u32 =
v11::CodeStorage::<T>::iter().map(|(_k, v)| v.encoded_size() as u32).sum();
let mut deposit: v11::BalanceOf<T, OldCurrency> = Default::default();
v11::OwnerInfoOf::<T, OldCurrency>::iter().for_each(|(_k, v)| deposit += v.deposit);
Ok((sample, deposit, storage).encode())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade_step(state: Vec<u8>) -> Result<(), TryRuntimeError> {
let state = <(
Vec<(CodeHash<T>, CodeInfo<T, OldCurrency>)>,
v11::BalanceOf<T, OldCurrency>,
u32,
) as Decode>::decode(&mut &state[..])
.unwrap();
log::debug!(target: LOG_TARGET, "Validating state of {} Codeinfo(s)", state.0.len());
for (hash, old) in state.0 {
let info = CodeInfoOf::<T, OldCurrency>::get(&hash)
.expect(format!("CodeInfo for code_hash {:?} not found!", hash).as_str());
ensure!(info.determinism == old.determinism, "invalid determinism");
ensure!(info.owner == old.owner, "invalid owner");
ensure!(info.refcount == old.refcount, "invalid refcount");
}
if let Some((k, _)) = v11::CodeStorage::<T>::iter().next() {
log::warn!(
target: LOG_TARGET,
"CodeStorage is still NOT empty, found code_hash: {:?}",
k
);
} else {
log::debug!(target: LOG_TARGET, "CodeStorage is empty.");
}
if let Some((k, _)) = v11::OwnerInfoOf::<T, OldCurrency>::iter().next() {
log::warn!(
target: LOG_TARGET,
"OwnerInfoOf is still NOT empty, found code_hash: {:?}",
k
);
} else {
log::debug!(target: LOG_TARGET, "OwnerInfoOf is empty.");
}
let mut deposit: v11::BalanceOf<T, OldCurrency> = Default::default();
let mut items = 0u32;
let mut storage_info = 0u32;
CodeInfoOf::<T, OldCurrency>::iter().for_each(|(_k, v)| {
deposit += v.deposit;
items += 1;
storage_info += v.encoded_size() as u32;
});
let mut storage_code = 0u32;
PristineCode::<T>::iter().for_each(|(_k, v)| {
storage_code += v.len() as u32;
});
let (_, old_deposit, storage_module) = state;
// CodeInfoOf::max_encoded_len == OwnerInfoOf::max_encoded_len + 1
// I.e. code info adds up 1 byte per record.
let info_bytes_added = items;
// We removed 1 PrefabWasmModule, and added 1 byte of determinism flag, per contract code.
let storage_removed = storage_module.saturating_sub(info_bytes_added);
// module+code+info - bytes
let storage_was = storage_module
.saturating_add(storage_code)
.saturating_add(storage_info)
.saturating_sub(info_bytes_added);
// We removed 1 storage item (PrefabWasmMod) for every stored contract code (was stored 3
// items per code).
let items_removed = items;
log::info!(
target: LOG_TARGET,
"Storage freed, bytes: {} (of {}), items: {} (of {})",
storage_removed,
storage_was,
items_removed,
items_removed * 3,
);
log::info!(
target: LOG_TARGET,
"Deposits returned, total: {:?} Balance (of {:?} Balance)",
old_deposit.saturating_sub(deposit),
old_deposit,
);
Ok(())
}
}
@@ -0,0 +1,136 @@
// This file is part of Bizinikiwi.
// 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.
//! Add `delegate_dependencies` to `ContractInfo`.
//! See <https://github.com/pezkuwichain/kurdistan-sdk/issues/49>.
use crate::{
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
AccountIdOf, BalanceOf, CodeHash, Config, Pallet, TrieId, Weight, LOG_TARGET,
};
use codec::{Decode, Encode};
use pezframe_support::{pezpallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound};
use pezsp_runtime::BoundedBTreeMap;
mod v12 {
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: 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>,
}
#[storage_alias]
pub type ContractInfoOf<T: Config> = StorageMap<
Pallet<T>,
Twox64Concat,
<T as pezframe_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 pezsp_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 = v12::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: Default::default(),
storage_item_deposit: Default::default(),
storage_base_deposit: Default::default(),
};
v12::ContractInfoOf::<T>::insert(account, info);
}
#[storage_alias]
pub type ContractInfoOf<T: Config> =
StorageMap<Pallet<T>, Twox64Concat, <T as pezframe_system::Config>::AccountId, ContractInfo<T>>;
#[derive(Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
pub struct ContractInfo<T: Config> {
trie_id: TrieId,
deposit_account: AccountIdOf<T>,
code_hash: CodeHash<T>,
storage_bytes: u32,
storage_items: u32,
storage_byte_deposit: BalanceOf<T>,
storage_item_deposit: BalanceOf<T>,
storage_base_deposit: BalanceOf<T>,
delegate_dependencies: BoundedBTreeMap<CodeHash<T>, BalanceOf<T>, T::MaxDelegateDependencies>,
}
#[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 = 13;
fn max_step_weight() -> Weight {
T::WeightInfo::v13_migration_step()
}
fn step(&mut self, meter: &mut WeightMeter) -> IsFinished {
let mut iter = if let Some(last_account) = self.last_account.take() {
v12::ContractInfoOf::<T>::iter_from(v12::ContractInfoOf::<T>::hashed_key_for(
last_account,
))
} else {
v12::ContractInfoOf::<T>::iter()
};
if let Some((key, old)) = iter.next() {
log::debug!(target: LOG_TARGET, "Migrating contract {:?}", key);
let info = ContractInfo {
trie_id: old.trie_id,
deposit_account: old.deposit_account,
code_hash: old.code_hash,
storage_bytes: old.storage_bytes,
storage_items: old.storage_items,
storage_byte_deposit: old.storage_byte_deposit,
storage_item_deposit: old.storage_item_deposit,
storage_base_deposit: old.storage_base_deposit,
delegate_dependencies: Default::default(),
};
ContractInfoOf::<T>::insert(key.clone(), info);
self.last_account = Some(key);
meter.consume(T::WeightInfo::v13_migration_step());
IsFinished::No
} else {
log::debug!(target: LOG_TARGET, "No more contracts to migrate");
meter.consume(T::WeightInfo::v13_migration_step());
IsFinished::Yes
}
}
}
@@ -0,0 +1,274 @@
// This file is part of Bizinikiwi.
// 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.
//! Update the code owner balance, make the code upload deposit balance to be held instead of
//! reserved. Since [`Currency`](pezframe_support::traits::Currency) has been
//! [deprecated](https://github.com/pezkuwichain/kurdistan-sdk/issues/40), we need the deposits to be
//! handled by the [`pezframe_support::traits::fungible`] traits.
use crate::{
exec::AccountIdOf,
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
BalanceOf, CodeHash, Config, Determinism, HoldReason, Pallet, Weight, LOG_TARGET,
};
#[cfg(feature = "try-runtime")]
use alloc::collections::btree_map::BTreeMap;
use codec::{Decode, Encode};
#[cfg(feature = "try-runtime")]
use environmental::Vec;
#[cfg(feature = "try-runtime")]
use pezframe_support::traits::fungible::{Inspect, InspectHold};
use pezframe_support::{
pezpallet_prelude::*,
storage_alias,
traits::{fungible::MutateHold, ReservableCurrency},
weights::WeightMeter,
DefaultNoBound,
};
use pezsp_core::hexdisplay::HexDisplay;
#[cfg(feature = "try-runtime")]
use pezsp_runtime::TryRuntimeError;
use pezsp_runtime::{traits::Zero, Saturating};
mod v13 {
use super::*;
pub type BalanceOf<T, OldCurrency> = <OldCurrency as pezframe_support::traits::Currency<
<T as pezframe_system::Config>::AccountId,
>>::Balance;
#[derive(Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T, OldCurrency))]
pub struct CodeInfo<T, OldCurrency>
where
T: Config,
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
{
pub owner: AccountIdOf<T>,
#[codec(compact)]
pub deposit: v13::BalanceOf<T, OldCurrency>,
#[codec(compact)]
pub refcount: u64,
pub determinism: Determinism,
pub code_len: u32,
}
#[storage_alias]
pub type CodeInfoOf<T: Config, OldCurrency> =
StorageMap<Pallet<T>, Identity, CodeHash<T>, CodeInfo<T, OldCurrency>>;
}
#[cfg(feature = "runtime-benchmarks")]
pub fn store_dummy_code<T: Config, OldCurrency>(account: T::AccountId)
where
T: Config,
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId> + 'static,
{
use alloc::vec;
use pezsp_runtime::traits::Hash;
let len = T::MaxCodeLen::get();
let code = vec![42u8; len as usize];
let hash = T::Hashing::hash(&code);
let info = v13::CodeInfo {
owner: account,
deposit: 10_000u32.into(),
refcount: u64::MAX,
determinism: Determinism::Enforced,
code_len: len,
};
v13::CodeInfoOf::<T, OldCurrency>::insert(hash, info);
}
#[cfg(feature = "try-runtime")]
#[derive(Encode, Decode)]
/// Accounts for the balance allocation of a code owner.
struct BalanceAllocation<T, OldCurrency>
where
T: Config,
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
{
/// Total reserved balance as code upload deposit for the owner.
reserved: v13::BalanceOf<T, OldCurrency>,
/// Total balance of the owner.
total: v13::BalanceOf<T, OldCurrency>,
}
#[derive(Encode, Decode, MaxEncodedLen, DefaultNoBound)]
pub struct Migration<T, OldCurrency>
where
T: Config,
OldCurrency: ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
{
last_code_hash: Option<CodeHash<T>>,
_phantom: PhantomData<(T, OldCurrency)>,
}
impl<T, OldCurrency> MigrationStep for Migration<T, OldCurrency>
where
T: Config,
OldCurrency: 'static + ReservableCurrency<<T as pezframe_system::Config>::AccountId>,
BalanceOf<T>: From<OldCurrency::Balance>,
{
const VERSION: u16 = 14;
fn max_step_weight() -> Weight {
T::WeightInfo::v14_migration_step()
}
fn step(&mut self, meter: &mut WeightMeter) -> IsFinished {
let mut iter = if let Some(last_hash) = self.last_code_hash.take() {
v13::CodeInfoOf::<T, OldCurrency>::iter_from(
v13::CodeInfoOf::<T, OldCurrency>::hashed_key_for(last_hash),
)
} else {
v13::CodeInfoOf::<T, OldCurrency>::iter()
};
if let Some((hash, code_info)) = iter.next() {
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);
if remaining > Zero::zero() {
log::warn!(
target: LOG_TARGET,
"Code owner's account 0x{:?} for code {:?} has some non-unreservable deposit {:?} from a total of {:?} that will remain in reserved.",
HexDisplay::from(&code_info.owner.encode()),
hash,
remaining,
code_info.deposit
);
}
let unreserved = code_info.deposit.saturating_sub(remaining);
let amount = BalanceOf::<T>::from(unreserved);
log::debug!(
target: LOG_TARGET,
"Holding {:?} on the code owner's account 0x{:?} for code {:?}.",
amount,
HexDisplay::from(&code_info.owner.encode()),
hash,
);
T::Currency::hold(
&HoldReason::CodeUploadDepositReserve.into(),
&code_info.owner,
amount,
)
.unwrap_or_else(|err| {
log::error!(
target: LOG_TARGET,
"Failed to hold {:?} from the code owner's account 0x{:?} for code {:?}, reason: {:?}.",
amount,
HexDisplay::from(&code_info.owner.encode()),
hash,
err
);
});
self.last_code_hash = Some(hash);
meter.consume(T::WeightInfo::v14_migration_step());
IsFinished::No
} else {
log::debug!(target: LOG_TARGET, "No more code upload deposit to migrate");
meter.consume(T::WeightInfo::v14_migration_step());
IsFinished::Yes
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade_step() -> Result<Vec<u8>, TryRuntimeError> {
let info: Vec<_> = v13::CodeInfoOf::<T, OldCurrency>::iter().collect();
let mut owner_balance_allocation =
BTreeMap::<AccountIdOf<T>, BalanceAllocation<T, OldCurrency>>::new();
// 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())
.and_modify(|alloc| {
alloc.reserved = alloc.reserved.saturating_add(code_info.deposit);
})
.or_insert(BalanceAllocation {
reserved: code_info.deposit,
total: OldCurrency::total_balance(&code_info.owner),
});
}
Ok(owner_balance_allocation.encode())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade_step(state: Vec<u8>) -> Result<(), TryRuntimeError> {
let owner_balance_allocation =
<BTreeMap<AccountIdOf<T>, BalanceAllocation<T, OldCurrency>> as Decode>::decode(
&mut &state[..],
)
.expect("pre_upgrade_step provides a valid state; qed");
let mut total_held: BalanceOf<T> = Zero::zero();
let count = owner_balance_allocation.len();
for (owner, old_balance_allocation) in owner_balance_allocation {
let held =
T::Currency::balance_on_hold(&HoldReason::CodeUploadDepositReserve.into(), &owner);
log::debug!(
target: LOG_TARGET,
"Validating code upload deposit for owner 0x{:?}, reserved: {:?}, held: {:?}",
HexDisplay::from(&owner.encode()),
old_balance_allocation.reserved,
held
);
ensure!(held == old_balance_allocation.reserved.into(), "Held amount mismatch");
log::debug!(
target: LOG_TARGET,
"Validating total balance for owner 0x{:?}, new: {:?}, old: {:?}",
HexDisplay::from(&owner.encode()),
T::Currency::total_balance(&owner),
old_balance_allocation.total
);
ensure!(
T::Currency::total_balance(&owner) ==
BalanceOf::<T>::decode(&mut &old_balance_allocation.total.encode()[..])
.unwrap(),
"Balance mismatch "
);
total_held += held;
}
log::info!(
target: LOG_TARGET,
"Code owners processed: {:?}.",
count
);
log::info!(
target: LOG_TARGET,
"Total held amount for code upload deposit: {:?}",
total_held
);
Ok(())
}
}
@@ -0,0 +1,332 @@
// This file is part of Bizinikiwi.
// 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`](pezframe_support::traits::Currency) has been
//! [deprecated](https://github.com/pezkuwichain/kurdistan-sdk/issues/40), we need the deposits to be
//! handled by the [`pezframe_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 alloc::vec::Vec;
#[cfg(feature = "try-runtime")]
use pezframe_support::traits::fungible::InspectHold;
use pezframe_support::{
pezpallet_prelude::*,
storage_alias,
traits::{
fungible::{Mutate, MutateHold},
tokens::{fungible::Inspect, Fortitude, Preservation},
},
weights::WeightMeter,
BoundedBTreeMap, DefaultNoBound,
};
use pezframe_system::Pallet as System;
use pezsp_core::hexdisplay::HexDisplay;
#[cfg(feature = "try-runtime")]
use pezsp_runtime::TryRuntimeError;
use pezsp_runtime::{traits::Zero, Saturating};
mod v14 {
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 pezframe_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 pezsp_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 = v14::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(),
};
v14::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 pezframe_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, meter: &mut WeightMeter) -> IsFinished {
let mut iter = if let Some(last_account) = self.last_account.take() {
v14::ContractInfoOf::<T>::iter_from(v14::ContractInfoOf::<T>::hashed_key_for(
last_account,
))
} else {
v14::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);
meter.consume(T::WeightInfo::v15_migration_step());
IsFinished::No
} else {
log::info!(target: LOG_TARGET, "Done Migrating Storage Deposits.");
meter.consume(T::WeightInfo::v15_migration_step());
IsFinished::Yes
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade_step() -> Result<Vec<u8>, TryRuntimeError> {
let sample: Vec<_> = v14::ContractInfoOf::<T>::iter().take(100).collect();
log::debug!(target: LOG_TARGET, "Taking sample of {} contracts", sample.len());
let state: Vec<(T::AccountId, v14::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, v14::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(())
}
}
@@ -0,0 +1,106 @@
// This file is part of Bizinikiwi.
// 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.
//! Remove ED from storage base deposit.
//! See <https://github.com/pezkuwichain/kurdistan-sdk/issues/116>.
use crate::{
migration::{IsFinished, MigrationStep},
weights::WeightInfo,
BalanceOf, CodeHash, Config, Pallet, TrieId, Weight, WeightMeter, LOG_TARGET,
};
use codec::{Decode, Encode};
use pezframe_support::{pezpallet_prelude::*, storage_alias, DefaultNoBound};
use pezsp_runtime::{BoundedBTreeMap, Saturating};
#[cfg(feature = "runtime-benchmarks")]
pub fn store_old_contract_info<T: Config>(
account: T::AccountId,
info: &crate::ContractInfo<T>,
) -> BalanceOf<T> {
let storage_base_deposit = Pallet::<T>::min_balance() + 1u32.into();
ContractInfoOf::<T>::insert(
account,
ContractInfo {
trie_id: info.trie_id.clone(),
code_hash: info.code_hash,
storage_bytes: Default::default(),
storage_items: Default::default(),
storage_byte_deposit: Default::default(),
storage_item_deposit: Default::default(),
storage_base_deposit,
delegate_dependencies: Default::default(),
},
);
storage_base_deposit
}
#[storage_alias]
pub type ContractInfoOf<T: Config> =
StorageMap<Pallet<T>, Twox64Concat, <T as pezframe_system::Config>::AccountId, ContractInfo<T>>;
#[derive(Encode, Decode, CloneNoBound, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
#[scale_info(skip_type_params(T))]
pub struct ContractInfo<T: Config> {
trie_id: TrieId,
code_hash: CodeHash<T>,
storage_bytes: u32,
storage_items: u32,
storage_byte_deposit: BalanceOf<T>,
storage_item_deposit: BalanceOf<T>,
pub storage_base_deposit: BalanceOf<T>,
delegate_dependencies: BoundedBTreeMap<CodeHash<T>, BalanceOf<T>, T::MaxDelegateDependencies>,
}
#[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 = 16;
fn max_step_weight() -> Weight {
T::WeightInfo::v16_migration_step()
}
fn step(&mut self, meter: &mut WeightMeter) -> IsFinished {
let mut iter = if let Some(last_account) = self.last_account.take() {
ContractInfoOf::<T>::iter_keys_from(ContractInfoOf::<T>::hashed_key_for(last_account))
} else {
ContractInfoOf::<T>::iter_keys()
};
if let Some(key) = iter.next() {
log::debug!(target: LOG_TARGET, "Migrating contract {:?}", key);
ContractInfoOf::<T>::mutate(key.clone(), |info| {
let ed = Pallet::<T>::min_balance();
let mut updated_info = info.take().expect("Item exists; qed");
updated_info.storage_base_deposit.saturating_reduce(ed);
*info = Some(updated_info);
});
self.last_account = Some(key);
meter.consume(T::WeightInfo::v16_migration_step());
IsFinished::No
} else {
log::debug!(target: LOG_TARGET, "No more contracts to migrate");
meter.consume(T::WeightInfo::v16_migration_step());
IsFinished::Yes
}
}
}